From e6c00f5164e4894dd684cc1a484dec42573f9138 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 8 Jul 2025 12:28:57 +0300 Subject: [PATCH 01/58] init --- .devcontainer/devcontainer.json | 25 ++ .devcontainer/post-install.sh | 23 ++ .dockerignore | 3 + .github/workflows/lint.yml | 23 ++ .github/workflows/test-e2e.yml | 32 ++ .github/workflows/test.yml | 23 ++ .gitignore | 27 ++ .golangci.yml | 52 +++ Dockerfile | 33 ++ Makefile | 241 +++++++++++++ PROJECT | 39 +++ README.md | 17 +- api/v1beta1/groupversion_info.go | 36 ++ api/v1beta1/mapaccount_types.go | 64 ++++ api/v1beta1/maprole_types.go | 76 ++++ api/v1beta1/mapuser_types.go | 76 ++++ awsauth/data.go | 200 +++++++++++ awsauth/data_test.go | 117 +++++++ awsauth/mapper.go | 258 ++++++++++++++ awsauth/mapper_test.go | 298 ++++++++++++++++ awsauth/retry.go | 57 +++ awsauth/service.go | 139 ++++++++ charts/aws-auth-operator/.helmignore | 23 ++ charts/aws-auth-operator/Chart.yaml | 24 ++ charts/aws-auth-operator/README.md | 61 ++++ .../prozorro.sr.ios.in.ua_mapaccounts.yaml | 54 +++ .../crds/prozorro.sr.ios.in.ua_maproles.yaml | 66 ++++ .../crds/prozorro.sr.ios.in.ua_mapusers.yaml | 66 ++++ charts/aws-auth-operator/templates/NOTES.txt | 0 .../aws-auth-operator/templates/_helpers.tpl | 62 ++++ .../templates/configmap.yaml | 20 ++ .../templates/deployment.yaml | 57 +++ charts/aws-auth-operator/templates/pdb.yaml | 15 + .../templates/prometheus.yaml | 20 ++ charts/aws-auth-operator/templates/rbac.yaml | 183 ++++++++++ charts/aws-auth-operator/values.yaml | 94 +++++ cmd/main.go | 258 ++++++++++++++ .../aws-auth.prozorro.sale_mapaccounts.yaml | 54 +++ .../aws-auth.prozorro.sale_maproles.yaml | 66 ++++ .../aws-auth.prozorro.sale_mapusers.yaml | 66 ++++ config/crd/kustomization.yaml | 18 + config/crd/kustomizeconfig.yaml | 19 + .../default/cert_metrics_manager_patch.yaml | 30 ++ config/default/kustomization.yaml | 234 +++++++++++++ config/default/manager_metrics_patch.yaml | 4 + config/default/metrics_service.yaml | 18 + config/manager/kustomization.yaml | 2 + config/manager/manager.yaml | 98 ++++++ .../network-policy/allow-metrics-traffic.yaml | 27 ++ config/network-policy/kustomization.yaml | 2 + config/prometheus/kustomization.yaml | 11 + config/prometheus/monitor.yaml | 27 ++ config/prometheus/monitor_tls_patch.yaml | 19 + config/rbac/kustomization.yaml | 34 ++ config/rbac/leader_election_role.yaml | 40 +++ config/rbac/leader_election_role_binding.yaml | 15 + config/rbac/mapaccount_admin_role.yaml | 27 ++ config/rbac/mapaccount_editor_role.yaml | 33 ++ config/rbac/mapaccount_viewer_role.yaml | 29 ++ config/rbac/maprole_admin_role.yaml | 27 ++ config/rbac/maprole_editor_role.yaml | 33 ++ config/rbac/maprole_viewer_role.yaml | 29 ++ config/rbac/mapuser_admin_role.yaml | 27 ++ config/rbac/mapuser_editor_role.yaml | 33 ++ config/rbac/mapuser_viewer_role.yaml | 29 ++ config/rbac/metrics_auth_role.yaml | 17 + config/rbac/metrics_auth_role_binding.yaml | 12 + config/rbac/metrics_reader_role.yaml | 9 + config/rbac/role.yaml | 38 ++ config/rbac/role_binding.yaml | 15 + config/rbac/service_account.yaml | 8 + .../samples/aws-auth_v1beta1_mapaccount.yaml | 9 + config/samples/aws-auth_v1beta1_maprole.yaml | 9 + config/samples/aws-auth_v1beta1_mapuser.yaml | 9 + config/samples/kustomization.yaml | 6 + go.mod | 100 ++++++ go.sum | 260 ++++++++++++++ hack/boilerplate.go.txt | 15 + internal/controller/mapaccount_controller.go | 63 ++++ .../controller/mapaccount_controller_test.go | 84 +++++ internal/controller/maprole_controller.go | 113 ++++++ .../controller/maprole_controller_test.go | 84 +++++ internal/controller/mapuser_controller.go | 119 +++++++ .../controller/mapuser_controller_test.go | 84 +++++ internal/controller/suite_test.go | 116 ++++++ kube/kube.go | 51 +++ test/e2e/e2e_suite_test.go | 89 +++++ test/e2e/e2e_test.go | 329 ++++++++++++++++++ test/utils/utils.go | 254 ++++++++++++++ 89 files changed, 5805 insertions(+), 1 deletion(-) create mode 100644 .devcontainer/devcontainer.json create mode 100644 .devcontainer/post-install.sh create mode 100644 .dockerignore create mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/test-e2e.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 .golangci.yml create mode 100644 Dockerfile create mode 100644 Makefile create mode 100644 PROJECT create mode 100644 api/v1beta1/groupversion_info.go create mode 100644 api/v1beta1/mapaccount_types.go create mode 100644 api/v1beta1/maprole_types.go create mode 100644 api/v1beta1/mapuser_types.go create mode 100644 awsauth/data.go create mode 100644 awsauth/data_test.go create mode 100644 awsauth/mapper.go create mode 100644 awsauth/mapper_test.go create mode 100644 awsauth/retry.go create mode 100644 awsauth/service.go create mode 100644 charts/aws-auth-operator/.helmignore create mode 100644 charts/aws-auth-operator/Chart.yaml create mode 100644 charts/aws-auth-operator/README.md create mode 100644 charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapaccounts.yaml create mode 100644 charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_maproles.yaml create mode 100644 charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapusers.yaml create mode 100644 charts/aws-auth-operator/templates/NOTES.txt create mode 100644 charts/aws-auth-operator/templates/_helpers.tpl create mode 100644 charts/aws-auth-operator/templates/configmap.yaml create mode 100644 charts/aws-auth-operator/templates/deployment.yaml create mode 100644 charts/aws-auth-operator/templates/pdb.yaml create mode 100644 charts/aws-auth-operator/templates/prometheus.yaml create mode 100644 charts/aws-auth-operator/templates/rbac.yaml create mode 100644 charts/aws-auth-operator/values.yaml create mode 100644 cmd/main.go create mode 100644 config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml create mode 100644 config/crd/bases/aws-auth.prozorro.sale_maproles.yaml create mode 100644 config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml create mode 100644 config/crd/kustomization.yaml create mode 100644 config/crd/kustomizeconfig.yaml create mode 100644 config/default/cert_metrics_manager_patch.yaml create mode 100644 config/default/kustomization.yaml create mode 100644 config/default/manager_metrics_patch.yaml create mode 100644 config/default/metrics_service.yaml create mode 100644 config/manager/kustomization.yaml create mode 100644 config/manager/manager.yaml create mode 100644 config/network-policy/allow-metrics-traffic.yaml create mode 100644 config/network-policy/kustomization.yaml create mode 100644 config/prometheus/kustomization.yaml create mode 100644 config/prometheus/monitor.yaml create mode 100644 config/prometheus/monitor_tls_patch.yaml create mode 100644 config/rbac/kustomization.yaml create mode 100644 config/rbac/leader_election_role.yaml create mode 100644 config/rbac/leader_election_role_binding.yaml create mode 100644 config/rbac/mapaccount_admin_role.yaml create mode 100644 config/rbac/mapaccount_editor_role.yaml create mode 100644 config/rbac/mapaccount_viewer_role.yaml create mode 100644 config/rbac/maprole_admin_role.yaml create mode 100644 config/rbac/maprole_editor_role.yaml create mode 100644 config/rbac/maprole_viewer_role.yaml create mode 100644 config/rbac/mapuser_admin_role.yaml create mode 100644 config/rbac/mapuser_editor_role.yaml create mode 100644 config/rbac/mapuser_viewer_role.yaml create mode 100644 config/rbac/metrics_auth_role.yaml create mode 100644 config/rbac/metrics_auth_role_binding.yaml create mode 100644 config/rbac/metrics_reader_role.yaml create mode 100644 config/rbac/role.yaml create mode 100644 config/rbac/role_binding.yaml create mode 100644 config/rbac/service_account.yaml create mode 100644 config/samples/aws-auth_v1beta1_mapaccount.yaml create mode 100644 config/samples/aws-auth_v1beta1_maprole.yaml create mode 100644 config/samples/aws-auth_v1beta1_mapuser.yaml create mode 100644 config/samples/kustomization.yaml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 hack/boilerplate.go.txt create mode 100644 internal/controller/mapaccount_controller.go create mode 100644 internal/controller/mapaccount_controller_test.go create mode 100644 internal/controller/maprole_controller.go create mode 100644 internal/controller/maprole_controller_test.go create mode 100644 internal/controller/mapuser_controller.go create mode 100644 internal/controller/mapuser_controller_test.go create mode 100644 internal/controller/suite_test.go create mode 100644 kube/kube.go create mode 100644 test/e2e/e2e_suite_test.go create mode 100644 test/e2e/e2e_test.go create mode 100644 test/utils/utils.go diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..a3ab754 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,25 @@ +{ + "name": "Kubebuilder DevContainer", + "image": "golang:1.24", + "features": { + "ghcr.io/devcontainers/features/docker-in-docker:2": {}, + "ghcr.io/devcontainers/features/git:1": {} + }, + + "runArgs": ["--network=host"], + + "customizations": { + "vscode": { + "settings": { + "terminal.integrated.shell.linux": "/bin/bash" + }, + "extensions": [ + "ms-kubernetes-tools.vscode-kubernetes-tools", + "ms-azuretools.vscode-docker" + ] + } + }, + + "onCreateCommand": "bash .devcontainer/post-install.sh" +} + diff --git a/.devcontainer/post-install.sh b/.devcontainer/post-install.sh new file mode 100644 index 0000000..265c43e --- /dev/null +++ b/.devcontainer/post-install.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -x + +curl -Lo ./kind https://kind.sigs.k8s.io/dl/latest/kind-linux-amd64 +chmod +x ./kind +mv ./kind /usr/local/bin/kind + +curl -L -o kubebuilder https://go.kubebuilder.io/dl/latest/linux/amd64 +chmod +x kubebuilder +mv kubebuilder /usr/local/bin/ + +KUBECTL_VERSION=$(curl -L -s https://dl.k8s.io/release/stable.txt) +curl -LO "https://dl.k8s.io/release/$KUBECTL_VERSION/bin/linux/amd64/kubectl" +chmod +x kubectl +mv kubectl /usr/local/bin/kubectl + +docker network create -d=bridge --subnet=172.19.0.0/24 kind + +kind version +kubebuilder version +docker --version +go version +kubectl version --client diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a3aab7a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +# More info: https://docs.docker.com/engine/reference/builder/#dockerignore-file +# Ignore build and test binaries. +bin/ diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..86e3845 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,23 @@ +name: Lint + +on: + push: + pull_request: + +jobs: + lint: + name: Run on Ubuntu + runs-on: ubuntu-latest + steps: + - name: Clone the code + uses: actions/checkout@v4 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Run linter + uses: golangci/golangci-lint-action@v8 + with: + version: v2.1.0 diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml new file mode 100644 index 0000000..68fd1ed --- /dev/null +++ b/.github/workflows/test-e2e.yml @@ -0,0 +1,32 @@ +name: E2E Tests + +on: + push: + pull_request: + +jobs: + test-e2e: + name: Run on Ubuntu + runs-on: ubuntu-latest + steps: + - name: Clone the code + uses: actions/checkout@v4 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Install the latest version of kind + run: | + curl -Lo ./kind https://kind.sigs.k8s.io/dl/latest/kind-linux-amd64 + chmod +x ./kind + sudo mv ./kind /usr/local/bin/kind + + - name: Verify kind installation + run: kind version + + - name: Running Test e2e + run: | + go mod tidy + make test-e2e diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..fc2e80d --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,23 @@ +name: Tests + +on: + push: + pull_request: + +jobs: + test: + name: Run on Ubuntu + runs-on: ubuntu-latest + steps: + - name: Clone the code + uses: actions/checkout@v4 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Running Tests + run: | + go mod tidy + make test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ada68ff --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib +bin/* +Dockerfile.cross + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Go workspace file +go.work + +# Kubernetes Generated files - skip generated files, except for vendored files +!vendor/**/zz_generated.* + +# editor and IDE paraphernalia +.idea +.vscode +*.swp +*.swo +*~ diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..e5b21b0 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,52 @@ +version: "2" +run: + allow-parallel-runners: true +linters: + default: none + enable: + - copyloopvar + - dupl + - errcheck + - ginkgolinter + - goconst + - gocyclo + - govet + - ineffassign + - lll + - misspell + - nakedret + - prealloc + - revive + - staticcheck + - unconvert + - unparam + - unused + settings: + revive: + rules: + - name: comment-spacings + - name: import-shadowing + exclusions: + generated: lax + rules: + - linters: + - lll + path: api/* + - linters: + - dupl + - lll + path: internal/* + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..cb1b130 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,33 @@ +# Build the manager binary +FROM golang:1.24 AS builder +ARG TARGETOS +ARG TARGETARCH + +WORKDIR /workspace +# Copy the Go Modules manifests +COPY go.mod go.mod +COPY go.sum go.sum +# cache deps before building and copying source so that we don't need to re-download as much +# and so that source changes don't invalidate our downloaded layer +RUN go mod download + +# Copy the go source +COPY cmd/main.go cmd/main.go +COPY api/ api/ +COPY internal/ internal/ + +# Build +# the GOARCH has not a default value to allow the binary be built according to the host where the command +# was called. For example, if we call make docker-build in a local env which has the Apple Silicon M1 SO +# the docker BUILDPLATFORM arg will be linux/arm64 when for Apple x86 it will be linux/amd64. Therefore, +# by leaving it empty we can ensure that the container and binary shipped on it will have the same platform. +RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -a -o manager cmd/main.go + +# Use distroless as minimal base image to package the manager binary +# Refer to https://github.com/GoogleContainerTools/distroless for more details +FROM gcr.io/distroless/static:nonroot +WORKDIR / +COPY --from=builder /workspace/manager . +USER 65532:65532 + +ENTRYPOINT ["/manager"] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..7c60dc3 --- /dev/null +++ b/Makefile @@ -0,0 +1,241 @@ +# Image URL to use all building/pushing image targets +#IMG ?= controller:latest +IMG ?= redacid/aws-auth-controller:0.0.8 + +# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) +ifeq (,$(shell go env GOBIN)) +GOBIN=$(shell go env GOPATH)/bin +else +GOBIN=$(shell go env GOBIN) +endif + +# CONTAINER_TOOL defines the container tool to be used for building images. +# Be aware that the target commands are only tested with Docker which is +# scaffolded by default. However, you might want to replace it to use other +# tools. (i.e. podman) +CONTAINER_TOOL ?= docker + +# Setting SHELL to bash allows bash commands to be executed by recipes. +# Options are set to exit when a recipe line exits non-zero or a piped command fails. +SHELL = /usr/bin/env bash -o pipefail +.SHELLFLAGS = -ec + +.PHONY: all +all: build + +##@ General + +# The help target prints out all targets with their descriptions organized +# beneath their categories. The categories are represented by '##@' and the +# target descriptions by '##'. The awk command is responsible for reading the +# entire set of makefiles included in this invocation, looking for lines of the +# file as xyz: ## something, and then pretty-format the target and help. Then, +# if there's a line with ##@ something, that gets pretty-printed as a category. +# More info on the usage of ANSI control characters for terminal formatting: +# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters +# More info on the awk command: +# http://linuxcommand.org/lc3_adv_awk.php + +.PHONY: mod-tidy +mod-tidy: + go mod tidy + +.PHONY: preview +preview: kustomize mod-tidy generate manifests + $(KUSTOMIZE) build config/default + +.PHONY: help +help: ## Display this help. + @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) + +##@ Development + +.PHONY: manifests +manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects. + $(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases + +.PHONY: generate +generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations. + $(CONTROLLER_GEN) object:headerFile="hack/boilerplate.go.txt" paths="./..." + +.PHONY: fmt +fmt: ## Run go fmt against code. + go fmt ./... + +.PHONY: vet +vet: ## Run go vet against code. + go vet ./... + +.PHONY: test +test: manifests generate fmt vet setup-envtest ## Run tests. + KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" go test $$(go list ./... | grep -v /e2e) -coverprofile cover.out + +# TODO(user): To use a different vendor for e2e tests, modify the setup under 'tests/e2e'. +# The default setup assumes Kind is pre-installed and builds/loads the Manager Docker image locally. +# CertManager is installed by default; skip with: +# - CERT_MANAGER_INSTALL_SKIP=true +KIND_CLUSTER ?= aws-auth-controller-prozorro-test-e2e + +.PHONY: setup-test-e2e +setup-test-e2e: ## Set up a Kind cluster for e2e tests if it does not exist + @command -v $(KIND) >/dev/null 2>&1 || { \ + echo "Kind is not installed. Please install Kind manually."; \ + exit 1; \ + } + $(KIND) create cluster --name $(KIND_CLUSTER) + +.PHONY: test-e2e +test-e2e: setup-test-e2e manifests generate fmt vet ## Run the e2e tests. Expected an isolated environment using Kind. + KIND_CLUSTER=$(KIND_CLUSTER) go test ./test/e2e/ -v -ginkgo.v + $(MAKE) cleanup-test-e2e + +.PHONY: cleanup-test-e2e +cleanup-test-e2e: ## Tear down the Kind cluster used for e2e tests + @$(KIND) delete cluster --name $(KIND_CLUSTER) + +.PHONY: lint +lint: golangci-lint ## Run golangci-lint linter + $(GOLANGCI_LINT) run + +.PHONY: lint-fix +lint-fix: golangci-lint ## Run golangci-lint linter and perform fixes + $(GOLANGCI_LINT) run --fix + +.PHONY: lint-config +lint-config: golangci-lint ## Verify golangci-lint linter configuration + $(GOLANGCI_LINT) config verify + +##@ Build + +.PHONY: build +build: manifests generate fmt vet ## Build manager binary. + go build -o bin/manager cmd/main.go + +.PHONY: run +run: manifests generate fmt vet ## Run a controller from your host. + go run ./cmd/main.go + +# If you wish to build the manager image targeting other platforms you can use the --platform flag. +# (i.e. docker build --platform linux/arm64). However, you must enable docker buildKit for it. +# More info: https://docs.docker.com/develop/develop-images/build_enhancements/ +.PHONY: docker-build +docker-build: ## Build docker image with the manager. + $(CONTAINER_TOOL) build -t ${IMG} . + +.PHONY: docker-push +docker-push: ## Push docker image with the manager. + $(CONTAINER_TOOL) push ${IMG} + +# PLATFORMS defines the target platforms for the manager image be built to provide support to multiple +# architectures. (i.e. make docker-buildx IMG=myregistry/mypoperator:0.0.1). To use this option you need to: +# - be able to use docker buildx. More info: https://docs.docker.com/build/buildx/ +# - have enabled BuildKit. More info: https://docs.docker.com/develop/develop-images/build_enhancements/ +# - be able to push the image to your registry (i.e. if you do not set a valid value via IMG=> then the export will fail) +# To adequately provide solutions that are compatible with multiple platforms, you should consider using this option. +PLATFORMS ?= linux/arm64,linux/amd64,linux/s390x,linux/ppc64le +.PHONY: docker-buildx +docker-buildx: ## Build and push docker image for the manager for cross-platform support + # copy existing Dockerfile and insert --platform=${BUILDPLATFORM} into Dockerfile.cross, and preserve the original Dockerfile + sed -e '1 s/\(^FROM\)/FROM --platform=\$$\{BUILDPLATFORM\}/; t' -e ' 1,// s//FROM --platform=\$$\{BUILDPLATFORM\}/' Dockerfile > Dockerfile.cross + - $(CONTAINER_TOOL) buildx create --name aws-auth-controller-prozorro-builder + $(CONTAINER_TOOL) buildx use aws-auth-controller-prozorro-builder + - $(CONTAINER_TOOL) buildx build --push --platform=$(PLATFORMS) --tag ${IMG} -f Dockerfile.cross . + - $(CONTAINER_TOOL) buildx rm aws-auth-controller-prozorro-builder + rm Dockerfile.cross + +.PHONY: build-installer +build-installer: manifests generate kustomize ## Generate a consolidated YAML with CRDs and deployment. + mkdir -p dist + cd config/manager && $(KUSTOMIZE) edit set image controller=${IMG} + $(KUSTOMIZE) build config/default > dist/install.yaml + +##@ Deployment + +ifndef ignore-not-found + ignore-not-found = false +endif + +.PHONY: install +install: manifests kustomize ## Install CRDs into the K8s cluster specified in ~/.kube/config. + $(KUSTOMIZE) build config/crd | $(KUBECTL) apply -f - + +.PHONY: uninstall +uninstall: manifests kustomize ## Uninstall CRDs from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion. + $(KUSTOMIZE) build config/crd | $(KUBECTL) delete --ignore-not-found=$(ignore-not-found) -f - + +.PHONY: deploy +deploy: manifests kustomize ## Deploy controller to the K8s cluster specified in ~/.kube/config. + cd config/manager && $(KUSTOMIZE) edit set image controller=${IMG} + $(KUSTOMIZE) build config/default | $(KUBECTL) apply -f - + +.PHONY: undeploy +undeploy: kustomize ## Undeploy controller from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion. + $(KUSTOMIZE) build config/default | $(KUBECTL) delete --ignore-not-found=$(ignore-not-found) -f - + +##@ Dependencies + +## Location to install dependencies to +LOCALBIN ?= $(shell pwd)/bin +$(LOCALBIN): + mkdir -p $(LOCALBIN) + +## Tool Binaries +KUBECTL ?= kubectl +KIND ?= kind +KUSTOMIZE ?= $(LOCALBIN)/kustomize +CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen +ENVTEST ?= $(LOCALBIN)/setup-envtest +GOLANGCI_LINT = $(LOCALBIN)/golangci-lint + +## Tool Versions +KUSTOMIZE_VERSION ?= v5.6.0 +CONTROLLER_TOOLS_VERSION ?= v0.18.0 +#ENVTEST_VERSION is the version of controller-runtime release branch to fetch the envtest setup script (i.e. release-0.20) +ENVTEST_VERSION ?= $(shell go list -m -f "{{ .Version }}" sigs.k8s.io/controller-runtime | awk -F'[v.]' '{printf "release-%d.%d", $$2, $$3}') +#ENVTEST_K8S_VERSION is the version of Kubernetes to use for setting up ENVTEST binaries (i.e. 1.31) +ENVTEST_K8S_VERSION ?= $(shell go list -m -f "{{ .Version }}" k8s.io/api | awk -F'[v.]' '{printf "1.%d", $$3}') +GOLANGCI_LINT_VERSION ?= v2.1.0 + +.PHONY: kustomize +kustomize: $(KUSTOMIZE) ## Download kustomize locally if necessary. +$(KUSTOMIZE): $(LOCALBIN) + $(call go-install-tool,$(KUSTOMIZE),sigs.k8s.io/kustomize/kustomize/v5,$(KUSTOMIZE_VERSION)) + +.PHONY: controller-gen +controller-gen: $(CONTROLLER_GEN) ## Download controller-gen locally if necessary. +$(CONTROLLER_GEN): $(LOCALBIN) + $(call go-install-tool,$(CONTROLLER_GEN),sigs.k8s.io/controller-tools/cmd/controller-gen,$(CONTROLLER_TOOLS_VERSION)) + +.PHONY: setup-envtest +setup-envtest: envtest ## Download the binaries required for ENVTEST in the local bin directory. + @echo "Setting up envtest binaries for Kubernetes version $(ENVTEST_K8S_VERSION)..." + @$(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path || { \ + echo "Error: Failed to set up envtest binaries for version $(ENVTEST_K8S_VERSION)."; \ + exit 1; \ + } + +.PHONY: envtest +envtest: $(ENVTEST) ## Download setup-envtest locally if necessary. +$(ENVTEST): $(LOCALBIN) + $(call go-install-tool,$(ENVTEST),sigs.k8s.io/controller-runtime/tools/setup-envtest,$(ENVTEST_VERSION)) + +.PHONY: golangci-lint +golangci-lint: $(GOLANGCI_LINT) ## Download golangci-lint locally if necessary. +$(GOLANGCI_LINT): $(LOCALBIN) + $(call go-install-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/v2/cmd/golangci-lint,$(GOLANGCI_LINT_VERSION)) + +# go-install-tool will 'go install' any package with custom target and name of binary, if it doesn't exist +# $1 - target path with name of binary +# $2 - package url which can be installed +# $3 - specific version of package +define go-install-tool +@[ -f "$(1)-$(3)" ] || { \ +set -e; \ +package=$(2)@$(3) ;\ +echo "Downloading $${package}" ;\ +rm -f $(1) || true ;\ +GOBIN=$(LOCALBIN) go install $${package} ;\ +mv $(1) $(1)-$(3) ;\ +} ;\ +ln -sf $(1)-$(3) $(1) +endef diff --git a/PROJECT b/PROJECT new file mode 100644 index 0000000..5d0bea1 --- /dev/null +++ b/PROJECT @@ -0,0 +1,39 @@ +# Code generated by tool. DO NOT EDIT. +# This file is used to track the info used to scaffold your project +# and allow the plugins properly work. +# More info: https://book.kubebuilder.io/reference/project-config.html +cliVersion: 4.6.0 +domain: prozorro.sale +layout: +- go.kubebuilder.io/v4 +projectName: aws-auth-controller-prozorro +repo: github.com/redacid/aws-auth-controller +resources: +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: prozorro.sale + group: aws-auth + kind: MapRole + path: github.com/redacid/aws-auth-controller/api/v1beta1 + version: v1beta1 +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: prozorro.sale + group: aws-auth + kind: MapUser + path: github.com/redacid/aws-auth-controller/api/v1beta1 + version: v1beta1 +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: prozorro.sale + group: aws-auth + kind: MapAccount + path: github.com/redacid/aws-auth-controller/api/v1beta1 + version: v1beta1 +version: "3" diff --git a/README.md b/README.md index 8c02383..dbdff1c 100644 --- a/README.md +++ b/README.md @@ -1 +1,16 @@ -# aws-auth-controller \ No newline at end of file +# aws-auth-controller + +kubebuilder init --domain prozorro.sale --plugins go/v4 --repo github.com/redacid/aws-auth-controller --project-name=aws-auth-controller-prozorro +kubebuilder create api --group aws-auth --version v1beta1 --kind MapRole --namespaced true --controller --resource +kubebuilder create api --group aws-auth --version v1beta1 --kind MapUser --namespaced true --controller --resource +kubebuilder create api --group aws-auth --version v1beta1 --kind MapAccount --namespaced true --controller --resource + + +git tag 0.0.1 -m "Test 0.0.1" +git push origin 0.0.1 + +cd ./charts helm upgrade -i --namespace kube-system aws-auth aws-auth-operator +cd ./config/samples kubectl apply -f prozorro_v1alpha1_mapuser.yaml -n kube-system +cd ./config/samples kubectl apply -f prozorro_v1alpha1_maprole.yaml -n kube-system + +https://book.kubebuilder.io/reference/using-finalizers \ No newline at end of file diff --git a/api/v1beta1/groupversion_info.go b/api/v1beta1/groupversion_info.go new file mode 100644 index 0000000..fa68792 --- /dev/null +++ b/api/v1beta1/groupversion_info.go @@ -0,0 +1,36 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package v1beta1 contains API Schema definitions for the aws-auth v1beta1 API group. +// +kubebuilder:object:generate=true +// +groupName=aws-auth.prozorro.sale +package v1beta1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/scheme" +) + +var ( + // GroupVersion is group version used to register these objects. + GroupVersion = schema.GroupVersion{Group: "aws-auth.prozorro.sale", Version: "v1beta1"} + + // 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 +) diff --git a/api/v1beta1/mapaccount_types.go b/api/v1beta1/mapaccount_types.go new file mode 100644 index 0000000..fe7239e --- /dev/null +++ b/api/v1beta1/mapaccount_types.go @@ -0,0 +1,64 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// MapAccountSpec defines the desired state of MapAccount. +type MapAccountSpec struct { + // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster + // Important: Run "make" to regenerate code after modifying this file + + // Foo is an example field of MapAccount. Edit mapaccount_types.go to remove/update + Foo string `json:"foo,omitempty"` +} + +// MapAccountStatus defines the observed state of MapAccount. +type MapAccountStatus struct { + // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster + // Important: Run "make" to regenerate code after modifying this file +} + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status + +// MapAccount is the Schema for the mapaccounts API. +type MapAccount struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec MapAccountSpec `json:"spec,omitempty"` + Status MapAccountStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// MapAccountList contains a list of MapAccount. +type MapAccountList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MapAccount `json:"items"` +} + +func init() { + SchemeBuilder.Register(&MapAccount{}, &MapAccountList{}) +} diff --git a/api/v1beta1/maprole_types.go b/api/v1beta1/maprole_types.go new file mode 100644 index 0000000..0a55a26 --- /dev/null +++ b/api/v1beta1/maprole_types.go @@ -0,0 +1,76 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// MapRoleSpec defines the desired state of MapRole. +type MapRoleSpec struct { + // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster + // Important: Run "make" to regenerate code after modifying this file + + // The Role ARN to associate with the MapRole + RoleARN string `json:"rolearn"` + + // The Kubernetes groups to associate with the MapRole + // +kubebuilder:validation:Optional + Groups []string `json:"groups"` + + // A useful description of the MapRole + // +kubebuilder:validation:Optional + Description string `json:"description"` + + // The username for the MapUser + // +kubebuilder:validation:Optional + Username string `json:"username"` +} + +// MapRoleStatus defines the observed state of MapRole. +type MapRoleStatus struct { + // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster + // Important: Run "make" to regenerate code after modifying this file +} + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status + +// MapRole is the Schema for the maproles API. +type MapRole struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec MapRoleSpec `json:"spec,omitempty"` + Status MapRoleStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// MapRoleList contains a list of MapRole. +type MapRoleList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MapRole `json:"items"` +} + +func init() { + SchemeBuilder.Register(&MapRole{}, &MapRoleList{}) +} diff --git a/api/v1beta1/mapuser_types.go b/api/v1beta1/mapuser_types.go new file mode 100644 index 0000000..b99796b --- /dev/null +++ b/api/v1beta1/mapuser_types.go @@ -0,0 +1,76 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// MapUserSpec defines the desired state of MapUser. +type MapUserSpec struct { + // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster + // Important: Run "make" to regenerate code after modifying this file + + // The User ARN to associate with the MapUser + UserARN string `json:"userarn"` + + // The Kubernetes groups to associate with the MapUser + // +kubebuilder:validation:Optional + Groups []string `json:"groups"` + + // A useful description of the MapUser + // +kubebuilder:validation:Optional + Description string `json:"description"` + + // The username for the MapUser + // +kubebuilder:validation:Optional + Username string `json:"username"` +} + +// MapUserStatus defines the observed state of MapUser. +type MapUserStatus struct { + // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster + // Important: Run "make" to regenerate code after modifying this file +} + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status + +// MapUser is the Schema for the mapusers API. +type MapUser struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec MapUserSpec `json:"spec,omitempty"` + Status MapUserStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// MapUserList contains a list of MapUser. +type MapUserList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MapUser `json:"items"` +} + +func init() { + SchemeBuilder.Register(&MapUser{}, &MapUserList{}) +} diff --git a/awsauth/data.go b/awsauth/data.go new file mode 100644 index 0000000..39e7ffb --- /dev/null +++ b/awsauth/data.go @@ -0,0 +1,200 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package awsauth + +import ( + "context" + "fmt" + "log" + "strings" + + "gopkg.in/yaml.v2" + kcorev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" +) + +func init() { + log.SetFlags(0) +} + +const ( + ConfigMapName = "aws-auth" + ConfigMapNamespace = "kube-system" +) + +// ReadAuthMap reads the auth ConfigMap and returns AwsAuthData and the read ConfigMap. +func ReadAuthMap(k kubernetes.Interface) (AwsAuthData, *kcorev1.ConfigMap, error) { + var authData AwsAuthData + + cm, err := k.CoreV1().ConfigMaps(ConfigMapNamespace).Get(context.Background(), ConfigMapName, apismetav1.GetOptions{}) + if err != nil { + if apierrors.IsNotFound(err) { + cm, err = CreateAuthMap(k) + if err != nil { + return authData, cm, err + } + } else { + return authData, cm, err + } + } + + err = yaml.Unmarshal([]byte(cm.Data["mapRoles"]), &authData.MapRoles) + if err != nil { + return authData, cm, err + } + + err = yaml.Unmarshal([]byte(cm.Data["mapUsers"]), &authData.MapUsers) + return authData, cm, err +} + +func CreateAuthMap(k kubernetes.Interface) (*kcorev1.ConfigMap, error) { + configMapObject := &kcorev1.ConfigMap{ + ObjectMeta: apismetav1.ObjectMeta{ + Name: ConfigMapName, + Namespace: ConfigMapNamespace, + }, + } + return k.CoreV1().ConfigMaps(ConfigMapNamespace).Create( + context.Background(), + configMapObject, + apismetav1.CreateOptions{}, + ) +} + +// UpdateAuthMap updates a given ConfigMap +func UpdateAuthMap(k kubernetes.Interface, authData AwsAuthData, cm *kcorev1.ConfigMap) error { + mapRoles, err := yaml.Marshal(authData.MapRoles) + if err != nil { + return err + } + + mapUsers, err := yaml.Marshal(authData.MapUsers) + if err != nil { + return err + } + + cm.Data = map[string]string{ + "mapRoles": string(mapRoles), + "mapUsers": string(mapUsers), + } + + _, err = k.CoreV1().ConfigMaps(ConfigMapNamespace).Update(context.Background(), cm, apismetav1.UpdateOptions{}) + return err +} + +// AwsAuthData represents the data of the aws-auth configmap +type AwsAuthData struct { + MapRoles []*MapRole `yaml:"mapRoles"` + MapUsers []*MapUser `yaml:"mapUsers"` +} + +// SetMapRoles sets the MapRoles element +func (m *AwsAuthData) SetMapRoles(authMap []*MapRole) { + m.MapRoles = authMap +} + +// SetMapUsers sets the MapUsers element +func (m *AwsAuthData) SetMapUsers(authMap []*MapUser) { + m.MapUsers = authMap +} + +// MapRole is the basic structure of a mapRoles authentication object +type MapRole struct { + RoleARN string `yaml:"rolearn"` + Username string `yaml:"username"` + Groups []string `yaml:"groups,omitempty"` +} + +func (r *MapRole) String() string { + var s strings.Builder + s.WriteString(fmt.Sprintf("- rolearn: %v\n ", r.RoleARN)) + s.WriteString(fmt.Sprintf("username: %v\n ", r.Username)) + s.WriteString("groups:\n") + for _, group := range r.Groups { + s.WriteString(fmt.Sprintf(" - %v\n", group)) + } + return s.String() + +} + +// SetGroups sets the Groups value +func (r *MapRole) SetGroups(g []string) *MapRole { + r.Groups = g + return r +} + +// SetRoleARN sets the Username value +func (r *MapRole) SetRoleARN(v string) *MapRole { + r.Username = v + return r +} + +// NewMapRole returns a new NewMapRole +func NewMapRole(rolearn, username string, groups []string) *MapRole { + return &MapRole{ + RoleARN: rolearn, + Username: username, + Groups: groups, + } +} + +// MapUser is the basic structure of a mapUsers authentication object +type MapUser struct { + CrdName string `yaml:"crdname"` + UserARN string `yaml:"userarn"` + Username string `yaml:"username"` + Groups []string `yaml:"groups,omitempty"` +} + +func (r *MapUser) String() string { + var s strings.Builder + s.WriteString(fmt.Sprintf("- userarn: %v\n ", r.UserARN)) + s.WriteString(fmt.Sprintf("username: %v\n ", r.Username)) + s.WriteString("groups:\n") + for _, group := range r.Groups { + s.WriteString(fmt.Sprintf(" - %v\n", group)) + } + return s.String() +} + +// SetGroups sets the Groups value +func (r *MapUser) SetGroups(g []string) *MapUser { + r.Groups = g + return r +} + +// SetUserARN sets the UserARN value +func (r *MapUser) SetUserARN(v string) *MapUser { + r.UserARN = v + return r +} + +func (r *MapUser) SetUsername(v string) *MapUser { + r.Username = v + return r +} + +// NewMapUser returns a new NewMapUser +func NewMapUser(crdname, userarn, username string, groups []string) *MapUser { + return &MapUser{ + CrdName: crdname, + UserARN: userarn, + Username: username, + Groups: groups, + } +} diff --git a/awsauth/data_test.go b/awsauth/data_test.go new file mode 100644 index 0000000..28f08f8 --- /dev/null +++ b/awsauth/data_test.go @@ -0,0 +1,117 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package awsauth + +import ( + "context" + "fmt" + "testing" + + "github.com/onsi/gomega" + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/kubernetes/fake" +) + +func createMockConfigMap(client kubernetes.Interface) { + role := NewMapRole("arn:aws:iam::00000000000:role/node-1", + "system:node:{{EC2PrivateDNSName}}", + []string{"system:bootstrappers", "system:nodes"}) + + user := NewMapUser("arn:aws:iam::00000000000:user/user-1", + "admin", + []string{"system:masters"}) + + configMap := &v1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{ + Name: ConfigMapName, + Namespace: ConfigMapNamespace, + }, + Data: map[string]string{ + "mapRoles": role.String(), + "mapUsers": user.String(), + }, + } + _, err := client.CoreV1().ConfigMaps(ConfigMapNamespace).Create( + context.Background(), + configMap, + metav1.CreateOptions{}, + ) + gomega.Expect(err).NotTo(gomega.HaveOccurred()) + +} + +func TestUpdateAuthMap(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + createMockConfigMap(client) + + auth, cm, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + role := NewMapRole("arn:aws:iam::00000000000:role/node-2", + "system:node:{{EC2PrivateDNSName}}", + []string{"system:bootstrappers", "system:nodes"}) + user := NewMapUser("arn:aws:iam::00000000000:user/user-2", + "ops-user", + []string{"system:masters"}) + + auth.MapRoles = append(auth.MapRoles, role) + auth.MapUsers = append(auth.MapUsers, user) + + err = UpdateAuthMap(client, auth, cm) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + // auth, cm, err = ReadAuthMap(client) + auth, _, err = ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + fmt.Println(auth.MapRoles[0]) + g.Expect(auth.MapRoles).To(gomega.HaveLen(2)) + g.Expect(auth.MapUsers).To(gomega.HaveLen(2)) +} + +func TestReadAuthMap(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + createMockConfigMap(client) + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(auth.MapRoles).To(gomega.HaveLen(1)) + g.Expect(auth.MapRoles[0].RoleARN).To(gomega.Equal("arn:aws:iam::00000000000:role/node-1")) + g.Expect(auth.MapRoles[0].Username).To(gomega.Equal("system:node:{{EC2PrivateDNSName}}")) + g.Expect(auth.MapRoles[0].Groups).To(gomega.Equal([]string{"system:bootstrappers", "system:nodes"})) + + g.Expect(auth.MapUsers).To(gomega.HaveLen(1)) + g.Expect(auth.MapUsers[0].UserARN).To(gomega.Equal("arn:aws:iam::00000000000:user/user-1")) + g.Expect(auth.MapUsers[0].Username).To(gomega.Equal("admin")) + g.Expect(auth.MapUsers[0].Groups).To(gomega.Equal([]string{"system:masters"})) +} + +func TestNewAuthMap(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(auth.MapRoles).To(gomega.BeEmpty()) + g.Expect(auth.MapUsers).To(gomega.BeEmpty()) +} diff --git a/awsauth/mapper.go b/awsauth/mapper.go new file mode 100644 index 0000000..7c7a499 --- /dev/null +++ b/awsauth/mapper.go @@ -0,0 +1,258 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package awsauth + +import ( + "fmt" + + "io" + "log" + "reflect" + "time" + + "k8s.io/client-go/kubernetes" +) + +// NewMapper returns a new Mapper object. +func NewMapper(client kubernetes.Interface, discardLogOutput bool) *Mapper { + var mapper = &Mapper{} + mapper.KubernetesClient = client + + if !discardLogOutput { + log.SetOutput(io.Discard) + } + return mapper +} + +// Mapper is responsible for managing the auth map. +type Mapper struct { + KubernetesClient kubernetes.Interface +} + +// Remove removes a mapRole or mapUser from the auth map. +func (m *Mapper) Remove(args *Arguments) error { + args.Validate() + if args.WithRetries { + return WithRetry(m.removeAuth, args) + } + return m.removeAuth(args) +} + +func (m *Mapper) removeAuth(args *Arguments) error { + authData, configMap, err := ReadAuthMap(m.KubernetesClient) + if err != nil { + return err + } + + var removed bool + + if args.DataType == MapRoleData { + var newRolesAuthMap []*MapRole + for _, mapRole := range authData.MapRoles { + if args.Username != mapRole.Username { + newRolesAuthMap = append(newRolesAuthMap, mapRole) + } else { + removed = true + } + } + authData.SetMapRoles(newRolesAuthMap) + } + + if args.DataType == MapUserData { + var newUsersAuthMap []*MapUser + for _, mapUser := range authData.MapUsers { + if args.CrdName != mapUser.CrdName { + newUsersAuthMap = append(newUsersAuthMap, mapUser) + } else { + removed = true + } + } + authData.SetMapUsers(newUsersAuthMap) + } + + if !removed { + return fmt.Errorf("%s with username '%s' not found in auth map", args.DataType, args.CrdName) + } + return UpdateAuthMap(m.KubernetesClient, authData, configMap) +} + +// Upsert updates or inserts a mapRole or mapUser item into the auth map. +func (m *Mapper) Upsert(args *Arguments) error { + args.Validate() + if args.WithRetries { + return WithRetry(m.upsertAuth, args) + } + return m.upsertAuth(args) +} + +func (m *Mapper) upsertAuth(args *Arguments) error { + authData, configMap, err := ReadAuthMap(m.KubernetesClient) + if err != nil { + return err + } + + if args.DataType == MapRoleData { + mapRole := NewMapRole(args.RoleARN, args.Username, args.Groups) + newMap, ok := upsertRole(authData.MapRoles, mapRole) + if ok { + log.Printf("%s with username '%s' key has been updated\n", args.DataType, args.Username) + } else { + log.Printf("no updates needed to %s with username '%s'\n", args.DataType, args.Username) + } + authData.SetMapRoles(newMap) + } + + if args.DataType == MapUserData { + mapUser := NewMapUser(args.CrdName, args.UserARN, args.Username, args.Groups) + newMap, ok := upsertUser(authData.MapUsers, mapUser) + if ok { + log.Printf("%s with username '%s' key has been updated\n", args.DataType, args.Username) + } else { + log.Printf("%s with username '%s' key has been updated\n", args.DataType, args.Username) + } + authData.SetMapUsers(newMap) + } + + return UpdateAuthMap(m.KubernetesClient, authData, configMap) +} + +func upsertRole(authMaps []*MapRole, resource *MapRole) ([]*MapRole, bool) { + var found, updated bool + for _, existing := range authMaps { + // Update existing role in auth map. + if existing.Username == resource.Username { + found = true + if !reflect.DeepEqual(existing.Groups, resource.Groups) { + existing.SetGroups(resource.Groups) + updated = true + } + if existing.RoleARN != resource.RoleARN { + existing.SetRoleARN(resource.RoleARN) + updated = true + } + } + } + + // Insert new role in auth map. + if !found { + updated = true + authMaps = append(authMaps, resource) + } + return authMaps, updated +} + +func upsertUser(authMaps []*MapUser, resource *MapUser) ([]*MapUser, bool) { + var found, updated bool + for _, existing := range authMaps { + // Update existing user in auth map. + //if existing.UserARN == resource.UserARN { + // found = true + // if !reflect.DeepEqual(existing.Groups, resource.Groups) { + // existing.SetGroups(resource.Groups) + // updated = true + // } + // if existing.Username != resource.Username { + // existing.SetUsername(resource.Username) + // updated = true + // } + // if existing.UserARN != resource.UserARN { + // existing.SetUserARN(resource.UserARN) + // updated = true + // } + //} + if existing.CrdName == resource.CrdName { + found = true + if !reflect.DeepEqual(existing.Groups, resource.Groups) { + existing.SetGroups(resource.Groups) + updated = true + } + if existing.Username != resource.Username { + existing.SetUsername(resource.Username) + updated = true + } + if existing.UserARN != resource.UserARN { + existing.SetUserARN(resource.UserARN) + updated = true + } + } + } + + // Insert new user in auth map. + if !found { + updated = true + authMaps = append(authMaps, resource) + } + return authMaps, updated +} + +// Arguments are the arguments for management of the auth map. +type Arguments struct { + OperationType OperationType + DataType DataType + RoleARN string + UserARN string + CrdName string + Username string + Groups []string + WithRetries bool + MinRetryTime time.Duration + MaxRetryTime time.Duration + MaxRetryCount int +} + +// Validate validates if all Arguments fields are valid. +func (args *Arguments) Validate() { + if args.WithRetries && args.MaxRetryCount < 1 { + log.Println("error: retry max count is invalid, must be greater than zero") + } + if args.Username == "" { + log.Println("error: username not provided") + } + if args.OperationType == "" { + log.Println("error: operation type not provided") + } + if args.OperationType != UpsertOperation && args.OperationType != RemoveOperation { + log.Printf("error: operation type '%s' not valid\n", args.OperationType) + } + if args.DataType == "" { + log.Println("error: data type not provided") + } + if args.DataType != MapRoleData && args.DataType != MapUserData { + log.Printf("error: data type '%s' not valid\n", args.DataType) + } + if args.OperationType == UpsertOperation && args.DataType == MapRoleData && args.RoleARN == "" { + log.Println("error: role arn not provided") + } + if args.OperationType == UpsertOperation && args.DataType == MapUserData && args.UserARN == "" { + log.Println("error: user arn not provided") + } +} + +// OperationType indicates the auth map management operation. +type OperationType string + +const ( + UpsertOperation OperationType = "upsert" + RemoveOperation OperationType = "remove" +) + +// DataType indicates the auth map management scope. +type DataType string + +const ( + MapRoleData DataType = "mapRole" + MapUserData DataType = "mapUser" +) diff --git a/awsauth/mapper_test.go b/awsauth/mapper_test.go new file mode 100644 index 0000000..4b213ea --- /dev/null +++ b/awsauth/mapper_test.go @@ -0,0 +1,298 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package awsauth + +import ( + "testing" + "time" + + "github.com/onsi/gomega" + "k8s.io/client-go/kubernetes/fake" +) + +var testARNs = map[string]string{ + "node-1": "arn:aws:iam::00000000000:role/node-1", + "node-2": "arn:aws:iam::00000000000:role/node-2", + "user-1": "arn:aws:iam::00000000000:user/user-1", + "user-2": "arn:aws:iam::00000000000:user/user-2", +} + +func TestMapper_Remove(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + mapper := NewMapper(client, true) + createMockConfigMap(client) + + err := mapper.Remove(&Arguments{ + OperationType: RemoveOperation, + DataType: MapRoleData, + Username: "system:node:{{EC2PrivateDNSName}}", + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + err = mapper.Remove(&Arguments{ + OperationType: RemoveOperation, + DataType: MapUserData, + Username: "admin", + UserARN: "doesn't matter", + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(auth.MapRoles).To(gomega.BeEmpty()) + g.Expect(auth.MapUsers).To(gomega.BeEmpty()) +} + +func TestMapper_RemoveNotFound(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + mapper := NewMapper(client, true) + createMockConfigMap(client) + + err := mapper.Remove(&Arguments{ + OperationType: RemoveOperation, + DataType: MapRoleData, + Username: "system:node:{{EC2PrivateDNSName}}-na", + }) + g.Expect(err).To(gomega.HaveOccurred()) + + err = mapper.Remove(&Arguments{ + OperationType: RemoveOperation, + DataType: MapUserData, + Username: "admin-na", + UserARN: "doesn't matter", + }) + g.Expect(err).To(gomega.HaveOccurred()) + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(auth.MapRoles).To(gomega.HaveLen(1)) + g.Expect(auth.MapUsers).To(gomega.HaveLen(1)) +} + +func TestMapper_RemoveWithRetries(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + mapper := NewMapper(client, true) + createMockConfigMap(client) + + err := mapper.Remove(&Arguments{ + OperationType: RemoveOperation, + DataType: MapRoleData, + Username: "system:node:{{EC2PrivateDNSName}}", + WithRetries: true, + MinRetryTime: time.Millisecond * 1, + MaxRetryTime: time.Millisecond * 2, + MaxRetryCount: 3, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + err = mapper.Remove(&Arguments{ + OperationType: RemoveOperation, + DataType: MapUserData, + Username: "admin", + WithRetries: true, + MinRetryTime: time.Millisecond * 1, + MaxRetryTime: time.Millisecond * 2, + MaxRetryCount: 3, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(auth.MapRoles).To(gomega.BeEmpty()) + g.Expect(auth.MapUsers).To(gomega.BeEmpty()) +} + +func TestMapper_UpsertInsert(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + mapper := NewMapper(client, true) + createMockConfigMap(client) + + err := mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapRoleData, + RoleARN: testARNs["node-2"], + Username: "system:node:{{EC2PrivateDNSName}}", + Groups: []string{"system:bootstrappers", "system:nodes"}, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + err = mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapUserData, + UserARN: testARNs["user-2"], + Username: "admin", + Groups: []string{"system:masters"}, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(auth.MapRoles).To(gomega.HaveLen(1)) + g.Expect(auth.MapUsers).To(gomega.HaveLen(2)) +} + +func TestMapper_UpsertUpdate(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + mapper := NewMapper(client, true) + createMockConfigMap(client) + + err := mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapRoleData, + RoleARN: testARNs["node-1"], + Username: "this:is:a:test", + Groups: []string{"system:some-role"}, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + err = mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapUserData, + UserARN: testARNs["user-1"], + Username: "admin", + Groups: []string{"system:some-role"}, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(auth.MapRoles).To(gomega.HaveLen(2)) + g.Expect(auth.MapUsers).To(gomega.HaveLen(1)) + g.Expect(auth.MapRoles[0].RoleARN).To(gomega.Equal(testARNs["node-1"])) + g.Expect(auth.MapRoles[0].Username).To(gomega.Equal("system:node:{{EC2PrivateDNSName}}")) + g.Expect(auth.MapRoles[0].Groups).To(gomega.Equal([]string{"system:bootstrappers", "system:nodes"})) + g.Expect(auth.MapUsers[0].UserARN).To(gomega.Equal(testARNs["user-1"])) + g.Expect(auth.MapUsers[0].Username).To(gomega.Equal("admin")) + g.Expect(auth.MapUsers[0].Groups).To(gomega.Equal([]string{"system:some-role"})) +} + +/* func TestMapper_UpsertNotNeeded(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + mapper := NewMapper(client, true) + createMockConfigMap(client) + + err := mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapRoleData, + RoleARN: testARNs["node-1"], + Username: "system:node:{{EC2PrivateDNSName}}", + Groups: []string{"system:bootstrappers", "system:nodes"}, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + err = mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapUserData, + UserARN: testARNs["user-1"], + Username: "admin", + Groups: []string{"system:masters"}, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(auth.MapRoles).To(gomega.HaveLen(1)) + g.Expect(auth.MapUsers).To(gomega.HaveLen(1)) +} */ + +func TestMapper_UpsertWithCreate(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + mapper := NewMapper(client, true) + + err := mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapRoleData, + RoleARN: testARNs["node-1"], + Username: "this:is:a:test", + Groups: []string{"system:some-role"}, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + err = mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapUserData, + UserARN: testARNs["user-1"], + Username: "this:is:a:test", + Groups: []string{"system:some-role"}, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(len(auth.MapRoles)).To(gomega.HaveLen(1)) + g.Expect(len(auth.MapUsers)).To(gomega.HaveLen(1)) + g.Expect(auth.MapRoles[0].RoleARN).To(gomega.Equal(testARNs["node-1"])) + g.Expect(auth.MapRoles[0].Username).To(gomega.Equal("this:is:a:test")) + g.Expect(auth.MapRoles[0].Groups).To(gomega.Equal([]string{"system:some-role"})) + g.Expect(auth.MapUsers[0].UserARN).To(gomega.Equal(testARNs["user-1"])) + g.Expect(auth.MapUsers[0].Username).To(gomega.Equal("this:is:a:test")) + g.Expect(auth.MapUsers[0].Groups).To(gomega.Equal([]string{"system:some-role"})) +} + +func TestMapper_UpsertWithRetries(t *testing.T) { + g := gomega.NewWithT(t) + gomega.RegisterTestingT(t) + client := fake.NewSimpleClientset() + mapper := NewMapper(client, true) + createMockConfigMap(client) + + err := mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapRoleData, + RoleARN: testARNs["node-1"], + Username: "system:node:{{EC2PrivateDNSName}}", + Groups: []string{"system:some-role"}, + WithRetries: true, + MaxRetryCount: 12, + MaxRetryTime: 1 * time.Millisecond, + MinRetryTime: 1 * time.Millisecond, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + err = mapper.Upsert(&Arguments{ + OperationType: UpsertOperation, + DataType: MapUserData, + UserARN: testARNs["user-1"], + Username: "this:is:a:test", + Groups: []string{"system:some-role"}, + }) + g.Expect(err).NotTo(gomega.HaveOccurred()) + + auth, _, err := ReadAuthMap(client) + g.Expect(err).NotTo(gomega.HaveOccurred()) + g.Expect(len(auth.MapRoles)).To(gomega.HaveLen(1)) + g.Expect(len(auth.MapUsers)).To(gomega.HaveLen(1)) + g.Expect(auth.MapRoles[0].RoleARN).To(gomega.Equal(testARNs["node-1"])) + g.Expect(auth.MapRoles[0].Username).To(gomega.Equal("system:node:{{EC2PrivateDNSName}}")) + g.Expect(auth.MapRoles[0].Groups).To(gomega.Equal([]string{"system:some-role"})) + g.Expect(auth.MapUsers[0].UserARN).To(gomega.Equal(testARNs["user-1"])) + g.Expect(auth.MapUsers[0].Username).To(gomega.Equal("admin")) + g.Expect(auth.MapUsers[0].Groups).To(gomega.Equal([]string{"system:some-role"})) +} diff --git a/awsauth/retry.go b/awsauth/retry.go new file mode 100644 index 0000000..db3d15d --- /dev/null +++ b/awsauth/retry.go @@ -0,0 +1,57 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package awsauth + +import ( + "log" + "time" + + "github.com/jpillora/backoff" + "github.com/pkg/errors" +) + +const ( + defaultRetryerBackoffFactor float64 = 2.0 + defaultRetryerBackoffJitter = true +) + +// WithRetry runs the passed operation function with its arguments and retries +// on failures until success or max number of retry attempts have failed. +func WithRetry(fn func(*Arguments) error, args *Arguments) error { + var ( + counter int + err error + bkoff = &backoff.Backoff{ + Min: args.MinRetryTime, + Max: args.MaxRetryTime, + Factor: defaultRetryerBackoffFactor, + Jitter: defaultRetryerBackoffJitter, + } + ) + + for counter < args.MaxRetryCount { + if err = fn(args); err != nil { + d := bkoff.Duration() + log.Printf("error: %v: will retry after %v", err, d) + time.Sleep(d) + counter++ + continue + } + return nil + } + + return errors.Wrap(err, "waiter timed out") +} diff --git a/awsauth/service.go b/awsauth/service.go new file mode 100644 index 0000000..d48e601 --- /dev/null +++ b/awsauth/service.go @@ -0,0 +1,139 @@ +/* +Copyright 2021. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package awsauth + +import ( + "errors" + "time" + + "github.com/go-logr/logr" + "k8s.io/client-go/kubernetes" +) + +// ServiceConfig is the configuration for a Service object. +type ServiceConfig struct { + KubeClient kubernetes.Interface + Log logr.Logger + MaxRetryCount int + MaxRetryTime time.Duration + MinRetryTime time.Duration + WithRetries bool +} + +// Service provides aws-auth configmap management behavior. +type Service interface { + // UpsertMapRole upserts a MapRole into the configmap keyed by username. + UpsertMapRole(username string, mapRole MapRole) error + + // RemoveMapRole removes a MapRole from the configmap by keyed by username + RemoveMapRole(username string) error + + // UpsertMapUser upserts a MapUser into the configmap keyed by username. + UpsertMapUser(username string, mapUser MapUser) error + + // RemoveMapUser removes a MapUser from the configmap keyed by username + RemoveMapUser(username string) error +} + +// NewService returns an implementation of the Service interface. +func NewService(cfg *ServiceConfig) (Service, error) { + if cfg.WithRetries { + if cfg.MaxRetryCount < 1 { + return nil, errors.New("retry max count config must be greater than zero") + } + } + return impl{cfg: *cfg}, nil +} + +type impl struct { + cfg ServiceConfig +} + +// UpsertMapRole upserts a MapRole into the configmap keyed by username. +func (svc impl) UpsertMapRole(username string, mapRole MapRole) error { + mapper := NewMapper(svc.cfg.KubeClient, false) + err := mapper.Upsert(&Arguments{ + DataType: MapRoleData, + RoleARN: mapRole.RoleARN, + Username: username, + Groups: mapRole.Groups, + WithRetries: svc.cfg.WithRetries, + MaxRetryCount: svc.cfg.MaxRetryCount, + MaxRetryTime: svc.cfg.MaxRetryTime, + MinRetryTime: svc.cfg.MinRetryTime, + }) + if err != nil { + svc.cfg.Log.Error(err, "failure to upsert mapRole", "username", username) + } + return err +} + +// RemoveMapRole removes a MapRole from the configmap keyed by username. +func (svc impl) RemoveMapRole(username string) error { + mapper := NewMapper(svc.cfg.KubeClient, false) + err := mapper.Remove(&Arguments{ + DataType: MapRoleData, + Username: username, + WithRetries: svc.cfg.WithRetries, + MaxRetryCount: svc.cfg.MaxRetryCount, + MaxRetryTime: svc.cfg.MaxRetryTime, + MinRetryTime: svc.cfg.MinRetryTime, + }) + if err != nil { + svc.cfg.Log.Info("mapRole not found", "username", username) + } + return err +} + +// UpsertMapUser upserts a MapUser into the configmap keyed by username. +func (svc impl) UpsertMapUser(username string, mapUser MapUser) error { + mapper := NewMapper(svc.cfg.KubeClient, false) + err := mapper.Upsert(&Arguments{ + DataType: MapUserData, + UserARN: mapUser.UserARN, + // Username: username, + CrdName: username, + Username: mapUser.Username, + Groups: mapUser.Groups, + WithRetries: svc.cfg.WithRetries, + MaxRetryCount: svc.cfg.MaxRetryCount, + MaxRetryTime: svc.cfg.MaxRetryTime, + MinRetryTime: svc.cfg.MinRetryTime, + }) + if err != nil { + svc.cfg.Log.Error(err, "failure to upsert mapUser", "username", username) + } + return err +} + +// RemoveMapUser removes a MapUser from the configmap keyed by username. +func (svc impl) RemoveMapUser(username string) error { + mapper := NewMapper(svc.cfg.KubeClient, false) + err := mapper.Remove(&Arguments{ + DataType: MapUserData, + //Username: username, + CrdName: username, + WithRetries: svc.cfg.WithRetries, + MaxRetryCount: svc.cfg.MaxRetryCount, + MaxRetryTime: svc.cfg.MaxRetryTime, + MinRetryTime: svc.cfg.MinRetryTime, + }) + if err != nil { + svc.cfg.Log.Info("mapUser not found", "username", username) + } + return err +} diff --git a/charts/aws-auth-operator/.helmignore b/charts/aws-auth-operator/.helmignore new file mode 100644 index 0000000..0e8a0eb --- /dev/null +++ b/charts/aws-auth-operator/.helmignore @@ -0,0 +1,23 @@ +# 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/charts/aws-auth-operator/Chart.yaml b/charts/aws-auth-operator/Chart.yaml new file mode 100644 index 0000000..1679ccc --- /dev/null +++ b/charts/aws-auth-operator/Chart.yaml @@ -0,0 +1,24 @@ +apiVersion: v2 +name: aws-auth-operator +description: Kubernetes operator to declaratively manage the EKS aws-auth configmap + +# 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/) +version: 0.0.4 + +# 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. +appVersion: "0.0.4" diff --git a/charts/aws-auth-operator/README.md b/charts/aws-auth-operator/README.md new file mode 100644 index 0000000..2f937c6 --- /dev/null +++ b/charts/aws-auth-operator/README.md @@ -0,0 +1,61 @@ +# Kubernetes aws-auth-operator + +[aws-auth-operator](https://github.com/sambatv/aws-auth-operator/) is an operator to declaratively manage the EKS aws-auth configmap. + +## Installing the Chart + +Before you can install the chart you will need to add the `aws-auth-operator` +repo to [Helm](https://helm.sh/). + +```shell +helm repo add aws-auth-operator-charts https://sambatv.github.io/aws-auth-operator/ +``` + +After you've installed the repo you can install the chart. + +```shell +helm upgrade --install aws-auth-operator aws-auth-operator-charts/aws-auth-operator --namespace aws-auth-operator --create-namespace +``` + +## Configuration + +The following table lists the configurable parameters of the `sambatv/aws-auth-operator` +chart and their default values. + +| Parameter | Description | Default | +|--------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------| +| `image.repository` | Image repository. | `sambatv/aws-auth-operator` | +| `image.tag` | Image tag, will override the default tag derived from the chart app version. | `""` | +| `image.pullPolicy` | Image pull policy. | `IfNotPresent` | +| `imagePullSecrets` | Image pull secrets. | `[]` | +| `nameOverride` | Override the `name` of the chart. | `nil` | +| `fullnameOverride` | Override the `fullname` of the chart. | `nil` | +| `serviceAccount.create` | If `true`, create a new service account. | `true` | +| `serviceAccount.annotations` | Annotations to add to the service account. | `{}` | +| `serviceAccount.name` | Service account to be used. If not set and `serviceAccount.create` is `true`, a name is generated using the full name template. | `nil` | +| `rbac.create` | If `true`, create the RBAC resources. | `true` | +| `rbac.pspEnabled` | If `true`, create a pod security policy resource. | `false` | +| `apiService.create` | If `true`, create the `v1beta1.metrics.k8s.io` API service. You typically want this enabled! If you disable API service creation you have to manage it outside of this chart for e.g horizontal pod autoscaling to work with this release. | `true` | +| `podLabels` | Labels to add to the pod. | `{}` | +| `podAnnotations` | Annotations to add to the pod. | `{}` | +| `podSecurityContext` | Security context for the pod. | `{}` | +| `securityContext` | Security context for the _metrics-server_ container. | _See values.yaml_ | +| `priorityClassName` | Priority class name to use. | `system-cluster-critical` | +| `containerPort` | port for the _metrics-server_ container. | `10250` | +| `hostNetwork.enabled` | If `true`, start _metric-server_ in hostNetwork mode. You would require this enabled if you use alternate overlay networking for pods and API server unable to communicate with metrics-server. As an example, this is required if you use Weave network on EKS. | `false` | +| `replicas` | Number of replicas to run. | `1` | +| `updateStrategy` | Customise the default update strategy. | `{}` | +| `podDisruptionBudget.enabled` | If `true`, create `PodDisruptionBudget` resource. | `{}` | +| `podDisruptionBudget.minAvailable` | Set the `PodDisruptionBugdet` minimum available pods. | `nil` | +| `podDisruptionBudget.maxUnavailable` | Set the `PodDisruptionBugdet` maximum unavailable pods. | `nil` | +| `livenessProbe` | Liveness probe. | See _values.yaml_ | +| `readinessProbe` | Readiness probe. | See _values.yaml_ | +| `leaderElect.enabled` | If `true`, enable leader election for highly available installation. | `false` | +| `prometheus.enabled` | If `true`, enable unauthenticated access to Prometheus `/metrics` endpoint. | `false` | +| `resources` | Resource requests and limits for the _metrics-server_ container. See https://github.com/kubernetes-sigs/metrics-server#scaling | `{}` | +| `extraVolumeMounts` | Additional volume mounts for the _metrics-server_ container. | `[]` | +| `extraVolumes` | Additional volumes for the pod. | `[]` | +| `nodeSelector` | Node labels for pod assignment. | `{}` | +| `tolerations` | Tolerations for pod assignment. | `[]` | +| `affinity` | Affinity for pod assignment. | `{}` | +| `topologySpreadConstraints` | Pod Topology Spread Constraints. | `[]` | diff --git a/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapaccounts.yaml b/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapaccounts.yaml new file mode 100644 index 0000000..cc3e1b1 --- /dev/null +++ b/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapaccounts.yaml @@ -0,0 +1,54 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.18.0 + name: mapaccounts.prozorro.sr.ios.in.ua +spec: + group: prozorro.sr.ios.in.ua + names: + kind: MapAccount + listKind: MapAccountList + plural: mapaccounts + singular: mapaccount + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: MapAccount is the Schema for the mapaccounts API. + 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: MapAccountSpec defines the desired state of MapAccount. + properties: + foo: + description: Foo is an example field of MapAccount. Edit mapaccount_types.go + to remove/update + type: string + type: object + status: + description: MapAccountStatus defines the observed state of MapAccount. + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_maproles.yaml b/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_maproles.yaml new file mode 100644 index 0000000..39bbadd --- /dev/null +++ b/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_maproles.yaml @@ -0,0 +1,66 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.18.0 + name: maproles.prozorro.sr.ios.in.ua +spec: + group: prozorro.sr.ios.in.ua + names: + kind: MapRole + listKind: MapRoleList + plural: maproles + singular: maprole + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: MapRole is the Schema for the maproles API. + 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: MapRoleSpec defines the desired state of MapRole. + properties: + description: + description: A useful description of the MapRole + type: string + groups: + description: The Kubernetes groups to associate with the MapRole + items: + type: string + type: array + rolearn: + description: The Role ARN to associate with the MapRole + type: string + username: + description: The email address of a contact person for the MapUser + type: string + required: + - rolearn + type: object + status: + description: MapRoleStatus defines the observed state of MapRole. + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapusers.yaml b/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapusers.yaml new file mode 100644 index 0000000..8379655 --- /dev/null +++ b/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapusers.yaml @@ -0,0 +1,66 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.18.0 + name: mapusers.prozorro.sr.ios.in.ua +spec: + group: prozorro.sr.ios.in.ua + names: + kind: MapUser + listKind: MapUserList + plural: mapusers + singular: mapuser + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: MapUser is the Schema for the mapusers API. + 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: MapUserSpec defines the desired state of MapUser. + properties: + description: + description: A useful description of the MapUser + type: string + groups: + description: The Kubernetes groups to associate with the MapUser + items: + type: string + type: array + userarn: + description: The User ARN to associate with the MapUser + type: string + username: + description: The email address of a contact person for the MapUser + type: string + required: + - userarn + type: object + status: + description: MapUserStatus defines the observed state of MapUser. + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/charts/aws-auth-operator/templates/NOTES.txt b/charts/aws-auth-operator/templates/NOTES.txt new file mode 100644 index 0000000..e69de29 diff --git a/charts/aws-auth-operator/templates/_helpers.tpl b/charts/aws-auth-operator/templates/_helpers.tpl new file mode 100644 index 0000000..5612d3d --- /dev/null +++ b/charts/aws-auth-operator/templates/_helpers.tpl @@ -0,0 +1,62 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "aws-auth-operator.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 "aws-auth-operator.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 }} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "aws-auth-operator.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels +*/}} +{{- define "aws-auth-operator.labels" -}} +helm.sh/chart: {{ include "aws-auth-operator.chart" . }} +{{ include "aws-auth-operator.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels +*/}} +{{- define "aws-auth-operator.selectorLabels" -}} +app.kubernetes.io/name: {{ include "aws-auth-operator.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Create the name of the service account to use +*/}} +{{- define "aws-auth-operator.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "aws-auth-operator.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} diff --git a/charts/aws-auth-operator/templates/configmap.yaml b/charts/aws-auth-operator/templates/configmap.yaml new file mode 100644 index 0000000..caacecb --- /dev/null +++ b/charts/aws-auth-operator/templates/configmap.yaml @@ -0,0 +1,20 @@ +apiVersion: v1 +data: + controller_manager_config.yaml: | + apiVersion: controller-runtime.sigs.k8s.io/v1alpha1 + kind: ControllerManagerConfig + health: + healthProbeBindAddress: :8081 + metrics: + bindAddress: 127.0.0.1:8080 + webhook: + port: 9443 + leaderElection: + leaderElect: {{ .Values.leaderElect.enabled }} + resourceName: 7bfe6d29.aws-auth.sr.ios.in.ua +kind: ConfigMap +metadata: + name: aws-auth-operator-manager-config + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + control-plane: controller-manager diff --git a/charts/aws-auth-operator/templates/deployment.yaml b/charts/aws-auth-operator/templates/deployment.yaml new file mode 100644 index 0000000..fa1a46a --- /dev/null +++ b/charts/aws-auth-operator/templates/deployment.yaml @@ -0,0 +1,57 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + control-plane: controller-manager + name: aws-auth-operator-controller-manager +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + control-plane: controller-manager + template: + metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 8 }} + control-plane: controller-manager + spec: + containers: + - args: + - --leader-elect + command: + - /manager + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + livenessProbe: + httpGet: + path: /healthz + port: 8081 + initialDelaySeconds: 15 + periodSeconds: 20 + name: manager + readinessProbe: + httpGet: + path: /readyz + port: 8081 + initialDelaySeconds: 5 + periodSeconds: 10 + resources: + {{- toYaml .Values.resources | nindent 10 }} + securityContext: + allowPrivilegeEscalation: false + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.securityContext | nindent 8 }} + serviceAccountName: aws-auth-operator-controller-manager + terminationGracePeriodSeconds: 10 diff --git a/charts/aws-auth-operator/templates/pdb.yaml b/charts/aws-auth-operator/templates/pdb.yaml new file mode 100644 index 0000000..e3d77be --- /dev/null +++ b/charts/aws-auth-operator/templates/pdb.yaml @@ -0,0 +1,15 @@ +{{- if .Values.podDisruptionBudget.enabled -}} +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + control-plane: controller-manager + name: {{ include "aws-auth-operator.fullname" . }} +spec: + maxUnavailable: 1 + selector: + matchLabels: + app.kubernetes.io/name: {{ include "aws-auth-operator.name" . }} + app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} diff --git a/charts/aws-auth-operator/templates/prometheus.yaml b/charts/aws-auth-operator/templates/prometheus.yaml new file mode 100644 index 0000000..21f9ee2 --- /dev/null +++ b/charts/aws-auth-operator/templates/prometheus.yaml @@ -0,0 +1,20 @@ +{{- if .Values.prometheus.enabled -}} +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + control-plane: controller-manager + name: aws-auth-operator-controller-manager-metrics-monitor +spec: + endpoints: + - bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token + path: /metrics + port: https + scheme: https + tlsConfig: + insecureSkipVerify: true + selector: + matchLabels: + control-plane: controller-manager +{{- end }} \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/rbac.yaml b/charts/aws-auth-operator/templates/rbac.yaml new file mode 100644 index 0000000..86f7b22 --- /dev/null +++ b/charts/aws-auth-operator/templates/rbac.yaml @@ -0,0 +1,183 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + control-plane: controller-manager + name: aws-auth-operator-controller-manager +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + control-plane: controller-manager + name: aws-auth-operator-leader-election-role +rules: +- apiGroups: + - "" + resources: + - configmaps + verbs: + - get + - list + - watch + - create + - update + - patch + - delete +- 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: ClusterRole +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + control-plane: controller-manager + name: aws-auth-operator-manager-role +rules: +- apiGroups: + - prozorro.sr.ios.in.ua + resources: + - maproles + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - prozorro.sr.ios.in.ua + resources: + - maproles/finalizers + verbs: + - update +- apiGroups: + - prozorro.sr.ios.in.ua + resources: + - maproles/status + verbs: + - get + - patch + - update +- apiGroups: + - prozorro.sr.ios.in.ua + resources: + - mapusers + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - prozorro.sr.ios.in.ua + resources: + - mapusers/finalizers + verbs: + - update +- apiGroups: + - prozorro.sr.ios.in.ua + resources: + - mapusers/status + verbs: + - get + - patch + - update +- apiGroups: + - prozorro.sr.ios.in.ua + resources: + - mapaccounts + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - prozorro.sr.ios.in.ua + resources: + - mapaccounts/finalizers + verbs: + - update +- apiGroups: + - prozorro.sr.ios.in.ua + resources: + - mapaccounts/status + verbs: + - get + - patch + - update +- apiGroups: + - "" + resources: + - configmaps + verbs: + - get + - list + - patch + - update + - watch +- apiGroups: + - "" + resources: + - namespaces + verbs: + - get + - list + - watch +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + control-plane: controller-manager + name: aws-auth-operator-leader-election-rolebinding +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: aws-auth-operator-leader-election-role +subjects: +- kind: ServiceAccount + name: aws-auth-operator-controller-manager +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + control-plane: controller-manager + name: aws-auth-operator-manager-rolebinding +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: aws-auth-operator-manager-role +subjects: +- kind: ServiceAccount + name: aws-auth-operator-controller-manager + namespace: {{ .Release.Namespace }} \ No newline at end of file diff --git a/charts/aws-auth-operator/values.yaml b/charts/aws-auth-operator/values.yaml new file mode 100644 index 0000000..9008f01 --- /dev/null +++ b/charts/aws-auth-operator/values.yaml @@ -0,0 +1,94 @@ +# Default values for aws-auth-operator. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +replicaCount: 2 + +image: + #repository: ghcr.io/redacid/kubebuilder_test + repository: redacid/aws-auth-controller + pullPolicy: IfNotPresent + # Overrides the image tag whose default is the chart appVersion. + tag: "0.0.8" + +imagePullSecrets: [] +nameOverride: "" +fullnameOverride: "" + +serviceAccount: + # Specifies whether a service account should be created + create: 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: "" + +podAnnotations: {} + +podSecurityContext: {} + # fsGroup: 2000 + +securityContext: {} + # capabilities: + # drop: + # - ALL + # readOnlyRootFilesystem: true + # runAsNonRoot: true + # runAsUser: 1000 + +service: + type: ClusterIP + port: 80 + +ingress: + enabled: false + className: "" + annotations: {} + # kubernetes.io/ingress.class: nginx + # kubernetes.io/tls-acme: "true" + hosts: + - host: chart-example.local.domain + paths: + - path: / + pathType: ImplementationSpecific + tls: [] + # - secretName: chart-example-tls + # hosts: + # - chart-example.local + +resources: {} + # We usually recommend not to specify default resources and to leave this as a conscious + # choice for the user. This also increases chances charts run on environments with little + # resources, such as Minikube. If you do want to specify resources, uncomment the following + # lines, adjust them as necessary, and remove the curly braces after 'resources:'. + # limits: + # cpu: 100m + # memory: 128Mi + # requests: + # cpu: 100m + # memory: 128Mi + +autoscaling: + enabled: false + minReplicas: 1 + maxReplicas: 100 + targetCPUUtilizationPercentage: 80 + # targetMemoryUtilizationPercentage: 80 + +nodeSelector: {} + +tolerations: [] + +affinity: {} + +# Controller-specific config + +leaderElect: + enabled: true + +podDisruptionBudget: + enabled: true + +prometheus: + enabled: false diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..e3c3a62 --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,258 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "crypto/tls" + "flag" + "os" + "path/filepath" + + // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) + // to ensure that exec-entrypoint and run can make use of them. + _ "k8s.io/client-go/plugin/pkg/client/auth" + + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/certwatcher" + "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + "sigs.k8s.io/controller-runtime/pkg/metrics/filters" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + "sigs.k8s.io/controller-runtime/pkg/webhook" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + "github.com/redacid/aws-auth-controller/internal/controller" + // +kubebuilder:scaffold:imports +) + +var ( + scheme = runtime.NewScheme() + setupLog = ctrl.Log.WithName("setup") +) + +func init() { + utilruntime.Must(clientgoscheme.AddToScheme(scheme)) + + utilruntime.Must(awsauthv1beta1.AddToScheme(scheme)) + // +kubebuilder:scaffold:scheme +} + +// nolint:gocyclo +func main() { + var metricsAddr string + var metricsCertPath, metricsCertName, metricsCertKey string + var webhookCertPath, webhookCertName, webhookCertKey string + var enableLeaderElection bool + var probeAddr string + var secureMetrics bool + var enableHTTP2 bool + var tlsOpts []func(*tls.Config) + flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ + "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") + flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") + flag.BoolVar(&enableLeaderElection, "leader-elect", false, + "Enable leader election for controller manager. "+ + "Enabling this will ensure there is only one active controller manager.") + flag.BoolVar(&secureMetrics, "metrics-secure", true, + "If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.") + flag.StringVar(&webhookCertPath, "webhook-cert-path", "", "The directory that contains the webhook certificate.") + flag.StringVar(&webhookCertName, "webhook-cert-name", "tls.crt", "The name of the webhook certificate file.") + flag.StringVar(&webhookCertKey, "webhook-cert-key", "tls.key", "The name of the webhook key file.") + flag.StringVar(&metricsCertPath, "metrics-cert-path", "", + "The directory that contains the metrics server certificate.") + flag.StringVar(&metricsCertName, "metrics-cert-name", "tls.crt", "The name of the metrics server certificate file.") + flag.StringVar(&metricsCertKey, "metrics-cert-key", "tls.key", "The name of the metrics server key file.") + flag.BoolVar(&enableHTTP2, "enable-http2", false, + "If set, HTTP/2 will be enabled for the metrics and webhook servers") + opts := zap.Options{ + Development: true, + } + opts.BindFlags(flag.CommandLine) + flag.Parse() + + ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + + // if the enable-http2 flag is false (the default), http/2 should be disabled + // due to its vulnerabilities. More specifically, disabling http/2 will + // prevent from being vulnerable to the HTTP/2 Stream Cancellation and + // Rapid Reset CVEs. For more information see: + // - https://github.com/advisories/GHSA-qppj-fm5r-hxr3 + // - https://github.com/advisories/GHSA-4374-p667-p6c8 + disableHTTP2 := func(c *tls.Config) { + setupLog.Info("disabling http/2") + c.NextProtos = []string{"http/1.1"} + } + + if !enableHTTP2 { + tlsOpts = append(tlsOpts, disableHTTP2) + } + + // Create watchers for metrics and webhooks certificates + var metricsCertWatcher, webhookCertWatcher *certwatcher.CertWatcher + + // Initial webhook TLS options + webhookTLSOpts := tlsOpts + + if len(webhookCertPath) > 0 { + setupLog.Info("Initializing webhook certificate watcher using provided certificates", + "webhook-cert-path", webhookCertPath, "webhook-cert-name", webhookCertName, "webhook-cert-key", webhookCertKey) + + var err error + webhookCertWatcher, err = certwatcher.New( + filepath.Join(webhookCertPath, webhookCertName), + filepath.Join(webhookCertPath, webhookCertKey), + ) + if err != nil { + setupLog.Error(err, "Failed to initialize webhook certificate watcher") + os.Exit(1) + } + + webhookTLSOpts = append(webhookTLSOpts, func(config *tls.Config) { + config.GetCertificate = webhookCertWatcher.GetCertificate + }) + } + + webhookServer := webhook.NewServer(webhook.Options{ + TLSOpts: webhookTLSOpts, + }) + + // Metrics endpoint is enabled in 'config/default/kustomization.yaml'. The Metrics options configure the server. + // More info: + // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.21.0/pkg/metrics/server + // - https://book.kubebuilder.io/reference/metrics.html + metricsServerOptions := metricsserver.Options{ + BindAddress: metricsAddr, + SecureServing: secureMetrics, + TLSOpts: tlsOpts, + } + + if secureMetrics { + // FilterProvider is used to protect the metrics endpoint with authn/authz. + // These configurations ensure that only authorized users and service accounts + // can access the metrics endpoint. The RBAC are configured in 'config/rbac/kustomization.yaml'. More info: + // https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.21.0/pkg/metrics/filters#WithAuthenticationAndAuthorization + metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization + } + + // If the certificate is not specified, controller-runtime will automatically + // generate self-signed certificates for the metrics server. While convenient for development and testing, + // this setup is not recommended for production. + // + // TODO(user): If you enable certManager, uncomment the following lines: + // - [METRICS-WITH-CERTS] at config/default/kustomization.yaml to generate and use certificates + // managed by cert-manager for the metrics server. + // - [PROMETHEUS-WITH-CERTS] at config/prometheus/kustomization.yaml for TLS certification. + if len(metricsCertPath) > 0 { + setupLog.Info("Initializing metrics certificate watcher using provided certificates", + "metrics-cert-path", metricsCertPath, "metrics-cert-name", metricsCertName, "metrics-cert-key", metricsCertKey) + + var err error + metricsCertWatcher, err = certwatcher.New( + filepath.Join(metricsCertPath, metricsCertName), + filepath.Join(metricsCertPath, metricsCertKey), + ) + if err != nil { + setupLog.Error(err, "to initialize metrics certificate watcher", "error", err) + os.Exit(1) + } + + metricsServerOptions.TLSOpts = append(metricsServerOptions.TLSOpts, func(config *tls.Config) { + config.GetCertificate = metricsCertWatcher.GetCertificate + }) + } + + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ + Scheme: scheme, + Metrics: metricsServerOptions, + WebhookServer: webhookServer, + HealthProbeBindAddress: probeAddr, + LeaderElection: enableLeaderElection, + LeaderElectionID: "72c9b2c6.prozorro.sale", + // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily + // when the Manager ends. This requires the binary to immediately end when the + // Manager is stopped, otherwise, this setting is unsafe. Setting this significantly + // speeds up voluntary leader transitions as the new leader don't have to wait + // LeaseDuration time first. + // + // In the default scaffold provided, the program ends immediately after + // the manager stops, so would be fine to enable this option. However, + // if you are doing or is intended to do any operation such as perform cleanups + // after the manager stops then its usage might be unsafe. + // LeaderElectionReleaseOnCancel: true, + }) + if err != nil { + setupLog.Error(err, "unable to start manager") + os.Exit(1) + } + + if err := (&controller.MapRoleReconciler{ + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "MapRole") + os.Exit(1) + } + if err := (&controller.MapUserReconciler{ + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "MapUser") + os.Exit(1) + } + if err := (&controller.MapAccountReconciler{ + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "MapAccount") + os.Exit(1) + } + // +kubebuilder:scaffold:builder + + if metricsCertWatcher != nil { + setupLog.Info("Adding metrics certificate watcher to manager") + if err := mgr.Add(metricsCertWatcher); err != nil { + setupLog.Error(err, "unable to add metrics certificate watcher to manager") + os.Exit(1) + } + } + + if webhookCertWatcher != nil { + setupLog.Info("Adding webhook certificate watcher to manager") + if err := mgr.Add(webhookCertWatcher); err != nil { + setupLog.Error(err, "unable to add webhook certificate watcher to manager") + os.Exit(1) + } + } + + if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { + setupLog.Error(err, "unable to set up health check") + os.Exit(1) + } + if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { + setupLog.Error(err, "unable to set up ready check") + os.Exit(1) + } + + setupLog.Info("starting manager") + if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { + setupLog.Error(err, "problem running manager") + os.Exit(1) + } +} diff --git a/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml b/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml new file mode 100644 index 0000000..61e5ada --- /dev/null +++ b/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml @@ -0,0 +1,54 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.18.0 + name: mapaccounts.aws-auth.prozorro.sale +spec: + group: aws-auth.prozorro.sale + names: + kind: MapAccount + listKind: MapAccountList + plural: mapaccounts + singular: mapaccount + scope: Namespaced + versions: + - name: v1beta1 + schema: + openAPIV3Schema: + description: MapAccount is the Schema for the mapaccounts API. + 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: MapAccountSpec defines the desired state of MapAccount. + properties: + foo: + description: Foo is an example field of MapAccount. Edit mapaccount_types.go + to remove/update + type: string + type: object + status: + description: MapAccountStatus defines the observed state of MapAccount. + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml b/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml new file mode 100644 index 0000000..46ffc55 --- /dev/null +++ b/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml @@ -0,0 +1,66 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.18.0 + name: maproles.aws-auth.prozorro.sale +spec: + group: aws-auth.prozorro.sale + names: + kind: MapRole + listKind: MapRoleList + plural: maproles + singular: maprole + scope: Namespaced + versions: + - name: v1beta1 + schema: + openAPIV3Schema: + description: MapRole is the Schema for the maproles API. + 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: MapRoleSpec defines the desired state of MapRole. + properties: + description: + description: A useful description of the MapRole + type: string + groups: + description: The Kubernetes groups to associate with the MapRole + items: + type: string + type: array + rolearn: + description: The Role ARN to associate with the MapRole + type: string + username: + description: The username for the MapUser + type: string + required: + - rolearn + type: object + status: + description: MapRoleStatus defines the observed state of MapRole. + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml b/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml new file mode 100644 index 0000000..5e35325 --- /dev/null +++ b/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml @@ -0,0 +1,66 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.18.0 + name: mapusers.aws-auth.prozorro.sale +spec: + group: aws-auth.prozorro.sale + names: + kind: MapUser + listKind: MapUserList + plural: mapusers + singular: mapuser + scope: Namespaced + versions: + - name: v1beta1 + schema: + openAPIV3Schema: + description: MapUser is the Schema for the mapusers API. + 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: MapUserSpec defines the desired state of MapUser. + properties: + description: + description: A useful description of the MapUser + type: string + groups: + description: The Kubernetes groups to associate with the MapUser + items: + type: string + type: array + userarn: + description: The User ARN to associate with the MapUser + type: string + username: + description: The username for the MapUser + type: string + required: + - userarn + type: object + status: + description: MapUserStatus defines the observed state of MapUser. + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml new file mode 100644 index 0000000..65eef44 --- /dev/null +++ b/config/crd/kustomization.yaml @@ -0,0 +1,18 @@ +# This kustomization.yaml is not intended to be run by itself, +# since it depends on service name and namespace that are out of this kustomize package. +# It should be run by config/default +resources: +- bases/aws-auth.prozorro.sale_maproles.yaml +- bases/aws-auth.prozorro.sale_mapusers.yaml +- bases/aws-auth.prozorro.sale_mapaccounts.yaml +# +kubebuilder:scaffold:crdkustomizeresource + +patches: +# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix. +# patches here are for enabling the conversion webhook for each CRD +# +kubebuilder:scaffold:crdkustomizewebhookpatch + +# [WEBHOOK] To enable webhook, uncomment the following section +# the following config is for teaching kustomize how to do kustomization for CRDs. +#configurations: +#- kustomizeconfig.yaml diff --git a/config/crd/kustomizeconfig.yaml b/config/crd/kustomizeconfig.yaml new file mode 100644 index 0000000..ec5c150 --- /dev/null +++ b/config/crd/kustomizeconfig.yaml @@ -0,0 +1,19 @@ +# This file is for teaching kustomize how to substitute name and namespace reference in CRD +nameReference: +- kind: Service + version: v1 + fieldSpecs: + - kind: CustomResourceDefinition + version: v1 + group: apiextensions.k8s.io + path: spec/conversion/webhook/clientConfig/service/name + +namespace: +- kind: CustomResourceDefinition + version: v1 + group: apiextensions.k8s.io + path: spec/conversion/webhook/clientConfig/service/namespace + create: false + +varReference: +- path: metadata/annotations diff --git a/config/default/cert_metrics_manager_patch.yaml b/config/default/cert_metrics_manager_patch.yaml new file mode 100644 index 0000000..d975015 --- /dev/null +++ b/config/default/cert_metrics_manager_patch.yaml @@ -0,0 +1,30 @@ +# This patch adds the args, volumes, and ports to allow the manager to use the metrics-server certs. + +# Add the volumeMount for the metrics-server certs +- op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + mountPath: /tmp/k8s-metrics-server/metrics-certs + name: metrics-certs + readOnly: true + +# Add the --metrics-cert-path argument for the metrics server +- op: add + path: /spec/template/spec/containers/0/args/- + value: --metrics-cert-path=/tmp/k8s-metrics-server/metrics-certs + +# Add the metrics-server certs volume configuration +- op: add + path: /spec/template/spec/volumes/- + value: + name: metrics-certs + secret: + secretName: metrics-server-cert + optional: false + items: + - key: ca.crt + path: ca.crt + - key: tls.crt + path: tls.crt + - key: tls.key + path: tls.key diff --git a/config/default/kustomization.yaml b/config/default/kustomization.yaml new file mode 100644 index 0000000..b4c5f5c --- /dev/null +++ b/config/default/kustomization.yaml @@ -0,0 +1,234 @@ +# Adds namespace to all resources. +namespace: aws-auth-controller-prozorro-system + +# Value of this field is prepended to the +# names of all resources, e.g. a deployment named +# "wordpress" becomes "alices-wordpress". +# Note that it should also match with the prefix (text before '-') of the namespace +# field above. +namePrefix: aws-auth-controller-prozorro- + +# Labels to add to all resources and selectors. +#labels: +#- includeSelectors: true +# pairs: +# someName: someValue + +resources: +- ../crd +- ../rbac +- ../manager +# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in +# crd/kustomization.yaml +#- ../webhook +# [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'. 'WEBHOOK' components are required. +#- ../certmanager +# [PROMETHEUS] To enable prometheus monitor, uncomment all sections with 'PROMETHEUS'. +#- ../prometheus +# [METRICS] Expose the controller manager metrics service. +- metrics_service.yaml +# [NETWORK POLICY] Protect the /metrics endpoint and Webhook Server with NetworkPolicy. +# Only Pod(s) running a namespace labeled with 'metrics: enabled' will be able to gather the metrics. +# Only CR(s) which requires webhooks and are applied on namespaces labeled with 'webhooks: enabled' will +# be able to communicate with the Webhook Server. +#- ../network-policy + +# Uncomment the patches line if you enable Metrics +patches: +# [METRICS] The following patch will enable the metrics endpoint using HTTPS and the port :8443. +# More info: https://book.kubebuilder.io/reference/metrics +- path: manager_metrics_patch.yaml + target: + kind: Deployment + +# Uncomment the patches line if you enable Metrics and CertManager +# [METRICS-WITH-CERTS] To enable metrics protected with certManager, uncomment the following line. +# This patch will protect the metrics with certManager self-signed certs. +#- path: cert_metrics_manager_patch.yaml +# target: +# kind: Deployment + +# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in +# crd/kustomization.yaml +#- path: manager_webhook_patch.yaml +# target: +# kind: Deployment + +# [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER' prefix. +# Uncomment the following replacements to add the cert-manager CA injection annotations +#replacements: +# - source: # Uncomment the following block to enable certificates for metrics +# kind: Service +# version: v1 +# name: controller-manager-metrics-service +# fieldPath: metadata.name +# targets: +# - select: +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: metrics-certs +# fieldPaths: +# - spec.dnsNames.0 +# - spec.dnsNames.1 +# options: +# delimiter: '.' +# index: 0 +# create: true +# - select: # Uncomment the following to set the Service name for TLS config in Prometheus ServiceMonitor +# kind: ServiceMonitor +# group: monitoring.coreos.com +# version: v1 +# name: controller-manager-metrics-monitor +# fieldPaths: +# - spec.endpoints.0.tlsConfig.serverName +# options: +# delimiter: '.' +# index: 0 +# create: true +# +# - source: +# kind: Service +# version: v1 +# name: controller-manager-metrics-service +# fieldPath: metadata.namespace +# targets: +# - select: +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: metrics-certs +# fieldPaths: +# - spec.dnsNames.0 +# - spec.dnsNames.1 +# options: +# delimiter: '.' +# index: 1 +# create: true +# - select: # Uncomment the following to set the Service namespace for TLS in Prometheus ServiceMonitor +# kind: ServiceMonitor +# group: monitoring.coreos.com +# version: v1 +# name: controller-manager-metrics-monitor +# fieldPaths: +# - spec.endpoints.0.tlsConfig.serverName +# options: +# delimiter: '.' +# index: 1 +# create: true +# +# - source: # Uncomment the following block if you have any webhook +# kind: Service +# version: v1 +# name: webhook-service +# fieldPath: .metadata.name # Name of the service +# targets: +# - select: +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: serving-cert +# fieldPaths: +# - .spec.dnsNames.0 +# - .spec.dnsNames.1 +# options: +# delimiter: '.' +# index: 0 +# create: true +# - source: +# kind: Service +# version: v1 +# name: webhook-service +# fieldPath: .metadata.namespace # Namespace of the service +# targets: +# - select: +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: serving-cert +# fieldPaths: +# - .spec.dnsNames.0 +# - .spec.dnsNames.1 +# options: +# delimiter: '.' +# index: 1 +# create: true +# +# - source: # Uncomment the following block if you have a ValidatingWebhook (--programmatic-validation) +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: serving-cert # This name should match the one in certificate.yaml +# fieldPath: .metadata.namespace # Namespace of the certificate CR +# targets: +# - select: +# kind: ValidatingWebhookConfiguration +# fieldPaths: +# - .metadata.annotations.[cert-manager.io/inject-ca-from] +# options: +# delimiter: '/' +# index: 0 +# create: true +# - source: +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: serving-cert +# fieldPath: .metadata.name +# targets: +# - select: +# kind: ValidatingWebhookConfiguration +# fieldPaths: +# - .metadata.annotations.[cert-manager.io/inject-ca-from] +# options: +# delimiter: '/' +# index: 1 +# create: true +# +# - source: # Uncomment the following block if you have a DefaultingWebhook (--defaulting ) +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: serving-cert +# fieldPath: .metadata.namespace # Namespace of the certificate CR +# targets: +# - select: +# kind: MutatingWebhookConfiguration +# fieldPaths: +# - .metadata.annotations.[cert-manager.io/inject-ca-from] +# options: +# delimiter: '/' +# index: 0 +# create: true +# - source: +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: serving-cert +# fieldPath: .metadata.name +# targets: +# - select: +# kind: MutatingWebhookConfiguration +# fieldPaths: +# - .metadata.annotations.[cert-manager.io/inject-ca-from] +# options: +# delimiter: '/' +# index: 1 +# create: true +# +# - source: # Uncomment the following block if you have a ConversionWebhook (--conversion) +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: serving-cert +# fieldPath: .metadata.namespace # Namespace of the certificate CR +# targets: # Do not remove or uncomment the following scaffold marker; required to generate code for target CRD. +# +kubebuilder:scaffold:crdkustomizecainjectionns +# - source: +# kind: Certificate +# group: cert-manager.io +# version: v1 +# name: serving-cert +# fieldPath: .metadata.name +# targets: # Do not remove or uncomment the following scaffold marker; required to generate code for target CRD. +# +kubebuilder:scaffold:crdkustomizecainjectionname diff --git a/config/default/manager_metrics_patch.yaml b/config/default/manager_metrics_patch.yaml new file mode 100644 index 0000000..2aaef65 --- /dev/null +++ b/config/default/manager_metrics_patch.yaml @@ -0,0 +1,4 @@ +# This patch adds the args to allow exposing the metrics endpoint using HTTPS +- op: add + path: /spec/template/spec/containers/0/args/0 + value: --metrics-bind-address=:8443 diff --git a/config/default/metrics_service.yaml b/config/default/metrics_service.yaml new file mode 100644 index 0000000..3bc735a --- /dev/null +++ b/config/default/metrics_service.yaml @@ -0,0 +1,18 @@ +apiVersion: v1 +kind: Service +metadata: + labels: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: controller-manager-metrics-service + namespace: system +spec: + ports: + - name: https + port: 8443 + protocol: TCP + targetPort: 8443 + selector: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml new file mode 100644 index 0000000..5c5f0b8 --- /dev/null +++ b/config/manager/kustomization.yaml @@ -0,0 +1,2 @@ +resources: +- manager.yaml diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml new file mode 100644 index 0000000..2b9d88c --- /dev/null +++ b/config/manager/manager.yaml @@ -0,0 +1,98 @@ +apiVersion: v1 +kind: Namespace +metadata: + labels: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: system +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: controller-manager + namespace: system + labels: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize +spec: + selector: + matchLabels: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro + replicas: 1 + template: + metadata: + annotations: + kubectl.kubernetes.io/default-container: manager + labels: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro + spec: + # TODO(user): Uncomment the following code to configure the nodeAffinity expression + # according to the platforms which are supported by your solution. + # It is considered best practice to support multiple architectures. You can + # build your manager image using the makefile target docker-buildx. + # affinity: + # nodeAffinity: + # requiredDuringSchedulingIgnoredDuringExecution: + # nodeSelectorTerms: + # - matchExpressions: + # - key: kubernetes.io/arch + # operator: In + # values: + # - amd64 + # - arm64 + # - ppc64le + # - s390x + # - key: kubernetes.io/os + # operator: In + # values: + # - linux + securityContext: + # Projects are configured by default to adhere to the "restricted" Pod Security Standards. + # This ensures that deployments meet the highest security requirements for Kubernetes. + # For more details, see: https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + containers: + - command: + - /manager + args: + - --leader-elect + - --health-probe-bind-address=:8081 + image: controller:latest + name: manager + ports: [] + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - "ALL" + livenessProbe: + httpGet: + path: /healthz + port: 8081 + initialDelaySeconds: 15 + periodSeconds: 20 + readinessProbe: + httpGet: + path: /readyz + port: 8081 + initialDelaySeconds: 5 + periodSeconds: 10 + # TODO(user): Configure the resources accordingly based on the project requirements. + # More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ + resources: + limits: + cpu: 500m + memory: 128Mi + requests: + cpu: 10m + memory: 64Mi + volumeMounts: [] + volumes: [] + serviceAccountName: controller-manager + terminationGracePeriodSeconds: 10 diff --git a/config/network-policy/allow-metrics-traffic.yaml b/config/network-policy/allow-metrics-traffic.yaml new file mode 100644 index 0000000..bf2cc94 --- /dev/null +++ b/config/network-policy/allow-metrics-traffic.yaml @@ -0,0 +1,27 @@ +# This NetworkPolicy allows ingress traffic +# with Pods running on namespaces labeled with 'metrics: enabled'. Only Pods on those +# namespaces are able to gather data from the metrics endpoint. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: allow-metrics-traffic + namespace: system +spec: + podSelector: + matchLabels: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro + policyTypes: + - Ingress + ingress: + # This allows ingress traffic from any namespace with the label metrics: enabled + - from: + - namespaceSelector: + matchLabels: + metrics: enabled # Only from namespaces with this label + ports: + - port: 8443 + protocol: TCP diff --git a/config/network-policy/kustomization.yaml b/config/network-policy/kustomization.yaml new file mode 100644 index 0000000..ec0fb5e --- /dev/null +++ b/config/network-policy/kustomization.yaml @@ -0,0 +1,2 @@ +resources: +- allow-metrics-traffic.yaml diff --git a/config/prometheus/kustomization.yaml b/config/prometheus/kustomization.yaml new file mode 100644 index 0000000..fdc5481 --- /dev/null +++ b/config/prometheus/kustomization.yaml @@ -0,0 +1,11 @@ +resources: +- monitor.yaml + +# [PROMETHEUS-WITH-CERTS] The following patch configures the ServiceMonitor in ../prometheus +# to securely reference certificates created and managed by cert-manager. +# Additionally, ensure that you uncomment the [METRICS WITH CERTMANAGER] patch under config/default/kustomization.yaml +# to mount the "metrics-server-cert" secret in the Manager Deployment. +#patches: +# - path: monitor_tls_patch.yaml +# target: +# kind: ServiceMonitor diff --git a/config/prometheus/monitor.yaml b/config/prometheus/monitor.yaml new file mode 100644 index 0000000..8b42228 --- /dev/null +++ b/config/prometheus/monitor.yaml @@ -0,0 +1,27 @@ +# Prometheus Monitor Service (Metrics) +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + labels: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: controller-manager-metrics-monitor + namespace: system +spec: + endpoints: + - path: /metrics + port: https # Ensure this is the name of the port that exposes HTTPS metrics + scheme: https + bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token + tlsConfig: + # TODO(user): The option insecureSkipVerify: true is not recommended for production since it disables + # certificate verification, exposing the system to potential man-in-the-middle attacks. + # For production environments, it is recommended to use cert-manager for automatic TLS certificate management. + # To apply this configuration, enable cert-manager and use the patch located at config/prometheus/servicemonitor_tls_patch.yaml, + # which securely references the certificate from the 'metrics-server-cert' secret. + insecureSkipVerify: true + selector: + matchLabels: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro diff --git a/config/prometheus/monitor_tls_patch.yaml b/config/prometheus/monitor_tls_patch.yaml new file mode 100644 index 0000000..5bf84ce --- /dev/null +++ b/config/prometheus/monitor_tls_patch.yaml @@ -0,0 +1,19 @@ +# Patch for Prometheus ServiceMonitor to enable secure TLS configuration +# using certificates managed by cert-manager +- op: replace + path: /spec/endpoints/0/tlsConfig + value: + # SERVICE_NAME and SERVICE_NAMESPACE will be substituted by kustomize + serverName: SERVICE_NAME.SERVICE_NAMESPACE.svc + insecureSkipVerify: false + ca: + secret: + name: metrics-server-cert + key: ca.crt + cert: + secret: + name: metrics-server-cert + key: tls.crt + keySecret: + name: metrics-server-cert + key: tls.key diff --git a/config/rbac/kustomization.yaml b/config/rbac/kustomization.yaml new file mode 100644 index 0000000..9ea4144 --- /dev/null +++ b/config/rbac/kustomization.yaml @@ -0,0 +1,34 @@ +resources: +# All RBAC will be applied under this service account in +# the deployment namespace. You may comment out this resource +# if your manager will use a service account that exists at +# runtime. Be sure to update RoleBinding and ClusterRoleBinding +# subjects if changing service account names. +- service_account.yaml +- role.yaml +- role_binding.yaml +- leader_election_role.yaml +- leader_election_role_binding.yaml +# The following RBAC configurations are used to protect +# the metrics endpoint with authn/authz. These configurations +# ensure that only authorized users and service accounts +# can access the metrics endpoint. Comment the following +# permissions if you want to disable this protection. +# More info: https://book.kubebuilder.io/reference/metrics.html +- metrics_auth_role.yaml +- metrics_auth_role_binding.yaml +- metrics_reader_role.yaml +# For each CRD, "Admin", "Editor" and "Viewer" roles are scaffolded by +# default, aiding admins in cluster management. Those roles are +# not used by the aws-auth-controller-prozorro itself. You can comment the following lines +# if you do not want those helpers be installed with your Project. +- mapaccount_admin_role.yaml +- mapaccount_editor_role.yaml +- mapaccount_viewer_role.yaml +- mapuser_admin_role.yaml +- mapuser_editor_role.yaml +- mapuser_viewer_role.yaml +- maprole_admin_role.yaml +- maprole_editor_role.yaml +- maprole_viewer_role.yaml + diff --git a/config/rbac/leader_election_role.yaml b/config/rbac/leader_election_role.yaml new file mode 100644 index 0000000..e3025a2 --- /dev/null +++ b/config/rbac/leader_election_role.yaml @@ -0,0 +1,40 @@ +# permissions to do leader election. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: leader-election-role +rules: +- apiGroups: + - "" + resources: + - configmaps + verbs: + - get + - list + - watch + - create + - update + - patch + - delete +- apiGroups: + - coordination.k8s.io + resources: + - leases + verbs: + - get + - list + - watch + - create + - update + - patch + - delete +- apiGroups: + - "" + resources: + - events + verbs: + - create + - patch diff --git a/config/rbac/leader_election_role_binding.yaml b/config/rbac/leader_election_role_binding.yaml new file mode 100644 index 0000000..358a66e --- /dev/null +++ b/config/rbac/leader_election_role_binding.yaml @@ -0,0 +1,15 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: leader-election-rolebinding +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: leader-election-role +subjects: +- kind: ServiceAccount + name: controller-manager + namespace: system diff --git a/config/rbac/mapaccount_admin_role.yaml b/config/rbac/mapaccount_admin_role.yaml new file mode 100644 index 0000000..685f3b6 --- /dev/null +++ b/config/rbac/mapaccount_admin_role.yaml @@ -0,0 +1,27 @@ +# This rule is not used by the project aws-auth-controller-prozorro itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants full permissions ('*') over aws-auth.prozorro.sale. +# This role is intended for users authorized to modify roles and bindings within the cluster, +# enabling them to delegate specific permissions to other users or groups as needed. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapaccount-admin-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts + verbs: + - '*' +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts/status + verbs: + - get diff --git a/config/rbac/mapaccount_editor_role.yaml b/config/rbac/mapaccount_editor_role.yaml new file mode 100644 index 0000000..529b975 --- /dev/null +++ b/config/rbac/mapaccount_editor_role.yaml @@ -0,0 +1,33 @@ +# This rule is not used by the project aws-auth-controller-prozorro itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants permissions to create, update, and delete resources within the aws-auth.prozorro.sale. +# This role is intended for users who need to manage these resources +# but should not control RBAC or manage permissions for others. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapaccount-editor-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts/status + verbs: + - get diff --git a/config/rbac/mapaccount_viewer_role.yaml b/config/rbac/mapaccount_viewer_role.yaml new file mode 100644 index 0000000..196b101 --- /dev/null +++ b/config/rbac/mapaccount_viewer_role.yaml @@ -0,0 +1,29 @@ +# This rule is not used by the project aws-auth-controller-prozorro itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants read-only access to aws-auth.prozorro.sale resources. +# This role is intended for users who need visibility into these resources +# without permissions to modify them. It is ideal for monitoring purposes and limited-access viewing. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapaccount-viewer-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts + verbs: + - get + - list + - watch +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts/status + verbs: + - get diff --git a/config/rbac/maprole_admin_role.yaml b/config/rbac/maprole_admin_role.yaml new file mode 100644 index 0000000..0558cc3 --- /dev/null +++ b/config/rbac/maprole_admin_role.yaml @@ -0,0 +1,27 @@ +# This rule is not used by the project aws-auth-controller-prozorro itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants full permissions ('*') over aws-auth.prozorro.sale. +# This role is intended for users authorized to modify roles and bindings within the cluster, +# enabling them to delegate specific permissions to other users or groups as needed. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: maprole-admin-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - maproles + verbs: + - '*' +- apiGroups: + - aws-auth.prozorro.sale + resources: + - maproles/status + verbs: + - get diff --git a/config/rbac/maprole_editor_role.yaml b/config/rbac/maprole_editor_role.yaml new file mode 100644 index 0000000..3fc2898 --- /dev/null +++ b/config/rbac/maprole_editor_role.yaml @@ -0,0 +1,33 @@ +# This rule is not used by the project aws-auth-controller-prozorro itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants permissions to create, update, and delete resources within the aws-auth.prozorro.sale. +# This role is intended for users who need to manage these resources +# but should not control RBAC or manage permissions for others. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: maprole-editor-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - maproles + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - aws-auth.prozorro.sale + resources: + - maproles/status + verbs: + - get diff --git a/config/rbac/maprole_viewer_role.yaml b/config/rbac/maprole_viewer_role.yaml new file mode 100644 index 0000000..5489996 --- /dev/null +++ b/config/rbac/maprole_viewer_role.yaml @@ -0,0 +1,29 @@ +# This rule is not used by the project aws-auth-controller-prozorro itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants read-only access to aws-auth.prozorro.sale resources. +# This role is intended for users who need visibility into these resources +# without permissions to modify them. It is ideal for monitoring purposes and limited-access viewing. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: maprole-viewer-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - maproles + verbs: + - get + - list + - watch +- apiGroups: + - aws-auth.prozorro.sale + resources: + - maproles/status + verbs: + - get diff --git a/config/rbac/mapuser_admin_role.yaml b/config/rbac/mapuser_admin_role.yaml new file mode 100644 index 0000000..698937a --- /dev/null +++ b/config/rbac/mapuser_admin_role.yaml @@ -0,0 +1,27 @@ +# This rule is not used by the project aws-auth-controller-prozorro itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants full permissions ('*') over aws-auth.prozorro.sale. +# This role is intended for users authorized to modify roles and bindings within the cluster, +# enabling them to delegate specific permissions to other users or groups as needed. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapuser-admin-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapusers + verbs: + - '*' +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapusers/status + verbs: + - get diff --git a/config/rbac/mapuser_editor_role.yaml b/config/rbac/mapuser_editor_role.yaml new file mode 100644 index 0000000..4fe161b --- /dev/null +++ b/config/rbac/mapuser_editor_role.yaml @@ -0,0 +1,33 @@ +# This rule is not used by the project aws-auth-controller-prozorro itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants permissions to create, update, and delete resources within the aws-auth.prozorro.sale. +# This role is intended for users who need to manage these resources +# but should not control RBAC or manage permissions for others. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapuser-editor-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapusers + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapusers/status + verbs: + - get diff --git a/config/rbac/mapuser_viewer_role.yaml b/config/rbac/mapuser_viewer_role.yaml new file mode 100644 index 0000000..8278490 --- /dev/null +++ b/config/rbac/mapuser_viewer_role.yaml @@ -0,0 +1,29 @@ +# This rule is not used by the project aws-auth-controller-prozorro itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants read-only access to aws-auth.prozorro.sale resources. +# This role is intended for users who need visibility into these resources +# without permissions to modify them. It is ideal for monitoring purposes and limited-access viewing. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapuser-viewer-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapusers + verbs: + - get + - list + - watch +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapusers/status + verbs: + - get diff --git a/config/rbac/metrics_auth_role.yaml b/config/rbac/metrics_auth_role.yaml new file mode 100644 index 0000000..32d2e4e --- /dev/null +++ b/config/rbac/metrics_auth_role.yaml @@ -0,0 +1,17 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: metrics-auth-role +rules: +- apiGroups: + - authentication.k8s.io + resources: + - tokenreviews + verbs: + - create +- apiGroups: + - authorization.k8s.io + resources: + - subjectaccessreviews + verbs: + - create diff --git a/config/rbac/metrics_auth_role_binding.yaml b/config/rbac/metrics_auth_role_binding.yaml new file mode 100644 index 0000000..e775d67 --- /dev/null +++ b/config/rbac/metrics_auth_role_binding.yaml @@ -0,0 +1,12 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: metrics-auth-rolebinding +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: metrics-auth-role +subjects: +- kind: ServiceAccount + name: controller-manager + namespace: system diff --git a/config/rbac/metrics_reader_role.yaml b/config/rbac/metrics_reader_role.yaml new file mode 100644 index 0000000..51a75db --- /dev/null +++ b/config/rbac/metrics_reader_role.yaml @@ -0,0 +1,9 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: metrics-reader +rules: +- nonResourceURLs: + - "/metrics" + verbs: + - get diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml new file mode 100644 index 0000000..f1c366c --- /dev/null +++ b/config/rbac/role.yaml @@ -0,0 +1,38 @@ +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: manager-role +rules: +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts + - maproles + - mapusers + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts/finalizers + - maproles/finalizers + - mapusers/finalizers + verbs: + - update +- apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts/status + - maproles/status + - mapusers/status + verbs: + - get + - patch + - update diff --git a/config/rbac/role_binding.yaml b/config/rbac/role_binding.yaml new file mode 100644 index 0000000..f9a397c --- /dev/null +++ b/config/rbac/role_binding.yaml @@ -0,0 +1,15 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: manager-rolebinding +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: manager-role +subjects: +- kind: ServiceAccount + name: controller-manager + namespace: system diff --git a/config/rbac/service_account.yaml b/config/rbac/service_account.yaml new file mode 100644 index 0000000..9cbb87d --- /dev/null +++ b/config/rbac/service_account.yaml @@ -0,0 +1,8 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: controller-manager + namespace: system diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml new file mode 100644 index 0000000..4f1fa26 --- /dev/null +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -0,0 +1,9 @@ +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapAccount +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapaccount-sample +spec: + # TODO(user): Add fields here diff --git a/config/samples/aws-auth_v1beta1_maprole.yaml b/config/samples/aws-auth_v1beta1_maprole.yaml new file mode 100644 index 0000000..a164f4b --- /dev/null +++ b/config/samples/aws-auth_v1beta1_maprole.yaml @@ -0,0 +1,9 @@ +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: maprole-sample +spec: + # TODO(user): Add fields here diff --git a/config/samples/aws-auth_v1beta1_mapuser.yaml b/config/samples/aws-auth_v1beta1_mapuser.yaml new file mode 100644 index 0000000..683df66 --- /dev/null +++ b/config/samples/aws-auth_v1beta1_mapuser.yaml @@ -0,0 +1,9 @@ +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapUser +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapuser-sample +spec: + # TODO(user): Add fields here diff --git a/config/samples/kustomization.yaml b/config/samples/kustomization.yaml new file mode 100644 index 0000000..829d25a --- /dev/null +++ b/config/samples/kustomization.yaml @@ -0,0 +1,6 @@ +## Append samples of your project ## +resources: +- aws-auth_v1beta1_maprole.yaml +- aws-auth_v1beta1_mapuser.yaml +- aws-auth_v1beta1_mapaccount.yaml +# +kubebuilder:scaffold:manifestskustomizesamples diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..6da7649 --- /dev/null +++ b/go.mod @@ -0,0 +1,100 @@ +module github.com/redacid/aws-auth-controller + +go 1.24.0 + +require ( + github.com/go-logr/logr v1.4.2 + github.com/jpillora/backoff v1.0.0 + github.com/mitchellh/go-homedir v1.1.0 + github.com/onsi/ginkgo/v2 v2.22.0 + github.com/onsi/gomega v1.36.1 + github.com/pkg/errors v0.9.1 + gopkg.in/yaml.v2 v2.4.0 + k8s.io/api v0.33.0 + k8s.io/apimachinery v0.33.0 + k8s.io/client-go v0.33.0 + sigs.k8s.io/controller-runtime v0.21.0 +) + +require ( + cel.dev/expr v0.19.1 // indirect + github.com/antlr4-go/antlr/v4 v4.13.0 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/blang/semver/v4 v4.0.0 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // 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/felixge/httpsnoop v1.0.4 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/fxamacker/cbor/v2 v2.7.0 // 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.21.0 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect + github.com/go-openapi/swag v0.23.0 // indirect + github.com/go-task/slim-sprig/v3 v3.0.0 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/google/btree v1.1.3 // indirect + github.com/google/cel-go v0.23.2 // indirect + github.com/google/gnostic-models v0.6.9 // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.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/mailru/easyjson v0.7.7 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // 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/cobra v1.8.1 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/stoewer/go-strcase v1.3.0 // indirect + github.com/x448/float16 v0.8.4 // indirect + go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 // indirect + go.opentelemetry.io/otel v1.33.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 // indirect + go.opentelemetry.io/otel/metric v1.33.0 // indirect + go.opentelemetry.io/otel/sdk v1.33.0 // indirect + go.opentelemetry.io/otel/trace v1.33.0 // indirect + go.opentelemetry.io/proto/otlp v1.4.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.27.0 // indirect + golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect + golang.org/x/net v0.38.0 // indirect + golang.org/x/oauth2 v0.27.0 // indirect + golang.org/x/sync v0.12.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 + golang.org/x/tools v0.26.0 // indirect + gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20241209162323-e6fa225c2576 // indirect + google.golang.org/grpc v1.68.1 // 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 + gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/apiextensions-apiserver v0.33.0 // indirect + k8s.io/apiserver v0.33.0 // indirect + k8s.io/component-base v0.33.0 // indirect + k8s.io/klog/v2 v2.130.1 // indirect + k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff // indirect + k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect + sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.2 // 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/v4 v4.6.0 // indirect + sigs.k8s.io/yaml v1.4.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..eb1a07f --- /dev/null +++ b/go.sum @@ -0,0 +1,260 @@ +cel.dev/expr v0.19.1 h1:NciYrtDRIR0lNCnH1LFJegdjspNx9fI59O7TWcua/W4= +cel.dev/expr v0.19.1/go.mod h1:MrpN08Q+lEBs+bGYdLxxHkZoUSsCp0nSKTs0nTymJgw= +github.com/antlr4-go/antlr/v4 v4.13.0 h1:lxCg3LAv+EUK6t1i0y1V6/SLeUi0eKEKdhQAlS8TVTI= +github.com/antlr4-go/antlr/v4 v4.13.0/go.mod h1:pfChB/xh/Unjila75QW7+VU4TSnWnnk9UTnmpPaOR2g= +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/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/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +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/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.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-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +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/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.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/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.23.2 h1:UdEe3CvQh3Nv+E/j9r1Y//WO0K0cSyD7/y0bzyLIMI4= +github.com/google/cel-go v0.23.2/go.mod h1:52Pb6QsDbC5kvgxvZhiL9QX1oZEkcUF/ZqaPx1J5Wwo= +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.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/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-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/grpc-ecosystem/grpc-gateway/v2 v2.24.0 h1:TmHmbvxPmaegwhDubVz0lICL0J5Ka2vwTzhoePEXsGE= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0/go.mod h1:qztMSjm835F2bXf+5HKAPIS5qsmQDqZna/PgVt4rWtI= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +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/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA= +github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= +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/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= +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/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +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/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.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/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/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= +github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= +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/stoewer/go-strcase v1.3.0 h1:g0eASXYtp+yvN9fK8sH94oCIk0fau9uV1/ZdJ0AVEzs= +github.com/stoewer/go-strcase v1.3.0/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo= +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.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/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 h1:yd02MEjBdJkG3uabWP9apV+OuWRIXGDuJEUJbOHmCFU= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0/go.mod h1:umTcuxiv1n/s/S6/c2AT/g2CQ7u5C59sHDNmfSwgz7Q= +go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw= +go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 h1:Vh5HayB/0HHfOQA7Ctx69E/Y/DcQSMPpKANYVMQ7fBA= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0/go.mod h1:cpgtDBaqD/6ok/UG0jT15/uKjAY8mRA53diogHBg3UI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 h1:5pojmb1U1AogINhN3SurB+zm/nIcusopeBNp42f45QM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0/go.mod h1:57gTHJSE5S1tqg+EKsLPlTWhpHMsWlVmer+LA926XiA= +go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ= +go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M= +go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc2IM= +go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM= +go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s= +go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck= +go.opentelemetry.io/proto/otlp v1.4.0 h1:TA9WRvW6zMwP+Ssb6fLoUIuirti1gGbP28GcKG1jgeg= +go.opentelemetry.io/proto/otlp v1.4.0/go.mod h1:PPBWZIP98o2ElSqI35IHfu7hIhSwvc5N38Jw8pXuGFY= +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.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +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/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8= +golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= +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/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= +golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= +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.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.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.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/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.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.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw= +gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= +google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576 h1:CkkIfIt50+lT6NHAVoRYEyAvQGFM7xEwXUUywFvEb3Q= +google.golang.org/genproto/googleapis/api v0.0.0-20241209162323-e6fa225c2576/go.mod h1:1R3kvZ1dtP3+4p4d3G8uJ8rFk/fWlScl38vanWACI08= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241209162323-e6fa225c2576 h1:8ZmaLZE4XWrtU3MyClkYqqtl6Oegr3235h7jxsDyqCY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241209162323-e6fa225c2576/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU= +google.golang.org/grpc v1.68.1 h1:oI5oTa11+ng8r8XMMN7jAOmWfPZWbYpCFaMUTACxkM0= +google.golang.org/grpc v1.68.1/go.mod h1:+q1XYFJjShcqn0QZHvCyeR4CXPA+llXIeUIfIe00waw= +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-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.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/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= +k8s.io/api v0.33.0 h1:yTgZVn1XEe6opVpP1FylmNrIFWuDqe2H0V8CT5gxfIU= +k8s.io/api v0.33.0/go.mod h1:CTO61ECK/KU7haa3qq8sarQ0biLq2ju405IZAd9zsiM= +k8s.io/apiextensions-apiserver v0.33.0 h1:d2qpYL7Mngbsc1taA4IjJPRJ9ilnsXIrndH+r9IimOs= +k8s.io/apiextensions-apiserver v0.33.0/go.mod h1:VeJ8u9dEEN+tbETo+lFkwaaZPg6uFKLGj5vyNEwwSzc= +k8s.io/apimachinery v0.33.0 h1:1a6kHrJxb2hs4t8EE5wuR/WxKDwGN1FKH3JvDtA0CIQ= +k8s.io/apimachinery v0.33.0/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= +k8s.io/apiserver v0.33.0 h1:QqcM6c+qEEjkOODHppFXRiw/cE2zP85704YrQ9YaBbc= +k8s.io/apiserver v0.33.0/go.mod h1:EixYOit0YTxt8zrO2kBU7ixAtxFce9gKGq367nFmqI8= +k8s.io/client-go v0.33.0 h1:UASR0sAYVUzs2kYuKn/ZakZlcs2bEHaizrrHUZg0G98= +k8s.io/client-go v0.33.0/go.mod h1:kGkd+l/gNGg8GYWAPr0xF1rRKvVWvzh9vmZAMXtaKOg= +k8s.io/component-base v0.33.0 h1:Ot4PyJI+0JAD9covDhwLp9UNkUja209OzsJ4FzScBNk= +k8s.io/component-base v0.33.0/go.mod h1:aXYZLbw3kihdkOPMDhWbjGCO6sg+luw554KP51t8qCU= +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/apiserver-network-proxy/konnectivity-client v0.31.2 h1:jpcvIRr3GLoUoEKRkHKSmGjxb6lWwrBlJsXc+eUYQHM= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.2/go.mod h1:Ve9uj1L+deCXFrPOk1LpFXqTg7LCFzFso6PA48q/XZw= +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/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.go.txt b/hack/boilerplate.go.txt new file mode 100644 index 0000000..221dcbe --- /dev/null +++ b/hack/boilerplate.go.txt @@ -0,0 +1,15 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ \ No newline at end of file diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go new file mode 100644 index 0000000..ca8456c --- /dev/null +++ b/internal/controller/mapaccount_controller.go @@ -0,0 +1,63 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controller + +import ( + "context" + + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + logf "sigs.k8s.io/controller-runtime/pkg/log" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" +) + +// MapAccountReconciler reconciles a MapAccount object +type MapAccountReconciler struct { + client.Client + Scheme *runtime.Scheme +} + +// +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapaccounts,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapaccounts/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapaccounts/finalizers,verbs=update + +// Reconcile is part of the main kubernetes reconciliation loop which aims to +// move the current state of the cluster closer to the desired state. +// TODO(user): Modify the Reconcile function to compare the state specified by +// the MapAccount object against the actual cluster state, and then +// perform operations to make the cluster state reflect the state specified by +// the user. +// +// For more details, check Reconcile and its Result here: +// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.21.0/pkg/reconcile +func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + _ = logf.FromContext(ctx) + + // TODO(user): your logic here + + return ctrl.Result{}, nil +} + +// SetupWithManager sets up the controller with the Manager. +func (r *MapAccountReconciler) SetupWithManager(mgr ctrl.Manager) error { + return ctrl.NewControllerManagedBy(mgr). + For(&awsauthv1beta1.MapAccount{}). + Named("mapaccount"). + Complete(r) +} diff --git a/internal/controller/mapaccount_controller_test.go b/internal/controller/mapaccount_controller_test.go new file mode 100644 index 0000000..14c5958 --- /dev/null +++ b/internal/controller/mapaccount_controller_test.go @@ -0,0 +1,84 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controller + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" +) + +var _ = Describe("MapAccount Controller", func() { + Context("When reconciling a resource", func() { + const resourceName = "test-resource" + + ctx := context.Background() + + typeNamespacedName := types.NamespacedName{ + Name: resourceName, + Namespace: "default", // TODO(user):Modify as needed + } + mapaccount := &awsauthv1beta1.MapAccount{} + + BeforeEach(func() { + By("creating the custom resource for the Kind MapAccount") + err := k8sClient.Get(ctx, typeNamespacedName, mapaccount) + if err != nil && errors.IsNotFound(err) { + resource := &awsauthv1beta1.MapAccount{ + ObjectMeta: metav1.ObjectMeta{ + Name: resourceName, + Namespace: "default", + }, + // TODO(user): Specify other spec details if needed. + } + Expect(k8sClient.Create(ctx, resource)).To(Succeed()) + } + }) + + AfterEach(func() { + // TODO(user): Cleanup logic after each test, like removing the resource instance. + resource := &awsauthv1beta1.MapAccount{} + err := k8sClient.Get(ctx, typeNamespacedName, resource) + Expect(err).NotTo(HaveOccurred()) + + By("Cleanup the specific resource instance MapAccount") + Expect(k8sClient.Delete(ctx, resource)).To(Succeed()) + }) + It("should successfully reconcile the resource", func() { + By("Reconciling the created resource") + controllerReconciler := &MapAccountReconciler{ + Client: k8sClient, + Scheme: k8sClient.Scheme(), + } + + _, err := controllerReconciler.Reconcile(ctx, reconcile.Request{ + NamespacedName: typeNamespacedName, + }) + Expect(err).NotTo(HaveOccurred()) + // TODO(user): Add more specific assertions depending on your controller's reconciliation logic. + // Example: If you expect a certain status condition after reconciliation, verify it here. + }) + }) +}) diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go new file mode 100644 index 0000000..669f783 --- /dev/null +++ b/internal/controller/maprole_controller.go @@ -0,0 +1,113 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controller + +import ( + "context" + apierrors "k8s.io/apimachinery/pkg/api/errors" + + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + logf "sigs.k8s.io/controller-runtime/pkg/log" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + "github.com/redacid/aws-auth-controller/awsauth" + "github.com/redacid/aws-auth-controller/kube" +) + +// MapRoleReconciler reconciles a MapRole object +type MapRoleReconciler struct { + client.Client + Scheme *runtime.Scheme +} + +// +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=maproles,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=maproles/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=maproles/finalizers,verbs=update + +// Reconcile is part of the main kubernetes reconciliation loop which aims to +// move the current state of the cluster closer to the desired state. +// TODO(user): Modify the Reconcile function to compare the state specified by +// the MapRole object against the actual cluster state, and then +// perform operations to make the cluster state reflect the state specified by +// the user. +// +// For more details, check Reconcile and its Result here: +// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.21.0/pkg/reconcile +func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + _ = logf.FromContext(ctx) + + mapRoleName := req.Name + log := ctrl.Log.WithValues("MapRole", mapRoleName) + log.Info("reconciling MapRole...") + + kubeClient, err := kube.GetClient() + if err != nil { + log.Error(err, "failure getting kube client") + return ctrl.Result{}, err + } + + // Get a new aws auth service object. + awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ + KubeClient: kubeClient, + //Log: r.Log, + Log: ctrl.Log, + }) + if err != nil { + log.Error(err, "failure creating new aws auth service") + return ctrl.Result{}, err + } + + // Load the MapRole object by name (its AWS IAM role ARN). + var mapRole awsauthv1beta1.MapRole + if err := r.Get(ctx, req.NamespacedName, &mapRole); err != nil { + // If any error other than a "NotFound" API error, it's a problem. + statusErr, ok := err.(*apierrors.StatusError) + if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { + log.Error(err, "failure getting MapRole") + return ctrl.Result{}, err + } + + if err := awsauthSvc.RemoveMapRole(mapRoleName); err != nil { + log.Error(err, "error removing mapRole data in aws-auth configmap") + return ctrl.Result{}, nil + } + log.Info("removed mapRole data in aws-auth configmap") + return ctrl.Result{}, nil + } + + // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. + if err := awsauthSvc.UpsertMapRole(mapRole.Name, awsauth.MapRole{ + RoleARN: mapRole.Spec.RoleARN, + Groups: mapRole.Spec.Groups, + }); err != nil { + log.Error(err, "error upserting MapRole in aws-auth") + return ctrl.Result{}, err + } + log.Info("upserted MapRole") + + return ctrl.Result{}, nil +} + +// SetupWithManager sets up the controller with the Manager. +func (r *MapRoleReconciler) SetupWithManager(mgr ctrl.Manager) error { + return ctrl.NewControllerManagedBy(mgr). + For(&awsauthv1beta1.MapRole{}). + Named("maprole"). + Complete(r) +} diff --git a/internal/controller/maprole_controller_test.go b/internal/controller/maprole_controller_test.go new file mode 100644 index 0000000..110f561 --- /dev/null +++ b/internal/controller/maprole_controller_test.go @@ -0,0 +1,84 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controller + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" +) + +var _ = Describe("MapRole Controller", func() { + Context("When reconciling a resource", func() { + const resourceName = "test-resource" + + ctx := context.Background() + + typeNamespacedName := types.NamespacedName{ + Name: resourceName, + Namespace: "default", // TODO(user):Modify as needed + } + maprole := &awsauthv1beta1.MapRole{} + + BeforeEach(func() { + By("creating the custom resource for the Kind MapRole") + err := k8sClient.Get(ctx, typeNamespacedName, maprole) + if err != nil && errors.IsNotFound(err) { + resource := &awsauthv1beta1.MapRole{ + ObjectMeta: metav1.ObjectMeta{ + Name: resourceName, + Namespace: "default", + }, + // TODO(user): Specify other spec details if needed. + } + Expect(k8sClient.Create(ctx, resource)).To(Succeed()) + } + }) + + AfterEach(func() { + // TODO(user): Cleanup logic after each test, like removing the resource instance. + resource := &awsauthv1beta1.MapRole{} + err := k8sClient.Get(ctx, typeNamespacedName, resource) + Expect(err).NotTo(HaveOccurred()) + + By("Cleanup the specific resource instance MapRole") + Expect(k8sClient.Delete(ctx, resource)).To(Succeed()) + }) + It("should successfully reconcile the resource", func() { + By("Reconciling the created resource") + controllerReconciler := &MapRoleReconciler{ + Client: k8sClient, + Scheme: k8sClient.Scheme(), + } + + _, err := controllerReconciler.Reconcile(ctx, reconcile.Request{ + NamespacedName: typeNamespacedName, + }) + Expect(err).NotTo(HaveOccurred()) + // TODO(user): Add more specific assertions depending on your controller's reconciliation logic. + // Example: If you expect a certain status condition after reconciliation, verify it here. + }) + }) +}) diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go new file mode 100644 index 0000000..dee6094 --- /dev/null +++ b/internal/controller/mapuser_controller.go @@ -0,0 +1,119 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controller + +import ( + "context" + apierrors "k8s.io/apimachinery/pkg/api/errors" + + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + logf "sigs.k8s.io/controller-runtime/pkg/log" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + "github.com/redacid/aws-auth-controller/awsauth" + "github.com/redacid/aws-auth-controller/kube" +) + +// MapUserReconciler reconciles a MapUser object +type MapUserReconciler struct { + client.Client + Scheme *runtime.Scheme +} + +// +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapusers,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapusers/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapusers/finalizers,verbs=update + +// Reconcile is part of the main kubernetes reconciliation loop which aims to +// move the current state of the cluster closer to the desired state. +// TODO(user): Modify the Reconcile function to compare the state specified by +// the MapUser object against the actual cluster state, and then +// perform operations to make the cluster state reflect the state specified by +// the user. +// +// For more details, check Reconcile and its Result here: +// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.21.0/pkg/reconcile +func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + _ = logf.FromContext(ctx) + + // MapUser objects are named by their associated AWS IAM user ARNs. + // mapUserName := req.Name + mapUserName := req.Name + log := ctrl.Log.WithValues("MapUser", mapUserName) + //log := r. Log.WithValues("MapUser", mapUserName) + log.Info("") + + kubeClient, err := kube.GetClient() + if err != nil { + log.Error(err, "failure getting kube client") + return ctrl.Result{}, err + } + + // Get a new aws auth service object. + awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ + KubeClient: kubeClient, + //Log: r.Log, + Log: ctrl.Log, + }) + if err != nil { + log.Error(err, "failure creating new aws auth service") + return ctrl.Result{}, err + } + + // Load the MapUser object by name (its AWS IAM user ARN). + var mapUser awsauthv1beta1.MapUser + + if err := r.Get(ctx, req.NamespacedName, &mapUser); err != nil { + // If any error other than a "NotFound" API error, it's a problem. + statusErr, ok := err.(*apierrors.StatusError) + if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { + logf.Log.Error(err, "failure getting MapUser") + return ctrl.Result{}, err + } + + if err := awsauthSvc.RemoveMapUser(mapUserName); err != nil { + log.Error(err, "failure removing mapUser data in aws-auth configmap") + return ctrl.Result{}, nil + } + log.Info("removed mapUser data in aws-auth configmap") + return ctrl.Result{}, nil + } + + // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. + if err := awsauthSvc.UpsertMapUser(mapUser.Name, awsauth.MapUser{ + CrdName: mapUser.Name, + Username: mapUser.Spec.Username, + UserARN: mapUser.Spec.UserARN, + Groups: mapUser.Spec.Groups, + }); err != nil { + log.Error(err, "failure upserting MapUser") + return ctrl.Result{}, err + } + log.Info("upserted MapUser") + + return ctrl.Result{}, nil +} + +// SetupWithManager sets up the controller with the Manager. +func (r *MapUserReconciler) SetupWithManager(mgr ctrl.Manager) error { + return ctrl.NewControllerManagedBy(mgr). + For(&awsauthv1beta1.MapUser{}). + Named("mapuser"). + Complete(r) +} diff --git a/internal/controller/mapuser_controller_test.go b/internal/controller/mapuser_controller_test.go new file mode 100644 index 0000000..298af3c --- /dev/null +++ b/internal/controller/mapuser_controller_test.go @@ -0,0 +1,84 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controller + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" +) + +var _ = Describe("MapUser Controller", func() { + Context("When reconciling a resource", func() { + const resourceName = "test-resource" + + ctx := context.Background() + + typeNamespacedName := types.NamespacedName{ + Name: resourceName, + Namespace: "default", // TODO(user):Modify as needed + } + mapuser := &awsauthv1beta1.MapUser{} + + BeforeEach(func() { + By("creating the custom resource for the Kind MapUser") + err := k8sClient.Get(ctx, typeNamespacedName, mapuser) + if err != nil && errors.IsNotFound(err) { + resource := &awsauthv1beta1.MapUser{ + ObjectMeta: metav1.ObjectMeta{ + Name: resourceName, + Namespace: "default", + }, + // TODO(user): Specify other spec details if needed. + } + Expect(k8sClient.Create(ctx, resource)).To(Succeed()) + } + }) + + AfterEach(func() { + // TODO(user): Cleanup logic after each test, like removing the resource instance. + resource := &awsauthv1beta1.MapUser{} + err := k8sClient.Get(ctx, typeNamespacedName, resource) + Expect(err).NotTo(HaveOccurred()) + + By("Cleanup the specific resource instance MapUser") + Expect(k8sClient.Delete(ctx, resource)).To(Succeed()) + }) + It("should successfully reconcile the resource", func() { + By("Reconciling the created resource") + controllerReconciler := &MapUserReconciler{ + Client: k8sClient, + Scheme: k8sClient.Scheme(), + } + + _, err := controllerReconciler.Reconcile(ctx, reconcile.Request{ + NamespacedName: typeNamespacedName, + }) + Expect(err).NotTo(HaveOccurred()) + // TODO(user): Add more specific assertions depending on your controller's reconciliation logic. + // Example: If you expect a certain status condition after reconciliation, verify it here. + }) + }) +}) diff --git a/internal/controller/suite_test.go b/internal/controller/suite_test.go new file mode 100644 index 0000000..2ba8995 --- /dev/null +++ b/internal/controller/suite_test.go @@ -0,0 +1,116 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package controller + +import ( + "context" + "os" + "path/filepath" + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + // +kubebuilder:scaffold:imports +) + +// These tests use Ginkgo (BDD-style Go testing framework). Refer to +// http://onsi.github.io/ginkgo/ to learn more about Ginkgo. + +var ( + ctx context.Context + cancel context.CancelFunc + testEnv *envtest.Environment + cfg *rest.Config + k8sClient client.Client +) + +func TestControllers(t *testing.T) { + RegisterFailHandler(Fail) + + RunSpecs(t, "Controller Suite") +} + +var _ = BeforeSuite(func() { + logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) + + ctx, cancel = context.WithCancel(context.TODO()) + + var err error + err = awsauthv1beta1.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + + // +kubebuilder:scaffold:scheme + + By("bootstrapping test environment") + testEnv = &envtest.Environment{ + CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")}, + ErrorIfCRDPathMissing: true, + } + + // Retrieve the first found binary directory to allow running tests from IDEs + if getFirstFoundEnvTestBinaryDir() != "" { + testEnv.BinaryAssetsDirectory = getFirstFoundEnvTestBinaryDir() + } + + // cfg is defined in this file globally. + cfg, err = testEnv.Start() + Expect(err).NotTo(HaveOccurred()) + Expect(cfg).NotTo(BeNil()) + + k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) + Expect(err).NotTo(HaveOccurred()) + Expect(k8sClient).NotTo(BeNil()) +}) + +var _ = AfterSuite(func() { + By("tearing down the test environment") + cancel() + err := testEnv.Stop() + Expect(err).NotTo(HaveOccurred()) +}) + +// getFirstFoundEnvTestBinaryDir locates the first binary in the specified path. +// ENVTEST-based tests depend on specific binaries, usually located in paths set by +// controller-runtime. When running tests directly (e.g., via an IDE) without using +// Makefile targets, the 'BinaryAssetsDirectory' must be explicitly configured. +// +// This function streamlines the process by finding the required binaries, similar to +// setting the 'KUBEBUILDER_ASSETS' environment variable. To ensure the binaries are +// properly set up, run 'make setup-envtest' beforehand. +func getFirstFoundEnvTestBinaryDir() string { + basePath := filepath.Join("..", "..", "bin", "k8s") + entries, err := os.ReadDir(basePath) + if err != nil { + logf.Log.Error(err, "Failed to read directory", "path", basePath) + return "" + } + for _, entry := range entries { + if entry.IsDir() { + return filepath.Join(basePath, entry.Name()) + } + } + return "" +} diff --git a/kube/kube.go b/kube/kube.go new file mode 100644 index 0000000..effda3d --- /dev/null +++ b/kube/kube.go @@ -0,0 +1,51 @@ +package kube + +import ( + "os" + + "github.com/mitchellh/go-homedir" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" +) + +// GetClient returns a new configured Kubernetes client. +func GetClient() (kubernetes.Interface, error) { + var cfg *rest.Config + var err error + + // Set the kubeconfig file to use. + kubeconfig := os.Getenv("KUBECONFIG") + if kubeconfig == "" { + kubeconfig = "~/.kube/config" + } + if kubeconfig, err = homedir.Expand(kubeconfig); err != nil { + return nil, err + } + + // Set the kubernetes client config from the kubeconfig file. + if !fileExists(kubeconfig) { + cfg, err = rest.InClusterConfig() + } else { + cfg, err = clientcmd.BuildConfigFromFlags("", kubeconfig) + } + if err != nil { + return nil, err + } + + // Create new kubernetes client from its config. + client, err := kubernetes.NewForConfig(cfg) + if err != nil { + return nil, err + } + return client, nil +} + +// fileExists tests if a file exists at path. +func fileExists(path string) bool { + info, err := os.Stat(path) + if os.IsNotExist(err) { + return false + } + return !info.IsDir() +} diff --git a/test/e2e/e2e_suite_test.go b/test/e2e/e2e_suite_test.go new file mode 100644 index 0000000..cd64e75 --- /dev/null +++ b/test/e2e/e2e_suite_test.go @@ -0,0 +1,89 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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" + "os" + "os/exec" + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/redacid/aws-auth-controller/test/utils" +) + +var ( + // Optional Environment Variables: + // - CERT_MANAGER_INSTALL_SKIP=true: Skips CertManager installation during test setup. + // These variables are useful if CertManager is already installed, avoiding + // re-installation and conflicts. + skipCertManagerInstall = os.Getenv("CERT_MANAGER_INSTALL_SKIP") == "true" + // isCertManagerAlreadyInstalled will be set true when CertManager CRDs be found on the cluster + isCertManagerAlreadyInstalled = false + + // projectImage is the name of the image which will be build and loaded + // with the code source changes to be tested. + projectImage = "example.com/aws-auth-controller-prozorro:v0.0.1" +) + +// TestE2E runs the end-to-end (e2e) test suite for the project. These tests execute in an isolated, +// temporary environment to validate project changes with the purposed to be used in CI jobs. +// The default setup requires Kind, builds/loads the Manager Docker image locally, and installs +// CertManager. +func TestE2E(t *testing.T) { + RegisterFailHandler(Fail) + _, _ = fmt.Fprintf(GinkgoWriter, "Starting aws-auth-controller-prozorro integration test suite\n") + RunSpecs(t, "e2e suite") +} + +var _ = BeforeSuite(func() { + By("building the manager(Operator) image") + cmd := exec.Command("make", "docker-build", fmt.Sprintf("IMG=%s", projectImage)) + _, err := utils.Run(cmd) + ExpectWithOffset(1, err).NotTo(HaveOccurred(), "Failed to build the manager(Operator) image") + + // TODO(user): If you want to change the e2e test vendor from Kind, ensure the image is + // built and available before running the tests. Also, remove the following block. + By("loading the manager(Operator) image on Kind") + err = utils.LoadImageToKindClusterWithName(projectImage) + ExpectWithOffset(1, err).NotTo(HaveOccurred(), "Failed to load the manager(Operator) image into Kind") + + // The tests-e2e are intended to run on a temporary cluster that is created and destroyed for testing. + // To prevent errors when tests run in environments with CertManager already installed, + // we check for its presence before execution. + // Setup CertManager before the suite if not skipped and if not already installed + if !skipCertManagerInstall { + By("checking if cert manager is installed already") + isCertManagerAlreadyInstalled = utils.IsCertManagerCRDsInstalled() + if !isCertManagerAlreadyInstalled { + _, _ = fmt.Fprintf(GinkgoWriter, "Installing CertManager...\n") + Expect(utils.InstallCertManager()).To(Succeed(), "Failed to install CertManager") + } else { + _, _ = fmt.Fprintf(GinkgoWriter, "WARNING: CertManager is already installed. Skipping installation...\n") + } + } +}) + +var _ = AfterSuite(func() { + // Teardown CertManager after the suite if not skipped and if it was not already installed + if !skipCertManagerInstall && !isCertManagerAlreadyInstalled { + _, _ = fmt.Fprintf(GinkgoWriter, "Uninstalling CertManager...\n") + utils.UninstallCertManager() + } +}) diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go new file mode 100644 index 0000000..9ca6b81 --- /dev/null +++ b/test/e2e/e2e_test.go @@ -0,0 +1,329 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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 ( + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/redacid/aws-auth-controller/test/utils" +) + +// namespace where the project is deployed in +const namespace = "aws-auth-controller-prozorro-system" + +// serviceAccountName created for the project +const serviceAccountName = "aws-auth-controller-prozorro-controller-manager" + +// metricsServiceName is the name of the metrics service of the project +const metricsServiceName = "aws-auth-controller-prozorro-controller-manager-metrics-service" + +// metricsRoleBindingName is the name of the RBAC that will be created to allow get the metrics data +const metricsRoleBindingName = "aws-auth-controller-prozorro-metrics-binding" + +var _ = Describe("Manager", Ordered, func() { + var controllerPodName string + + // Before running the tests, set up the environment by creating the namespace, + // enforce the restricted security policy to the namespace, installing CRDs, + // and deploying the controller. + BeforeAll(func() { + By("creating manager namespace") + cmd := exec.Command("kubectl", "create", "ns", namespace) + _, err := utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to create namespace") + + By("labeling the namespace to enforce the restricted security policy") + cmd = exec.Command("kubectl", "label", "--overwrite", "ns", namespace, + "pod-security.kubernetes.io/enforce=restricted") + _, err = utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to label namespace with restricted policy") + + By("installing CRDs") + cmd = exec.Command("make", "install") + _, err = utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to install CRDs") + + By("deploying the controller-manager") + cmd = exec.Command("make", "deploy", fmt.Sprintf("IMG=%s", projectImage)) + _, err = utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to deploy the controller-manager") + }) + + // After all tests have been executed, clean up by undeploying the controller, uninstalling CRDs, + // and deleting the namespace. + AfterAll(func() { + By("cleaning up the curl pod for metrics") + cmd := exec.Command("kubectl", "delete", "pod", "curl-metrics", "-n", namespace) + _, _ = utils.Run(cmd) + + By("undeploying the controller-manager") + cmd = exec.Command("make", "undeploy") + _, _ = utils.Run(cmd) + + By("uninstalling CRDs") + cmd = exec.Command("make", "uninstall") + _, _ = utils.Run(cmd) + + By("removing manager namespace") + cmd = exec.Command("kubectl", "delete", "ns", namespace) + _, _ = utils.Run(cmd) + }) + + // After each test, check for failures and collect logs, events, + // and pod descriptions for debugging. + AfterEach(func() { + specReport := CurrentSpecReport() + if specReport.Failed() { + By("Fetching controller manager pod logs") + cmd := exec.Command("kubectl", "logs", controllerPodName, "-n", namespace) + controllerLogs, err := utils.Run(cmd) + if err == nil { + _, _ = fmt.Fprintf(GinkgoWriter, "Controller logs:\n %s", controllerLogs) + } else { + _, _ = fmt.Fprintf(GinkgoWriter, "Failed to get Controller logs: %s", err) + } + + By("Fetching Kubernetes events") + cmd = exec.Command("kubectl", "get", "events", "-n", namespace, "--sort-by=.lastTimestamp") + eventsOutput, err := utils.Run(cmd) + if err == nil { + _, _ = fmt.Fprintf(GinkgoWriter, "Kubernetes events:\n%s", eventsOutput) + } else { + _, _ = fmt.Fprintf(GinkgoWriter, "Failed to get Kubernetes events: %s", err) + } + + By("Fetching curl-metrics logs") + cmd = exec.Command("kubectl", "logs", "curl-metrics", "-n", namespace) + metricsOutput, err := utils.Run(cmd) + if err == nil { + _, _ = fmt.Fprintf(GinkgoWriter, "Metrics logs:\n %s", metricsOutput) + } else { + _, _ = fmt.Fprintf(GinkgoWriter, "Failed to get curl-metrics logs: %s", err) + } + + By("Fetching controller manager pod description") + cmd = exec.Command("kubectl", "describe", "pod", controllerPodName, "-n", namespace) + podDescription, err := utils.Run(cmd) + if err == nil { + fmt.Println("Pod description:\n", podDescription) + } else { + fmt.Println("Failed to describe controller pod") + } + } + }) + + SetDefaultEventuallyTimeout(2 * time.Minute) + SetDefaultEventuallyPollingInterval(time.Second) + + Context("Manager", func() { + It("should run successfully", func() { + By("validating that the controller-manager pod is running as expected") + verifyControllerUp := func(g Gomega) { + // Get the name of the controller-manager pod + cmd := exec.Command("kubectl", "get", + "pods", "-l", "control-plane=controller-manager", + "-o", "go-template={{ range .items }}"+ + "{{ if not .metadata.deletionTimestamp }}"+ + "{{ .metadata.name }}"+ + "{{ \"\\n\" }}{{ end }}{{ end }}", + "-n", namespace, + ) + + podOutput, err := utils.Run(cmd) + g.Expect(err).NotTo(HaveOccurred(), "Failed to retrieve controller-manager pod information") + podNames := utils.GetNonEmptyLines(podOutput) + g.Expect(podNames).To(HaveLen(1), "expected 1 controller pod running") + controllerPodName = podNames[0] + g.Expect(controllerPodName).To(ContainSubstring("controller-manager")) + + // Validate the pod's status + cmd = exec.Command("kubectl", "get", + "pods", controllerPodName, "-o", "jsonpath={.status.phase}", + "-n", namespace, + ) + output, err := utils.Run(cmd) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(output).To(Equal("Running"), "Incorrect controller-manager pod status") + } + Eventually(verifyControllerUp).Should(Succeed()) + }) + + It("should ensure the metrics endpoint is serving metrics", func() { + By("creating a ClusterRoleBinding for the service account to allow access to metrics") + cmd := exec.Command("kubectl", "create", "clusterrolebinding", metricsRoleBindingName, + "--clusterrole=aws-auth-controller-prozorro-metrics-reader", + fmt.Sprintf("--serviceaccount=%s:%s", namespace, serviceAccountName), + ) + _, err := utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to create ClusterRoleBinding") + + By("validating that the metrics service is available") + cmd = exec.Command("kubectl", "get", "service", metricsServiceName, "-n", namespace) + _, err = utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Metrics service should exist") + + By("getting the service account token") + token, err := serviceAccountToken() + Expect(err).NotTo(HaveOccurred()) + Expect(token).NotTo(BeEmpty()) + + By("waiting for the metrics endpoint to be ready") + verifyMetricsEndpointReady := func(g Gomega) { + cmd := exec.Command("kubectl", "get", "endpoints", metricsServiceName, "-n", namespace) + output, err := utils.Run(cmd) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(output).To(ContainSubstring("8443"), "Metrics endpoint is not ready") + } + Eventually(verifyMetricsEndpointReady).Should(Succeed()) + + By("verifying that the controller manager is serving the metrics server") + verifyMetricsServerStarted := func(g Gomega) { + cmd := exec.Command("kubectl", "logs", controllerPodName, "-n", namespace) + output, err := utils.Run(cmd) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(output).To(ContainSubstring("controller-runtime.metrics\tServing metrics server"), + "Metrics server not yet started") + } + Eventually(verifyMetricsServerStarted).Should(Succeed()) + + By("creating the curl-metrics pod to access the metrics endpoint") + cmd = exec.Command("kubectl", "run", "curl-metrics", "--restart=Never", + "--namespace", namespace, + "--image=curlimages/curl:latest", + "--overrides", + fmt.Sprintf(`{ + "spec": { + "containers": [{ + "name": "curl", + "image": "curlimages/curl:latest", + "command": ["/bin/sh", "-c"], + "args": ["curl -v -k -H 'Authorization: Bearer %s' https://%s.%s.svc.cluster.local:8443/metrics"], + "securityContext": { + "allowPrivilegeEscalation": false, + "capabilities": { + "drop": ["ALL"] + }, + "runAsNonRoot": true, + "runAsUser": 1000, + "seccompProfile": { + "type": "RuntimeDefault" + } + } + }], + "serviceAccount": "%s" + } + }`, token, metricsServiceName, namespace, serviceAccountName)) + _, err = utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to create curl-metrics pod") + + By("waiting for the curl-metrics pod to complete.") + verifyCurlUp := func(g Gomega) { + cmd := exec.Command("kubectl", "get", "pods", "curl-metrics", + "-o", "jsonpath={.status.phase}", + "-n", namespace) + output, err := utils.Run(cmd) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(output).To(Equal("Succeeded"), "curl pod in wrong status") + } + Eventually(verifyCurlUp, 5*time.Minute).Should(Succeed()) + + By("getting the metrics by checking curl-metrics logs") + metricsOutput := getMetricsOutput() + Expect(metricsOutput).To(ContainSubstring( + "controller_runtime_reconcile_total", + )) + }) + + // +kubebuilder:scaffold:e2e-webhooks-checks + + // TODO: Customize the e2e test suite with scenarios specific to your project. + // Consider applying sample/CR(s) and check their status and/or verifying + // the reconciliation by using the metrics, i.e.: + // metricsOutput := getMetricsOutput() + // Expect(metricsOutput).To(ContainSubstring( + // fmt.Sprintf(`controller_runtime_reconcile_total{controller="%s",result="success"} 1`, + // strings.ToLower(), + // )) + }) +}) + +// serviceAccountToken returns a token for the specified service account in the given namespace. +// It uses the Kubernetes TokenRequest API to generate a token by directly sending a request +// and parsing the resulting token from the API response. +func serviceAccountToken() (string, error) { + const tokenRequestRawString = `{ + "apiVersion": "authentication.k8s.io/v1", + "kind": "TokenRequest" + }` + + // Temporary file to store the token request + secretName := fmt.Sprintf("%s-token-request", serviceAccountName) + tokenRequestFile := filepath.Join("/tmp", secretName) + err := os.WriteFile(tokenRequestFile, []byte(tokenRequestRawString), os.FileMode(0o644)) + if err != nil { + return "", err + } + + var out string + verifyTokenCreation := func(g Gomega) { + // Execute kubectl command to create the token + cmd := exec.Command("kubectl", "create", "--raw", fmt.Sprintf( + "/api/v1/namespaces/%s/serviceaccounts/%s/token", + namespace, + serviceAccountName, + ), "-f", tokenRequestFile) + + output, err := cmd.CombinedOutput() + g.Expect(err).NotTo(HaveOccurred()) + + // Parse the JSON output to extract the token + var token tokenRequest + err = json.Unmarshal(output, &token) + g.Expect(err).NotTo(HaveOccurred()) + + out = token.Status.Token + } + Eventually(verifyTokenCreation).Should(Succeed()) + + return out, err +} + +// getMetricsOutput retrieves and returns the logs from the curl pod used to access the metrics endpoint. +func getMetricsOutput() string { + By("getting the curl-metrics logs") + cmd := exec.Command("kubectl", "logs", "curl-metrics", "-n", namespace) + metricsOutput, err := utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to retrieve logs from curl pod") + Expect(metricsOutput).To(ContainSubstring("< HTTP/1.1 200 OK")) + return metricsOutput +} + +// tokenRequest is a simplified representation of the Kubernetes TokenRequest API response, +// containing only the token field that we need to extract. +type tokenRequest struct { + Status struct { + Token string `json:"token"` + } `json:"status"` +} diff --git a/test/utils/utils.go b/test/utils/utils.go new file mode 100644 index 0000000..8416836 --- /dev/null +++ b/test/utils/utils.go @@ -0,0 +1,254 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package utils + +import ( + "bufio" + "bytes" + "fmt" + "os" + "os/exec" + "strings" + + . "github.com/onsi/ginkgo/v2" // nolint:revive,staticcheck +) + +const ( + prometheusOperatorVersion = "v0.77.1" + prometheusOperatorURL = "https://github.com/prometheus-operator/prometheus-operator/" + + "releases/download/%s/bundle.yaml" + + certmanagerVersion = "v1.16.3" + certmanagerURLTmpl = "https://github.com/cert-manager/cert-manager/releases/download/%s/cert-manager.yaml" +) + +func warnError(err error) { + _, _ = fmt.Fprintf(GinkgoWriter, "warning: %v\n", err) +} + +// Run executes the provided command within this context +func Run(cmd *exec.Cmd) (string, error) { + dir, _ := GetProjectDir() + cmd.Dir = dir + + if err := os.Chdir(cmd.Dir); err != nil { + _, _ = fmt.Fprintf(GinkgoWriter, "chdir dir: %q\n", err) + } + + cmd.Env = append(os.Environ(), "GO111MODULE=on") + command := strings.Join(cmd.Args, " ") + _, _ = fmt.Fprintf(GinkgoWriter, "running: %q\n", command) + output, err := cmd.CombinedOutput() + if err != nil { + return string(output), fmt.Errorf("%q failed with error %q: %w", command, string(output), err) + } + + return string(output), nil +} + +// InstallPrometheusOperator installs the prometheus Operator to be used to export the enabled metrics. +func InstallPrometheusOperator() error { + url := fmt.Sprintf(prometheusOperatorURL, prometheusOperatorVersion) + cmd := exec.Command("kubectl", "create", "-f", url) + _, err := Run(cmd) + return err +} + +// UninstallPrometheusOperator uninstalls the prometheus +func UninstallPrometheusOperator() { + url := fmt.Sprintf(prometheusOperatorURL, prometheusOperatorVersion) + cmd := exec.Command("kubectl", "delete", "-f", url) + if _, err := Run(cmd); err != nil { + warnError(err) + } +} + +// IsPrometheusCRDsInstalled checks if any Prometheus CRDs are installed +// by verifying the existence of key CRDs related to Prometheus. +func IsPrometheusCRDsInstalled() bool { + // List of common Prometheus CRDs + prometheusCRDs := []string{ + "prometheuses.monitoring.coreos.com", + "prometheusrules.monitoring.coreos.com", + "prometheusagents.monitoring.coreos.com", + } + + cmd := exec.Command("kubectl", "get", "crds", "-o", "custom-columns=NAME:.metadata.name") + output, err := Run(cmd) + if err != nil { + return false + } + crdList := GetNonEmptyLines(output) + for _, crd := range prometheusCRDs { + for _, line := range crdList { + if strings.Contains(line, crd) { + return true + } + } + } + + return false +} + +// UninstallCertManager uninstalls the cert manager +func UninstallCertManager() { + url := fmt.Sprintf(certmanagerURLTmpl, certmanagerVersion) + cmd := exec.Command("kubectl", "delete", "-f", url) + if _, err := Run(cmd); err != nil { + warnError(err) + } +} + +// InstallCertManager installs the cert manager bundle. +func InstallCertManager() error { + url := fmt.Sprintf(certmanagerURLTmpl, certmanagerVersion) + cmd := exec.Command("kubectl", "apply", "-f", url) + if _, err := Run(cmd); err != nil { + return err + } + // Wait for cert-manager-webhook to be ready, which can take time if cert-manager + // was re-installed after uninstalling on a cluster. + cmd = exec.Command("kubectl", "wait", "deployment.apps/cert-manager-webhook", + "--for", "condition=Available", + "--namespace", "cert-manager", + "--timeout", "5m", + ) + + _, err := Run(cmd) + return err +} + +// IsCertManagerCRDsInstalled checks if any Cert Manager CRDs are installed +// by verifying the existence of key CRDs related to Cert Manager. +func IsCertManagerCRDsInstalled() bool { + // List of common Cert Manager CRDs + certManagerCRDs := []string{ + "certificates.cert-manager.io", + "issuers.cert-manager.io", + "clusterissuers.cert-manager.io", + "certificaterequests.cert-manager.io", + "orders.acme.cert-manager.io", + "challenges.acme.cert-manager.io", + } + + // Execute the kubectl command to get all CRDs + cmd := exec.Command("kubectl", "get", "crds") + output, err := Run(cmd) + if err != nil { + return false + } + + // Check if any of the Cert Manager CRDs are present + crdList := GetNonEmptyLines(output) + for _, crd := range certManagerCRDs { + for _, line := range crdList { + if strings.Contains(line, crd) { + return true + } + } + } + + return false +} + +// LoadImageToKindClusterWithName loads a local docker image to the kind cluster +func LoadImageToKindClusterWithName(name string) error { + cluster := "kind" + if v, ok := os.LookupEnv("KIND_CLUSTER"); ok { + cluster = v + } + kindOptions := []string{"load", "docker-image", name, "--name", cluster} + cmd := exec.Command("kind", kindOptions...) + _, err := Run(cmd) + return err +} + +// GetNonEmptyLines converts given command output string into individual objects +// according to line breakers, and ignores the empty elements in it. +func GetNonEmptyLines(output string) []string { + var res []string + elements := strings.Split(output, "\n") + for _, element := range elements { + if element != "" { + res = append(res, element) + } + } + + return res +} + +// GetProjectDir will return the directory where the project is +func GetProjectDir() (string, error) { + wd, err := os.Getwd() + if err != nil { + return wd, fmt.Errorf("failed to get current working directory: %w", err) + } + wd = strings.ReplaceAll(wd, "/test/e2e", "") + return wd, nil +} + +// UncommentCode searches for target in the file and remove the comment prefix +// of the target content. The target content may span multiple lines. +func UncommentCode(filename, target, prefix string) error { + // false positive + // nolint:gosec + content, err := os.ReadFile(filename) + if err != nil { + return fmt.Errorf("failed to read file %q: %w", filename, err) + } + strContent := string(content) + + idx := strings.Index(strContent, target) + if idx < 0 { + return fmt.Errorf("unable to find the code %q to be uncomment", target) + } + + out := new(bytes.Buffer) + _, err = out.Write(content[:idx]) + if err != nil { + return fmt.Errorf("failed to write to output: %w", err) + } + + scanner := bufio.NewScanner(bytes.NewBufferString(target)) + if !scanner.Scan() { + return nil + } + for { + if _, err = out.WriteString(strings.TrimPrefix(scanner.Text(), prefix)); err != nil { + return fmt.Errorf("failed to write to output: %w", err) + } + // Avoid writing a newline in case the previous line was the last in target. + if !scanner.Scan() { + break + } + if _, err = out.WriteString("\n"); err != nil { + return fmt.Errorf("failed to write to output: %w", err) + } + } + + if _, err = out.Write(content[idx+len(target):]); err != nil { + return fmt.Errorf("failed to write to output: %w", err) + } + + // false positive + // nolint:gosec + if err = os.WriteFile(filename, out.Bytes(), 0644); err != nil { + return fmt.Errorf("failed to write file %q: %w", filename, err) + } + + return nil +} From 3ae842d2ef3543767661dff58f49daa863bbb351 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 8 Jul 2025 14:32:44 +0300 Subject: [PATCH 02/58] init --- Dockerfile | 2 ++ Makefile | 10 ++++---- config/manager/kustomization.yaml | 6 +++++ config/rbac/role.yaml | 25 ++++++++++++++++++++ config/samples/aws-auth_v1beta1_maprole.yaml | 7 +++++- config/samples/aws-auth_v1beta1_mapuser.yaml | 8 +++++-- internal/controller/mapaccount_controller.go | 2 ++ internal/controller/maprole_controller.go | 2 ++ internal/controller/mapuser_controller.go | 2 ++ 9 files changed, 57 insertions(+), 7 deletions(-) diff --git a/Dockerfile b/Dockerfile index cb1b130..864b10f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,6 +15,8 @@ RUN go mod download COPY cmd/main.go cmd/main.go COPY api/ api/ COPY internal/ internal/ +COPY awsauth/ awsauth/ +COPY kube/ kube/ # Build # the GOARCH has not a default value to allow the binary be built according to the host where the command diff --git a/Makefile b/Makefile index 7c60dc3..3e24cc6 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.8 +IMG ?= redacid/aws-auth-controller:0.0.9 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) @@ -36,13 +36,15 @@ all: build # More info on the awk command: # http://linuxcommand.org/lc3_adv_awk.php +.PHONY: preview +preview: mod-tidy generate manifests kustomize + $(KUSTOMIZE) build config/default + .PHONY: mod-tidy mod-tidy: go mod tidy -.PHONY: preview -preview: kustomize mod-tidy generate manifests - $(KUSTOMIZE) build config/default + .PHONY: help help: ## Display this help. diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 5c5f0b8..d0c21ec 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -1,2 +1,8 @@ resources: - manager.yaml +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +images: +- name: controller + newName: redacid/aws-auth-controller + newTag: 0.0.9 diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index f1c366c..fa311f0 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -4,6 +4,31 @@ kind: ClusterRole metadata: name: manager-role rules: +- apiGroups: + - "" + resources: + - configmaps + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - "" + resourceNames: + - aws-auth + resources: + - configmaps + verbs: + - delete + - get + - list + - patch + - update + - watch - apiGroups: - aws-auth.prozorro.sale resources: diff --git a/config/samples/aws-auth_v1beta1_maprole.yaml b/config/samples/aws-auth_v1beta1_maprole.yaml index a164f4b..7f872ba 100644 --- a/config/samples/aws-auth_v1beta1_maprole.yaml +++ b/config/samples/aws-auth_v1beta1_maprole.yaml @@ -6,4 +6,9 @@ metadata: app.kubernetes.io/managed-by: kustomize name: maprole-sample spec: - # TODO(user): Add fields here + rolearn: arn:aws:iam::130488995195:role/prod-self-managed-node-group + groups: + - sample:group1 + - sample:group2 + description: A sample maprole + username: system:node:{{EC2PrivateDNSName}} diff --git a/config/samples/aws-auth_v1beta1_mapuser.yaml b/config/samples/aws-auth_v1beta1_mapuser.yaml index 683df66..e97c071 100644 --- a/config/samples/aws-auth_v1beta1_mapuser.yaml +++ b/config/samples/aws-auth_v1beta1_mapuser.yaml @@ -4,6 +4,10 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: mapuser-sample + name: test2 spec: - # TODO(user): Add fields here + description: A test mapuser + username: test1.user@ios.in.ua + groups: + - test:group + userarn: arn:aws:iam::123456789012:user/sample-mapuser1-1 diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index ca8456c..e1308da 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -36,6 +36,8 @@ type MapAccountReconciler struct { // +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapaccounts,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapaccounts/status,verbs=get;update;patch // +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapaccounts/finalizers,verbs=update +// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;update;patch;delete,resourceNames=aws-auth // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index 669f783..ceecc0f 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -39,6 +39,8 @@ type MapRoleReconciler struct { // +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=maproles,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=maproles/status,verbs=get;update;patch // +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=maproles/finalizers,verbs=update +// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;update;patch;delete,resourceNames=aws-auth // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index dee6094..71183e6 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -39,6 +39,8 @@ type MapUserReconciler struct { // +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapusers,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapusers/status,verbs=get;update;patch // +kubebuilder:rbac:groups=aws-auth.prozorro.sale,resources=mapusers/finalizers,verbs=update +// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;update;patch;delete,resourceNames=aws-auth // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. From 1e25ba7d2d7c3474a03e187f71ebf058acb25ba8 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 8 Jul 2025 16:08:48 +0300 Subject: [PATCH 03/58] add mapuser webhook --- Makefile | 2 +- PROJECT | 4 + README.md | 1 + cmd/main.go | 8 + config/certmanager/certificate-metrics.yaml | 20 +++ config/certmanager/certificate-webhook.yaml | 20 +++ config/certmanager/issuer.yaml | 13 ++ config/certmanager/kustomization.yaml | 7 + config/certmanager/kustomizeconfig.yaml | 8 + config/default/kustomization.yaml | 10 +- config/default/manager_webhook_patch.yaml | 31 ++++ config/manager/kustomization.yaml | 2 +- .../network-policy/allow-webhook-traffic.yaml | 27 +++ config/network-policy/kustomization.yaml | 1 + config/webhook/kustomization.yaml | 6 + config/webhook/kustomizeconfig.yaml | 22 +++ config/webhook/manifests.yaml | 52 ++++++ config/webhook/service.yaml | 16 ++ internal/webhook/v1beta1/mapuser_webhook.go | 126 ++++++++++++++ .../webhook/v1beta1/mapuser_webhook_test.go | 87 ++++++++++ .../webhook/v1beta1/webhook_suite_test.go | 164 ++++++++++++++++++ test/e2e/e2e_test.go | 38 ++++ 22 files changed, 658 insertions(+), 7 deletions(-) create mode 100644 config/certmanager/certificate-metrics.yaml create mode 100644 config/certmanager/certificate-webhook.yaml create mode 100644 config/certmanager/issuer.yaml create mode 100644 config/certmanager/kustomization.yaml create mode 100644 config/certmanager/kustomizeconfig.yaml create mode 100644 config/default/manager_webhook_patch.yaml create mode 100644 config/network-policy/allow-webhook-traffic.yaml create mode 100644 config/webhook/kustomization.yaml create mode 100644 config/webhook/kustomizeconfig.yaml create mode 100644 config/webhook/manifests.yaml create mode 100644 config/webhook/service.yaml create mode 100644 internal/webhook/v1beta1/mapuser_webhook.go create mode 100644 internal/webhook/v1beta1/mapuser_webhook_test.go create mode 100644 internal/webhook/v1beta1/webhook_suite_test.go diff --git a/Makefile b/Makefile index 3e24cc6..5baaa10 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.9 +IMG ?= redacid/aws-auth-controller:0.0.10 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/PROJECT b/PROJECT index 5d0bea1..47feea7 100644 --- a/PROJECT +++ b/PROJECT @@ -27,6 +27,10 @@ resources: kind: MapUser path: github.com/redacid/aws-auth-controller/api/v1beta1 version: v1beta1 + webhooks: + defaulting: true + validation: true + webhookVersion: v1 - api: crdVersion: v1 namespaced: true diff --git a/README.md b/README.md index dbdff1c..65da924 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ kubebuilder create api --group aws-auth --version v1beta1 --kind MapRole --names kubebuilder create api --group aws-auth --version v1beta1 --kind MapUser --namespaced true --controller --resource kubebuilder create api --group aws-auth --version v1beta1 --kind MapAccount --namespaced true --controller --resource +kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapUser --defaulting --programmatic-validation git tag 0.0.1 -m "Test 0.0.1" git push origin 0.0.1 diff --git a/cmd/main.go b/cmd/main.go index e3c3a62..1a4243a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -39,6 +39,7 @@ import ( awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" "github.com/redacid/aws-auth-controller/internal/controller" + webhookv1beta1 "github.com/redacid/aws-auth-controller/internal/webhook/v1beta1" // +kubebuilder:scaffold:imports ) @@ -223,6 +224,13 @@ func main() { setupLog.Error(err, "unable to create controller", "controller", "MapAccount") os.Exit(1) } + // nolint:goconst + if os.Getenv("ENABLE_WEBHOOKS") != "false" { + if err := webhookv1beta1.SetupMapUserWebhookWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create webhook", "webhook", "MapUser") + os.Exit(1) + } + } // +kubebuilder:scaffold:builder if metricsCertWatcher != nil { diff --git a/config/certmanager/certificate-metrics.yaml b/config/certmanager/certificate-metrics.yaml new file mode 100644 index 0000000..707db07 --- /dev/null +++ b/config/certmanager/certificate-metrics.yaml @@ -0,0 +1,20 @@ +# The following manifests contain a self-signed issuer CR and a metrics certificate CR. +# More document can be found at https://docs.cert-manager.io +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: metrics-certs # this name should match the one appeared in kustomizeconfig.yaml + namespace: system +spec: + dnsNames: + # SERVICE_NAME and SERVICE_NAMESPACE will be substituted by kustomize + # replacements in the config/default/kustomization.yaml file. + - SERVICE_NAME.SERVICE_NAMESPACE.svc + - SERVICE_NAME.SERVICE_NAMESPACE.svc.cluster.local + issuerRef: + kind: Issuer + name: selfsigned-issuer + secretName: metrics-server-cert diff --git a/config/certmanager/certificate-webhook.yaml b/config/certmanager/certificate-webhook.yaml new file mode 100644 index 0000000..46823f0 --- /dev/null +++ b/config/certmanager/certificate-webhook.yaml @@ -0,0 +1,20 @@ +# The following manifests contain a self-signed issuer CR and a certificate CR. +# More document can be found at https://docs.cert-manager.io +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: serving-cert # this name should match the one appeared in kustomizeconfig.yaml + namespace: system +spec: + # SERVICE_NAME and SERVICE_NAMESPACE will be substituted by kustomize + # replacements in the config/default/kustomization.yaml file. + dnsNames: + - SERVICE_NAME.SERVICE_NAMESPACE.svc + - SERVICE_NAME.SERVICE_NAMESPACE.svc.cluster.local + issuerRef: + kind: Issuer + name: selfsigned-issuer + secretName: webhook-server-cert diff --git a/config/certmanager/issuer.yaml b/config/certmanager/issuer.yaml new file mode 100644 index 0000000..4b34167 --- /dev/null +++ b/config/certmanager/issuer.yaml @@ -0,0 +1,13 @@ +# The following manifest contains a self-signed issuer CR. +# More information can be found at https://docs.cert-manager.io +# WARNING: Targets CertManager v1.0. Check https://cert-manager.io/docs/installation/upgrading/ for breaking changes. +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: selfsigned-issuer + namespace: system +spec: + selfSigned: {} diff --git a/config/certmanager/kustomization.yaml b/config/certmanager/kustomization.yaml new file mode 100644 index 0000000..fcb7498 --- /dev/null +++ b/config/certmanager/kustomization.yaml @@ -0,0 +1,7 @@ +resources: +- issuer.yaml +- certificate-webhook.yaml +- certificate-metrics.yaml + +configurations: +- kustomizeconfig.yaml diff --git a/config/certmanager/kustomizeconfig.yaml b/config/certmanager/kustomizeconfig.yaml new file mode 100644 index 0000000..cf6f89e --- /dev/null +++ b/config/certmanager/kustomizeconfig.yaml @@ -0,0 +1,8 @@ +# This configuration is for teaching kustomize how to update name ref substitution +nameReference: +- kind: Issuer + group: cert-manager.io + fieldSpecs: + - kind: Certificate + group: cert-manager.io + path: spec/issuerRef/name diff --git a/config/default/kustomization.yaml b/config/default/kustomization.yaml index b4c5f5c..8be5c2b 100644 --- a/config/default/kustomization.yaml +++ b/config/default/kustomization.yaml @@ -20,9 +20,9 @@ resources: - ../manager # [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in # crd/kustomization.yaml -#- ../webhook +- ../webhook # [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'. 'WEBHOOK' components are required. -#- ../certmanager +- ../certmanager # [PROMETHEUS] To enable prometheus monitor, uncomment all sections with 'PROMETHEUS'. #- ../prometheus # [METRICS] Expose the controller manager metrics service. @@ -50,9 +50,9 @@ patches: # [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in # crd/kustomization.yaml -#- path: manager_webhook_patch.yaml -# target: -# kind: Deployment +- path: manager_webhook_patch.yaml + target: + kind: Deployment # [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER' prefix. # Uncomment the following replacements to add the cert-manager CA injection annotations diff --git a/config/default/manager_webhook_patch.yaml b/config/default/manager_webhook_patch.yaml new file mode 100644 index 0000000..963c8a4 --- /dev/null +++ b/config/default/manager_webhook_patch.yaml @@ -0,0 +1,31 @@ +# This patch ensures the webhook certificates are properly mounted in the manager container. +# It configures the necessary arguments, volumes, volume mounts, and container ports. + +# Add the --webhook-cert-path argument for configuring the webhook certificate path +- op: add + path: /spec/template/spec/containers/0/args/- + value: --webhook-cert-path=/tmp/k8s-webhook-server/serving-certs + +# Add the volumeMount for the webhook certificates +- op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + mountPath: /tmp/k8s-webhook-server/serving-certs + name: webhook-certs + readOnly: true + +# Add the port configuration for the webhook server +- op: add + path: /spec/template/spec/containers/0/ports/- + value: + containerPort: 9443 + name: webhook-server + protocol: TCP + +# Add the volume configuration for the webhook certificates +- op: add + path: /spec/template/spec/volumes/- + value: + name: webhook-certs + secret: + secretName: webhook-server-cert diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index d0c21ec..396d941 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller - newTag: 0.0.9 + newTag: 0.0.10 diff --git a/config/network-policy/allow-webhook-traffic.yaml b/config/network-policy/allow-webhook-traffic.yaml new file mode 100644 index 0000000..857488a --- /dev/null +++ b/config/network-policy/allow-webhook-traffic.yaml @@ -0,0 +1,27 @@ +# This NetworkPolicy allows ingress traffic to your webhook server running +# as part of the controller-manager from specific namespaces and pods. CR(s) which uses webhooks +# will only work when applied in namespaces labeled with 'webhook: enabled' +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: allow-webhook-traffic + namespace: system +spec: + podSelector: + matchLabels: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro + policyTypes: + - Ingress + ingress: + # This allows ingress traffic from any namespace with the label webhook: enabled + - from: + - namespaceSelector: + matchLabels: + webhook: enabled # Only from namespaces with this label + ports: + - port: 443 + protocol: TCP diff --git a/config/network-policy/kustomization.yaml b/config/network-policy/kustomization.yaml index ec0fb5e..0872bee 100644 --- a/config/network-policy/kustomization.yaml +++ b/config/network-policy/kustomization.yaml @@ -1,2 +1,3 @@ resources: +- allow-webhook-traffic.yaml - allow-metrics-traffic.yaml diff --git a/config/webhook/kustomization.yaml b/config/webhook/kustomization.yaml new file mode 100644 index 0000000..9cf2613 --- /dev/null +++ b/config/webhook/kustomization.yaml @@ -0,0 +1,6 @@ +resources: +- manifests.yaml +- service.yaml + +configurations: +- kustomizeconfig.yaml diff --git a/config/webhook/kustomizeconfig.yaml b/config/webhook/kustomizeconfig.yaml new file mode 100644 index 0000000..206316e --- /dev/null +++ b/config/webhook/kustomizeconfig.yaml @@ -0,0 +1,22 @@ +# the following config is for teaching kustomize where to look at when substituting nameReference. +# It requires kustomize v2.1.0 or newer to work properly. +nameReference: +- kind: Service + version: v1 + fieldSpecs: + - kind: MutatingWebhookConfiguration + group: admissionregistration.k8s.io + path: webhooks/clientConfig/service/name + - kind: ValidatingWebhookConfiguration + group: admissionregistration.k8s.io + path: webhooks/clientConfig/service/name + +namespace: +- kind: MutatingWebhookConfiguration + group: admissionregistration.k8s.io + path: webhooks/clientConfig/service/namespace + create: true +- kind: ValidatingWebhookConfiguration + group: admissionregistration.k8s.io + path: webhooks/clientConfig/service/namespace + create: true diff --git a/config/webhook/manifests.yaml b/config/webhook/manifests.yaml new file mode 100644 index 0000000..33a36d2 --- /dev/null +++ b/config/webhook/manifests.yaml @@ -0,0 +1,52 @@ +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingWebhookConfiguration +metadata: + name: mutating-webhook-configuration +webhooks: +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /mutate-aws-auth-prozorro-sale-v1beta1-mapuser + failurePolicy: Fail + name: mmapuser-v1beta1.kb.io + rules: + - apiGroups: + - aws-auth.prozorro.sale + apiVersions: + - v1beta1 + operations: + - CREATE + - UPDATE + resources: + - mapusers + sideEffects: None +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: validating-webhook-configuration +webhooks: +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /validate-aws-auth-prozorro-sale-v1beta1-mapuser + failurePolicy: Fail + name: vmapuser-v1beta1.kb.io + rules: + - apiGroups: + - aws-auth.prozorro.sale + apiVersions: + - v1beta1 + operations: + - CREATE + - UPDATE + resources: + - mapusers + sideEffects: None diff --git a/config/webhook/service.yaml b/config/webhook/service.yaml new file mode 100644 index 0000000..3637f14 --- /dev/null +++ b/config/webhook/service.yaml @@ -0,0 +1,16 @@ +apiVersion: v1 +kind: Service +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: webhook-service + namespace: system +spec: + ports: + - port: 443 + protocol: TCP + targetPort: 9443 + selector: + control-plane: controller-manager + app.kubernetes.io/name: aws-auth-controller-prozorro diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go new file mode 100644 index 0000000..5a4ae8e --- /dev/null +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -0,0 +1,126 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "context" + "fmt" + + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/webhook" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" +) + +// nolint:unused +// log is for logging in this package. +var mapuserlog = logf.Log.WithName("mapuser-resource") + +// SetupMapUserWebhookWithManager registers the webhook for MapUser in the manager. +func SetupMapUserWebhookWithManager(mgr ctrl.Manager) error { + return ctrl.NewWebhookManagedBy(mgr).For(&awsauthv1beta1.MapUser{}). + WithValidator(&MapUserCustomValidator{}). + WithDefaulter(&MapUserCustomDefaulter{}). + Complete() +} + +// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! + +// +kubebuilder:webhook:path=/mutate-aws-auth-prozorro-sale-v1beta1-mapuser,mutating=true,failurePolicy=fail,sideEffects=None,groups=aws-auth.prozorro.sale,resources=mapusers,verbs=create;update,versions=v1beta1,name=mmapuser-v1beta1.kb.io,admissionReviewVersions=v1 + +// MapUserCustomDefaulter struct is responsible for setting default values on the custom resource of the +// Kind MapUser when those are created or updated. +// +// NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods, +// as it is used only for temporary operations and does not need to be deeply copied. +type MapUserCustomDefaulter struct { + // TODO(user): Add more fields as needed for defaulting +} + +var _ webhook.CustomDefaulter = &MapUserCustomDefaulter{} + +// Default implements webhook.CustomDefaulter so a webhook will be registered for the Kind MapUser. +func (d *MapUserCustomDefaulter) Default(_ context.Context, obj runtime.Object) error { + mapuser, ok := obj.(*awsauthv1beta1.MapUser) + + if !ok { + return fmt.Errorf("expected an MapUser object but got %T", obj) + } + mapuserlog.Info("Defaulting for MapUser", "name", mapuser.GetName()) + + // TODO(user): fill in your defaulting logic. + + return nil +} + +// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. +// NOTE: The 'path' attribute must follow a specific pattern and should not be modified directly here. +// Modifying the path for an invalid path can cause API server errors; failing to locate the webhook. +// +kubebuilder:webhook:path=/validate-aws-auth-prozorro-sale-v1beta1-mapuser,mutating=false,failurePolicy=fail,sideEffects=None,groups=aws-auth.prozorro.sale,resources=mapusers,verbs=create;update,versions=v1beta1,name=vmapuser-v1beta1.kb.io,admissionReviewVersions=v1 + +// MapUserCustomValidator struct is responsible for validating the MapUser resource +// when it is created, updated, or deleted. +// +// NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods, +// as this struct is used only for temporary operations and does not need to be deeply copied. +type MapUserCustomValidator struct { + // TODO(user): Add more fields as needed for validation +} + +var _ webhook.CustomValidator = &MapUserCustomValidator{} + +// ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type MapUser. +func (v *MapUserCustomValidator) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) { + mapuser, ok := obj.(*awsauthv1beta1.MapUser) + if !ok { + return nil, fmt.Errorf("expected a MapUser object but got %T", obj) + } + mapuserlog.Info("Validation for MapUser upon creation", "name", mapuser.GetName()) + + // TODO(user): fill in your validation logic upon object creation. + + return nil, nil +} + +// ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type MapUser. +func (v *MapUserCustomValidator) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { + mapuser, ok := newObj.(*awsauthv1beta1.MapUser) + if !ok { + return nil, fmt.Errorf("expected a MapUser object for the newObj but got %T", newObj) + } + mapuserlog.Info("Validation for MapUser upon update", "name", mapuser.GetName()) + + // TODO(user): fill in your validation logic upon object update. + + return nil, nil +} + +// ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type MapUser. +func (v *MapUserCustomValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { + mapuser, ok := obj.(*awsauthv1beta1.MapUser) + if !ok { + return nil, fmt.Errorf("expected a MapUser object but got %T", obj) + } + mapuserlog.Info("Validation for MapUser upon deletion", "name", mapuser.GetName()) + + // TODO(user): fill in your validation logic upon object deletion. + + return nil, nil +} diff --git a/internal/webhook/v1beta1/mapuser_webhook_test.go b/internal/webhook/v1beta1/mapuser_webhook_test.go new file mode 100644 index 0000000..bba35b4 --- /dev/null +++ b/internal/webhook/v1beta1/mapuser_webhook_test.go @@ -0,0 +1,87 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + // TODO (user): Add any additional imports if needed +) + +var _ = Describe("MapUser Webhook", func() { + var ( + obj *awsauthv1beta1.MapUser + oldObj *awsauthv1beta1.MapUser + validator MapUserCustomValidator + defaulter MapUserCustomDefaulter + ) + + BeforeEach(func() { + obj = &awsauthv1beta1.MapUser{} + oldObj = &awsauthv1beta1.MapUser{} + validator = MapUserCustomValidator{} + Expect(validator).NotTo(BeNil(), "Expected validator to be initialized") + defaulter = MapUserCustomDefaulter{} + Expect(defaulter).NotTo(BeNil(), "Expected defaulter to be initialized") + Expect(oldObj).NotTo(BeNil(), "Expected oldObj to be initialized") + Expect(obj).NotTo(BeNil(), "Expected obj to be initialized") + // TODO (user): Add any setup logic common to all tests + }) + + AfterEach(func() { + // TODO (user): Add any teardown logic common to all tests + }) + + Context("When creating MapUser under Defaulting Webhook", func() { + // TODO (user): Add logic for defaulting webhooks + // Example: + // It("Should apply defaults when a required field is empty", func() { + // By("simulating a scenario where defaults should be applied") + // obj.SomeFieldWithDefault = "" + // By("calling the Default method to apply defaults") + // defaulter.Default(ctx, obj) + // By("checking that the default values are set") + // Expect(obj.SomeFieldWithDefault).To(Equal("default_value")) + // }) + }) + + Context("When creating or updating MapUser under Validating Webhook", func() { + // TODO (user): Add logic for validating webhooks + // Example: + // It("Should deny creation if a required field is missing", func() { + // By("simulating an invalid creation scenario") + // obj.SomeRequiredField = "" + // Expect(validator.ValidateCreate(ctx, obj)).Error().To(HaveOccurred()) + // }) + // + // It("Should admit creation if all required fields are present", func() { + // By("simulating an invalid creation scenario") + // obj.SomeRequiredField = "valid_value" + // Expect(validator.ValidateCreate(ctx, obj)).To(BeNil()) + // }) + // + // It("Should validate updates correctly", func() { + // By("simulating a valid update scenario") + // oldObj.SomeRequiredField = "updated_value" + // obj.SomeRequiredField = "updated_value" + // Expect(validator.ValidateUpdate(ctx, oldObj, obj)).To(BeNil()) + // }) + }) + +}) diff --git a/internal/webhook/v1beta1/webhook_suite_test.go b/internal/webhook/v1beta1/webhook_suite_test.go new file mode 100644 index 0000000..9253703 --- /dev/null +++ b/internal/webhook/v1beta1/webhook_suite_test.go @@ -0,0 +1,164 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "context" + "crypto/tls" + "fmt" + "net" + "os" + "path/filepath" + "testing" + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + "sigs.k8s.io/controller-runtime/pkg/webhook" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + // +kubebuilder:scaffold:imports +) + +// These tests use Ginkgo (BDD-style Go testing framework). Refer to +// http://onsi.github.io/ginkgo/ to learn more about Ginkgo. + +var ( + ctx context.Context + cancel context.CancelFunc + k8sClient client.Client + cfg *rest.Config + testEnv *envtest.Environment +) + +func TestAPIs(t *testing.T) { + RegisterFailHandler(Fail) + + RunSpecs(t, "Webhook Suite") +} + +var _ = BeforeSuite(func() { + logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) + + ctx, cancel = context.WithCancel(context.TODO()) + + var err error + err = awsauthv1beta1.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + + // +kubebuilder:scaffold:scheme + + By("bootstrapping test environment") + testEnv = &envtest.Environment{ + CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crd", "bases")}, + ErrorIfCRDPathMissing: false, + + WebhookInstallOptions: envtest.WebhookInstallOptions{ + Paths: []string{filepath.Join("..", "..", "..", "config", "webhook")}, + }, + } + + // Retrieve the first found binary directory to allow running tests from IDEs + if getFirstFoundEnvTestBinaryDir() != "" { + testEnv.BinaryAssetsDirectory = getFirstFoundEnvTestBinaryDir() + } + + // cfg is defined in this file globally. + cfg, err = testEnv.Start() + Expect(err).NotTo(HaveOccurred()) + Expect(cfg).NotTo(BeNil()) + + k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) + Expect(err).NotTo(HaveOccurred()) + Expect(k8sClient).NotTo(BeNil()) + + // start webhook server using Manager. + webhookInstallOptions := &testEnv.WebhookInstallOptions + mgr, err := ctrl.NewManager(cfg, ctrl.Options{ + Scheme: scheme.Scheme, + WebhookServer: webhook.NewServer(webhook.Options{ + Host: webhookInstallOptions.LocalServingHost, + Port: webhookInstallOptions.LocalServingPort, + CertDir: webhookInstallOptions.LocalServingCertDir, + }), + LeaderElection: false, + Metrics: metricsserver.Options{BindAddress: "0"}, + }) + Expect(err).NotTo(HaveOccurred()) + + err = SetupMapUserWebhookWithManager(mgr) + Expect(err).NotTo(HaveOccurred()) + + // +kubebuilder:scaffold:webhook + + go func() { + defer GinkgoRecover() + err = mgr.Start(ctx) + Expect(err).NotTo(HaveOccurred()) + }() + + // wait for the webhook server to get ready. + dialer := &net.Dialer{Timeout: time.Second} + addrPort := fmt.Sprintf("%s:%d", webhookInstallOptions.LocalServingHost, webhookInstallOptions.LocalServingPort) + Eventually(func() error { + conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true}) + if err != nil { + return err + } + + return conn.Close() + }).Should(Succeed()) +}) + +var _ = AfterSuite(func() { + By("tearing down the test environment") + cancel() + err := testEnv.Stop() + Expect(err).NotTo(HaveOccurred()) +}) + +// getFirstFoundEnvTestBinaryDir locates the first binary in the specified path. +// ENVTEST-based tests depend on specific binaries, usually located in paths set by +// controller-runtime. When running tests directly (e.g., via an IDE) without using +// Makefile targets, the 'BinaryAssetsDirectory' must be explicitly configured. +// +// This function streamlines the process by finding the required binaries, similar to +// setting the 'KUBEBUILDER_ASSETS' environment variable. To ensure the binaries are +// properly set up, run 'make setup-envtest' beforehand. +func getFirstFoundEnvTestBinaryDir() string { + basePath := filepath.Join("..", "..", "..", "bin", "k8s") + entries, err := os.ReadDir(basePath) + if err != nil { + logf.Log.Error(err, "Failed to read directory", "path", basePath) + return "" + } + for _, entry := range entries { + if entry.IsDir() { + return filepath.Join(basePath, entry.Name()) + } + } + return "" +} diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index 9ca6b81..8d88eda 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -256,6 +256,44 @@ var _ = Describe("Manager", Ordered, func() { )) }) + It("should provisioned cert-manager", func() { + By("validating that cert-manager has the certificate Secret") + verifyCertManager := func(g Gomega) { + cmd := exec.Command("kubectl", "get", "secrets", "webhook-server-cert", "-n", namespace) + _, err := utils.Run(cmd) + g.Expect(err).NotTo(HaveOccurred()) + } + Eventually(verifyCertManager).Should(Succeed()) + }) + + It("should have CA injection for mutating webhooks", func() { + By("checking CA injection for mutating webhooks") + verifyCAInjection := func(g Gomega) { + cmd := exec.Command("kubectl", "get", + "mutatingwebhookconfigurations.admissionregistration.k8s.io", + "aws-auth-controller-prozorro-mutating-webhook-configuration", + "-o", "go-template={{ range .webhooks }}{{ .clientConfig.caBundle }}{{ end }}") + mwhOutput, err := utils.Run(cmd) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(len(mwhOutput)).To(BeNumerically(">", 10)) + } + Eventually(verifyCAInjection).Should(Succeed()) + }) + + It("should have CA injection for validating webhooks", func() { + By("checking CA injection for validating webhooks") + verifyCAInjection := func(g Gomega) { + cmd := exec.Command("kubectl", "get", + "validatingwebhookconfigurations.admissionregistration.k8s.io", + "aws-auth-controller-prozorro-validating-webhook-configuration", + "-o", "go-template={{ range .webhooks }}{{ .clientConfig.caBundle }}{{ end }}") + vwhOutput, err := utils.Run(cmd) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(len(vwhOutput)).To(BeNumerically(">", 10)) + } + Eventually(verifyCAInjection).Should(Succeed()) + }) + // +kubebuilder:scaffold:e2e-webhooks-checks // TODO: Customize the e2e test suite with scenarios specific to your project. From 406d137d54d13da5ab337f101414ff790d29b319 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Wed, 9 Jul 2025 14:43:22 +0300 Subject: [PATCH 04/58] add verify.go --- Makefile | 7 +- README.md | 3 +- TODO.md | 1 + api/v1beta1/mapaccount_types.go | 16 +- api/v1beta1/maprole_types.go | 7 +- api/v1beta1/mapuser_types.go | 7 +- awsauth/data.go | 18 ++ awsauth/verify.go | 173 +++++++++++++++ cmd/main.go | 21 ++ .../aws-auth.prozorro.sale_mapaccounts.yaml | 12 +- .../aws-auth.prozorro.sale_maproles.yaml | 7 + .../aws-auth.prozorro.sale_mapusers.yaml | 7 + config/default/kustomization.yaml | 198 +++++++++--------- config/manager/kustomization.yaml | 2 +- config/manager/manager.yaml | 1 + config/samples/aws-auth_v1beta1_mapuser.yaml | 9 +- config/webhook/manifests.yaml | 1 + internal/webhook/v1beta1/mapuser_webhook.go | 81 ++++++- 18 files changed, 439 insertions(+), 132 deletions(-) create mode 100644 TODO.md create mode 100644 awsauth/verify.go diff --git a/Makefile b/Makefile index 5baaa10..899ace9 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.10 +IMG ?= redacid/aws-auth-controller:0.0.19 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) @@ -44,8 +44,6 @@ preview: mod-tidy generate manifests kustomize mod-tidy: go mod tidy - - .PHONY: help help: ## Display this help. @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) @@ -134,7 +132,8 @@ docker-push: ## Push docker image with the manager. # - have enabled BuildKit. More info: https://docs.docker.com/develop/develop-images/build_enhancements/ # - be able to push the image to your registry (i.e. if you do not set a valid value via IMG=> then the export will fail) # To adequately provide solutions that are compatible with multiple platforms, you should consider using this option. -PLATFORMS ?= linux/arm64,linux/amd64,linux/s390x,linux/ppc64le +#PLATFORMS ?= linux/arm64,linux/amd64,linux/s390x,linux/ppc64le +PLATFORMS ?= linux/amd64 .PHONY: docker-buildx docker-buildx: ## Build and push docker image for the manager for cross-platform support # copy existing Dockerfile and insert --platform=${BUILDPLATFORM} into Dockerfile.cross, and preserve the original Dockerfile diff --git a/README.md b/README.md index 65da924..cf9e9bf 100644 --- a/README.md +++ b/README.md @@ -14,4 +14,5 @@ cd ./charts helm upgrade -i --namespace kube-system aws-auth aws-auth-operator cd ./config/samples kubectl apply -f prozorro_v1alpha1_mapuser.yaml -n kube-system cd ./config/samples kubectl apply -f prozorro_v1alpha1_maprole.yaml -n kube-system -https://book.kubebuilder.io/reference/using-finalizers \ No newline at end of file +https://book.kubebuilder.io/reference/using-finalizers +https://book.kubebuilder.io/reference/markers/crd-validation \ No newline at end of file diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..ace45c4 --- /dev/null +++ b/TODO.md @@ -0,0 +1 @@ +Додати флаг CrdAllowedNamespace, для контролю створення ресурсів \ No newline at end of file diff --git a/api/v1beta1/mapaccount_types.go b/api/v1beta1/mapaccount_types.go index fe7239e..efa6925 100644 --- a/api/v1beta1/mapaccount_types.go +++ b/api/v1beta1/mapaccount_types.go @@ -24,13 +24,17 @@ import ( // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // MapAccountSpec defines the desired state of MapAccount. -type MapAccountSpec struct { - // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster - // Important: Run "make" to regenerate code after modifying this file +//type MapAccountSpec struct { +// // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster +// // Important: Run "make" to regenerate code after modifying this file +// +// // Foo is an example field of MapAccount. Edit mapaccount_types.go to remove/update +// //Foo string `json:"foo,omitempty"` +//} - // Foo is an example field of MapAccount. Edit mapaccount_types.go to remove/update - Foo string `json:"foo,omitempty"` -} +// +kubebuilder:validation:items:MaxLength:=12 +// +kubebuilder:validation:items:MinLength:=12 +type MapAccountSpec []string // MapAccountStatus defines the observed state of MapAccount. type MapAccountStatus struct { diff --git a/api/v1beta1/maprole_types.go b/api/v1beta1/maprole_types.go index 0a55a26..d0289c4 100644 --- a/api/v1beta1/maprole_types.go +++ b/api/v1beta1/maprole_types.go @@ -29,18 +29,21 @@ type MapRoleSpec struct { // Important: Run "make" to regenerate code after modifying this file // The Role ARN to associate with the MapRole + // +kubebuilder:validation:Pattern:=`^arn:aws:iam::[0-9]{12}:role/[a-zA-Z0-9+=,.@_/-]+$` RoleARN string `json:"rolearn"` // The Kubernetes groups to associate with the MapRole - // +kubebuilder:validation:Optional + // +kubebuilder:validation:MinItems:=1 Groups []string `json:"groups"` // A useful description of the MapRole // +kubebuilder:validation:Optional + // +kubebuilder:validation:MaxLength:=254 Description string `json:"description"` // The username for the MapUser - // +kubebuilder:validation:Optional + // +kubebuilder:validation:MaxLength:=254 + // +kubebuilder:validation:MinLength:=3 Username string `json:"username"` } diff --git a/api/v1beta1/mapuser_types.go b/api/v1beta1/mapuser_types.go index b99796b..8c308e7 100644 --- a/api/v1beta1/mapuser_types.go +++ b/api/v1beta1/mapuser_types.go @@ -29,18 +29,21 @@ type MapUserSpec struct { // Important: Run "make" to regenerate code after modifying this file // The User ARN to associate with the MapUser + // +kubebuilder:validation:Pattern:=`^arn:aws:iam::[0-9]{12}:user/[a-zA-Z0-9+=,.@_/-]+$` UserARN string `json:"userarn"` // The Kubernetes groups to associate with the MapUser - // +kubebuilder:validation:Optional + // +kubebuilder:validation:MinItems:=1 Groups []string `json:"groups"` // A useful description of the MapUser // +kubebuilder:validation:Optional + // +kubebuilder:validation:MaxLength:=254 Description string `json:"description"` // The username for the MapUser - // +kubebuilder:validation:Optional + // +kubebuilder:validation:MaxLength:=254 + // +kubebuilder:validation:MinLength:=3 Username string `json:"username"` } diff --git a/awsauth/data.go b/awsauth/data.go index 39e7ffb..64f66b0 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -37,6 +37,24 @@ const ( ConfigMapNamespace = "kube-system" ) +var UsernameMustBeEmail = false +var MustPresentAccountID = "" + +var CrdItemAllowedNamespace = "" + +type ControllerArgs struct { + UsernameMustBeEmail bool + MustPresentAccountID string + CrdItemAllowedNamespace string +} + +// SetUsernameMustBeEmail sets the global flag for username email validation +func DeclareVariables(controllerArgs ControllerArgs) { + UsernameMustBeEmail = controllerArgs.UsernameMustBeEmail + MustPresentAccountID = controllerArgs.MustPresentAccountID + MustPresentAccountID = controllerArgs.CrdItemAllowedNamespace +} + // ReadAuthMap reads the auth ConfigMap and returns AwsAuthData and the read ConfigMap. func ReadAuthMap(k kubernetes.Interface) (AwsAuthData, *kcorev1.ConfigMap, error) { var authData AwsAuthData diff --git a/awsauth/verify.go b/awsauth/verify.go new file mode 100644 index 0000000..3211e9b --- /dev/null +++ b/awsauth/verify.go @@ -0,0 +1,173 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package awsauth + +import ( + "fmt" + "regexp" + "strings" +) + +var AllowedAWSAccounts = []string{ + "123456789012", + "130488995195", +} + +// VerifyAWSAccount validates if the provided string is a valid AWS account ID (12 digits) +func VerifyAWSAccount(accountID string) error { + if accountID == "" { + return fmt.Errorf("AWS account ID cannot be empty") + } + + if !regexp.MustCompile(`^\d{12}$`).MatchString(accountID) { + return fmt.Errorf("invalid AWS account ID format: %s. Must be exactly 12 digits", accountID) + } + + return nil +} + +// VerifyAWSAccountID verifies if the AWS account ID is allowed +func VerifyAWSAccountIDArn(arn string) error { + // Extract account ID from ARN + arnParts := strings.Split(arn, ":") + if len(arnParts) < 5 { + return fmt.Errorf("invalid ARN format: cannot extract account ID from %s", arn) + } + + accountID := arnParts[4] + + // Validate account ID format + if err := VerifyAWSAccount(accountID); err != nil { + return err + } + + // Check if account ID is in allowed list + for _, allowed := range AllowedAWSAccounts { + if accountID == allowed { + return nil + } + } + + return fmt.Errorf("AWS account ID %s is not allowed. Allowed accounts: %s", + accountID, strings.Join(AllowedAWSAccounts, ", ")) +} + +// VerifyUserARN validates AWS user ARN format +func VerifyUserARN(arn string) error { + if arn == "" { + return fmt.Errorf("userARN cannot be empty") + } + + // Regular expression to verify ARN format + arnPattern := `^arn:aws:iam::\d{12}:user/[a-zA-Z0-9+=,.@\-_/]+$` + matched, _ := regexp.MatchString(arnPattern, arn) + if !matched { + return fmt.Errorf("invalid userARN format: %s. Expected format: arn:aws:iam:::user/", arn) + } + + // Verify AWS account ID + if err := VerifyAWSAccountIDArn(arn); err != nil { + return err + } + + return nil +} + +func VerifyRoleARN(arn string) error { + if arn == "" { + return fmt.Errorf("roleARN cannot be empty") + } + + // Regular expression to verify ARN format + arnPattern := `^arn:aws:iam::\d{12}:role/[a-zA-Z0-9+=,.@\-_/]+$` + matched, _ := regexp.MatchString(arnPattern, arn) + if !matched { + return fmt.Errorf("invalid roleARN format: %s. Expected format: arn:aws:iam:::role/", arn) + } + + return nil +} + +// VerifyUsername validates username format +func VerifyUsername(username string, enforceEmail bool) error { + if username == "" { + return fmt.Errorf("username cannot be empty") + } + + // Check length + if len(username) < 3 || len(username) > 254 { + return fmt.Errorf("username length must be between 3 and 254 characters") + } + + // Validate email format if enforceEmail is true or if username contains @ + if enforceEmail || strings.Contains(username, "@") { + emailPattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` + matched, _ := regexp.MatchString(emailPattern, username) + if !matched { + return fmt.Errorf("invalid email format in username: %s", username) + } + } else { + // Validate regular username format + usernamePattern := `^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$` + matched, _ := regexp.MatchString(usernamePattern, username) + if !matched { + return fmt.Errorf("username can only contain letters, numbers, dots, hyphens, and underscores: %s", username) + } + } + + return nil +} + +// VerifyGroups validates group names +func VerifyGroups(groups []string) error { + if len(groups) == 0 { + return fmt.Errorf("at least one group must be specified") + } + + // Regular expression for DNS label format validation + //groupPattern := `^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + + for _, group := range groups { + if group == "" { + return fmt.Errorf("group name cannot be empty") + } + + if len(group) > 253 { + return fmt.Errorf("group name cannot be longer than 253 characters: %s", group) + } + + //matched, _ := regexp.MatchString(groupPattern, group) + //if !matched { + // return fmt.Errorf("invalid group name format: %s. Group must be DNS-compatible", group) + //} + } + + return nil +} + +// SetAllowedAWSAccounts updates the list of allowed AWS account IDs +func SetAllowedAWSAccounts(accounts []string) error { + // Validate format of all accounts + for _, acc := range accounts { + // Validate account ID format + if err := VerifyAWSAccount(acc); err != nil { + return err + } + } + + AllowedAWSAccounts = accounts + return nil +} diff --git a/cmd/main.go b/cmd/main.go index 1a4243a..0d6a81d 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -19,6 +19,7 @@ package main import ( "crypto/tls" "flag" + "github.com/redacid/aws-auth-controller/awsauth" "os" "path/filepath" @@ -64,7 +65,15 @@ func main() { var probeAddr string var secureMetrics bool var enableHTTP2 bool + var userNameMustBeEmail bool + var mustPresentAccountID string + var crdItemAllowedNamespace string var tlsOpts []func(*tls.Config) + flag.BoolVar(&userNameMustBeEmail, "username-must-be-email", false, + "Enables checking of username, should it be an email address, default false. Use --username-must-be-email=true to enable this feature.") + flag.StringVar(&mustPresentAccountID, "must-present-account-id", "", "This account must be allways present in ConfigMap, must-present-account-id=123456789012") + flag.StringVar(&crdItemAllowedNamespace, "crd-item-allowed-namespace", "", "Namespace where allowed creation of Resources crd-item-allowed-namespace=kube-system,"+ + "If is set, only in this namespace allowed creation of Resources, if not set, all namespaces allowed creation of Resources.") flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") @@ -90,6 +99,18 @@ func main() { ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + if mustPresentAccountID != "" { + awsauth.VerifyAWSAccount(mustPresentAccountID) + } + + VariablesDeclare := awsauth.ControllerArgs{ + UsernameMustBeEmail: userNameMustBeEmail, + MustPresentAccountID: mustPresentAccountID, + CrdItemAllowedNamespace: crdItemAllowedNamespace, + } + + awsauth.DeclareVariables(VariablesDeclare) + // if the enable-http2 flag is false (the default), http/2 should be disabled // due to its vulnerabilities. More specifically, disabling http/2 will // prevent from being vulnerable to the HTTP/2 Stream Cancellation and diff --git a/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml b/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml index 61e5ada..c65d887 100644 --- a/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml +++ b/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml @@ -37,13 +37,11 @@ spec: metadata: type: object spec: - description: MapAccountSpec defines the desired state of MapAccount. - properties: - foo: - description: Foo is an example field of MapAccount. Edit mapaccount_types.go - to remove/update - type: string - type: object + items: + maxLength: 12 + minLength: 12 + type: string + type: array status: description: MapAccountStatus defines the observed state of MapAccount. type: object diff --git a/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml b/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml index 46ffc55..1d03de5 100644 --- a/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml +++ b/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml @@ -41,20 +41,27 @@ spec: properties: description: description: A useful description of the MapRole + maxLength: 254 type: string groups: description: The Kubernetes groups to associate with the MapRole items: type: string + minItems: 1 type: array rolearn: description: The Role ARN to associate with the MapRole + pattern: ^arn:aws:iam::[0-9]{12}:role/[a-zA-Z0-9+=,.@_/-]+$ type: string username: description: The username for the MapUser + maxLength: 254 + minLength: 3 type: string required: + - groups - rolearn + - username type: object status: description: MapRoleStatus defines the observed state of MapRole. diff --git a/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml b/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml index 5e35325..1e926f9 100644 --- a/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml +++ b/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml @@ -41,20 +41,27 @@ spec: properties: description: description: A useful description of the MapUser + maxLength: 254 type: string groups: description: The Kubernetes groups to associate with the MapUser items: type: string + minItems: 1 type: array userarn: description: The User ARN to associate with the MapUser + pattern: ^arn:aws:iam::[0-9]{12}:user/[a-zA-Z0-9+=,.@_/-]+$ type: string username: description: The username for the MapUser + maxLength: 254 + minLength: 3 type: string required: + - groups - userarn + - username type: object status: description: MapUserStatus defines the observed state of MapUser. diff --git a/config/default/kustomization.yaml b/config/default/kustomization.yaml index 8be5c2b..c65f55a 100644 --- a/config/default/kustomization.yaml +++ b/config/default/kustomization.yaml @@ -56,7 +56,7 @@ patches: # [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER' prefix. # Uncomment the following replacements to add the cert-manager CA injection annotations -#replacements: +replacements: # - source: # Uncomment the following block to enable certificates for metrics # kind: Service # version: v1 @@ -117,104 +117,104 @@ patches: # index: 1 # create: true # -# - source: # Uncomment the following block if you have any webhook -# kind: Service -# version: v1 -# name: webhook-service -# fieldPath: .metadata.name # Name of the service -# targets: -# - select: -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert -# fieldPaths: -# - .spec.dnsNames.0 -# - .spec.dnsNames.1 -# options: -# delimiter: '.' -# index: 0 -# create: true -# - source: -# kind: Service -# version: v1 -# name: webhook-service -# fieldPath: .metadata.namespace # Namespace of the service -# targets: -# - select: -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert -# fieldPaths: -# - .spec.dnsNames.0 -# - .spec.dnsNames.1 -# options: -# delimiter: '.' -# index: 1 -# create: true -# -# - source: # Uncomment the following block if you have a ValidatingWebhook (--programmatic-validation) -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert # This name should match the one in certificate.yaml -# fieldPath: .metadata.namespace # Namespace of the certificate CR -# targets: -# - select: -# kind: ValidatingWebhookConfiguration -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 0 -# create: true -# - source: -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert -# fieldPath: .metadata.name -# targets: -# - select: -# kind: ValidatingWebhookConfiguration -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 1 -# create: true -# -# - source: # Uncomment the following block if you have a DefaultingWebhook (--defaulting ) -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert -# fieldPath: .metadata.namespace # Namespace of the certificate CR -# targets: -# - select: -# kind: MutatingWebhookConfiguration -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 0 -# create: true -# - source: -# kind: Certificate -# group: cert-manager.io -# version: v1 -# name: serving-cert -# fieldPath: .metadata.name -# targets: -# - select: -# kind: MutatingWebhookConfiguration -# fieldPaths: -# - .metadata.annotations.[cert-manager.io/inject-ca-from] -# options: -# delimiter: '/' -# index: 1 -# create: true + - source: # Uncomment the following block if you have any webhook + kind: Service + version: v1 + name: webhook-service + fieldPath: .metadata.name # Name of the service + targets: + - select: + kind: Certificate + group: cert-manager.io + version: v1 + name: serving-cert + fieldPaths: + - .spec.dnsNames.0 + - .spec.dnsNames.1 + options: + delimiter: '.' + index: 0 + create: true + - source: + kind: Service + version: v1 + name: webhook-service + fieldPath: .metadata.namespace # Namespace of the service + targets: + - select: + kind: Certificate + group: cert-manager.io + version: v1 + name: serving-cert + fieldPaths: + - .spec.dnsNames.0 + - .spec.dnsNames.1 + options: + delimiter: '.' + index: 1 + create: true + + - source: # Uncomment the following block if you have a ValidatingWebhook (--programmatic-validation) + kind: Certificate + group: cert-manager.io + version: v1 + name: serving-cert # This name should match the one in certificate.yaml + fieldPath: .metadata.namespace # Namespace of the certificate CR + targets: + - select: + kind: ValidatingWebhookConfiguration + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 0 + create: true + - source: + kind: Certificate + group: cert-manager.io + version: v1 + name: serving-cert + fieldPath: .metadata.name + targets: + - select: + kind: ValidatingWebhookConfiguration + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 1 + create: true + + - source: # Uncomment the following block if you have a DefaultingWebhook (--defaulting ) + kind: Certificate + group: cert-manager.io + version: v1 + name: serving-cert + fieldPath: .metadata.namespace # Namespace of the certificate CR + targets: + - select: + kind: MutatingWebhookConfiguration + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 0 + create: true + - source: + kind: Certificate + group: cert-manager.io + version: v1 + name: serving-cert + fieldPath: .metadata.name + targets: + - select: + kind: MutatingWebhookConfiguration + fieldPaths: + - .metadata.annotations.[cert-manager.io/inject-ca-from] + options: + delimiter: '/' + index: 1 + create: true # # - source: # Uncomment the following block if you have a ConversionWebhook (--conversion) # kind: Certificate diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 396d941..de50760 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller - newTag: 0.0.10 + newTag: 0.0.19 diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index 2b9d88c..ecc4c4f 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -61,6 +61,7 @@ spec: - command: - /manager args: + - --username-must-be-email - --leader-elect - --health-probe-bind-address=:8081 image: controller:latest diff --git a/config/samples/aws-auth_v1beta1_mapuser.yaml b/config/samples/aws-auth_v1beta1_mapuser.yaml index e97c071..bbcb383 100644 --- a/config/samples/aws-auth_v1beta1_mapuser.yaml +++ b/config/samples/aws-auth_v1beta1_mapuser.yaml @@ -4,10 +4,11 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: test2 + name: test9 spec: description: A test mapuser - username: test1.user@ios.in.ua + username: test2.userios.in.ua groups: - - test:group - userarn: arn:aws:iam::123456789012:user/sample-mapuser1-1 + - system:masters + - admins + userarn: arn:aws:iam::123456789012:user/sample-mapuser3 diff --git a/config/webhook/manifests.yaml b/config/webhook/manifests.yaml index 33a36d2..b45115f 100644 --- a/config/webhook/manifests.yaml +++ b/config/webhook/manifests.yaml @@ -47,6 +47,7 @@ webhooks: operations: - CREATE - UPDATE + - DELETE resources: - mapusers sideEffects: None diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index 5a4ae8e..4495264 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -19,7 +19,7 @@ package v1beta1 import ( "context" "fmt" - + "github.com/redacid/aws-auth-controller/awsauth" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" @@ -27,6 +27,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + _ "github.com/redacid/aws-auth-controller/awsauth" + _ "github.com/redacid/aws-auth-controller/kube" ) // nolint:unused @@ -73,7 +75,7 @@ func (d *MapUserCustomDefaulter) Default(_ context.Context, obj runtime.Object) // TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. // NOTE: The 'path' attribute must follow a specific pattern and should not be modified directly here. // Modifying the path for an invalid path can cause API server errors; failing to locate the webhook. -// +kubebuilder:webhook:path=/validate-aws-auth-prozorro-sale-v1beta1-mapuser,mutating=false,failurePolicy=fail,sideEffects=None,groups=aws-auth.prozorro.sale,resources=mapusers,verbs=create;update,versions=v1beta1,name=vmapuser-v1beta1.kb.io,admissionReviewVersions=v1 +// +kubebuilder:webhook:path=/validate-aws-auth-prozorro-sale-v1beta1-mapuser,mutating=false,failurePolicy=fail,sideEffects=None,groups=aws-auth.prozorro.sale,resources=mapusers,verbs=create;update;delete,versions=v1beta1,name=vmapuser-v1beta1.kb.io,admissionReviewVersions=v1 // MapUserCustomValidator struct is responsible for validating the MapUser resource // when it is created, updated, or deleted. @@ -92,7 +94,30 @@ func (v *MapUserCustomValidator) ValidateCreate(_ context.Context, obj runtime.O if !ok { return nil, fmt.Errorf("expected a MapUser object but got %T", obj) } - mapuserlog.Info("Validation for MapUser upon creation", "name", mapuser.GetName()) + mapuserlog.Info("Validation for MapUser upon creation", + "name", mapuser.GetName(), + "UserARN", mapuser.Spec.UserARN, + "Username", mapuser.Spec.Username, + "Description", mapuser.Spec.Description, + "Groups", mapuser.Spec.Groups, + "Namespace", mapuser.GetNamespace(), + ) + if mapuser.GetNamespace() != "kube-system" { + mapuserlog.Error(nil, "Namespace "+mapuser.GetNamespace()+" is NOT allowed for creation MapUser") + return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapUser", mapuser.GetNamespace()) + } + // Validate fields + //if err := awsauth.VerifyUserARN(mapuser.Spec.UserARN); err != nil { + // return nil, err + //} + + //if err := awsauth.VerifyUsername(mapuser.Spec.Username, awsauth.UsernameMustBeEmail); err != nil { + // return nil, err + //} + + //if err := awsauth.VerifyGroups(mapuser.Spec.Groups); err != nil { + // return nil, err + //} // TODO(user): fill in your validation logic upon object creation. @@ -102,10 +127,44 @@ func (v *MapUserCustomValidator) ValidateCreate(_ context.Context, obj runtime.O // ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type MapUser. func (v *MapUserCustomValidator) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { mapuser, ok := newObj.(*awsauthv1beta1.MapUser) + oldmapuser, ok := oldObj.(*awsauthv1beta1.MapUser) + if !ok { return nil, fmt.Errorf("expected a MapUser object for the newObj but got %T", newObj) } - mapuserlog.Info("Validation for MapUser upon update", "name", mapuser.GetName()) + mapuserlog.Info("Validation for MapUser upon update OLD:", + "name", oldmapuser.GetName(), + "UserARN", oldmapuser.Spec.UserARN, + "Username", oldmapuser.Spec.Username, + "Description", oldmapuser.Spec.Description, + "Groups", oldmapuser.Spec.Groups, + "Namespace", mapuser.GetNamespace(), + ) + mapuserlog.Info("Validation for MapUser upon update NEW:", + "name", mapuser.GetName(), + "UserARN", mapuser.Spec.UserARN, + "Username", mapuser.Spec.Username, + "Description", mapuser.Spec.Description, + "Groups", mapuser.Spec.Groups, + "Namespace", mapuser.GetNamespace(), + ) + + if mapuser.GetNamespace() != "kube-system" { + mapuserlog.Error(nil, "Namespace "+mapuser.GetNamespace()+" is NOT allowed for creation MapUser") + return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapUser", mapuser.GetNamespace()) + } + // Validate fields + if err := awsauth.VerifyUserARN(mapuser.Spec.UserARN); err != nil { + return nil, err + } + + if err := awsauth.VerifyUsername(mapuser.Spec.Username, awsauth.UsernameMustBeEmail); err != nil { + return nil, err + } + + if err := awsauth.VerifyGroups(mapuser.Spec.Groups); err != nil { + return nil, err + } // TODO(user): fill in your validation logic upon object update. @@ -118,8 +177,18 @@ func (v *MapUserCustomValidator) ValidateDelete(ctx context.Context, obj runtime if !ok { return nil, fmt.Errorf("expected a MapUser object but got %T", obj) } - mapuserlog.Info("Validation for MapUser upon deletion", "name", mapuser.GetName()) - + mapuserlog.Info("Validation for MapUser upon deletion", + "name", mapuser.GetName(), + "UserARN", mapuser.Spec.UserARN, + "Username", mapuser.Spec.Username, + "Description", mapuser.Spec.Description, + "Groups", mapuser.Spec.Groups, + ) + + mapuserlog.Info("Validation for MapUser upon deletion", + "name", mapuser.GetName(), + "UserARN", mapuser.Spec.UserARN, + ) // TODO(user): fill in your validation logic upon object deletion. return nil, nil From 644dfc7a1ac189751077a93e8423babe627deda4 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Wed, 9 Jul 2025 16:01:42 +0300 Subject: [PATCH 05/58] add webhooks --- Makefile | 2 +- PROJECT | 8 + README.md | 2 + api/v1beta1/maprole_types.go | 2 + api/v1beta1/mapuser_types.go | 2 + api/v1beta1/zz_generated.deepcopy.go | 310 ++++++++++++++++++ awsauth/data.go | 13 +- cmd/main.go | 21 +- .../aws-auth.prozorro.sale_maproles.yaml | 2 + .../aws-auth.prozorro.sale_mapusers.yaml | 2 + config/manager/kustomization.yaml | 2 +- .../samples/aws-auth_v1beta1_mapaccount.yaml | 1 + config/webhook/manifests.yaml | 82 +++++ .../webhook/v1beta1/mapaccount_webhook.go | 126 +++++++ .../v1beta1/mapaccount_webhook_test.go | 87 +++++ internal/webhook/v1beta1/maprole_webhook.go | 126 +++++++ .../webhook/v1beta1/maprole_webhook_test.go | 87 +++++ internal/webhook/v1beta1/mapuser_webhook.go | 9 +- .../webhook/v1beta1/webhook_suite_test.go | 6 + 19 files changed, 879 insertions(+), 11 deletions(-) create mode 100644 api/v1beta1/zz_generated.deepcopy.go create mode 100644 internal/webhook/v1beta1/mapaccount_webhook.go create mode 100644 internal/webhook/v1beta1/mapaccount_webhook_test.go create mode 100644 internal/webhook/v1beta1/maprole_webhook.go create mode 100644 internal/webhook/v1beta1/maprole_webhook_test.go diff --git a/Makefile b/Makefile index 899ace9..98079ae 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.19 +IMG ?= redacid/aws-auth-controller:0.0.22 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/PROJECT b/PROJECT index 47feea7..f4be704 100644 --- a/PROJECT +++ b/PROJECT @@ -18,6 +18,10 @@ resources: kind: MapRole path: github.com/redacid/aws-auth-controller/api/v1beta1 version: v1beta1 + webhooks: + defaulting: true + validation: true + webhookVersion: v1 - api: crdVersion: v1 namespaced: true @@ -40,4 +44,8 @@ resources: kind: MapAccount path: github.com/redacid/aws-auth-controller/api/v1beta1 version: v1beta1 + webhooks: + defaulting: true + validation: true + webhookVersion: v1 version: "3" diff --git a/README.md b/README.md index cf9e9bf..3f3727b 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ kubebuilder create api --group aws-auth --version v1beta1 --kind MapUser --names kubebuilder create api --group aws-auth --version v1beta1 --kind MapAccount --namespaced true --controller --resource kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapUser --defaulting --programmatic-validation +kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapRole --defaulting --programmatic-validation +kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapAccount --defaulting --programmatic-validation git tag 0.0.1 -m "Test 0.0.1" git push origin 0.0.1 diff --git a/api/v1beta1/maprole_types.go b/api/v1beta1/maprole_types.go index d0289c4..17eebcd 100644 --- a/api/v1beta1/maprole_types.go +++ b/api/v1beta1/maprole_types.go @@ -34,6 +34,8 @@ type MapRoleSpec struct { // The Kubernetes groups to associate with the MapRole // +kubebuilder:validation:MinItems:=1 + // +kubebuilder:validation:items:MinLength:=3 + // +kubebuilder:validation:items:MaxLength:=254 Groups []string `json:"groups"` // A useful description of the MapRole diff --git a/api/v1beta1/mapuser_types.go b/api/v1beta1/mapuser_types.go index 8c308e7..0e00b24 100644 --- a/api/v1beta1/mapuser_types.go +++ b/api/v1beta1/mapuser_types.go @@ -34,6 +34,8 @@ type MapUserSpec struct { // The Kubernetes groups to associate with the MapUser // +kubebuilder:validation:MinItems:=1 + // +kubebuilder:validation:items:MinLength:=3 + // +kubebuilder:validation:items:MaxLength:=254 Groups []string `json:"groups"` // A useful description of the MapUser diff --git a/api/v1beta1/zz_generated.deepcopy.go b/api/v1beta1/zz_generated.deepcopy.go new file mode 100644 index 0000000..55bc2d6 --- /dev/null +++ b/api/v1beta1/zz_generated.deepcopy.go @@ -0,0 +1,310 @@ +//go:build !ignore_autogenerated + +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 v1beta1 + +import ( + 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 *MapAccount) DeepCopyInto(out *MapAccount) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + if in.Spec != nil { + in, out := &in.Spec, &out.Spec + *out = make(MapAccountSpec, len(*in)) + copy(*out, *in) + } + out.Status = in.Status +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapAccount. +func (in *MapAccount) DeepCopy() *MapAccount { + if in == nil { + return nil + } + out := new(MapAccount) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MapAccount) 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 *MapAccountList) DeepCopyInto(out *MapAccountList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MapAccount, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapAccountList. +func (in *MapAccountList) DeepCopy() *MapAccountList { + if in == nil { + return nil + } + out := new(MapAccountList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MapAccountList) 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 MapAccountSpec) DeepCopyInto(out *MapAccountSpec) { + { + in := &in + *out = make(MapAccountSpec, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapAccountSpec. +func (in MapAccountSpec) DeepCopy() MapAccountSpec { + if in == nil { + return nil + } + out := new(MapAccountSpec) + in.DeepCopyInto(out) + return *out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MapAccountStatus) DeepCopyInto(out *MapAccountStatus) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapAccountStatus. +func (in *MapAccountStatus) DeepCopy() *MapAccountStatus { + if in == nil { + return nil + } + out := new(MapAccountStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MapRole) DeepCopyInto(out *MapRole) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + out.Status = in.Status +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapRole. +func (in *MapRole) DeepCopy() *MapRole { + if in == nil { + return nil + } + out := new(MapRole) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MapRole) 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 *MapRoleList) DeepCopyInto(out *MapRoleList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MapRole, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapRoleList. +func (in *MapRoleList) DeepCopy() *MapRoleList { + if in == nil { + return nil + } + out := new(MapRoleList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MapRoleList) 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 *MapRoleSpec) DeepCopyInto(out *MapRoleSpec) { + *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 MapRoleSpec. +func (in *MapRoleSpec) DeepCopy() *MapRoleSpec { + if in == nil { + return nil + } + out := new(MapRoleSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MapRoleStatus) DeepCopyInto(out *MapRoleStatus) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapRoleStatus. +func (in *MapRoleStatus) DeepCopy() *MapRoleStatus { + if in == nil { + return nil + } + out := new(MapRoleStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MapUser) DeepCopyInto(out *MapUser) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + out.Status = in.Status +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapUser. +func (in *MapUser) DeepCopy() *MapUser { + if in == nil { + return nil + } + out := new(MapUser) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MapUser) 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 *MapUserList) DeepCopyInto(out *MapUserList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]MapUser, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapUserList. +func (in *MapUserList) DeepCopy() *MapUserList { + if in == nil { + return nil + } + out := new(MapUserList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *MapUserList) 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 *MapUserSpec) DeepCopyInto(out *MapUserSpec) { + *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 MapUserSpec. +func (in *MapUserSpec) DeepCopy() *MapUserSpec { + if in == nil { + return nil + } + out := new(MapUserSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MapUserStatus) DeepCopyInto(out *MapUserStatus) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapUserStatus. +func (in *MapUserStatus) DeepCopy() *MapUserStatus { + if in == nil { + return nil + } + out := new(MapUserStatus) + in.DeepCopyInto(out) + return out +} diff --git a/awsauth/data.go b/awsauth/data.go index 64f66b0..a423b42 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -33,26 +33,29 @@ func init() { } const ( - ConfigMapName = "aws-auth" + //ConfigMapName = "aws-auth" ConfigMapNamespace = "kube-system" ) +var ConfigMapName = "aws-auth" + var UsernameMustBeEmail = false -var MustPresentAccountID = "" +var MustPresentAccountID string = "" -var CrdItemAllowedNamespace = "" +var CrdItemAllowedNamespace string = "" type ControllerArgs struct { UsernameMustBeEmail bool MustPresentAccountID string CrdItemAllowedNamespace string + ConfigMapName string } -// SetUsernameMustBeEmail sets the global flag for username email validation func DeclareVariables(controllerArgs ControllerArgs) { UsernameMustBeEmail = controllerArgs.UsernameMustBeEmail MustPresentAccountID = controllerArgs.MustPresentAccountID - MustPresentAccountID = controllerArgs.CrdItemAllowedNamespace + CrdItemAllowedNamespace = controllerArgs.CrdItemAllowedNamespace + ConfigMapName = controllerArgs.ConfigMapName } // ReadAuthMap reads the auth ConfigMap and returns AwsAuthData and the read ConfigMap. diff --git a/cmd/main.go b/cmd/main.go index 0d6a81d..2c1f33a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -19,10 +19,11 @@ package main import ( "crypto/tls" "flag" - "github.com/redacid/aws-auth-controller/awsauth" "os" "path/filepath" + "github.com/redacid/aws-auth-controller/awsauth" + // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" @@ -68,12 +69,15 @@ func main() { var userNameMustBeEmail bool var mustPresentAccountID string var crdItemAllowedNamespace string + var configMapName string var tlsOpts []func(*tls.Config) flag.BoolVar(&userNameMustBeEmail, "username-must-be-email", false, "Enables checking of username, should it be an email address, default false. Use --username-must-be-email=true to enable this feature.") flag.StringVar(&mustPresentAccountID, "must-present-account-id", "", "This account must be allways present in ConfigMap, must-present-account-id=123456789012") flag.StringVar(&crdItemAllowedNamespace, "crd-item-allowed-namespace", "", "Namespace where allowed creation of Resources crd-item-allowed-namespace=kube-system,"+ "If is set, only in this namespace allowed creation of Resources, if not set, all namespaces allowed creation of Resources.") + flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where store items, config-map-name=aws-auth, if not set, use default name aws-auth") + flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") @@ -107,6 +111,7 @@ func main() { UsernameMustBeEmail: userNameMustBeEmail, MustPresentAccountID: mustPresentAccountID, CrdItemAllowedNamespace: crdItemAllowedNamespace, + ConfigMapName: configMapName, } awsauth.DeclareVariables(VariablesDeclare) @@ -252,6 +257,20 @@ func main() { os.Exit(1) } } + // nolint:goconst + if os.Getenv("ENABLE_WEBHOOKS") != "false" { + if err := webhookv1beta1.SetupMapRoleWebhookWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create webhook", "webhook", "MapRole") + os.Exit(1) + } + } + // nolint:goconst + if os.Getenv("ENABLE_WEBHOOKS") != "false" { + if err := webhookv1beta1.SetupMapAccountWebhookWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create webhook", "webhook", "MapAccount") + os.Exit(1) + } + } // +kubebuilder:scaffold:builder if metricsCertWatcher != nil { diff --git a/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml b/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml index 1d03de5..81152f6 100644 --- a/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml +++ b/config/crd/bases/aws-auth.prozorro.sale_maproles.yaml @@ -46,6 +46,8 @@ spec: groups: description: The Kubernetes groups to associate with the MapRole items: + maxLength: 254 + minLength: 3 type: string minItems: 1 type: array diff --git a/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml b/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml index 1e926f9..1590c2a 100644 --- a/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml +++ b/config/crd/bases/aws-auth.prozorro.sale_mapusers.yaml @@ -46,6 +46,8 @@ spec: groups: description: The Kubernetes groups to associate with the MapUser items: + maxLength: 254 + minLength: 3 type: string minItems: 1 type: array diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index de50760..4cf9587 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller - newTag: 0.0.19 + newTag: 0.0.22 diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index 4f1fa26..31fda9a 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -7,3 +7,4 @@ metadata: name: mapaccount-sample spec: # TODO(user): Add fields here + - "123123123123" diff --git a/config/webhook/manifests.yaml b/config/webhook/manifests.yaml index b45115f..4038de7 100644 --- a/config/webhook/manifests.yaml +++ b/config/webhook/manifests.yaml @@ -4,6 +4,46 @@ kind: MutatingWebhookConfiguration metadata: name: mutating-webhook-configuration webhooks: +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /mutate-aws-auth-prozorro-sale-v1beta1-mapaccount + failurePolicy: Fail + name: mmapaccount-v1beta1.kb.io + rules: + - apiGroups: + - aws-auth.prozorro.sale + apiVersions: + - v1beta1 + operations: + - CREATE + - UPDATE + resources: + - mapaccounts + sideEffects: None +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /mutate-aws-auth-prozorro-sale-v1beta1-maprole + failurePolicy: Fail + name: mmaprole-v1beta1.kb.io + rules: + - apiGroups: + - aws-auth.prozorro.sale + apiVersions: + - v1beta1 + operations: + - CREATE + - UPDATE + resources: + - maproles + sideEffects: None - admissionReviewVersions: - v1 clientConfig: @@ -30,6 +70,48 @@ kind: ValidatingWebhookConfiguration metadata: name: validating-webhook-configuration webhooks: +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /validate-aws-auth-prozorro-sale-v1beta1-mapaccount + failurePolicy: Fail + name: vmapaccount-v1beta1.kb.io + rules: + - apiGroups: + - aws-auth.prozorro.sale + apiVersions: + - v1beta1 + operations: + - CREATE + - UPDATE + - DELETE + resources: + - mapaccounts + sideEffects: None +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /validate-aws-auth-prozorro-sale-v1beta1-maprole + failurePolicy: Fail + name: vmaprole-v1beta1.kb.io + rules: + - apiGroups: + - aws-auth.prozorro.sale + apiVersions: + - v1beta1 + operations: + - CREATE + - UPDATE + - DELETE + resources: + - maproles + sideEffects: None - admissionReviewVersions: - v1 clientConfig: diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go new file mode 100644 index 0000000..6793de3 --- /dev/null +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -0,0 +1,126 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "context" + "fmt" + + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/webhook" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" +) + +// nolint:unused +// log is for logging in this package. +var mapaccountlog = logf.Log.WithName("mapaccount-resource") + +// SetupMapAccountWebhookWithManager registers the webhook for MapAccount in the manager. +func SetupMapAccountWebhookWithManager(mgr ctrl.Manager) error { + return ctrl.NewWebhookManagedBy(mgr).For(&awsauthv1beta1.MapAccount{}). + WithValidator(&MapAccountCustomValidator{}). + WithDefaulter(&MapAccountCustomDefaulter{}). + Complete() +} + +// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! + +// +kubebuilder:webhook:path=/mutate-aws-auth-prozorro-sale-v1beta1-mapaccount,mutating=true,failurePolicy=fail,sideEffects=None,groups=aws-auth.prozorro.sale,resources=mapaccounts,verbs=create;update,versions=v1beta1,name=mmapaccount-v1beta1.kb.io,admissionReviewVersions=v1 + +// MapAccountCustomDefaulter struct is responsible for setting default values on the custom resource of the +// Kind MapAccount when those are created or updated. +// +// NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods, +// as it is used only for temporary operations and does not need to be deeply copied. +type MapAccountCustomDefaulter struct { + // TODO(user): Add more fields as needed for defaulting +} + +var _ webhook.CustomDefaulter = &MapAccountCustomDefaulter{} + +// Default implements webhook.CustomDefaulter so a webhook will be registered for the Kind MapAccount. +func (d *MapAccountCustomDefaulter) Default(_ context.Context, obj runtime.Object) error { + mapaccount, ok := obj.(*awsauthv1beta1.MapAccount) + + if !ok { + return fmt.Errorf("expected an MapAccount object but got %T", obj) + } + mapaccountlog.Info("Defaulting for MapAccount", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) + + // TODO(user): fill in your defaulting logic. + + return nil +} + +// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. +// NOTE: The 'path' attribute must follow a specific pattern and should not be modified directly here. +// Modifying the path for an invalid path can cause API server errors; failing to locate the webhook. +// +kubebuilder:webhook:path=/validate-aws-auth-prozorro-sale-v1beta1-mapaccount,mutating=false,failurePolicy=fail,sideEffects=None,groups=aws-auth.prozorro.sale,resources=mapaccounts,verbs=create;update;delete,versions=v1beta1,name=vmapaccount-v1beta1.kb.io,admissionReviewVersions=v1 + +// MapAccountCustomValidator struct is responsible for validating the MapAccount resource +// when it is created, updated, or deleted. +// +// NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods, +// as this struct is used only for temporary operations and does not need to be deeply copied. +type MapAccountCustomValidator struct { + // TODO(user): Add more fields as needed for validation +} + +var _ webhook.CustomValidator = &MapAccountCustomValidator{} + +// ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type MapAccount. +func (v *MapAccountCustomValidator) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) { + mapaccount, ok := obj.(*awsauthv1beta1.MapAccount) + if !ok { + return nil, fmt.Errorf("expected a MapAccount object but got %T", obj) + } + mapaccountlog.Info("Validation for MapAccount upon creation", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) + + // TODO(user): fill in your validation logic upon object creation. + + return nil, nil +} + +// ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type MapAccount. +func (v *MapAccountCustomValidator) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { + mapaccount, ok := newObj.(*awsauthv1beta1.MapAccount) + if !ok { + return nil, fmt.Errorf("expected a MapAccount object for the newObj but got %T", newObj) + } + mapaccountlog.Info("Validation for MapAccount upon update", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) + + // TODO(user): fill in your validation logic upon object update. + + return nil, nil +} + +// ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type MapAccount. +func (v *MapAccountCustomValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { + mapaccount, ok := obj.(*awsauthv1beta1.MapAccount) + if !ok { + return nil, fmt.Errorf("expected a MapAccount object but got %T", obj) + } + mapaccountlog.Info("Validation for MapAccount upon deletion", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) + + // TODO(user): fill in your validation logic upon object deletion. + + return nil, nil +} diff --git a/internal/webhook/v1beta1/mapaccount_webhook_test.go b/internal/webhook/v1beta1/mapaccount_webhook_test.go new file mode 100644 index 0000000..bb5fcea --- /dev/null +++ b/internal/webhook/v1beta1/mapaccount_webhook_test.go @@ -0,0 +1,87 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + // TODO (user): Add any additional imports if needed +) + +var _ = Describe("MapAccount Webhook", func() { + var ( + obj *awsauthv1beta1.MapAccount + oldObj *awsauthv1beta1.MapAccount + validator MapAccountCustomValidator + defaulter MapAccountCustomDefaulter + ) + + BeforeEach(func() { + obj = &awsauthv1beta1.MapAccount{} + oldObj = &awsauthv1beta1.MapAccount{} + validator = MapAccountCustomValidator{} + Expect(validator).NotTo(BeNil(), "Expected validator to be initialized") + defaulter = MapAccountCustomDefaulter{} + Expect(defaulter).NotTo(BeNil(), "Expected defaulter to be initialized") + Expect(oldObj).NotTo(BeNil(), "Expected oldObj to be initialized") + Expect(obj).NotTo(BeNil(), "Expected obj to be initialized") + // TODO (user): Add any setup logic common to all tests + }) + + AfterEach(func() { + // TODO (user): Add any teardown logic common to all tests + }) + + Context("When creating MapAccount under Defaulting Webhook", func() { + // TODO (user): Add logic for defaulting webhooks + // Example: + // It("Should apply defaults when a required field is empty", func() { + // By("simulating a scenario where defaults should be applied") + // obj.SomeFieldWithDefault = "" + // By("calling the Default method to apply defaults") + // defaulter.Default(ctx, obj) + // By("checking that the default values are set") + // Expect(obj.SomeFieldWithDefault).To(Equal("default_value")) + // }) + }) + + Context("When creating or updating MapAccount under Validating Webhook", func() { + // TODO (user): Add logic for validating webhooks + // Example: + // It("Should deny creation if a required field is missing", func() { + // By("simulating an invalid creation scenario") + // obj.SomeRequiredField = "" + // Expect(validator.ValidateCreate(ctx, obj)).Error().To(HaveOccurred()) + // }) + // + // It("Should admit creation if all required fields are present", func() { + // By("simulating an invalid creation scenario") + // obj.SomeRequiredField = "valid_value" + // Expect(validator.ValidateCreate(ctx, obj)).To(BeNil()) + // }) + // + // It("Should validate updates correctly", func() { + // By("simulating a valid update scenario") + // oldObj.SomeRequiredField = "updated_value" + // obj.SomeRequiredField = "updated_value" + // Expect(validator.ValidateUpdate(ctx, oldObj, obj)).To(BeNil()) + // }) + }) + +}) diff --git a/internal/webhook/v1beta1/maprole_webhook.go b/internal/webhook/v1beta1/maprole_webhook.go new file mode 100644 index 0000000..b6a7ae0 --- /dev/null +++ b/internal/webhook/v1beta1/maprole_webhook.go @@ -0,0 +1,126 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + "context" + "fmt" + + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/webhook" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" +) + +// nolint:unused +// log is for logging in this package. +var maprolelog = logf.Log.WithName("maprole-resource") + +// SetupMapRoleWebhookWithManager registers the webhook for MapRole in the manager. +func SetupMapRoleWebhookWithManager(mgr ctrl.Manager) error { + return ctrl.NewWebhookManagedBy(mgr).For(&awsauthv1beta1.MapRole{}). + WithValidator(&MapRoleCustomValidator{}). + WithDefaulter(&MapRoleCustomDefaulter{}). + Complete() +} + +// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! + +// +kubebuilder:webhook:path=/mutate-aws-auth-prozorro-sale-v1beta1-maprole,mutating=true,failurePolicy=fail,sideEffects=None,groups=aws-auth.prozorro.sale,resources=maproles,verbs=create;update,versions=v1beta1,name=mmaprole-v1beta1.kb.io,admissionReviewVersions=v1 + +// MapRoleCustomDefaulter struct is responsible for setting default values on the custom resource of the +// Kind MapRole when those are created or updated. +// +// NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods, +// as it is used only for temporary operations and does not need to be deeply copied. +type MapRoleCustomDefaulter struct { + // TODO(user): Add more fields as needed for defaulting +} + +var _ webhook.CustomDefaulter = &MapRoleCustomDefaulter{} + +// Default implements webhook.CustomDefaulter so a webhook will be registered for the Kind MapRole. +func (d *MapRoleCustomDefaulter) Default(_ context.Context, obj runtime.Object) error { + maprole, ok := obj.(*awsauthv1beta1.MapRole) + + if !ok { + return fmt.Errorf("expected an MapRole object but got %T", obj) + } + maprolelog.Info("Defaulting for MapRole", "name", maprole.GetName()) + + // TODO(user): fill in your defaulting logic. + + return nil +} + +// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. +// NOTE: The 'path' attribute must follow a specific pattern and should not be modified directly here. +// Modifying the path for an invalid path can cause API server errors; failing to locate the webhook. +// +kubebuilder:webhook:path=/validate-aws-auth-prozorro-sale-v1beta1-maprole,mutating=false,failurePolicy=fail,sideEffects=None,groups=aws-auth.prozorro.sale,resources=maproles,verbs=create;update;delete,versions=v1beta1,name=vmaprole-v1beta1.kb.io,admissionReviewVersions=v1 + +// MapRoleCustomValidator struct is responsible for validating the MapRole resource +// when it is created, updated, or deleted. +// +// NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods, +// as this struct is used only for temporary operations and does not need to be deeply copied. +type MapRoleCustomValidator struct { + // TODO(user): Add more fields as needed for validation +} + +var _ webhook.CustomValidator = &MapRoleCustomValidator{} + +// ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type MapRole. +func (v *MapRoleCustomValidator) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) { + maprole, ok := obj.(*awsauthv1beta1.MapRole) + if !ok { + return nil, fmt.Errorf("expected a MapRole object but got %T", obj) + } + maprolelog.Info("Validation for MapRole upon creation", "name", maprole.GetName()) + + // TODO(user): fill in your validation logic upon object creation. + + return nil, nil +} + +// ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type MapRole. +func (v *MapRoleCustomValidator) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { + maprole, ok := newObj.(*awsauthv1beta1.MapRole) + if !ok { + return nil, fmt.Errorf("expected a MapRole object for the newObj but got %T", newObj) + } + maprolelog.Info("Validation for MapRole upon update", "name", maprole.GetName()) + + // TODO(user): fill in your validation logic upon object update. + + return nil, nil +} + +// ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type MapRole. +func (v *MapRoleCustomValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { + maprole, ok := obj.(*awsauthv1beta1.MapRole) + if !ok { + return nil, fmt.Errorf("expected a MapRole object but got %T", obj) + } + maprolelog.Info("Validation for MapRole upon deletion", "name", maprole.GetName()) + + // TODO(user): fill in your validation logic upon object deletion. + + return nil, nil +} diff --git a/internal/webhook/v1beta1/maprole_webhook_test.go b/internal/webhook/v1beta1/maprole_webhook_test.go new file mode 100644 index 0000000..0782830 --- /dev/null +++ b/internal/webhook/v1beta1/maprole_webhook_test.go @@ -0,0 +1,87 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta1 + +import ( + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + // TODO (user): Add any additional imports if needed +) + +var _ = Describe("MapRole Webhook", func() { + var ( + obj *awsauthv1beta1.MapRole + oldObj *awsauthv1beta1.MapRole + validator MapRoleCustomValidator + defaulter MapRoleCustomDefaulter + ) + + BeforeEach(func() { + obj = &awsauthv1beta1.MapRole{} + oldObj = &awsauthv1beta1.MapRole{} + validator = MapRoleCustomValidator{} + Expect(validator).NotTo(BeNil(), "Expected validator to be initialized") + defaulter = MapRoleCustomDefaulter{} + Expect(defaulter).NotTo(BeNil(), "Expected defaulter to be initialized") + Expect(oldObj).NotTo(BeNil(), "Expected oldObj to be initialized") + Expect(obj).NotTo(BeNil(), "Expected obj to be initialized") + // TODO (user): Add any setup logic common to all tests + }) + + AfterEach(func() { + // TODO (user): Add any teardown logic common to all tests + }) + + Context("When creating MapRole under Defaulting Webhook", func() { + // TODO (user): Add logic for defaulting webhooks + // Example: + // It("Should apply defaults when a required field is empty", func() { + // By("simulating a scenario where defaults should be applied") + // obj.SomeFieldWithDefault = "" + // By("calling the Default method to apply defaults") + // defaulter.Default(ctx, obj) + // By("checking that the default values are set") + // Expect(obj.SomeFieldWithDefault).To(Equal("default_value")) + // }) + }) + + Context("When creating or updating MapRole under Validating Webhook", func() { + // TODO (user): Add logic for validating webhooks + // Example: + // It("Should deny creation if a required field is missing", func() { + // By("simulating an invalid creation scenario") + // obj.SomeRequiredField = "" + // Expect(validator.ValidateCreate(ctx, obj)).Error().To(HaveOccurred()) + // }) + // + // It("Should admit creation if all required fields are present", func() { + // By("simulating an invalid creation scenario") + // obj.SomeRequiredField = "valid_value" + // Expect(validator.ValidateCreate(ctx, obj)).To(BeNil()) + // }) + // + // It("Should validate updates correctly", func() { + // By("simulating a valid update scenario") + // oldObj.SomeRequiredField = "updated_value" + // obj.SomeRequiredField = "updated_value" + // Expect(validator.ValidateUpdate(ctx, oldObj, obj)).To(BeNil()) + // }) + }) + +}) diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index 4495264..7aa9dc4 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -102,9 +102,12 @@ func (v *MapUserCustomValidator) ValidateCreate(_ context.Context, obj runtime.O "Groups", mapuser.Spec.Groups, "Namespace", mapuser.GetNamespace(), ) - if mapuser.GetNamespace() != "kube-system" { - mapuserlog.Error(nil, "Namespace "+mapuser.GetNamespace()+" is NOT allowed for creation MapUser") - return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapUser", mapuser.GetNamespace()) + + if awsauth.CrdItemAllowedNamespace != "" { + if mapuser.GetNamespace() != awsauth.CrdItemAllowedNamespace { + mapuserlog.Error(nil, "Namespace "+mapuser.GetNamespace()+" is NOT allowed for creation MapUser") + return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapUser", mapuser.GetNamespace()) + } } // Validate fields //if err := awsauth.VerifyUserARN(mapuser.Spec.UserARN); err != nil { diff --git a/internal/webhook/v1beta1/webhook_suite_test.go b/internal/webhook/v1beta1/webhook_suite_test.go index 9253703..6a4a34b 100644 --- a/internal/webhook/v1beta1/webhook_suite_test.go +++ b/internal/webhook/v1beta1/webhook_suite_test.go @@ -112,6 +112,12 @@ var _ = BeforeSuite(func() { err = SetupMapUserWebhookWithManager(mgr) Expect(err).NotTo(HaveOccurred()) + err = SetupMapRoleWebhookWithManager(mgr) + Expect(err).NotTo(HaveOccurred()) + + err = SetupMapAccountWebhookWithManager(mgr) + Expect(err).NotTo(HaveOccurred()) + // +kubebuilder:scaffold:webhook go func() { From 738b068e049c5d4b7c9851474fee7b9e4bd6ac89 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 10 Jul 2025 11:42:26 +0300 Subject: [PATCH 06/58] add webhooks --- Makefile | 2 +- README.md | 5 +- TODO.md | 2 +- api/v1beta1/mapaccount_types.go | 8 +- api/v1beta1/zz_generated.deepcopy.go | 18 +--- awsauth/data.go | 50 +++++++++- awsauth/data_test.go | 4 +- awsauth/mapper.go | 61 +++++++++++- awsauth/service.go | 40 ++++++++ cmd/main.go | 4 +- .../aws-auth.prozorro.sale_mapaccounts.yaml | 13 ++- config/manager/kustomization.yaml | 2 +- config/manager/manager.yaml | 2 + .../samples/aws-auth_v1beta1_mapaccount.yaml | 15 ++- internal/controller/mapaccount_controller.go | 92 ++++++++++++++++++- 15 files changed, 277 insertions(+), 41 deletions(-) diff --git a/Makefile b/Makefile index 98079ae..fc3bde7 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.22 +IMG ?= redacid/aws-auth-controller:0.0.28 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/README.md b/README.md index 3f3727b..89edef3 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,9 @@ git tag 0.0.1 -m "Test 0.0.1" git push origin 0.0.1 cd ./charts helm upgrade -i --namespace kube-system aws-auth aws-auth-operator -cd ./config/samples kubectl apply -f prozorro_v1alpha1_mapuser.yaml -n kube-system -cd ./config/samples kubectl apply -f prozorro_v1alpha1_maprole.yaml -n kube-system +cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapuser.yaml -n kube-system +cd ./config/samples kubectl apply -f aws-auth_v1beta1_maprole.yaml -n kube-system +cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapaccount.yaml -n kube-system https://book.kubebuilder.io/reference/using-finalizers https://book.kubebuilder.io/reference/markers/crd-validation \ No newline at end of file diff --git a/TODO.md b/TODO.md index ace45c4..31b831e 100644 --- a/TODO.md +++ b/TODO.md @@ -1 +1 @@ -Додати флаг CrdAllowedNamespace, для контролю створення ресурсів \ No newline at end of file +~~Додати флаг CrdAllowedNamespace, для контролю створення ресурсів~~ \ No newline at end of file diff --git a/api/v1beta1/mapaccount_types.go b/api/v1beta1/mapaccount_types.go index efa6925..e8dd6c7 100644 --- a/api/v1beta1/mapaccount_types.go +++ b/api/v1beta1/mapaccount_types.go @@ -32,9 +32,11 @@ import ( // //Foo string `json:"foo,omitempty"` //} -// +kubebuilder:validation:items:MaxLength:=12 -// +kubebuilder:validation:items:MinLength:=12 -type MapAccountSpec []string +type MapAccountSpec struct { + // +kubebuilder:validation:MaxLength:=12 + // +kubebuilder:validation:MinLength:=12 + AccountID string `json:"accountid"` +} // MapAccountStatus defines the observed state of MapAccount. type MapAccountStatus struct { diff --git a/api/v1beta1/zz_generated.deepcopy.go b/api/v1beta1/zz_generated.deepcopy.go index 55bc2d6..1ebdfb5 100644 --- a/api/v1beta1/zz_generated.deepcopy.go +++ b/api/v1beta1/zz_generated.deepcopy.go @@ -29,11 +29,7 @@ func (in *MapAccount) DeepCopyInto(out *MapAccount) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - if in.Spec != nil { - in, out := &in.Spec, &out.Spec - *out = make(MapAccountSpec, len(*in)) - copy(*out, *in) - } + out.Spec = in.Spec out.Status = in.Status } @@ -88,22 +84,18 @@ func (in *MapAccountList) DeepCopyObject() runtime.Object { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in MapAccountSpec) DeepCopyInto(out *MapAccountSpec) { - { - in := &in - *out = make(MapAccountSpec, len(*in)) - copy(*out, *in) - } +func (in *MapAccountSpec) DeepCopyInto(out *MapAccountSpec) { + *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapAccountSpec. -func (in MapAccountSpec) DeepCopy() MapAccountSpec { +func (in *MapAccountSpec) DeepCopy() *MapAccountSpec { if in == nil { return nil } out := new(MapAccountSpec) in.DeepCopyInto(out) - return *out + return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. diff --git a/awsauth/data.go b/awsauth/data.go index a423b42..aace166 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -33,12 +33,13 @@ func init() { } const ( - //ConfigMapName = "aws-auth" + // ConfigMapName = "aws-auth" ConfigMapNamespace = "kube-system" ) var ConfigMapName = "aws-auth" +var CrdFinalizerName = "aws-auth.prozorro.sale/finalizer" var UsernameMustBeEmail = false var MustPresentAccountID string = "" @@ -79,8 +80,14 @@ func ReadAuthMap(k kubernetes.Interface) (AwsAuthData, *kcorev1.ConfigMap, error return authData, cm, err } + err = yaml.Unmarshal([]byte(cm.Data["mapAccounts"]), &authData.MapAccounts) + if err != nil { + return authData, cm, err + } + err = yaml.Unmarshal([]byte(cm.Data["mapUsers"]), &authData.MapUsers) return authData, cm, err + } func CreateAuthMap(k kubernetes.Interface) (*kcorev1.ConfigMap, error) { @@ -109,9 +116,15 @@ func UpdateAuthMap(k kubernetes.Interface, authData AwsAuthData, cm *kcorev1.Con return err } + mapAccounts, err := yaml.Marshal(authData.MapAccounts) + if err != nil { + return err + } + cm.Data = map[string]string{ - "mapRoles": string(mapRoles), - "mapUsers": string(mapUsers), + "mapRoles": string(mapRoles), + "mapUsers": string(mapUsers), + "mapAccounts": string(mapAccounts), } _, err = k.CoreV1().ConfigMaps(ConfigMapNamespace).Update(context.Background(), cm, apismetav1.UpdateOptions{}) @@ -120,8 +133,9 @@ func UpdateAuthMap(k kubernetes.Interface, authData AwsAuthData, cm *kcorev1.Con // AwsAuthData represents the data of the aws-auth configmap type AwsAuthData struct { - MapRoles []*MapRole `yaml:"mapRoles"` - MapUsers []*MapUser `yaml:"mapUsers"` + MapRoles []*MapRole `yaml:"mapRoles"` + MapUsers []*MapUser `yaml:"mapUsers"` + MapAccounts []*MapAccount `yaml:"mapAccounts"` } // SetMapRoles sets the MapRoles element @@ -134,6 +148,10 @@ func (m *AwsAuthData) SetMapUsers(authMap []*MapUser) { m.MapUsers = authMap } +func (m *AwsAuthData) SetMapAccounts(authMap []*MapAccount) { + m.MapAccounts = authMap +} + // MapRole is the basic structure of a mapRoles authentication object type MapRole struct { RoleARN string `yaml:"rolearn"` @@ -175,6 +193,7 @@ func NewMapRole(rolearn, username string, groups []string) *MapRole { } // MapUser is the basic structure of a mapUsers authentication object + type MapUser struct { CrdName string `yaml:"crdname"` UserARN string `yaml:"userarn"` @@ -219,3 +238,24 @@ func NewMapUser(crdname, userarn, username string, groups []string) *MapUser { Groups: groups, } } + +type MapAccount struct { + AccountID string `yaml:"accountid"` +} + +func (r *MapAccount) SetAccount(v string) *MapAccount { + r.AccountID = v + return r +} + +func (r *MapAccount) String() string { + var s strings.Builder + s.WriteString(fmt.Sprintf("- accountid: %v\n ", r.AccountID)) + return s.String() +} + +func NewMapAccount(accountid string) *MapAccount { + return &MapAccount{ + AccountID: accountid, + } +} diff --git a/awsauth/data_test.go b/awsauth/data_test.go index 28f08f8..cbd489e 100644 --- a/awsauth/data_test.go +++ b/awsauth/data_test.go @@ -32,7 +32,7 @@ func createMockConfigMap(client kubernetes.Interface) { "system:node:{{EC2PrivateDNSName}}", []string{"system:bootstrappers", "system:nodes"}) - user := NewMapUser("arn:aws:iam::00000000000:user/user-1", + user := NewMapUser("testcrd", "arn:aws:iam::00000000000:user/user-1", "admin", []string{"system:masters"}) @@ -67,7 +67,7 @@ func TestUpdateAuthMap(t *testing.T) { role := NewMapRole("arn:aws:iam::00000000000:role/node-2", "system:node:{{EC2PrivateDNSName}}", []string{"system:bootstrappers", "system:nodes"}) - user := NewMapUser("arn:aws:iam::00000000000:user/user-2", + user := NewMapUser("testcrd", "arn:aws:iam::00000000000:user/user-2", "ops-user", []string{"system:masters"}) diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 7c7a499..4106e36 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -82,15 +82,28 @@ func (m *Mapper) removeAuth(args *Arguments) error { } authData.SetMapUsers(newUsersAuthMap) } + // TODO тут якась херня + if args.DataType == MapAccountData { + var newAccountsAuthMap []*MapAccount + for _, mapAccount := range authData.MapAccounts { + if args.AccountID != mapAccount.AccountID { + newAccountsAuthMap = append(newAccountsAuthMap, mapAccount) + } else { + removed = true + } + } + authData.SetMapAccounts(newAccountsAuthMap) + } if !removed { - return fmt.Errorf("%s with username '%s' not found in auth map", args.DataType, args.CrdName) + return fmt.Errorf("%s with account id '%s' not found in auth map", args.DataType, args.AccountID) } return UpdateAuthMap(m.KubernetesClient, authData, configMap) } // Upsert updates or inserts a mapRole or mapUser item into the auth map. func (m *Mapper) Upsert(args *Arguments) error { + // TODO Remove this validate args.Validate() if args.WithRetries { return WithRetry(m.upsertAuth, args) @@ -126,6 +139,17 @@ func (m *Mapper) upsertAuth(args *Arguments) error { authData.SetMapUsers(newMap) } + if args.DataType == MapAccountData { + mapAccount := NewMapAccount(args.AccountID) + newMap, ok := upsertAccount(authData.MapAccounts, mapAccount) + if ok { + log.Printf("%s with account id '%s' key has been updated\n", args.DataType, args.AccountID) + } else { + log.Printf("%s with account id '%s' key has been updated\n", args.DataType, args.AccountID) + } + authData.SetMapAccounts(newMap) + } + return UpdateAuthMap(m.KubernetesClient, authData, configMap) } @@ -198,10 +222,40 @@ func upsertUser(authMaps []*MapUser, resource *MapUser) ([]*MapUser, bool) { return authMaps, updated } +func upsertAccount(authMaps []*MapAccount, resource *MapAccount) ([]*MapAccount, bool) { + var found, updated bool + //for _, existing := range authMaps { + // + // if existing.CrdName == resource.CrdName { + // found = true + // if !reflect.DeepEqual(existing.Groups, resource.Groups) { + // existing.SetGroups(resource.Groups) + // updated = true + // } + // if existing.Username != resource.Username { + // existing.SetUsername(resource.Username) + // updated = true + // } + // if existing.UserARN != resource.UserARN { + // existing.SetUserARN(resource.UserARN) + // updated = true + // } + // } + //} + + // Insert new account in auth map. + if !found { + updated = true + authMaps = append(authMaps, resource) + } + return authMaps, updated +} + // Arguments are the arguments for management of the auth map. type Arguments struct { OperationType OperationType DataType DataType + AccountID string RoleARN string UserARN string CrdName string @@ -253,6 +307,7 @@ const ( type DataType string const ( - MapRoleData DataType = "mapRole" - MapUserData DataType = "mapUser" + MapRoleData DataType = "mapRole" + MapUserData DataType = "mapUser" + MapAccountData DataType = "mapAccount" ) diff --git a/awsauth/service.go b/awsauth/service.go index d48e601..997f231 100644 --- a/awsauth/service.go +++ b/awsauth/service.go @@ -47,6 +47,12 @@ type Service interface { // RemoveMapUser removes a MapUser from the configmap keyed by username RemoveMapUser(username string) error + + // UpsertMapAccount upserts a mapAccount into the configmap keyed by username. + UpsertMapAccount(mapAccount MapAccount) error + + // RemoveMapAccount removes a mapAccount from the configmap keyed by username + RemoveMapAccount(mapAccount MapAccount) error } // NewService returns an implementation of the Service interface. @@ -137,3 +143,37 @@ func (svc impl) RemoveMapUser(username string) error { } return err } + +// UpsertMapAccount upserts a MapAccount into the configmap keyed by username. +func (svc impl) UpsertMapAccount(mapAccount MapAccount) error { + mapper := NewMapper(svc.cfg.KubeClient, false) + err := mapper.Upsert(&Arguments{ + DataType: MapAccountData, + AccountID: mapAccount.AccountID, + WithRetries: svc.cfg.WithRetries, + MaxRetryCount: svc.cfg.MaxRetryCount, + MaxRetryTime: svc.cfg.MaxRetryTime, + MinRetryTime: svc.cfg.MinRetryTime, + }) + if err != nil { + svc.cfg.Log.Error(err, "failure to upsert mapUser", "accountid", mapAccount.AccountID) + } + return err +} + +// RemoveMapUser removes a MapUser from the configmap keyed by username. +func (svc impl) RemoveMapAccount(mapAccount MapAccount) error { + mapper := NewMapper(svc.cfg.KubeClient, false) + err := mapper.Remove(&Arguments{ + DataType: MapAccountData, + AccountID: mapAccount.AccountID, + WithRetries: svc.cfg.WithRetries, + MaxRetryCount: svc.cfg.MaxRetryCount, + MaxRetryTime: svc.cfg.MaxRetryTime, + MinRetryTime: svc.cfg.MinRetryTime, + }) + if err != nil { + svc.cfg.Log.Info("mapAccount not found", "account id", mapAccount.AccountID) + } + return err +} diff --git a/cmd/main.go b/cmd/main.go index 2c1f33a..a9ff3fc 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -74,9 +74,9 @@ func main() { flag.BoolVar(&userNameMustBeEmail, "username-must-be-email", false, "Enables checking of username, should it be an email address, default false. Use --username-must-be-email=true to enable this feature.") flag.StringVar(&mustPresentAccountID, "must-present-account-id", "", "This account must be allways present in ConfigMap, must-present-account-id=123456789012") - flag.StringVar(&crdItemAllowedNamespace, "crd-item-allowed-namespace", "", "Namespace where allowed creation of Resources crd-item-allowed-namespace=kube-system,"+ + flag.StringVar(&crdItemAllowedNamespace, "crd-item-allowed-namespace", "", "Namespace where allowed creation of Resources --crd-item-allowed-namespace=kube-system,"+ "If is set, only in this namespace allowed creation of Resources, if not set, all namespaces allowed creation of Resources.") - flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where store items, config-map-name=aws-auth, if not set, use default name aws-auth") + flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where store items, --config-map-name=aws-auth, if not set, use default name aws-auth") flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") diff --git a/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml b/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml index c65d887..68d818d 100644 --- a/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml +++ b/config/crd/bases/aws-auth.prozorro.sale_mapaccounts.yaml @@ -37,11 +37,14 @@ spec: metadata: type: object spec: - items: - maxLength: 12 - minLength: 12 - type: string - type: array + properties: + accountid: + maxLength: 12 + minLength: 12 + type: string + required: + - accountid + type: object status: description: MapAccountStatus defines the observed state of MapAccount. type: object diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 4cf9587..a755dc4 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller - newTag: 0.0.22 + newTag: 0.0.28 diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index ecc4c4f..fdba67c 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -61,6 +61,8 @@ spec: - command: - /manager args: + - --config-map-name=aws-auth-test + - --crd-item-allowed-namespace=kube-system - --username-must-be-email - --leader-elect - --health-probe-bind-address=:8081 diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index 31fda9a..e0c6f8c 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -6,5 +6,16 @@ metadata: app.kubernetes.io/managed-by: kustomize name: mapaccount-sample spec: - # TODO(user): Add fields here - - "123123123123" + accountid: "111111111111" + +#--- +# +#apiVersion: aws-auth.prozorro.sale/v1beta1 +#kind: MapAccount +#metadata: +# labels: +# app.kubernetes.io/name: aws-auth-controller-prozorro +# app.kubernetes.io/managed-by: kustomize +# name: mapaccount-sample2 +#spec: +# accountid: "222222222222" \ No newline at end of file diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index e1308da..03e8023 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -18,10 +18,13 @@ package controller import ( "context" - + "github.com/redacid/aws-auth-controller/awsauth" + "github.com/redacid/aws-auth-controller/kube" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" logf "sigs.k8s.io/controller-runtime/pkg/log" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" @@ -53,6 +56,93 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) // TODO(user): your logic here + // MapAccount objects a list of AWS Accounts. + mapAccountName := req.Name + log := ctrl.Log.WithValues("MapAccount", mapAccountName) + + log.Info("") + + kubeClient, err := kube.GetClient() + if err != nil { + log.Error(err, "failure getting kube client") + return ctrl.Result{}, err + } + + // Get a new aws auth service object. + awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ + KubeClient: kubeClient, + //Log: r.Log, + Log: ctrl.Log, + }) + if err != nil { + log.Error(err, "failure creating new aws auth service") + return ctrl.Result{}, err + } + + // Load the MapUser object by name (its AWS IAM user ARN). + mapAccount := &awsauthv1beta1.MapAccount{} + + if err := r.Get(ctx, req.NamespacedName, mapAccount); err != nil { + // If any error other than a "NotFound" API error, it's a problem. + statusErr, ok := err.(*apierrors.StatusError) + if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { + logf.Log.Error(err, "failure getting mapAccount") + return ctrl.Result{}, err + } + // FINALIZER + // examine DeletionTimestamp to determine if object is under deletion + if mapAccount.ObjectMeta.DeletionTimestamp.IsZero() { + logf.Log.Info("mapAccount is not being deleted, so adding finalizer") + // The object is not being deleted, so if it does not have our finalizer, + // then let's add the finalizer and update the object. This is equivalent + // to registering our finalizer. + if !controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { + controllerutil.AddFinalizer(mapAccount, awsauth.CrdFinalizerName) + if err := r.Update(ctx, mapAccount); err != nil { + return ctrl.Result{}, err + } + } + } else { + // The object is being deleted + //if controllerutil.ContainsFinalizer(&mapAccount, awsauth.CrdFinalizerName) { + // // our finalizer is present, so let's handle any external dependency + // if err := r.deleteExternalResources(mapAccount); err != nil { + // // if fail to delete the external dependency here, return with error + // // so that it can be retried. + // return ctrl.Result{}, err + // } + // + // // remove our finalizer from the list and update it. + // controllerutil.RemoveFinalizer(&mapAccount, awsauth.CrdFinalizerName) + // if err := r.Update(ctx, &mapAccount); err != nil { + // return ctrl.Result{}, err + // } + //} + + // Stop reconciliation as the item is being deleted + return ctrl.Result{}, nil + } + // END FINALIZER + + if err := awsauthSvc.RemoveMapAccount(awsauth.MapAccount{ + AccountID: mapAccount.Spec.AccountID, + }); err != nil { + log.Error(err, "failure removing mapAccount data in aws-auth configmap") + return ctrl.Result{}, nil + } + log.Info("removed mapAccount data in aws-auth configmap") + return ctrl.Result{}, nil + } + + // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. + if err := awsauthSvc.UpsertMapAccount(awsauth.MapAccount{ + AccountID: mapAccount.Spec.AccountID, + }); err != nil { + log.Error(err, "failure upserting MapAccount") + return ctrl.Result{}, err + } + log.Info("upserted MapAccount") + return ctrl.Result{}, nil } From 09c291b4d44a6733eac36df888c30d1272ffdefd Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 10 Jul 2025 19:06:31 +0300 Subject: [PATCH 07/58] account create,update,delete with verification --- Makefile | 3 +- awsauth/mapper.go | 71 ++++++++++---- awsauth/service.go | 22 ++++- awsauth/verify.go | 27 +++++ config/manager/kustomization.yaml | 2 +- .../samples/aws-auth_v1beta1_mapaccount.yaml | 4 +- internal/controller/mapaccount_controller.go | 98 +++++++++---------- .../webhook/v1beta1/mapaccount_webhook.go | 30 ++++++ 8 files changed, 181 insertions(+), 76 deletions(-) diff --git a/Makefile b/Makefile index fc3bde7..cdb55c7 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.28 +IMG ?= redacid/aws-auth-controller:0.0.45 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) @@ -38,6 +38,7 @@ all: build .PHONY: preview preview: mod-tidy generate manifests kustomize + cd config/manager && $(KUSTOMIZE) edit set image controller=${IMG} $(KUSTOMIZE) build config/default .PHONY: mod-tidy diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 4106e36..0372dfa 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -101,6 +101,49 @@ func (m *Mapper) removeAuth(args *Arguments) error { return UpdateAuthMap(m.KubernetesClient, authData, configMap) } +func (m *Mapper) CheckExists(args *Arguments) error { + + if args.WithRetries { + return WithRetry(m.existsAuth, args) + } + return m.existsAuth(args) +} + +func (m *Mapper) existsAuth(args *Arguments) error { + authData, _, err := ReadAuthMap(m.KubernetesClient) + if err != nil { + return err + } + log.Printf("authData: %v\n", authData) + if args.DataType == MapAccountData { + mapAccount := NewMapAccount(args.AccountID) + errAccount, exists := existsAccount(authData.MapAccounts, mapAccount) + if exists { + log.Printf("%s with account id '%s' already exists\n", args.DataType, args.AccountID) + return errAccount + } else { + log.Printf("%s with account id '%s' not exists\n", args.DataType, args.AccountID) + return nil + } + } + // TODO + return nil //UpdateAuthMap(m.KubernetesClient, authData, configMap) +} + +func existsAccount(authMaps []*MapAccount, resource *MapAccount) (error, bool) { + var found bool + for _, existing := range authMaps { + if existing.AccountID == resource.AccountID { + found = true + return fmt.Errorf("account with id '%s' already exists", resource.AccountID), found + } else { + found = false + return nil, found + } + } + return nil, false +} + // Upsert updates or inserts a mapRole or mapUser item into the auth map. func (m *Mapper) Upsert(args *Arguments) error { // TODO Remove this validate @@ -224,24 +267,16 @@ func upsertUser(authMaps []*MapUser, resource *MapUser) ([]*MapUser, bool) { func upsertAccount(authMaps []*MapAccount, resource *MapAccount) ([]*MapAccount, bool) { var found, updated bool - //for _, existing := range authMaps { - // - // if existing.CrdName == resource.CrdName { - // found = true - // if !reflect.DeepEqual(existing.Groups, resource.Groups) { - // existing.SetGroups(resource.Groups) - // updated = true - // } - // if existing.Username != resource.Username { - // existing.SetUsername(resource.Username) - // updated = true - // } - // if existing.UserARN != resource.UserARN { - // existing.SetUserARN(resource.UserARN) - // updated = true - // } - // } - //} + for _, existing := range authMaps { + + if existing.AccountID == resource.AccountID { + found = true + if existing.AccountID != resource.AccountID { + existing.SetAccount(resource.AccountID) + updated = true + } + } + } // Insert new account in auth map. if !found { diff --git a/awsauth/service.go b/awsauth/service.go index 997f231..c6face9 100644 --- a/awsauth/service.go +++ b/awsauth/service.go @@ -48,6 +48,9 @@ type Service interface { // RemoveMapUser removes a MapUser from the configmap keyed by username RemoveMapUser(username string) error + // CheckAccountExists checks if an account with the specified account ID exists. + CheckAccountExists(mapAccount MapAccount) error + // UpsertMapAccount upserts a mapAccount into the configmap keyed by username. UpsertMapAccount(mapAccount MapAccount) error @@ -144,6 +147,23 @@ func (svc impl) RemoveMapUser(username string) error { return err } +func (svc impl) CheckAccountExists(mapAccount MapAccount) error { + svc.cfg.Log.Info("CheckAccountExists", "accountid", mapAccount.AccountID) + mapper := NewMapper(svc.cfg.KubeClient, false) + err := mapper.CheckExists(&Arguments{ + DataType: MapAccountData, + AccountID: mapAccount.AccountID, + WithRetries: svc.cfg.WithRetries, + MaxRetryCount: svc.cfg.MaxRetryCount, + MaxRetryTime: svc.cfg.MaxRetryTime, + MinRetryTime: svc.cfg.MinRetryTime, + }) + if err != nil { + svc.cfg.Log.Info("mapAccount already exists", "accountid", mapAccount.AccountID) + } + return err +} + // UpsertMapAccount upserts a MapAccount into the configmap keyed by username. func (svc impl) UpsertMapAccount(mapAccount MapAccount) error { mapper := NewMapper(svc.cfg.KubeClient, false) @@ -156,7 +176,7 @@ func (svc impl) UpsertMapAccount(mapAccount MapAccount) error { MinRetryTime: svc.cfg.MinRetryTime, }) if err != nil { - svc.cfg.Log.Error(err, "failure to upsert mapUser", "accountid", mapAccount.AccountID) + svc.cfg.Log.Error(err, "failure to upsert mapAccount", "accountid", mapAccount.AccountID) } return err } diff --git a/awsauth/verify.go b/awsauth/verify.go index 3211e9b..958dbb4 100644 --- a/awsauth/verify.go +++ b/awsauth/verify.go @@ -19,6 +19,7 @@ import ( "fmt" "regexp" "strings" + // "k8s.io/client-go/kubernetes" ) var AllowedAWSAccounts = []string{ @@ -26,6 +27,32 @@ var AllowedAWSAccounts = []string{ "130488995195", } +//type Verifier struct { +// KubernetesClient kubernetes.Interface +//} +// +//// NewVerifier returns a new Verifier object. +//func NewVerifier(client kubernetes.Interface, discardLogOutput bool) *Verifier { +// var verifier = &Verifier{} +// verifier.KubernetesClient = client +// +// if !discardLogOutput { +// log.SetOutput(io.Discard) +// } +// return verifier +//} +// +// +//func (v *Verifier) checkAccountExists(accountID string) bool { +// authData, configMap, err := ReadAuthMap(v.KubernetesClient) +// for _, acc := range AllowedAWSAccounts { +// if acc == accountID { +// return true +// } +// } +// return false +//} + // VerifyAWSAccount validates if the provided string is a valid AWS account ID (12 digits) func VerifyAWSAccount(accountID string) error { if accountID == "" { diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index a755dc4..0f6e945 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller - newTag: 0.0.28 + newTag: 0.0.45 diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index e0c6f8c..0b2b9d5 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -4,9 +4,9 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: mapaccount-sample + name: mapaccount-sample1 spec: - accountid: "111111111111" + accountid: "111111111113" #--- # diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 03e8023..f57931d 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -58,13 +58,13 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) // MapAccount objects a list of AWS Accounts. mapAccountName := req.Name - log := ctrl.Log.WithValues("MapAccount", mapAccountName) + log := ctrl.Log.WithValues("----------MapAccount", mapAccountName) - log.Info("") + log.Info("---------------------------------------------------") kubeClient, err := kube.GetClient() if err != nil { - log.Error(err, "failure getting kube client") + log.Error(err, "Failure getting kube client") return ctrl.Result{}, err } @@ -75,74 +75,66 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) Log: ctrl.Log, }) if err != nil { - log.Error(err, "failure creating new aws auth service") + log.Error(err, "Failure creating new aws auth service") return ctrl.Result{}, err } // Load the MapUser object by name (its AWS IAM user ARN). - mapAccount := &awsauthv1beta1.MapAccount{} + mapAccount := awsauthv1beta1.MapAccount{} - if err := r.Get(ctx, req.NamespacedName, mapAccount); err != nil { + if err := r.Get(ctx, req.NamespacedName, &mapAccount); err != nil { // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { - logf.Log.Error(err, "failure getting mapAccount") + logf.Log.Error(err, "Failure getting mapAccount") return ctrl.Result{}, err } - // FINALIZER - // examine DeletionTimestamp to determine if object is under deletion - if mapAccount.ObjectMeta.DeletionTimestamp.IsZero() { + + return ctrl.Result{}, nil + } + + // examine DeletionTimestamp to determine if object is under deletion + if mapAccount.ObjectMeta.DeletionTimestamp.IsZero() { + logf.Log.Info("mapAccount is not being deleted") + // The object is not being deleted, so if it does not have our finalizer, + // then let's add the finalizer and update the object. This is equivalent + // to registering our finalizer. + if !controllerutil.ContainsFinalizer(&mapAccount, awsauth.CrdFinalizerName) { logf.Log.Info("mapAccount is not being deleted, so adding finalizer") - // The object is not being deleted, so if it does not have our finalizer, - // then let's add the finalizer and update the object. This is equivalent - // to registering our finalizer. - if !controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { - controllerutil.AddFinalizer(mapAccount, awsauth.CrdFinalizerName) - if err := r.Update(ctx, mapAccount); err != nil { - return ctrl.Result{}, err - } + controllerutil.AddFinalizer(&mapAccount, awsauth.CrdFinalizerName) + if err := r.Update(ctx, &mapAccount); err != nil { + return ctrl.Result{}, err } } else { - // The object is being deleted - //if controllerutil.ContainsFinalizer(&mapAccount, awsauth.CrdFinalizerName) { - // // our finalizer is present, so let's handle any external dependency - // if err := r.deleteExternalResources(mapAccount); err != nil { - // // if fail to delete the external dependency here, return with error - // // so that it can be retried. - // return ctrl.Result{}, err - // } - // - // // remove our finalizer from the list and update it. - // controllerutil.RemoveFinalizer(&mapAccount, awsauth.CrdFinalizerName) - // if err := r.Update(ctx, &mapAccount); err != nil { - // return ctrl.Result{}, err - // } - //} - - // Stop reconciliation as the item is being deleted - return ctrl.Result{}, nil + + // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. + if err := awsauthSvc.UpsertMapAccount(awsauth.MapAccount{ + AccountID: mapAccount.Spec.AccountID, + }); err != nil { + log.Error(err, "Failure upserting MapAccount") + return ctrl.Result{}, err + } + log.Info("Upserted MapAccount") } - // END FINALIZER - if err := awsauthSvc.RemoveMapAccount(awsauth.MapAccount{ - AccountID: mapAccount.Spec.AccountID, - }); err != nil { - log.Error(err, "failure removing mapAccount data in aws-auth configmap") - return ctrl.Result{}, nil + } else { + log.Info("mapAccount is being deleted") + if controllerutil.ContainsFinalizer(&mapAccount, awsauth.CrdFinalizerName) { + if err := awsauthSvc.RemoveMapAccount(awsauth.MapAccount{ + AccountID: mapAccount.Spec.AccountID, + }); err != nil { + log.Error(err, "Failure removing mapAccount data in aws-auth configmap") + return ctrl.Result{}, nil + } + logf.Log.Info("mapAccount is being deleted, so removing finalizer") + controllerutil.RemoveFinalizer(&mapAccount, awsauth.CrdFinalizerName) + if err := r.Update(ctx, &mapAccount); err != nil { + return ctrl.Result{}, err + } } - log.Info("removed mapAccount data in aws-auth configmap") + log.Info("Removed mapAccount data in aws-auth configmap") return ctrl.Result{}, nil } - - // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. - if err := awsauthSvc.UpsertMapAccount(awsauth.MapAccount{ - AccountID: mapAccount.Spec.AccountID, - }); err != nil { - log.Error(err, "failure upserting MapAccount") - return ctrl.Result{}, err - } - log.Info("upserted MapAccount") - return ctrl.Result{}, nil } diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index 6793de3..1118309 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -19,6 +19,8 @@ package v1beta1 import ( "context" "fmt" + "github.com/redacid/aws-auth-controller/awsauth" + "github.com/redacid/aws-auth-controller/kube" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -96,18 +98,46 @@ func (v *MapAccountCustomValidator) ValidateCreate(_ context.Context, obj runtim // TODO(user): fill in your validation logic upon object creation. + kubeClient, err := kube.GetClient() + if err != nil { + mapaccountlog.Error(err, "Failure getting kube client") + return nil, err + } + + // Get a new aws auth service object. + awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ + KubeClient: kubeClient, + //Log: r.Log, + Log: ctrl.Log, + }) + if err != nil { + mapaccountlog.Error(err, "Failure creating new aws auth service") + return nil, err + } + + if err = awsauthSvc.CheckAccountExists(awsauth.MapAccount{ + AccountID: mapaccount.Spec.AccountID, + }); err != nil { + mapaccountlog.Info("Failure checking, account exists in aws-auth configmap") + return nil, fmt.Errorf("Failure checking, accountid %v exists in aws-auth configmap", mapaccount.Spec.AccountID) + } + return nil, nil } // ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type MapAccount. func (v *MapAccountCustomValidator) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { mapaccount, ok := newObj.(*awsauthv1beta1.MapAccount) + oldmapaccount, ok := oldObj.(*awsauthv1beta1.MapAccount) if !ok { return nil, fmt.Errorf("expected a MapAccount object for the newObj but got %T", newObj) } mapaccountlog.Info("Validation for MapAccount upon update", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) // TODO(user): fill in your validation logic upon object update. + if (mapaccount.Spec.AccountID != oldmapaccount.Spec.AccountID) && (mapaccount.Spec.AccountID != "") { + return nil, fmt.Errorf("AccountID cannot be changed, pls create a new MapAccount with the new AccountID") + } return nil, nil } From 7d7e55eef8a1b1d518f84198cab17d4998c78168 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 10 Jul 2025 20:23:54 +0300 Subject: [PATCH 08/58] user create,update,delete with verification --- Makefile | 2 +- awsauth/data.go | 2 + awsauth/verify.go | 26 -------- config/manager/kustomization.yaml | 2 +- .../samples/aws-auth_v1beta1_mapaccount.yaml | 36 +++++++---- config/samples/aws-auth_v1beta1_mapuser.yaml | 22 ++++++- internal/controller/mapaccount_controller.go | 23 +++----- internal/controller/maprole_controller.go | 4 +- internal/controller/mapuser_controller.go | 59 ++++++++++++------- .../webhook/v1beta1/mapaccount_webhook.go | 7 +++ internal/webhook/v1beta1/maprole_webhook.go | 8 +++ internal/webhook/v1beta1/mapuser_webhook.go | 6 +- 12 files changed, 115 insertions(+), 82 deletions(-) diff --git a/Makefile b/Makefile index cdb55c7..dfcccca 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.45 +IMG ?= redacid/aws-auth-controller:0.0.47 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/awsauth/data.go b/awsauth/data.go index aace166..3e1b6c1 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -41,6 +41,8 @@ var ConfigMapName = "aws-auth" var CrdFinalizerName = "aws-auth.prozorro.sale/finalizer" var UsernameMustBeEmail = false + +// TODO automatic add to configmap var MustPresentAccountID string = "" var CrdItemAllowedNamespace string = "" diff --git a/awsauth/verify.go b/awsauth/verify.go index 958dbb4..b44dc80 100644 --- a/awsauth/verify.go +++ b/awsauth/verify.go @@ -27,32 +27,6 @@ var AllowedAWSAccounts = []string{ "130488995195", } -//type Verifier struct { -// KubernetesClient kubernetes.Interface -//} -// -//// NewVerifier returns a new Verifier object. -//func NewVerifier(client kubernetes.Interface, discardLogOutput bool) *Verifier { -// var verifier = &Verifier{} -// verifier.KubernetesClient = client -// -// if !discardLogOutput { -// log.SetOutput(io.Discard) -// } -// return verifier -//} -// -// -//func (v *Verifier) checkAccountExists(accountID string) bool { -// authData, configMap, err := ReadAuthMap(v.KubernetesClient) -// for _, acc := range AllowedAWSAccounts { -// if acc == accountID { -// return true -// } -// } -// return false -//} - // VerifyAWSAccount validates if the provided string is a valid AWS account ID (12 digits) func VerifyAWSAccount(accountID string) error { if accountID == "" { diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 0f6e945..af1a57e 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller - newTag: 0.0.45 + newTag: 0.0.47 diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index 0b2b9d5..e318f3b 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -6,16 +6,28 @@ metadata: app.kubernetes.io/managed-by: kustomize name: mapaccount-sample1 spec: - accountid: "111111111113" + accountid: "111111111111" -#--- -# -#apiVersion: aws-auth.prozorro.sale/v1beta1 -#kind: MapAccount -#metadata: -# labels: -# app.kubernetes.io/name: aws-auth-controller-prozorro -# app.kubernetes.io/managed-by: kustomize -# name: mapaccount-sample2 -#spec: -# accountid: "222222222222" \ No newline at end of file +--- + +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapAccount +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapaccount-sample2 +spec: + accountid: "222222222222" + +--- + +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapAccount +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: mapaccount-sample3 +spec: + accountid: "333333333333" \ No newline at end of file diff --git a/config/samples/aws-auth_v1beta1_mapuser.yaml b/config/samples/aws-auth_v1beta1_mapuser.yaml index bbcb383..437bb20 100644 --- a/config/samples/aws-auth_v1beta1_mapuser.yaml +++ b/config/samples/aws-auth_v1beta1_mapuser.yaml @@ -4,11 +4,27 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: test9 + name: test spec: description: A test mapuser - username: test2.userios.in.ua + username: test.user@ios.in.ua groups: - system:masters - admins - userarn: arn:aws:iam::123456789012:user/sample-mapuser3 + userarn: arn:aws:iam::123456789012:user/sample-mapuser + +--- +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapUser +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: test2 +spec: + description: A test mapuser + username: test2.user@ios.in.ua + groups: + - system:masters + - admins + userarn: arn:aws:iam::123456789012:user/sample-mapuser2 diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index f57931d..8c90d7c 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -80,33 +80,28 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) } // Load the MapUser object by name (its AWS IAM user ARN). - mapAccount := awsauthv1beta1.MapAccount{} + mapAccount := &awsauthv1beta1.MapAccount{} - if err := r.Get(ctx, req.NamespacedName, &mapAccount); err != nil { + if err := r.Get(ctx, req.NamespacedName, mapAccount); err != nil { // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { logf.Log.Error(err, "Failure getting mapAccount") return ctrl.Result{}, err } - return ctrl.Result{}, nil } - // examine DeletionTimestamp to determine if object is under deletion if mapAccount.ObjectMeta.DeletionTimestamp.IsZero() { logf.Log.Info("mapAccount is not being deleted") - // The object is not being deleted, so if it does not have our finalizer, - // then let's add the finalizer and update the object. This is equivalent - // to registering our finalizer. - if !controllerutil.ContainsFinalizer(&mapAccount, awsauth.CrdFinalizerName) { + // Add finalizer + if !controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { logf.Log.Info("mapAccount is not being deleted, so adding finalizer") - controllerutil.AddFinalizer(&mapAccount, awsauth.CrdFinalizerName) - if err := r.Update(ctx, &mapAccount); err != nil { + controllerutil.AddFinalizer(mapAccount, awsauth.CrdFinalizerName) + if err := r.Update(ctx, mapAccount); err != nil { return ctrl.Result{}, err } } else { - // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. if err := awsauthSvc.UpsertMapAccount(awsauth.MapAccount{ AccountID: mapAccount.Spec.AccountID, @@ -119,7 +114,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) } else { log.Info("mapAccount is being deleted") - if controllerutil.ContainsFinalizer(&mapAccount, awsauth.CrdFinalizerName) { + if controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { if err := awsauthSvc.RemoveMapAccount(awsauth.MapAccount{ AccountID: mapAccount.Spec.AccountID, }); err != nil { @@ -127,8 +122,8 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) return ctrl.Result{}, nil } logf.Log.Info("mapAccount is being deleted, so removing finalizer") - controllerutil.RemoveFinalizer(&mapAccount, awsauth.CrdFinalizerName) - if err := r.Update(ctx, &mapAccount); err != nil { + controllerutil.RemoveFinalizer(mapAccount, awsauth.CrdFinalizerName) + if err := r.Update(ctx, mapAccount); err != nil { return ctrl.Result{}, err } } diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index ceecc0f..da42455 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -76,8 +76,8 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct } // Load the MapRole object by name (its AWS IAM role ARN). - var mapRole awsauthv1beta1.MapRole - if err := r.Get(ctx, req.NamespacedName, &mapRole); err != nil { + mapRole := &awsauthv1beta1.MapRole{} + if err := r.Get(ctx, req.NamespacedName, mapRole); err != nil { // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index 71183e6..b3aee62 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -19,6 +19,7 @@ package controller import ( "context" apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -79,36 +80,54 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct } // Load the MapUser object by name (its AWS IAM user ARN). - var mapUser awsauthv1beta1.MapUser + mapUser := &awsauthv1beta1.MapUser{} - if err := r.Get(ctx, req.NamespacedName, &mapUser); err != nil { + if err := r.Get(ctx, req.NamespacedName, mapUser); err != nil { // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { logf.Log.Error(err, "failure getting MapUser") return ctrl.Result{}, err } - - if err := awsauthSvc.RemoveMapUser(mapUserName); err != nil { - log.Error(err, "failure removing mapUser data in aws-auth configmap") - return ctrl.Result{}, nil - } - log.Info("removed mapUser data in aws-auth configmap") return ctrl.Result{}, nil } - - // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. - if err := awsauthSvc.UpsertMapUser(mapUser.Name, awsauth.MapUser{ - CrdName: mapUser.Name, - Username: mapUser.Spec.Username, - UserARN: mapUser.Spec.UserARN, - Groups: mapUser.Spec.Groups, - }); err != nil { - log.Error(err, "failure upserting MapUser") - return ctrl.Result{}, err + if mapUser.ObjectMeta.DeletionTimestamp.IsZero() { + logf.Log.Info("mapAccount is not being deleted") + // Add finalizer + if !controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { + logf.Log.Info("mapAccount is not being deleted, so adding finalizer") + controllerutil.AddFinalizer(mapUser, awsauth.CrdFinalizerName) + if err := r.Update(ctx, mapUser); err != nil { + return ctrl.Result{}, err + } + } else { + // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. + if err := awsauthSvc.UpsertMapUser(mapUser.Name, awsauth.MapUser{ + CrdName: mapUser.Name, + Username: mapUser.Spec.Username, + UserARN: mapUser.Spec.UserARN, + Groups: mapUser.Spec.Groups, + }); err != nil { + log.Error(err, "failure upserting MapUser") + return ctrl.Result{}, err + } + log.Info("upserted MapUser") + } + } else { + log.Info("mapUser is being deleted") + if controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { + if err := awsauthSvc.RemoveMapUser(mapUserName); err != nil { + log.Error(err, "failure removing mapUser data in aws-auth configmap") + return ctrl.Result{}, nil + } + logf.Log.Info("mapUser is being deleted, so removing finalizer") + controllerutil.RemoveFinalizer(mapUser, awsauth.CrdFinalizerName) + if err := r.Update(ctx, mapUser); err != nil { + return ctrl.Result{}, err + } + } } - log.Info("upserted MapUser") - + log.Info("removed mapUser data in aws-auth configmap") return ctrl.Result{}, nil } diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index 1118309..ddc1089 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -115,6 +115,13 @@ func (v *MapAccountCustomValidator) ValidateCreate(_ context.Context, obj runtim return nil, err } + if awsauth.CrdItemAllowedNamespace != "" { + if mapaccount.GetNamespace() != awsauth.CrdItemAllowedNamespace { + mapuserlog.Error(nil, "Namespace "+mapaccount.GetNamespace()+" is NOT allowed for creation MapAccount") + return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapAccount", mapaccount.GetNamespace()) + } + } + if err = awsauthSvc.CheckAccountExists(awsauth.MapAccount{ AccountID: mapaccount.Spec.AccountID, }); err != nil { diff --git a/internal/webhook/v1beta1/maprole_webhook.go b/internal/webhook/v1beta1/maprole_webhook.go index b6a7ae0..618f82b 100644 --- a/internal/webhook/v1beta1/maprole_webhook.go +++ b/internal/webhook/v1beta1/maprole_webhook.go @@ -19,6 +19,7 @@ package v1beta1 import ( "context" "fmt" + "github.com/redacid/aws-auth-controller/awsauth" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -94,6 +95,13 @@ func (v *MapRoleCustomValidator) ValidateCreate(_ context.Context, obj runtime.O } maprolelog.Info("Validation for MapRole upon creation", "name", maprole.GetName()) + if awsauth.CrdItemAllowedNamespace != "" { + if maprole.GetNamespace() != awsauth.CrdItemAllowedNamespace { + mapuserlog.Error(nil, "Namespace "+maprole.GetNamespace()+" is NOT allowed for creation MapRole") + return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapRole", maprole.GetNamespace()) + } + } + // TODO(user): fill in your validation logic upon object creation. return nil, nil diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index 7aa9dc4..d8edf2d 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -114,9 +114,9 @@ func (v *MapUserCustomValidator) ValidateCreate(_ context.Context, obj runtime.O // return nil, err //} - //if err := awsauth.VerifyUsername(mapuser.Spec.Username, awsauth.UsernameMustBeEmail); err != nil { - // return nil, err - //} + if err := awsauth.VerifyUsername(mapuser.Spec.Username, awsauth.UsernameMustBeEmail); err != nil { + return nil, err + } //if err := awsauth.VerifyGroups(mapuser.Spec.Groups); err != nil { // return nil, err From b574565d7f4c4dcea05ded7d55c02184e8b29483 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Fri, 11 Jul 2025 10:19:28 +0300 Subject: [PATCH 09/58] user create,update,delete with verification --- awsauth/mapper.go | 2 +- config/samples/aws-auth_v1beta1_mapaccount.yaml | 2 +- internal/controller/maprole_controller.go | 1 + internal/webhook/v1beta1/mapaccount_webhook.go | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 0372dfa..615e6ac 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -127,7 +127,7 @@ func (m *Mapper) existsAuth(args *Arguments) error { } } // TODO - return nil //UpdateAuthMap(m.KubernetesClient, authData, configMap) + return nil } func existsAccount(authMaps []*MapAccount, resource *MapAccount) (error, bool) { diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index e318f3b..923e02a 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -30,4 +30,4 @@ metadata: app.kubernetes.io/managed-by: kustomize name: mapaccount-sample3 spec: - accountid: "333333333333" \ No newline at end of file + accountid: "111111111111" \ No newline at end of file diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index da42455..2aa5ca1 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -55,6 +55,7 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct _ = logf.FromContext(ctx) mapRoleName := req.Name + log := ctrl.Log.WithValues("MapRole", mapRoleName) log.Info("reconciling MapRole...") diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index ddc1089..7490c79 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -135,7 +135,7 @@ func (v *MapAccountCustomValidator) ValidateCreate(_ context.Context, obj runtim // ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type MapAccount. func (v *MapAccountCustomValidator) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { mapaccount, ok := newObj.(*awsauthv1beta1.MapAccount) - oldmapaccount, ok := oldObj.(*awsauthv1beta1.MapAccount) + oldmapaccount, _ := oldObj.(*awsauthv1beta1.MapAccount) if !ok { return nil, fmt.Errorf("expected a MapAccount object for the newObj but got %T", newObj) } From 2b0ad934cf8aa1f32e95ebca8fa4f69cf762cd57 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Fri, 11 Jul 2025 10:47:54 +0300 Subject: [PATCH 10/58] user create,update,delete with verification --- cmd/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index a9ff3fc..0948b90 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -107,14 +107,14 @@ func main() { awsauth.VerifyAWSAccount(mustPresentAccountID) } - VariablesDeclare := awsauth.ControllerArgs{ + declareVariables := awsauth.ControllerArgs{ UsernameMustBeEmail: userNameMustBeEmail, MustPresentAccountID: mustPresentAccountID, CrdItemAllowedNamespace: crdItemAllowedNamespace, ConfigMapName: configMapName, } - awsauth.DeclareVariables(VariablesDeclare) + awsauth.DeclareVariables(declareVariables) // if the enable-http2 flag is false (the default), http/2 should be disabled // due to its vulnerabilities. More specifically, disabling http/2 will From 9bca556c239b56faa3743595fa67db10bd8290b6 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Fri, 11 Jul 2025 10:50:09 +0300 Subject: [PATCH 11/58] user create,update,delete with verification --- cmd/main.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cmd/main.go b/cmd/main.go index 0948b90..7acbcde 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -104,7 +104,11 @@ func main() { ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) if mustPresentAccountID != "" { - awsauth.VerifyAWSAccount(mustPresentAccountID) + err := awsauth.VerifyAWSAccount(mustPresentAccountID) + if err != nil { + setupLog.Error(err, "Error verifying AWS Account ID", "account-id", mustPresentAccountID) + os.Exit(1) + } } declareVariables := awsauth.ControllerArgs{ From 7f24478ceb418de6b96e1e4a2f1d503bd7718e9b Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sat, 12 Jul 2025 14:30:16 +0300 Subject: [PATCH 12/58] reconf MapUser --- Makefile | 2 +- README.md | 4 +- awsauth/data.go | 4 +- awsauth/mapper.go | 79 ++++++++++--------- awsauth/service.go | 51 ++++++++---- config/manager/kustomization.yaml | 2 +- .../samples/aws-auth_v1beta1_mapaccount.yaml | 8 +- config/samples/aws-auth_v1beta1_mapuser.yaml | 28 +++++-- internal/controller/mapuser_controller.go | 13 ++- .../webhook/v1beta1/mapaccount_webhook.go | 2 +- internal/webhook/v1beta1/mapuser_webhook.go | 57 +++++++------ 11 files changed, 153 insertions(+), 97 deletions(-) diff --git a/Makefile b/Makefile index dfcccca..a146054 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.47 +IMG ?= redacid/aws-auth-controller:0.0.61 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/README.md b/README.md index 89edef3..5711d8b 100644 --- a/README.md +++ b/README.md @@ -18,4 +18,6 @@ cd ./config/samples kubectl apply -f aws-auth_v1beta1_maprole.yaml -n kube-syste cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapaccount.yaml -n kube-system https://book.kubebuilder.io/reference/using-finalizers -https://book.kubebuilder.io/reference/markers/crd-validation \ No newline at end of file +https://book.kubebuilder.io/reference/markers/crd-validation + +https://github.com/gp42/aws-auth-operator \ No newline at end of file diff --git a/awsauth/data.go b/awsauth/data.go index 3e1b6c1..476188b 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -197,7 +197,6 @@ func NewMapRole(rolearn, username string, groups []string) *MapRole { // MapUser is the basic structure of a mapUsers authentication object type MapUser struct { - CrdName string `yaml:"crdname"` UserARN string `yaml:"userarn"` Username string `yaml:"username"` Groups []string `yaml:"groups,omitempty"` @@ -232,9 +231,8 @@ func (r *MapUser) SetUsername(v string) *MapUser { } // NewMapUser returns a new NewMapUser -func NewMapUser(crdname, userarn, username string, groups []string) *MapUser { +func NewMapUser(userarn, username string, groups []string) *MapUser { return &MapUser{ - CrdName: crdname, UserARN: userarn, Username: username, Groups: groups, diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 615e6ac..8bf2c36 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -31,7 +31,7 @@ func NewMapper(client kubernetes.Interface, discardLogOutput bool) *Mapper { var mapper = &Mapper{} mapper.KubernetesClient = client - if !discardLogOutput { + if discardLogOutput { log.SetOutput(io.Discard) } return mapper @@ -74,7 +74,7 @@ func (m *Mapper) removeAuth(args *Arguments) error { if args.DataType == MapUserData { var newUsersAuthMap []*MapUser for _, mapUser := range authData.MapUsers { - if args.CrdName != mapUser.CrdName { + if args.Username != mapUser.Username && args.UserARN != mapUser.UserARN { newUsersAuthMap = append(newUsersAuthMap, mapUser) } else { removed = true @@ -82,7 +82,7 @@ func (m *Mapper) removeAuth(args *Arguments) error { } authData.SetMapUsers(newUsersAuthMap) } - // TODO тут якась херня + if args.DataType == MapAccountData { var newAccountsAuthMap []*MapAccount for _, mapAccount := range authData.MapAccounts { @@ -96,7 +96,7 @@ func (m *Mapper) removeAuth(args *Arguments) error { } if !removed { - return fmt.Errorf("%s with account id '%s' not found in auth map", args.DataType, args.AccountID) + return fmt.Errorf("%s with fields '%s' not found in auth map", args.DataType, args) } return UpdateAuthMap(m.KubernetesClient, authData, configMap) } @@ -114,8 +114,9 @@ func (m *Mapper) existsAuth(args *Arguments) error { if err != nil { return err } - log.Printf("authData: %v\n", authData) + if args.DataType == MapAccountData { + log.Printf("authData.MapAccounts: %v\n", authData.MapAccounts) mapAccount := NewMapAccount(args.AccountID) errAccount, exists := existsAccount(authData.MapAccounts, mapAccount) if exists { @@ -126,22 +127,53 @@ func (m *Mapper) existsAuth(args *Arguments) error { return nil } } - // TODO + if args.DataType == MapUserData { + log.Printf("authData.MapUsers: %v\n", authData.MapUsers) + mapUser := NewMapUser(args.UserARN, args.Username, args.Groups) + err, exists := existsUser(authData.MapUsers, mapUser) + if exists { + log.Printf("%v", err) + return err + } else { + log.Printf("%s with username '%s' or userarn '%s' not exists\n", args.DataType, args.Username, args.UserARN) + return nil + } + } return nil } func existsAccount(authMaps []*MapAccount, resource *MapAccount) (error, bool) { - var found bool + var found = false for _, existing := range authMaps { if existing.AccountID == resource.AccountID { found = true return fmt.Errorf("account with id '%s' already exists", resource.AccountID), found } else { found = false - return nil, found + //return nil, found + } + } + return nil, found +} + +func existsUser(authMaps []*MapUser, resource *MapUser) (error, bool) { + var found = false + log.Printf("existsUser check: username: %v userarn:%v \n", resource.Username, resource.UserARN) + for _, existing := range authMaps { + log.Printf("existsUser: cm username: %v userarn: %v \n", existing.Username, existing.UserARN) + log.Printf("existsUser: new username: %v userarn: %v \n", resource.Username, resource.UserARN) + if existing.Username == resource.Username { + found = true + return fmt.Errorf("existsUser: username '%s' already exists", resource.Username), found + } else if existing.UserARN == resource.UserARN { + found = true + return fmt.Errorf("existsUser: userarn '%s' already exists", resource.UserARN), found + } else { + found = false + //return nil, found } } - return nil, false + return nil, found } // Upsert updates or inserts a mapRole or mapUser item into the auth map. @@ -172,7 +204,7 @@ func (m *Mapper) upsertAuth(args *Arguments) error { } if args.DataType == MapUserData { - mapUser := NewMapUser(args.CrdName, args.UserARN, args.Username, args.Groups) + mapUser := NewMapUser(args.UserARN, args.Username, args.Groups) newMap, ok := upsertUser(authData.MapUsers, mapUser) if ok { log.Printf("%s with username '%s' key has been updated\n", args.DataType, args.Username) @@ -224,36 +256,12 @@ func upsertRole(authMaps []*MapRole, resource *MapRole) ([]*MapRole, bool) { func upsertUser(authMaps []*MapUser, resource *MapUser) ([]*MapUser, bool) { var found, updated bool for _, existing := range authMaps { - // Update existing user in auth map. - //if existing.UserARN == resource.UserARN { - // found = true - // if !reflect.DeepEqual(existing.Groups, resource.Groups) { - // existing.SetGroups(resource.Groups) - // updated = true - // } - // if existing.Username != resource.Username { - // existing.SetUsername(resource.Username) - // updated = true - // } - // if existing.UserARN != resource.UserARN { - // existing.SetUserARN(resource.UserARN) - // updated = true - // } - //} - if existing.CrdName == resource.CrdName { + if existing.Username+existing.UserARN == resource.Username+resource.UserARN { found = true if !reflect.DeepEqual(existing.Groups, resource.Groups) { existing.SetGroups(resource.Groups) updated = true } - if existing.Username != resource.Username { - existing.SetUsername(resource.Username) - updated = true - } - if existing.UserARN != resource.UserARN { - existing.SetUserARN(resource.UserARN) - updated = true - } } } @@ -293,7 +301,6 @@ type Arguments struct { AccountID string RoleARN string UserARN string - CrdName string Username string Groups []string WithRetries bool diff --git a/awsauth/service.go b/awsauth/service.go index c6face9..063d4d9 100644 --- a/awsauth/service.go +++ b/awsauth/service.go @@ -43,13 +43,16 @@ type Service interface { RemoveMapRole(username string) error // UpsertMapUser upserts a MapUser into the configmap keyed by username. - UpsertMapUser(username string, mapUser MapUser) error + UpsertMapUser(mapUser MapUser) error // RemoveMapUser removes a MapUser from the configmap keyed by username - RemoveMapUser(username string) error + RemoveMapUser(mapUser MapUser) error - // CheckAccountExists checks if an account with the specified account ID exists. - CheckAccountExists(mapAccount MapAccount) error + // CheckMapAccountExists checks if an MapAccount with the specified account ID exists. + CheckMapAccountExists(mapAccount MapAccount) error + + // CheckMapUserExists checks if an MapUser with the specified username and userarn ID exists. + CheckMapUserExists(mapUser MapUser) error // UpsertMapAccount upserts a mapAccount into the configmap keyed by username. UpsertMapAccount(mapAccount MapAccount) error @@ -108,14 +111,30 @@ func (svc impl) RemoveMapRole(username string) error { return err } +func (svc impl) CheckMapUserExists(mapUser MapUser) error { + svc.cfg.Log.Info("CheckMapUserExists", "username", mapUser.Username, "userarn", mapUser.UserARN) + mapper := NewMapper(svc.cfg.KubeClient, false) + err := mapper.CheckExists(&Arguments{ + DataType: MapUserData, + Username: mapUser.Username, + UserARN: mapUser.UserARN, + WithRetries: svc.cfg.WithRetries, + MaxRetryCount: svc.cfg.MaxRetryCount, + MaxRetryTime: svc.cfg.MaxRetryTime, + MinRetryTime: svc.cfg.MinRetryTime, + }) + if err != nil { + svc.cfg.Log.Info("username or userarn already exists", "username", mapUser.Username, "userarn", mapUser.UserARN) + } + return err +} + // UpsertMapUser upserts a MapUser into the configmap keyed by username. -func (svc impl) UpsertMapUser(username string, mapUser MapUser) error { +func (svc impl) UpsertMapUser(mapUser MapUser) error { mapper := NewMapper(svc.cfg.KubeClient, false) err := mapper.Upsert(&Arguments{ - DataType: MapUserData, - UserARN: mapUser.UserARN, - // Username: username, - CrdName: username, + DataType: MapUserData, + UserARN: mapUser.UserARN, Username: mapUser.Username, Groups: mapUser.Groups, WithRetries: svc.cfg.WithRetries, @@ -124,30 +143,30 @@ func (svc impl) UpsertMapUser(username string, mapUser MapUser) error { MinRetryTime: svc.cfg.MinRetryTime, }) if err != nil { - svc.cfg.Log.Error(err, "failure to upsert mapUser", "username", username) + svc.cfg.Log.Error(err, "failure to upsert mapUser", "username", mapUser.Username, "userarn", mapUser.UserARN) } return err } // RemoveMapUser removes a MapUser from the configmap keyed by username. -func (svc impl) RemoveMapUser(username string) error { +func (svc impl) RemoveMapUser(mapUser MapUser) error { mapper := NewMapper(svc.cfg.KubeClient, false) err := mapper.Remove(&Arguments{ - DataType: MapUserData, - //Username: username, - CrdName: username, + DataType: MapUserData, + Username: mapUser.Username, + UserARN: mapUser.UserARN, WithRetries: svc.cfg.WithRetries, MaxRetryCount: svc.cfg.MaxRetryCount, MaxRetryTime: svc.cfg.MaxRetryTime, MinRetryTime: svc.cfg.MinRetryTime, }) if err != nil { - svc.cfg.Log.Info("mapUser not found", "username", username) + svc.cfg.Log.Info("mapUser not found", "username", mapUser.Username, "userarn", mapUser.UserARN) } return err } -func (svc impl) CheckAccountExists(mapAccount MapAccount) error { +func (svc impl) CheckMapAccountExists(mapAccount MapAccount) error { svc.cfg.Log.Info("CheckAccountExists", "accountid", mapAccount.AccountID) mapper := NewMapper(svc.cfg.KubeClient, false) err := mapper.CheckExists(&Arguments{ diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index af1a57e..8e0a149 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller - newTag: 0.0.47 + newTag: 0.0.61 diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index 923e02a..1e37e19 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: mapaccount-sample1 + name: account1 spec: accountid: "111111111111" @@ -16,7 +16,7 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: mapaccount-sample2 + name: account2 spec: accountid: "222222222222" @@ -28,6 +28,6 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: mapaccount-sample3 + name: account4 spec: - accountid: "111111111111" \ No newline at end of file + accountid: "222222222222" \ No newline at end of file diff --git a/config/samples/aws-auth_v1beta1_mapuser.yaml b/config/samples/aws-auth_v1beta1_mapuser.yaml index 437bb20..a90e21c 100644 --- a/config/samples/aws-auth_v1beta1_mapuser.yaml +++ b/config/samples/aws-auth_v1beta1_mapuser.yaml @@ -4,14 +4,14 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: test + name: user1 spec: description: A test mapuser - username: test.user@ios.in.ua + username: user1@ios.in.ua groups: - system:masters - admins - userarn: arn:aws:iam::123456789012:user/sample-mapuser + userarn: arn:aws:iam::123456789012:user/user1 --- apiVersion: aws-auth.prozorro.sale/v1beta1 @@ -20,11 +20,27 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: test2 + name: user2 spec: description: A test mapuser - username: test2.user@ios.in.ua + username: user2@ios.in.ua groups: - system:masters - admins - userarn: arn:aws:iam::123456789012:user/sample-mapuser2 + userarn: arn:aws:iam::123456789012:user/user2 + +--- +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapUser +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: user3 +spec: + description: A test mapuser + username: user3@ios.in.ua + groups: + - system:masters + - users + userarn: arn:aws:iam::123456789012:user/user2 \ No newline at end of file diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index b3aee62..64dbfd0 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -102,8 +102,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct } } else { // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. - if err := awsauthSvc.UpsertMapUser(mapUser.Name, awsauth.MapUser{ - CrdName: mapUser.Name, + if err := awsauthSvc.UpsertMapUser(awsauth.MapUser{ Username: mapUser.Spec.Username, UserARN: mapUser.Spec.UserARN, Groups: mapUser.Spec.Groups, @@ -116,7 +115,11 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct } else { log.Info("mapUser is being deleted") if controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { - if err := awsauthSvc.RemoveMapUser(mapUserName); err != nil { + if err := awsauthSvc.RemoveMapUser(awsauth.MapUser{ + Username: mapUser.Spec.Username, + UserARN: mapUser.Spec.UserARN, + Groups: mapUser.Spec.Groups, + }); err != nil { log.Error(err, "failure removing mapUser data in aws-auth configmap") return ctrl.Result{}, nil } @@ -126,8 +129,10 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct return ctrl.Result{}, err } } + log.Info("removed mapUser data in aws-auth configmap") + return ctrl.Result{}, nil } - log.Info("removed mapUser data in aws-auth configmap") + return ctrl.Result{}, nil } diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index 7490c79..4660071 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -122,7 +122,7 @@ func (v *MapAccountCustomValidator) ValidateCreate(_ context.Context, obj runtim } } - if err = awsauthSvc.CheckAccountExists(awsauth.MapAccount{ + if err = awsauthSvc.CheckMapAccountExists(awsauth.MapAccount{ AccountID: mapaccount.Spec.AccountID, }); err != nil { mapaccountlog.Info("Failure checking, account exists in aws-auth configmap") diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index d8edf2d..a54f175 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -19,7 +19,7 @@ package v1beta1 import ( "context" "fmt" - "github.com/redacid/aws-auth-controller/awsauth" + "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" @@ -27,8 +27,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" - _ "github.com/redacid/aws-auth-controller/awsauth" - _ "github.com/redacid/aws-auth-controller/kube" + "github.com/redacid/aws-auth-controller/awsauth" + "github.com/redacid/aws-auth-controller/kube" ) // nolint:unused @@ -103,26 +103,43 @@ func (v *MapUserCustomValidator) ValidateCreate(_ context.Context, obj runtime.O "Namespace", mapuser.GetNamespace(), ) + kubeClient, err := kube.GetClient() + if err != nil { + mapuserlog.Error(err, "Failure getting kube client") + return nil, err + } + + // Get a new aws auth service object. + awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ + KubeClient: kubeClient, + Log: ctrl.Log, + }) + if err != nil { + mapuserlog.Error(err, "Failure creating new aws auth service") + return nil, err + } + if awsauth.CrdItemAllowedNamespace != "" { if mapuser.GetNamespace() != awsauth.CrdItemAllowedNamespace { mapuserlog.Error(nil, "Namespace "+mapuser.GetNamespace()+" is NOT allowed for creation MapUser") return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapUser", mapuser.GetNamespace()) } } - // Validate fields - //if err := awsauth.VerifyUserARN(mapuser.Spec.UserARN); err != nil { - // return nil, err - //} if err := awsauth.VerifyUsername(mapuser.Spec.Username, awsauth.UsernameMustBeEmail); err != nil { return nil, err } - //if err := awsauth.VerifyGroups(mapuser.Spec.Groups); err != nil { - // return nil, err - //} - - // TODO(user): fill in your validation logic upon object creation. + if err := awsauthSvc.CheckMapUserExists(awsauth.MapUser{ + Username: mapuser.Spec.Username, + UserARN: mapuser.Spec.UserARN, + Groups: mapuser.Spec.Groups, + }); err != nil { + mapuserlog.Info("Failure checking, username or userarn exists in aws-auth configmap") + return nil, fmt.Errorf("failure checking, username %v or userarn %v exists in aws-auth configmap", mapuser.Spec.Username, mapuser.Spec.UserARN) + } else { + mapuserlog.Info("username and userarn not exists in aws-auth configmap") + } return nil, nil } @@ -152,25 +169,17 @@ func (v *MapUserCustomValidator) ValidateUpdate(_ context.Context, oldObj, newOb "Namespace", mapuser.GetNamespace(), ) - if mapuser.GetNamespace() != "kube-system" { - mapuserlog.Error(nil, "Namespace "+mapuser.GetNamespace()+" is NOT allowed for creation MapUser") - return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapUser", mapuser.GetNamespace()) - } - // Validate fields - if err := awsauth.VerifyUserARN(mapuser.Spec.UserARN); err != nil { - return nil, err + if (mapuser.Spec.Username != oldmapuser.Spec.Username) && (mapuser.Spec.Username != "") { + return nil, fmt.Errorf("Username cannot be changed, pls create a new MapUser with the new Username, only change Groups allowed") } - - if err := awsauth.VerifyUsername(mapuser.Spec.Username, awsauth.UsernameMustBeEmail); err != nil { - return nil, err + if (mapuser.Spec.UserARN != oldmapuser.Spec.UserARN) && (mapuser.Spec.UserARN != "") { + return nil, fmt.Errorf("UserARN cannot be changed, pls create a new MapUser with the new UserARN, only change Groups allowed") } if err := awsauth.VerifyGroups(mapuser.Spec.Groups); err != nil { return nil, err } - // TODO(user): fill in your validation logic upon object update. - return nil, nil } From 45f263a1d700b6567110074c51854b3fc2034c5f Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sat, 12 Jul 2025 19:32:53 +0300 Subject: [PATCH 13/58] add checking data in already created MapUser resources for duplicates --- Makefile | 2 +- awsauth/{verify.go => common.go} | 0 awsauth/data.go | 23 ++-- awsauth/mapper.go | 130 +++++++++--------- config/manager/kustomization.yaml | 2 +- .../samples/aws-auth_v1beta1_mapaccount.yaml | 2 +- config/samples/aws-auth_v1beta1_mapuser.yaml | 2 +- internal/controller/mapaccount_controller.go | 3 +- internal/controller/mapuser_controller.go | 3 +- .../webhook/v1beta1/mapaccount_webhook.go | 12 +- internal/webhook/v1beta1/mapuser_webhook.go | 54 ++++++-- 11 files changed, 135 insertions(+), 98 deletions(-) rename awsauth/{verify.go => common.go} (100%) diff --git a/Makefile b/Makefile index a146054..81757d6 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.61 +IMG ?= redacid/aws-auth-controller:0.0.69 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/awsauth/verify.go b/awsauth/common.go similarity index 100% rename from awsauth/verify.go rename to awsauth/common.go diff --git a/awsauth/data.go b/awsauth/data.go index 476188b..7fc0711 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -18,14 +18,13 @@ package awsauth import ( "context" "fmt" - "log" - "strings" - "gopkg.in/yaml.v2" kcorev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" + "log" + "strings" ) func init() { @@ -37,15 +36,14 @@ const ( ConfigMapNamespace = "kube-system" ) -var ConfigMapName = "aws-auth" - -var CrdFinalizerName = "aws-auth.prozorro.sale/finalizer" -var UsernameMustBeEmail = false - -// TODO automatic add to configmap -var MustPresentAccountID string = "" - -var CrdItemAllowedNamespace string = "" +var ( + ConfigMapName = "aws-auth" + CrdFinalizerName = "aws-auth.prozorro.sale/finalizer" + UsernameMustBeEmail = false + // TODO automatic add to configmap + MustPresentAccountID string = "" + CrdItemAllowedNamespace string = "" +) type ControllerArgs struct { UsernameMustBeEmail bool @@ -63,6 +61,7 @@ func DeclareVariables(controllerArgs ControllerArgs) { // ReadAuthMap reads the auth ConfigMap and returns AwsAuthData and the read ConfigMap. func ReadAuthMap(k kubernetes.Interface) (AwsAuthData, *kcorev1.ConfigMap, error) { + var authData AwsAuthData cm, err := k.CoreV1().ConfigMaps(ConfigMapNamespace).Get(context.Background(), ConfigMapName, apismetav1.GetOptions{}) diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 8bf2c36..ed8fa5f 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -26,6 +26,67 @@ import ( "k8s.io/client-go/kubernetes" ) +// Arguments are the arguments for management of the auth map. +type Arguments struct { + OperationType OperationType + DataType DataType + AccountID string + RoleARN string + UserARN string + Username string + Groups []string + WithRetries bool + MinRetryTime time.Duration + MaxRetryTime time.Duration + MaxRetryCount int +} + +// Validate validates if all Arguments fields are valid. +func (args *Arguments) Validate() { + if args.WithRetries && args.MaxRetryCount < 1 { + log.Println("error: retry max count is invalid, must be greater than zero") + } + if args.Username == "" { + log.Println("error: username not provided") + } + if args.OperationType == "" { + log.Println("error: operation type not provided") + } + if args.OperationType != UpsertOperation && args.OperationType != RemoveOperation { + log.Printf("error: operation type '%s' not valid\n", args.OperationType) + } + if args.DataType == "" { + log.Println("error: data type not provided") + } + if args.DataType != MapRoleData && args.DataType != MapUserData && args.DataType != MapAccountData { + log.Printf("error: data type '%s' not valid\n", args.DataType) + } + if args.OperationType == UpsertOperation && args.DataType == MapRoleData && args.RoleARN == "" { + log.Println("error: role arn not provided") + } + if args.OperationType == UpsertOperation && args.DataType == MapUserData && args.UserARN == "" { + log.Println("error: user arn not provided") + } +} + +// OperationType indicates the auth map management operation. +type OperationType string + +const ( + UpsertOperation OperationType = "upsert" + RemoveOperation OperationType = "remove" + CheckExistsOperation OperationType = "checkExists" +) + +// DataType indicates the auth map management scope. +type DataType string + +const ( + MapRoleData DataType = "mapRole" + MapUserData DataType = "mapUser" + MapAccountData DataType = "mapAccount" +) + // NewMapper returns a new Mapper object. func NewMapper(client kubernetes.Interface, discardLogOutput bool) *Mapper { var mapper = &Mapper{} @@ -118,10 +179,10 @@ func (m *Mapper) existsAuth(args *Arguments) error { if args.DataType == MapAccountData { log.Printf("authData.MapAccounts: %v\n", authData.MapAccounts) mapAccount := NewMapAccount(args.AccountID) - errAccount, exists := existsAccount(authData.MapAccounts, mapAccount) + err, exists := existsAccount(authData.MapAccounts, mapAccount) if exists { - log.Printf("%s with account id '%s' already exists\n", args.DataType, args.AccountID) - return errAccount + log.Printf("%v", err) + return err } else { log.Printf("%s with account id '%s' not exists\n", args.DataType, args.AccountID) return nil @@ -144,7 +205,10 @@ func (m *Mapper) existsAuth(args *Arguments) error { func existsAccount(authMaps []*MapAccount, resource *MapAccount) (error, bool) { var found = false + log.Printf("existsAccount check: account id: %v \n", resource.AccountID) for _, existing := range authMaps { + log.Printf("existsAccount: cm account id: %v \n", existing.AccountID) + log.Printf("existsAccount: new account id: %v \n", resource.AccountID) if existing.AccountID == resource.AccountID { found = true return fmt.Errorf("account with id '%s' already exists", resource.AccountID), found @@ -293,63 +357,3 @@ func upsertAccount(authMaps []*MapAccount, resource *MapAccount) ([]*MapAccount, } return authMaps, updated } - -// Arguments are the arguments for management of the auth map. -type Arguments struct { - OperationType OperationType - DataType DataType - AccountID string - RoleARN string - UserARN string - Username string - Groups []string - WithRetries bool - MinRetryTime time.Duration - MaxRetryTime time.Duration - MaxRetryCount int -} - -// Validate validates if all Arguments fields are valid. -func (args *Arguments) Validate() { - if args.WithRetries && args.MaxRetryCount < 1 { - log.Println("error: retry max count is invalid, must be greater than zero") - } - if args.Username == "" { - log.Println("error: username not provided") - } - if args.OperationType == "" { - log.Println("error: operation type not provided") - } - if args.OperationType != UpsertOperation && args.OperationType != RemoveOperation { - log.Printf("error: operation type '%s' not valid\n", args.OperationType) - } - if args.DataType == "" { - log.Println("error: data type not provided") - } - if args.DataType != MapRoleData && args.DataType != MapUserData { - log.Printf("error: data type '%s' not valid\n", args.DataType) - } - if args.OperationType == UpsertOperation && args.DataType == MapRoleData && args.RoleARN == "" { - log.Println("error: role arn not provided") - } - if args.OperationType == UpsertOperation && args.DataType == MapUserData && args.UserARN == "" { - log.Println("error: user arn not provided") - } -} - -// OperationType indicates the auth map management operation. -type OperationType string - -const ( - UpsertOperation OperationType = "upsert" - RemoveOperation OperationType = "remove" -) - -// DataType indicates the auth map management scope. -type DataType string - -const ( - MapRoleData DataType = "mapRole" - MapUserData DataType = "mapUser" - MapAccountData DataType = "mapAccount" -) diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 8e0a149..14649a8 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller - newTag: 0.0.61 + newTag: 0.0.69 diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index 1e37e19..c138b74 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -28,6 +28,6 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: account4 + name: account3 spec: accountid: "222222222222" \ No newline at end of file diff --git a/config/samples/aws-auth_v1beta1_mapuser.yaml b/config/samples/aws-auth_v1beta1_mapuser.yaml index a90e21c..1e7e87c 100644 --- a/config/samples/aws-auth_v1beta1_mapuser.yaml +++ b/config/samples/aws-auth_v1beta1_mapuser.yaml @@ -39,7 +39,7 @@ metadata: name: user3 spec: description: A test mapuser - username: user3@ios.in.ua + username: user2@ios.in.ua groups: - system:masters - users diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 8c90d7c..0200572 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -72,7 +72,8 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ KubeClient: kubeClient, //Log: r.Log, - Log: ctrl.Log, + Log: ctrl.Log, + MaxRetryCount: 5, }) if err != nil { log.Error(err, "Failure creating new aws auth service") diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index 64dbfd0..5744118 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -72,7 +72,8 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ KubeClient: kubeClient, //Log: r.Log, - Log: ctrl.Log, + Log: ctrl.Log, + MaxRetryCount: 5, }) if err != nil { log.Error(err, "failure creating new aws auth service") diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index 4660071..0e53a1c 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -21,19 +21,22 @@ import ( "fmt" "github.com/redacid/aws-auth-controller/awsauth" "github.com/redacid/aws-auth-controller/kube" - "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "time" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" ) // nolint:unused // log is for logging in this package. -var mapaccountlog = logf.Log.WithName("mapaccount-resource") +var ( + //mapAccountMutex sync.Mutex + mapaccountlog = logf.Log.WithName("mapaccount-resource") +) // SetupMapAccountWebhookWithManager registers the webhook for MapAccount in the manager. func SetupMapAccountWebhookWithManager(mgr ctrl.Manager) error { @@ -90,6 +93,11 @@ var _ webhook.CustomValidator = &MapAccountCustomValidator{} // ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type MapAccount. func (v *MapAccountCustomValidator) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) { + // This wait need for write to configmap + //mapAccountMutex.Lock() + //defer mapAccountMutex.Unlock() + time.Sleep(100 * time.Millisecond) + mapaccount, ok := obj.(*awsauthv1beta1.MapAccount) if !ok { return nil, fmt.Errorf("expected a MapAccount object but got %T", obj) diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index a54f175..f086cfd 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -19,26 +19,33 @@ package v1beta1 import ( "context" "fmt" - + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + "github.com/redacid/aws-auth-controller/awsauth" + "github.com/redacid/aws-auth-controller/kube" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - - awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" - "github.com/redacid/aws-auth-controller/awsauth" - "github.com/redacid/aws-auth-controller/kube" + "time" ) // nolint:unused // log is for logging in this package. -var mapuserlog = logf.Log.WithName("mapuser-resource") +var ( + mapuserlog = logf.Log.WithName("mapuser-resource") +) // SetupMapUserWebhookWithManager registers the webhook for MapUser in the manager. func SetupMapUserWebhookWithManager(mgr ctrl.Manager) error { + validator := &MapUserCustomValidator{ + Client: mgr.GetClient(), + } + return ctrl.NewWebhookManagedBy(mgr).For(&awsauthv1beta1.MapUser{}). - WithValidator(&MapUserCustomValidator{}). + // WithValidator(&MapUserCustomValidator{}). + WithValidator(validator). WithDefaulter(&MapUserCustomDefaulter{}). Complete() } @@ -84,12 +91,16 @@ func (d *MapUserCustomDefaulter) Default(_ context.Context, obj runtime.Object) // as this struct is used only for temporary operations and does not need to be deeply copied. type MapUserCustomValidator struct { // TODO(user): Add more fields as needed for validation + Client client.Client } var _ webhook.CustomValidator = &MapUserCustomValidator{} // ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type MapUser. -func (v *MapUserCustomValidator) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) { +func (v *MapUserCustomValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { + // This wait need for write to configmap + time.Sleep(100 * time.Millisecond) + mapuser, ok := obj.(*awsauthv1beta1.MapUser) if !ok { return nil, fmt.Errorf("expected a MapUser object but got %T", obj) @@ -103,6 +114,26 @@ func (v *MapUserCustomValidator) ValidateCreate(_ context.Context, obj runtime.O "Namespace", mapuser.GetNamespace(), ) + if awsauth.CrdItemAllowedNamespace != "" { + if mapuser.GetNamespace() != awsauth.CrdItemAllowedNamespace { + mapuserlog.Error(nil, "Namespace "+mapuser.GetNamespace()+" is NOT allowed for creation MapUser") + return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapUser", mapuser.GetNamespace()) + } + } + // ----- + var mapUserList awsauthv1beta1.MapUserList + if err := v.Client.List(ctx, &mapUserList); err != nil { + return nil, err + } + for _, existingUser := range mapUserList.Items { + if existingUser.Spec.Username == mapuser.Spec.Username || + existingUser.Spec.UserARN == mapuser.Spec.UserARN { + return nil, fmt.Errorf("duplicate user data found: username %s or userarn %s already exists in another MapUser resource: %s", + mapuser.Spec.Username, mapuser.Spec.UserARN, existingUser.GetName()) + } + } + // ----- + kubeClient, err := kube.GetClient() if err != nil { mapuserlog.Error(err, "Failure getting kube client") @@ -119,13 +150,6 @@ func (v *MapUserCustomValidator) ValidateCreate(_ context.Context, obj runtime.O return nil, err } - if awsauth.CrdItemAllowedNamespace != "" { - if mapuser.GetNamespace() != awsauth.CrdItemAllowedNamespace { - mapuserlog.Error(nil, "Namespace "+mapuser.GetNamespace()+" is NOT allowed for creation MapUser") - return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapUser", mapuser.GetNamespace()) - } - } - if err := awsauth.VerifyUsername(mapuser.Spec.Username, awsauth.UsernameMustBeEmail); err != nil { return nil, err } From 4cb8d0d1760fe99e5f82d6bb2b0764bb9a34d861 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sat, 12 Jul 2025 19:36:22 +0300 Subject: [PATCH 14/58] add checking data in already created MapUser resources for duplicates --- awsauth/mapper.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/awsauth/mapper.go b/awsauth/mapper.go index ed8fa5f..08510ea 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -73,9 +73,9 @@ func (args *Arguments) Validate() { type OperationType string const ( - UpsertOperation OperationType = "upsert" - RemoveOperation OperationType = "remove" - CheckExistsOperation OperationType = "checkExists" + UpsertOperation OperationType = "upsert" + RemoveOperation OperationType = "remove" + // CheckExistsOperation OperationType = "checkExists" ) // DataType indicates the auth map management scope. @@ -105,7 +105,8 @@ type Mapper struct { // Remove removes a mapRole or mapUser from the auth map. func (m *Mapper) Remove(args *Arguments) error { - args.Validate() + // TODO Remove this validate + // args.Validate() if args.WithRetries { return WithRetry(m.removeAuth, args) } @@ -243,7 +244,7 @@ func existsUser(authMaps []*MapUser, resource *MapUser) (error, bool) { // Upsert updates or inserts a mapRole or mapUser item into the auth map. func (m *Mapper) Upsert(args *Arguments) error { // TODO Remove this validate - args.Validate() + // args.Validate() if args.WithRetries { return WithRetry(m.upsertAuth, args) } From 6098f0923b03c549fd51d7a811001566f464cfab Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sat, 12 Jul 2025 20:07:28 +0300 Subject: [PATCH 15/58] clean --- Makefile | 2 +- config/manager/kustomization.yaml | 2 +- .../webhook/v1beta1/mapaccount_webhook.go | 52 ++++++++++++------- internal/webhook/v1beta1/mapuser_webhook.go | 6 +-- 4 files changed, 36 insertions(+), 26 deletions(-) diff --git a/Makefile b/Makefile index 81757d6..6915f0f 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller:0.0.69 +IMG ?= redacid/aws-auth-controller-dev:0.0.69 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 14649a8..934a3c5 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -4,5 +4,5 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization images: - name: controller - newName: redacid/aws-auth-controller + newName: redacid/aws-auth-controller-dev newTag: 0.0.69 diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index 0e53a1c..5930c2a 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -23,6 +23,7 @@ import ( "github.com/redacid/aws-auth-controller/kube" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" @@ -34,14 +35,17 @@ import ( // nolint:unused // log is for logging in this package. var ( - //mapAccountMutex sync.Mutex mapaccountlog = logf.Log.WithName("mapaccount-resource") ) // SetupMapAccountWebhookWithManager registers the webhook for MapAccount in the manager. func SetupMapAccountWebhookWithManager(mgr ctrl.Manager) error { + validator := &MapUserCustomValidator{ + Client: mgr.GetClient(), + } return ctrl.NewWebhookManagedBy(mgr).For(&awsauthv1beta1.MapAccount{}). - WithValidator(&MapAccountCustomValidator{}). + // WithValidator(&MapAccountCustomValidator{}). + WithValidator(validator). WithDefaulter(&MapAccountCustomDefaulter{}). Complete() } @@ -70,8 +74,6 @@ func (d *MapAccountCustomDefaulter) Default(_ context.Context, obj runtime.Objec } mapaccountlog.Info("Defaulting for MapAccount", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) - // TODO(user): fill in your defaulting logic. - return nil } @@ -86,25 +88,45 @@ func (d *MapAccountCustomDefaulter) Default(_ context.Context, obj runtime.Objec // NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods, // as this struct is used only for temporary operations and does not need to be deeply copied. type MapAccountCustomValidator struct { - // TODO(user): Add more fields as needed for validation + Client client.Client } var _ webhook.CustomValidator = &MapAccountCustomValidator{} // ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type MapAccount. -func (v *MapAccountCustomValidator) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) { +func (v *MapAccountCustomValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { // This wait need for write to configmap - //mapAccountMutex.Lock() - //defer mapAccountMutex.Unlock() time.Sleep(100 * time.Millisecond) mapaccount, ok := obj.(*awsauthv1beta1.MapAccount) if !ok { return nil, fmt.Errorf("expected a MapAccount object but got %T", obj) } - mapaccountlog.Info("Validation for MapAccount upon creation", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) + mapaccountlog.Info("Validation for MapAccount upon creation", + "name", + mapaccount.GetName(), + "AccountID", mapaccount.Spec, + ) + + if awsauth.CrdItemAllowedNamespace != "" { + if mapaccount.GetNamespace() != awsauth.CrdItemAllowedNamespace { + mapuserlog.Error(nil, "Namespace "+mapaccount.GetNamespace()+" is NOT allowed for creation MapAccount") + return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapAccount", mapaccount.GetNamespace()) + } + } - // TODO(user): fill in your validation logic upon object creation. + // ----- + var mapAccountList awsauthv1beta1.MapAccountList + if err := v.Client.List(ctx, &mapAccountList); err != nil { + return nil, err + } + for _, existingAccount := range mapAccountList.Items { + if existingAccount.Spec.AccountID == mapaccount.Spec.AccountID { + return nil, fmt.Errorf("duplicate account data found: account id %s already exists in another MapAccount resource: %s", + mapaccount.Spec.AccountID, existingAccount.GetName()) + } + } + // ----- kubeClient, err := kube.GetClient() if err != nil { @@ -123,18 +145,11 @@ func (v *MapAccountCustomValidator) ValidateCreate(_ context.Context, obj runtim return nil, err } - if awsauth.CrdItemAllowedNamespace != "" { - if mapaccount.GetNamespace() != awsauth.CrdItemAllowedNamespace { - mapuserlog.Error(nil, "Namespace "+mapaccount.GetNamespace()+" is NOT allowed for creation MapAccount") - return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapAccount", mapaccount.GetNamespace()) - } - } - if err = awsauthSvc.CheckMapAccountExists(awsauth.MapAccount{ AccountID: mapaccount.Spec.AccountID, }); err != nil { mapaccountlog.Info("Failure checking, account exists in aws-auth configmap") - return nil, fmt.Errorf("Failure checking, accountid %v exists in aws-auth configmap", mapaccount.Spec.AccountID) + return nil, fmt.Errorf("failure checking, accountid %v exists in aws-auth configmap", mapaccount.Spec.AccountID) } return nil, nil @@ -149,7 +164,6 @@ func (v *MapAccountCustomValidator) ValidateUpdate(_ context.Context, oldObj, ne } mapaccountlog.Info("Validation for MapAccount upon update", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) - // TODO(user): fill in your validation logic upon object update. if (mapaccount.Spec.AccountID != oldmapaccount.Spec.AccountID) && (mapaccount.Spec.AccountID != "") { return nil, fmt.Errorf("AccountID cannot be changed, pls create a new MapAccount with the new AccountID") } diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index f086cfd..97c4b30 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -74,8 +74,6 @@ func (d *MapUserCustomDefaulter) Default(_ context.Context, obj runtime.Object) } mapuserlog.Info("Defaulting for MapUser", "name", mapuser.GetName()) - // TODO(user): fill in your defaulting logic. - return nil } @@ -90,7 +88,6 @@ func (d *MapUserCustomDefaulter) Default(_ context.Context, obj runtime.Object) // NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods, // as this struct is used only for temporary operations and does not need to be deeply copied. type MapUserCustomValidator struct { - // TODO(user): Add more fields as needed for validation Client client.Client } @@ -194,7 +191,7 @@ func (v *MapUserCustomValidator) ValidateUpdate(_ context.Context, oldObj, newOb ) if (mapuser.Spec.Username != oldmapuser.Spec.Username) && (mapuser.Spec.Username != "") { - return nil, fmt.Errorf("Username cannot be changed, pls create a new MapUser with the new Username, only change Groups allowed") + return nil, fmt.Errorf("username cannot be changed, pls create a new MapUser with the new Username, only change Groups allowed") } if (mapuser.Spec.UserARN != oldmapuser.Spec.UserARN) && (mapuser.Spec.UserARN != "") { return nil, fmt.Errorf("UserARN cannot be changed, pls create a new MapUser with the new UserARN, only change Groups allowed") @@ -225,7 +222,6 @@ func (v *MapUserCustomValidator) ValidateDelete(ctx context.Context, obj runtime "name", mapuser.GetName(), "UserARN", mapuser.Spec.UserARN, ) - // TODO(user): fill in your validation logic upon object deletion. return nil, nil } From de347399400adbca64cefe70e6e8d3ac02264270 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sat, 12 Jul 2025 20:22:26 +0300 Subject: [PATCH 16/58] clean --- awsauth/data.go | 4 +++- awsauth/data_test.go | 6 +++--- awsauth/mapper.go | 2 +- internal/controller/mapaccount_controller.go | 7 ++++--- internal/controller/maprole_controller.go | 2 +- internal/controller/mapuser_controller.go | 3 ++- internal/webhook/v1beta1/mapaccount_webhook.go | 4 +++- internal/webhook/v1beta1/maprole_webhook.go | 2 +- internal/webhook/v1beta1/mapuser_webhook.go | 11 +++++++---- 9 files changed, 25 insertions(+), 16 deletions(-) diff --git a/awsauth/data.go b/awsauth/data.go index 7fc0711..d7a8801 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -18,12 +18,14 @@ package awsauth import ( "context" "fmt" + "log" + "gopkg.in/yaml.v2" kcorev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" apismetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" - "log" + "strings" ) diff --git a/awsauth/data_test.go b/awsauth/data_test.go index cbd489e..f67c44d 100644 --- a/awsauth/data_test.go +++ b/awsauth/data_test.go @@ -32,8 +32,9 @@ func createMockConfigMap(client kubernetes.Interface) { "system:node:{{EC2PrivateDNSName}}", []string{"system:bootstrappers", "system:nodes"}) - user := NewMapUser("testcrd", "arn:aws:iam::00000000000:user/user-1", - "admin", + user := NewMapUser( + "arn:aws:iam::00000000000:user/user-1", + "testcrd", []string{"system:masters"}) configMap := &v1.ConfigMap{ @@ -68,7 +69,6 @@ func TestUpdateAuthMap(t *testing.T) { "system:node:{{EC2PrivateDNSName}}", []string{"system:bootstrappers", "system:nodes"}) user := NewMapUser("testcrd", "arn:aws:iam::00000000000:user/user-2", - "ops-user", []string{"system:masters"}) auth.MapRoles = append(auth.MapRoles, role) diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 08510ea..ff43120 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -158,7 +158,7 @@ func (m *Mapper) removeAuth(args *Arguments) error { } if !removed { - return fmt.Errorf("%s with fields '%s' not found in auth map", args.DataType, args) + return fmt.Errorf("%s with fields '%v' not found in auth map", args.DataType, args) } return UpdateAuthMap(m.KubernetesClient, authData, configMap) } diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 0200572..02e8936 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -18,8 +18,7 @@ package controller import ( "context" - "github.com/redacid/aws-auth-controller/awsauth" - "github.com/redacid/aws-auth-controller/kube" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -28,6 +27,8 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + "github.com/redacid/aws-auth-controller/awsauth" + "github.com/redacid/aws-auth-controller/kube" ) // MapAccountReconciler reconciles a MapAccount object @@ -93,7 +94,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) return ctrl.Result{}, nil } // examine DeletionTimestamp to determine if object is under deletion - if mapAccount.ObjectMeta.DeletionTimestamp.IsZero() { + if mapAccount.DeletionTimestamp.IsZero() { logf.Log.Info("mapAccount is not being deleted") // Add finalizer if !controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index 2aa5ca1..3c98dad 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -18,8 +18,8 @@ package controller import ( "context" - apierrors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index 5744118..5a595e8 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -18,6 +18,7 @@ package controller import ( "context" + apierrors "k8s.io/apimachinery/pkg/api/errors" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" @@ -92,7 +93,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct } return ctrl.Result{}, nil } - if mapUser.ObjectMeta.DeletionTimestamp.IsZero() { + if mapUser.DeletionTimestamp.IsZero() { logf.Log.Info("mapAccount is not being deleted") // Add finalizer if !controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index 5930c2a..be3c4b4 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -19,6 +19,9 @@ package v1beta1 import ( "context" "fmt" + + "time" + "github.com/redacid/aws-auth-controller/awsauth" "github.com/redacid/aws-auth-controller/kube" "k8s.io/apimachinery/pkg/runtime" @@ -27,7 +30,6 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "time" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" ) diff --git a/internal/webhook/v1beta1/maprole_webhook.go b/internal/webhook/v1beta1/maprole_webhook.go index 618f82b..7867b27 100644 --- a/internal/webhook/v1beta1/maprole_webhook.go +++ b/internal/webhook/v1beta1/maprole_webhook.go @@ -19,7 +19,6 @@ package v1beta1 import ( "context" "fmt" - "github.com/redacid/aws-auth-controller/awsauth" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -28,6 +27,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + "github.com/redacid/aws-auth-controller/awsauth" ) // nolint:unused diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index 97c4b30..605fdb1 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -19,16 +19,19 @@ package v1beta1 import ( "context" "fmt" - awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" - "github.com/redacid/aws-auth-controller/awsauth" - "github.com/redacid/aws-auth-controller/kube" + + "time" + "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "time" + + awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + "github.com/redacid/aws-auth-controller/awsauth" + "github.com/redacid/aws-auth-controller/kube" ) // nolint:unused From ef877e04304623fbbcff7b957f35218863b3dd18 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sat, 12 Jul 2025 20:35:44 +0300 Subject: [PATCH 17/58] clean --- api/v1beta1/mapaccount_types.go | 7 ------- awsauth/common.go | 10 +++++----- awsauth/mapper.go | 4 ++-- cmd/main.go | 15 ++++++++++----- internal/controller/common.go | 5 +++++ internal/controller/mapaccount_controller.go | 4 ++-- internal/controller/maprole_controller.go | 4 ++-- internal/controller/mapuser_controller.go | 6 +++--- internal/webhook/v1beta1/mapaccount_webhook.go | 2 +- internal/webhook/v1beta1/mapuser_webhook.go | 2 +- 10 files changed, 31 insertions(+), 28 deletions(-) create mode 100644 internal/controller/common.go diff --git a/api/v1beta1/mapaccount_types.go b/api/v1beta1/mapaccount_types.go index e8dd6c7..3a1c7d0 100644 --- a/api/v1beta1/mapaccount_types.go +++ b/api/v1beta1/mapaccount_types.go @@ -24,13 +24,6 @@ import ( // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // MapAccountSpec defines the desired state of MapAccount. -//type MapAccountSpec struct { -// // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster -// // Important: Run "make" to regenerate code after modifying this file -// -// // Foo is an example field of MapAccount. Edit mapaccount_types.go to remove/update -// //Foo string `json:"foo,omitempty"` -//} type MapAccountSpec struct { // +kubebuilder:validation:MaxLength:=12 diff --git a/awsauth/common.go b/awsauth/common.go index b44dc80..c195639 100644 --- a/awsauth/common.go +++ b/awsauth/common.go @@ -139,7 +139,7 @@ func VerifyGroups(groups []string) error { } // Regular expression for DNS label format validation - //groupPattern := `^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` + // groupPattern := `^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` for _, group := range groups { if group == "" { @@ -150,10 +150,10 @@ func VerifyGroups(groups []string) error { return fmt.Errorf("group name cannot be longer than 253 characters: %s", group) } - //matched, _ := regexp.MatchString(groupPattern, group) - //if !matched { - // return fmt.Errorf("invalid group name format: %s. Group must be DNS-compatible", group) - //} + // matched, _ := regexp.MatchString(groupPattern, group) + // if !matched { + // return fmt.Errorf("invalid group name format: %s. Group must be DNS-compatible", group) + // } } return nil diff --git a/awsauth/mapper.go b/awsauth/mapper.go index ff43120..e60cf5b 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -215,7 +215,7 @@ func existsAccount(authMaps []*MapAccount, resource *MapAccount) (error, bool) { return fmt.Errorf("account with id '%s' already exists", resource.AccountID), found } else { found = false - //return nil, found + // return nil, found } } return nil, found @@ -235,7 +235,7 @@ func existsUser(authMaps []*MapUser, resource *MapUser) (error, bool) { return fmt.Errorf("existsUser: userarn '%s' already exists", resource.UserARN), found } else { found = false - //return nil, found + // return nil, found } } return nil, found diff --git a/cmd/main.go b/cmd/main.go index 7acbcde..f88809c 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -72,11 +72,16 @@ func main() { var configMapName string var tlsOpts []func(*tls.Config) flag.BoolVar(&userNameMustBeEmail, "username-must-be-email", false, - "Enables checking of username, should it be an email address, default false. Use --username-must-be-email=true to enable this feature.") - flag.StringVar(&mustPresentAccountID, "must-present-account-id", "", "This account must be allways present in ConfigMap, must-present-account-id=123456789012") - flag.StringVar(&crdItemAllowedNamespace, "crd-item-allowed-namespace", "", "Namespace where allowed creation of Resources --crd-item-allowed-namespace=kube-system,"+ - "If is set, only in this namespace allowed creation of Resources, if not set, all namespaces allowed creation of Resources.") - flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where store items, --config-map-name=aws-auth, if not set, use default name aws-auth") + "Enables checking of username, should it be an email address, default false."+ + "Use --username-must-be-email=true to enable this feature.") + flag.StringVar(&mustPresentAccountID, "must-present-account-id", "", "This account must be "+ + "allways present in ConfigMap, must-present-account-id=123456789012") + flag.StringVar(&crdItemAllowedNamespace, "crd-item-allowed-namespace", "", + "Namespace where allowed creation of Resources --crd-item-allowed-namespace=kube-system,"+ + "If is set, only in this namespace allowed creation of Resources,"+ + " if not set, all namespaces allowed creation of Resources.") + flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where store items,"+ + " --config-map-name=aws-auth, if not set, use default name aws-auth") flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") diff --git a/internal/controller/common.go b/internal/controller/common.go new file mode 100644 index 0000000..48913eb --- /dev/null +++ b/internal/controller/common.go @@ -0,0 +1,5 @@ +package controller + +const ( + NotFound = "NotFound" +) diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 02e8936..0036dc3 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -72,7 +72,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) // Get a new aws auth service object. awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ KubeClient: kubeClient, - //Log: r.Log, + // Log: r.Log, Log: ctrl.Log, MaxRetryCount: 5, }) @@ -87,7 +87,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) if err := r.Get(ctx, req.NamespacedName, mapAccount); err != nil { // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) - if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { + if !ok || (ok && statusErr.ErrStatus.Reason != NotFound) { logf.Log.Error(err, "Failure getting mapAccount") return ctrl.Result{}, err } diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index 3c98dad..465142f 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -68,7 +68,7 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct // Get a new aws auth service object. awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ KubeClient: kubeClient, - //Log: r.Log, + // Log: r.Log, Log: ctrl.Log, }) if err != nil { @@ -81,7 +81,7 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct if err := r.Get(ctx, req.NamespacedName, mapRole); err != nil { // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) - if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { + if !ok || (ok && statusErr.ErrStatus.Reason != NotFound) { log.Error(err, "failure getting MapRole") return ctrl.Result{}, err } diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index 5a595e8..c92cd78 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -60,7 +60,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct // mapUserName := req.Name mapUserName := req.Name log := ctrl.Log.WithValues("MapUser", mapUserName) - //log := r. Log.WithValues("MapUser", mapUserName) + // log := r. Log.WithValues("MapUser", mapUserName) log.Info("") kubeClient, err := kube.GetClient() @@ -72,7 +72,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct // Get a new aws auth service object. awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ KubeClient: kubeClient, - //Log: r.Log, + // Log: r.Log, Log: ctrl.Log, MaxRetryCount: 5, }) @@ -87,7 +87,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct if err := r.Get(ctx, req.NamespacedName, mapUser); err != nil { // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) - if !ok || (ok && statusErr.ErrStatus.Reason != "NotFound") { + if !ok || (ok && statusErr.ErrStatus.Reason != NotFound) { logf.Log.Error(err, "failure getting MapUser") return ctrl.Result{}, err } diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index be3c4b4..e7c1bca 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -139,7 +139,7 @@ func (v *MapAccountCustomValidator) ValidateCreate(ctx context.Context, obj runt // Get a new aws auth service object. awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ KubeClient: kubeClient, - //Log: r.Log, + // Log: r.Log, Log: ctrl.Log, }) if err != nil { diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index 605fdb1..7c3100f 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -171,7 +171,7 @@ func (v *MapUserCustomValidator) ValidateCreate(ctx context.Context, obj runtime // ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type MapUser. func (v *MapUserCustomValidator) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { mapuser, ok := newObj.(*awsauthv1beta1.MapUser) - oldmapuser, ok := oldObj.(*awsauthv1beta1.MapUser) + oldmapuser, _ := oldObj.(*awsauthv1beta1.MapUser) if !ok { return nil, fmt.Errorf("expected a MapUser object for the newObj but got %T", newObj) From c1655c296cb1841225399b41caeb6c19bfc501d2 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sat, 12 Jul 2025 20:36:57 +0300 Subject: [PATCH 18/58] clean --- internal/webhook/v1beta1/mapaccount_webhook.go | 2 +- internal/webhook/v1beta1/mapuser_webhook.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index e7c1bca..5ebdda4 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -174,7 +174,7 @@ func (v *MapAccountCustomValidator) ValidateUpdate(_ context.Context, oldObj, ne } // ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type MapAccount. -func (v *MapAccountCustomValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { +func (v *MapAccountCustomValidator) ValidateDelete(_ context.Context, obj runtime.Object) (admission.Warnings, error) { mapaccount, ok := obj.(*awsauthv1beta1.MapAccount) if !ok { return nil, fmt.Errorf("expected a MapAccount object but got %T", obj) diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index 7c3100f..06caae7 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -208,7 +208,7 @@ func (v *MapUserCustomValidator) ValidateUpdate(_ context.Context, oldObj, newOb } // ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type MapUser. -func (v *MapUserCustomValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { +func (v *MapUserCustomValidator) ValidateDelete(_ context.Context, obj runtime.Object) (admission.Warnings, error) { mapuser, ok := obj.(*awsauthv1beta1.MapUser) if !ok { return nil, fmt.Errorf("expected a MapUser object but got %T", obj) From 5768626ac0fee07433e49eb4c970790ccc07821a Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sat, 12 Jul 2025 20:52:33 +0300 Subject: [PATCH 19/58] clean --- Makefile | 2 +- config/manager/kustomization.yaml | 2 +- internal/webhook/v1beta1/mapaccount_webhook.go | 2 -- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 6915f0f..f25b951 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.69 +IMG ?= redacid/aws-auth-controller-dev:0.0.70 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 934a3c5..b4f9224 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.69 + newTag: 0.0.70 diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index 5ebdda4..ae605c6 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -181,7 +181,5 @@ func (v *MapAccountCustomValidator) ValidateDelete(_ context.Context, obj runtim } mapaccountlog.Info("Validation for MapAccount upon deletion", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) - // TODO(user): fill in your validation logic upon object deletion. - return nil, nil } From a9db0805cdac90b3de2309f219e1b5e7106ea3f3 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sun, 13 Jul 2025 07:02:54 +0300 Subject: [PATCH 20/58] mapAccount convertation --- Makefile | 2 +- awsauth/common.go | 38 ++++++++++++++++++- awsauth/data.go | 18 ++++++++- config/manager/kustomization.yaml | 2 +- internal/controller/mapaccount_controller.go | 2 +- internal/controller/maprole_controller.go | 3 +- internal/controller/mapuser_controller.go | 2 +- .../webhook/v1beta1/mapaccount_webhook.go | 5 ++- internal/webhook/v1beta1/mapuser_webhook.go | 5 ++- 9 files changed, 64 insertions(+), 13 deletions(-) diff --git a/Makefile b/Makefile index f25b951..51bd2ec 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.70 +IMG ?= redacid/aws-auth-controller-dev:0.0.73 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/awsauth/common.go b/awsauth/common.go index c195639..db8dd6e 100644 --- a/awsauth/common.go +++ b/awsauth/common.go @@ -19,7 +19,6 @@ import ( "fmt" "regexp" "strings" - // "k8s.io/client-go/kubernetes" ) var AllowedAWSAccounts = []string{ @@ -40,7 +39,7 @@ func VerifyAWSAccount(accountID string) error { return nil } -// VerifyAWSAccountID verifies if the AWS account ID is allowed +// VerifyAWSAccountIDArn VerifyAWSAccountID verifies if the AWS account ID is allowed func VerifyAWSAccountIDArn(arn string) error { // Extract account ID from ARN arnParts := strings.Split(arn, ":") @@ -172,3 +171,38 @@ func SetAllowedAWSAccounts(accounts []string) error { AllowedAWSAccounts = accounts return nil } + +// ConvertMapAccountToString конвертує MapAccountSpec в строку accountid +func ConvertMapAccountToString(accounts []*MapAccount) []string { + result := make([]string, len(accounts)) + for i, account := range accounts { + result[i] = account.AccountID + } + return result +} + +// ConvertStringToMapAccount конвертує строки accountid в MapAccountSpec +func ConvertStringToMapAccount(accountIDs []string) []*MapAccount { + result := make([]*MapAccount, len(accountIDs)) + for i, accountID := range accountIDs { + result[i] = &MapAccount{ + AccountID: accountID, + } + } + return result +} + +/* + // Конвертація з MapAccountSpec в строки + specs := []MapAccountSpec{ + {AccountID: "111111111111"}, + {AccountID: "222222222222"}, + } + strings := ConvertMapAccountToString(specs) + // результат: []string{"111111111111", "222222222222"} + + // Конвертація зі строк в MapAccountSpec + accountIDs := []string{"111111111111", "222222222222"} + specs = ConvertStringToMapAccount(accountIDs) + // результат: []MapAccountSpec{{AccountID: "111111111111"}, {AccountID: "222222222222"}} +*/ diff --git a/awsauth/data.go b/awsauth/data.go index d7a8801..a38c3c7 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -19,6 +19,7 @@ import ( "context" "fmt" "log" + "sync" "gopkg.in/yaml.v2" kcorev1 "k8s.io/api/core/v1" @@ -45,6 +46,7 @@ var ( // TODO automatic add to configmap MustPresentAccountID string = "" CrdItemAllowedNamespace string = "" + configMapMutex sync.RWMutex ) type ControllerArgs struct { @@ -63,6 +65,8 @@ func DeclareVariables(controllerArgs ControllerArgs) { // ReadAuthMap reads the auth ConfigMap and returns AwsAuthData and the read ConfigMap. func ReadAuthMap(k kubernetes.Interface) (AwsAuthData, *kcorev1.ConfigMap, error) { + configMapMutex.RLock() + defer configMapMutex.RUnlock() var authData AwsAuthData @@ -83,10 +87,17 @@ func ReadAuthMap(k kubernetes.Interface) (AwsAuthData, *kcorev1.ConfigMap, error return authData, cm, err } - err = yaml.Unmarshal([]byte(cm.Data["mapAccounts"]), &authData.MapAccounts) + /*err = yaml.Unmarshal([]byte(cm.Data["mapAccounts"]), &authData.MapAccounts) + if err != nil { + return authData, cm, err + }*/ + + var accountIDs []string + err = yaml.Unmarshal([]byte(cm.Data["mapAccounts"]), &accountIDs) if err != nil { return authData, cm, err } + authData.MapAccounts = ConvertStringToMapAccount(accountIDs) err = yaml.Unmarshal([]byte(cm.Data["mapUsers"]), &authData.MapUsers) return authData, cm, err @@ -109,6 +120,9 @@ func CreateAuthMap(k kubernetes.Interface) (*kcorev1.ConfigMap, error) { // UpdateAuthMap updates a given ConfigMap func UpdateAuthMap(k kubernetes.Interface, authData AwsAuthData, cm *kcorev1.ConfigMap) error { + configMapMutex.Lock() + defer configMapMutex.Unlock() + mapRoles, err := yaml.Marshal(authData.MapRoles) if err != nil { return err @@ -119,7 +133,7 @@ func UpdateAuthMap(k kubernetes.Interface, authData AwsAuthData, cm *kcorev1.Con return err } - mapAccounts, err := yaml.Marshal(authData.MapAccounts) + mapAccounts, err := yaml.Marshal(ConvertMapAccountToString(authData.MapAccounts)) if err != nil { return err } diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index b4f9224..b0f9981 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.70 + newTag: 0.0.73 diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 0036dc3..46cb0a9 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -123,7 +123,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) log.Error(err, "Failure removing mapAccount data in aws-auth configmap") return ctrl.Result{}, nil } - logf.Log.Info("mapAccount is being deleted, so removing finalizer") + logf.Log.Info("Removing finalizer") controllerutil.RemoveFinalizer(mapAccount, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapAccount); err != nil { return ctrl.Result{}, err diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index 465142f..21c1465 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -69,7 +69,8 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ KubeClient: kubeClient, // Log: r.Log, - Log: ctrl.Log, + Log: ctrl.Log, + MaxRetryCount: 5, }) if err != nil { log.Error(err, "failure creating new aws auth service") diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index c92cd78..f39d00f 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -125,7 +125,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct log.Error(err, "failure removing mapUser data in aws-auth configmap") return ctrl.Result{}, nil } - logf.Log.Info("mapUser is being deleted, so removing finalizer") + logf.Log.Info("Removing finalizer") controllerutil.RemoveFinalizer(mapUser, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapUser); err != nil { return ctrl.Result{}, err diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index ae605c6..b833171 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -42,7 +42,7 @@ var ( // SetupMapAccountWebhookWithManager registers the webhook for MapAccount in the manager. func SetupMapAccountWebhookWithManager(mgr ctrl.Manager) error { - validator := &MapUserCustomValidator{ + validator := &MapAccountCustomValidator{ Client: mgr.GetClient(), } return ctrl.NewWebhookManagedBy(mgr).For(&awsauthv1beta1.MapAccount{}). @@ -140,7 +140,8 @@ func (v *MapAccountCustomValidator) ValidateCreate(ctx context.Context, obj runt awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ KubeClient: kubeClient, // Log: r.Log, - Log: ctrl.Log, + Log: ctrl.Log, + MaxRetryCount: 5, }) if err != nil { mapaccountlog.Error(err, "Failure creating new aws auth service") diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index 06caae7..d5df145 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -142,8 +142,9 @@ func (v *MapUserCustomValidator) ValidateCreate(ctx context.Context, obj runtime // Get a new aws auth service object. awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ - KubeClient: kubeClient, - Log: ctrl.Log, + KubeClient: kubeClient, + Log: ctrl.Log, + MaxRetryCount: 5, }) if err != nil { mapuserlog.Error(err, "Failure creating new aws auth service") From ecf140004d124a98b4f6f627f0fd7a703b894dff Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sun, 13 Jul 2025 08:04:20 +0300 Subject: [PATCH 21/58] reconfigure mapRole --- awsauth/common.go | 8 -- awsauth/mapper.go | 34 ++++++++ awsauth/service.go | 46 ++++++++-- internal/controller/maprole_controller.go | 54 +++++++++--- internal/controller/mapuser_controller.go | 5 +- internal/webhook/v1beta1/maprole_webhook.go | 93 +++++++++++++++++++-- 6 files changed, 201 insertions(+), 39 deletions(-) diff --git a/awsauth/common.go b/awsauth/common.go index db8dd6e..b17e15f 100644 --- a/awsauth/common.go +++ b/awsauth/common.go @@ -137,9 +137,6 @@ func VerifyGroups(groups []string) error { return fmt.Errorf("at least one group must be specified") } - // Regular expression for DNS label format validation - // groupPattern := `^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` - for _, group := range groups { if group == "" { return fmt.Errorf("group name cannot be empty") @@ -148,11 +145,6 @@ func VerifyGroups(groups []string) error { if len(group) > 253 { return fmt.Errorf("group name cannot be longer than 253 characters: %s", group) } - - // matched, _ := regexp.MatchString(groupPattern, group) - // if !matched { - // return fmt.Errorf("invalid group name format: %s. Group must be DNS-compatible", group) - // } } return nil diff --git a/awsauth/mapper.go b/awsauth/mapper.go index e60cf5b..3ae1d88 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -201,6 +201,20 @@ func (m *Mapper) existsAuth(args *Arguments) error { return nil } } + + if args.DataType == MapRoleData { + log.Printf("authData.MapRoles: %v\n", authData.MapRoles) + mapRole := NewMapRole(args.RoleARN, args.Username, args.Groups) + err, exists := existsRole(authData.MapRoles, mapRole) + if exists { + log.Printf("%v", err) + return err + } else { + log.Printf("%s with username '%s' or rolearn '%s' not exists\n", args.DataType, args.Username, args.RoleARN) + return nil + } + } + return nil } @@ -241,6 +255,26 @@ func existsUser(authMaps []*MapUser, resource *MapUser) (error, bool) { return nil, found } +func existsRole(authMaps []*MapRole, resource *MapRole) (error, bool) { + var found = false + log.Printf("existsRole check: username: %v rolearn:%v \n", resource.Username, resource.RoleARN) + for _, existing := range authMaps { + log.Printf("existsRole: cm username: %v rolearn: %v \n", existing.Username, existing.RoleARN) + log.Printf("existsRole: new username: %v rolearn: %v \n", resource.Username, resource.RoleARN) + if existing.Username == resource.Username { + found = true + return fmt.Errorf("existsRole: username '%s' already exists", resource.Username), found + } else if existing.RoleARN == resource.RoleARN { + found = true + return fmt.Errorf("existsRole: rolearn '%s' already exists", resource.RoleARN), found + } else { + found = false + // return nil, found + } + } + return nil, found +} + // Upsert updates or inserts a mapRole or mapUser item into the auth map. func (m *Mapper) Upsert(args *Arguments) error { // TODO Remove this validate diff --git a/awsauth/service.go b/awsauth/service.go index 063d4d9..d2c3869 100644 --- a/awsauth/service.go +++ b/awsauth/service.go @@ -37,10 +37,10 @@ type ServiceConfig struct { // Service provides aws-auth configmap management behavior. type Service interface { // UpsertMapRole upserts a MapRole into the configmap keyed by username. - UpsertMapRole(username string, mapRole MapRole) error + UpsertMapRole(mapRole MapRole) error // RemoveMapRole removes a MapRole from the configmap by keyed by username - RemoveMapRole(username string) error + RemoveMapRole(mapRole MapRole) error // UpsertMapUser upserts a MapUser into the configmap keyed by username. UpsertMapUser(mapUser MapUser) error @@ -54,6 +54,9 @@ type Service interface { // CheckMapUserExists checks if an MapUser with the specified username and userarn ID exists. CheckMapUserExists(mapUser MapUser) error + // CheckMapRoleExists checks if an MapRole with the specified username and rolearn ID exists. + CheckMapRoleExists(mapRole MapRole) error + // UpsertMapAccount upserts a mapAccount into the configmap keyed by username. UpsertMapAccount(mapAccount MapAccount) error @@ -75,13 +78,31 @@ type impl struct { cfg ServiceConfig } +func (svc impl) CheckMapRoleExists(mapRole MapRole) error { + svc.cfg.Log.Info("CheckMapRoleExists", "username", mapRole.Username, "rolearn", mapRole.RoleARN) + mapper := NewMapper(svc.cfg.KubeClient, false) + err := mapper.CheckExists(&Arguments{ + DataType: MapRoleData, + Username: mapRole.Username, + UserARN: mapRole.RoleARN, + WithRetries: svc.cfg.WithRetries, + MaxRetryCount: svc.cfg.MaxRetryCount, + MaxRetryTime: svc.cfg.MaxRetryTime, + MinRetryTime: svc.cfg.MinRetryTime, + }) + if err != nil { + svc.cfg.Log.Info("username or rolearn already exists", "username", mapRole.Username, "rolearn", mapRole.RoleARN) + } + return err +} + // UpsertMapRole upserts a MapRole into the configmap keyed by username. -func (svc impl) UpsertMapRole(username string, mapRole MapRole) error { +func (svc impl) UpsertMapRole(mapRole MapRole) error { mapper := NewMapper(svc.cfg.KubeClient, false) err := mapper.Upsert(&Arguments{ DataType: MapRoleData, RoleARN: mapRole.RoleARN, - Username: username, + Username: mapRole.Username, Groups: mapRole.Groups, WithRetries: svc.cfg.WithRetries, MaxRetryCount: svc.cfg.MaxRetryCount, @@ -89,24 +110,33 @@ func (svc impl) UpsertMapRole(username string, mapRole MapRole) error { MinRetryTime: svc.cfg.MinRetryTime, }) if err != nil { - svc.cfg.Log.Error(err, "failure to upsert mapRole", "username", username) + svc.cfg.Log.Error(err, "failure to upsert mapRole", + "username", mapRole.Username, + "rolearn", mapRole.RoleARN, + "groups", mapRole.Groups, + ) } return err } // RemoveMapRole removes a MapRole from the configmap keyed by username. -func (svc impl) RemoveMapRole(username string) error { +func (svc impl) RemoveMapRole(mapRole MapRole) error { mapper := NewMapper(svc.cfg.KubeClient, false) err := mapper.Remove(&Arguments{ DataType: MapRoleData, - Username: username, + Username: mapRole.Username, + RoleARN: mapRole.RoleARN, + Groups: mapRole.Groups, WithRetries: svc.cfg.WithRetries, MaxRetryCount: svc.cfg.MaxRetryCount, MaxRetryTime: svc.cfg.MaxRetryTime, MinRetryTime: svc.cfg.MinRetryTime, }) if err != nil { - svc.cfg.Log.Info("mapRole not found", "username", username) + svc.cfg.Log.Info("mapRole not found", + "username", mapRole.Username, + "rolearn", mapRole.RoleARN, + "groups", mapRole.Groups) } return err } diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index 21c1465..3a6faa9 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -18,6 +18,7 @@ package controller import ( "context" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" @@ -86,24 +87,51 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct log.Error(err, "failure getting MapRole") return ctrl.Result{}, err } - - if err := awsauthSvc.RemoveMapRole(mapRoleName); err != nil { - log.Error(err, "error removing mapRole data in aws-auth configmap") - return ctrl.Result{}, nil - } log.Info("removed mapRole data in aws-auth configmap") return ctrl.Result{}, nil } - // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. - if err := awsauthSvc.UpsertMapRole(mapRole.Name, awsauth.MapRole{ - RoleARN: mapRole.Spec.RoleARN, - Groups: mapRole.Spec.Groups, - }); err != nil { - log.Error(err, "error upserting MapRole in aws-auth") - return ctrl.Result{}, err + if mapRole.DeletionTimestamp.IsZero() { + logf.Log.Info("mapRole is not being deleted") + // Add finalizer + if !controllerutil.ContainsFinalizer(mapRole, awsauth.CrdFinalizerName) { + logf.Log.Info("mapRole is not being deleted, so adding finalizer") + controllerutil.AddFinalizer(mapRole, awsauth.CrdFinalizerName) + if err := r.Update(ctx, mapRole); err != nil { + return ctrl.Result{}, err + } + } else { + // Ensure that any changes are synced to the kube-system:aws-auth ConfigMap. + if err := awsauthSvc.UpsertMapRole(awsauth.MapRole{ + Username: mapRole.Spec.Username, + RoleARN: mapRole.Spec.RoleARN, + Groups: mapRole.Spec.Groups, + }); err != nil { + log.Error(err, "failure upserting MapRole") + return ctrl.Result{}, err + } + log.Info("upserted MapRole") + } + } else { + log.Info("mapRole is being deleted") + if controllerutil.ContainsFinalizer(mapRole, awsauth.CrdFinalizerName) { + if err := awsauthSvc.RemoveMapRole(awsauth.MapRole{ + Username: mapRole.Spec.Username, + RoleARN: mapRole.Spec.RoleARN, + Groups: mapRole.Spec.Groups, + }); err != nil { + log.Error(err, "failure removing mapRole data in aws-auth configmap") + return ctrl.Result{}, nil + } + logf.Log.Info("Removing finalizer") + controllerutil.RemoveFinalizer(mapRole, awsauth.CrdFinalizerName) + if err := r.Update(ctx, mapRole); err != nil { + return ctrl.Result{}, err + } + } + log.Info("removed mapRole data in aws-auth configmap") + return ctrl.Result{}, nil } - log.Info("upserted MapRole") return ctrl.Result{}, nil } diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index f39d00f..e19db82 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -57,7 +57,6 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct _ = logf.FromContext(ctx) // MapUser objects are named by their associated AWS IAM user ARNs. - // mapUserName := req.Name mapUserName := req.Name log := ctrl.Log.WithValues("MapUser", mapUserName) // log := r. Log.WithValues("MapUser", mapUserName) @@ -94,10 +93,10 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct return ctrl.Result{}, nil } if mapUser.DeletionTimestamp.IsZero() { - logf.Log.Info("mapAccount is not being deleted") + logf.Log.Info("mapUser is not being deleted") // Add finalizer if !controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { - logf.Log.Info("mapAccount is not being deleted, so adding finalizer") + logf.Log.Info("mapUser is not being deleted, so adding finalizer") controllerutil.AddFinalizer(mapUser, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapUser); err != nil { return ctrl.Result{}, err diff --git a/internal/webhook/v1beta1/maprole_webhook.go b/internal/webhook/v1beta1/maprole_webhook.go index 7867b27..09617ea 100644 --- a/internal/webhook/v1beta1/maprole_webhook.go +++ b/internal/webhook/v1beta1/maprole_webhook.go @@ -19,6 +19,8 @@ package v1beta1 import ( "context" "fmt" + "github.com/redacid/aws-auth-controller/kube" + "sigs.k8s.io/controller-runtime/pkg/client" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -36,8 +38,13 @@ var maprolelog = logf.Log.WithName("maprole-resource") // SetupMapRoleWebhookWithManager registers the webhook for MapRole in the manager. func SetupMapRoleWebhookWithManager(mgr ctrl.Manager) error { + validator := &MapRoleCustomValidator{ + Client: mgr.GetClient(), + } + return ctrl.NewWebhookManagedBy(mgr).For(&awsauthv1beta1.MapRole{}). - WithValidator(&MapRoleCustomValidator{}). + // WithValidator(&MapRoleCustomValidator{}). + WithValidator(validator). WithDefaulter(&MapRoleCustomDefaulter{}). Complete() } @@ -82,18 +89,25 @@ func (d *MapRoleCustomDefaulter) Default(_ context.Context, obj runtime.Object) // NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods, // as this struct is used only for temporary operations and does not need to be deeply copied. type MapRoleCustomValidator struct { - // TODO(user): Add more fields as needed for validation + Client client.Client } var _ webhook.CustomValidator = &MapRoleCustomValidator{} // ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type MapRole. -func (v *MapRoleCustomValidator) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) { +func (v *MapRoleCustomValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { maprole, ok := obj.(*awsauthv1beta1.MapRole) if !ok { return nil, fmt.Errorf("expected a MapRole object but got %T", obj) } - maprolelog.Info("Validation for MapRole upon creation", "name", maprole.GetName()) + maprolelog.Info("Validation for MapRole upon creation", + "name", maprole.GetName(), + "RoleARN", maprole.Spec.RoleARN, + "Username", maprole.Spec.Username, + "Description", maprole.Spec.Description, + "Groups", maprole.Spec.Groups, + "Namespace", maprole.GetNamespace(), + ) if awsauth.CrdItemAllowedNamespace != "" { if maprole.GetNamespace() != awsauth.CrdItemAllowedNamespace { @@ -102,7 +116,47 @@ func (v *MapRoleCustomValidator) ValidateCreate(_ context.Context, obj runtime.O } } - // TODO(user): fill in your validation logic upon object creation. + // ----- + var mapRoleList awsauthv1beta1.MapRoleList + if err := v.Client.List(ctx, &mapRoleList); err != nil { + return nil, err + } + for _, existingUser := range mapRoleList.Items { + if existingUser.Spec.Username == maprole.Spec.Username || + existingUser.Spec.RoleARN == maprole.Spec.RoleARN { + return nil, fmt.Errorf("duplicate user data found: username %s or rolearn %s already exists in another MapRole resource: %s", + maprole.Spec.Username, maprole.Spec.RoleARN, existingUser.GetName()) + } + } + // ----- + + kubeClient, err := kube.GetClient() + if err != nil { + mapuserlog.Error(err, "Failure getting kube client") + return nil, err + } + + // Get a new aws auth service object. + awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ + KubeClient: kubeClient, + Log: ctrl.Log, + MaxRetryCount: 5, + }) + if err != nil { + mapuserlog.Error(err, "Failure creating new aws auth service") + return nil, err + } + + if err := awsauthSvc.CheckMapRoleExists(awsauth.MapRole{ + Username: maprole.Spec.Username, + RoleARN: maprole.Spec.RoleARN, + Groups: maprole.Spec.Groups, + }); err != nil { + mapuserlog.Info("Failure checking, username or userarn exists in aws-auth configmap") + return nil, fmt.Errorf("failure checking, username %v or rolearn %v exists in aws-auth configmap", maprole.Spec.Username, maprole.Spec.RoleARN) + } else { + mapuserlog.Info("username and rolearn not exists in aws-auth configmap") + } return nil, nil } @@ -110,12 +164,37 @@ func (v *MapRoleCustomValidator) ValidateCreate(_ context.Context, obj runtime.O // ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type MapRole. func (v *MapRoleCustomValidator) ValidateUpdate(_ context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { maprole, ok := newObj.(*awsauthv1beta1.MapRole) + oldmaprole, _ := oldObj.(*awsauthv1beta1.MapRole) if !ok { return nil, fmt.Errorf("expected a MapRole object for the newObj but got %T", newObj) } - maprolelog.Info("Validation for MapRole upon update", "name", maprole.GetName()) + maprolelog.Info("Validation for MapUser upon update OLD:", + "name", oldmaprole.GetName(), + "RoleARN", oldmaprole.Spec.RoleARN, + "Username", oldmaprole.Spec.Username, + "Description", oldmaprole.Spec.Description, + "Groups", oldmaprole.Spec.Groups, + "Namespace", oldmaprole.GetNamespace(), + ) + maprolelog.Info("Validation for MapUser upon update NEW:", + "name", maprole.GetName(), + "RoleARN", maprole.Spec.RoleARN, + "Username", maprole.Spec.Username, + "Description", maprole.Spec.Description, + "Groups", maprole.Spec.Groups, + "Namespace", maprole.GetNamespace(), + ) + + if (maprole.Spec.Username != oldmaprole.Spec.Username) && (maprole.Spec.Username != "") { + return nil, fmt.Errorf("username cannot be changed, pls create a new MapRole with the new Username, only change Groups allowed") + } + if (maprole.Spec.RoleARN != oldmaprole.Spec.RoleARN) && (maprole.Spec.RoleARN != "") { + return nil, fmt.Errorf("RoleARN cannot be changed, pls create a new MapRole with the new RoleARN, only change Groups allowed") + } - // TODO(user): fill in your validation logic upon object update. + if err := awsauth.VerifyGroups(maprole.Spec.Groups); err != nil { + return nil, err + } return nil, nil } From 39571f48daf2f89f37db7dc86af1dfe29571d631 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sun, 13 Jul 2025 08:06:32 +0300 Subject: [PATCH 22/58] add timewait to maprole webhook --- internal/webhook/v1beta1/maprole_webhook.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/internal/webhook/v1beta1/maprole_webhook.go b/internal/webhook/v1beta1/maprole_webhook.go index 09617ea..be56ae4 100644 --- a/internal/webhook/v1beta1/maprole_webhook.go +++ b/internal/webhook/v1beta1/maprole_webhook.go @@ -21,6 +21,7 @@ import ( "fmt" "github.com/redacid/aws-auth-controller/kube" "sigs.k8s.io/controller-runtime/pkg/client" + "time" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" @@ -96,6 +97,9 @@ var _ webhook.CustomValidator = &MapRoleCustomValidator{} // ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type MapRole. func (v *MapRoleCustomValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { + // This wait need for write to configmap + time.Sleep(100 * time.Millisecond) + maprole, ok := obj.(*awsauthv1beta1.MapRole) if !ok { return nil, fmt.Errorf("expected a MapRole object but got %T", obj) @@ -200,7 +204,7 @@ func (v *MapRoleCustomValidator) ValidateUpdate(_ context.Context, oldObj, newOb } // ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type MapRole. -func (v *MapRoleCustomValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { +func (v *MapRoleCustomValidator) ValidateDelete(_ context.Context, obj runtime.Object) (admission.Warnings, error) { maprole, ok := obj.(*awsauthv1beta1.MapRole) if !ok { return nil, fmt.Errorf("expected a MapRole object but got %T", obj) From 696ae524b384c9683725f1c560ede5831b01f548 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sun, 13 Jul 2025 09:26:53 +0300 Subject: [PATCH 23/58] disable check existent in cm disallow delete crd mapAccount if is must-present-account-id commanline flag --- Makefile | 2 +- TODO.md | 5 +- cmd/main.go | 2 +- config/manager/kustomization.yaml | 2 +- config/manager/manager.yaml | 3 +- .../samples/aws-auth_v1beta1_mapaccount.yaml | 2 +- config/samples/aws-auth_v1beta1_maprole.yaml | 19 +++- config/samples/aws-auth_v1beta1_mapuser.yaml | 86 +++++++++++-------- .../webhook/v1beta1/mapaccount_webhook.go | 49 ++++++----- internal/webhook/v1beta1/maprole_webhook.go | 54 ++++++------ internal/webhook/v1beta1/mapuser_webhook.go | 56 ++++++------ 11 files changed, 158 insertions(+), 122 deletions(-) diff --git a/Makefile b/Makefile index 51bd2ec..a9d265e 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.73 +IMG ?= redacid/aws-auth-controller-dev:0.0.75 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/TODO.md b/TODO.md index 31b831e..4667bd7 100644 --- a/TODO.md +++ b/TODO.md @@ -1 +1,4 @@ -~~Додати флаг CrdAllowedNamespace, для контролю створення ресурсів~~ \ No newline at end of file +~~Додати флаг CrdAllowedNamespace, для контролю створення ресурсів~~ +* Реалізувати додавання акаунта за замовчуванням +* Дізнатися як обробляти дублікати при створенні ролей +* Прибрати зайве логування \ No newline at end of file diff --git a/cmd/main.go b/cmd/main.go index f88809c..f633460 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -75,7 +75,7 @@ func main() { "Enables checking of username, should it be an email address, default false."+ "Use --username-must-be-email=true to enable this feature.") flag.StringVar(&mustPresentAccountID, "must-present-account-id", "", "This account must be "+ - "allways present in ConfigMap, must-present-account-id=123456789012") + "allways present in ConfigMap, --must-present-account-id=123456789012") flag.StringVar(&crdItemAllowedNamespace, "crd-item-allowed-namespace", "", "Namespace where allowed creation of Resources --crd-item-allowed-namespace=kube-system,"+ "If is set, only in this namespace allowed creation of Resources,"+ diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index b0f9981..0e2b168 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.73 + newTag: 0.0.75 diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index fdba67c..63d2bc1 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -62,8 +62,9 @@ spec: - /manager args: - --config-map-name=aws-auth-test + - --must-present-account-id=123456789012 - --crd-item-allowed-namespace=kube-system - - --username-must-be-email + #- --username-must-be-email - --leader-elect - --health-probe-bind-address=:8081 image: controller:latest diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index c138b74..fa9788c 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -30,4 +30,4 @@ metadata: app.kubernetes.io/managed-by: kustomize name: account3 spec: - accountid: "222222222222" \ No newline at end of file + accountid: "333333333333" \ No newline at end of file diff --git a/config/samples/aws-auth_v1beta1_maprole.yaml b/config/samples/aws-auth_v1beta1_maprole.yaml index 7f872ba..f82680f 100644 --- a/config/samples/aws-auth_v1beta1_maprole.yaml +++ b/config/samples/aws-auth_v1beta1_maprole.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: maprole-sample + name: maprole1 spec: rolearn: arn:aws:iam::130488995195:role/prod-self-managed-node-group groups: @@ -12,3 +12,20 @@ spec: - sample:group2 description: A sample maprole username: system:node:{{EC2PrivateDNSName}} + +--- + +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapRole +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: maprole2 +spec: + rolearn: arn:aws:iam::130488995195:role/prod-self-managed-node-group2 + groups: + - sample:group1 + - sample:group2 + description: A sample maprole + username: system:node:{{EC2PrivateDNSName2}} \ No newline at end of file diff --git a/config/samples/aws-auth_v1beta1_mapuser.yaml b/config/samples/aws-auth_v1beta1_mapuser.yaml index 1e7e87c..f28fb0f 100644 --- a/config/samples/aws-auth_v1beta1_mapuser.yaml +++ b/config/samples/aws-auth_v1beta1_mapuser.yaml @@ -1,46 +1,62 @@ -apiVersion: aws-auth.prozorro.sale/v1beta1 -kind: MapUser -metadata: - labels: - app.kubernetes.io/name: aws-auth-controller-prozorro - app.kubernetes.io/managed-by: kustomize - name: user1 -spec: - description: A test mapuser - username: user1@ios.in.ua - groups: - - system:masters - - admins - userarn: arn:aws:iam::123456789012:user/user1 - ---- -apiVersion: aws-auth.prozorro.sale/v1beta1 -kind: MapUser -metadata: - labels: - app.kubernetes.io/name: aws-auth-controller-prozorro - app.kubernetes.io/managed-by: kustomize - name: user2 -spec: - description: A test mapuser - username: user2@ios.in.ua - groups: - - system:masters - - admins - userarn: arn:aws:iam::123456789012:user/user2 +#apiVersion: aws-auth.prozorro.sale/v1beta1 +#kind: MapUser +#metadata: +# labels: +# app.kubernetes.io/name: aws-auth-controller-prozorro +# app.kubernetes.io/managed-by: kustomize +# name: user1 +#spec: +# description: A test mapuser +# username: user1@ios.in.ua +# groups: +# - system:masters +# - admins +# userarn: arn:aws:iam::123456789012:user/user1 +# +#--- +#apiVersion: aws-auth.prozorro.sale/v1beta1 +#kind: MapUser +#metadata: +# labels: +# app.kubernetes.io/name: aws-auth-controller-prozorro +# app.kubernetes.io/managed-by: kustomize +# name: user2 +#spec: +# description: A test mapuser +# username: user2@ios.in.ua +# groups: +# - system:masters +# - admins +# userarn: arn:aws:iam::123456789012:user/user2 +# +#--- +#apiVersion: aws-auth.prozorro.sale/v1beta1 +#kind: MapUser +#metadata: +# labels: +# app.kubernetes.io/name: aws-auth-controller-prozorro +# app.kubernetes.io/managed-by: kustomize +# name: user3 +#spec: +# description: A test mapuser +# username: user3@ios.in.ua +# groups: +# - system:masters +# - users +# userarn: arn:aws:iam::123456789012:user/user3 ---- apiVersion: aws-auth.prozorro.sale/v1beta1 kind: MapUser metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: user3 + name: serhii.rudenko spec: - description: A test mapuser - username: user2@ios.in.ua + description: Serhii Rudenko + username: serhii.rudenko@prozorro.sale groups: - system:masters - users - userarn: arn:aws:iam::123456789012:user/user2 \ No newline at end of file + - admins + userarn: arn:aws:iam::130488995195:user/serhii.rudenko@prozorro.sale \ No newline at end of file diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index b833171..47cf6b3 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -23,7 +23,6 @@ import ( "time" "github.com/redacid/aws-auth-controller/awsauth" - "github.com/redacid/aws-auth-controller/kube" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -130,30 +129,30 @@ func (v *MapAccountCustomValidator) ValidateCreate(ctx context.Context, obj runt } // ----- - kubeClient, err := kube.GetClient() - if err != nil { - mapaccountlog.Error(err, "Failure getting kube client") - return nil, err - } + /* kubeClient, err := kube.GetClient() + if err != nil { + mapaccountlog.Error(err, "Failure getting kube client") + return nil, err + } - // Get a new aws auth service object. - awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ - KubeClient: kubeClient, - // Log: r.Log, - Log: ctrl.Log, - MaxRetryCount: 5, - }) - if err != nil { - mapaccountlog.Error(err, "Failure creating new aws auth service") - return nil, err - } + // Get a new aws auth service object. + awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ + KubeClient: kubeClient, + // Log: r.Log, + Log: ctrl.Log, + MaxRetryCount: 5, + }) + if err != nil { + mapaccountlog.Error(err, "Failure creating new aws auth service") + return nil, err + } - if err = awsauthSvc.CheckMapAccountExists(awsauth.MapAccount{ - AccountID: mapaccount.Spec.AccountID, - }); err != nil { - mapaccountlog.Info("Failure checking, account exists in aws-auth configmap") - return nil, fmt.Errorf("failure checking, accountid %v exists in aws-auth configmap", mapaccount.Spec.AccountID) - } + if err = awsauthSvc.CheckMapAccountExists(awsauth.MapAccount{ + AccountID: mapaccount.Spec.AccountID, + }); err != nil { + mapaccountlog.Info("Failure checking, account exists in aws-auth configmap") + return nil, fmt.Errorf("failure checking, accountid %v exists in aws-auth configmap", mapaccount.Spec.AccountID) + }*/ return nil, nil } @@ -182,5 +181,9 @@ func (v *MapAccountCustomValidator) ValidateDelete(_ context.Context, obj runtim } mapaccountlog.Info("Validation for MapAccount upon deletion", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) + if mapaccount.Spec.AccountID == awsauth.MustPresentAccountID { + return nil, fmt.Errorf("cannot delete MapAccount with AccountID %s", awsauth.MustPresentAccountID) + } + return nil, nil } diff --git a/internal/webhook/v1beta1/maprole_webhook.go b/internal/webhook/v1beta1/maprole_webhook.go index be56ae4..0fb959d 100644 --- a/internal/webhook/v1beta1/maprole_webhook.go +++ b/internal/webhook/v1beta1/maprole_webhook.go @@ -19,7 +19,6 @@ package v1beta1 import ( "context" "fmt" - "github.com/redacid/aws-auth-controller/kube" "sigs.k8s.io/controller-runtime/pkg/client" "time" @@ -126,41 +125,40 @@ func (v *MapRoleCustomValidator) ValidateCreate(ctx context.Context, obj runtime return nil, err } for _, existingUser := range mapRoleList.Items { - if existingUser.Spec.Username == maprole.Spec.Username || - existingUser.Spec.RoleARN == maprole.Spec.RoleARN { + if existingUser.Spec.Username+existingUser.Spec.RoleARN == maprole.Spec.Username+maprole.Spec.RoleARN { return nil, fmt.Errorf("duplicate user data found: username %s or rolearn %s already exists in another MapRole resource: %s", maprole.Spec.Username, maprole.Spec.RoleARN, existingUser.GetName()) } } // ----- - kubeClient, err := kube.GetClient() - if err != nil { - mapuserlog.Error(err, "Failure getting kube client") - return nil, err - } + /* kubeClient, err := kube.GetClient() + if err != nil { + mapuserlog.Error(err, "Failure getting kube client") + return nil, err + } - // Get a new aws auth service object. - awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ - KubeClient: kubeClient, - Log: ctrl.Log, - MaxRetryCount: 5, - }) - if err != nil { - mapuserlog.Error(err, "Failure creating new aws auth service") - return nil, err - } + // Get a new aws auth service object. + awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ + KubeClient: kubeClient, + Log: ctrl.Log, + MaxRetryCount: 5, + }) + if err != nil { + mapuserlog.Error(err, "Failure creating new aws auth service") + return nil, err + } - if err := awsauthSvc.CheckMapRoleExists(awsauth.MapRole{ - Username: maprole.Spec.Username, - RoleARN: maprole.Spec.RoleARN, - Groups: maprole.Spec.Groups, - }); err != nil { - mapuserlog.Info("Failure checking, username or userarn exists in aws-auth configmap") - return nil, fmt.Errorf("failure checking, username %v or rolearn %v exists in aws-auth configmap", maprole.Spec.Username, maprole.Spec.RoleARN) - } else { - mapuserlog.Info("username and rolearn not exists in aws-auth configmap") - } + if err := awsauthSvc.CheckMapRoleExists(awsauth.MapRole{ + Username: maprole.Spec.Username, + RoleARN: maprole.Spec.RoleARN, + Groups: maprole.Spec.Groups, + }); err != nil { + mapuserlog.Info("Failure checking, username or userarn exists in aws-auth configmap") + return nil, fmt.Errorf("failure checking, username %v or rolearn %v exists in aws-auth configmap", maprole.Spec.Username, maprole.Spec.RoleARN) + } else { + mapuserlog.Info("username and rolearn not exists in aws-auth configmap") + }*/ return nil, nil } diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index d5df145..314f9d4 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -19,7 +19,6 @@ package v1beta1 import ( "context" "fmt" - "time" "k8s.io/apimachinery/pkg/runtime" @@ -31,7 +30,6 @@ import ( awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" "github.com/redacid/aws-auth-controller/awsauth" - "github.com/redacid/aws-auth-controller/kube" ) // nolint:unused @@ -134,37 +132,37 @@ func (v *MapUserCustomValidator) ValidateCreate(ctx context.Context, obj runtime } // ----- - kubeClient, err := kube.GetClient() - if err != nil { - mapuserlog.Error(err, "Failure getting kube client") - return nil, err - } - - // Get a new aws auth service object. - awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ - KubeClient: kubeClient, - Log: ctrl.Log, - MaxRetryCount: 5, - }) - if err != nil { - mapuserlog.Error(err, "Failure creating new aws auth service") - return nil, err - } - if err := awsauth.VerifyUsername(mapuser.Spec.Username, awsauth.UsernameMustBeEmail); err != nil { return nil, err } - if err := awsauthSvc.CheckMapUserExists(awsauth.MapUser{ - Username: mapuser.Spec.Username, - UserARN: mapuser.Spec.UserARN, - Groups: mapuser.Spec.Groups, - }); err != nil { - mapuserlog.Info("Failure checking, username or userarn exists in aws-auth configmap") - return nil, fmt.Errorf("failure checking, username %v or userarn %v exists in aws-auth configmap", mapuser.Spec.Username, mapuser.Spec.UserARN) - } else { - mapuserlog.Info("username and userarn not exists in aws-auth configmap") - } + /* kubeClient, err := kube.GetClient() + if err != nil { + mapuserlog.Error(err, "Failure getting kube client") + return nil, err + } + + // Get a new aws auth service object. + awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ + KubeClient: kubeClient, + Log: ctrl.Log, + MaxRetryCount: 5, + }) + if err != nil { + mapuserlog.Error(err, "Failure creating new aws auth service") + return nil, err + } + + if err := awsauthSvc.CheckMapUserExists(awsauth.MapUser{ + Username: mapuser.Spec.Username, + UserARN: mapuser.Spec.UserARN, + Groups: mapuser.Spec.Groups, + }); err != nil { + mapuserlog.Info("Failure checking, username or userarn exists in aws-auth configmap") + return nil, fmt.Errorf("failure checking, username %v or userarn %v exists in aws-auth configmap", mapuser.Spec.Username, mapuser.Spec.UserARN) + } else { + mapuserlog.Info("username and userarn not exists in aws-auth configmap") + }*/ return nil, nil } From e32c6fa1fe0c6133a89b8d5e3493c428a709a190 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sun, 13 Jul 2025 10:02:04 +0300 Subject: [PATCH 24/58] fix logging --- Makefile | 2 +- config/manager/kustomization.yaml | 2 +- config/manager/manager.yaml | 2 +- .../samples/aws-auth_v1beta1_mapaccount.yaml | 14 +------------ internal/controller/mapaccount_controller.go | 21 +++++++++---------- internal/controller/maprole_controller.go | 16 +++++++------- internal/controller/mapuser_controller.go | 18 ++++++++-------- .../webhook/v1beta1/mapaccount_webhook.go | 3 ++- 8 files changed, 33 insertions(+), 45 deletions(-) diff --git a/Makefile b/Makefile index a9d265e..86ba487 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.75 +IMG ?= redacid/aws-auth-controller-dev:0.0.79 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 0e2b168..5e9edc4 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.75 + newTag: 0.0.79 diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index 63d2bc1..e5d7368 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -62,7 +62,7 @@ spec: - /manager args: - --config-map-name=aws-auth-test - - --must-present-account-id=123456789012 + - --must-present-account-id=130488995195 - --crd-item-allowed-namespace=kube-system #- --username-must-be-email - --leader-elect diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index fa9788c..37e0a0e 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -18,16 +18,4 @@ metadata: app.kubernetes.io/managed-by: kustomize name: account2 spec: - accountid: "222222222222" - ---- - -apiVersion: aws-auth.prozorro.sale/v1beta1 -kind: MapAccount -metadata: - labels: - app.kubernetes.io/name: aws-auth-controller-prozorro - app.kubernetes.io/managed-by: kustomize - name: account3 -spec: - accountid: "333333333333" \ No newline at end of file + accountid: "130488995195" diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 46cb0a9..0ec903c 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -59,9 +59,8 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) // MapAccount objects a list of AWS Accounts. mapAccountName := req.Name - log := ctrl.Log.WithValues("----------MapAccount", mapAccountName) - - log.Info("---------------------------------------------------") + log := ctrl.Log.WithValues("MapAccount", mapAccountName) + log.Info("reconciling MapAccount...") kubeClient, err := kube.GetClient() if err != nil { @@ -95,10 +94,10 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) } // examine DeletionTimestamp to determine if object is under deletion if mapAccount.DeletionTimestamp.IsZero() { - logf.Log.Info("mapAccount is not being deleted") + logf.Log.Info("mapAccount is not being deleted: " + mapAccount.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { - logf.Log.Info("mapAccount is not being deleted, so adding finalizer") + logf.Log.Info("adding finalizer: " + mapAccount.Name) controllerutil.AddFinalizer(mapAccount, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapAccount); err != nil { return ctrl.Result{}, err @@ -108,28 +107,28 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) if err := awsauthSvc.UpsertMapAccount(awsauth.MapAccount{ AccountID: mapAccount.Spec.AccountID, }); err != nil { - log.Error(err, "Failure upserting MapAccount") + log.Error(err, "Failure upserting MapAccount: "+mapAccount.Name) return ctrl.Result{}, err } - log.Info("Upserted MapAccount") + log.Info("Upserted MapAccount: " + mapAccount.Name) } } else { - log.Info("mapAccount is being deleted") + log.Info("mapAccount is being deleted: " + mapAccount.Name) if controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { if err := awsauthSvc.RemoveMapAccount(awsauth.MapAccount{ AccountID: mapAccount.Spec.AccountID, }); err != nil { - log.Error(err, "Failure removing mapAccount data in aws-auth configmap") + log.Error(err, "Failure removing mapAccount data in aws-auth configmap: "+mapAccount.Name) return ctrl.Result{}, nil } - logf.Log.Info("Removing finalizer") + logf.Log.Info("Removing finalizer: " + mapAccount.Name) controllerutil.RemoveFinalizer(mapAccount, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapAccount); err != nil { return ctrl.Result{}, err } } - log.Info("Removed mapAccount data in aws-auth configmap") + log.Info("Removed mapAccount data in aws-auth configmap: " + mapAccount.Name) return ctrl.Result{}, nil } return ctrl.Result{}, nil diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index 3a6faa9..8b4a047 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -92,10 +92,10 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct } if mapRole.DeletionTimestamp.IsZero() { - logf.Log.Info("mapRole is not being deleted") + logf.Log.Info("mapRole is not being deleted: " + mapRole.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapRole, awsauth.CrdFinalizerName) { - logf.Log.Info("mapRole is not being deleted, so adding finalizer") + logf.Log.Info("Adding finalizer: " + mapRole.Name) controllerutil.AddFinalizer(mapRole, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapRole); err != nil { return ctrl.Result{}, err @@ -107,29 +107,29 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct RoleARN: mapRole.Spec.RoleARN, Groups: mapRole.Spec.Groups, }); err != nil { - log.Error(err, "failure upserting MapRole") + log.Error(err, "failure upserting MapRole: "+mapRole.Name) return ctrl.Result{}, err } - log.Info("upserted MapRole") + log.Info("upserted MapRole: " + mapRole.Name) } } else { - log.Info("mapRole is being deleted") + log.Info("mapRole is being deleted: " + mapRole.Name) if controllerutil.ContainsFinalizer(mapRole, awsauth.CrdFinalizerName) { if err := awsauthSvc.RemoveMapRole(awsauth.MapRole{ Username: mapRole.Spec.Username, RoleARN: mapRole.Spec.RoleARN, Groups: mapRole.Spec.Groups, }); err != nil { - log.Error(err, "failure removing mapRole data in aws-auth configmap") + log.Error(err, "failure removing mapRole data in aws-auth configmap: "+mapRole.Name) return ctrl.Result{}, nil } - logf.Log.Info("Removing finalizer") + logf.Log.Info("Removing finalizer: " + mapRole.Name) controllerutil.RemoveFinalizer(mapRole, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapRole); err != nil { return ctrl.Result{}, err } } - log.Info("removed mapRole data in aws-auth configmap") + log.Info("removed mapRole data in aws-auth configmap: " + mapRole.Name) return ctrl.Result{}, nil } diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index e19db82..f184cac 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -60,7 +60,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct mapUserName := req.Name log := ctrl.Log.WithValues("MapUser", mapUserName) // log := r. Log.WithValues("MapUser", mapUserName) - log.Info("") + log.Info("reconciling MapUser...") kubeClient, err := kube.GetClient() if err != nil { @@ -93,10 +93,10 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct return ctrl.Result{}, nil } if mapUser.DeletionTimestamp.IsZero() { - logf.Log.Info("mapUser is not being deleted") + logf.Log.Info("mapUser is not being deleted: " + mapUser.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { - logf.Log.Info("mapUser is not being deleted, so adding finalizer") + logf.Log.Info("Adding finalizer: " + mapUser.Name) controllerutil.AddFinalizer(mapUser, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapUser); err != nil { return ctrl.Result{}, err @@ -108,29 +108,29 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct UserARN: mapUser.Spec.UserARN, Groups: mapUser.Spec.Groups, }); err != nil { - log.Error(err, "failure upserting MapUser") + log.Error(err, "failure upserting MapUser: "+mapUser.Name) return ctrl.Result{}, err } - log.Info("upserted MapUser") + log.Info("upserted MapUser: " + mapUser.Name) } } else { - log.Info("mapUser is being deleted") + log.Info("mapUser is being deleted: " + mapUser.Name) if controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { if err := awsauthSvc.RemoveMapUser(awsauth.MapUser{ Username: mapUser.Spec.Username, UserARN: mapUser.Spec.UserARN, Groups: mapUser.Spec.Groups, }); err != nil { - log.Error(err, "failure removing mapUser data in aws-auth configmap") + log.Error(err, "failure removing mapUser data in aws-auth configmap: "+mapUser.Name) return ctrl.Result{}, nil } - logf.Log.Info("Removing finalizer") + logf.Log.Info("Removing finalizer: " + mapUser.Name) controllerutil.RemoveFinalizer(mapUser, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapUser); err != nil { return ctrl.Result{}, err } } - log.Info("removed mapUser data in aws-auth configmap") + log.Info("removed mapUser data in aws-auth configmap: " + mapUser.Name) return ctrl.Result{}, nil } diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index 47cf6b3..36abdc6 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -182,7 +182,8 @@ func (v *MapAccountCustomValidator) ValidateDelete(_ context.Context, obj runtim mapaccountlog.Info("Validation for MapAccount upon deletion", "name", mapaccount.GetName(), "AccountID", mapaccount.Spec) if mapaccount.Spec.AccountID == awsauth.MustPresentAccountID { - return nil, fmt.Errorf("cannot delete MapAccount with AccountID %s", awsauth.MustPresentAccountID) + mapaccountlog.Info("cannot delete MapAccount is must-present-account-id", "AccountID", mapaccount.Spec.AccountID) + return nil, fmt.Errorf("cannot delete MapAccount with AccountID %s is must-present-account-id", mapaccount.Spec.AccountID) } return nil, nil From ebf2d7b78e0cde038fe3e98ebc98f18c9b239ef7 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sun, 13 Jul 2025 11:01:57 +0300 Subject: [PATCH 25/58] fix logging --- Makefile | 2 +- awsauth/mapper.go | 4 ++-- config/manager/kustomization.yaml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 86ba487..1d6611e 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.79 +IMG ?= redacid/aws-auth-controller-dev:0.0.81 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 3ae1d88..89f32f2 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -308,7 +308,7 @@ func (m *Mapper) upsertAuth(args *Arguments) error { if ok { log.Printf("%s with username '%s' key has been updated\n", args.DataType, args.Username) } else { - log.Printf("%s with username '%s' key has been updated\n", args.DataType, args.Username) + log.Printf("no updates needed to %s with username '%s'\n", args.DataType, args.Username) } authData.SetMapUsers(newMap) } @@ -319,7 +319,7 @@ func (m *Mapper) upsertAuth(args *Arguments) error { if ok { log.Printf("%s with account id '%s' key has been updated\n", args.DataType, args.AccountID) } else { - log.Printf("%s with account id '%s' key has been updated\n", args.DataType, args.AccountID) + log.Printf("no updates needed to %s with account id '%s'\n", args.DataType, args.AccountID) } authData.SetMapAccounts(newMap) } diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 5e9edc4..352c80c 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.79 + newTag: 0.0.81 From 0b6261f38fae12bb249220a3f5d86a6df8b3e330 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Sun, 13 Jul 2025 11:45:10 +0300 Subject: [PATCH 26/58] set retry params --- Makefile | 2 +- awsauth/retry.go | 38 +++++++++++++++++--- config/manager/kustomization.yaml | 2 +- internal/controller/mapaccount_controller.go | 4 +++ internal/controller/maprole_controller.go | 4 +++ internal/controller/mapuser_controller.go | 4 +++ 6 files changed, 48 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 1d6611e..00ba109 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.81 +IMG ?= redacid/aws-auth-controller-dev:0.0.83 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/awsauth/retry.go b/awsauth/retry.go index db3d15d..649cb4e 100644 --- a/awsauth/retry.go +++ b/awsauth/retry.go @@ -16,11 +16,11 @@ limitations under the License. package awsauth import ( - "log" - "time" - "github.com/jpillora/backoff" "github.com/pkg/errors" + "log" + "strings" + "time" ) const ( @@ -30,7 +30,7 @@ const ( // WithRetry runs the passed operation function with its arguments and retries // on failures until success or max number of retry attempts have failed. -func WithRetry(fn func(*Arguments) error, args *Arguments) error { +/*func WithRetry(fn func(*Arguments) error, args *Arguments) error { var ( counter int err error @@ -54,4 +54,34 @@ func WithRetry(fn func(*Arguments) error, args *Arguments) error { } return errors.Wrap(err, "waiter timed out") +}*/ +func WithRetry(fn func(*Arguments) error, args *Arguments) error { + var ( + counter int + err error + bkoff = &backoff.Backoff{ + Min: args.MinRetryTime, + Max: args.MaxRetryTime, + Factor: defaultRetryerBackoffFactor, + Jitter: defaultRetryerBackoffJitter, + } + ) + + for counter < args.MaxRetryCount { + if err = fn(args); err != nil { + // Check if error is related to ConfigMap conflict + if strings.Contains(err.Error(), "the object has been modified") { + d := bkoff.Duration() + log.Printf("ConfigMap conflict detected: %v: will retry after %v", err, d) + time.Sleep(d) + counter++ + continue + } + // Return immediately for other types of errors + return err + } + return nil + } + + return errors.Wrap(err, "max retry attempts exceeded") } diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 352c80c..48c2d7c 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.81 + newTag: 0.0.83 diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 0ec903c..4a4308d 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -18,6 +18,7 @@ package controller import ( "context" + "time" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" @@ -73,7 +74,10 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) KubeClient: kubeClient, // Log: r.Log, Log: ctrl.Log, + WithRetries: true, MaxRetryCount: 5, + MinRetryTime: time.Millisecond * 100, + MaxRetryTime: time.Second * 3, }) if err != nil { log.Error(err, "Failure creating new aws auth service") diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index 8b4a047..726b343 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -19,6 +19,7 @@ package controller import ( "context" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "time" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" @@ -71,7 +72,10 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct KubeClient: kubeClient, // Log: r.Log, Log: ctrl.Log, + WithRetries: true, MaxRetryCount: 5, + MinRetryTime: time.Millisecond * 100, + MaxRetryTime: time.Second * 3, }) if err != nil { log.Error(err, "failure creating new aws auth service") diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index f184cac..6ae5ebf 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -18,6 +18,7 @@ package controller import ( "context" + "time" apierrors "k8s.io/apimachinery/pkg/api/errors" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" @@ -73,7 +74,10 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct KubeClient: kubeClient, // Log: r.Log, Log: ctrl.Log, + WithRetries: true, MaxRetryCount: 5, + MinRetryTime: time.Millisecond * 100, + MaxRetryTime: time.Second * 3, }) if err != nil { log.Error(err, "failure creating new aws auth service") From 34728a3eeed298b96df65dfd19f6adf80946bfd9 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 14 Jul 2025 09:40:51 +0300 Subject: [PATCH 27/58] edt logs output --- TODO.md | 5 +- awsauth/mapper.go | 8 +- .../samples/aws-auth_v1beta1_mapaccount.yaml | 4 +- config/samples/aws-auth_v1beta1_maprole.yaml | 7 +- config/samples/aws-auth_v1beta1_mapuser.yaml | 93 ++++++++++--------- 5 files changed, 61 insertions(+), 56 deletions(-) diff --git a/TODO.md b/TODO.md index 4667bd7..101841a 100644 --- a/TODO.md +++ b/TODO.md @@ -1,4 +1,7 @@ ~~Додати флаг CrdAllowedNamespace, для контролю створення ресурсів~~ * Реалізувати додавання акаунта за замовчуванням * Дізнатися як обробляти дублікати при створенні ролей -* Прибрати зайве логування \ No newline at end of file +* Прибрати зайве логування, налаштувати поточне +* Переробити тести +* Написати helm chart +* Написати документацію \ No newline at end of file diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 89f32f2..c2dec52 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -295,9 +295,9 @@ func (m *Mapper) upsertAuth(args *Arguments) error { mapRole := NewMapRole(args.RoleARN, args.Username, args.Groups) newMap, ok := upsertRole(authData.MapRoles, mapRole) if ok { - log.Printf("%s with username '%s' key has been updated\n", args.DataType, args.Username) + log.Printf("%s with username '%s' and rolearn '%s' key has been updated\n", args.DataType, args.Username, args.RoleARN) } else { - log.Printf("no updates needed to %s with username '%s'\n", args.DataType, args.Username) + log.Printf("no updates needed to %s with username '%s' and rolearn '%s'\n", args.DataType, args.Username, args.RoleARN) } authData.SetMapRoles(newMap) } @@ -306,9 +306,9 @@ func (m *Mapper) upsertAuth(args *Arguments) error { mapUser := NewMapUser(args.UserARN, args.Username, args.Groups) newMap, ok := upsertUser(authData.MapUsers, mapUser) if ok { - log.Printf("%s with username '%s' key has been updated\n", args.DataType, args.Username) + log.Printf("%s with username '%s' and userarn '%s' key has been updated\n", args.DataType, args.Username, args.UserARN) } else { - log.Printf("no updates needed to %s with username '%s'\n", args.DataType, args.Username) + log.Printf("no updates needed to %s with username '%s' and userarn '%s'\n", args.DataType, args.Username, args.UserARN) } authData.SetMapUsers(newMap) } diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index 37e0a0e..191cf70 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: account1 + name: account-111111111111 spec: accountid: "111111111111" @@ -16,6 +16,6 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: account2 + name: account-130488995195 spec: accountid: "130488995195" diff --git a/config/samples/aws-auth_v1beta1_maprole.yaml b/config/samples/aws-auth_v1beta1_maprole.yaml index f82680f..a8950b6 100644 --- a/config/samples/aws-auth_v1beta1_maprole.yaml +++ b/config/samples/aws-auth_v1beta1_maprole.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: maprole1 + name: maprole_prod-self-managed-node-group spec: rolearn: arn:aws:iam::130488995195:role/prod-self-managed-node-group groups: @@ -21,11 +21,12 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: maprole2 + name: maprole_self-mng-single-az-node-group spec: - rolearn: arn:aws:iam::130488995195:role/prod-self-managed-node-group2 + rolearn: arn:aws:iam::130488995195:role/self-mng-single-az-node-group-20240218223715755100000001 groups: - sample:group1 - sample:group2 + - sample:group3 description: A sample maprole username: system:node:{{EC2PrivateDNSName2}} \ No newline at end of file diff --git a/config/samples/aws-auth_v1beta1_mapuser.yaml b/config/samples/aws-auth_v1beta1_mapuser.yaml index f28fb0f..a454350 100644 --- a/config/samples/aws-auth_v1beta1_mapuser.yaml +++ b/config/samples/aws-auth_v1beta1_mapuser.yaml @@ -1,50 +1,51 @@ -#apiVersion: aws-auth.prozorro.sale/v1beta1 -#kind: MapUser -#metadata: -# labels: -# app.kubernetes.io/name: aws-auth-controller-prozorro -# app.kubernetes.io/managed-by: kustomize -# name: user1 -#spec: -# description: A test mapuser -# username: user1@ios.in.ua -# groups: -# - system:masters -# - admins -# userarn: arn:aws:iam::123456789012:user/user1 -# -#--- -#apiVersion: aws-auth.prozorro.sale/v1beta1 -#kind: MapUser -#metadata: -# labels: -# app.kubernetes.io/name: aws-auth-controller-prozorro -# app.kubernetes.io/managed-by: kustomize -# name: user2 -#spec: -# description: A test mapuser -# username: user2@ios.in.ua -# groups: -# - system:masters -# - admins -# userarn: arn:aws:iam::123456789012:user/user2 -# -#--- -#apiVersion: aws-auth.prozorro.sale/v1beta1 -#kind: MapUser -#metadata: -# labels: -# app.kubernetes.io/name: aws-auth-controller-prozorro -# app.kubernetes.io/managed-by: kustomize -# name: user3 -#spec: -# description: A test mapuser -# username: user3@ios.in.ua -# groups: -# - system:masters -# - users -# userarn: arn:aws:iam::123456789012:user/user3 +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapUser +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: user1 +spec: + description: A test mapuser + username: user1@ios.in.ua + groups: + - system:masters + - admins + userarn: arn:aws:iam::123456789012:user/user1 + +--- +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapUser +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: user2 +spec: + description: A test mapuser + username: user2@ios.in.ua + groups: + - system:masters + - admins + userarn: arn:aws:iam::123456789012:user/user2 + +--- +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapUser +metadata: + labels: + app.kubernetes.io/name: aws-auth-controller-prozorro + app.kubernetes.io/managed-by: kustomize + name: user3 +spec: + description: A test mapuser + username: user3@ios.in.ua + groups: + - system:masters + - users + userarn: arn:aws:iam::123456789012:user/user3 +--- apiVersion: aws-auth.prozorro.sale/v1beta1 kind: MapUser metadata: From 25e0c78353b0170a856539c4db84291ffa592d69 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 14 Jul 2025 17:51:24 +0300 Subject: [PATCH 28/58] edt logs output --- Makefile | 2 +- README.md | 6 +- awsauth/data.go | 12 ++- awsauth/mapper.go | 100 +++++++++++-------- awsauth/retry.go | 3 +- cmd/main.go | 5 + config/manager/kustomization.yaml | 2 +- config/manager/manager.yaml | 1 + config/samples/aws-auth_v1beta1_maprole.yaml | 4 +- internal/controller/mapaccount_controller.go | 27 +++-- internal/controller/maprole_controller.go | 29 +++--- internal/controller/mapuser_controller.go | 31 +++--- internal/webhook/v1beta1/maprole_webhook.go | 3 +- 13 files changed, 125 insertions(+), 100 deletions(-) diff --git a/Makefile b/Makefile index 00ba109..2c3bf12 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.83 +IMG ?= redacid/aws-auth-controller-dev:0.0.89 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/README.md b/README.md index 5711d8b..a869ba9 100644 --- a/README.md +++ b/README.md @@ -20,4 +20,8 @@ cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapaccount.yaml -n kube-sy https://book.kubebuilder.io/reference/using-finalizers https://book.kubebuilder.io/reference/markers/crd-validation -https://github.com/gp42/aws-auth-operator \ No newline at end of file +https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/reconcile/reconcile.go#L46 +https://book.kubebuilder.io/reference/watching-resources.html?highlight=RequeueAfter#when-requeueafter-x-is-useful + +https://github.com/gp42/aws-auth-operator + diff --git a/awsauth/data.go b/awsauth/data.go index a38c3c7..0eb57fa 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -18,7 +18,9 @@ package awsauth import ( "context" "fmt" - "log" + "time" + + // "log" "sync" "gopkg.in/yaml.v2" @@ -31,7 +33,7 @@ import ( ) func init() { - log.SetFlags(0) + //log.SetFlags(0) } const ( @@ -46,7 +48,9 @@ var ( // TODO automatic add to configmap MustPresentAccountID string = "" CrdItemAllowedNamespace string = "" - configMapMutex sync.RWMutex + + ReconcileTime time.Duration = time.Minute * 30 + configMapMutex sync.RWMutex ) type ControllerArgs struct { @@ -54,6 +58,7 @@ type ControllerArgs struct { MustPresentAccountID string CrdItemAllowedNamespace string ConfigMapName string + ReconcileTime time.Duration } func DeclareVariables(controllerArgs ControllerArgs) { @@ -61,6 +66,7 @@ func DeclareVariables(controllerArgs ControllerArgs) { MustPresentAccountID = controllerArgs.MustPresentAccountID CrdItemAllowedNamespace = controllerArgs.CrdItemAllowedNamespace ConfigMapName = controllerArgs.ConfigMapName + ReconcileTime = controllerArgs.ReconcileTime } // ReadAuthMap reads the auth ConfigMap and returns AwsAuthData and the read ConfigMap. diff --git a/awsauth/mapper.go b/awsauth/mapper.go index c2dec52..28011fb 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -17,9 +17,10 @@ package awsauth import ( "fmt" + "github.com/go-logr/logr" + ctrl "sigs.k8s.io/controller-runtime" + logf "sigs.k8s.io/controller-runtime/pkg/log" - "io" - "log" "reflect" "time" @@ -41,31 +42,34 @@ type Arguments struct { MaxRetryCount int } +var logger = ctrl.Log.WithName("mapper") + // Validate validates if all Arguments fields are valid. func (args *Arguments) Validate() { + if args.WithRetries && args.MaxRetryCount < 1 { - log.Println("error: retry max count is invalid, must be greater than zero") + logger.Info("error: retry max count is invalid, must be greater than zero", "MaxRetryCount", args.MaxRetryCount) } if args.Username == "" { - log.Println("error: username not provided") + logger.Info("error: username not provided") } if args.OperationType == "" { - log.Println("error: operation type not provided") + logger.Info("error: operation type not provided") } if args.OperationType != UpsertOperation && args.OperationType != RemoveOperation { - log.Printf("error: operation type '%s' not valid\n", args.OperationType) + logger.Info("error: operation type '%s' not valid\n", args.OperationType) } if args.DataType == "" { - log.Println("error: data type not provided") + logger.Info("error: data type not provided") } if args.DataType != MapRoleData && args.DataType != MapUserData && args.DataType != MapAccountData { - log.Printf("error: data type '%s' not valid\n", args.DataType) + logger.Info("error: data type '%s' not valid\n", args.DataType) } if args.OperationType == UpsertOperation && args.DataType == MapRoleData && args.RoleARN == "" { - log.Println("error: role arn not provided") + logger.Info("error: role arn not provided") } if args.OperationType == UpsertOperation && args.DataType == MapUserData && args.UserARN == "" { - log.Println("error: user arn not provided") + logger.Info("error: user arn not provided") } } @@ -89,18 +93,19 @@ const ( // NewMapper returns a new Mapper object. func NewMapper(client kubernetes.Interface, discardLogOutput bool) *Mapper { - var mapper = &Mapper{} - mapper.KubernetesClient = client - - if discardLogOutput { - log.SetOutput(io.Discard) + var mapper = &Mapper{ + KubernetesClient: client, + Log: logf.Log.WithName("mapper"), } + return mapper + } // Mapper is responsible for managing the auth map. type Mapper struct { KubernetesClient kubernetes.Interface + Log logr.Logger } // Remove removes a mapRole or mapUser from the auth map. @@ -178,39 +183,39 @@ func (m *Mapper) existsAuth(args *Arguments) error { } if args.DataType == MapAccountData { - log.Printf("authData.MapAccounts: %v\n", authData.MapAccounts) + m.Log.Info("existsAuth", "DataType", args.DataType, "AccountID", args.AccountID) mapAccount := NewMapAccount(args.AccountID) err, exists := existsAccount(authData.MapAccounts, mapAccount) if exists { - log.Printf("%v", err) + m.Log.Info("%v", err) return err } else { - log.Printf("%s with account id '%s' not exists\n", args.DataType, args.AccountID) + m.Log.Info("MapAccount not exists", "DataType", args.DataType, "AccountID", args.AccountID) return nil } } if args.DataType == MapUserData { - log.Printf("authData.MapUsers: %v\n", authData.MapUsers) + m.Log.Info("existsAuth", "DataType", args.DataType, "Username", args.Username, "UserARN", args.UserARN) mapUser := NewMapUser(args.UserARN, args.Username, args.Groups) err, exists := existsUser(authData.MapUsers, mapUser) if exists { - log.Printf("%v", err) + m.Log.Info("%v", err) return err } else { - log.Printf("%s with username '%s' or userarn '%s' not exists\n", args.DataType, args.Username, args.UserARN) + m.Log.Info("MapUser not exists", "DataType", args.DataType, "Username", args.Username, "UserARN", args.UserARN) return nil } } if args.DataType == MapRoleData { - log.Printf("authData.MapRoles: %v\n", authData.MapRoles) + m.Log.Info("existsAuth", "DataType", args.DataType, "Username", args.Username, "RoleARN", args.RoleARN) mapRole := NewMapRole(args.RoleARN, args.Username, args.Groups) err, exists := existsRole(authData.MapRoles, mapRole) if exists { - log.Printf("%v", err) + m.Log.Info("%v", err) return err } else { - log.Printf("%s with username '%s' or rolearn '%s' not exists\n", args.DataType, args.Username, args.RoleARN) + m.Log.Info("MapRole not exists", "DataType", args.DataType, "Username", args.Username, "RoleARN", args.RoleARN) return nil } } @@ -220,16 +225,17 @@ func (m *Mapper) existsAuth(args *Arguments) error { func existsAccount(authMaps []*MapAccount, resource *MapAccount) (error, bool) { var found = false - log.Printf("existsAccount check: account id: %v \n", resource.AccountID) + //log.Printf("existsAccount check: account id: %v \n", resource.AccountID) + logger.Info("existsAccount", "AccountID", resource.AccountID) for _, existing := range authMaps { - log.Printf("existsAccount: cm account id: %v \n", existing.AccountID) - log.Printf("existsAccount: new account id: %v \n", resource.AccountID) + logger.Info("existsAccount.Compare", "cm account id", existing.AccountID, "new account id", resource.AccountID) + //log.Printf("existsAccount: cm account id: %v \n", existing.AccountID) + //log.Printf("existsAccount: new account id: %v \n", resource.AccountID) if existing.AccountID == resource.AccountID { found = true return fmt.Errorf("account with id '%s' already exists", resource.AccountID), found } else { found = false - // return nil, found } } return nil, found @@ -237,10 +243,13 @@ func existsAccount(authMaps []*MapAccount, resource *MapAccount) (error, bool) { func existsUser(authMaps []*MapUser, resource *MapUser) (error, bool) { var found = false - log.Printf("existsUser check: username: %v userarn:%v \n", resource.Username, resource.UserARN) + //log.Printf("existsUser check: username: %v userarn:%v \n", resource.Username, resource.UserARN) + logger.Info("existsUser", "Username", resource.Username, "UserARN", resource.UserARN) for _, existing := range authMaps { - log.Printf("existsUser: cm username: %v userarn: %v \n", existing.Username, existing.UserARN) - log.Printf("existsUser: new username: %v userarn: %v \n", resource.Username, resource.UserARN) + logger.Info("existsUser.Compare", "cm username", existing.Username, "new username", resource.Username) + logger.Info("existsUser.Compare", "cm userarn", existing.UserARN, "new userarn", resource.UserARN) + //log.Printf("existsUser: cm username: %v userarn: %v \n", existing.Username, existing.UserARN) + //log.Printf("existsUser: new username: %v userarn: %v \n", resource.Username, resource.UserARN) if existing.Username == resource.Username { found = true return fmt.Errorf("existsUser: username '%s' already exists", resource.Username), found @@ -249,7 +258,6 @@ func existsUser(authMaps []*MapUser, resource *MapUser) (error, bool) { return fmt.Errorf("existsUser: userarn '%s' already exists", resource.UserARN), found } else { found = false - // return nil, found } } return nil, found @@ -257,10 +265,13 @@ func existsUser(authMaps []*MapUser, resource *MapUser) (error, bool) { func existsRole(authMaps []*MapRole, resource *MapRole) (error, bool) { var found = false - log.Printf("existsRole check: username: %v rolearn:%v \n", resource.Username, resource.RoleARN) + //log.Printf("existsRole check: username: %v rolearn:%v \n", resource.Username, resource.RoleARN) + logger.Info("existsRole", "Username", resource.Username, "RoleARN", resource.RoleARN) for _, existing := range authMaps { - log.Printf("existsRole: cm username: %v rolearn: %v \n", existing.Username, existing.RoleARN) - log.Printf("existsRole: new username: %v rolearn: %v \n", resource.Username, resource.RoleARN) + //log.Printf("existsRole: cm username: %v rolearn: %v \n", existing.Username, existing.RoleARN) + //log.Printf("existsRole: new username: %v rolearn: %v \n", resource.Username, resource.RoleARN) + logger.Info("existsRole.Compare", "cm username", existing.Username, "new username", resource.Username) + logger.Info("existsRole.Compare", "cm rolearn", existing.RoleARN, "new rolearn", resource.RoleARN) if existing.Username == resource.Username { found = true return fmt.Errorf("existsRole: username '%s' already exists", resource.Username), found @@ -269,7 +280,6 @@ func existsRole(authMaps []*MapRole, resource *MapRole) (error, bool) { return fmt.Errorf("existsRole: rolearn '%s' already exists", resource.RoleARN), found } else { found = false - // return nil, found } } return nil, found @@ -295,9 +305,11 @@ func (m *Mapper) upsertAuth(args *Arguments) error { mapRole := NewMapRole(args.RoleARN, args.Username, args.Groups) newMap, ok := upsertRole(authData.MapRoles, mapRole) if ok { - log.Printf("%s with username '%s' and rolearn '%s' key has been updated\n", args.DataType, args.Username, args.RoleARN) + // log.Printf("%s with username '%s' and rolearn '%s' key has been updated\n", args.DataType, args.Username, args.RoleARN) + logger.Info("upsertAuth.Updated", "DataType", args.DataType, "Username", args.Username, "RoleARN", args.RoleARN) } else { - log.Printf("no updates needed to %s with username '%s' and rolearn '%s'\n", args.DataType, args.Username, args.RoleARN) + // log.Printf("no updates needed to %s with username '%s' and rolearn '%s'\n", args.DataType, args.Username, args.RoleARN) + // logger.Info("upsertAuth.NoNeedUpdate", "DataType", args.DataType, "Username", args.Username, "RoleARN", args.RoleARN) } authData.SetMapRoles(newMap) } @@ -306,9 +318,11 @@ func (m *Mapper) upsertAuth(args *Arguments) error { mapUser := NewMapUser(args.UserARN, args.Username, args.Groups) newMap, ok := upsertUser(authData.MapUsers, mapUser) if ok { - log.Printf("%s with username '%s' and userarn '%s' key has been updated\n", args.DataType, args.Username, args.UserARN) + //log.Printf("%s with username '%s' and userarn '%s' key has been updated\n", args.DataType, args.Username, args.UserARN) + logger.Info("upsertAuth.Updated", "DataType", args.DataType, "Username", args.Username, "UserARN", args.UserARN) } else { - log.Printf("no updates needed to %s with username '%s' and userarn '%s'\n", args.DataType, args.Username, args.UserARN) + // log.Printf("no updates needed to %s with username '%s' and userarn '%s'\n", args.DataType, args.Username, args.UserARN) + // logger.Info("upsertAuth.NoNeedUpdate", "DataType", args.DataType, "Username", args.Username, "UserARN", args.UserARN) } authData.SetMapUsers(newMap) } @@ -317,9 +331,11 @@ func (m *Mapper) upsertAuth(args *Arguments) error { mapAccount := NewMapAccount(args.AccountID) newMap, ok := upsertAccount(authData.MapAccounts, mapAccount) if ok { - log.Printf("%s with account id '%s' key has been updated\n", args.DataType, args.AccountID) + // log.Printf("%s with account id '%s' key has been updated\n", args.DataType, args.AccountID) + logger.Info("upsertAuth.Updated", "DataType", args.DataType, "AccountID", args.AccountID) } else { - log.Printf("no updates needed to %s with account id '%s'\n", args.DataType, args.AccountID) + // log.Printf("no updates needed to %s with account id '%s'\n", args.DataType, args.AccountID) + // logger.Info("upsertAuth.NoNeedUpdate", "DataType", args.DataType, "AccountID", args.AccountID) } authData.SetMapAccounts(newMap) } diff --git a/awsauth/retry.go b/awsauth/retry.go index 649cb4e..1f1ab6d 100644 --- a/awsauth/retry.go +++ b/awsauth/retry.go @@ -18,7 +18,6 @@ package awsauth import ( "github.com/jpillora/backoff" "github.com/pkg/errors" - "log" "strings" "time" ) @@ -72,7 +71,7 @@ func WithRetry(fn func(*Arguments) error, args *Arguments) error { // Check if error is related to ConfigMap conflict if strings.Contains(err.Error(), "the object has been modified") { d := bkoff.Duration() - log.Printf("ConfigMap conflict detected: %v: will retry after %v", err, d) + logger.Info("ConfigMap conflict detected", "error", err, "retry after", d) time.Sleep(d) counter++ continue diff --git a/cmd/main.go b/cmd/main.go index f633460..9efc1be 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -21,6 +21,7 @@ import ( "flag" "os" "path/filepath" + "time" "github.com/redacid/aws-auth-controller/awsauth" @@ -70,6 +71,7 @@ func main() { var mustPresentAccountID string var crdItemAllowedNamespace string var configMapName string + var reconcileTime time.Duration var tlsOpts []func(*tls.Config) flag.BoolVar(&userNameMustBeEmail, "username-must-be-email", false, "Enables checking of username, should it be an email address, default false."+ @@ -82,6 +84,8 @@ func main() { " if not set, all namespaces allowed creation of Resources.") flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where store items,"+ " --config-map-name=aws-auth, if not set, use default name aws-auth") + flag.DurationVar(&reconcileTime, "reconcile-time", time.Minute*30, "Time to reconcile CRDs and recreate configmap item if need"+ + " --reconcile-time=30m, if not set, use default value 30 minutes") flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") @@ -121,6 +125,7 @@ func main() { MustPresentAccountID: mustPresentAccountID, CrdItemAllowedNamespace: crdItemAllowedNamespace, ConfigMapName: configMapName, + ReconcileTime: reconcileTime, } awsauth.DeclareVariables(declareVariables) diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 48c2d7c..0b24de1 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.83 + newTag: 0.0.89 diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index e5d7368..69832f9 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -64,6 +64,7 @@ spec: - --config-map-name=aws-auth-test - --must-present-account-id=130488995195 - --crd-item-allowed-namespace=kube-system + - --reconcile-time=30s #- --username-must-be-email - --leader-elect - --health-probe-bind-address=:8081 diff --git a/config/samples/aws-auth_v1beta1_maprole.yaml b/config/samples/aws-auth_v1beta1_maprole.yaml index a8950b6..6ea7e35 100644 --- a/config/samples/aws-auth_v1beta1_maprole.yaml +++ b/config/samples/aws-auth_v1beta1_maprole.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: maprole_prod-self-managed-node-group + name: maprole-prod-self-managed-node-group spec: rolearn: arn:aws:iam::130488995195:role/prod-self-managed-node-group groups: @@ -21,7 +21,7 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: maprole_self-mng-single-az-node-group + name: maprole-self-mng-single-az-node-group spec: rolearn: arn:aws:iam::130488995195:role/self-mng-single-az-node-group-20240218223715755100000001 groups: diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 4a4308d..ab7da73 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -59,9 +59,9 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) // TODO(user): your logic here // MapAccount objects a list of AWS Accounts. - mapAccountName := req.Name - log := ctrl.Log.WithValues("MapAccount", mapAccountName) - log.Info("reconciling MapAccount...") + + log := ctrl.Log.WithValues("MapAccount", req.Name, "namespace", req.Namespace) + log.Info("Reconciling MapAccount...") kubeClient, err := kube.GetClient() if err != nil { @@ -71,8 +71,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) // Get a new aws auth service object. awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ - KubeClient: kubeClient, - // Log: r.Log, + KubeClient: kubeClient, Log: ctrl.Log, WithRetries: true, MaxRetryCount: 5, @@ -98,10 +97,10 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) } // examine DeletionTimestamp to determine if object is under deletion if mapAccount.DeletionTimestamp.IsZero() { - logf.Log.Info("mapAccount is not being deleted: " + mapAccount.Name) + //logf.Log.Info("mapAccount is not being deleted: " + mapAccount.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { - logf.Log.Info("adding finalizer: " + mapAccount.Name) + logf.Log.Info("Adding finalizer: " + mapAccount.Name) controllerutil.AddFinalizer(mapAccount, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapAccount); err != nil { return ctrl.Result{}, err @@ -111,31 +110,31 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) if err := awsauthSvc.UpsertMapAccount(awsauth.MapAccount{ AccountID: mapAccount.Spec.AccountID, }); err != nil { - log.Error(err, "Failure upserting MapAccount: "+mapAccount.Name) + log.Error(err, "Failure upserting MapAccount") return ctrl.Result{}, err } - log.Info("Upserted MapAccount: " + mapAccount.Name) + //log.Info("Upserted MapAccount") } } else { - log.Info("mapAccount is being deleted: " + mapAccount.Name) + log.Info("mapAccount is being deleted") if controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { if err := awsauthSvc.RemoveMapAccount(awsauth.MapAccount{ AccountID: mapAccount.Spec.AccountID, }); err != nil { - log.Error(err, "Failure removing mapAccount data in aws-auth configmap: "+mapAccount.Name) + log.Error(err, "Failure removing mapAccount data in aws-auth configmap") return ctrl.Result{}, nil } - logf.Log.Info("Removing finalizer: " + mapAccount.Name) + log.Info("Removing finalizer") controllerutil.RemoveFinalizer(mapAccount, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapAccount); err != nil { return ctrl.Result{}, err } } - log.Info("Removed mapAccount data in aws-auth configmap: " + mapAccount.Name) + log.Info("Removed mapAccount data in aws-auth configmap") return ctrl.Result{}, nil } - return ctrl.Result{}, nil + return ctrl.Result{RequeueAfter: awsauth.ReconcileTime}, nil } // SetupWithManager sets up the controller with the Manager. diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index 726b343..c9e674e 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -56,14 +56,12 @@ type MapRoleReconciler struct { func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { _ = logf.FromContext(ctx) - mapRoleName := req.Name - - log := ctrl.Log.WithValues("MapRole", mapRoleName) - log.Info("reconciling MapRole...") + log := ctrl.Log.WithValues("MapRole", req.Name, "namespace", req.Namespace) + log.Info("Reconciling MapRole...") kubeClient, err := kube.GetClient() if err != nil { - log.Error(err, "failure getting kube client") + log.Error(err, "Failure getting kube client") return ctrl.Result{}, err } @@ -78,7 +76,7 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct MaxRetryTime: time.Second * 3, }) if err != nil { - log.Error(err, "failure creating new aws auth service") + log.Error(err, "Failure creating new aws auth service") return ctrl.Result{}, err } @@ -88,15 +86,14 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) if !ok || (ok && statusErr.ErrStatus.Reason != NotFound) { - log.Error(err, "failure getting MapRole") + log.Error(err, "Failure getting MapRole") return ctrl.Result{}, err } - log.Info("removed mapRole data in aws-auth configmap") return ctrl.Result{}, nil } if mapRole.DeletionTimestamp.IsZero() { - logf.Log.Info("mapRole is not being deleted: " + mapRole.Name) + //logf.Log.Info("mapRole is not being deleted: " + mapRole.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapRole, awsauth.CrdFinalizerName) { logf.Log.Info("Adding finalizer: " + mapRole.Name) @@ -111,33 +108,33 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct RoleARN: mapRole.Spec.RoleARN, Groups: mapRole.Spec.Groups, }); err != nil { - log.Error(err, "failure upserting MapRole: "+mapRole.Name) + log.Error(err, "Failure upserting MapRole") return ctrl.Result{}, err } - log.Info("upserted MapRole: " + mapRole.Name) + //log.Info("Upserted MapRole") } } else { - log.Info("mapRole is being deleted: " + mapRole.Name) + log.Info("mapRole is being deleted") if controllerutil.ContainsFinalizer(mapRole, awsauth.CrdFinalizerName) { if err := awsauthSvc.RemoveMapRole(awsauth.MapRole{ Username: mapRole.Spec.Username, RoleARN: mapRole.Spec.RoleARN, Groups: mapRole.Spec.Groups, }); err != nil { - log.Error(err, "failure removing mapRole data in aws-auth configmap: "+mapRole.Name) + log.Error(err, "Failure removing mapRole data in aws-auth configmap") return ctrl.Result{}, nil } - logf.Log.Info("Removing finalizer: " + mapRole.Name) + log.Info("Removing finalizer") controllerutil.RemoveFinalizer(mapRole, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapRole); err != nil { return ctrl.Result{}, err } } - log.Info("removed mapRole data in aws-auth configmap: " + mapRole.Name) + log.Info("Removed mapRole data in aws-auth configmap") return ctrl.Result{}, nil } - return ctrl.Result{}, nil + return ctrl.Result{RequeueAfter: awsauth.ReconcileTime}, nil } // SetupWithManager sets up the controller with the Manager. diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index 6ae5ebf..7af95e0 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -58,21 +58,18 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct _ = logf.FromContext(ctx) // MapUser objects are named by their associated AWS IAM user ARNs. - mapUserName := req.Name - log := ctrl.Log.WithValues("MapUser", mapUserName) - // log := r. Log.WithValues("MapUser", mapUserName) - log.Info("reconciling MapUser...") + log := ctrl.Log.WithValues("MapUser", req.Name, "namespace", req.Namespace) + log.Info("Reconciling MapUser...") kubeClient, err := kube.GetClient() if err != nil { - log.Error(err, "failure getting kube client") + log.Error(err, "Failure getting kube client") return ctrl.Result{}, err } // Get a new aws auth service object. awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ - KubeClient: kubeClient, - // Log: r.Log, + KubeClient: kubeClient, Log: ctrl.Log, WithRetries: true, MaxRetryCount: 5, @@ -80,7 +77,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct MaxRetryTime: time.Second * 3, }) if err != nil { - log.Error(err, "failure creating new aws auth service") + log.Error(err, "Failure creating new aws auth service") return ctrl.Result{}, err } @@ -91,13 +88,13 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) if !ok || (ok && statusErr.ErrStatus.Reason != NotFound) { - logf.Log.Error(err, "failure getting MapUser") + logf.Log.Error(err, "Failure getting MapUser") return ctrl.Result{}, err } return ctrl.Result{}, nil } if mapUser.DeletionTimestamp.IsZero() { - logf.Log.Info("mapUser is not being deleted: " + mapUser.Name) + //logf.Log.Info("mapUser is not being deleted: " + mapUser.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { logf.Log.Info("Adding finalizer: " + mapUser.Name) @@ -112,33 +109,33 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct UserARN: mapUser.Spec.UserARN, Groups: mapUser.Spec.Groups, }); err != nil { - log.Error(err, "failure upserting MapUser: "+mapUser.Name) + log.Error(err, "Failure upserting MapUser") return ctrl.Result{}, err } - log.Info("upserted MapUser: " + mapUser.Name) + //log.Info("Upserted MapUser") } } else { - log.Info("mapUser is being deleted: " + mapUser.Name) + log.Info("mapUser is being deleted") if controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { if err := awsauthSvc.RemoveMapUser(awsauth.MapUser{ Username: mapUser.Spec.Username, UserARN: mapUser.Spec.UserARN, Groups: mapUser.Spec.Groups, }); err != nil { - log.Error(err, "failure removing mapUser data in aws-auth configmap: "+mapUser.Name) + log.Error(err, "Failure removing mapUser data in aws-auth configmap") return ctrl.Result{}, nil } - logf.Log.Info("Removing finalizer: " + mapUser.Name) + log.Info("Removing finalizer") controllerutil.RemoveFinalizer(mapUser, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapUser); err != nil { return ctrl.Result{}, err } } - log.Info("removed mapUser data in aws-auth configmap: " + mapUser.Name) + log.Info("Removed mapUser data in aws-auth configmap") return ctrl.Result{}, nil } - return ctrl.Result{}, nil + return ctrl.Result{RequeueAfter: awsauth.ReconcileTime}, nil } // SetupWithManager sets up the controller with the Manager. diff --git a/internal/webhook/v1beta1/maprole_webhook.go b/internal/webhook/v1beta1/maprole_webhook.go index 0fb959d..b01de9c 100644 --- a/internal/webhook/v1beta1/maprole_webhook.go +++ b/internal/webhook/v1beta1/maprole_webhook.go @@ -125,7 +125,8 @@ func (v *MapRoleCustomValidator) ValidateCreate(ctx context.Context, obj runtime return nil, err } for _, existingUser := range mapRoleList.Items { - if existingUser.Spec.Username+existingUser.Spec.RoleARN == maprole.Spec.Username+maprole.Spec.RoleARN { + if existingUser.Spec.Username == maprole.Spec.Username && + existingUser.Spec.RoleARN == maprole.Spec.RoleARN { return nil, fmt.Errorf("duplicate user data found: username %s or rolearn %s already exists in another MapRole resource: %s", maprole.Spec.Username, maprole.Spec.RoleARN, existingUser.GetName()) } From e99e5a7a4d05c1bf3a5780810175265d96146e53 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 15 Jul 2025 07:02:38 +0300 Subject: [PATCH 29/58] update deprecated func --- Dockerfile | 2 +- Makefile | 2 +- awsauth/data.go | 9 +++---- awsauth/data_test.go | 23 +++++++++++----- awsauth/mapper_test.go | 26 +++++++++---------- config/manager/kustomization.yaml | 2 +- config/manager/manager.yaml | 2 +- .../samples/aws-auth_v1beta1_mapaccount.yaml | 4 +-- config/samples/aws-auth_v1beta1_maprole.yaml | 4 +-- config/samples/aws-auth_v1beta1_mapuser.yaml | 22 +++------------- .../controller/mapaccount_controller_test.go | 11 +++++--- .../controller/maprole_controller_test.go | 15 ++++++++--- .../controller/mapuser_controller_test.go | 15 ++++++++--- 13 files changed, 76 insertions(+), 61 deletions(-) diff --git a/Dockerfile b/Dockerfile index 864b10f..1e5ae41 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,7 +12,7 @@ COPY go.sum go.sum RUN go mod download # Copy the go source -COPY cmd/main.go cmd/main.go +COPY "cmd"/ "cmd"/ COPY api/ api/ COPY internal/ internal/ COPY awsauth/ awsauth/ diff --git a/Makefile b/Makefile index 2c3bf12..7ca53ec 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.89 +IMG ?= redacid/aws-auth-controller-dev:0.0.91 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/awsauth/data.go b/awsauth/data.go index 0eb57fa..3597968 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -32,12 +32,7 @@ import ( "strings" ) -func init() { - //log.SetFlags(0) -} - const ( - // ConfigMapName = "aws-auth" ConfigMapNamespace = "kube-system" ) @@ -275,6 +270,10 @@ func (r *MapAccount) String() string { return s.String() } +func (r *MapAccount) String2() string { + return fmt.Sprintf("- %s", r.AccountID) +} + func NewMapAccount(accountid string) *MapAccount { return &MapAccount{ AccountID: accountid, diff --git a/awsauth/data_test.go b/awsauth/data_test.go index f67c44d..37d6319 100644 --- a/awsauth/data_test.go +++ b/awsauth/data_test.go @@ -34,8 +34,9 @@ func createMockConfigMap(client kubernetes.Interface) { user := NewMapUser( "arn:aws:iam::00000000000:user/user-1", - "testcrd", + "admin", []string{"system:masters"}) + account := NewMapAccount("111111111111") configMap := &v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ @@ -43,8 +44,9 @@ func createMockConfigMap(client kubernetes.Interface) { Namespace: ConfigMapNamespace, }, Data: map[string]string{ - "mapRoles": role.String(), - "mapUsers": user.String(), + "mapRoles": role.String(), + "mapUsers": user.String(), + "mapAccounts": account.String2(), }, } _, err := client.CoreV1().ConfigMaps(ConfigMapNamespace).Create( @@ -59,7 +61,7 @@ func createMockConfigMap(client kubernetes.Interface) { func TestUpdateAuthMap(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() createMockConfigMap(client) auth, cm, err := ReadAuthMap(client) @@ -68,11 +70,13 @@ func TestUpdateAuthMap(t *testing.T) { role := NewMapRole("arn:aws:iam::00000000000:role/node-2", "system:node:{{EC2PrivateDNSName}}", []string{"system:bootstrappers", "system:nodes"}) - user := NewMapUser("testcrd", "arn:aws:iam::00000000000:user/user-2", + user := NewMapUser("arn:aws:iam::00000000000:user/user-2", "admin", []string{"system:masters"}) + account := NewMapAccount("222222222222") auth.MapRoles = append(auth.MapRoles, role) auth.MapUsers = append(auth.MapUsers, user) + auth.MapAccounts = append(auth.MapAccounts, account) err = UpdateAuthMap(client, auth, cm) g.Expect(err).NotTo(gomega.HaveOccurred()) @@ -84,12 +88,13 @@ func TestUpdateAuthMap(t *testing.T) { fmt.Println(auth.MapRoles[0]) g.Expect(auth.MapRoles).To(gomega.HaveLen(2)) g.Expect(auth.MapUsers).To(gomega.HaveLen(2)) + g.Expect(auth.MapAccounts).To(gomega.HaveLen(2)) } func TestReadAuthMap(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() createMockConfigMap(client) auth, _, err := ReadAuthMap(client) @@ -103,15 +108,19 @@ func TestReadAuthMap(t *testing.T) { g.Expect(auth.MapUsers[0].UserARN).To(gomega.Equal("arn:aws:iam::00000000000:user/user-1")) g.Expect(auth.MapUsers[0].Username).To(gomega.Equal("admin")) g.Expect(auth.MapUsers[0].Groups).To(gomega.Equal([]string{"system:masters"})) + + g.Expect(auth.MapAccounts).To(gomega.HaveLen(1)) + g.Expect(auth.MapAccounts[0].AccountID).To(gomega.Equal("111111111111")) } func TestNewAuthMap(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() auth, _, err := ReadAuthMap(client) g.Expect(err).NotTo(gomega.HaveOccurred()) g.Expect(auth.MapRoles).To(gomega.BeEmpty()) g.Expect(auth.MapUsers).To(gomega.BeEmpty()) + g.Expect(auth.MapAccounts).To(gomega.BeEmpty()) } diff --git a/awsauth/mapper_test.go b/awsauth/mapper_test.go index 4b213ea..008d8a7 100644 --- a/awsauth/mapper_test.go +++ b/awsauth/mapper_test.go @@ -33,7 +33,7 @@ var testARNs = map[string]string{ func TestMapper_Remove(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() mapper := NewMapper(client, true) createMockConfigMap(client) @@ -61,7 +61,7 @@ func TestMapper_Remove(t *testing.T) { func TestMapper_RemoveNotFound(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() mapper := NewMapper(client, true) createMockConfigMap(client) @@ -89,7 +89,7 @@ func TestMapper_RemoveNotFound(t *testing.T) { func TestMapper_RemoveWithRetries(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() mapper := NewMapper(client, true) createMockConfigMap(client) @@ -124,7 +124,7 @@ func TestMapper_RemoveWithRetries(t *testing.T) { func TestMapper_UpsertInsert(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() mapper := NewMapper(client, true) createMockConfigMap(client) @@ -142,7 +142,7 @@ func TestMapper_UpsertInsert(t *testing.T) { DataType: MapUserData, UserARN: testARNs["user-2"], Username: "admin", - Groups: []string{"system:masters"}, + Groups: []string{"system:some-role"}, }) g.Expect(err).NotTo(gomega.HaveOccurred()) @@ -155,7 +155,7 @@ func TestMapper_UpsertInsert(t *testing.T) { func TestMapper_UpsertUpdate(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() mapper := NewMapper(client, true) createMockConfigMap(client) @@ -223,7 +223,7 @@ func TestMapper_UpsertUpdate(t *testing.T) { func TestMapper_UpsertWithCreate(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() mapper := NewMapper(client, true) err := mapper.Upsert(&Arguments{ @@ -246,8 +246,8 @@ func TestMapper_UpsertWithCreate(t *testing.T) { auth, _, err := ReadAuthMap(client) g.Expect(err).NotTo(gomega.HaveOccurred()) - g.Expect(len(auth.MapRoles)).To(gomega.HaveLen(1)) - g.Expect(len(auth.MapUsers)).To(gomega.HaveLen(1)) + g.Expect(len(auth.MapRoles)).To(gomega.Equal(1)) + g.Expect(len(auth.MapUsers)).To(gomega.Equal(1)) g.Expect(auth.MapRoles[0].RoleARN).To(gomega.Equal(testARNs["node-1"])) g.Expect(auth.MapRoles[0].Username).To(gomega.Equal("this:is:a:test")) g.Expect(auth.MapRoles[0].Groups).To(gomega.Equal([]string{"system:some-role"})) @@ -259,7 +259,7 @@ func TestMapper_UpsertWithCreate(t *testing.T) { func TestMapper_UpsertWithRetries(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) - client := fake.NewSimpleClientset() + client := fake.NewClientset() mapper := NewMapper(client, true) createMockConfigMap(client) @@ -287,12 +287,12 @@ func TestMapper_UpsertWithRetries(t *testing.T) { auth, _, err := ReadAuthMap(client) g.Expect(err).NotTo(gomega.HaveOccurred()) - g.Expect(len(auth.MapRoles)).To(gomega.HaveLen(1)) - g.Expect(len(auth.MapUsers)).To(gomega.HaveLen(1)) + g.Expect(len(auth.MapRoles)).To(gomega.Equal(1)) + g.Expect(len(auth.MapUsers)).To(gomega.Equal(2)) g.Expect(auth.MapRoles[0].RoleARN).To(gomega.Equal(testARNs["node-1"])) g.Expect(auth.MapRoles[0].Username).To(gomega.Equal("system:node:{{EC2PrivateDNSName}}")) g.Expect(auth.MapRoles[0].Groups).To(gomega.Equal([]string{"system:some-role"})) g.Expect(auth.MapUsers[0].UserARN).To(gomega.Equal(testARNs["user-1"])) g.Expect(auth.MapUsers[0].Username).To(gomega.Equal("admin")) - g.Expect(auth.MapUsers[0].Groups).To(gomega.Equal([]string{"system:some-role"})) + g.Expect(auth.MapUsers[0].Groups).To(gomega.Equal([]string{"system:masters"})) } diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 0b24de1..42be66f 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.89 + newTag: 0.0.91 diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index 69832f9..61cc49c 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -62,7 +62,7 @@ spec: - /manager args: - --config-map-name=aws-auth-test - - --must-present-account-id=130488995195 + - --must-present-account-id=123456789012 - --crd-item-allowed-namespace=kube-system - --reconcile-time=30s #- --username-must-be-email diff --git a/config/samples/aws-auth_v1beta1_mapaccount.yaml b/config/samples/aws-auth_v1beta1_mapaccount.yaml index 191cf70..e6ddc81 100644 --- a/config/samples/aws-auth_v1beta1_mapaccount.yaml +++ b/config/samples/aws-auth_v1beta1_mapaccount.yaml @@ -16,6 +16,6 @@ metadata: labels: app.kubernetes.io/name: aws-auth-controller-prozorro app.kubernetes.io/managed-by: kustomize - name: account-130488995195 + name: account-123456789012 spec: - accountid: "130488995195" + accountid: "123456789012" diff --git a/config/samples/aws-auth_v1beta1_maprole.yaml b/config/samples/aws-auth_v1beta1_maprole.yaml index 6ea7e35..13ef201 100644 --- a/config/samples/aws-auth_v1beta1_maprole.yaml +++ b/config/samples/aws-auth_v1beta1_maprole.yaml @@ -6,7 +6,7 @@ metadata: app.kubernetes.io/managed-by: kustomize name: maprole-prod-self-managed-node-group spec: - rolearn: arn:aws:iam::130488995195:role/prod-self-managed-node-group + rolearn: arn:aws:iam::123456789012:role/prod-self-managed-node-group groups: - sample:group1 - sample:group2 @@ -23,7 +23,7 @@ metadata: app.kubernetes.io/managed-by: kustomize name: maprole-self-mng-single-az-node-group spec: - rolearn: arn:aws:iam::130488995195:role/self-mng-single-az-node-group-20240218223715755100000001 + rolearn: arn:aws:iam::123456789012:role/self-mng-single-az-node-group-20240218223715755100000001 groups: - sample:group1 - sample:group2 diff --git a/config/samples/aws-auth_v1beta1_mapuser.yaml b/config/samples/aws-auth_v1beta1_mapuser.yaml index a454350..d0c6598 100644 --- a/config/samples/aws-auth_v1beta1_mapuser.yaml +++ b/config/samples/aws-auth_v1beta1_mapuser.yaml @@ -24,26 +24,10 @@ metadata: spec: description: A test mapuser username: user2@ios.in.ua - groups: - - system:masters - - admins - userarn: arn:aws:iam::123456789012:user/user2 - ---- -apiVersion: aws-auth.prozorro.sale/v1beta1 -kind: MapUser -metadata: - labels: - app.kubernetes.io/name: aws-auth-controller-prozorro - app.kubernetes.io/managed-by: kustomize - name: user3 -spec: - description: A test mapuser - username: user3@ios.in.ua groups: - system:masters - users - userarn: arn:aws:iam::123456789012:user/user3 + userarn: arn:aws:iam::123456789012:user/user2 --- apiVersion: aws-auth.prozorro.sale/v1beta1 @@ -55,9 +39,9 @@ metadata: name: serhii.rudenko spec: description: Serhii Rudenko - username: serhii.rudenko@prozorro.sale + username: sr@ios.in.ua groups: - system:masters - users - admins - userarn: arn:aws:iam::130488995195:user/serhii.rudenko@prozorro.sale \ No newline at end of file + userarn: arn:aws:iam::123456789012:user/sr@ios.in.ua \ No newline at end of file diff --git a/internal/controller/mapaccount_controller_test.go b/internal/controller/mapaccount_controller_test.go index 14c5958..d7fc8fe 100644 --- a/internal/controller/mapaccount_controller_test.go +++ b/internal/controller/mapaccount_controller_test.go @@ -32,13 +32,15 @@ import ( var _ = Describe("MapAccount Controller", func() { Context("When reconciling a resource", func() { - const resourceName = "test-resource" + const resourceName = "test-account-resource" + const accountid = "123456789012" + const namespace = "kube-system" ctx := context.Background() typeNamespacedName := types.NamespacedName{ Name: resourceName, - Namespace: "default", // TODO(user):Modify as needed + Namespace: namespace, } mapaccount := &awsauthv1beta1.MapAccount{} @@ -49,7 +51,10 @@ var _ = Describe("MapAccount Controller", func() { resource := &awsauthv1beta1.MapAccount{ ObjectMeta: metav1.ObjectMeta{ Name: resourceName, - Namespace: "default", + Namespace: namespace, + }, + Spec: awsauthv1beta1.MapAccountSpec{ + AccountID: accountid, }, // TODO(user): Specify other spec details if needed. } diff --git a/internal/controller/maprole_controller_test.go b/internal/controller/maprole_controller_test.go index 110f561..9de905b 100644 --- a/internal/controller/maprole_controller_test.go +++ b/internal/controller/maprole_controller_test.go @@ -32,13 +32,17 @@ import ( var _ = Describe("MapRole Controller", func() { Context("When reconciling a resource", func() { - const resourceName = "test-resource" + const resourceName = "test-role-resource" + const roleName = "test-role" + var groups = []string{"system:masters", "system:nodes"} + const rolearn = "arn:aws:iam::123456789012:role/test-role" + const namespace = "kube-system" ctx := context.Background() typeNamespacedName := types.NamespacedName{ Name: resourceName, - Namespace: "default", // TODO(user):Modify as needed + Namespace: namespace, } maprole := &awsauthv1beta1.MapRole{} @@ -49,9 +53,14 @@ var _ = Describe("MapRole Controller", func() { resource := &awsauthv1beta1.MapRole{ ObjectMeta: metav1.ObjectMeta{ Name: resourceName, - Namespace: "default", + Namespace: namespace, }, // TODO(user): Specify other spec details if needed. + Spec: awsauthv1beta1.MapRoleSpec{ + Username: roleName, + Groups: groups, + RoleARN: rolearn, + }, } Expect(k8sClient.Create(ctx, resource)).To(Succeed()) } diff --git a/internal/controller/mapuser_controller_test.go b/internal/controller/mapuser_controller_test.go index 298af3c..b802201 100644 --- a/internal/controller/mapuser_controller_test.go +++ b/internal/controller/mapuser_controller_test.go @@ -32,13 +32,17 @@ import ( var _ = Describe("MapUser Controller", func() { Context("When reconciling a resource", func() { - const resourceName = "test-resource" + const resourceName = "test-user-resource" + const userName = "test-user" + var groups = []string{"system:masters", "system:nodes"} + const userarn = "arn:aws:iam::123456789012:user/test-user" + const namespace = "kube-system" ctx := context.Background() typeNamespacedName := types.NamespacedName{ Name: resourceName, - Namespace: "default", // TODO(user):Modify as needed + Namespace: namespace, } mapuser := &awsauthv1beta1.MapUser{} @@ -49,7 +53,12 @@ var _ = Describe("MapUser Controller", func() { resource := &awsauthv1beta1.MapUser{ ObjectMeta: metav1.ObjectMeta{ Name: resourceName, - Namespace: "default", + Namespace: namespace, + }, + Spec: awsauthv1beta1.MapUserSpec{ + Username: userName, + Groups: groups, + UserARN: userarn, }, // TODO(user): Specify other spec details if needed. } From dbcd59174d21b36e7cdb62699e44ad54a2aee744 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 15 Jul 2025 07:35:09 +0300 Subject: [PATCH 30/58] fix lint errors --- .github/workflows/publish-release.yml | 66 ++++++++++++++++++ awsauth/data.go | 8 +-- awsauth/mapper.go | 73 +++++++++++--------- awsauth/mapper_test.go | 8 +-- awsauth/retry.go | 9 +-- cmd/main.go | 4 +- internal/controller/mapaccount_controller.go | 4 +- internal/controller/maprole_controller.go | 6 +- internal/controller/mapuser_controller.go | 4 +- internal/webhook/v1beta1/maprole_webhook.go | 2 +- 10 files changed, 129 insertions(+), 55 deletions(-) create mode 100644 .github/workflows/publish-release.yml diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml new file mode 100644 index 0000000..e693765 --- /dev/null +++ b/.github/workflows/publish-release.yml @@ -0,0 +1,66 @@ +name: Publish release + +on: + push: + tags: + - "0.*" + - "1.*" + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + verify-app: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Setup Go + uses: actions/setup-go@v3 + with: + go-version: "1.24.0" + + - name: Lint app + run: make lint + + build-and-push-image: + needs: verify-app + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Log in to the Container registry + uses: docker/login-action@v2 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v4 + with: + images: | + ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=ref,event=branch + type=ref,event=pr + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + + - name: Build and push Docker image + uses: docker/build-push-action@v4 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} diff --git a/awsauth/data.go b/awsauth/data.go index 3597968..c02d483 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -88,10 +88,10 @@ func ReadAuthMap(k kubernetes.Interface) (AwsAuthData, *kcorev1.ConfigMap, error return authData, cm, err } - /*err = yaml.Unmarshal([]byte(cm.Data["mapAccounts"]), &authData.MapAccounts) - if err != nil { - return authData, cm, err - }*/ + /* err = yaml.Unmarshal([]byte(cm.Data["mapAccounts"]), &authData.MapAccounts) + if err != nil { + return authData, cm, err + } */ var accountIDs []string err = yaml.Unmarshal([]byte(cm.Data["mapAccounts"]), &accountIDs) diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 28011fb..7d68c7d 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -17,13 +17,13 @@ package awsauth import ( "fmt" + "reflect" + "time" + "github.com/go-logr/logr" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" - "reflect" - "time" - "k8s.io/client-go/kubernetes" ) @@ -225,12 +225,9 @@ func (m *Mapper) existsAuth(args *Arguments) error { func existsAccount(authMaps []*MapAccount, resource *MapAccount) (error, bool) { var found = false - //log.Printf("existsAccount check: account id: %v \n", resource.AccountID) logger.Info("existsAccount", "AccountID", resource.AccountID) for _, existing := range authMaps { logger.Info("existsAccount.Compare", "cm account id", existing.AccountID, "new account id", resource.AccountID) - //log.Printf("existsAccount: cm account id: %v \n", existing.AccountID) - //log.Printf("existsAccount: new account id: %v \n", resource.AccountID) if existing.AccountID == resource.AccountID { found = true return fmt.Errorf("account with id '%s' already exists", resource.AccountID), found @@ -243,13 +240,10 @@ func existsAccount(authMaps []*MapAccount, resource *MapAccount) (error, bool) { func existsUser(authMaps []*MapUser, resource *MapUser) (error, bool) { var found = false - //log.Printf("existsUser check: username: %v userarn:%v \n", resource.Username, resource.UserARN) logger.Info("existsUser", "Username", resource.Username, "UserARN", resource.UserARN) for _, existing := range authMaps { logger.Info("existsUser.Compare", "cm username", existing.Username, "new username", resource.Username) logger.Info("existsUser.Compare", "cm userarn", existing.UserARN, "new userarn", resource.UserARN) - //log.Printf("existsUser: cm username: %v userarn: %v \n", existing.Username, existing.UserARN) - //log.Printf("existsUser: new username: %v userarn: %v \n", resource.Username, resource.UserARN) if existing.Username == resource.Username { found = true return fmt.Errorf("existsUser: username '%s' already exists", resource.Username), found @@ -265,13 +259,16 @@ func existsUser(authMaps []*MapUser, resource *MapUser) (error, bool) { func existsRole(authMaps []*MapRole, resource *MapRole) (error, bool) { var found = false - //log.Printf("existsRole check: username: %v rolearn:%v \n", resource.Username, resource.RoleARN) - logger.Info("existsRole", "Username", resource.Username, "RoleARN", resource.RoleARN) + logger.Info("existsRole", + "Username", resource.Username, + "RoleARN", resource.RoleARN) for _, existing := range authMaps { - //log.Printf("existsRole: cm username: %v rolearn: %v \n", existing.Username, existing.RoleARN) - //log.Printf("existsRole: new username: %v rolearn: %v \n", resource.Username, resource.RoleARN) - logger.Info("existsRole.Compare", "cm username", existing.Username, "new username", resource.Username) - logger.Info("existsRole.Compare", "cm rolearn", existing.RoleARN, "new rolearn", resource.RoleARN) + logger.Info("existsRole.Compare", + "cm username", existing.Username, + "new username", resource.Username) + logger.Info("existsRole.Compare", + "cm rolearn", existing.RoleARN, + "new rolearn", resource.RoleARN) if existing.Username == resource.Username { found = true return fmt.Errorf("existsRole: username '%s' already exists", resource.Username), found @@ -305,12 +302,16 @@ func (m *Mapper) upsertAuth(args *Arguments) error { mapRole := NewMapRole(args.RoleARN, args.Username, args.Groups) newMap, ok := upsertRole(authData.MapRoles, mapRole) if ok { - // log.Printf("%s with username '%s' and rolearn '%s' key has been updated\n", args.DataType, args.Username, args.RoleARN) - logger.Info("upsertAuth.Updated", "DataType", args.DataType, "Username", args.Username, "RoleARN", args.RoleARN) - } else { - // log.Printf("no updates needed to %s with username '%s' and rolearn '%s'\n", args.DataType, args.Username, args.RoleARN) - // logger.Info("upsertAuth.NoNeedUpdate", "DataType", args.DataType, "Username", args.Username, "RoleARN", args.RoleARN) - } + logger.Info("upsertAuth.Updated", + "DataType", args.DataType, + "Username", args.Username, + "RoleARN", args.RoleARN) + } /* else { + logger.Info("upsertAuth.NoNeedUpdate", + "DataType", args.DataType, + "Username", args.Username, + "RoleARN", args.RoleARN) + } */ authData.SetMapRoles(newMap) } @@ -318,12 +319,16 @@ func (m *Mapper) upsertAuth(args *Arguments) error { mapUser := NewMapUser(args.UserARN, args.Username, args.Groups) newMap, ok := upsertUser(authData.MapUsers, mapUser) if ok { - //log.Printf("%s with username '%s' and userarn '%s' key has been updated\n", args.DataType, args.Username, args.UserARN) - logger.Info("upsertAuth.Updated", "DataType", args.DataType, "Username", args.Username, "UserARN", args.UserARN) - } else { - // log.Printf("no updates needed to %s with username '%s' and userarn '%s'\n", args.DataType, args.Username, args.UserARN) - // logger.Info("upsertAuth.NoNeedUpdate", "DataType", args.DataType, "Username", args.Username, "UserARN", args.UserARN) - } + logger.Info("upsertAuth.Updated", + "DataType", args.DataType, + "Username", args.Username, + "UserARN", args.UserARN) + } /* else { + logger.Info("upsertAuth.NoNeedUpdate", + "DataType", args.DataType, + "Username", args.Username, + "UserARN", args.UserARN) + } */ authData.SetMapUsers(newMap) } @@ -331,12 +336,14 @@ func (m *Mapper) upsertAuth(args *Arguments) error { mapAccount := NewMapAccount(args.AccountID) newMap, ok := upsertAccount(authData.MapAccounts, mapAccount) if ok { - // log.Printf("%s with account id '%s' key has been updated\n", args.DataType, args.AccountID) - logger.Info("upsertAuth.Updated", "DataType", args.DataType, "AccountID", args.AccountID) - } else { - // log.Printf("no updates needed to %s with account id '%s'\n", args.DataType, args.AccountID) - // logger.Info("upsertAuth.NoNeedUpdate", "DataType", args.DataType, "AccountID", args.AccountID) - } + logger.Info("upsertAuth.Updated", + "DataType", args.DataType, + "AccountID", args.AccountID) + } /* else { + logger.Info("upsertAuth.NoNeedUpdate", + "DataType", args.DataType, + "AccountID", args.AccountID) + } */ authData.SetMapAccounts(newMap) } diff --git a/awsauth/mapper_test.go b/awsauth/mapper_test.go index 008d8a7..ed36ef6 100644 --- a/awsauth/mapper_test.go +++ b/awsauth/mapper_test.go @@ -246,8 +246,8 @@ func TestMapper_UpsertWithCreate(t *testing.T) { auth, _, err := ReadAuthMap(client) g.Expect(err).NotTo(gomega.HaveOccurred()) - g.Expect(len(auth.MapRoles)).To(gomega.Equal(1)) - g.Expect(len(auth.MapUsers)).To(gomega.Equal(1)) + g.Expect(auth.MapRoles).To(gomega.HaveLen(1)) + g.Expect(auth.MapUsers).To(gomega.HaveLen(1)) g.Expect(auth.MapRoles[0].RoleARN).To(gomega.Equal(testARNs["node-1"])) g.Expect(auth.MapRoles[0].Username).To(gomega.Equal("this:is:a:test")) g.Expect(auth.MapRoles[0].Groups).To(gomega.Equal([]string{"system:some-role"})) @@ -287,8 +287,8 @@ func TestMapper_UpsertWithRetries(t *testing.T) { auth, _, err := ReadAuthMap(client) g.Expect(err).NotTo(gomega.HaveOccurred()) - g.Expect(len(auth.MapRoles)).To(gomega.Equal(1)) - g.Expect(len(auth.MapUsers)).To(gomega.Equal(2)) + g.Expect(auth.MapRoles).To(gomega.HaveLen(1)) + g.Expect(auth.MapUsers).To(gomega.HaveLen(2)) g.Expect(auth.MapRoles[0].RoleARN).To(gomega.Equal(testARNs["node-1"])) g.Expect(auth.MapRoles[0].Username).To(gomega.Equal("system:node:{{EC2PrivateDNSName}}")) g.Expect(auth.MapRoles[0].Groups).To(gomega.Equal([]string{"system:some-role"})) diff --git a/awsauth/retry.go b/awsauth/retry.go index 1f1ab6d..b4b6e30 100644 --- a/awsauth/retry.go +++ b/awsauth/retry.go @@ -16,10 +16,11 @@ limitations under the License. package awsauth import ( - "github.com/jpillora/backoff" - "github.com/pkg/errors" "strings" "time" + + "github.com/jpillora/backoff" + "github.com/pkg/errors" ) const ( @@ -29,7 +30,7 @@ const ( // WithRetry runs the passed operation function with its arguments and retries // on failures until success or max number of retry attempts have failed. -/*func WithRetry(fn func(*Arguments) error, args *Arguments) error { +/* func WithRetry(fn func(*Arguments) error, args *Arguments) error { var ( counter int err error @@ -53,7 +54,7 @@ const ( } return errors.Wrap(err, "waiter timed out") -}*/ +} */ func WithRetry(fn func(*Arguments) error, args *Arguments) error { var ( counter int diff --git a/cmd/main.go b/cmd/main.go index 9efc1be..b78baf4 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -84,8 +84,8 @@ func main() { " if not set, all namespaces allowed creation of Resources.") flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where store items,"+ " --config-map-name=aws-auth, if not set, use default name aws-auth") - flag.DurationVar(&reconcileTime, "reconcile-time", time.Minute*30, "Time to reconcile CRDs and recreate configmap item if need"+ - " --reconcile-time=30m, if not set, use default value 30 minutes") + flag.DurationVar(&reconcileTime, "reconcile-time", time.Minute*30, "Time to reconcile CRDs and recreate "+ + " configmap item if need, --reconcile-time=30m, if not set, use default value 30 minutes") flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index ab7da73..49738d5 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -97,7 +97,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) } // examine DeletionTimestamp to determine if object is under deletion if mapAccount.DeletionTimestamp.IsZero() { - //logf.Log.Info("mapAccount is not being deleted: " + mapAccount.Name) + // logf.Log.Info("mapAccount is not being deleted: " + mapAccount.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { logf.Log.Info("Adding finalizer: " + mapAccount.Name) @@ -113,7 +113,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) log.Error(err, "Failure upserting MapAccount") return ctrl.Result{}, err } - //log.Info("Upserted MapAccount") + // log.Info("Upserted MapAccount") } } else { diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index c9e674e..d4e7229 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -18,13 +18,13 @@ package controller import ( "context" - "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "time" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" logf "sigs.k8s.io/controller-runtime/pkg/log" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" @@ -93,7 +93,7 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct } if mapRole.DeletionTimestamp.IsZero() { - //logf.Log.Info("mapRole is not being deleted: " + mapRole.Name) + // logf.Log.Info("mapRole is not being deleted: " + mapRole.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapRole, awsauth.CrdFinalizerName) { logf.Log.Info("Adding finalizer: " + mapRole.Name) @@ -111,7 +111,7 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct log.Error(err, "Failure upserting MapRole") return ctrl.Result{}, err } - //log.Info("Upserted MapRole") + // log.Info("Upserted MapRole") } } else { log.Info("mapRole is being deleted") diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index 7af95e0..1a9bfb3 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -94,7 +94,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct return ctrl.Result{}, nil } if mapUser.DeletionTimestamp.IsZero() { - //logf.Log.Info("mapUser is not being deleted: " + mapUser.Name) + // logf.Log.Info("mapUser is not being deleted: " + mapUser.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { logf.Log.Info("Adding finalizer: " + mapUser.Name) @@ -112,7 +112,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct log.Error(err, "Failure upserting MapUser") return ctrl.Result{}, err } - //log.Info("Upserted MapUser") + // log.Info("Upserted MapUser") } } else { log.Info("mapUser is being deleted") diff --git a/internal/webhook/v1beta1/maprole_webhook.go b/internal/webhook/v1beta1/maprole_webhook.go index b01de9c..36ee0e8 100644 --- a/internal/webhook/v1beta1/maprole_webhook.go +++ b/internal/webhook/v1beta1/maprole_webhook.go @@ -19,11 +19,11 @@ package v1beta1 import ( "context" "fmt" - "sigs.k8s.io/controller-runtime/pkg/client" "time" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" From a8e6f2f37ec9c5a591113de164a53746709a54c8 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 15 Jul 2025 08:44:35 +0300 Subject: [PATCH 31/58] fix lint errors --- internal/controller/mapaccount_controller_test.go | 2 +- internal/controller/maprole_controller_test.go | 2 +- internal/controller/mapuser_controller_test.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/controller/mapaccount_controller_test.go b/internal/controller/mapaccount_controller_test.go index d7fc8fe..bde92f8 100644 --- a/internal/controller/mapaccount_controller_test.go +++ b/internal/controller/mapaccount_controller_test.go @@ -34,7 +34,7 @@ var _ = Describe("MapAccount Controller", func() { Context("When reconciling a resource", func() { const resourceName = "test-account-resource" const accountid = "123456789012" - const namespace = "kube-system" + const namespace = "default" ctx := context.Background() diff --git a/internal/controller/maprole_controller_test.go b/internal/controller/maprole_controller_test.go index 9de905b..23f47b4 100644 --- a/internal/controller/maprole_controller_test.go +++ b/internal/controller/maprole_controller_test.go @@ -36,7 +36,7 @@ var _ = Describe("MapRole Controller", func() { const roleName = "test-role" var groups = []string{"system:masters", "system:nodes"} const rolearn = "arn:aws:iam::123456789012:role/test-role" - const namespace = "kube-system" + const namespace = "default" ctx := context.Background() diff --git a/internal/controller/mapuser_controller_test.go b/internal/controller/mapuser_controller_test.go index b802201..87d3e8b 100644 --- a/internal/controller/mapuser_controller_test.go +++ b/internal/controller/mapuser_controller_test.go @@ -36,7 +36,7 @@ var _ = Describe("MapUser Controller", func() { const userName = "test-user" var groups = []string{"system:masters", "system:nodes"} const userarn = "arn:aws:iam::123456789012:user/test-user" - const namespace = "kube-system" + const namespace = "default" ctx := context.Background() From 3d6c1ccf71c1b4334058a9e44c182906f530acac Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 15 Jul 2025 10:42:32 +0300 Subject: [PATCH 32/58] fix test suite --- internal/controller/suite_test.go | 8 ++++++++ kube/kube.go | 5 +++++ kube/testing.go | 15 +++++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 kube/testing.go diff --git a/internal/controller/suite_test.go b/internal/controller/suite_test.go index 2ba8995..c832ae5 100644 --- a/internal/controller/suite_test.go +++ b/internal/controller/suite_test.go @@ -24,6 +24,7 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + "github.com/redacid/aws-auth-controller/kube" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" @@ -80,6 +81,10 @@ var _ = BeforeSuite(func() { Expect(err).NotTo(HaveOccurred()) Expect(cfg).NotTo(BeNil()) + kube.SetTestConfig(cfg) + + // fmt.Printf("Test environment config: %+v\n", cfg) + k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) Expect(err).NotTo(HaveOccurred()) Expect(k8sClient).NotTo(BeNil()) @@ -88,6 +93,9 @@ var _ = BeforeSuite(func() { var _ = AfterSuite(func() { By("tearing down the test environment") cancel() + + kube.ResetTestConfig() + err := testEnv.Stop() Expect(err).NotTo(HaveOccurred()) }) diff --git a/kube/kube.go b/kube/kube.go index effda3d..9042377 100644 --- a/kube/kube.go +++ b/kube/kube.go @@ -11,6 +11,11 @@ import ( // GetClient returns a new configured Kubernetes client. func GetClient() (kubernetes.Interface, error) { + + if testConfig != nil { + return kubernetes.NewForConfig(testConfig) + } + var cfg *rest.Config var err error diff --git a/kube/testing.go b/kube/testing.go new file mode 100644 index 0000000..961e91d --- /dev/null +++ b/kube/testing.go @@ -0,0 +1,15 @@ +package kube + +import "k8s.io/client-go/rest" + +var testConfig *rest.Config + +// SetTestConfig встановлює конфігурацію для тестів +func SetTestConfig(cfg *rest.Config) { + testConfig = cfg +} + +// ResetTestConfig скидає тестову конфігурацію +func ResetTestConfig() { + testConfig = nil +} From de0134c0b20eec70f086883ffa16a157c0ffbe98 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 15 Jul 2025 11:07:37 +0300 Subject: [PATCH 33/58] add deploy samples to makefile --- DEV-DOCS.md | 27 +++++++++++++++++++++++++++ Makefile | 6 +++++- README.md | 28 +--------------------------- config/manager/kustomization.yaml | 2 +- 4 files changed, 34 insertions(+), 29 deletions(-) create mode 100644 DEV-DOCS.md diff --git a/DEV-DOCS.md b/DEV-DOCS.md new file mode 100644 index 0000000..a869ba9 --- /dev/null +++ b/DEV-DOCS.md @@ -0,0 +1,27 @@ +# aws-auth-controller + +kubebuilder init --domain prozorro.sale --plugins go/v4 --repo github.com/redacid/aws-auth-controller --project-name=aws-auth-controller-prozorro +kubebuilder create api --group aws-auth --version v1beta1 --kind MapRole --namespaced true --controller --resource +kubebuilder create api --group aws-auth --version v1beta1 --kind MapUser --namespaced true --controller --resource +kubebuilder create api --group aws-auth --version v1beta1 --kind MapAccount --namespaced true --controller --resource + +kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapUser --defaulting --programmatic-validation +kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapRole --defaulting --programmatic-validation +kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapAccount --defaulting --programmatic-validation + +git tag 0.0.1 -m "Test 0.0.1" +git push origin 0.0.1 + +cd ./charts helm upgrade -i --namespace kube-system aws-auth aws-auth-operator +cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapuser.yaml -n kube-system +cd ./config/samples kubectl apply -f aws-auth_v1beta1_maprole.yaml -n kube-system +cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapaccount.yaml -n kube-system + +https://book.kubebuilder.io/reference/using-finalizers +https://book.kubebuilder.io/reference/markers/crd-validation + +https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/reconcile/reconcile.go#L46 +https://book.kubebuilder.io/reference/watching-resources.html?highlight=RequeueAfter#when-requeueafter-x-is-useful + +https://github.com/gp42/aws-auth-operator + diff --git a/Makefile b/Makefile index 7ca53ec..8d4dc9e 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.91 +IMG ?= redacid/aws-auth-controller-dev:0.0.92 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) @@ -41,6 +41,10 @@ preview: mod-tidy generate manifests kustomize cd config/manager && $(KUSTOMIZE) edit set image controller=${IMG} $(KUSTOMIZE) build config/default +.PHONY: deploy-samples +deploy-samples: manifests kustomize ## Deploy controller to the K8s cluster specified in ~/.kube/config. + $(KUSTOMIZE) build config/samples | $(KUBECTL) -n kube-system apply -f - + .PHONY: mod-tidy mod-tidy: go mod tidy diff --git a/README.md b/README.md index a869ba9..8c02383 100644 --- a/README.md +++ b/README.md @@ -1,27 +1 @@ -# aws-auth-controller - -kubebuilder init --domain prozorro.sale --plugins go/v4 --repo github.com/redacid/aws-auth-controller --project-name=aws-auth-controller-prozorro -kubebuilder create api --group aws-auth --version v1beta1 --kind MapRole --namespaced true --controller --resource -kubebuilder create api --group aws-auth --version v1beta1 --kind MapUser --namespaced true --controller --resource -kubebuilder create api --group aws-auth --version v1beta1 --kind MapAccount --namespaced true --controller --resource - -kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapUser --defaulting --programmatic-validation -kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapRole --defaulting --programmatic-validation -kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapAccount --defaulting --programmatic-validation - -git tag 0.0.1 -m "Test 0.0.1" -git push origin 0.0.1 - -cd ./charts helm upgrade -i --namespace kube-system aws-auth aws-auth-operator -cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapuser.yaml -n kube-system -cd ./config/samples kubectl apply -f aws-auth_v1beta1_maprole.yaml -n kube-system -cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapaccount.yaml -n kube-system - -https://book.kubebuilder.io/reference/using-finalizers -https://book.kubebuilder.io/reference/markers/crd-validation - -https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/reconcile/reconcile.go#L46 -https://book.kubebuilder.io/reference/watching-resources.html?highlight=RequeueAfter#when-requeueafter-x-is-useful - -https://github.com/gp42/aws-auth-operator - +# aws-auth-controller \ No newline at end of file diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 42be66f..26b8ba7 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.91 + newTag: 0.0.92 From 94cf805dc4d162b6f1a7b734b4c46aee6a5ca36f Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 15 Jul 2025 11:17:09 +0300 Subject: [PATCH 34/58] translate comments --- awsauth/common.go | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/awsauth/common.go b/awsauth/common.go index b17e15f..8433037 100644 --- a/awsauth/common.go +++ b/awsauth/common.go @@ -21,9 +21,10 @@ import ( "strings" ) +// THIS NOT USED var AllowedAWSAccounts = []string{ "123456789012", - "130488995195", + "210987654321", } // VerifyAWSAccount validates if the provided string is a valid AWS account ID (12 digits) @@ -164,7 +165,7 @@ func SetAllowedAWSAccounts(accounts []string) error { return nil } -// ConvertMapAccountToString конвертує MapAccountSpec в строку accountid +// ConvertMapAccountToString convert MapAccountSpec to string accountid func ConvertMapAccountToString(accounts []*MapAccount) []string { result := make([]string, len(accounts)) for i, account := range accounts { @@ -173,7 +174,7 @@ func ConvertMapAccountToString(accounts []*MapAccount) []string { return result } -// ConvertStringToMapAccount конвертує строки accountid в MapAccountSpec +// ConvertStringToMapAccount convert strings accountid to MapAccountSpec func ConvertStringToMapAccount(accountIDs []string) []*MapAccount { result := make([]*MapAccount, len(accountIDs)) for i, accountID := range accountIDs { @@ -185,16 +186,16 @@ func ConvertStringToMapAccount(accountIDs []string) []*MapAccount { } /* - // Конвертація з MapAccountSpec в строки + // Convert from MapAccountSpec to strings specs := []MapAccountSpec{ {AccountID: "111111111111"}, {AccountID: "222222222222"}, } strings := ConvertMapAccountToString(specs) - // результат: []string{"111111111111", "222222222222"} + // result: []string{"111111111111", "222222222222"} - // Конвертація зі строк в MapAccountSpec + // Convert from strings to MapAccountSpec accountIDs := []string{"111111111111", "222222222222"} specs = ConvertStringToMapAccount(accountIDs) - // результат: []MapAccountSpec{{AccountID: "111111111111"}, {AccountID: "222222222222"}} + // result: []MapAccountSpec{{AccountID: "111111111111"}, {AccountID: "222222222222"}} */ From fba9ca9afe561feee708c6cf0aa80b3f15c3b79a Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 15 Jul 2025 13:01:52 +0300 Subject: [PATCH 35/58] ltl fixes --- awsauth/common.go | 2 +- awsauth/data.go | 3 +-- awsauth/service.go | 2 +- cmd/main.go | 4 ++-- internal/controller/common.go | 15 +++++++++++++++ 5 files changed, 20 insertions(+), 6 deletions(-) diff --git a/awsauth/common.go b/awsauth/common.go index 8433037..c3089aa 100644 --- a/awsauth/common.go +++ b/awsauth/common.go @@ -21,7 +21,7 @@ import ( "strings" ) -// THIS NOT USED +// AllowedAWSAccounts THIS NOT USED var AllowedAWSAccounts = []string{ "123456789012", "210987654321", diff --git a/awsauth/data.go b/awsauth/data.go index c02d483..36edf32 100644 --- a/awsauth/data.go +++ b/awsauth/data.go @@ -20,7 +20,6 @@ import ( "fmt" "time" - // "log" "sync" "gopkg.in/yaml.v2" @@ -40,7 +39,7 @@ var ( ConfigMapName = "aws-auth" CrdFinalizerName = "aws-auth.prozorro.sale/finalizer" UsernameMustBeEmail = false - // TODO automatic add to configmap + // MustPresentAccountID TODO automatic add to configmap MustPresentAccountID string = "" CrdItemAllowedNamespace string = "" diff --git a/awsauth/service.go b/awsauth/service.go index d2c3869..6481f1c 100644 --- a/awsauth/service.go +++ b/awsauth/service.go @@ -230,7 +230,7 @@ func (svc impl) UpsertMapAccount(mapAccount MapAccount) error { return err } -// RemoveMapUser removes a MapUser from the configmap keyed by username. +// RemoveMapAccount removes a MapAccount from the configmap keyed by account id. func (svc impl) RemoveMapAccount(mapAccount MapAccount) error { mapper := NewMapper(svc.cfg.KubeClient, false) err := mapper.Remove(&Arguments{ diff --git a/cmd/main.go b/cmd/main.go index b78baf4..b78fb72 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -79,13 +79,13 @@ func main() { flag.StringVar(&mustPresentAccountID, "must-present-account-id", "", "This account must be "+ "allways present in ConfigMap, --must-present-account-id=123456789012") flag.StringVar(&crdItemAllowedNamespace, "crd-item-allowed-namespace", "", - "Namespace where allowed creation of Resources --crd-item-allowed-namespace=kube-system,"+ + "Namespace where allowed creation of Resources --crd-item-allowed-namespace=kube-system, "+ "If is set, only in this namespace allowed creation of Resources,"+ " if not set, all namespaces allowed creation of Resources.") flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where store items,"+ " --config-map-name=aws-auth, if not set, use default name aws-auth") flag.DurationVar(&reconcileTime, "reconcile-time", time.Minute*30, "Time to reconcile CRDs and recreate "+ - " configmap item if need, --reconcile-time=30m, if not set, use default value 30 minutes") + " configmap item if need, --reconcile-time=30m, s - seconds, m - minutes, h - hours, d - days") flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") diff --git a/internal/controller/common.go b/internal/controller/common.go index 48913eb..dced75d 100644 --- a/internal/controller/common.go +++ b/internal/controller/common.go @@ -1,3 +1,18 @@ +/* + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + package controller const ( From 8f6d62f5217e747477fb4ab398465c6d95f87f66 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 15 Jul 2025 17:16:42 +0300 Subject: [PATCH 36/58] fix logging --- DEV-DOCS.md | 45 ++++++++++++++++++++ Makefile | 2 +- awsauth/mapper.go | 20 ++++----- awsauth/mapper_test.go | 14 +++--- awsauth/retry.go | 2 +- awsauth/service.go | 32 ++++++++------ config/manager/kustomization.yaml | 2 +- config/manager/manager.yaml | 5 +++ internal/controller/mapaccount_controller.go | 12 +++--- internal/controller/maprole_controller.go | 8 ++-- internal/controller/mapuser_controller.go | 10 ++--- 11 files changed, 103 insertions(+), 49 deletions(-) diff --git a/DEV-DOCS.md b/DEV-DOCS.md index a869ba9..e0c353c 100644 --- a/DEV-DOCS.md +++ b/DEV-DOCS.md @@ -25,3 +25,48 @@ https://book.kubebuilder.io/reference/watching-resources.html?highlight=RequeueA https://github.com/gp42/aws-auth-operator +Usage of ./manager: +-config-map-name string +ConfigMap-name where store items, --config-map-name=aws-auth, if not set, use default name aws-auth (default "aws-auth") +-crd-item-allowed-namespace string +Namespace where allowed creation of Resources --crd-item-allowed-namespace=kube-system, If is set, only in this namespace allowed creation of Resources, if not set, all namespaces allowed creation of Resources. +-enable-http2 +If set, HTTP/2 will be enabled for the metrics and webhook servers +-health-probe-bind-address string +The address the probe endpoint binds to. (default ":8081") +-kubeconfig string +Paths to a kubeconfig. Only required if out-of-cluster. +-leader-elect +Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager. +-metrics-bind-address string +The address the metrics endpoint binds to. Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service. (default "0") +-metrics-cert-key string +The name of the metrics server key file. (default "tls.key") +-metrics-cert-name string +The name of the metrics server certificate file. (default "tls.crt") +-metrics-cert-path string +The directory that contains the metrics server certificate. +-metrics-secure +If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead. (default true) +-must-present-account-id string +This account must be allways present in ConfigMap, --must-present-account-id=123456789012 +-reconcile-time duration +Time to reconcile CRDs and recreate configmap item if need, --reconcile-time=30m, s - seconds, m - minutes, h - hours, d - days (default 30m0s) +-username-must-be-email +Enables checking of username, should it be an email address, default false.Use --username-must-be-email=true to enable this feature. +-webhook-cert-key string +The name of the webhook key file. (default "tls.key") +-webhook-cert-name string +The name of the webhook certificate file. (default "tls.crt") +-webhook-cert-path string +The directory that contains the webhook certificate. +-zap-devel +Development Mode defaults(encoder=consoleEncoder,logLevel=Debug,stackTraceLevel=Warn). Production Mode defaults(encoder=jsonEncoder,logLevel=Info,stackTraceLevel=Error) (default true) +-zap-encoder value +Zap log encoding (one of 'json' or 'console') +-zap-log-level value +Zap Level to configure the verbosity of logging. Can be one of 'debug', 'info', 'error', 'panic'or any integer value > 0 which corresponds to custom debug levels of increasing verbosity +-zap-stacktrace-level value +Zap Level at and above which stacktraces are captured (one of 'info', 'error', 'panic'). +-zap-time-encoding value +Zap time encoding (one of 'epoch', 'millis', 'nano', 'iso8601', 'rfc3339' or 'rfc3339nano'). Defaults to 'epoch'. \ No newline at end of file diff --git a/Makefile b/Makefile index 8d4dc9e..b83550d 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Image URL to use all building/pushing image targets #IMG ?= controller:latest -IMG ?= redacid/aws-auth-controller-dev:0.0.92 +IMG ?= redacid/aws-auth-controller-dev:0.0.107 # Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) ifeq (,$(shell go env GOBIN)) diff --git a/awsauth/mapper.go b/awsauth/mapper.go index 7d68c7d..1d904b0 100644 --- a/awsauth/mapper.go +++ b/awsauth/mapper.go @@ -92,7 +92,7 @@ const ( ) // NewMapper returns a new Mapper object. -func NewMapper(client kubernetes.Interface, discardLogOutput bool) *Mapper { +func NewMapper(client kubernetes.Interface) *Mapper { var mapper = &Mapper{ KubernetesClient: client, Log: logf.Log.WithName("mapper"), @@ -306,12 +306,12 @@ func (m *Mapper) upsertAuth(args *Arguments) error { "DataType", args.DataType, "Username", args.Username, "RoleARN", args.RoleARN) - } /* else { - logger.Info("upsertAuth.NoNeedUpdate", + } else { + logger.V(1).Info("upsertAuth.NoNeedUpdate", "DataType", args.DataType, "Username", args.Username, "RoleARN", args.RoleARN) - } */ + } authData.SetMapRoles(newMap) } @@ -323,12 +323,12 @@ func (m *Mapper) upsertAuth(args *Arguments) error { "DataType", args.DataType, "Username", args.Username, "UserARN", args.UserARN) - } /* else { - logger.Info("upsertAuth.NoNeedUpdate", + } else { + logger.V(1).Info("upsertAuth.NoNeedUpdate", "DataType", args.DataType, "Username", args.Username, "UserARN", args.UserARN) - } */ + } authData.SetMapUsers(newMap) } @@ -339,11 +339,11 @@ func (m *Mapper) upsertAuth(args *Arguments) error { logger.Info("upsertAuth.Updated", "DataType", args.DataType, "AccountID", args.AccountID) - } /* else { - logger.Info("upsertAuth.NoNeedUpdate", + } else { + logger.V(1).Info("upsertAuth.NoNeedUpdate", "DataType", args.DataType, "AccountID", args.AccountID) - } */ + } authData.SetMapAccounts(newMap) } diff --git a/awsauth/mapper_test.go b/awsauth/mapper_test.go index ed36ef6..20a57a4 100644 --- a/awsauth/mapper_test.go +++ b/awsauth/mapper_test.go @@ -34,7 +34,7 @@ func TestMapper_Remove(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) client := fake.NewClientset() - mapper := NewMapper(client, true) + mapper := NewMapper(client) createMockConfigMap(client) err := mapper.Remove(&Arguments{ @@ -62,7 +62,7 @@ func TestMapper_RemoveNotFound(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) client := fake.NewClientset() - mapper := NewMapper(client, true) + mapper := NewMapper(client) createMockConfigMap(client) err := mapper.Remove(&Arguments{ @@ -90,7 +90,7 @@ func TestMapper_RemoveWithRetries(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) client := fake.NewClientset() - mapper := NewMapper(client, true) + mapper := NewMapper(client) createMockConfigMap(client) err := mapper.Remove(&Arguments{ @@ -125,7 +125,7 @@ func TestMapper_UpsertInsert(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) client := fake.NewClientset() - mapper := NewMapper(client, true) + mapper := NewMapper(client) createMockConfigMap(client) err := mapper.Upsert(&Arguments{ @@ -156,7 +156,7 @@ func TestMapper_UpsertUpdate(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) client := fake.NewClientset() - mapper := NewMapper(client, true) + mapper := NewMapper(client) createMockConfigMap(client) err := mapper.Upsert(&Arguments{ @@ -224,7 +224,7 @@ func TestMapper_UpsertWithCreate(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) client := fake.NewClientset() - mapper := NewMapper(client, true) + mapper := NewMapper(client) err := mapper.Upsert(&Arguments{ OperationType: UpsertOperation, @@ -260,7 +260,7 @@ func TestMapper_UpsertWithRetries(t *testing.T) { g := gomega.NewWithT(t) gomega.RegisterTestingT(t) client := fake.NewClientset() - mapper := NewMapper(client, true) + mapper := NewMapper(client) createMockConfigMap(client) err := mapper.Upsert(&Arguments{ diff --git a/awsauth/retry.go b/awsauth/retry.go index b4b6e30..f891377 100644 --- a/awsauth/retry.go +++ b/awsauth/retry.go @@ -72,7 +72,7 @@ func WithRetry(fn func(*Arguments) error, args *Arguments) error { // Check if error is related to ConfigMap conflict if strings.Contains(err.Error(), "the object has been modified") { d := bkoff.Duration() - logger.Info("ConfigMap conflict detected", "error", err, "retry after", d) + logger.Error(err, "ConfigMap conflict detected", "retry after", d) time.Sleep(d) counter++ continue diff --git a/awsauth/service.go b/awsauth/service.go index 6481f1c..42fd514 100644 --- a/awsauth/service.go +++ b/awsauth/service.go @@ -79,8 +79,8 @@ type impl struct { } func (svc impl) CheckMapRoleExists(mapRole MapRole) error { - svc.cfg.Log.Info("CheckMapRoleExists", "username", mapRole.Username, "rolearn", mapRole.RoleARN) - mapper := NewMapper(svc.cfg.KubeClient, false) + svc.cfg.Log.V(1).Info("CheckMapRoleExists", "username", mapRole.Username, "rolearn", mapRole.RoleARN) + mapper := NewMapper(svc.cfg.KubeClient) err := mapper.CheckExists(&Arguments{ DataType: MapRoleData, Username: mapRole.Username, @@ -98,7 +98,8 @@ func (svc impl) CheckMapRoleExists(mapRole MapRole) error { // UpsertMapRole upserts a MapRole into the configmap keyed by username. func (svc impl) UpsertMapRole(mapRole MapRole) error { - mapper := NewMapper(svc.cfg.KubeClient, false) + svc.cfg.Log.V(1).Info("UpsertMapRole", "username", mapRole.Username, "rolearn", mapRole.RoleARN) + mapper := NewMapper(svc.cfg.KubeClient) err := mapper.Upsert(&Arguments{ DataType: MapRoleData, RoleARN: mapRole.RoleARN, @@ -121,7 +122,8 @@ func (svc impl) UpsertMapRole(mapRole MapRole) error { // RemoveMapRole removes a MapRole from the configmap keyed by username. func (svc impl) RemoveMapRole(mapRole MapRole) error { - mapper := NewMapper(svc.cfg.KubeClient, false) + svc.cfg.Log.V(1).Info("RemoveMapRole", "username", mapRole.Username, "rolearn", mapRole.RoleARN) + mapper := NewMapper(svc.cfg.KubeClient) err := mapper.Remove(&Arguments{ DataType: MapRoleData, Username: mapRole.Username, @@ -142,8 +144,8 @@ func (svc impl) RemoveMapRole(mapRole MapRole) error { } func (svc impl) CheckMapUserExists(mapUser MapUser) error { - svc.cfg.Log.Info("CheckMapUserExists", "username", mapUser.Username, "userarn", mapUser.UserARN) - mapper := NewMapper(svc.cfg.KubeClient, false) + svc.cfg.Log.V(1).Info("CheckMapUserExists", "username", mapUser.Username, "userarn", mapUser.UserARN) + mapper := NewMapper(svc.cfg.KubeClient) err := mapper.CheckExists(&Arguments{ DataType: MapUserData, Username: mapUser.Username, @@ -161,7 +163,8 @@ func (svc impl) CheckMapUserExists(mapUser MapUser) error { // UpsertMapUser upserts a MapUser into the configmap keyed by username. func (svc impl) UpsertMapUser(mapUser MapUser) error { - mapper := NewMapper(svc.cfg.KubeClient, false) + svc.cfg.Log.V(1).Info("UpsertMapUser", "username", mapUser.Username, "userarn", mapUser.UserARN) + mapper := NewMapper(svc.cfg.KubeClient) err := mapper.Upsert(&Arguments{ DataType: MapUserData, UserARN: mapUser.UserARN, @@ -180,7 +183,8 @@ func (svc impl) UpsertMapUser(mapUser MapUser) error { // RemoveMapUser removes a MapUser from the configmap keyed by username. func (svc impl) RemoveMapUser(mapUser MapUser) error { - mapper := NewMapper(svc.cfg.KubeClient, false) + svc.cfg.Log.V(1).Info("RemoveMapUser", "username", mapUser.Username, "userarn", mapUser.UserARN) + mapper := NewMapper(svc.cfg.KubeClient) err := mapper.Remove(&Arguments{ DataType: MapUserData, Username: mapUser.Username, @@ -197,8 +201,8 @@ func (svc impl) RemoveMapUser(mapUser MapUser) error { } func (svc impl) CheckMapAccountExists(mapAccount MapAccount) error { - svc.cfg.Log.Info("CheckAccountExists", "accountid", mapAccount.AccountID) - mapper := NewMapper(svc.cfg.KubeClient, false) + svc.cfg.Log.V(1).Info("CheckAccountExists", "accountid", mapAccount.AccountID) + mapper := NewMapper(svc.cfg.KubeClient) err := mapper.CheckExists(&Arguments{ DataType: MapAccountData, AccountID: mapAccount.AccountID, @@ -215,7 +219,8 @@ func (svc impl) CheckMapAccountExists(mapAccount MapAccount) error { // UpsertMapAccount upserts a MapAccount into the configmap keyed by username. func (svc impl) UpsertMapAccount(mapAccount MapAccount) error { - mapper := NewMapper(svc.cfg.KubeClient, false) + svc.cfg.Log.V(1).Info("UpsertMapAccount", "accountid", mapAccount.AccountID) + mapper := NewMapper(svc.cfg.KubeClient) err := mapper.Upsert(&Arguments{ DataType: MapAccountData, AccountID: mapAccount.AccountID, @@ -232,7 +237,8 @@ func (svc impl) UpsertMapAccount(mapAccount MapAccount) error { // RemoveMapAccount removes a MapAccount from the configmap keyed by account id. func (svc impl) RemoveMapAccount(mapAccount MapAccount) error { - mapper := NewMapper(svc.cfg.KubeClient, false) + svc.cfg.Log.V(1).Info("RemoveMapAccount", "accountid", mapAccount.AccountID) + mapper := NewMapper(svc.cfg.KubeClient) err := mapper.Remove(&Arguments{ DataType: MapAccountData, AccountID: mapAccount.AccountID, @@ -242,7 +248,7 @@ func (svc impl) RemoveMapAccount(mapAccount MapAccount) error { MinRetryTime: svc.cfg.MinRetryTime, }) if err != nil { - svc.cfg.Log.Info("mapAccount not found", "account id", mapAccount.AccountID) + svc.cfg.Log.Info("mapAccount not found", "accountid", mapAccount.AccountID) } return err } diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 26b8ba7..84243c1 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -5,4 +5,4 @@ kind: Kustomization images: - name: controller newName: redacid/aws-auth-controller-dev - newTag: 0.0.92 + newTag: 0.0.107 diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index 61cc49c..b3b88cc 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -68,6 +68,11 @@ spec: #- --username-must-be-email - --leader-elect - --health-probe-bind-address=:8081 + - --zap-devel=true + - --zap-encoder=console + - --zap-log-level=info + - --zap-time-encoding=iso8601 + - --zap-stacktrace-level=panic image: controller:latest name: manager ports: [] diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 49738d5..855bef0 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -56,12 +56,10 @@ type MapAccountReconciler struct { func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { _ = logf.FromContext(ctx) - // TODO(user): your logic here - // MapAccount objects a list of AWS Accounts. log := ctrl.Log.WithValues("MapAccount", req.Name, "namespace", req.Namespace) - log.Info("Reconciling MapAccount...") + log.Info("Reconciling MapAccount") kubeClient, err := kube.GetClient() if err != nil { @@ -90,17 +88,17 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) if !ok || (ok && statusErr.ErrStatus.Reason != NotFound) { - logf.Log.Error(err, "Failure getting mapAccount") + log.Error(err, "Failure getting mapAccount") return ctrl.Result{}, err } return ctrl.Result{}, nil } // examine DeletionTimestamp to determine if object is under deletion if mapAccount.DeletionTimestamp.IsZero() { - // logf.Log.Info("mapAccount is not being deleted: " + mapAccount.Name) + log.V(1).Info("mapAccount is not being deleted") // Add finalizer if !controllerutil.ContainsFinalizer(mapAccount, awsauth.CrdFinalizerName) { - logf.Log.Info("Adding finalizer: " + mapAccount.Name) + log.V(1).Info("Adding finalizer: " + mapAccount.Name) controllerutil.AddFinalizer(mapAccount, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapAccount); err != nil { return ctrl.Result{}, err @@ -113,7 +111,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) log.Error(err, "Failure upserting MapAccount") return ctrl.Result{}, err } - // log.Info("Upserted MapAccount") + log.V(1).Info("Upserted MapAccount") } } else { diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index d4e7229..45d175b 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -57,7 +57,7 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct _ = logf.FromContext(ctx) log := ctrl.Log.WithValues("MapRole", req.Name, "namespace", req.Namespace) - log.Info("Reconciling MapRole...") + log.Info("Reconciling MapRole") kubeClient, err := kube.GetClient() if err != nil { @@ -93,10 +93,10 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct } if mapRole.DeletionTimestamp.IsZero() { - // logf.Log.Info("mapRole is not being deleted: " + mapRole.Name) + log.V(1).Info("mapRole is not being deleted: " + mapRole.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapRole, awsauth.CrdFinalizerName) { - logf.Log.Info("Adding finalizer: " + mapRole.Name) + log.V(1).Info("Adding finalizer: " + mapRole.Name) controllerutil.AddFinalizer(mapRole, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapRole); err != nil { return ctrl.Result{}, err @@ -111,7 +111,7 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct log.Error(err, "Failure upserting MapRole") return ctrl.Result{}, err } - // log.Info("Upserted MapRole") + log.V(1).Info("Upserted MapRole") } } else { log.Info("mapRole is being deleted") diff --git a/internal/controller/mapuser_controller.go b/internal/controller/mapuser_controller.go index 1a9bfb3..1a624fa 100644 --- a/internal/controller/mapuser_controller.go +++ b/internal/controller/mapuser_controller.go @@ -59,7 +59,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct // MapUser objects are named by their associated AWS IAM user ARNs. log := ctrl.Log.WithValues("MapUser", req.Name, "namespace", req.Namespace) - log.Info("Reconciling MapUser...") + log.Info("Reconciling MapUser") kubeClient, err := kube.GetClient() if err != nil { @@ -88,16 +88,16 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct // If any error other than a "NotFound" API error, it's a problem. statusErr, ok := err.(*apierrors.StatusError) if !ok || (ok && statusErr.ErrStatus.Reason != NotFound) { - logf.Log.Error(err, "Failure getting MapUser") + log.Error(err, "Failure getting MapUser") return ctrl.Result{}, err } return ctrl.Result{}, nil } if mapUser.DeletionTimestamp.IsZero() { - // logf.Log.Info("mapUser is not being deleted: " + mapUser.Name) + log.V(1).Info("mapUser is not being deleted: " + mapUser.Name) // Add finalizer if !controllerutil.ContainsFinalizer(mapUser, awsauth.CrdFinalizerName) { - logf.Log.Info("Adding finalizer: " + mapUser.Name) + log.V(1).Info("Adding finalizer: " + mapUser.Name) controllerutil.AddFinalizer(mapUser, awsauth.CrdFinalizerName) if err := r.Update(ctx, mapUser); err != nil { return ctrl.Result{}, err @@ -112,7 +112,7 @@ func (r *MapUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct log.Error(err, "Failure upserting MapUser") return ctrl.Result{}, err } - // log.Info("Upserted MapUser") + log.V(1).Info("Upserted MapUser") } } else { log.Info("mapUser is being deleted") From 57e06907582925c3394bca9e6930a9eac53571e9 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Wed, 16 Jul 2025 12:14:42 +0300 Subject: [PATCH 37/58] change kubeconfig for testing --- TODO.md | 6 ++-- cmd/main.go | 8 ++--- config/manager/manager.yaml | 6 ++-- internal/controller/suite_test.go | 58 ++++++++++++++++++++++++++++--- kube/kube.go | 4 --- kube/testing.go | 15 -------- 6 files changed, 63 insertions(+), 34 deletions(-) delete mode 100644 kube/testing.go diff --git a/TODO.md b/TODO.md index 101841a..d3cb760 100644 --- a/TODO.md +++ b/TODO.md @@ -1,7 +1,7 @@ ~~Додати флаг CrdAllowedNamespace, для контролю створення ресурсів~~ -* Реалізувати додавання акаунта за замовчуванням -* Дізнатися як обробляти дублікати при створенні ролей -* Прибрати зайве логування, налаштувати поточне +~~* Реалізувати додавання акаунта за замовчуванням~~ +~~* Дізнатися як обробляти дублікати при створенні ролей~~ +~~* Прибрати зайве логування, налаштувати поточне~~ * Переробити тести * Написати helm chart * Написати документацію \ No newline at end of file diff --git a/cmd/main.go b/cmd/main.go index b78fb72..1d63a23 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -74,7 +74,7 @@ func main() { var reconcileTime time.Duration var tlsOpts []func(*tls.Config) flag.BoolVar(&userNameMustBeEmail, "username-must-be-email", false, - "Enables checking of username, should it be an email address, default false."+ + "Enables checking of username in MapUser, should it be an email address, default false."+ "Use --username-must-be-email=true to enable this feature.") flag.StringVar(&mustPresentAccountID, "must-present-account-id", "", "This account must be "+ "allways present in ConfigMap, --must-present-account-id=123456789012") @@ -82,10 +82,10 @@ func main() { "Namespace where allowed creation of Resources --crd-item-allowed-namespace=kube-system, "+ "If is set, only in this namespace allowed creation of Resources,"+ " if not set, all namespaces allowed creation of Resources.") - flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where store items,"+ - " --config-map-name=aws-auth, if not set, use default name aws-auth") + flag.StringVar(&configMapName, "config-map-name", "aws-auth", "ConfigMap-name where stored items,"+ + " --config-map-name=aws-auth-test") flag.DurationVar(&reconcileTime, "reconcile-time", time.Minute*30, "Time to reconcile CRDs and recreate "+ - " configmap item if need, --reconcile-time=30m, s - seconds, m - minutes, h - hours, d - days") + "configmap item if need, --reconcile-time=30m, s - seconds, m - minutes, h - hours, d - days") flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index b3b88cc..77059d8 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -21,7 +21,7 @@ spec: matchLabels: control-plane: controller-manager app.kubernetes.io/name: aws-auth-controller-prozorro - replicas: 1 + replicas: 2 template: metadata: annotations: @@ -64,13 +64,13 @@ spec: - --config-map-name=aws-auth-test - --must-present-account-id=123456789012 - --crd-item-allowed-namespace=kube-system - - --reconcile-time=30s + - --reconcile-time=30m #- --username-must-be-email - --leader-elect - --health-probe-bind-address=:8081 - --zap-devel=true - --zap-encoder=console - - --zap-log-level=info + - --zap-log-level=debug - --zap-time-encoding=iso8601 - --zap-stacktrace-level=panic image: controller:latest diff --git a/internal/controller/suite_test.go b/internal/controller/suite_test.go index c832ae5..a5d5344 100644 --- a/internal/controller/suite_test.go +++ b/internal/controller/suite_test.go @@ -18,13 +18,16 @@ package controller import ( "context" + "fmt" "os" "path/filepath" "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - "github.com/redacid/aws-auth-controller/kube" + _ "github.com/redacid/aws-auth-controller/kube" + "k8s.io/client-go/tools/clientcmd" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" @@ -46,6 +49,7 @@ var ( testEnv *envtest.Environment cfg *rest.Config k8sClient client.Client + tmpDir string ) func TestControllers(t *testing.T) { @@ -81,9 +85,41 @@ var _ = BeforeSuite(func() { Expect(err).NotTo(HaveOccurred()) Expect(cfg).NotTo(BeNil()) - kube.SetTestConfig(cfg) + tmpDir, err = os.MkdirTemp("", "test-kubeconfig") + Expect(err).NotTo(HaveOccurred()) + kubeconfigPath := filepath.Join(tmpDir, "kubeconfig") + + apiConfig := &clientcmdapi.Config{ + APIVersion: "v1", + Kind: "Config", + Clusters: map[string]*clientcmdapi.Cluster{ + "test-cluster": { + Server: cfg.Host, + CertificateAuthorityData: cfg.CAData, + }, + }, + Contexts: map[string]*clientcmdapi.Context{ + "test-context": { + Cluster: "test-cluster", + AuthInfo: "test-user", + }, + }, + CurrentContext: "test-context", + AuthInfos: map[string]*clientcmdapi.AuthInfo{ + "test-user": { + ClientCertificateData: cfg.CertData, + ClientKeyData: cfg.KeyData, + }, + }, + } + + err = clientcmd.WriteToFile(*apiConfig, kubeconfigPath) + Expect(err).NotTo(HaveOccurred()) + + err = os.Setenv("KUBECONFIG", kubeconfigPath) + Expect(err).NotTo(HaveOccurred()) - // fmt.Printf("Test environment config: %+v\n", cfg) + fmt.Printf("Test environment config: %+v\n", cfg) k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) Expect(err).NotTo(HaveOccurred()) @@ -94,9 +130,21 @@ var _ = AfterSuite(func() { By("tearing down the test environment") cancel() - kube.ResetTestConfig() + // Видаляємо тимчасову директорію з kubeconfig + if tmpDir != "" { + logf.Log.Info("Removing temporary directory", "path", tmpDir) + err := os.RemoveAll(tmpDir) + if err != nil { + return + } + } + + err := os.Unsetenv("KUBECONFIG") + if err != nil { + return + } - err := testEnv.Stop() + err = testEnv.Stop() Expect(err).NotTo(HaveOccurred()) }) diff --git a/kube/kube.go b/kube/kube.go index 9042377..af3810f 100644 --- a/kube/kube.go +++ b/kube/kube.go @@ -12,10 +12,6 @@ import ( // GetClient returns a new configured Kubernetes client. func GetClient() (kubernetes.Interface, error) { - if testConfig != nil { - return kubernetes.NewForConfig(testConfig) - } - var cfg *rest.Config var err error diff --git a/kube/testing.go b/kube/testing.go deleted file mode 100644 index 961e91d..0000000 --- a/kube/testing.go +++ /dev/null @@ -1,15 +0,0 @@ -package kube - -import "k8s.io/client-go/rest" - -var testConfig *rest.Config - -// SetTestConfig встановлює конфігурацію для тестів -func SetTestConfig(cfg *rest.Config) { - testConfig = cfg -} - -// ResetTestConfig скидає тестову конфігурацію -func ResetTestConfig() { - testConfig = nil -} From 4093f87c3831f316c4a21307aa584ecf14c12a3e Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Wed, 16 Jul 2025 16:37:04 +0300 Subject: [PATCH 38/58] add webhook tests --- config/manager/manager.yaml | 2 +- .../webhook/v1beta1/mapaccount_webhook.go | 29 +--- .../v1beta1/mapaccount_webhook_test.go | 81 ++++++++--- internal/webhook/v1beta1/maprole_webhook.go | 30 ----- .../webhook/v1beta1/maprole_webhook_test.go | 108 ++++++++++++--- internal/webhook/v1beta1/mapuser_webhook.go | 31 +---- .../webhook/v1beta1/mapuser_webhook_test.go | 127 ++++++++++++++---- 7 files changed, 252 insertions(+), 156 deletions(-) diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index 77059d8..10bc3a1 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -70,7 +70,7 @@ spec: - --health-probe-bind-address=:8081 - --zap-devel=true - --zap-encoder=console - - --zap-log-level=debug + - --zap-log-level=info - --zap-time-encoding=iso8601 - --zap-stacktrace-level=panic image: controller:latest diff --git a/internal/webhook/v1beta1/mapaccount_webhook.go b/internal/webhook/v1beta1/mapaccount_webhook.go index 36abdc6..9243921 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook.go +++ b/internal/webhook/v1beta1/mapaccount_webhook.go @@ -106,7 +106,7 @@ func (v *MapAccountCustomValidator) ValidateCreate(ctx context.Context, obj runt mapaccountlog.Info("Validation for MapAccount upon creation", "name", mapaccount.GetName(), - "AccountID", mapaccount.Spec, + "AccountID", mapaccount.Spec.AccountID, ) if awsauth.CrdItemAllowedNamespace != "" { @@ -116,7 +116,6 @@ func (v *MapAccountCustomValidator) ValidateCreate(ctx context.Context, obj runt } } - // ----- var mapAccountList awsauthv1beta1.MapAccountList if err := v.Client.List(ctx, &mapAccountList); err != nil { return nil, err @@ -127,32 +126,6 @@ func (v *MapAccountCustomValidator) ValidateCreate(ctx context.Context, obj runt mapaccount.Spec.AccountID, existingAccount.GetName()) } } - // ----- - - /* kubeClient, err := kube.GetClient() - if err != nil { - mapaccountlog.Error(err, "Failure getting kube client") - return nil, err - } - - // Get a new aws auth service object. - awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ - KubeClient: kubeClient, - // Log: r.Log, - Log: ctrl.Log, - MaxRetryCount: 5, - }) - if err != nil { - mapaccountlog.Error(err, "Failure creating new aws auth service") - return nil, err - } - - if err = awsauthSvc.CheckMapAccountExists(awsauth.MapAccount{ - AccountID: mapaccount.Spec.AccountID, - }); err != nil { - mapaccountlog.Info("Failure checking, account exists in aws-auth configmap") - return nil, fmt.Errorf("failure checking, accountid %v exists in aws-auth configmap", mapaccount.Spec.AccountID) - }*/ return nil, nil } diff --git a/internal/webhook/v1beta1/mapaccount_webhook_test.go b/internal/webhook/v1beta1/mapaccount_webhook_test.go index bb5fcea..34ce23d 100644 --- a/internal/webhook/v1beta1/mapaccount_webhook_test.go +++ b/internal/webhook/v1beta1/mapaccount_webhook_test.go @@ -17,11 +17,13 @@ limitations under the License. package v1beta1 import ( + "context" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" - // TODO (user): Add any additional imports if needed ) var _ = Describe("MapAccount Webhook", func() { @@ -31,6 +33,14 @@ var _ = Describe("MapAccount Webhook", func() { validator MapAccountCustomValidator defaulter MapAccountCustomDefaulter ) + const ( + ResourceName = "test-account-resource" + PresentResourceName = "test-account-resource-present" + PresentAccountID = "333333333333" + AccountID = "111111111111" + OldAccountID = "222222222222" + Namespace = "default" + ) BeforeEach(func() { obj = &awsauthv1beta1.MapAccount{} @@ -41,7 +51,6 @@ var _ = Describe("MapAccount Webhook", func() { Expect(defaulter).NotTo(BeNil(), "Expected defaulter to be initialized") Expect(oldObj).NotTo(BeNil(), "Expected oldObj to be initialized") Expect(obj).NotTo(BeNil(), "Expected obj to be initialized") - // TODO (user): Add any setup logic common to all tests }) AfterEach(func() { @@ -62,26 +71,54 @@ var _ = Describe("MapAccount Webhook", func() { }) Context("When creating or updating MapAccount under Validating Webhook", func() { - // TODO (user): Add logic for validating webhooks - // Example: - // It("Should deny creation if a required field is missing", func() { - // By("simulating an invalid creation scenario") - // obj.SomeRequiredField = "" - // Expect(validator.ValidateCreate(ctx, obj)).Error().To(HaveOccurred()) - // }) - // - // It("Should admit creation if all required fields are present", func() { - // By("simulating an invalid creation scenario") - // obj.SomeRequiredField = "valid_value" - // Expect(validator.ValidateCreate(ctx, obj)).To(BeNil()) - // }) - // - // It("Should validate updates correctly", func() { - // By("simulating a valid update scenario") - // oldObj.SomeRequiredField = "updated_value" - // obj.SomeRequiredField = "updated_value" - // Expect(validator.ValidateUpdate(ctx, oldObj, obj)).To(BeNil()) - // }) + + It("Should MapAccount created", func() { + By("By creating a new MapAccount") + ctx := context.Background() + mapAccount := &awsauthv1beta1.MapAccount{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "aws-auth.prozorro.sale/v1beta1", + Kind: "MapAccount", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: PresentResourceName, + Namespace: Namespace, + }, + Spec: awsauthv1beta1.MapAccountSpec{ + AccountID: PresentAccountID, + }, + } + Expect(k8sClient.Create(ctx, mapAccount)).To(Succeed()) + }) + + It("Should MapAccount create new account with same data", func() { + By("By invalid creating a new MapAccount same account id") + ctx := context.Background() + mapAccount := &awsauthv1beta1.MapAccount{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "aws-auth.prozorro.sale/v1beta1", + Kind: "MapAccount", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: ResourceName, + Namespace: Namespace, + }, + Spec: awsauthv1beta1.MapAccountSpec{ + AccountID: PresentAccountID, + }, + } + Expect(k8sClient.Create(ctx, mapAccount)).Error().To(HaveOccurred()) + }) + + It("Should validate incorrect updates", func() { + By("simulating a invalid update scenario") + oldObj.Spec.AccountID = OldAccountID + oldObj.Namespace = Namespace + obj.Name = ResourceName + obj.Spec.AccountID = AccountID + obj.Namespace = Namespace + Expect(validator.ValidateUpdate(ctx, oldObj, obj)).Error().To(HaveOccurred()) + }) }) }) diff --git a/internal/webhook/v1beta1/maprole_webhook.go b/internal/webhook/v1beta1/maprole_webhook.go index 36ee0e8..2e54962 100644 --- a/internal/webhook/v1beta1/maprole_webhook.go +++ b/internal/webhook/v1beta1/maprole_webhook.go @@ -119,7 +119,6 @@ func (v *MapRoleCustomValidator) ValidateCreate(ctx context.Context, obj runtime } } - // ----- var mapRoleList awsauthv1beta1.MapRoleList if err := v.Client.List(ctx, &mapRoleList); err != nil { return nil, err @@ -131,35 +130,6 @@ func (v *MapRoleCustomValidator) ValidateCreate(ctx context.Context, obj runtime maprole.Spec.Username, maprole.Spec.RoleARN, existingUser.GetName()) } } - // ----- - - /* kubeClient, err := kube.GetClient() - if err != nil { - mapuserlog.Error(err, "Failure getting kube client") - return nil, err - } - - // Get a new aws auth service object. - awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ - KubeClient: kubeClient, - Log: ctrl.Log, - MaxRetryCount: 5, - }) - if err != nil { - mapuserlog.Error(err, "Failure creating new aws auth service") - return nil, err - } - - if err := awsauthSvc.CheckMapRoleExists(awsauth.MapRole{ - Username: maprole.Spec.Username, - RoleARN: maprole.Spec.RoleARN, - Groups: maprole.Spec.Groups, - }); err != nil { - mapuserlog.Info("Failure checking, username or userarn exists in aws-auth configmap") - return nil, fmt.Errorf("failure checking, username %v or rolearn %v exists in aws-auth configmap", maprole.Spec.Username, maprole.Spec.RoleARN) - } else { - mapuserlog.Info("username and rolearn not exists in aws-auth configmap") - }*/ return nil, nil } diff --git a/internal/webhook/v1beta1/maprole_webhook_test.go b/internal/webhook/v1beta1/maprole_webhook_test.go index 0782830..00bd7b4 100644 --- a/internal/webhook/v1beta1/maprole_webhook_test.go +++ b/internal/webhook/v1beta1/maprole_webhook_test.go @@ -17,11 +17,13 @@ limitations under the License. package v1beta1 import ( + "context" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" - // TODO (user): Add any additional imports if needed ) var _ = Describe("MapRole Webhook", func() { @@ -32,6 +34,19 @@ var _ = Describe("MapRole Webhook", func() { defaulter MapRoleCustomDefaulter ) + const ResourceName = "test-role-resource" + const PresentResourceName = "test-role-resource-present" + const PresentUsername = "test-user-present" + const PresentRoleARN = "arn:aws:iam::123456789012:role/test-role-present" + var PresentGroups = []string{"system:users", "system:viewers"} + const UserName = "test-role" + const OldUserName = "test-role-old" + const OldRoleARN = "arn:aws:iam::123456789012:role/test-role" + var OldGroups = []string{"system:users", "system:viewers"} + var Groups = []string{"system:masters", "system:nodes"} + const RoleARN = "arn:aws:iam::123456789012:role/test-role" + const Namespace = "default" + BeforeEach(func() { obj = &awsauthv1beta1.MapRole{} oldObj = &awsauthv1beta1.MapRole{} @@ -41,7 +56,6 @@ var _ = Describe("MapRole Webhook", func() { Expect(defaulter).NotTo(BeNil(), "Expected defaulter to be initialized") Expect(oldObj).NotTo(BeNil(), "Expected oldObj to be initialized") Expect(obj).NotTo(BeNil(), "Expected obj to be initialized") - // TODO (user): Add any setup logic common to all tests }) AfterEach(func() { @@ -62,26 +76,76 @@ var _ = Describe("MapRole Webhook", func() { }) Context("When creating or updating MapRole under Validating Webhook", func() { - // TODO (user): Add logic for validating webhooks - // Example: - // It("Should deny creation if a required field is missing", func() { - // By("simulating an invalid creation scenario") - // obj.SomeRequiredField = "" - // Expect(validator.ValidateCreate(ctx, obj)).Error().To(HaveOccurred()) - // }) - // - // It("Should admit creation if all required fields are present", func() { - // By("simulating an invalid creation scenario") - // obj.SomeRequiredField = "valid_value" - // Expect(validator.ValidateCreate(ctx, obj)).To(BeNil()) - // }) - // - // It("Should validate updates correctly", func() { - // By("simulating a valid update scenario") - // oldObj.SomeRequiredField = "updated_value" - // obj.SomeRequiredField = "updated_value" - // Expect(validator.ValidateUpdate(ctx, oldObj, obj)).To(BeNil()) - // }) + + It("Should MapRole created", func() { + By("By creating a new MapRole") + ctx := context.Background() + mapRole := &awsauthv1beta1.MapRole{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "aws-auth.prozorro.sale/v1beta1", + Kind: "MapRole", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: PresentResourceName, + Namespace: Namespace, + }, + Spec: awsauthv1beta1.MapRoleSpec{ + Username: PresentUsername, + Groups: PresentGroups, + RoleARN: PresentRoleARN, + }, + } + Expect(k8sClient.Create(ctx, mapRole)).To(Succeed()) + }) + + It("Should MapRole create new user with same data", func() { + By("By invalid creating a new MapRole same data") + ctx := context.Background() + mapRole := &awsauthv1beta1.MapRole{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "aws-auth.prozorro.sale/v1beta1", + Kind: "MapRole", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: ResourceName, + Namespace: Namespace, + }, + Spec: awsauthv1beta1.MapRoleSpec{ + Username: PresentUsername, + Groups: PresentGroups, + RoleARN: PresentRoleARN, + }, + } + Expect(k8sClient.Create(ctx, mapRole)).Error().To(HaveOccurred()) + }) + + It("Should validate incorrect updates", func() { + By("simulating a invalid update scenario") + oldObj.Spec.Username = OldUserName + oldObj.Spec.Groups = OldGroups + oldObj.Spec.RoleARN = OldRoleARN + oldObj.Namespace = Namespace + obj.Name = ResourceName + obj.Spec.Groups = Groups + obj.Spec.RoleARN = RoleARN + obj.Spec.Username = UserName + obj.Namespace = Namespace + Expect(validator.ValidateUpdate(ctx, oldObj, obj)).Error().To(HaveOccurred()) + }) + + It("Should validate updates correctly", func() { + By("simulating a valid update scenario") + oldObj.Spec.Username = UserName + oldObj.Spec.Groups = OldGroups + oldObj.Spec.RoleARN = RoleARN + oldObj.Namespace = Namespace + obj.Name = ResourceName + obj.Spec.Groups = Groups + obj.Spec.RoleARN = RoleARN + obj.Spec.Username = UserName + obj.Namespace = Namespace + Expect(validator.ValidateUpdate(ctx, oldObj, obj)).To(BeNil()) + }) }) }) diff --git a/internal/webhook/v1beta1/mapuser_webhook.go b/internal/webhook/v1beta1/mapuser_webhook.go index 314f9d4..d33b72c 100644 --- a/internal/webhook/v1beta1/mapuser_webhook.go +++ b/internal/webhook/v1beta1/mapuser_webhook.go @@ -118,7 +118,7 @@ func (v *MapUserCustomValidator) ValidateCreate(ctx context.Context, obj runtime return nil, fmt.Errorf("namespace %s is NOT allowed for creation MapUser", mapuser.GetNamespace()) } } - // ----- + var mapUserList awsauthv1beta1.MapUserList if err := v.Client.List(ctx, &mapUserList); err != nil { return nil, err @@ -130,40 +130,11 @@ func (v *MapUserCustomValidator) ValidateCreate(ctx context.Context, obj runtime mapuser.Spec.Username, mapuser.Spec.UserARN, existingUser.GetName()) } } - // ----- if err := awsauth.VerifyUsername(mapuser.Spec.Username, awsauth.UsernameMustBeEmail); err != nil { return nil, err } - /* kubeClient, err := kube.GetClient() - if err != nil { - mapuserlog.Error(err, "Failure getting kube client") - return nil, err - } - - // Get a new aws auth service object. - awsauthSvc, err := awsauth.NewService(&awsauth.ServiceConfig{ - KubeClient: kubeClient, - Log: ctrl.Log, - MaxRetryCount: 5, - }) - if err != nil { - mapuserlog.Error(err, "Failure creating new aws auth service") - return nil, err - } - - if err := awsauthSvc.CheckMapUserExists(awsauth.MapUser{ - Username: mapuser.Spec.Username, - UserARN: mapuser.Spec.UserARN, - Groups: mapuser.Spec.Groups, - }); err != nil { - mapuserlog.Info("Failure checking, username or userarn exists in aws-auth configmap") - return nil, fmt.Errorf("failure checking, username %v or userarn %v exists in aws-auth configmap", mapuser.Spec.Username, mapuser.Spec.UserARN) - } else { - mapuserlog.Info("username and userarn not exists in aws-auth configmap") - }*/ - return nil, nil } diff --git a/internal/webhook/v1beta1/mapuser_webhook_test.go b/internal/webhook/v1beta1/mapuser_webhook_test.go index bba35b4..8fe4c5c 100644 --- a/internal/webhook/v1beta1/mapuser_webhook_test.go +++ b/internal/webhook/v1beta1/mapuser_webhook_test.go @@ -17,11 +17,14 @@ limitations under the License. package v1beta1 import ( + "context" + . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + // v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" - // TODO (user): Add any additional imports if needed ) var _ = Describe("MapUser Webhook", func() { @@ -32,6 +35,19 @@ var _ = Describe("MapUser Webhook", func() { defaulter MapUserCustomDefaulter ) + const ResourceName = "test-user-resource" + const PresentResourceName = "test-user-resource-present" + const PresentUsername = "test-user-present" + const PresentUserARN = "arn:aws:iam::123456789012:user/test-user-present" + var PresentGroups = []string{"system:users", "system:viewers"} + const UserName = "test-user" + const OldUserName = "test-user-old" + const OldUserARN = "arn:aws:iam::123456789012:user/test-user-old" + var OldGroups = []string{"system:users", "system:viewers"} + var Groups = []string{"system:masters", "system:nodes"} + const UserARN = "arn:aws:iam::123456789012:user/test-user" + const Namespace = "default" + BeforeEach(func() { obj = &awsauthv1beta1.MapUser{} oldObj = &awsauthv1beta1.MapUser{} @@ -41,7 +57,6 @@ var _ = Describe("MapUser Webhook", func() { Expect(defaulter).NotTo(BeNil(), "Expected defaulter to be initialized") Expect(oldObj).NotTo(BeNil(), "Expected oldObj to be initialized") Expect(obj).NotTo(BeNil(), "Expected obj to be initialized") - // TODO (user): Add any setup logic common to all tests }) AfterEach(func() { @@ -62,26 +77,92 @@ var _ = Describe("MapUser Webhook", func() { }) Context("When creating or updating MapUser under Validating Webhook", func() { - // TODO (user): Add logic for validating webhooks - // Example: - // It("Should deny creation if a required field is missing", func() { - // By("simulating an invalid creation scenario") - // obj.SomeRequiredField = "" - // Expect(validator.ValidateCreate(ctx, obj)).Error().To(HaveOccurred()) - // }) - // - // It("Should admit creation if all required fields are present", func() { - // By("simulating an invalid creation scenario") - // obj.SomeRequiredField = "valid_value" - // Expect(validator.ValidateCreate(ctx, obj)).To(BeNil()) - // }) - // - // It("Should validate updates correctly", func() { - // By("simulating a valid update scenario") - // oldObj.SomeRequiredField = "updated_value" - // obj.SomeRequiredField = "updated_value" - // Expect(validator.ValidateUpdate(ctx, oldObj, obj)).To(BeNil()) - // }) - }) + It("Should MapUser created", func() { + By("By creating a new MapUser") + ctx := context.Background() + mapUser := &awsauthv1beta1.MapUser{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "aws-auth.prozorro.sale/v1beta1", + Kind: "MapUser", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: PresentResourceName, + Namespace: Namespace, + }, + Spec: awsauthv1beta1.MapUserSpec{ + Username: PresentUsername, + Groups: PresentGroups, + UserARN: PresentUserARN, + }, + } + Expect(k8sClient.Create(ctx, mapUser)).To(Succeed()) + }) + It("Should MapUser create new user with same Username", func() { + By("By invalid creating a new MapUser same Username") + ctx := context.Background() + mapUser := &awsauthv1beta1.MapUser{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "aws-auth.prozorro.sale/v1beta1", + Kind: "MapUser", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: ResourceName, + Namespace: Namespace, + }, + Spec: awsauthv1beta1.MapUserSpec{ + Username: PresentUsername, + Groups: PresentGroups, + UserARN: UserARN, + }, + } + Expect(k8sClient.Create(ctx, mapUser)).Error().To(HaveOccurred()) + }) + It("Should MapUser create new user with same UserARN", func() { + By("By invalid creating a new MapUser same UserARN") + ctx := context.Background() + mapUser := &awsauthv1beta1.MapUser{ + TypeMeta: metav1.TypeMeta{ + APIVersion: "aws-auth.prozorro.sale/v1beta1", + Kind: "MapUser", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: ResourceName, + Namespace: Namespace, + }, + Spec: awsauthv1beta1.MapUserSpec{ + Username: UserName, + Groups: PresentGroups, + UserARN: PresentUserARN, + }, + } + Expect(k8sClient.Create(ctx, mapUser)).Error().To(HaveOccurred()) + }) + It("Should validate incorrect updates", func() { + By("simulating a invalid update scenario") + oldObj.Spec.Username = OldUserName + oldObj.Spec.Groups = OldGroups + oldObj.Spec.UserARN = OldUserARN + oldObj.Namespace = Namespace + obj.Name = ResourceName + obj.Spec.Groups = Groups + obj.Spec.UserARN = UserARN + obj.Spec.Username = UserName + obj.Namespace = Namespace + Expect(validator.ValidateUpdate(ctx, oldObj, obj)).Error().To(HaveOccurred()) + }) + It("Should validate updates correctly", func() { + By("simulating a valid update scenario") + oldObj.Spec.Username = UserName + oldObj.Spec.Groups = OldGroups + oldObj.Spec.UserARN = UserARN + oldObj.Namespace = Namespace + obj.Name = ResourceName + obj.Spec.Groups = Groups + obj.Spec.UserARN = UserARN + obj.Spec.Username = UserName + obj.Namespace = Namespace + Expect(validator.ValidateUpdate(ctx, oldObj, obj)).To(BeNil()) + }) + }) }) From 20a54f056681bb53137dab408051bbec5975216b Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Wed, 16 Jul 2025 18:22:24 +0300 Subject: [PATCH 39/58] fix e2e tests --- .github/workflows/publish-release.yml | 3 +-- DEV-DOCS.md | 4 ++-- config/manager/kustomization.yaml | 4 ++-- config/manager/manager.yaml | 2 +- internal/webhook/v1beta1/mapuser_webhook_test.go | 3 +-- 5 files changed, 7 insertions(+), 9 deletions(-) diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index e693765..574d34a 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -3,8 +3,7 @@ name: Publish release on: push: tags: - - "0.*" - - "1.*" + - "*.*.*" env: REGISTRY: ghcr.io diff --git a/DEV-DOCS.md b/DEV-DOCS.md index e0c353c..18a9cfb 100644 --- a/DEV-DOCS.md +++ b/DEV-DOCS.md @@ -9,8 +9,8 @@ kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapUser --d kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapRole --defaulting --programmatic-validation kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapAccount --defaulting --programmatic-validation -git tag 0.0.1 -m "Test 0.0.1" -git push origin 0.0.1 +git tag 0.1.0 -m "Test Release 0.1.0" +git push origin 0.1.0 cd ./charts helm upgrade -i --namespace kube-system aws-auth aws-auth-operator cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapuser.yaml -n kube-system diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 84243c1..1606a7b 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -4,5 +4,5 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization images: - name: controller - newName: redacid/aws-auth-controller-dev - newTag: 0.0.107 + newName: example.com/aws-auth-controller-prozorro + newTag: v0.0.1 diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index 10bc3a1..9a03646 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -21,7 +21,7 @@ spec: matchLabels: control-plane: controller-manager app.kubernetes.io/name: aws-auth-controller-prozorro - replicas: 2 + replicas: 1 template: metadata: annotations: diff --git a/internal/webhook/v1beta1/mapuser_webhook_test.go b/internal/webhook/v1beta1/mapuser_webhook_test.go index 8fe4c5c..d7efb92 100644 --- a/internal/webhook/v1beta1/mapuser_webhook_test.go +++ b/internal/webhook/v1beta1/mapuser_webhook_test.go @@ -21,10 +21,9 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - // v1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" awsauthv1beta1 "github.com/redacid/aws-auth-controller/api/v1beta1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var _ = Describe("MapUser Webhook", func() { From 617d970dd3575df6ed66c239c604526b3d82ecc8 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 17 Jul 2025 17:43:16 +0300 Subject: [PATCH 40/58] helmchart edt --- charts/aws-auth-operator/Chart.yaml | 6 +- ...> aws-auth.prozorro.sale_mapaccounts.yaml} | 15 +- ...l => aws-auth.prozorro.sale_maproles.yaml} | 17 +- ...l => aws-auth.prozorro.sale_mapusers.yaml} | 17 +- .../templates/certificate-serving.yaml | 15 ++ .../templates/configmap.yaml | 20 -- .../templates/deployment.yaml | 32 ++- .../aws-auth-operator/templates/issuer.yaml | 9 + .../templates/prometheus.yaml | 20 -- charts/aws-auth-operator/templates/rbac.yaml | 215 +++++++----------- .../aws-auth-operator/templates/service.yaml | 16 ++ .../templates/webhook-validation.yaml | 70 ++++++ charts/aws-auth-operator/values.yaml | 12 +- config/manager/kustomization.yaml | 4 +- config/manager/manager.yaml | 2 +- 15 files changed, 276 insertions(+), 194 deletions(-) rename charts/aws-auth-operator/crds/{prozorro.sr.ios.in.ua_mapaccounts.yaml => aws-auth.prozorro.sale_mapaccounts.yaml} (83%) rename charts/aws-auth-operator/crds/{prozorro.sr.ios.in.ua_maproles.yaml => aws-auth.prozorro.sale_maproles.yaml} (82%) rename charts/aws-auth-operator/crds/{prozorro.sr.ios.in.ua_mapusers.yaml => aws-auth.prozorro.sale_mapusers.yaml} (82%) create mode 100644 charts/aws-auth-operator/templates/certificate-serving.yaml delete mode 100644 charts/aws-auth-operator/templates/configmap.yaml create mode 100644 charts/aws-auth-operator/templates/issuer.yaml delete mode 100644 charts/aws-auth-operator/templates/prometheus.yaml create mode 100644 charts/aws-auth-operator/templates/service.yaml create mode 100644 charts/aws-auth-operator/templates/webhook-validation.yaml diff --git a/charts/aws-auth-operator/Chart.yaml b/charts/aws-auth-operator/Chart.yaml index 1679ccc..58a376c 100644 --- a/charts/aws-auth-operator/Chart.yaml +++ b/charts/aws-auth-operator/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v2 -name: aws-auth-operator +name: aws-auth-operator-hhhhhhhhhhhhhhhhhhhh description: Kubernetes operator to declaratively manage the EKS aws-auth configmap # A chart can be either an 'application' or a 'library' chart. @@ -15,10 +15,10 @@ 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/) -version: 0.0.4 +version: 0.1.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. -appVersion: "0.0.4" +appVersion: "0.1.0" diff --git a/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapaccounts.yaml b/charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapaccounts.yaml similarity index 83% rename from charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapaccounts.yaml rename to charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapaccounts.yaml index cc3e1b1..68d818d 100644 --- a/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapaccounts.yaml +++ b/charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapaccounts.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.18.0 - name: mapaccounts.prozorro.sr.ios.in.ua + name: mapaccounts.aws-auth.prozorro.sale spec: - group: prozorro.sr.ios.in.ua + group: aws-auth.prozorro.sale names: kind: MapAccount listKind: MapAccountList @@ -14,7 +14,7 @@ spec: singular: mapaccount scope: Namespaced versions: - - name: v1alpha1 + - name: v1beta1 schema: openAPIV3Schema: description: MapAccount is the Schema for the mapaccounts API. @@ -37,12 +37,13 @@ spec: metadata: type: object spec: - description: MapAccountSpec defines the desired state of MapAccount. properties: - foo: - description: Foo is an example field of MapAccount. Edit mapaccount_types.go - to remove/update + accountid: + maxLength: 12 + minLength: 12 type: string + required: + - accountid type: object status: description: MapAccountStatus defines the observed state of MapAccount. diff --git a/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_maproles.yaml b/charts/aws-auth-operator/crds/aws-auth.prozorro.sale_maproles.yaml similarity index 82% rename from charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_maproles.yaml rename to charts/aws-auth-operator/crds/aws-auth.prozorro.sale_maproles.yaml index 39bbadd..81152f6 100644 --- a/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_maproles.yaml +++ b/charts/aws-auth-operator/crds/aws-auth.prozorro.sale_maproles.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.18.0 - name: maproles.prozorro.sr.ios.in.ua + name: maproles.aws-auth.prozorro.sale spec: - group: prozorro.sr.ios.in.ua + group: aws-auth.prozorro.sale names: kind: MapRole listKind: MapRoleList @@ -14,7 +14,7 @@ spec: singular: maprole scope: Namespaced versions: - - name: v1alpha1 + - name: v1beta1 schema: openAPIV3Schema: description: MapRole is the Schema for the maproles API. @@ -41,20 +41,29 @@ spec: properties: description: description: A useful description of the MapRole + maxLength: 254 type: string groups: description: The Kubernetes groups to associate with the MapRole items: + maxLength: 254 + minLength: 3 type: string + minItems: 1 type: array rolearn: description: The Role ARN to associate with the MapRole + pattern: ^arn:aws:iam::[0-9]{12}:role/[a-zA-Z0-9+=,.@_/-]+$ type: string username: - description: The email address of a contact person for the MapUser + description: The username for the MapUser + maxLength: 254 + minLength: 3 type: string required: + - groups - rolearn + - username type: object status: description: MapRoleStatus defines the observed state of MapRole. diff --git a/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapusers.yaml b/charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapusers.yaml similarity index 82% rename from charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapusers.yaml rename to charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapusers.yaml index 8379655..1590c2a 100644 --- a/charts/aws-auth-operator/crds/prozorro.sr.ios.in.ua_mapusers.yaml +++ b/charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapusers.yaml @@ -4,9 +4,9 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.18.0 - name: mapusers.prozorro.sr.ios.in.ua + name: mapusers.aws-auth.prozorro.sale spec: - group: prozorro.sr.ios.in.ua + group: aws-auth.prozorro.sale names: kind: MapUser listKind: MapUserList @@ -14,7 +14,7 @@ spec: singular: mapuser scope: Namespaced versions: - - name: v1alpha1 + - name: v1beta1 schema: openAPIV3Schema: description: MapUser is the Schema for the mapusers API. @@ -41,20 +41,29 @@ spec: properties: description: description: A useful description of the MapUser + maxLength: 254 type: string groups: description: The Kubernetes groups to associate with the MapUser items: + maxLength: 254 + minLength: 3 type: string + minItems: 1 type: array userarn: description: The User ARN to associate with the MapUser + pattern: ^arn:aws:iam::[0-9]{12}:user/[a-zA-Z0-9+=,.@_/-]+$ type: string username: - description: The email address of a contact person for the MapUser + description: The username for the MapUser + maxLength: 254 + minLength: 3 type: string required: + - groups - userarn + - username type: object status: description: MapUserStatus defines the observed state of MapUser. diff --git a/charts/aws-auth-operator/templates/certificate-serving.yaml b/charts/aws-auth-operator/templates/certificate-serving.yaml new file mode 100644 index 0000000..2f1a841 --- /dev/null +++ b/charts/aws-auth-operator/templates/certificate-serving.yaml @@ -0,0 +1,15 @@ +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + name: aws-auth-operator-serving-cert + namespace: {{ .Release.Namespace }} +spec: + dnsNames: + - {{ .Release.Name }}-webhook-service.{{ .Release.Namespace }}.svc + - {{ .Release.Name }}-webhook-service.{{ .Release.Namespace }}.svc.cluster.local + issuerRef: + kind: Issuer + name: aws-auth-operator-selfsigned-issuer + secretName: webhook-server-cert \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/configmap.yaml b/charts/aws-auth-operator/templates/configmap.yaml deleted file mode 100644 index caacecb..0000000 --- a/charts/aws-auth-operator/templates/configmap.yaml +++ /dev/null @@ -1,20 +0,0 @@ -apiVersion: v1 -data: - controller_manager_config.yaml: | - apiVersion: controller-runtime.sigs.k8s.io/v1alpha1 - kind: ControllerManagerConfig - health: - healthProbeBindAddress: :8081 - metrics: - bindAddress: 127.0.0.1:8080 - webhook: - port: 9443 - leaderElection: - leaderElect: {{ .Values.leaderElect.enabled }} - resourceName: 7bfe6d29.aws-auth.sr.ios.in.ua -kind: ConfigMap -metadata: - name: aws-auth-operator-manager-config - labels: - {{- include "aws-auth-operator.labels" . | nindent 4 }} - control-plane: controller-manager diff --git a/charts/aws-auth-operator/templates/deployment.yaml b/charts/aws-auth-operator/templates/deployment.yaml index fa1a46a..848d067 100644 --- a/charts/aws-auth-operator/templates/deployment.yaml +++ b/charts/aws-auth-operator/templates/deployment.yaml @@ -4,7 +4,8 @@ metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager - name: aws-auth-operator-controller-manager + name: {{ .Release.Name }}-controller-manager + namespace: {{ .Release.Namespace }} spec: replicas: {{ .Values.replicaCount }} selector: @@ -18,7 +19,19 @@ spec: spec: containers: - args: - - --leader-elect + - --metrics-bind-address=:8443 + - --config-map-name=aws-auth-test + - --must-present-account-id=123456789012 + - --crd-item-allowed-namespace=kube-system + - --reconcile-time=30m + - --leader-elect + - --health-probe-bind-address=:8081 + - --zap-devel=true + - --zap-encoder=console + - --zap-log-level=info + - --zap-time-encoding=iso8601 + - --zap-stacktrace-level=panic + - --webhook-cert-path=/tmp/k8s-webhook-server/serving-certs command: - /manager image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" @@ -29,6 +42,10 @@ spec: initialDelaySeconds: 15 periodSeconds: 20 name: manager + ports: + - containerPort: 9443 + name: webhook-server + protocol: TCP readinessProbe: httpGet: path: /readyz @@ -39,6 +56,13 @@ spec: {{- toYaml .Values.resources | nindent 10 }} securityContext: allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + volumeMounts: + - mountPath: /tmp/k8s-webhook-server/serving-certs + name: webhook-certs + readOnly: true {{- with .Values.nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} @@ -55,3 +79,7 @@ spec: {{- toYaml .Values.securityContext | nindent 8 }} serviceAccountName: aws-auth-operator-controller-manager terminationGracePeriodSeconds: 10 + volumes: + - name: webhook-certs + secret: + secretName: webhook-server-cert diff --git a/charts/aws-auth-operator/templates/issuer.yaml b/charts/aws-auth-operator/templates/issuer.yaml new file mode 100644 index 0000000..9d0f561 --- /dev/null +++ b/charts/aws-auth-operator/templates/issuer.yaml @@ -0,0 +1,9 @@ +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + name: aws-auth-operator-selfsigned-issuer + namespace: {{ .Release.Namespace }} +spec: + selfSigned: {} \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/prometheus.yaml b/charts/aws-auth-operator/templates/prometheus.yaml deleted file mode 100644 index 21f9ee2..0000000 --- a/charts/aws-auth-operator/templates/prometheus.yaml +++ /dev/null @@ -1,20 +0,0 @@ -{{- if .Values.prometheus.enabled -}} -apiVersion: monitoring.coreos.com/v1 -kind: ServiceMonitor -metadata: - labels: - {{- include "aws-auth-operator.labels" . | nindent 4 }} - control-plane: controller-manager - name: aws-auth-operator-controller-manager-metrics-monitor -spec: - endpoints: - - bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token - path: /metrics - port: https - scheme: https - tlsConfig: - insecureSkipVerify: true - selector: - matchLabels: - control-plane: controller-manager -{{- end }} \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/rbac.yaml b/charts/aws-auth-operator/templates/rbac.yaml index 86f7b22..9c0be31 100644 --- a/charts/aws-auth-operator/templates/rbac.yaml +++ b/charts/aws-auth-operator/templates/rbac.yaml @@ -14,37 +14,37 @@ metadata: control-plane: controller-manager name: aws-auth-operator-leader-election-role rules: -- apiGroups: - - "" - resources: - - configmaps - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - coordination.k8s.io - resources: - - leases - verbs: - - get - - list - - watch - - create - - update - - patch - - delete -- apiGroups: - - "" - resources: - - events - verbs: - - create - - patch + - apiGroups: + - "" + resources: + - configmaps + verbs: + - get + - list + - watch + - create + - update + - patch + - delete + - 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: ClusterRole @@ -54,102 +54,63 @@ metadata: control-plane: controller-manager name: aws-auth-operator-manager-role rules: -- apiGroups: - - prozorro.sr.ios.in.ua - resources: - - maproles - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - prozorro.sr.ios.in.ua - resources: - - maproles/finalizers - verbs: - - update -- apiGroups: - - prozorro.sr.ios.in.ua - resources: - - maproles/status - verbs: - - get - - patch - - update -- apiGroups: - - prozorro.sr.ios.in.ua - resources: - - mapusers - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - prozorro.sr.ios.in.ua - resources: - - mapusers/finalizers - verbs: - - update -- apiGroups: - - prozorro.sr.ios.in.ua - resources: - - mapusers/status - verbs: - - get - - patch - - update -- apiGroups: - - prozorro.sr.ios.in.ua - resources: - - mapaccounts - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - prozorro.sr.ios.in.ua - resources: - - mapaccounts/finalizers - verbs: - - update -- apiGroups: - - prozorro.sr.ios.in.ua - resources: - - mapaccounts/status - verbs: - - get - - patch - - update -- apiGroups: - - "" - resources: - - configmaps - verbs: - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - - namespaces - verbs: - - get - - list - - watch + - apiGroups: + - "" + resources: + - configmaps + verbs: + - create + - delete + - get + - list + - patch + - update + - watch + - apiGroups: + - "" + resourceNames: + - aws-auth + resources: + - configmaps + verbs: + - delete + - get + - list + - patch + - update + - watch + - apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts + - maproles + - mapusers + verbs: + - create + - delete + - get + - list + - patch + - update + - watch + - apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts/finalizers + - maproles/finalizers + - mapusers/finalizers + verbs: + - update + - apiGroups: + - aws-auth.prozorro.sale + resources: + - mapaccounts/status + - maproles/status + - mapusers/status + verbs: + - get + - patch + - update --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/charts/aws-auth-operator/templates/service.yaml b/charts/aws-auth-operator/templates/service.yaml new file mode 100644 index 0000000..375ffa6 --- /dev/null +++ b/charts/aws-auth-operator/templates/service.yaml @@ -0,0 +1,16 @@ +apiVersion: v1 +kind: Service +metadata: + labels: + {{- include "aws-auth-operator.labels" . | nindent 4 }} + name: {{ .Release.Name }}-webhook-service + namespace: {{ .Release.Namespace }} +spec: + ports: + - port: 443 + protocol: TCP + targetPort: 9443 + selector: + app.kubernetes.io/name: {{ include "aws-auth-operator.name" . }} + app.kubernetes.io/instance: {{ .Release.Name }} + control-plane: controller-manager \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/webhook-validation.yaml b/charts/aws-auth-operator/templates/webhook-validation.yaml new file mode 100644 index 0000000..474aa0b --- /dev/null +++ b/charts/aws-auth-operator/templates/webhook-validation.yaml @@ -0,0 +1,70 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + annotations: + cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/aws-auth-operator-serving-cert + name: aws-auth-operator-validating-webhook-configuration +webhooks: + - admissionReviewVersions: + - v1 + clientConfig: + service: + name: {{ .Release.Name }}-webhook-service + namespace: {{ .Release.Namespace }} + path: /validate-aws-auth-prozorro-sale-v1beta1-mapaccount + failurePolicy: Fail + name: vmapaccount-v1beta1.kb.io + rules: + - apiGroups: + - aws-auth.prozorro.sale + apiVersions: + - v1beta1 + operations: + - CREATE + - UPDATE + - DELETE + resources: + - mapaccounts + sideEffects: None + - admissionReviewVersions: + - v1 + clientConfig: + service: + name: {{ .Release.Name }}-webhook-service + namespace: {{ .Release.Namespace }} + path: /validate-aws-auth-prozorro-sale-v1beta1-maprole + failurePolicy: Fail + name: vmaprole-v1beta1.kb.io + rules: + - apiGroups: + - aws-auth.prozorro.sale + apiVersions: + - v1beta1 + operations: + - CREATE + - UPDATE + - DELETE + resources: + - maproles + sideEffects: None + - admissionReviewVersions: + - v1 + clientConfig: + service: + name: {{ .Release.Name }}-webhook-service + namespace: {{ .Release.Namespace }} + path: /validate-aws-auth-prozorro-sale-v1beta1-mapuser + failurePolicy: Fail + name: vmapuser-v1beta1.kb.io + rules: + - apiGroups: + - aws-auth.prozorro.sale + apiVersions: + - v1beta1 + operations: + - CREATE + - UPDATE + - DELETE + resources: + - mapusers + sideEffects: None \ No newline at end of file diff --git a/charts/aws-auth-operator/values.yaml b/charts/aws-auth-operator/values.yaml index 9008f01..f3a1c86 100644 --- a/charts/aws-auth-operator/values.yaml +++ b/charts/aws-auth-operator/values.yaml @@ -2,14 +2,14 @@ # This is a YAML-formatted file. # Declare variables to be passed into your templates. -replicaCount: 2 +replicaCount: 1 image: #repository: ghcr.io/redacid/kubebuilder_test - repository: redacid/aws-auth-controller + repository: ghcr.io/redacid/aws-auth-controller pullPolicy: IfNotPresent # Overrides the image tag whose default is the chart appVersion. - tag: "0.0.8" + tag: "0.1.0" imagePullSecrets: [] nameOverride: "" @@ -29,7 +29,11 @@ podAnnotations: {} podSecurityContext: {} # fsGroup: 2000 -securityContext: {} +securityContext: + #{} + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault # capabilities: # drop: # - ALL diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml index 1606a7b..84243c1 100644 --- a/config/manager/kustomization.yaml +++ b/config/manager/kustomization.yaml @@ -4,5 +4,5 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization images: - name: controller - newName: example.com/aws-auth-controller-prozorro - newTag: v0.0.1 + newName: redacid/aws-auth-controller-dev + newTag: 0.0.107 diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index 9a03646..10bc3a1 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -21,7 +21,7 @@ spec: matchLabels: control-plane: controller-manager app.kubernetes.io/name: aws-auth-controller-prozorro - replicas: 1 + replicas: 2 template: metadata: annotations: From 9f09f74917af1241d3784312aab6bd8e42b9a8b7 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 17 Jul 2025 19:53:18 +0300 Subject: [PATCH 41/58] add codecow --- .github/workflows/test.yml | 5 +++++ .gitignore | 1 + DEV-DOCS.md | 8 ++++++++ Makefile | 2 +- 4 files changed, 15 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fc2e80d..e868d63 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -21,3 +21,8 @@ jobs: run: | go mod tidy make test + + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index ada68ff..bb937e4 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,4 @@ go.work *.swp *.swo *~ +/coverage.txt diff --git a/DEV-DOCS.md b/DEV-DOCS.md index 18a9cfb..d24c0c5 100644 --- a/DEV-DOCS.md +++ b/DEV-DOCS.md @@ -12,6 +12,13 @@ kubebuilder create webhook --group aws-auth --version v1beta1 --kind MapAccount git tag 0.1.0 -m "Test Release 0.1.0" git push origin 0.1.0 + +clear && helm template ttttt ./aws-auth-operator -n nnnnn +clear && helm upgrade -i rrrrr ./aws-auth-operator -n nnnnn --create-namespace +helm uninstall rrrrr -n nnnnn + +echo | openssl s_client -servername rrrrr-webhook-service.nnnnn.svc -showcerts -connect localhost:42765 2>/dev/null | openssl x509 -inform pem -noout -text + cd ./charts helm upgrade -i --namespace kube-system aws-auth aws-auth-operator cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapuser.yaml -n kube-system cd ./config/samples kubectl apply -f aws-auth_v1beta1_maprole.yaml -n kube-system @@ -24,6 +31,7 @@ https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/reconcile/re https://book.kubebuilder.io/reference/watching-resources.html?highlight=RequeueAfter#when-requeueafter-x-is-useful https://github.com/gp42/aws-auth-operator +https://github.com/keikoproj/aws-auth/ Usage of ./manager: -config-map-name string diff --git a/Makefile b/Makefile index b83550d..640e26c 100644 --- a/Makefile +++ b/Makefile @@ -73,7 +73,7 @@ vet: ## Run go vet against code. .PHONY: test test: manifests generate fmt vet setup-envtest ## Run tests. - KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" go test $$(go list ./... | grep -v /e2e) -coverprofile cover.out + KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" go test $$(go list ./... | grep -v /e2e) -coverprofile coverage.txt # TODO(user): To use a different vendor for e2e tests, modify the setup under 'tests/e2e'. # The default setup assumes Kind is pre-installed and builds/loads the Manager Docker image locally. From d9e9fc46f645fe86072f7dcc301a0ba2d438f037 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 17 Jul 2025 20:05:39 +0300 Subject: [PATCH 42/58] add codecow badge --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8c02383..0c0b2eb 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ -# aws-auth-controller \ No newline at end of file +# aws-auth-controller +[![codecov](https://codecov.io/github/redacid/aws-auth-controller/graph/badge.svg?token=3B6KI6EJCR)](https://codecov.io/github/redacid/aws-auth-controller) \ No newline at end of file From 37f8a6ffcd56f766a670c4783e7470a26505d19d Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 17 Jul 2025 20:14:26 +0300 Subject: [PATCH 43/58] add tests badge --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0c0b2eb..f8eeeed 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ # aws-auth-controller -[![codecov](https://codecov.io/github/redacid/aws-auth-controller/graph/badge.svg?token=3B6KI6EJCR)](https://codecov.io/github/redacid/aws-auth-controller) \ No newline at end of file +[![codecov](https://codecov.io/github/redacid/aws-auth-controller/graph/badge.svg?token=3B6KI6EJCR)](https://codecov.io/github/redacid/aws-auth-controller) +[![unit-test](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml/badge.svg?branch=init)](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml) \ No newline at end of file From 4973f857b1d735c84db2a856c85339c6fbe1d946 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 17 Jul 2025 20:21:34 +0300 Subject: [PATCH 44/58] add LICENSE --- .github/LICENSE | 146 ++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 3 +- 2 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 .github/LICENSE diff --git a/.github/LICENSE b/.github/LICENSE new file mode 100644 index 0000000..c3b8c75 --- /dev/null +++ b/.github/LICENSE @@ -0,0 +1,146 @@ + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index f8eeeed..ca84fcd 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ # aws-auth-controller [![codecov](https://codecov.io/github/redacid/aws-auth-controller/graph/badge.svg?token=3B6KI6EJCR)](https://codecov.io/github/redacid/aws-auth-controller) -[![unit-test](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml/badge.svg?branch=init)](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml) \ No newline at end of file +[![unit-test](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml/badge.svg?branch=init)](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml) +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/redacid/aws-auth-controller/blob/init/LICENSE) \ No newline at end of file From 17b56cf193fbfd21763b9d908e09be700a1e45c1 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 17 Jul 2025 20:22:39 +0300 Subject: [PATCH 45/58] ups --- .github/LICENSE => LICENSE | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/LICENSE => LICENSE (100%) diff --git a/.github/LICENSE b/LICENSE similarity index 100% rename from .github/LICENSE rename to LICENSE From f31b80b559933b9ebc6b41e2d9bf3052d560f520 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Fri, 18 Jul 2025 15:53:19 +0300 Subject: [PATCH 46/58] chart edt --- DEV-DOCS.md | 2 +- charts/aws-auth-operator/Chart.yaml | 2 +- .../aws-auth-operator/templates/_helpers.tpl | 6 +- .../templates/certificate-serving.yaml | 12 +-- .../templates/deployment.yaml | 40 ++++----- .../aws-auth-operator/templates/issuer.yaml | 6 +- charts/aws-auth-operator/templates/pdb.yaml | 2 +- charts/aws-auth-operator/templates/rbac.yaml | 18 ++-- .../aws-auth-operator/templates/service.yaml | 2 +- .../templates/webhook-validation.yaml | 12 +-- charts/aws-auth-operator/values.yaml | 86 ++++++++----------- 11 files changed, 88 insertions(+), 100 deletions(-) diff --git a/DEV-DOCS.md b/DEV-DOCS.md index d24c0c5..93bcbaa 100644 --- a/DEV-DOCS.md +++ b/DEV-DOCS.md @@ -13,7 +13,7 @@ git tag 0.1.0 -m "Test Release 0.1.0" git push origin 0.1.0 -clear && helm template ttttt ./aws-auth-operator -n nnnnn +clear && helm template rrrrr ./aws-auth-operator -n nnnnn clear && helm upgrade -i rrrrr ./aws-auth-operator -n nnnnn --create-namespace helm uninstall rrrrr -n nnnnn diff --git a/charts/aws-auth-operator/Chart.yaml b/charts/aws-auth-operator/Chart.yaml index 58a376c..08053a6 100644 --- a/charts/aws-auth-operator/Chart.yaml +++ b/charts/aws-auth-operator/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v2 -name: aws-auth-operator-hhhhhhhhhhhhhhhhhhhh +name: aws-auth-operator description: Kubernetes operator to declaratively manage the EKS aws-auth configmap # A chart can be either an 'application' or a 'library' chart. diff --git a/charts/aws-auth-operator/templates/_helpers.tpl b/charts/aws-auth-operator/templates/_helpers.tpl index 5612d3d..40ad987 100644 --- a/charts/aws-auth-operator/templates/_helpers.tpl +++ b/charts/aws-auth-operator/templates/_helpers.tpl @@ -2,7 +2,7 @@ Expand the name of the chart. */}} {{- define "aws-auth-operator.name" -}} -{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- default .Chart.Name .Values.nameOverride | trunc 41 | trimSuffix "-" }} {{- end }} {{/* @@ -12,13 +12,13 @@ If release name contains chart name it will be used as a full name. */}} {{- define "aws-auth-operator.fullname" -}} {{- if .Values.fullnameOverride }} -{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- .Values.fullnameOverride | trunc 41 | 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 "-" }} +{{- printf "%s-%s" .Release.Name $name | trunc 41 | trimSuffix "-" }} {{- end }} {{- end }} {{- end }} diff --git a/charts/aws-auth-operator/templates/certificate-serving.yaml b/charts/aws-auth-operator/templates/certificate-serving.yaml index 2f1a841..c69210e 100644 --- a/charts/aws-auth-operator/templates/certificate-serving.yaml +++ b/charts/aws-auth-operator/templates/certificate-serving.yaml @@ -1,15 +1,17 @@ +{{- if .Values.selfSignedIssuer.enabled -}} apiVersion: cert-manager.io/v1 kind: Certificate metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} - name: aws-auth-operator-serving-cert + name: {{ include "aws-auth-operator.fullname" . }}-serving-cert namespace: {{ .Release.Namespace }} spec: dnsNames: - - {{ .Release.Name }}-webhook-service.{{ .Release.Namespace }}.svc - - {{ .Release.Name }}-webhook-service.{{ .Release.Namespace }}.svc.cluster.local + - {{ include "aws-auth-operator.fullname" . }}-webhook-service.{{ .Release.Namespace }}.svc + - {{ include "aws-auth-operator.fullname" . }}-webhook-service.{{ .Release.Namespace }}.svc.cluster.local issuerRef: kind: Issuer - name: aws-auth-operator-selfsigned-issuer - secretName: webhook-server-cert \ No newline at end of file + name: {{ include "aws-auth-operator.fullname" . }}-selfsigned-issuer + secretName: {{ include "aws-auth-operator.fullname" . }}-webhook-server-cert +{{- end }} \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/deployment.yaml b/charts/aws-auth-operator/templates/deployment.yaml index 848d067..c449229 100644 --- a/charts/aws-auth-operator/templates/deployment.yaml +++ b/charts/aws-auth-operator/templates/deployment.yaml @@ -4,7 +4,7 @@ metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager - name: {{ .Release.Name }}-controller-manager + name: {{ include "aws-auth-operator.fullname" . }}-controller-manager namespace: {{ .Release.Namespace }} spec: replicas: {{ .Values.replicaCount }} @@ -16,22 +16,23 @@ spec: labels: {{- include "aws-auth-operator.labels" . | nindent 8 }} control-plane: controller-manager + {{- with .Values.podAnnotations }} + annotations: + {{ toYaml . | nindent 8 }} + {{- end }} spec: containers: - args: - - --metrics-bind-address=:8443 - - --config-map-name=aws-auth-test - - --must-present-account-id=123456789012 - - --crd-item-allowed-namespace=kube-system - - --reconcile-time=30m + - --config-map-name={{ .Values.configMapName }} + - --must-present-account-id={{ .Values.mustPresentAccountID }} + - --crd-item-allowed-namespace={{ .Values.crdCreationAllowedNS }} + - --reconcile-time={{ .Values.reconcileTime }} - --leader-elect - --health-probe-bind-address=:8081 - - --zap-devel=true - - --zap-encoder=console - - --zap-log-level=info - - --zap-time-encoding=iso8601 - - --zap-stacktrace-level=panic - --webhook-cert-path=/tmp/k8s-webhook-server/serving-certs + {{- with .Values.controllerArguments -}} + {{ toYaml . | nindent 10 }} + {{- end }} command: - /manager image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" @@ -55,31 +56,28 @@ spec: resources: {{- toYaml .Values.resources | nindent 10 }} securityContext: - allowPrivilegeEscalation: false - capabilities: - drop: - - ALL + {{- toYaml .Values.securityContext | nindent 10 }} volumeMounts: - mountPath: /tmp/k8s-webhook-server/serving-certs name: webhook-certs readOnly: true {{- with .Values.nodeSelector }} nodeSelector: - {{- toYaml . | nindent 8 }} + {{ toYaml . | nindent 8 }} {{- end }} {{- with .Values.affinity }} affinity: - {{- toYaml . | nindent 8 }} + {{ toYaml . | nindent 8 }} {{- end }} {{- with .Values.tolerations }} tolerations: - {{- toYaml . | nindent 8 }} + {{ toYaml . | nindent 8 }} {{- end }} securityContext: - {{- toYaml .Values.securityContext | nindent 8 }} - serviceAccountName: aws-auth-operator-controller-manager + {{- toYaml .Values.podSecurityContext | nindent 8 }} + serviceAccountName: {{ include "aws-auth-operator.fullname" . }}-controller-manager terminationGracePeriodSeconds: 10 volumes: - name: webhook-certs secret: - secretName: webhook-server-cert + secretName: {{ include "aws-auth-operator.fullname" . }}-webhook-server-cert diff --git a/charts/aws-auth-operator/templates/issuer.yaml b/charts/aws-auth-operator/templates/issuer.yaml index 9d0f561..347ae7d 100644 --- a/charts/aws-auth-operator/templates/issuer.yaml +++ b/charts/aws-auth-operator/templates/issuer.yaml @@ -1,9 +1,11 @@ +{{- if .Values.selfSignedIssuer.enabled -}} apiVersion: cert-manager.io/v1 kind: Issuer metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} - name: aws-auth-operator-selfsigned-issuer + name: {{ include "aws-auth-operator.fullname" . }}-selfsigned-issuer namespace: {{ .Release.Namespace }} spec: - selfSigned: {} \ No newline at end of file + selfSigned: {} +{{- end }} \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/pdb.yaml b/charts/aws-auth-operator/templates/pdb.yaml index e3d77be..ce9c055 100644 --- a/charts/aws-auth-operator/templates/pdb.yaml +++ b/charts/aws-auth-operator/templates/pdb.yaml @@ -3,7 +3,7 @@ apiVersion: policy/v1 kind: PodDisruptionBudget metadata: labels: - {{- include "aws-auth-operator.labels" . | nindent 4 }} + {{ include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager name: {{ include "aws-auth-operator.fullname" . }} spec: diff --git a/charts/aws-auth-operator/templates/rbac.yaml b/charts/aws-auth-operator/templates/rbac.yaml index 9c0be31..e5aab1d 100644 --- a/charts/aws-auth-operator/templates/rbac.yaml +++ b/charts/aws-auth-operator/templates/rbac.yaml @@ -4,7 +4,7 @@ metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager - name: aws-auth-operator-controller-manager + name: {{ include "aws-auth-operator.fullname" . }}-controller-manager --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role @@ -12,7 +12,7 @@ metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager - name: aws-auth-operator-leader-election-role + name: {{ include "aws-auth-operator.fullname" . }}-leader-election-role rules: - apiGroups: - "" @@ -52,7 +52,7 @@ metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager - name: aws-auth-operator-manager-role + name: {{ include "aws-auth-operator.fullname" . }}-manager-role rules: - apiGroups: - "" @@ -118,14 +118,14 @@ metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager - name: aws-auth-operator-leader-election-rolebinding + name: {{ include "aws-auth-operator.fullname" . }}-leader-election-rb roleRef: apiGroup: rbac.authorization.k8s.io kind: Role - name: aws-auth-operator-leader-election-role + name: {{ include "aws-auth-operator.fullname" . }}-leader-election-role subjects: - kind: ServiceAccount - name: aws-auth-operator-controller-manager + name: {{ include "aws-auth-operator.fullname" . }}-controller-manager --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding @@ -133,12 +133,12 @@ metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager - name: aws-auth-operator-manager-rolebinding + name: {{ include "aws-auth-operator.fullname" . }}-manager-rb roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole - name: aws-auth-operator-manager-role + name: {{ include "aws-auth-operator.fullname" . }}-manager-role subjects: - kind: ServiceAccount - name: aws-auth-operator-controller-manager + name: {{ include "aws-auth-operator.fullname" . }}-controller-manager namespace: {{ .Release.Namespace }} \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/service.yaml b/charts/aws-auth-operator/templates/service.yaml index 375ffa6..9101efe 100644 --- a/charts/aws-auth-operator/templates/service.yaml +++ b/charts/aws-auth-operator/templates/service.yaml @@ -3,7 +3,7 @@ kind: Service metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} - name: {{ .Release.Name }}-webhook-service + name: {{ include "aws-auth-operator.fullname" . }}-webhook-service namespace: {{ .Release.Namespace }} spec: ports: diff --git a/charts/aws-auth-operator/templates/webhook-validation.yaml b/charts/aws-auth-operator/templates/webhook-validation.yaml index 474aa0b..0195f7d 100644 --- a/charts/aws-auth-operator/templates/webhook-validation.yaml +++ b/charts/aws-auth-operator/templates/webhook-validation.yaml @@ -2,14 +2,16 @@ apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingWebhookConfiguration metadata: annotations: - cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/aws-auth-operator-serving-cert - name: aws-auth-operator-validating-webhook-configuration + {{- if .Values.selfSignedIssuer.enabled }} + cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/{{ include "aws-auth-operator.fullname" . }}-serving-cert + {{- end }} + name: {{ include "aws-auth-operator.fullname" . }}-validating-webhook webhooks: - admissionReviewVersions: - v1 clientConfig: service: - name: {{ .Release.Name }}-webhook-service + name: {{ include "aws-auth-operator.fullname" . }}-webhook-service namespace: {{ .Release.Namespace }} path: /validate-aws-auth-prozorro-sale-v1beta1-mapaccount failurePolicy: Fail @@ -30,7 +32,7 @@ webhooks: - v1 clientConfig: service: - name: {{ .Release.Name }}-webhook-service + name: {{ include "aws-auth-operator.fullname" . }}-webhook-service namespace: {{ .Release.Namespace }} path: /validate-aws-auth-prozorro-sale-v1beta1-maprole failurePolicy: Fail @@ -51,7 +53,7 @@ webhooks: - v1 clientConfig: service: - name: {{ .Release.Name }}-webhook-service + name: {{ include "aws-auth-operator.fullname" . }}-webhook-service namespace: {{ .Release.Namespace }} path: /validate-aws-auth-prozorro-sale-v1beta1-mapuser failurePolicy: Fail diff --git a/charts/aws-auth-operator/values.yaml b/charts/aws-auth-operator/values.yaml index f3a1c86..9ef3f36 100644 --- a/charts/aws-auth-operator/values.yaml +++ b/charts/aws-auth-operator/values.yaml @@ -2,38 +2,24 @@ # This is a YAML-formatted file. # Declare variables to be passed into your templates. -replicaCount: 1 +replicaCount: 2 image: - #repository: ghcr.io/redacid/kubebuilder_test repository: ghcr.io/redacid/aws-auth-controller pullPolicy: IfNotPresent - # Overrides the image tag whose default is the chart appVersion. tag: "0.1.0" imagePullSecrets: [] nameOverride: "" fullnameOverride: "" -serviceAccount: - # Specifies whether a service account should be created - create: 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: "" - podAnnotations: {} -podSecurityContext: {} - # fsGroup: 2000 - securityContext: - #{} - runAsNonRoot: true - seccompProfile: - type: RuntimeDefault + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL # capabilities: # drop: # - ALL @@ -41,44 +27,32 @@ securityContext: # runAsNonRoot: true # runAsUser: 1000 -service: - type: ClusterIP - port: 80 +podSecurityContext: + #{} + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + -ingress: - enabled: false - className: "" - annotations: {} - # kubernetes.io/ingress.class: nginx - # kubernetes.io/tls-acme: "true" - hosts: - - host: chart-example.local.domain - paths: - - path: / - pathType: ImplementationSpecific - tls: [] - # - secretName: chart-example-tls - # hosts: - # - chart-example.local - -resources: {} +resources: + #{} # We usually recommend not to specify default resources and to leave this as a conscious # choice for the user. This also increases chances charts run on environments with little # resources, such as Minikube. If you do want to specify resources, uncomment the following # lines, adjust them as necessary, and remove the curly braces after 'resources:'. - # limits: - # cpu: 100m - # memory: 128Mi - # requests: - # cpu: 100m - # memory: 128Mi + limits: + cpu: 100m + memory: 128Mi + requests: + cpu: 100m + memory: 128Mi autoscaling: enabled: false minReplicas: 1 maxReplicas: 100 targetCPUUtilizationPercentage: 80 - # targetMemoryUtilizationPercentage: 80 + targetMemoryUtilizationPercentage: 80 nodeSelector: {} @@ -88,11 +62,21 @@ affinity: {} # Controller-specific config -leaderElect: - enabled: true - podDisruptionBudget: + enabled: false + +selfSignedIssuer: enabled: true -prometheus: - enabled: false +configMapName: "aws-auth-test" +mustPresentAccountID: "123456789012" +crdCreationAllowedNS: "kube-system" +reconcileTime: "30m" + +controllerArguments: + #{} + - --zap-devel=true + - --zap-encoder=console + - --zap-log-level=info + - --zap-time-encoding=iso8601 + - --zap-stacktrace-level=panic From 4ba16f09432cabe7f287a912bd3c3749e4b95674 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Fri, 18 Jul 2025 17:20:37 +0300 Subject: [PATCH 47/58] chart edt --- .github/workflows/publish-release.yml | 42 +++++++++++++++++ Makefile | 15 ++++++ .../aws-auth-operator/VALUES-DESCRIPTION.md | 47 +++++++++++++++++++ .../{README.md => _README.md} | 6 +-- charts/aws-auth-operator/values.yaml | 10 +++- 5 files changed, 116 insertions(+), 4 deletions(-) create mode 100644 charts/aws-auth-operator/VALUES-DESCRIPTION.md rename charts/aws-auth-operator/{README.md => _README.md} (97%) diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 574d34a..41c77dc 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -63,3 +63,45 @@ jobs: push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} + +# release-chart: +# needs: verify-app +# runs-on: ubuntu-latest +# steps: +# - name: Checkout repository +# uses: actions/checkout@v3 +# with: +# fetch-depth: 0 +# +# - name: Configure git +# run: | +# git config user.name "$GITHUB_ACTOR" +# git config user.email "$GITHUB_ACTOR@users.noreply.github.com" +# +# - name: Release chart +# run: | +# # download helm chart releaser +# curl -sSLo cr.tar.gz "https://github.com/helm/chart-releaser/releases/download/v1.2.1/chart-releaser_1.2.1_linux_amd64.tar.gz" +# tar -xzf cr.tar.gz +# rm -f cr.tar.gz +# owner=$(cut -d '/' -f 1 <<< "$GITHUB_REPOSITORY") +# repo=$(cut -d '/' -f 2 <<< "$GITHUB_REPOSITORY") +# # package chart +# ./cr package charts/$repo +# # upload chart to github releases +# ./cr upload \ +# --owner "$owner" \ +# --git-repo "$repo" \ +# --token "${{ secrets.GITHUB_TOKEN }}" \ +# --release-name-template "{{ .Version }}" +# # update index and push to github pages +# git config user.email "$owner@users.noreply.github.com" +# git config user.name "$owner" +# ./cr index \ +# --owner "$owner" \ +# --git-repo "$repo" \ +# --token "${{ secrets.GITHUB_TOKEN }}" \ +# --release-name-template "{{ .Version }}" \ +# --index-path ./index.yaml \ +# --charts-repo https://$owner.github.io/$repo \ +# --push diff --git a/Makefile b/Makefile index 640e26c..58d33d5 100644 --- a/Makefile +++ b/Makefile @@ -9,6 +9,8 @@ else GOBIN=$(shell go env GOBIN) endif +CHART_PATH ?= ./charts/aws-auth-operator + # CONTAINER_TOOL defines the container tool to be used for building images. # Be aware that the target commands are only tested with Docker which is # scaffolded by default. However, you might want to replace it to use other @@ -23,6 +25,19 @@ SHELL = /usr/bin/env bash -o pipefail .PHONY: all all: build +##@Docs + +.PHONY: +install_helm-docs: ## Install helm-docs + wget https://github.com/norwoodj/helm-docs/releases/download/v1.14.2/helm-docs_1.14.2_Linux_x86_64.tar.gz + tar -zxvf helm-docs_1.14.2_Linux_x86_64.tar.gz helm-docs + sudo mv helm-docs ./bin/ + rm helm-docs_1.14.2_Linux_x86_64.tar.gz + +.PHONY: helm-docs-generate +helm-docs-generate: ## Generate Helm Chart Docs + helm-docs -c $(CHART_PATH) -o VALUES-DESCRIPTION.md + ##@ General # The help target prints out all targets with their descriptions organized diff --git a/charts/aws-auth-operator/VALUES-DESCRIPTION.md b/charts/aws-auth-operator/VALUES-DESCRIPTION.md new file mode 100644 index 0000000..b968f16 --- /dev/null +++ b/charts/aws-auth-operator/VALUES-DESCRIPTION.md @@ -0,0 +1,47 @@ +# aws-auth-operator + +![Version: 0.1.0](https://img.shields.io/badge/Version-0.1.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 0.1.0](https://img.shields.io/badge/AppVersion-0.1.0-informational?style=flat-square) + +Kubernetes operator to declaratively manage the EKS aws-auth configmap + +## Values + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| affinity | object | `{}` | | +| autoscaling.enabled | bool | `false` | | +| autoscaling.maxReplicas | int | `100` | | +| autoscaling.minReplicas | int | `1` | | +| autoscaling.targetCPUUtilizationPercentage | int | `80` | | +| autoscaling.targetMemoryUtilizationPercentage | int | `80` | | +| configMapName | string | `"aws-auth-test"` | | +| controllerArguments[0] | string | `"--zap-devel=true"` | | +| controllerArguments[1] | string | `"--zap-encoder=console"` | | +| controllerArguments[2] | string | `"--zap-log-level=info"` | | +| controllerArguments[3] | string | `"--zap-time-encoding=iso8601"` | | +| controllerArguments[4] | string | `"--zap-stacktrace-level=panic"` | | +| crdCreationAllowedNS | string | `"kube-system"` | | +| fullnameOverride | string | `""` | Override the `fullname` of the chart | +| image.pullPolicy | string | `"IfNotPresent"` | Image pull policy | +| image.repository | string | `"ghcr.io/redacid/aws-auth-controller"` | Image repository | +| image.tag | string | `"0.1.0"` | Image tag, will override the default tag derived from the chart app version | +| imagePullSecrets | list | `[]` | Image pull secrets | +| mustPresentAccountID | string | `"123456789012"` | | +| nameOverride | string | `""` | Override the `name` of the chart | +| nodeSelector | object | `{}` | | +| podAnnotations | object | `{}` | Annotations to add to the pod | +| podDisruptionBudget.enabled | bool | `false` | | +| podSecurityContext.runAsNonRoot | bool | `true` | | +| podSecurityContext.seccompProfile.type | string | `"RuntimeDefault"` | | +| reconcileTime | string | `"30m"` | | +| replicaCount | int | `2` | Controller Pod replica count | +| resources.limits.cpu | string | `"100m"` | | +| resources.limits.memory | string | `"128Mi"` | | +| resources.requests.cpu | string | `"100m"` | | +| resources.requests.memory | string | `"128Mi"` | | +| securityContext | object | `{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}` | Security context for the manager container | +| selfSignedIssuer.enabled | bool | `true` | | +| tolerations | list | `[]` | | + +---------------------------------------------- +Autogenerated from chart metadata using [helm-docs v1.14.2](https://github.com/norwoodj/helm-docs/releases/v1.14.2) diff --git a/charts/aws-auth-operator/README.md b/charts/aws-auth-operator/_README.md similarity index 97% rename from charts/aws-auth-operator/README.md rename to charts/aws-auth-operator/_README.md index 2f937c6..3acb98b 100644 --- a/charts/aws-auth-operator/README.md +++ b/charts/aws-auth-operator/_README.md @@ -1,6 +1,6 @@ # Kubernetes aws-auth-operator -[aws-auth-operator](https://github.com/sambatv/aws-auth-operator/) is an operator to declaratively manage the EKS aws-auth configmap. +[aws-auth-operator](https://github.com/redacid/aws-auth-controller/) is an operator to declaratively manage the EKS aws-auth configmap. ## Installing the Chart @@ -8,7 +8,7 @@ Before you can install the chart you will need to add the `aws-auth-operator` repo to [Helm](https://helm.sh/). ```shell -helm repo add aws-auth-operator-charts https://sambatv.github.io/aws-auth-operator/ +helm repo add aws-auth-operator-charts https://redacid.github.io/aws-auth-controller/ ``` After you've installed the repo you can install the chart. @@ -19,7 +19,7 @@ helm upgrade --install aws-auth-operator aws-auth-operator-charts/aws-auth-opera ## Configuration -The following table lists the configurable parameters of the `sambatv/aws-auth-operator` +The following table lists the configurable parameters of the `redacid/aws-auth-operator` chart and their default values. | Parameter | Description | Default | diff --git a/charts/aws-auth-operator/values.yaml b/charts/aws-auth-operator/values.yaml index 9ef3f36..53e2397 100644 --- a/charts/aws-auth-operator/values.yaml +++ b/charts/aws-auth-operator/values.yaml @@ -2,19 +2,27 @@ # This is a YAML-formatted file. # Declare variables to be passed into your templates. +# -- Controller Pod replica count replicaCount: 2 image: + # -- Image repository repository: ghcr.io/redacid/aws-auth-controller + # -- Image pull policy pullPolicy: IfNotPresent + # -- Image tag, will override the default tag derived from the chart app version tag: "0.1.0" +# -- Image pull secrets imagePullSecrets: [] +# -- Override the `name` of the chart nameOverride: "" +# -- Override the `fullname` of the chart fullnameOverride: "" +# -- Annotations to add to the pod podAnnotations: {} - +# -- Security context for the manager container securityContext: allowPrivilegeEscalation: false capabilities: From 1fc041c245030dbc350aa6c373bc846f00cfba8e Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 21 Jul 2025 10:47:36 +0300 Subject: [PATCH 48/58] chart edt --- Makefile | 2 +- charts/Makefile | 93 +++++++++++++++ charts/aws-auth-operator/README.md | 34 ++++++ .../aws-auth-operator/VALUES-DESCRIPTION.md | 47 -------- charts/aws-auth-operator/_README.md | 61 ---------- charts/aws-auth-operator/values.yaml | 104 +++++++++-------- charts/values.yaml | 108 ++++++++++++++++++ config/manager/manager.yaml | 2 +- 8 files changed, 296 insertions(+), 155 deletions(-) create mode 100644 charts/Makefile create mode 100644 charts/aws-auth-operator/README.md delete mode 100644 charts/aws-auth-operator/VALUES-DESCRIPTION.md delete mode 100644 charts/aws-auth-operator/_README.md create mode 100644 charts/values.yaml diff --git a/Makefile b/Makefile index 58d33d5..52116c3 100644 --- a/Makefile +++ b/Makefile @@ -36,7 +36,7 @@ install_helm-docs: ## Install helm-docs .PHONY: helm-docs-generate helm-docs-generate: ## Generate Helm Chart Docs - helm-docs -c $(CHART_PATH) -o VALUES-DESCRIPTION.md + helm-docs -c $(CHART_PATH) -o README.md ##@ General diff --git a/charts/Makefile b/charts/Makefile new file mode 100644 index 0000000..f8e4776 --- /dev/null +++ b/charts/Makefile @@ -0,0 +1,93 @@ +-include .env +GIT_STAMP ?= $(shell git describe || echo v0.1.0) + +KUBEVAL_SCHEMA_LOCATION ?= https://raw.githubusercontent.com/redacid/k8s-json-scheme/refs/heads/main +KUBECONFORM_SCHEMA ?= --schema-location 'https://raw.githubusercontent.com/redacid/k8s-json-scheme/refs/heads/main/{{.NormalizedKubernetesVersion}}-standalone{{.StrictSuffix}}/{{.ResourceKind}}{{.KindSuffix}}.json' +CHART_PATH ?= ./aws-auth-operator + +ENV_NAME ?= TEST + +TEST_VALUES ?= -f ./values.yaml +TEST_NAMESPACE ?= aws-auth-ns +TEST_RELEASE_NAME ?= auth-test +TEST_KUBERNETES_VERSION ?= 1.32.2 + +# colors +GREEN = $(shell tput -Txterm setaf 2) +YELLOW = $(shell tput -Txterm setaf 3) +WHITE = $(shell tput -Txterm setaf 7) +RESET = $(shell tput -Txterm sgr0) +GRAY = $(shell tput -Txterm setaf 6) +TARGET_MAX_CHAR_NUM = 30 + +.EXPORT_ALL_VARIABLES: + +all: help + +## Check helm | Linters +helm-lint: helm-dependency-update + @$(foreach var,$(ENV_NAME), echo "\n\n======= Check $(var) =======\n\n" \ + && helm lint --namespace=$($(var)_NAMESPACE) $(CHART_PATH) $($(var)_VALUES) || exit;) + +## Check helm-kubeval +helm-kubeval: helm-dependency-update + @$(foreach var,$(ENV_NAME), echo "\n\n======= Check $(var) on kubernetes-version $($(var)_KUBERNETES_VERSION) =======\n\n" \ + && helm kubeval --exit-on-error --kubernetes-version $($(var)_KUBERNETES_VERSION) \ + --strict --name-template=$($(var)_RELEASE_NAME) --namespace=$($(var)_NAMESPACE) $($(var)_VALUES) \ + $(CHART_PATH) || exit;) + +## Check Kubeconform +helm-kubeconform: helm-dependency-update install-kubeconform-plugin + @$(foreach var,$(ENV_NAME), echo "\n\n======= Check $(var) on kubernetes-version $($(var)_KUBERNETES_VERSION) =======\n\n" \ + && helm kubeconform --output pretty --goroutines $(shell nproc) --exit-on-error $(KUBECONFORM_SCHEMA) \ + --kube-version $($(var)_KUBERNETES_VERSION) \ + --strict --summary --name-template=$($(var)_RELEASE_NAME) --namespace=$($(var)_NAMESPACE) $($(var)_VALUES) $(CHART_PATH) || exit;) + +## Deploy TEST +deploy-test: helm-dependency-update helm-package + @helm upgrade -i --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) ./aws-auth-operator-$(GIT_STAMP).tgz $(TEST_VALUES) + +## Deploy TEST +template-test: helm-dependency-update + @helm template --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) $(CHART_PATH) $(TEST_VALUES) + +## Dependency update helm | Tools +helm-dependency-update: + @helm dependency update $(CHART_PATH) + @helm dependency list $(CHART_PATH) + @ls -l $(CHART_PATH) + +## Build helm package +helm-package: + @helm package --app-version=$(GIT_STAMP) --version=$(GIT_STAMP) $(CHART_PATH) + +## Install kubeconform helm plugin +install-kubeconform-plugin: + @helm plugin list | grep -q kubeconform || helm plugin install https://github.com/redacid/helm-kubeconform --version 0.6.8.1 + + +## Shows help. | Help +help: + @echo '' + @echo 'Usage:' + @echo '' + @echo ' ${YELLOW}make${RESET} ${GREEN}${RESET}' + @echo '' + @echo 'Targets:' + @awk '/^[a-zA-Z0-9\-_]+:/ { \ + helpMessage = match(lastLine, /^## (.*)/); \ + if (helpMessage) { \ + if (index(lastLine, "|") != 0) { \ + stage = substr(lastLine, index(lastLine, "|") + 1); \ + printf "\n ${GRAY}%s: \n\n", stage; \ + } \ + helpCommand = substr($$1, 0, index($$1, ":")-1); \ + helpMessage = substr(lastLine, RSTART + 3, RLENGTH); \ + if (index(lastLine, "|") != 0) { \ + helpMessage = substr(helpMessage, 0, index(helpMessage, "|")-1); \ + } \ + printf " ${YELLOW}%-$(TARGET_MAX_CHAR_NUM)s${RESET} ${GREEN}%s${RESET}\n", helpCommand, helpMessage; \ + } \ + } \ + { lastLine = $$0 }' $(MAKEFILE_LIST) + @echo '' diff --git a/charts/aws-auth-operator/README.md b/charts/aws-auth-operator/README.md new file mode 100644 index 0000000..911720a --- /dev/null +++ b/charts/aws-auth-operator/README.md @@ -0,0 +1,34 @@ +# aws-auth-operator + +![Version: 0.1.0](https://img.shields.io/badge/Version-0.1.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 0.1.0](https://img.shields.io/badge/AppVersion-0.1.0-informational?style=flat-square) + +Kubernetes operator to declaratively manage the EKS aws-auth configmap + +## Values + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| affinity | object | `{}` | Affinity for pod assignment | +| configMapName | string | `"aws-auth-test"` | ConfigMap for MapAccount, MapUser, MapRoles in kube-system ns, aws-auth bu default | +| controllerArguments | list | `["--zap-devel=true","--zap-encoder=console","--zap-log-level=info","--zap-time-encoding=iso8601","--zap-stacktrace-level=panic"]` | Other commandline controller arguments | +| crdCreationAllowedNS | string | `"kube-system"` | Allow creating crds only on this ns, if blank allowing in any ns | +| fullnameOverride | string | `""` | Override the `fullname` of the chart | +| image.pullPolicy | string | `"IfNotPresent"` | Image pull policy | +| image.repository | string | `"ghcr.io/redacid/aws-auth-controller"` | Image repository | +| image.tag | string | `"0.1.0"` | Image tag, will override the default tag derived from the chart app version | +| imagePullSecrets | list | `[]` | Image pull secrets | +| mustPresentAccountID | string | `"123456789012"` | This account id must allways present in cm, and disallow to delete crd MapAccount with this id | +| nameOverride | string | `""` | Override the `name` of the chart | +| nodeSelector | object | `{}` | Node labels for pod assignment | +| podAnnotations | object | `{}` | Annotations to add to the pod | +| podDisruptionBudget | object | `{"enabled":false}` | If true, create PodDisruptionBudget resource | +| podSecurityContext | object | `{"runAsNonRoot":true,"seccompProfile":{"type":"RuntimeDefault"}}` | Security context for the pod | +| reconcileTime | string | `"30m"` | Reconcile time in controller, recheck all crds, and recreate cm records if needed | +| replicaCount | int | `2` | Controller Pod replica count | +| resources | object | `{"limits":{"cpu":"100m","memory":"128Mi"},"requests":{"cpu":"100m","memory":"128Mi"}}` | Resource requests and limits for the manager container | +| securityContext | object | `{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}` | Security context for the manager container | +| selfSignedIssuer | object | `{"enabled":true}` | Enable cert-manager issuer and create self-signed certs | +| tolerations | list | `[]` | Tolerations for pod assignment | + +---------------------------------------------- +Autogenerated from chart metadata using [helm-docs v1.14.2](https://github.com/norwoodj/helm-docs/releases/v1.14.2) diff --git a/charts/aws-auth-operator/VALUES-DESCRIPTION.md b/charts/aws-auth-operator/VALUES-DESCRIPTION.md deleted file mode 100644 index b968f16..0000000 --- a/charts/aws-auth-operator/VALUES-DESCRIPTION.md +++ /dev/null @@ -1,47 +0,0 @@ -# aws-auth-operator - -![Version: 0.1.0](https://img.shields.io/badge/Version-0.1.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 0.1.0](https://img.shields.io/badge/AppVersion-0.1.0-informational?style=flat-square) - -Kubernetes operator to declaratively manage the EKS aws-auth configmap - -## Values - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| affinity | object | `{}` | | -| autoscaling.enabled | bool | `false` | | -| autoscaling.maxReplicas | int | `100` | | -| autoscaling.minReplicas | int | `1` | | -| autoscaling.targetCPUUtilizationPercentage | int | `80` | | -| autoscaling.targetMemoryUtilizationPercentage | int | `80` | | -| configMapName | string | `"aws-auth-test"` | | -| controllerArguments[0] | string | `"--zap-devel=true"` | | -| controllerArguments[1] | string | `"--zap-encoder=console"` | | -| controllerArguments[2] | string | `"--zap-log-level=info"` | | -| controllerArguments[3] | string | `"--zap-time-encoding=iso8601"` | | -| controllerArguments[4] | string | `"--zap-stacktrace-level=panic"` | | -| crdCreationAllowedNS | string | `"kube-system"` | | -| fullnameOverride | string | `""` | Override the `fullname` of the chart | -| image.pullPolicy | string | `"IfNotPresent"` | Image pull policy | -| image.repository | string | `"ghcr.io/redacid/aws-auth-controller"` | Image repository | -| image.tag | string | `"0.1.0"` | Image tag, will override the default tag derived from the chart app version | -| imagePullSecrets | list | `[]` | Image pull secrets | -| mustPresentAccountID | string | `"123456789012"` | | -| nameOverride | string | `""` | Override the `name` of the chart | -| nodeSelector | object | `{}` | | -| podAnnotations | object | `{}` | Annotations to add to the pod | -| podDisruptionBudget.enabled | bool | `false` | | -| podSecurityContext.runAsNonRoot | bool | `true` | | -| podSecurityContext.seccompProfile.type | string | `"RuntimeDefault"` | | -| reconcileTime | string | `"30m"` | | -| replicaCount | int | `2` | Controller Pod replica count | -| resources.limits.cpu | string | `"100m"` | | -| resources.limits.memory | string | `"128Mi"` | | -| resources.requests.cpu | string | `"100m"` | | -| resources.requests.memory | string | `"128Mi"` | | -| securityContext | object | `{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}` | Security context for the manager container | -| selfSignedIssuer.enabled | bool | `true` | | -| tolerations | list | `[]` | | - ----------------------------------------------- -Autogenerated from chart metadata using [helm-docs v1.14.2](https://github.com/norwoodj/helm-docs/releases/v1.14.2) diff --git a/charts/aws-auth-operator/_README.md b/charts/aws-auth-operator/_README.md deleted file mode 100644 index 3acb98b..0000000 --- a/charts/aws-auth-operator/_README.md +++ /dev/null @@ -1,61 +0,0 @@ -# Kubernetes aws-auth-operator - -[aws-auth-operator](https://github.com/redacid/aws-auth-controller/) is an operator to declaratively manage the EKS aws-auth configmap. - -## Installing the Chart - -Before you can install the chart you will need to add the `aws-auth-operator` -repo to [Helm](https://helm.sh/). - -```shell -helm repo add aws-auth-operator-charts https://redacid.github.io/aws-auth-controller/ -``` - -After you've installed the repo you can install the chart. - -```shell -helm upgrade --install aws-auth-operator aws-auth-operator-charts/aws-auth-operator --namespace aws-auth-operator --create-namespace -``` - -## Configuration - -The following table lists the configurable parameters of the `redacid/aws-auth-operator` -chart and their default values. - -| Parameter | Description | Default | -|--------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------| -| `image.repository` | Image repository. | `sambatv/aws-auth-operator` | -| `image.tag` | Image tag, will override the default tag derived from the chart app version. | `""` | -| `image.pullPolicy` | Image pull policy. | `IfNotPresent` | -| `imagePullSecrets` | Image pull secrets. | `[]` | -| `nameOverride` | Override the `name` of the chart. | `nil` | -| `fullnameOverride` | Override the `fullname` of the chart. | `nil` | -| `serviceAccount.create` | If `true`, create a new service account. | `true` | -| `serviceAccount.annotations` | Annotations to add to the service account. | `{}` | -| `serviceAccount.name` | Service account to be used. If not set and `serviceAccount.create` is `true`, a name is generated using the full name template. | `nil` | -| `rbac.create` | If `true`, create the RBAC resources. | `true` | -| `rbac.pspEnabled` | If `true`, create a pod security policy resource. | `false` | -| `apiService.create` | If `true`, create the `v1beta1.metrics.k8s.io` API service. You typically want this enabled! If you disable API service creation you have to manage it outside of this chart for e.g horizontal pod autoscaling to work with this release. | `true` | -| `podLabels` | Labels to add to the pod. | `{}` | -| `podAnnotations` | Annotations to add to the pod. | `{}` | -| `podSecurityContext` | Security context for the pod. | `{}` | -| `securityContext` | Security context for the _metrics-server_ container. | _See values.yaml_ | -| `priorityClassName` | Priority class name to use. | `system-cluster-critical` | -| `containerPort` | port for the _metrics-server_ container. | `10250` | -| `hostNetwork.enabled` | If `true`, start _metric-server_ in hostNetwork mode. You would require this enabled if you use alternate overlay networking for pods and API server unable to communicate with metrics-server. As an example, this is required if you use Weave network on EKS. | `false` | -| `replicas` | Number of replicas to run. | `1` | -| `updateStrategy` | Customise the default update strategy. | `{}` | -| `podDisruptionBudget.enabled` | If `true`, create `PodDisruptionBudget` resource. | `{}` | -| `podDisruptionBudget.minAvailable` | Set the `PodDisruptionBugdet` minimum available pods. | `nil` | -| `podDisruptionBudget.maxUnavailable` | Set the `PodDisruptionBugdet` maximum unavailable pods. | `nil` | -| `livenessProbe` | Liveness probe. | See _values.yaml_ | -| `readinessProbe` | Readiness probe. | See _values.yaml_ | -| `leaderElect.enabled` | If `true`, enable leader election for highly available installation. | `false` | -| `prometheus.enabled` | If `true`, enable unauthenticated access to Prometheus `/metrics` endpoint. | `false` | -| `resources` | Resource requests and limits for the _metrics-server_ container. See https://github.com/kubernetes-sigs/metrics-server#scaling | `{}` | -| `extraVolumeMounts` | Additional volume mounts for the _metrics-server_ container. | `[]` | -| `extraVolumes` | Additional volumes for the pod. | `[]` | -| `nodeSelector` | Node labels for pod assignment. | `{}` | -| `tolerations` | Tolerations for pod assignment. | `[]` | -| `affinity` | Affinity for pod assignment. | `{}` | -| `topologySpreadConstraints` | Pod Topology Spread Constraints. | `[]` | diff --git a/charts/aws-auth-operator/values.yaml b/charts/aws-auth-operator/values.yaml index 53e2397..9c6d21c 100644 --- a/charts/aws-auth-operator/values.yaml +++ b/charts/aws-auth-operator/values.yaml @@ -3,7 +3,7 @@ # Declare variables to be passed into your templates. # -- Controller Pod replica count -replicaCount: 2 +replicaCount: 1 image: # -- Image repository @@ -23,66 +23,80 @@ fullnameOverride: "" # -- Annotations to add to the pod podAnnotations: {} # -- Security context for the manager container -securityContext: - allowPrivilegeEscalation: false - capabilities: - drop: - - ALL - # capabilities: - # drop: - # - ALL - # readOnlyRootFilesystem: true - # runAsNonRoot: true - # runAsUser: 1000 - -podSecurityContext: - #{} - runAsNonRoot: true - seccompProfile: - type: RuntimeDefault - - -resources: - #{} - # We usually recommend not to specify default resources and to leave this as a conscious - # choice for the user. This also increases chances charts run on environments with little - # resources, such as Minikube. If you do want to specify resources, uncomment the following - # lines, adjust them as necessary, and remove the curly braces after 'resources:'. - limits: - cpu: 100m - memory: 128Mi - requests: - cpu: 100m - memory: 128Mi - -autoscaling: - enabled: false - minReplicas: 1 - maxReplicas: 100 - targetCPUUtilizationPercentage: 80 - targetMemoryUtilizationPercentage: 80 - +securityContext: {} +# allowPrivilegeEscalation: false +# capabilities: +# drop: +# - ALL +# readOnlyRootFilesystem: true +# runAsNonRoot: true +# runAsUser: 1000 + +# -- Security context for the pod +podSecurityContext: {} + # Projects are configured by default to adhere to the "restricted" Pod Security Standards. + # This ensures that deployments meet the highest security requirements for Kubernetes. + # For more details, see: https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted +# runAsNonRoot: true +# seccompProfile: +# type: RuntimeDefault + +# -- Resource requests and limits for the manager container +resources: {} +# limits: +# cpu: 100m +# memory: 128Mi +# requests: +# cpu: 100m +# memory: 128Mi + +# -- Node labels for pod assignment nodeSelector: {} +# -- Tolerations for pod assignment tolerations: [] +# -- Affinity for pod assignment affinity: {} +# nodeAffinity: +# requiredDuringSchedulingIgnoredDuringExecution: +# nodeSelectorTerms: +# - matchExpressions: +# - key: kubernetes.io/arch +# operator: In +# values: +# - amd64 +# - arm64 +# - ppc64le +# - s390x +# - key: kubernetes.io/os +# operator: In +# values: +# - linux -# Controller-specific config +# Controller-specific config +# -- If true, create PodDisruptionBudget resource podDisruptionBudget: enabled: false +# -- Enable cert-manager issuer and create self-signed certs selfSignedIssuer: enabled: true +# -- ConfigMap for MapAccount, MapUser, MapRoles in kube-system ns, aws-auth bu default configMapName: "aws-auth-test" -mustPresentAccountID: "123456789012" -crdCreationAllowedNS: "kube-system" -reconcileTime: "30m" +# -- This account id must allways present in cm, and disallow to delete crd MapAccount with this id +mustPresentAccountID: "" + +# -- Allow creating crds only on this ns, if blank allowing in any ns +crdCreationAllowedNS: "" + +# -- Reconcile time in controller, recheck all crds, and recreate cm records if needed +reconcileTime: "120m" +# -- Other commandline controller arguments controllerArguments: - #{} - --zap-devel=true - --zap-encoder=console - --zap-log-level=info diff --git a/charts/values.yaml b/charts/values.yaml new file mode 100644 index 0000000..f3e23d6 --- /dev/null +++ b/charts/values.yaml @@ -0,0 +1,108 @@ +# Default values for aws-auth-operator. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +# -- Controller Pod replica count +replicaCount: 2 + +image: + # -- Image repository + repository: ghcr.io/redacid/aws-auth-controller + # -- Image pull policy + pullPolicy: IfNotPresent + # -- Image tag, will override the default tag derived from the chart app version + tag: "0.1.0" + +# -- Image pull secrets +imagePullSecrets: [] +# -- Override the `name` of the chart +nameOverride: "" +# -- Override the `fullname` of the chart +fullnameOverride: "" + +# -- Annotations to add to the pod +podAnnotations: {} +# -- Security context for the manager container +securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + # capabilities: + # drop: + # - ALL + # readOnlyRootFilesystem: true + # runAsNonRoot: true + # runAsUser: 1000 + +# -- Security context for the pod +podSecurityContext: + #{} + # Projects are configured by default to adhere to the "restricted" Pod Security Standards. + # This ensures that deployments meet the highest security requirements for Kubernetes. + # For more details, see: https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + +# -- Resource requests and limits for the manager container +resources: + limits: + cpu: 100m + memory: 128Mi + requests: + cpu: 100m + memory: 128Mi + +# -- Node labels for pod assignment +nodeSelector: {} + +# -- Tolerations for pod assignment +tolerations: [] + +# -- Affinity for pod assignment +affinity: {} +# nodeAffinity: +# requiredDuringSchedulingIgnoredDuringExecution: +# nodeSelectorTerms: +# - matchExpressions: +# - key: kubernetes.io/arch +# operator: In +# values: +# - amd64 +# - arm64 +# - ppc64le +# - s390x +# - key: kubernetes.io/os +# operator: In +# values: +# - linux + + +# Controller-specific config +# -- If true, create PodDisruptionBudget resource +podDisruptionBudget: + enabled: false + +# -- Enable cert-manager issuer and create self-signed certs +selfSignedIssuer: + enabled: true + +# -- ConfigMap for MapAccount, MapUser, MapRoles in kube-system ns, aws-auth bu default +configMapName: "aws-auth-test" +# -- This account id must allways present in cm, and disallow to delete crd MapAccount with this id +mustPresentAccountID: "123456789012" + +# -- Allow creating crds only on this ns, if blank allowing in any ns +crdCreationAllowedNS: "kube-system" + +# -- Reconcile time in controller, recheck all crds, and recreate cm records if needed +reconcileTime: "30m" + +# -- Other commandline controller arguments +controllerArguments: + - --zap-devel=true + - --zap-encoder=console + - --zap-log-level=info + - --zap-time-encoding=iso8601 + - --zap-stacktrace-level=panic diff --git a/config/manager/manager.yaml b/config/manager/manager.yaml index 10bc3a1..9a03646 100644 --- a/config/manager/manager.yaml +++ b/config/manager/manager.yaml @@ -21,7 +21,7 @@ spec: matchLabels: control-plane: controller-manager app.kubernetes.io/name: aws-auth-controller-prozorro - replicas: 2 + replicas: 1 template: metadata: annotations: From 11ac7ca7a37fb3396f10a99ca93c1031c68a67de Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 21 Jul 2025 10:55:16 +0300 Subject: [PATCH 49/58] chart edt --- README.md | 4 +++- charts/aws-auth-operator/README.md | 16 ++++++++-------- charts/aws-auth-operator/values.yaml | 2 +- charts/values.yaml | 13 +++---------- 4 files changed, 15 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index ca84fcd..edbb77e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # aws-auth-controller [![codecov](https://codecov.io/github/redacid/aws-auth-controller/graph/badge.svg?token=3B6KI6EJCR)](https://codecov.io/github/redacid/aws-auth-controller) [![unit-test](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml/badge.svg?branch=init)](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml) -[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/redacid/aws-auth-controller/blob/init/LICENSE) \ No newline at end of file +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/redacid/aws-auth-controller/blob/init/LICENSE) + +[Helm chart README.md](charts/aws-auth-operator/README.md) \ No newline at end of file diff --git a/charts/aws-auth-operator/README.md b/charts/aws-auth-operator/README.md index 911720a..7434843 100644 --- a/charts/aws-auth-operator/README.md +++ b/charts/aws-auth-operator/README.md @@ -9,24 +9,24 @@ Kubernetes operator to declaratively manage the EKS aws-auth configmap | Key | Type | Default | Description | |-----|------|---------|-------------| | affinity | object | `{}` | Affinity for pod assignment | -| configMapName | string | `"aws-auth-test"` | ConfigMap for MapAccount, MapUser, MapRoles in kube-system ns, aws-auth bu default | +| configMapName | string | `"aws-auth"` | ConfigMap for MapAccount, MapUser, MapRoles in kube-system ns, aws-auth bu default | | controllerArguments | list | `["--zap-devel=true","--zap-encoder=console","--zap-log-level=info","--zap-time-encoding=iso8601","--zap-stacktrace-level=panic"]` | Other commandline controller arguments | -| crdCreationAllowedNS | string | `"kube-system"` | Allow creating crds only on this ns, if blank allowing in any ns | +| crdCreationAllowedNS | string | `""` | Allow creating crds only on this ns, if blank allowing in any ns | | fullnameOverride | string | `""` | Override the `fullname` of the chart | | image.pullPolicy | string | `"IfNotPresent"` | Image pull policy | | image.repository | string | `"ghcr.io/redacid/aws-auth-controller"` | Image repository | | image.tag | string | `"0.1.0"` | Image tag, will override the default tag derived from the chart app version | | imagePullSecrets | list | `[]` | Image pull secrets | -| mustPresentAccountID | string | `"123456789012"` | This account id must allways present in cm, and disallow to delete crd MapAccount with this id | +| mustPresentAccountID | string | `""` | This account id must allways present in cm, and disallow to delete crd MapAccount with this id | | nameOverride | string | `""` | Override the `name` of the chart | | nodeSelector | object | `{}` | Node labels for pod assignment | | podAnnotations | object | `{}` | Annotations to add to the pod | | podDisruptionBudget | object | `{"enabled":false}` | If true, create PodDisruptionBudget resource | -| podSecurityContext | object | `{"runAsNonRoot":true,"seccompProfile":{"type":"RuntimeDefault"}}` | Security context for the pod | -| reconcileTime | string | `"30m"` | Reconcile time in controller, recheck all crds, and recreate cm records if needed | -| replicaCount | int | `2` | Controller Pod replica count | -| resources | object | `{"limits":{"cpu":"100m","memory":"128Mi"},"requests":{"cpu":"100m","memory":"128Mi"}}` | Resource requests and limits for the manager container | -| securityContext | object | `{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}` | Security context for the manager container | +| podSecurityContext | object | `{}` | Security context for the pod | +| reconcileTime | string | `"120m"` | Reconcile time in controller, recheck all crds, and recreate cm records if needed | +| replicaCount | int | `1` | Controller Pod replica count | +| resources | object | `{}` | Resource requests and limits for the manager container | +| securityContext | object | `{}` | Security context for the manager container | | selfSignedIssuer | object | `{"enabled":true}` | Enable cert-manager issuer and create self-signed certs | | tolerations | list | `[]` | Tolerations for pod assignment | diff --git a/charts/aws-auth-operator/values.yaml b/charts/aws-auth-operator/values.yaml index 9c6d21c..e514d24 100644 --- a/charts/aws-auth-operator/values.yaml +++ b/charts/aws-auth-operator/values.yaml @@ -85,7 +85,7 @@ selfSignedIssuer: enabled: true # -- ConfigMap for MapAccount, MapUser, MapRoles in kube-system ns, aws-auth bu default -configMapName: "aws-auth-test" +configMapName: "aws-auth" # -- This account id must allways present in cm, and disallow to delete crd MapAccount with this id mustPresentAccountID: "" diff --git a/charts/values.yaml b/charts/values.yaml index f3e23d6..b46f7f5 100644 --- a/charts/values.yaml +++ b/charts/values.yaml @@ -28,19 +28,12 @@ securityContext: capabilities: drop: - ALL - # capabilities: - # drop: - # - ALL - # readOnlyRootFilesystem: true - # runAsNonRoot: true - # runAsUser: 1000 +# readOnlyRootFilesystem: true +# runAsNonRoot: true +# runAsUser: 1000 # -- Security context for the pod podSecurityContext: - #{} - # Projects are configured by default to adhere to the "restricted" Pod Security Standards. - # This ensures that deployments meet the highest security requirements for Kubernetes. - # For more details, see: https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted runAsNonRoot: true seccompProfile: type: RuntimeDefault From 2adbd8ea516e7b0ffa25e520ac915e8bdc042714 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 21 Jul 2025 11:29:39 +0300 Subject: [PATCH 50/58] chart edt --- .gitignore | 3 +++ Makefile | 13 ------------- charts/Makefile | 16 +++++++++++++++- charts/aws-auth-operator/README.md | 1 - .../templates/certificate-serving.yaml | 2 -- charts/aws-auth-operator/templates/issuer.yaml | 2 -- .../templates/webhook-validation.yaml | 2 -- charts/aws-auth-operator/values.yaml | 4 ---- charts/values.yaml | 4 ---- 9 files changed, 18 insertions(+), 29 deletions(-) diff --git a/.gitignore b/.gitignore index bb937e4..f6ad33a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,9 @@ *.exe~ *.dll *.so + +*.tgz + *.dylib bin/* Dockerfile.cross diff --git a/Makefile b/Makefile index 52116c3..9e6d32a 100644 --- a/Makefile +++ b/Makefile @@ -25,19 +25,6 @@ SHELL = /usr/bin/env bash -o pipefail .PHONY: all all: build -##@Docs - -.PHONY: -install_helm-docs: ## Install helm-docs - wget https://github.com/norwoodj/helm-docs/releases/download/v1.14.2/helm-docs_1.14.2_Linux_x86_64.tar.gz - tar -zxvf helm-docs_1.14.2_Linux_x86_64.tar.gz helm-docs - sudo mv helm-docs ./bin/ - rm helm-docs_1.14.2_Linux_x86_64.tar.gz - -.PHONY: helm-docs-generate -helm-docs-generate: ## Generate Helm Chart Docs - helm-docs -c $(CHART_PATH) -o README.md - ##@ General # The help target prints out all targets with their descriptions organized diff --git a/charts/Makefile b/charts/Makefile index f8e4776..fe88781 100644 --- a/charts/Makefile +++ b/charts/Makefile @@ -4,6 +4,7 @@ GIT_STAMP ?= $(shell git describe || echo v0.1.0) KUBEVAL_SCHEMA_LOCATION ?= https://raw.githubusercontent.com/redacid/k8s-json-scheme/refs/heads/main KUBECONFORM_SCHEMA ?= --schema-location 'https://raw.githubusercontent.com/redacid/k8s-json-scheme/refs/heads/main/{{.NormalizedKubernetesVersion}}-standalone{{.StrictSuffix}}/{{.ResourceKind}}{{.KindSuffix}}.json' CHART_PATH ?= ./aws-auth-operator +CREATE_NAMESPACE ?= --create-namespace ENV_NAME ?= TEST @@ -24,6 +25,19 @@ TARGET_MAX_CHAR_NUM = 30 all: help +## Install helm-docs | Docs +.PHONY: install_helm-docs +install_helm-docs: + wget https://github.com/norwoodj/helm-docs/releases/download/v1.14.2/helm-docs_1.14.2_Linux_x86_64.tar.gz + tar -zxvf helm-docs_1.14.2_Linux_x86_64.tar.gz helm-docs + sudo mv helm-docs ./bin/ + rm helm-docs_1.14.2_Linux_x86_64.tar.gz + +## Generate Helm Chart Docs +.PHONY: helm-docs-generate +helm-docs-generate: + helm-docs -c $(CHART_PATH) -o README.md + ## Check helm | Linters helm-lint: helm-dependency-update @$(foreach var,$(ENV_NAME), echo "\n\n======= Check $(var) =======\n\n" \ @@ -45,7 +59,7 @@ helm-kubeconform: helm-dependency-update install-kubeconform-plugin ## Deploy TEST deploy-test: helm-dependency-update helm-package - @helm upgrade -i --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) ./aws-auth-operator-$(GIT_STAMP).tgz $(TEST_VALUES) + @helm upgrade -i --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) ./aws-auth-operator-$(GIT_STAMP).tgz $(TEST_VALUES) $(CREATE_NAMESPACE) ## Deploy TEST template-test: helm-dependency-update diff --git a/charts/aws-auth-operator/README.md b/charts/aws-auth-operator/README.md index 7434843..3df1401 100644 --- a/charts/aws-auth-operator/README.md +++ b/charts/aws-auth-operator/README.md @@ -27,7 +27,6 @@ Kubernetes operator to declaratively manage the EKS aws-auth configmap | replicaCount | int | `1` | Controller Pod replica count | | resources | object | `{}` | Resource requests and limits for the manager container | | securityContext | object | `{}` | Security context for the manager container | -| selfSignedIssuer | object | `{"enabled":true}` | Enable cert-manager issuer and create self-signed certs | | tolerations | list | `[]` | Tolerations for pod assignment | ---------------------------------------------- diff --git a/charts/aws-auth-operator/templates/certificate-serving.yaml b/charts/aws-auth-operator/templates/certificate-serving.yaml index c69210e..fec67d7 100644 --- a/charts/aws-auth-operator/templates/certificate-serving.yaml +++ b/charts/aws-auth-operator/templates/certificate-serving.yaml @@ -1,4 +1,3 @@ -{{- if .Values.selfSignedIssuer.enabled -}} apiVersion: cert-manager.io/v1 kind: Certificate metadata: @@ -14,4 +13,3 @@ spec: kind: Issuer name: {{ include "aws-auth-operator.fullname" . }}-selfsigned-issuer secretName: {{ include "aws-auth-operator.fullname" . }}-webhook-server-cert -{{- end }} \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/issuer.yaml b/charts/aws-auth-operator/templates/issuer.yaml index 347ae7d..46cfb6a 100644 --- a/charts/aws-auth-operator/templates/issuer.yaml +++ b/charts/aws-auth-operator/templates/issuer.yaml @@ -1,4 +1,3 @@ -{{- if .Values.selfSignedIssuer.enabled -}} apiVersion: cert-manager.io/v1 kind: Issuer metadata: @@ -8,4 +7,3 @@ metadata: namespace: {{ .Release.Namespace }} spec: selfSigned: {} -{{- end }} \ No newline at end of file diff --git a/charts/aws-auth-operator/templates/webhook-validation.yaml b/charts/aws-auth-operator/templates/webhook-validation.yaml index 0195f7d..639bd51 100644 --- a/charts/aws-auth-operator/templates/webhook-validation.yaml +++ b/charts/aws-auth-operator/templates/webhook-validation.yaml @@ -2,9 +2,7 @@ apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingWebhookConfiguration metadata: annotations: - {{- if .Values.selfSignedIssuer.enabled }} cert-manager.io/inject-ca-from: {{ .Release.Namespace }}/{{ include "aws-auth-operator.fullname" . }}-serving-cert - {{- end }} name: {{ include "aws-auth-operator.fullname" . }}-validating-webhook webhooks: - admissionReviewVersions: diff --git a/charts/aws-auth-operator/values.yaml b/charts/aws-auth-operator/values.yaml index e514d24..33a8fc7 100644 --- a/charts/aws-auth-operator/values.yaml +++ b/charts/aws-auth-operator/values.yaml @@ -80,10 +80,6 @@ affinity: {} podDisruptionBudget: enabled: false -# -- Enable cert-manager issuer and create self-signed certs -selfSignedIssuer: - enabled: true - # -- ConfigMap for MapAccount, MapUser, MapRoles in kube-system ns, aws-auth bu default configMapName: "aws-auth" # -- This account id must allways present in cm, and disallow to delete crd MapAccount with this id diff --git a/charts/values.yaml b/charts/values.yaml index b46f7f5..92008b9 100644 --- a/charts/values.yaml +++ b/charts/values.yaml @@ -77,10 +77,6 @@ affinity: {} podDisruptionBudget: enabled: false -# -- Enable cert-manager issuer and create self-signed certs -selfSignedIssuer: - enabled: true - # -- ConfigMap for MapAccount, MapUser, MapRoles in kube-system ns, aws-auth bu default configMapName: "aws-auth-test" # -- This account id must allways present in cm, and disallow to delete crd MapAccount with this id From da735d6ceb9df1d51721bca37f3abb88abe35c50 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 21 Jul 2025 12:17:31 +0300 Subject: [PATCH 51/58] add chart creation action --- .github/workflows/publish-release.yml | 82 +++++++++++++-------------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 41c77dc..aa84fa1 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -64,44 +64,44 @@ jobs: tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} -# release-chart: -# needs: verify-app -# runs-on: ubuntu-latest -# steps: -# - name: Checkout repository -# uses: actions/checkout@v3 -# with: -# fetch-depth: 0 -# -# - name: Configure git -# run: | -# git config user.name "$GITHUB_ACTOR" -# git config user.email "$GITHUB_ACTOR@users.noreply.github.com" -# -# - name: Release chart -# run: | -# # download helm chart releaser -# curl -sSLo cr.tar.gz "https://github.com/helm/chart-releaser/releases/download/v1.2.1/chart-releaser_1.2.1_linux_amd64.tar.gz" -# tar -xzf cr.tar.gz -# rm -f cr.tar.gz -# owner=$(cut -d '/' -f 1 <<< "$GITHUB_REPOSITORY") -# repo=$(cut -d '/' -f 2 <<< "$GITHUB_REPOSITORY") -# # package chart -# ./cr package charts/$repo -# # upload chart to github releases -# ./cr upload \ -# --owner "$owner" \ -# --git-repo "$repo" \ -# --token "${{ secrets.GITHUB_TOKEN }}" \ -# --release-name-template "{{ .Version }}" -# # update index and push to github pages -# git config user.email "$owner@users.noreply.github.com" -# git config user.name "$owner" -# ./cr index \ -# --owner "$owner" \ -# --git-repo "$repo" \ -# --token "${{ secrets.GITHUB_TOKEN }}" \ -# --release-name-template "{{ .Version }}" \ -# --index-path ./index.yaml \ -# --charts-repo https://$owner.github.io/$repo \ -# --push + release-chart: + needs: verify-app + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Configure git + run: | + git config user.name "$GITHUB_ACTOR" + git config user.email "$GITHUB_ACTOR@users.noreply.github.com" + + - name: Release chart + run: | + # download helm chart releaser + curl -sSLo cr.tar.gz "https://github.com/helm/chart-releaser/releases/download/v1.2.1/chart-releaser_1.2.1_linux_amd64.tar.gz" + tar -xzf cr.tar.gz + rm -f cr.tar.gz + owner=$(cut -d '/' -f 1 <<< "$GITHUB_REPOSITORY") + repo=$(cut -d '/' -f 2 <<< "$GITHUB_REPOSITORY") + # package chart + ./cr package charts/$repo + # upload chart to github releases + ./cr upload \ + --owner "$owner" \ + --git-repo "$repo" \ + --token "${{ secrets.GITHUB_TOKEN }}" \ + --release-name-template "{{ .Version }}" + # update index and push to github pages + git config user.email "$owner@users.noreply.github.com" + git config user.name "$owner" + ./cr index \ + --owner "$owner" \ + --git-repo "$repo" \ + --token "${{ secrets.GITHUB_TOKEN }}" \ + --release-name-template "{{ .Version }}" \ + --index-path ./index.yaml \ + --charts-repo https://$owner.github.io/$repo \ + --push From 69e852758db316ee6646e9b516f060b3bf6cc9db Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 21 Jul 2025 12:48:16 +0300 Subject: [PATCH 52/58] fix actions --- README.md | 2 +- charts/Makefile | 7 ++++-- .../.helmignore | 0 charts/aws-auth-controller/Chart.yaml | 18 ++++++++++++++ .../README.md | 0 .../aws-auth.prozorro.sale_mapaccounts.yaml | 0 .../crds/aws-auth.prozorro.sale_maproles.yaml | 0 .../crds/aws-auth.prozorro.sale_mapusers.yaml | 0 .../templates/NOTES.txt | 0 .../templates/_helpers.tpl | 0 .../templates/certificate-serving.yaml | 0 .../templates/deployment.yaml | 0 .../templates/issuer.yaml | 0 .../templates/pdb.yaml | 0 .../templates/rbac.yaml | 0 .../templates/service.yaml | 0 .../templates/webhook-validation.yaml | 0 .../values.yaml | 0 charts/aws-auth-operator/Chart.yaml | 24 ------------------- 19 files changed, 24 insertions(+), 27 deletions(-) rename charts/{aws-auth-operator => aws-auth-controller}/.helmignore (100%) create mode 100644 charts/aws-auth-controller/Chart.yaml rename charts/{aws-auth-operator => aws-auth-controller}/README.md (100%) rename charts/{aws-auth-operator => aws-auth-controller}/crds/aws-auth.prozorro.sale_mapaccounts.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/crds/aws-auth.prozorro.sale_maproles.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/crds/aws-auth.prozorro.sale_mapusers.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/templates/NOTES.txt (100%) rename charts/{aws-auth-operator => aws-auth-controller}/templates/_helpers.tpl (100%) rename charts/{aws-auth-operator => aws-auth-controller}/templates/certificate-serving.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/templates/deployment.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/templates/issuer.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/templates/pdb.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/templates/rbac.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/templates/service.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/templates/webhook-validation.yaml (100%) rename charts/{aws-auth-operator => aws-auth-controller}/values.yaml (100%) delete mode 100644 charts/aws-auth-operator/Chart.yaml diff --git a/README.md b/README.md index edbb77e..679c489 100644 --- a/README.md +++ b/README.md @@ -3,4 +3,4 @@ [![unit-test](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml/badge.svg?branch=init)](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/redacid/aws-auth-controller/blob/init/LICENSE) -[Helm chart README.md](charts/aws-auth-operator/README.md) \ No newline at end of file +[Helm chart README.md](charts/aws-auth-controller/README.md) \ No newline at end of file diff --git a/charts/Makefile b/charts/Makefile index fe88781..8fc3310 100644 --- a/charts/Makefile +++ b/charts/Makefile @@ -3,7 +3,7 @@ GIT_STAMP ?= $(shell git describe || echo v0.1.0) KUBEVAL_SCHEMA_LOCATION ?= https://raw.githubusercontent.com/redacid/k8s-json-scheme/refs/heads/main KUBECONFORM_SCHEMA ?= --schema-location 'https://raw.githubusercontent.com/redacid/k8s-json-scheme/refs/heads/main/{{.NormalizedKubernetesVersion}}-standalone{{.StrictSuffix}}/{{.ResourceKind}}{{.KindSuffix}}.json' -CHART_PATH ?= ./aws-auth-operator +CHART_PATH ?= ./aws-auth-controller CREATE_NAMESPACE ?= --create-namespace ENV_NAME ?= TEST @@ -59,7 +59,10 @@ helm-kubeconform: helm-dependency-update install-kubeconform-plugin ## Deploy TEST deploy-test: helm-dependency-update helm-package - @helm upgrade -i --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) ./aws-auth-operator-$(GIT_STAMP).tgz $(TEST_VALUES) $(CREATE_NAMESPACE) + @helm upgrade -i --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) ./aws-auth-controller-$(GIT_STAMP).tgz $(TEST_VALUES) $(CREATE_NAMESPACE) + +uninstall-test: + @helm uninstall --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) ## Deploy TEST template-test: helm-dependency-update diff --git a/charts/aws-auth-operator/.helmignore b/charts/aws-auth-controller/.helmignore similarity index 100% rename from charts/aws-auth-operator/.helmignore rename to charts/aws-auth-controller/.helmignore diff --git a/charts/aws-auth-controller/Chart.yaml b/charts/aws-auth-controller/Chart.yaml new file mode 100644 index 0000000..711d425 --- /dev/null +++ b/charts/aws-auth-controller/Chart.yaml @@ -0,0 +1,18 @@ +apiVersion: v2 +name: aws-auth-controller +description: Kubernetes operator to declaratively manage the EKS aws-auth configmap +type: application +version: 0.1.0 +appVersion: "0.1.0" +icon: https://raw.githubusercontent.com/aws/eks-charts/master/docs/logo/aws.png +home: https://github.com/redacid/aws-auth-controller +sources: + - https://github.com/redacid/aws-auth-controller +keywords: + - eks + - aws + - aws-auth +maintainers: + - name: Serhii Rudenko + url: https://github.com/redacid + email: sr@ios.in.ua \ No newline at end of file diff --git a/charts/aws-auth-operator/README.md b/charts/aws-auth-controller/README.md similarity index 100% rename from charts/aws-auth-operator/README.md rename to charts/aws-auth-controller/README.md diff --git a/charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapaccounts.yaml b/charts/aws-auth-controller/crds/aws-auth.prozorro.sale_mapaccounts.yaml similarity index 100% rename from charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapaccounts.yaml rename to charts/aws-auth-controller/crds/aws-auth.prozorro.sale_mapaccounts.yaml diff --git a/charts/aws-auth-operator/crds/aws-auth.prozorro.sale_maproles.yaml b/charts/aws-auth-controller/crds/aws-auth.prozorro.sale_maproles.yaml similarity index 100% rename from charts/aws-auth-operator/crds/aws-auth.prozorro.sale_maproles.yaml rename to charts/aws-auth-controller/crds/aws-auth.prozorro.sale_maproles.yaml diff --git a/charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapusers.yaml b/charts/aws-auth-controller/crds/aws-auth.prozorro.sale_mapusers.yaml similarity index 100% rename from charts/aws-auth-operator/crds/aws-auth.prozorro.sale_mapusers.yaml rename to charts/aws-auth-controller/crds/aws-auth.prozorro.sale_mapusers.yaml diff --git a/charts/aws-auth-operator/templates/NOTES.txt b/charts/aws-auth-controller/templates/NOTES.txt similarity index 100% rename from charts/aws-auth-operator/templates/NOTES.txt rename to charts/aws-auth-controller/templates/NOTES.txt diff --git a/charts/aws-auth-operator/templates/_helpers.tpl b/charts/aws-auth-controller/templates/_helpers.tpl similarity index 100% rename from charts/aws-auth-operator/templates/_helpers.tpl rename to charts/aws-auth-controller/templates/_helpers.tpl diff --git a/charts/aws-auth-operator/templates/certificate-serving.yaml b/charts/aws-auth-controller/templates/certificate-serving.yaml similarity index 100% rename from charts/aws-auth-operator/templates/certificate-serving.yaml rename to charts/aws-auth-controller/templates/certificate-serving.yaml diff --git a/charts/aws-auth-operator/templates/deployment.yaml b/charts/aws-auth-controller/templates/deployment.yaml similarity index 100% rename from charts/aws-auth-operator/templates/deployment.yaml rename to charts/aws-auth-controller/templates/deployment.yaml diff --git a/charts/aws-auth-operator/templates/issuer.yaml b/charts/aws-auth-controller/templates/issuer.yaml similarity index 100% rename from charts/aws-auth-operator/templates/issuer.yaml rename to charts/aws-auth-controller/templates/issuer.yaml diff --git a/charts/aws-auth-operator/templates/pdb.yaml b/charts/aws-auth-controller/templates/pdb.yaml similarity index 100% rename from charts/aws-auth-operator/templates/pdb.yaml rename to charts/aws-auth-controller/templates/pdb.yaml diff --git a/charts/aws-auth-operator/templates/rbac.yaml b/charts/aws-auth-controller/templates/rbac.yaml similarity index 100% rename from charts/aws-auth-operator/templates/rbac.yaml rename to charts/aws-auth-controller/templates/rbac.yaml diff --git a/charts/aws-auth-operator/templates/service.yaml b/charts/aws-auth-controller/templates/service.yaml similarity index 100% rename from charts/aws-auth-operator/templates/service.yaml rename to charts/aws-auth-controller/templates/service.yaml diff --git a/charts/aws-auth-operator/templates/webhook-validation.yaml b/charts/aws-auth-controller/templates/webhook-validation.yaml similarity index 100% rename from charts/aws-auth-operator/templates/webhook-validation.yaml rename to charts/aws-auth-controller/templates/webhook-validation.yaml diff --git a/charts/aws-auth-operator/values.yaml b/charts/aws-auth-controller/values.yaml similarity index 100% rename from charts/aws-auth-operator/values.yaml rename to charts/aws-auth-controller/values.yaml diff --git a/charts/aws-auth-operator/Chart.yaml b/charts/aws-auth-operator/Chart.yaml deleted file mode 100644 index 08053a6..0000000 --- a/charts/aws-auth-operator/Chart.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: v2 -name: aws-auth-operator -description: Kubernetes operator to declaratively manage the EKS aws-auth configmap - -# 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/) -version: 0.1.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. -appVersion: "0.1.0" From 6d3bab240c8cbdc6229e7e4742c293b8174e7d13 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 21 Jul 2025 14:18:54 +0300 Subject: [PATCH 53/58] fix actions --- .github/workflows/publish-release.yml | 5 ++++- .gitignore | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index aa84fa1..f5b563c 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -67,6 +67,9 @@ jobs: release-chart: needs: verify-app runs-on: ubuntu-latest + permissions: + contents: write + packages: write steps: - name: Checkout repository uses: actions/checkout@v3 @@ -81,7 +84,7 @@ jobs: - name: Release chart run: | # download helm chart releaser - curl -sSLo cr.tar.gz "https://github.com/helm/chart-releaser/releases/download/v1.2.1/chart-releaser_1.2.1_linux_amd64.tar.gz" + curl -sSLo cr.tar.gz "https://github.com/helm/chart-releaser/releases/download/v1.8.1/chart-releaser_1.8.1_linux_amd64.tar.gz" tar -xzf cr.tar.gz rm -f cr.tar.gz owner=$(cut -d '/' -f 1 <<< "$GITHUB_REPOSITORY") diff --git a/.gitignore b/.gitignore index f6ad33a..7edbbfd 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ go.work *.swo *~ /coverage.txt +/.env From 90e189127523b3c1a875d107f04e87f94ae02822 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 21 Jul 2025 16:29:26 +0300 Subject: [PATCH 54/58] edt helm chart --- charts/Makefile | 52 +++++++++++++------ .../templates/deployment.yaml | 4 +- .../aws-auth-controller/templates/rbac.yaml | 6 +-- charts/examples/mapaccount.yaml | 15 ++++++ charts/examples/maprole.yaml | 24 +++++++++ charts/examples/mapuser.yaml | 24 +++++++++ charts/values.yaml | 2 +- 7 files changed, 106 insertions(+), 21 deletions(-) create mode 100644 charts/examples/mapaccount.yaml create mode 100644 charts/examples/maprole.yaml create mode 100644 charts/examples/mapuser.yaml diff --git a/charts/Makefile b/charts/Makefile index 8fc3310..9335fc9 100644 --- a/charts/Makefile +++ b/charts/Makefile @@ -25,15 +25,29 @@ TARGET_MAX_CHAR_NUM = 30 all: help -## Install helm-docs | Docs -.PHONY: install_helm-docs -install_helm-docs: - wget https://github.com/norwoodj/helm-docs/releases/download/v1.14.2/helm-docs_1.14.2_Linux_x86_64.tar.gz - tar -zxvf helm-docs_1.14.2_Linux_x86_64.tar.gz helm-docs - sudo mv helm-docs ./bin/ - rm helm-docs_1.14.2_Linux_x86_64.tar.gz - -## Generate Helm Chart Docs +## Deploy example MapUser | Examples +example_mapuser_deploy: + kubectl apply -f ./examples/mapuser.yaml -n $(TEST_NAMESPACE) +## Deploy example MapRole +example_maprole_deploy: + kubectl apply -f ./examples/maprole.yaml -n $(TEST_NAMESPACE) +## Deploy example MapAccount +example_mapaccount_deploy: + kubectl apply -f ./examples/mapaccount.yaml -n $(TEST_NAMESPACE) +## Undeploy example MapUser +example_mapuser_undeploy: + kubectl delete MapUser user1 -n $(TEST_NAMESPACE) + kubectl delete MapUser user2 -n $(TEST_NAMESPACE) +## Undeploy example MapRole +example_maprole_undeploy: + kubectl delete MapRole maprole-managed-node-group -n $(TEST_NAMESPACE) + kubectl delete MapRole maprole-node-group -n $(TEST_NAMESPACE) +## Undeploy example MapAccount (account-123456789012 is must present account id, and not be deleted, see values.yaml for mustPresentAccountID) +example_mapaccount_undeploy: + kubectl delete MapAccount account-111111111111 -n $(TEST_NAMESPACE) + kubectl delete MapAccount account-123456789012 -n $(TEST_NAMESPACE) + +## Generate Helm Chart Docs | Docs .PHONY: helm-docs-generate helm-docs-generate: helm-docs -c $(CHART_PATH) -o README.md @@ -57,23 +71,32 @@ helm-kubeconform: helm-dependency-update install-kubeconform-plugin --kube-version $($(var)_KUBERNETES_VERSION) \ --strict --summary --name-template=$($(var)_RELEASE_NAME) --namespace=$($(var)_NAMESPACE) $($(var)_VALUES) $(CHART_PATH) || exit;) +## Template TEST | Deploy +template-test: helm-dependency-update helm-lint helm-kubeval helm-kubeconform + @helm template --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) $(CHART_PATH) $(TEST_VALUES) + ## Deploy TEST -deploy-test: helm-dependency-update helm-package +deploy-test: helm-dependency-update helm-lint helm-kubeval helm-kubeconform helm-package @helm upgrade -i --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) ./aws-auth-controller-$(GIT_STAMP).tgz $(TEST_VALUES) $(CREATE_NAMESPACE) +## Uninstall TEST uninstall-test: @helm uninstall --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) -## Deploy TEST -template-test: helm-dependency-update - @helm template --namespace=$(TEST_NAMESPACE) $(TEST_RELEASE_NAME) $(CHART_PATH) $(TEST_VALUES) - ## Dependency update helm | Tools helm-dependency-update: @helm dependency update $(CHART_PATH) @helm dependency list $(CHART_PATH) @ls -l $(CHART_PATH) +## Install helm-docs +.PHONY: install_helm-docs +install_helm-docs: + wget https://github.com/norwoodj/helm-docs/releases/download/v1.14.2/helm-docs_1.14.2_Linux_x86_64.tar.gz + tar -zxvf helm-docs_1.14.2_Linux_x86_64.tar.gz helm-docs + sudo mv helm-docs /usr/bin/ + rm helm-docs_1.14.2_Linux_x86_64.tar.gz + ## Build helm package helm-package: @helm package --app-version=$(GIT_STAMP) --version=$(GIT_STAMP) $(CHART_PATH) @@ -82,7 +105,6 @@ helm-package: install-kubeconform-plugin: @helm plugin list | grep -q kubeconform || helm plugin install https://github.com/redacid/helm-kubeconform --version 0.6.8.1 - ## Shows help. | Help help: @echo '' diff --git a/charts/aws-auth-controller/templates/deployment.yaml b/charts/aws-auth-controller/templates/deployment.yaml index c449229..d92e254 100644 --- a/charts/aws-auth-controller/templates/deployment.yaml +++ b/charts/aws-auth-controller/templates/deployment.yaml @@ -4,7 +4,7 @@ metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager - name: {{ include "aws-auth-operator.fullname" . }}-controller-manager + name: {{ include "aws-auth-operator.fullname" . }}-manager namespace: {{ .Release.Namespace }} spec: replicas: {{ .Values.replicaCount }} @@ -75,7 +75,7 @@ spec: {{- end }} securityContext: {{- toYaml .Values.podSecurityContext | nindent 8 }} - serviceAccountName: {{ include "aws-auth-operator.fullname" . }}-controller-manager + serviceAccountName: {{ include "aws-auth-operator.fullname" . }}-manager terminationGracePeriodSeconds: 10 volumes: - name: webhook-certs diff --git a/charts/aws-auth-controller/templates/rbac.yaml b/charts/aws-auth-controller/templates/rbac.yaml index e5aab1d..d2356a7 100644 --- a/charts/aws-auth-controller/templates/rbac.yaml +++ b/charts/aws-auth-controller/templates/rbac.yaml @@ -4,7 +4,7 @@ metadata: labels: {{- include "aws-auth-operator.labels" . | nindent 4 }} control-plane: controller-manager - name: {{ include "aws-auth-operator.fullname" . }}-controller-manager + name: {{ include "aws-auth-operator.fullname" . }}-manager --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role @@ -125,7 +125,7 @@ roleRef: name: {{ include "aws-auth-operator.fullname" . }}-leader-election-role subjects: - kind: ServiceAccount - name: {{ include "aws-auth-operator.fullname" . }}-controller-manager + name: {{ include "aws-auth-operator.fullname" . }}-manager --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding @@ -140,5 +140,5 @@ roleRef: name: {{ include "aws-auth-operator.fullname" . }}-manager-role subjects: - kind: ServiceAccount - name: {{ include "aws-auth-operator.fullname" . }}-controller-manager + name: {{ include "aws-auth-operator.fullname" . }}-manager namespace: {{ .Release.Namespace }} \ No newline at end of file diff --git a/charts/examples/mapaccount.yaml b/charts/examples/mapaccount.yaml new file mode 100644 index 0000000..c24469b --- /dev/null +++ b/charts/examples/mapaccount.yaml @@ -0,0 +1,15 @@ +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapAccount +metadata: + name: account-111111111111 +spec: + accountid: "111111111111" + +--- + +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapAccount +metadata: + name: account-123456789012 +spec: + accountid: "123456789012" diff --git a/charts/examples/maprole.yaml b/charts/examples/maprole.yaml new file mode 100644 index 0000000..894bb05 --- /dev/null +++ b/charts/examples/maprole.yaml @@ -0,0 +1,24 @@ +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapRole +metadata: + name: maprole-managed-node-group +spec: + rolearn: arn:aws:iam::123456789012:role/managed-node-group + groups: + - sample:group1 + - sample:group2 + description: A sample maprole + username: system:node:{{EC2PrivateDNSName}} + +--- + +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapRole +metadata: + name: maprole-node-group +spec: + rolearn: arn:aws:iam::123456789012:role/node-group-20240218223715755100000001 + groups: + - sample:group3 + description: A sample maprole2 + username: system:node:{{EC2PrivateDNSName2}} \ No newline at end of file diff --git a/charts/examples/mapuser.yaml b/charts/examples/mapuser.yaml new file mode 100644 index 0000000..5d6ca42 --- /dev/null +++ b/charts/examples/mapuser.yaml @@ -0,0 +1,24 @@ +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapUser +metadata: + name: user1 +spec: + description: A test mapuser1 + username: user1@domain.com + groups: + - system:masters + - admins + userarn: arn:aws:iam::123456789012:user/user1@domain.com + +--- +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapUser +metadata: + name: user2 +spec: + description: A test mapuser2 + username: user2@domain.com + groups: + - system:masters + - users + userarn: arn:aws:iam::123456789012:user/user2@domain.com diff --git a/charts/values.yaml b/charts/values.yaml index 92008b9..ef580d6 100644 --- a/charts/values.yaml +++ b/charts/values.yaml @@ -83,7 +83,7 @@ configMapName: "aws-auth-test" mustPresentAccountID: "123456789012" # -- Allow creating crds only on this ns, if blank allowing in any ns -crdCreationAllowedNS: "kube-system" +crdCreationAllowedNS: "aws-auth-ns" # -- Reconcile time in controller, recheck all crds, and recreate cm records if needed reconcileTime: "30m" From cc5d6275c7e077644e35007997e61401495ac091 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 21 Jul 2025 16:56:58 +0300 Subject: [PATCH 55/58] edt README.md --- README.md | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 679c489..92e4ec7 100644 --- a/README.md +++ b/README.md @@ -3,4 +3,39 @@ [![unit-test](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml/badge.svg?branch=init)](https://github.com/redacid/aws-auth-controller/actions/workflows/test.yml) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/redacid/aws-auth-controller/blob/init/LICENSE) -[Helm chart README.md](charts/aws-auth-controller/README.md) \ No newline at end of file +[Helm chart README.md](charts/aws-auth-controller/README.md) + +This repository contains the Golang implementation of a [Kubernetes Operator](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/) +managing the `aws-auth` ConfigMap(for testing you can set another name, see configMapName in values.yaml), built with [Kubebuilder](https://kubebuilder.io/) +Worked with Validation Webhook + +## Custom Resource Definitions + +This operator provides the following CRD kinds in the `aws-auth.prozorro.sale` API group. + +- [MapAccount](charts/examples/mapaccount.yaml) +- [MapRole](charts/examples/maprole.yaml) +- [MapUser](charts/examples/mapuser.yaml) + +## External Resources + +- [Kubebuilder documentation](https://book.kubebuilder.io/) +- [kubernetes Custom Resources documentation](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/) +- [Kubernetes Controllers documentation](https://kubernetes.io/docs/concepts/architecture/controller/) +- [Kubernetes Operator documentation](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/) +- [AWS EKS aws-auth ConfigMap documentation](https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html) + +## Related work + +- [sambatv aws-auth-operator](https://github.com/sambatv/aws-auth-operator) This repository contains the Golang + implementation of a Kubernetes Operator managing the aws-auth ConfigMap, built with Kubebuilder + +- [ops42 aws-auth-operator](https://ops42.org/aws-auth-operator/) provides a + way to map AWS IAM users to the `data.mapUsers` section of the `kube-system:aws-auth` + ConfigMap. +- [rustrial aws-eks-iam-auth-controller](https://github.com/rustrial/aws-eks-iam-auth-controller) + similarly provides a way to map AWS IAM users to the `data.mapUsers` section of the + `kube-system:aws-auth` ConfigMap. +- [aws-auth](https://github.com/keikoproj/aws-auth) provides a CLI and Golang + package enabling management of the `data.mapRoles` and `data.mapUsers` + sections of the `kube-system:aws-auth` ConfigMap. \ No newline at end of file From fe925c90bb5a8ef2571ab3f756ffb9580d58a213 Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Mon, 21 Jul 2025 17:30:59 +0300 Subject: [PATCH 56/58] edt README.md --- README.md | 39 +++++++++++++++++++- internal/controller/mapaccount_controller.go | 2 +- internal/controller/maprole_controller.go | 2 +- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 92e4ec7..db98c72 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,44 @@ This repository contains the Golang implementation of a [Kubernetes Operator](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/) managing the `aws-auth` ConfigMap(for testing you can set another name, see configMapName in values.yaml), built with [Kubebuilder](https://kubebuilder.io/) -Worked with Validation Webhook +For self-signed certs used cert-manager.io, must be present in a cluster. +Allow creation user-names, role-names with special characters. +Manipulations with all of crd resources controlled by Validation Webhook and CRDs spec.properties. + +```yaml +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapUser +metadata: + name: user1 +spec: + description: A test mapuser1 + username: user1@domain.com # < this name will be stored in cm + groups: + - system:masters + - admins + userarn: arn:aws:iam::123456789012:user/user1@domain.com +``` +```yaml +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapRole +metadata: + name: maprole-managed-node-group +spec: + rolearn: arn:aws:iam::123456789012:role/managed-node-group + groups: + - sample:group1 + - sample:group2 + description: A sample maprole + username: system:node:{{EC2PrivateDNSName}} # < this name will be stored in cm +``` +```yaml +apiVersion: aws-auth.prozorro.sale/v1beta1 +kind: MapAccount +metadata: + name: account-123456789012 +spec: + accountid: "123456789012" # < if this account id is present in mustPresentAccountID, you can't delete this crd resource +``` ## Custom Resource Definitions diff --git a/internal/controller/mapaccount_controller.go b/internal/controller/mapaccount_controller.go index 855bef0..ecc61e2 100644 --- a/internal/controller/mapaccount_controller.go +++ b/internal/controller/mapaccount_controller.go @@ -81,7 +81,7 @@ func (r *MapAccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) return ctrl.Result{}, err } - // Load the MapUser object by name (its AWS IAM user ARN). + // Load the MapAccount object by name. mapAccount := &awsauthv1beta1.MapAccount{} if err := r.Get(ctx, req.NamespacedName, mapAccount); err != nil { diff --git a/internal/controller/maprole_controller.go b/internal/controller/maprole_controller.go index 45d175b..5e18ec1 100644 --- a/internal/controller/maprole_controller.go +++ b/internal/controller/maprole_controller.go @@ -80,7 +80,7 @@ func (r *MapRoleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct return ctrl.Result{}, err } - // Load the MapRole object by name (its AWS IAM role ARN). + // Load the MapRole object by name. mapRole := &awsauthv1beta1.MapRole{} if err := r.Get(ctx, req.NamespacedName, mapRole); err != nil { // If any error other than a "NotFound" API error, it's a problem. From 882cd2255e10a204ab8742ceedc3f88ed08cbc3d Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Tue, 22 Jul 2025 14:11:08 +0300 Subject: [PATCH 57/58] ltl fix --- DEV-DOCS.md | 4 +++- charts/Makefile | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/DEV-DOCS.md b/DEV-DOCS.md index 93bcbaa..2ed9874 100644 --- a/DEV-DOCS.md +++ b/DEV-DOCS.md @@ -19,7 +19,7 @@ helm uninstall rrrrr -n nnnnn echo | openssl s_client -servername rrrrr-webhook-service.nnnnn.svc -showcerts -connect localhost:42765 2>/dev/null | openssl x509 -inform pem -noout -text -cd ./charts helm upgrade -i --namespace kube-system aws-auth aws-auth-operator +cd ./charts helm upgrade -i --namespace kube-system aws-auth aws-auth-controller cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapuser.yaml -n kube-system cd ./config/samples kubectl apply -f aws-auth_v1beta1_maprole.yaml -n kube-system cd ./config/samples kubectl apply -f aws-auth_v1beta1_mapaccount.yaml -n kube-system @@ -30,6 +30,8 @@ https://book.kubebuilder.io/reference/markers/crd-validation https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/reconcile/reconcile.go#L46 https://book.kubebuilder.io/reference/watching-resources.html?highlight=RequeueAfter#when-requeueafter-x-is-useful + +https://docs.aws.amazon.com/eks/latest/best-practices/identity-and-access-management.html https://github.com/gp42/aws-auth-operator https://github.com/keikoproj/aws-auth/ diff --git a/charts/Makefile b/charts/Makefile index 9335fc9..d8cc335 100644 --- a/charts/Makefile +++ b/charts/Makefile @@ -34,6 +34,10 @@ example_maprole_deploy: ## Deploy example MapAccount example_mapaccount_deploy: kubectl apply -f ./examples/mapaccount.yaml -n $(TEST_NAMESPACE) + +example_show_cm: + kubectl get configmap -n kube-system aws-auth-test -o yaml + ## Undeploy example MapUser example_mapuser_undeploy: kubectl delete MapUser user1 -n $(TEST_NAMESPACE) @@ -47,6 +51,8 @@ example_mapaccount_undeploy: kubectl delete MapAccount account-111111111111 -n $(TEST_NAMESPACE) kubectl delete MapAccount account-123456789012 -n $(TEST_NAMESPACE) + + ## Generate Helm Chart Docs | Docs .PHONY: helm-docs-generate helm-docs-generate: From 66dfee3ffbbc2cf8087f29b33824f9f5b87b252f Mon Sep 17 00:00:00 2001 From: Serhii Rudenko Date: Thu, 24 Jul 2025 14:00:09 +0300 Subject: [PATCH 58/58] edt README.md --- README.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index db98c72..2edfe2c 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,62 @@ This operator provides the following CRD kinds in the `aws-auth.prozorro.sale` A - [kubernetes Custom Resources documentation](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/) - [Kubernetes Controllers documentation](https://kubernetes.io/docs/concepts/architecture/controller/) - [Kubernetes Operator documentation](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/) -- [AWS EKS aws-auth ConfigMap documentation](https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html) +- [AWS EKS aws-auth ConfigMap documentation](https://docs.aws.amazon.com/eks/latest/best-practices/identity-and-access-management.html) +- [CRD Validation](https://book.kubebuilder.io/reference/markers/crd-validation) +- [Using Finalizers](https://book.kubebuilder.io/reference/using-finalizers) +- [About Webhooks](https://book.kubebuilder.io/multiversion-tutorial/webhooks) +- [Writing tests](https://book.kubebuilder.io/cronjob-tutorial/writing-tests) +- [RequeueAfter](https://book.kubebuilder.io/reference/watching-resources.html?highlight=RequeueAfter#when-requeueafter-x-is-useful) + +## Controller command line parameters +```text + ./bin/manager --help +Usage of ./bin/manager: + -config-map-name string + ConfigMap-name where stored items, --config-map-name=aws-auth-test (default "aws-auth") + -crd-item-allowed-namespace string + Namespace where allowed creation of Resources --crd-item-allowed-namespace=kube-system, If is set, only in this namespace allowed creation of Resources, if not set, all namespaces allowed creation of Resources. + -enable-http2 + If set, HTTP/2 will be enabled for the metrics and webhook servers + -health-probe-bind-address string + The address the probe endpoint binds to. (default ":8081") + -kubeconfig string + Paths to a kubeconfig. Only required if out-of-cluster. + -leader-elect + Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager. + -metrics-bind-address string + The address the metrics endpoint binds to. Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service. (default "0") + -metrics-cert-key string + The name of the metrics server key file. (default "tls.key") + -metrics-cert-name string + The name of the metrics server certificate file. (default "tls.crt") + -metrics-cert-path string + The directory that contains the metrics server certificate. + -metrics-secure + If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead. (default true) + -must-present-account-id string + This account must be allways present in ConfigMap, --must-present-account-id=123456789012 + -reconcile-time duration + Time to reconcile CRDs and recreate configmap item if need, --reconcile-time=30m, s - seconds, m - minutes, h - hours, d - days (default 30m0s) + -username-must-be-email + Enables checking of username in MapUser, should it be an email address, default false.Use --username-must-be-email=true to enable this feature. + -webhook-cert-key string + The name of the webhook key file. (default "tls.key") + -webhook-cert-name string + The name of the webhook certificate file. (default "tls.crt") + -webhook-cert-path string + The directory that contains the webhook certificate. + -zap-devel + Development Mode defaults(encoder=consoleEncoder,logLevel=Debug,stackTraceLevel=Warn). Production Mode defaults(encoder=jsonEncoder,logLevel=Info,stackTraceLevel=Error) (default true) + -zap-encoder value + Zap log encoding (one of 'json' or 'console') + -zap-log-level value + Zap Level to configure the verbosity of logging. Can be one of 'debug', 'info', 'error', 'panic'or any integer value > 0 which corresponds to custom debug levels of increasing verbosity + -zap-stacktrace-level value + Zap Level at and above which stacktraces are captured (one of 'info', 'error', 'panic'). + -zap-time-encoding value + Zap time encoding (one of 'epoch', 'millis', 'nano', 'iso8601', 'rfc3339' or 'rfc3339nano'). Defaults to 'epoch'. +``` ## Related work