From 6dcf024fd2b12b9e4c779c553df7a4143634c0f9 Mon Sep 17 00:00:00 2001 From: Suneha Bose Date: Mon, 20 Jul 2026 15:33:09 -0700 Subject: [PATCH 1/3] Move private-cluster integration test to 1ES pipeline GitHub-repo Federated Identity Credentials are being removed, so the private-cluster integration test moves from GitHub Actions to an Azure DevOps 1ES pipeline that authenticates via a WIF service connection. - Add .pipelines/1es-integration-tests-private.yml (extends 1ES Unofficial template; runs on staging-pool-amd64-mariner-2). - Invoke the node24 action via `node lib/index.js` with INPUT_* env vars. - Use a pre-created, shared resource group; create/delete only a per-build cluster (no az group create/delete). - Add optional resourceGroup= arg to k8s-deploy-test.py (defaults to cluster name) so verification targets the shared RG. - Delete the GitHub workflow whose FIC-based azure/login no longer authenticates. --- .../1es-integration-tests-private.yml | 155 ++++++++++++++++++ .../run-integration-tests-private.yml | 85 ---------- test/integration/k8s-deploy-test.py | 8 +- 3 files changed, 162 insertions(+), 86 deletions(-) create mode 100644 .azure-pipelines/1es-integration-tests-private.yml delete mode 100644 .github/workflows/run-integration-tests-private.yml diff --git a/.azure-pipelines/1es-integration-tests-private.yml b/.azure-pipelines/1es-integration-tests-private.yml new file mode 100644 index 000000000..751f04aef --- /dev/null +++ b/.azure-pipelines/1es-integration-tests-private.yml @@ -0,0 +1,155 @@ +# Private-cluster integration test (1ES pipeline). +# +# Runs the k8s-deploy action against a real private AKS cluster. Lives in Azure +# DevOps (not GitHub Actions) because GitHub-repo Federated Identity Credentials +# are being removed; auth uses a governed WIF service connection instead. +# +# The node24 JS action is invoked as `node lib/index.js` with inputs supplied via +# INPUT_* env vars. There is no action.yml default injection here, so keep INPUT_* +# in sync with action.yml; skip-tls-verify (getBooleanInput) and GITHUB_WORKFLOW +# must be set or the action throws. +# +# The pipeline does not create/delete the resource group (it must already exist); +# it only creates and deletes a per-build cluster inside it. + +trigger: + branches: + include: + - main + +pr: + branches: + include: + - releases/* + +resources: + repositories: + - repository: 1esPipelines + type: git + name: 1ESPipelineTemplates/1ESPipelineTemplates + ref: refs/tags/release + +variables: + serviceConnection: k8s-deploy-intg-test-svc-conn + resourceGroup: k8s-deploy-intg-rg + location: eastus2 + clusterName: test-$(Build.BuildId) + namespace: test-$(Build.BuildId) + workflowFriendlyName: k8s-deploy-integration-tests-private + +extends: + template: v1/1ES.Unofficial.PipelineTemplate.yml@1esPipelines + parameters: + pool: + name: staging-pool-amd64-mariner-2 + image: 1es-azlinux-3-amd64-custom-disk + os: linux + hostArchitecture: amd64 + sdl: + sourceAnalysisPool: + name: staging-pool-amd64-mariner-2 + image: azcu-agent-amd64-windows-22-img + os: windows + hostArchitecture: amd64 + stages: + - stage: integration_test + displayName: Private cluster integration tests + jobs: + - job: run_integration_test + displayName: Run Private Cluster Integration Tests + timeoutInMinutes: 60 + steps: + - task: NodeTool@0 + displayName: Install Node.js + inputs: + versionSpec: '24.x' + + - script: | + rm -rf node_modules/ + npm install + displayName: Install dependencies + + - script: npm run build + displayName: Build + + - task: AzureCLI@2 + displayName: Create private AKS cluster and set context + inputs: + azureSubscription: $(serviceConnection) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -e + set +x + # RG must already exist; do not run `az group create`. + az aks create --name $(clusterName) --resource-group $(resourceGroup) --enable-private-cluster --generate-ssh-keys + az aks get-credentials --resource-group $(resourceGroup) --name $(clusterName) + + - task: AzureCLI@2 + displayName: Create namespace to run tests + inputs: + azureSubscription: $(serviceConnection) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -e + az aks command invoke --resource-group $(resourceGroup) --name $(clusterName) --command "kubectl create ns $(namespace)" + + - task: UsePythonVersion@0 + displayName: Install Python + inputs: + versionSpec: '3.x' + + - task: AzureCLI@2 + displayName: Executing deploy action for pod + inputs: + azureSubscription: $(serviceConnection) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -e + node lib/index.js + env: + KUBECONFIG: $(HOME)/.kube/config + # Inputs supplied via INPUT_* (no action.yml injection here). + INPUT_ACTION: deploy + INPUT_STRATEGY: basic + INPUT_TRAFFIC-SPLIT-METHOD: pod + INPUT_SKIP-TLS-VERIFY: 'false' + INPUT_NAMESPACE: $(namespace) + INPUT_IMAGES: nginx:1.14.2 + INPUT_MANIFESTS: | + test/integration/manifests/test.yml + test/integration/manifests/test2.yml + INPUT_PRIVATE-CLUSTER: 'true' + INPUT_RESOURCE-GROUP: $(resourceGroup) + INPUT_NAME: $(clusterName) + INPUT_RESOURCE-TYPE: Microsoft.ContainerService/managedClusters + # Required by the action; also the workflowFriendlyName label. + GITHUB_WORKFLOW: $(workflowFriendlyName) + + - task: AzureCLI@2 + displayName: Checking if deployments and services were created + inputs: + azureSubscription: $(serviceConnection) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -e + python test/integration/k8s-deploy-test.py private=$(clusterName) resourceGroup=$(resourceGroup) namespace=$(namespace) kind=Deployment name=nginx-deployment containerName=nginx:1.14.2 labels=app:nginx,workflow:actions.github.com-k8s-deploy,workflowFriendlyName:$(workflowFriendlyName) selectorLabels=app:nginx + python test/integration/k8s-deploy-test.py private=$(clusterName) resourceGroup=$(resourceGroup) namespace=$(namespace) kind=Service name=nginx-service labels=workflow:actions.github.com-k8s-deploy,workflowFriendlyName:$(workflowFriendlyName) selectorLabels=app:nginx + + python test/integration/k8s-deploy-test.py private=$(clusterName) resourceGroup=$(resourceGroup) namespace=$(namespace) kind=Deployment name=nginx-deployment2 containerName=nginx:1.14.2 labels=app:nginx2,workflow:actions.github.com-k8s-deploy,workflowFriendlyName:$(workflowFriendlyName) selectorLabels=app:nginx2 + python test/integration/k8s-deploy-test.py private=$(clusterName) resourceGroup=$(resourceGroup) namespace=$(namespace) kind=Service name=nginx-service2 labels=workflow:actions.github.com-k8s-deploy,workflowFriendlyName:$(workflowFriendlyName) selectorLabels=app:nginx2 + + - task: AzureCLI@2 + displayName: Clean up AKS cluster + condition: always() + inputs: + azureSubscription: $(serviceConnection) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + # Delete only the cluster; the shared RG persists. + echo "deleting AKS cluster $(clusterName)" + az aks delete --yes --resource-group $(resourceGroup) --name $(clusterName) || true diff --git a/.github/workflows/run-integration-tests-private.yml b/.github/workflows/run-integration-tests-private.yml deleted file mode 100644 index 6b4b3847e..000000000 --- a/.github/workflows/run-integration-tests-private.yml +++ /dev/null @@ -1,85 +0,0 @@ -name: Cluster Integration Tests - private cluster -on: - pull_request: - branches: - - 'releases/*' - push: - branches: - - main - workflow_dispatch: - -jobs: - run-integration-test: - name: Run Minikube Integration Tests - runs-on: ubuntu-22.04 - env: - KUBECONFIG: /home/runner/.kube/config - NAMESPACE: test-${{ github.run_id }} - permissions: - contents: read - id-token: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Install dependencies - run: | - rm -rf node_modules/ - npm install - - - name: Build - run: npm run build - - - name: Azure login - uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0 - with: - client-id: ${{ secrets.AZURE_CLIENT_ID }} - tenant-id: ${{ secrets.AZURE_TENANT_ID }} - subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} - - - uses: Azure/setup-kubectl@bda439f5f36b99b262ebdcd3613869bddb064c8e # v5.2.0 - name: Install Kubectl - - - name: Create private AKS cluster and set context - run: | - set +x - # create cluster - az group create --location eastus2 --name ${{ env.NAMESPACE }} - az aks create --name ${{ env.NAMESPACE }} --resource-group ${{ env.NAMESPACE }} --enable-private-cluster --generate-ssh-keys - az aks get-credentials --resource-group ${{ env.NAMESPACE }} --name ${{ env.NAMESPACE }} - - - name: Create namespace to run tests - run: | - az aks command invoke --resource-group ${{ env.NAMESPACE }} --name ${{ env.NAMESPACE }} --command "kubectl create ns ${{ env.NAMESPACE }}" - - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # 7.1.0 - name: Install Python - with: - python-version: '3.x' - - - name: Executing deploy action for pod - uses: ./ - with: - namespace: ${{ env.NAMESPACE }} - images: nginx:1.14.2 - manifests: | - test/integration/manifests/test.yml - test/integration/manifests/test2.yml - action: deploy - private-cluster: true - resource-group: ${{ env.NAMESPACE }} - name: ${{ env.NAMESPACE }} - - - name: Checking if deployments and services were created - run: | - python test/integration/k8s-deploy-test.py private=${{ env.NAMESPACE }} namespace=${{ env.NAMESPACE }} kind=Deployment name=nginx-deployment containerName=nginx:1.14.2 labels=app:nginx,workflow:actions.github.com-k8s-deploy,workflowFriendlyName:Cluster_Integration_Tests_-_private_cluster selectorLabels=app:nginx - python test/integration/k8s-deploy-test.py private=${{ env.NAMESPACE }} namespace=${{ env.NAMESPACE }} kind=Service name=nginx-service labels=workflow:actions.github.com-k8s-deploy,workflowFriendlyName:Cluster_Integration_Tests_-_private_cluster selectorLabels=app:nginx - - python test/integration/k8s-deploy-test.py private=${{ env.NAMESPACE }} namespace=${{ env.NAMESPACE }} kind=Deployment name=nginx-deployment2 containerName=nginx:1.14.2 labels=app:nginx2,workflow:actions.github.com-k8s-deploy,workflowFriendlyName:Cluster_Integration_Tests_-_private_cluster selectorLabels=app:nginx2 - python test/integration/k8s-deploy-test.py private=${{ env.NAMESPACE }} namespace=${{ env.NAMESPACE }} kind=Service name=nginx-service2 labels=workflow:actions.github.com-k8s-deploy,workflowFriendlyName:Cluster_Integration_Tests_-_private_cluster selectorLabels=app:nginx2 - - - name: Clean up AKS cluster - if: ${{ always() }} - run: | - echo "deleting AKS cluster and resource group" - az aks delete --yes --resource-group ${{ env.NAMESPACE }} --name ${{ env.NAMESPACE }} - az group delete --resource-group ${{ env.NAMESPACE }} --yes diff --git a/test/integration/k8s-deploy-test.py b/test/integration/k8s-deploy-test.py index 20c0ce7a5..cf07e5d47 100644 --- a/test/integration/k8s-deploy-test.py +++ b/test/integration/k8s-deploy-test.py @@ -21,6 +21,7 @@ ingressServicesKey = "ingressServices" tsServicesKey = "tsServices" privateKey = "private" +resourceGroupKey = "resourceGroup" def parseArgs(sysArgs): @@ -211,7 +212,12 @@ def main(): try: if privateKey in parsedArgs: uniqueName = parsedArgs[privateKey] - azPrefix = f"az aks command invoke --resource-group {uniqueName} --name {uniqueName} --command " + # The resource group defaults to the cluster's unique name for + # backward compatibility (older workflows named the RG and cluster + # identically). When the RG is shared/pre-created and differs from + # the cluster name, pass it explicitly via resourceGroup=. + resourceGroup = parsedArgs.get(resourceGroupKey, uniqueName) + azPrefix = f"az aks command invoke --resource-group {resourceGroup} --name {uniqueName} --command " cmd = azPrefix + "'" + cmd + "'" outputString = os.popen(cmd).read() successExit = "exitcode=0" From ab97d98f3dfd953496e637424c05ad54d8c75bf8 Mon Sep 17 00:00:00 2001 From: Tatsat Mishra Date: Sun, 20 Sep 2026 07:58:02 +1200 Subject: [PATCH 2/3] fix(ci): gate private-cluster tests on release candidates --- .../1es-integration-tests-private.yml | 119 ++++++++++++++---- 1 file changed, 94 insertions(+), 25 deletions(-) diff --git a/.azure-pipelines/1es-integration-tests-private.yml b/.azure-pipelines/1es-integration-tests-private.yml index 751f04aef..d3b9e22fd 100644 --- a/.azure-pipelines/1es-integration-tests-private.yml +++ b/.azure-pipelines/1es-integration-tests-private.yml @@ -1,8 +1,12 @@ -# Private-cluster integration test (1ES pipeline). +# Private-cluster release gate (1ES pipeline). # -# Runs the k8s-deploy action against a real private AKS cluster. Lives in Azure -# DevOps (not GitHub Actions) because GitHub-repo Federated Identity Credentials -# are being removed; auth uses a governed WIF service connection instead. +# Runs the k8s-deploy action against a real private AKS cluster before a release +# is published. The internal release orchestrator must queue this pipeline for +# the exact releases/vX.Y.Z commit, pass that SHA as releaseCandidateCommit, and +# depend on this run succeeding before it tags or publishes the release. +# +# This pipeline intentionally has no CI or PR trigger. It uses a governed WIF +# service connection and must never execute code supplied by a pull request. # # The node24 JS action is invoked as `node lib/index.js` with inputs supplied via # INPUT_* env vars. There is no action.yml default injection here, so keep INPUT_* @@ -10,17 +14,19 @@ # must be set or the action throws. # # The pipeline does not create/delete the resource group (it must already exist); -# it only creates and deletes a per-build cluster inside it. +# it only creates and deletes a per-build cluster inside it. Azure DevOps pipeline +# UI triggers must also remain disabled because UI settings override this YAML. +# The service connection must use a custom role scoped to the shared resource +# group; do not grant subscription-wide Contributor or Owner. -trigger: - branches: - include: - - main +parameters: + - name: releaseCandidateCommit + displayName: Exact release candidate commit SHA + type: string + default: '' -pr: - branches: - include: - - releases/* +trigger: none +pr: none resources: repositories: @@ -33,6 +39,7 @@ variables: serviceConnection: k8s-deploy-intg-test-svc-conn resourceGroup: k8s-deploy-intg-rg location: eastus2 + kubectlVersion: 1.34.1 clusterName: test-$(Build.BuildId) namespace: test-$(Build.BuildId) workflowFriendlyName: k8s-deploy-integration-tests-private @@ -65,13 +72,47 @@ extends: versionSpec: '24.x' - script: | - rm -rf node_modules/ - npm install + set -euo pipefail + + if [[ ! "$BUILD_SOURCEBRANCH" =~ ^refs/heads/releases/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "##vso[task.logissue type=error]This release gate only accepts releases/vX.Y.Z branches; received $BUILD_SOURCEBRANCH" + exit 1 + fi + + if [[ ! "$EXPECTED_RELEASE_COMMIT" =~ ^[0-9a-fA-F]{40}$ ]]; then + echo "##vso[task.logissue type=error]releaseCandidateCommit must be a full 40-character commit SHA" + exit 1 + fi + + checked_out_commit="$(git rev-parse HEAD)" + if [[ "$BUILD_SOURCEVERSION" != "$EXPECTED_RELEASE_COMMIT" || "$checked_out_commit" != "$EXPECTED_RELEASE_COMMIT" ]]; then + echo "##vso[task.logissue type=error]Release candidate mismatch: requested $EXPECTED_RELEASE_COMMIT, source $BUILD_SOURCEVERSION, checked out $checked_out_commit" + exit 1 + fi + + expected_version="${BUILD_SOURCEBRANCH#refs/heads/releases/v}" + actual_version="$(node -p "require('./package.json').version")" + if [[ "$actual_version" != "$expected_version" ]]; then + echo "##vso[task.logissue type=error]Release branch version $expected_version does not match package.json version $actual_version" + exit 1 + fi + + echo "##vso[task.setvariable variable=releaseCandidateValidated]true" + displayName: Validate release candidate + env: + EXPECTED_RELEASE_COMMIT: ${{ parameters.releaseCandidateCommit }} + + - script: npm ci displayName: Install dependencies - script: npm run build displayName: Build + - task: KubectlInstaller@0 + displayName: Install kubectl + inputs: + kubectlVersion: $(kubectlVersion) + - task: AzureCLI@2 displayName: Create private AKS cluster and set context inputs: @@ -79,10 +120,17 @@ extends: scriptType: bash scriptLocation: inlineScript inlineScript: | - set -e + set -euo pipefail set +x # RG must already exist; do not run `az group create`. - az aks create --name $(clusterName) --resource-group $(resourceGroup) --enable-private-cluster --generate-ssh-keys + az aks create \ + --name $(clusterName) \ + --resource-group $(resourceGroup) \ + --location $(location) \ + --enable-private-cluster \ + --generate-ssh-keys \ + --node-count 1 \ + --tags purpose=k8s-deploy-private-integration build-id=$(Build.BuildId) az aks get-credentials --resource-group $(resourceGroup) --name $(clusterName) - task: AzureCLI@2 @@ -92,7 +140,7 @@ extends: scriptType: bash scriptLocation: inlineScript inlineScript: | - set -e + set -euo pipefail az aks command invoke --resource-group $(resourceGroup) --name $(clusterName) --command "kubectl create ns $(namespace)" - task: UsePythonVersion@0 @@ -107,7 +155,7 @@ extends: scriptType: bash scriptLocation: inlineScript inlineScript: | - set -e + set -euo pipefail node lib/index.js env: KUBECONFIG: $(HOME)/.kube/config @@ -125,8 +173,24 @@ extends: INPUT_RESOURCE-GROUP: $(resourceGroup) INPUT_NAME: $(clusterName) INPUT_RESOURCE-TYPE: Microsoft.ContainerService/managedClusters - # Required by the action; also the workflowFriendlyName label. - GITHUB_WORKFLOW: $(workflowFriendlyName) + INPUT_PULL-IMAGES: 'false' + INPUT_ANNOTATE-RESOURCES: 'true' + INPUT_ANNOTATE-NAMESPACE: 'true' + INPUT_FORCE: 'false' + INPUT_SERVER-SIDE: 'false' + INPUT_TIMEOUT: 10m + # Emulate the GitHub Action context used in annotations and + # manifest path containment. A workflow-style path avoids an + # unnecessary GitHub API request for its display name. + GITHUB_WORKSPACE: $(Build.Repository.LocalPath) + RUNNER_TEMP: $(Agent.TempDirectory) + GITHUB_REPOSITORY: Azure/k8s-deploy + GITHUB_SHA: $(Build.SourceVersion) + GITHUB_REF: $(Build.SourceBranch) + GITHUB_RUN_ID: $(Build.BuildId) + GITHUB_JOB: run_integration_test + GITHUB_ACTOR: $(Build.RequestedFor) + GITHUB_WORKFLOW: .github/workflows/$(workflowFriendlyName) - task: AzureCLI@2 displayName: Checking if deployments and services were created @@ -135,7 +199,7 @@ extends: scriptType: bash scriptLocation: inlineScript inlineScript: | - set -e + set -euo pipefail python test/integration/k8s-deploy-test.py private=$(clusterName) resourceGroup=$(resourceGroup) namespace=$(namespace) kind=Deployment name=nginx-deployment containerName=nginx:1.14.2 labels=app:nginx,workflow:actions.github.com-k8s-deploy,workflowFriendlyName:$(workflowFriendlyName) selectorLabels=app:nginx python test/integration/k8s-deploy-test.py private=$(clusterName) resourceGroup=$(resourceGroup) namespace=$(namespace) kind=Service name=nginx-service labels=workflow:actions.github.com-k8s-deploy,workflowFriendlyName:$(workflowFriendlyName) selectorLabels=app:nginx @@ -144,12 +208,17 @@ extends: - task: AzureCLI@2 displayName: Clean up AKS cluster - condition: always() + condition: and(always(), eq(variables['releaseCandidateValidated'], 'true')) inputs: azureSubscription: $(serviceConnection) scriptType: bash scriptLocation: inlineScript inlineScript: | + set -euo pipefail # Delete only the cluster; the shared RG persists. - echo "deleting AKS cluster $(clusterName)" - az aks delete --yes --resource-group $(resourceGroup) --name $(clusterName) || true + if az aks show --resource-group $(resourceGroup) --name $(clusterName) >/dev/null 2>&1; then + echo "deleting AKS cluster $(clusterName)" + az aks delete --yes --resource-group $(resourceGroup) --name $(clusterName) + else + echo "AKS cluster $(clusterName) was not created; nothing to delete" + fi From 796a47b521e42c4c632daa080dd5b101c03bfff0 Mon Sep 17 00:00:00 2001 From: Suneha Bose Date: Mon, 23 Nov 2026 14:37:03 -0800 Subject: [PATCH 3/3] fix: isolate private-cluster release candidates --- .../1es-integration-tests-private.yml | 76 +++--- .../scripts/checkout-release-candidate.sh | 45 ++++ .../scripts/cleanup-private-cluster.sh | 17 ++ .../tests/test_private_cluster_pipeline.py | 223 ++++++++++++++++++ .github/workflows/unit-tests.yml | 2 + docs/private-cluster-release-gate.md | 139 +++++++++++ 6 files changed, 458 insertions(+), 44 deletions(-) create mode 100644 .azure-pipelines/scripts/checkout-release-candidate.sh create mode 100644 .azure-pipelines/scripts/cleanup-private-cluster.sh create mode 100644 .azure-pipelines/tests/test_private_cluster_pipeline.py create mode 100644 docs/private-cluster-release-gate.md diff --git a/.azure-pipelines/1es-integration-tests-private.yml b/.azure-pipelines/1es-integration-tests-private.yml index d3b9e22fd..6931b9043 100644 --- a/.azure-pipelines/1es-integration-tests-private.yml +++ b/.azure-pipelines/1es-integration-tests-private.yml @@ -2,8 +2,9 @@ # # Runs the k8s-deploy action against a real private AKS cluster before a release # is published. The internal release orchestrator must queue this pipeline for -# the exact releases/vX.Y.Z commit, pass that SHA as releaseCandidateCommit, and -# depend on this run succeeding before it tags or publishes the release. +# a reviewed pipeline-definition revision, pass the release branch and exact +# candidate SHA, and wait for success before it tags or publishes the release. +# The candidate is checked out separately; its pipeline YAML is never loaded. # # This pipeline intentionally has no CI or PR trigger. It uses a governed WIF # service connection and must never execute code supplied by a pull request. @@ -20,6 +21,10 @@ # group; do not grant subscription-wide Contributor or Owner. parameters: + - name: releaseCandidateBranch + displayName: Release candidate branch (releases/vX.Y.Z) + type: string + default: '' - name: releaseCandidateCommit displayName: Exact release candidate commit SHA type: string @@ -66,47 +71,32 @@ extends: displayName: Run Private Cluster Integration Tests timeoutInMinutes: 60 steps: + - checkout: self + clean: true + persistCredentials: false + - task: NodeTool@0 displayName: Install Node.js inputs: versionSpec: '24.x' - - script: | - set -euo pipefail - - if [[ ! "$BUILD_SOURCEBRANCH" =~ ^refs/heads/releases/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "##vso[task.logissue type=error]This release gate only accepts releases/vX.Y.Z branches; received $BUILD_SOURCEBRANCH" - exit 1 - fi - - if [[ ! "$EXPECTED_RELEASE_COMMIT" =~ ^[0-9a-fA-F]{40}$ ]]; then - echo "##vso[task.logissue type=error]releaseCandidateCommit must be a full 40-character commit SHA" - exit 1 - fi - - checked_out_commit="$(git rev-parse HEAD)" - if [[ "$BUILD_SOURCEVERSION" != "$EXPECTED_RELEASE_COMMIT" || "$checked_out_commit" != "$EXPECTED_RELEASE_COMMIT" ]]; then - echo "##vso[task.logissue type=error]Release candidate mismatch: requested $EXPECTED_RELEASE_COMMIT, source $BUILD_SOURCEVERSION, checked out $checked_out_commit" - exit 1 - fi - - expected_version="${BUILD_SOURCEBRANCH#refs/heads/releases/v}" - actual_version="$(node -p "require('./package.json').version")" - if [[ "$actual_version" != "$expected_version" ]]; then - echo "##vso[task.logissue type=error]Release branch version $expected_version does not match package.json version $actual_version" - exit 1 - fi - - echo "##vso[task.setvariable variable=releaseCandidateValidated]true" - displayName: Validate release candidate + - script: bash "$(Build.SourcesDirectory)/.azure-pipelines/scripts/checkout-release-candidate.sh" + displayName: Check out and validate release candidate env: - EXPECTED_RELEASE_COMMIT: ${{ parameters.releaseCandidateCommit }} + RELEASE_CANDIDATE_BRANCH: ${{ parameters.releaseCandidateBranch }} + RELEASE_CANDIDATE_COMMIT: ${{ parameters.releaseCandidateCommit }} - script: npm ci displayName: Install dependencies + workingDirectory: $(releaseCandidateDirectory) - - script: npm run build - displayName: Build + - script: | + set -euo pipefail + git ls-files --error-unmatch lib/index.js >/dev/null + test -f lib/index.js + git diff --exit-code HEAD -- lib/index.js + displayName: Verify prepared release bundle + workingDirectory: $(releaseCandidateDirectory) - task: KubectlInstaller@0 displayName: Install kubectl @@ -154,6 +144,7 @@ extends: azureSubscription: $(serviceConnection) scriptType: bash scriptLocation: inlineScript + workingDirectory: $(releaseCandidateDirectory) inlineScript: | set -euo pipefail node lib/index.js @@ -182,11 +173,11 @@ extends: # Emulate the GitHub Action context used in annotations and # manifest path containment. A workflow-style path avoids an # unnecessary GitHub API request for its display name. - GITHUB_WORKSPACE: $(Build.Repository.LocalPath) + GITHUB_WORKSPACE: $(releaseCandidateDirectory) RUNNER_TEMP: $(Agent.TempDirectory) GITHUB_REPOSITORY: Azure/k8s-deploy - GITHUB_SHA: $(Build.SourceVersion) - GITHUB_REF: $(Build.SourceBranch) + GITHUB_SHA: ${{ parameters.releaseCandidateCommit }} + GITHUB_REF: refs/heads/${{ parameters.releaseCandidateBranch }} GITHUB_RUN_ID: $(Build.BuildId) GITHUB_JOB: run_integration_test GITHUB_ACTOR: $(Build.RequestedFor) @@ -198,6 +189,7 @@ extends: azureSubscription: $(serviceConnection) scriptType: bash scriptLocation: inlineScript + workingDirectory: $(releaseCandidateDirectory) inlineScript: | set -euo pipefail python test/integration/k8s-deploy-test.py private=$(clusterName) resourceGroup=$(resourceGroup) namespace=$(namespace) kind=Deployment name=nginx-deployment containerName=nginx:1.14.2 labels=app:nginx,workflow:actions.github.com-k8s-deploy,workflowFriendlyName:$(workflowFriendlyName) selectorLabels=app:nginx @@ -214,11 +206,7 @@ extends: scriptType: bash scriptLocation: inlineScript inlineScript: | - set -euo pipefail - # Delete only the cluster; the shared RG persists. - if az aks show --resource-group $(resourceGroup) --name $(clusterName) >/dev/null 2>&1; then - echo "deleting AKS cluster $(clusterName)" - az aks delete --yes --resource-group $(resourceGroup) --name $(clusterName) - else - echo "AKS cluster $(clusterName) was not created; nothing to delete" - fi + bash "$(Build.SourcesDirectory)/.azure-pipelines/scripts/cleanup-private-cluster.sh" + env: + RESOURCE_GROUP: $(resourceGroup) + CLUSTER_NAME: $(clusterName) diff --git a/.azure-pipelines/scripts/checkout-release-candidate.sh b/.azure-pipelines/scripts/checkout-release-candidate.sh new file mode 100644 index 000000000..53ced6faf --- /dev/null +++ b/.azure-pipelines/scripts/checkout-release-candidate.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail + +: "${RELEASE_CANDIDATE_BRANCH:?releaseCandidateBranch must be set}" +: "${RELEASE_CANDIDATE_COMMIT:?releaseCandidateCommit must be set}" +: "${AGENT_TEMPDIRECTORY:?AGENT_TEMPDIRECTORY must be set}" + +if [[ ! "$RELEASE_CANDIDATE_BRANCH" =~ ^releases/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "##vso[task.logissue type=error]releaseCandidateBranch must match releases/vX.Y.Z" + exit 1 +fi + +if [[ ! "$RELEASE_CANDIDATE_COMMIT" =~ ^[0-9a-f]{40}$ ]]; then + echo "##vso[task.logissue type=error]releaseCandidateCommit must be a full lowercase commit SHA" + exit 1 +fi + +# Keep candidate files separate from the trusted pipeline definition and scripts. +candidate_directory=$(mktemp -d "$AGENT_TEMPDIRECTORY/k8s-deploy-candidate.XXXXXX") +git -C "$candidate_directory" init --quiet +git -C "$candidate_directory" remote add origin https://github.com/Azure/k8s-deploy.git +git -C "$candidate_directory" fetch --no-tags --depth=1 origin "refs/heads/$RELEASE_CANDIDATE_BRANCH" + +fetched_commit=$(git -C "$candidate_directory" rev-parse FETCH_HEAD) +if [[ "$fetched_commit" != "$RELEASE_CANDIDATE_COMMIT" ]]; then + echo "##vso[task.logissue type=error]Release branch no longer matches the requested candidate commit" + exit 1 +fi + +git -C "$candidate_directory" checkout --detach --quiet "$RELEASE_CANDIDATE_COMMIT" +checked_out_commit=$(git -C "$candidate_directory" rev-parse HEAD) +if [[ "$checked_out_commit" != "$RELEASE_CANDIDATE_COMMIT" ]]; then + echo "##vso[task.logissue type=error]Checked-out commit does not match the requested candidate commit" + exit 1 +fi + +expected_version="${RELEASE_CANDIDATE_BRANCH#releases/v}" +actual_version=$(node -p "require(process.argv[1]).version" "$candidate_directory/package.json") +if [[ "$actual_version" != "$expected_version" ]]; then + echo "##vso[task.logissue type=error]Release branch version does not match package.json" + exit 1 +fi + +echo "##vso[task.setvariable variable=releaseCandidateDirectory]$candidate_directory" +echo "##vso[task.setvariable variable=releaseCandidateValidated]true" diff --git a/.azure-pipelines/scripts/cleanup-private-cluster.sh b/.azure-pipelines/scripts/cleanup-private-cluster.sh new file mode 100644 index 000000000..e5867f0e9 --- /dev/null +++ b/.azure-pipelines/scripts/cleanup-private-cluster.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail + +: "${RESOURCE_GROUP:?RESOURCE_GROUP must be set}" +: "${CLUSTER_NAME:?CLUSTER_NAME must be set}" + +# A successful empty listing means absence; lookup errors must remain failures. +existing_cluster=$(az aks list --resource-group "$RESOURCE_GROUP" \ + --query "[?name=='${CLUSTER_NAME}'].name" --output tsv) + +if [[ -z "$existing_cluster" ]]; then + echo "AKS cluster $CLUSTER_NAME was not created; nothing to delete" + exit 0 +fi + +echo "deleting AKS cluster $CLUSTER_NAME" +az aks delete --yes --resource-group "$RESOURCE_GROUP" --name "$CLUSTER_NAME" diff --git a/.azure-pipelines/tests/test_private_cluster_pipeline.py b/.azure-pipelines/tests/test_private_cluster_pipeline.py new file mode 100644 index 000000000..7ad889f4b --- /dev/null +++ b/.azure-pipelines/tests/test_private_cluster_pipeline.py @@ -0,0 +1,223 @@ +import json +import os +from pathlib import Path +import subprocess +import tempfile +import textwrap +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/cleanup-private-cluster.sh" +CHECKOUT_SCRIPT = SCRIPT.with_name("checkout-release-candidate.sh") + + +class CandidateCheckoutTests(unittest.TestCase): + def run_checkout( + self, branch="releases/v7.0.2", commit="2" * 40, + fetched_commit="2" * 40, checked_out_commit="2" * 40, + version="7.0.2", fetch_exit=0, + ): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + log = root / "calls.jsonl" + stub = root / "git" + stub.write_text( + "#!/usr/bin/env python3\n" + "import json, os, sys\n" + "args = sys.argv[3:]\n" + "with open(os.environ['CHECKOUT_TEST_LOG'], 'a') as log:\n" + " log.write(json.dumps(['git', *args]) + '\\n')\n" + "if args[0] == 'fetch':\n" + " sys.exit(int(os.environ['FETCH_EXIT']))\n" + "if args == ['rev-parse', 'FETCH_HEAD']:\n" + " print(os.environ['FETCHED_COMMIT'])\n" + "elif args == ['rev-parse', 'HEAD']:\n" + " print(os.environ['CHECKED_OUT_COMMIT'])\n" + "elif args[0] not in ['init', 'remote', 'checkout']:\n" + " sys.exit(99)\n" + ) + stub.chmod(0o755) + node = root / "node" + node.write_text( + "#!/usr/bin/env python3\n" + "import json, os\n" + "with open(os.environ['CHECKOUT_TEST_LOG'], 'a') as log:\n" + " log.write(json.dumps(['node']) + '\\n')\n" + "print(os.environ['CANDIDATE_VERSION'])\n" + ) + node.chmod(0o755) + result = subprocess.run( + ["bash", str(CHECKOUT_SCRIPT)], cwd=root, + env={ + **os.environ, + "PATH": str(root) + os.pathsep + os.environ["PATH"], + "AGENT_TEMPDIRECTORY": str(root), + "BUILD_SOURCEBRANCH": "refs/heads/main", + "BUILD_SOURCEVERSION": "1" * 40, + "RELEASE_CANDIDATE_BRANCH": branch, + "RELEASE_CANDIDATE_COMMIT": commit, + "CHECKOUT_TEST_LOG": str(log), + "FETCHED_COMMIT": fetched_commit, + "CHECKED_OUT_COMMIT": checked_out_commit, + "CANDIDATE_VERSION": version, + "FETCH_EXIT": str(fetch_exit), + }, + capture_output=True, text=True, timeout=10, + ) + calls = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] + return result, calls + + def test_trusted_definition_can_test_a_different_release_commit(self): + result, calls = self.run_checkout() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("variable=releaseCandidateDirectory]", result.stdout) + self.assertIn("variable=releaseCandidateValidated]true", result.stdout) + self.assertIn( + ["git", "remote", "add", "origin", "https://github.com/Azure/k8s-deploy.git"], + calls, + ) + self.assertIn( + ["git", "fetch", "--no-tags", "--depth=1", "origin", "refs/heads/releases/v7.0.2"], + calls, + ) + self.assertIn(["git", "checkout", "--detach", "--quiet", "2" * 40], calls) + + def test_invalid_candidate_is_rejected_before_fetch(self): + for kwargs in [{"branch": ""}, {"branch": "refs/pull/549/merge"}, {"commit": "2222222"}]: + with self.subTest(kwargs=kwargs): + result, calls = self.run_checkout(**kwargs) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(calls, []) + self.assertNotIn("variable=releaseCandidateValidated]true", result.stdout) + + def test_moved_branch_is_rejected_before_checkout(self): + result, calls = self.run_checkout(fetched_commit="3" * 40) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(any(call[:2] == ["git", "checkout"] for call in calls)) + self.assertNotIn(["node"], calls) + self.assertNotIn("variable=releaseCandidateValidated]true", result.stdout) + + def test_checked_out_commit_must_match_candidate(self): + result, calls = self.run_checkout(checked_out_commit="3" * 40) + self.assertNotEqual(result.returncode, 0) + self.assertNotIn(["node"], calls) + self.assertNotIn("variable=releaseCandidateValidated]true", result.stdout) + + def test_candidate_package_version_must_match_branch(self): + result, _ = self.run_checkout(version="7.0.1") + self.assertNotEqual(result.returncode, 0) + self.assertNotIn("variable=releaseCandidateValidated]true", result.stdout) + + def test_fetch_failure_is_reported(self): + result, calls = self.run_checkout(fetch_exit=1) + self.assertNotEqual(result.returncode, 0) + self.assertNotIn(["node"], calls) + self.assertNotIn("variable=releaseCandidateValidated]true", result.stdout) + + +class CleanupTests(unittest.TestCase): + def run_cleanup(self, listing="", lookup_exit=0, delete_exit=0): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + stub = root / "az" + log = root / "calls.jsonl" + stub.write_text( + "#!/usr/bin/env python3\n" + "import json, os, sys\n" + "with open(os.environ['AZ_TEST_LOG'], 'a') as log:\n" + " log.write(json.dumps(sys.argv[1:]) + '\\n')\n" + "if sys.argv[1:3] == ['aks', 'list']:\n" + " print(os.environ['AZ_TEST_LISTING'])\n" + " if os.environ['AZ_TEST_LOOKUP_EXIT'] != '0':\n" + " print('AuthorizationFailed', file=sys.stderr)\n" + " sys.exit(int(os.environ['AZ_TEST_LOOKUP_EXIT']))\n" + "if sys.argv[1:3] == ['aks', 'delete']:\n" + " sys.exit(int(os.environ['AZ_TEST_DELETE_EXIT']))\n" + "sys.exit(99)\n" + ) + stub.chmod(0o755) + env = { + **os.environ, + "PATH": str(root) + os.pathsep + os.environ["PATH"], + "RESOURCE_GROUP": "shared-integration-rg", + "CLUSTER_NAME": "test-123", + "AZ_TEST_LOG": str(log), + "AZ_TEST_LISTING": listing, + "AZ_TEST_LOOKUP_EXIT": str(lookup_exit), + "AZ_TEST_DELETE_EXIT": str(delete_exit), + } + result = subprocess.run( + ["bash", str(SCRIPT)], env=env, capture_output=True, text=True, timeout=10 + ) + return result, [json.loads(line) for line in log.read_text().splitlines()] + + def test_absent_cluster_is_not_deleted(self): + result, calls = self.run_cleanup() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(calls), 1) + self.assertIn("nothing to delete", result.stdout) + + def test_lookup_failure_is_not_treated_as_absence(self): + result, calls = self.run_cleanup(lookup_exit=1) + self.assertNotEqual(result.returncode, 0) + self.assertIn("AuthorizationFailed", result.stderr) + self.assertNotIn("nothing to delete", result.stdout) + self.assertEqual(len(calls), 1) + + def test_only_the_per_build_cluster_is_deleted(self): + result, calls = self.run_cleanup(listing="test-123") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + calls[1], + [ + "aks", "delete", "--yes", "--resource-group", "shared-integration-rg", + "--name", "test-123", + ], + ) + self.assertEqual(len(calls), 2) + + def test_deletion_failure_is_reported(self): + result, _ = self.run_cleanup(listing="test-123", delete_exit=1) + self.assertNotEqual(result.returncode, 0) + + +class PreparedBundleTests(unittest.TestCase): + def verify_bundle(self, tracked=True, modified=False): + pipeline = (SCRIPT.parents[1] / "1es-integration-tests-private.yml").read_text() + script = pipeline.split("displayName: Verify prepared release bundle", 1)[0] + script = textwrap.dedent(script.rsplit("- script: |\n", 1)[1]) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "lib").mkdir() + (root / "lib/index.js").write_text("fixture bundle\n") + git = root / "git" + git.write_text( + "#!/bin/sh\n" + "if [ \"$1\" = ls-files ]; then exit \"$TRACKED_EXIT\"; fi\n" + "if [ \"$1\" = diff ]; then exit \"$MODIFIED_EXIT\"; fi\n" + "exit 99\n" + ) + git.chmod(0o755) + return subprocess.run( + ["bash", "-c", script], cwd=root, + env={ + **os.environ, + "PATH": str(root) + os.pathsep + os.environ["PATH"], + "TRACKED_EXIT": "0" if tracked else "1", + "MODIFIED_EXIT": "1" if modified else "0", + }, + capture_output=True, text=True, timeout=10, + ) + + def test_committed_unchanged_bundle_is_accepted(self): + result = self.verify_bundle() + self.assertEqual(result.returncode, 0, result.stderr) + + def test_untracked_or_modified_bundle_is_rejected(self): + for kwargs in [{"tracked": False}, {"modified": True}]: + with self.subTest(kwargs=kwargs): + self.assertNotEqual(self.verify_bundle(**kwargs).returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 20f21170a..f4a88b04f 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -18,3 +18,5 @@ jobs: - run: | npm install npm test + - name: Test private-cluster pipeline without Azure access + run: python3 -B -m unittest discover -s .azure-pipelines/tests diff --git a/docs/private-cluster-release-gate.md b/docs/private-cluster-release-gate.md new file mode 100644 index 000000000..0475cbccd --- /dev/null +++ b/docs/private-cluster-release-gate.md @@ -0,0 +1,139 @@ +# Private-cluster release gate + +## Migration state + +The existing release entry point and its pinned automatic publisher remain +unchanged. The pipeline and companion hooks are local migration work, not an +operational release gate. Keep the current publisher until the complete gated +replacement is ready, then switch the caller in one coordinated update. Do not +deploy an intermediate preparation-only workflow. + +The companion adds optional preparation outputs and a new gated publisher for +stable `vX.Y.Z` releases. Existing callers keep their current publication, tag, +and prerelease behavior unless they explicitly adopt the new flow. The stricter +commit/check validation and guarded tag replacement belong to that opt-in path. + +The 1ES test definition keeps `trigger: none` and `pr: none`. The bridge must load +an approved pipeline-definition revision, not the candidate's pipeline YAML. +That definition checks out the candidate separately from the canonical +`Azure/k8s-deploy` repository. It validates the release ref, full candidate SHA, +checked-out commit, and package version before Azure-authenticated tasks. These +are consistency checks, not authorization to execute arbitrary GitHub code with +the service connection. The test verifies that `lib/index.js` is committed and +unchanged, then executes that prepared bundle without rebuilding it. + +## Definition and candidate revisions + +The pipeline uses two independent revisions: + +| Revision | Purpose | +| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Approved definition revision | Supplies the pipeline YAML and its checkout/cleanup scripts through `checkout: self`. Azure DevOps must enforce the approved source and queue permissions outside this YAML. | +| Built release-candidate revision | Supplies the action bundle and integration fixtures in a separate temporary directory. Its pipeline YAML and cleanup script are not used. | + +`Build.SourceBranch` and `Build.SourceVersion` identify the definition revision, +not the candidate. Pass `releaseCandidateBranch`, such as `releases/v7.0.2`, and +the full `releaseCandidateCommit` separately. The candidate checkout must match +both inputs. Action execution, bundle verification, and test fixtures use that +checkout; cleanup stays in the trusted definition checkout. `GITHUB_SHA`, +`GITHUB_REF`, and `GITHUB_WORKSPACE` describe the candidate being tested. + +For example, the trusted bridge's +[Run Pipeline request](https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/run-pipeline?view=azure-devops-rest-7.1) +must select the reviewed definition revision independently: + +```json +{ + "resources": { + "repositories": { + "self": { + "refName": "refs/heads/main", + "version": "" + } + } + }, + "templateParameters": { + "releaseCandidateBranch": "releases/v7.0.2", + "releaseCandidateCommit": "" + } +} +``` + +This is a request-shape example, not an installed bridge or authorization policy. +The approved definition must include the pipeline and both scripts under +`.azure-pipelines/scripts/`. Do not select the release branch as `self`. + +## Required activation flow + +```text +Approved release change + | +Prepare built release commit + | +Trusted bridge queues a reviewed definition with that candidate + | +Private-cluster test and cleanup + | +Bridge reports its result to GitHub for the same SHA + | +Gated publisher checks App, result, SHA, and refs + | +Publish version and major tags at the tested SHA +``` + +1. Review and publish the companion changes to `Azure/action-release-workflows`. + Pin the reviewed commit, not a mutable branch, when enabling the caller. +2. Prepare the coordinated caller update using `release_js_project.yaml` with + `prepareOnly: true`. Consume its `commit` output, which identifies the final + build commit rather than the original commit on `main`. Do not activate this + preparation step without the automatic test trigger and gated publisher. +3. Assign an owner to the trusted bridge. It must verify the approved preparation + run and source revision, select a governed definition revision, and pass the + preparation outputs as `releaseCandidateBranch` and `releaseCandidateCommit`. + The definition revision and the candidate SHA need not be the same commit. +4. Configure the bridge's GitHub App to report a check named + `1ES private-cluster release gate` on that commit. Restrict its repository + access and permissions to the intended integration. Configure the trusted + numeric App ID outside candidate-controlled code. +5. Connect preparation, automatic bridge notification, and a caller of + `publish_js_project.yaml` in the same cutover. Pass the returned branch, + commit, version, and release notes, plus the check name and App ID. Grant the + publishing job `contents: write` and `checks: read`. Missing App configuration, + failed/cancelled tests, missing results, and changed refs must prevent + publication. The shared README contains the repository-hook example; the + approved bridge supplies the automatic test-trigger integration. +6. Confirm Azure DevOps UI CI/PR overrides are disabled and the privileged + pipeline is not attached to PR validation. Restrict queue permissions and + enforce the trusted definition/service-connection checks outside this YAML. + Authorize the service connection only for the approved pipeline, not all + pipelines. Confirm the pool, images, and 1ES template are authorized. +7. Have the Azure owners verify the pre-created shared resource group and the + least-privilege role/identity assignments needed by the service connection. + Do not grant subscription-wide Contributor or Owner simply to bypass a + provisioning failure. +8. Run an approved candidate end to end. Demonstrate that wrong-commit, + failed-test, cancelled-test, missing-result, and moved-ref cases cannot + publish. Confirm the temporary cluster is deleted and the shared resource + group remains. Only then replace the existing publisher with the complete + automatic flow. + +Bridge ownership, Azure DevOps configuration, the trusted reporting App, and a +live gated run are still pending. No bridge or privileged trigger is installed +by this repository change. The intended result is automatic preparation, a +successful private-cluster test, and automatic publication of that same commit, +without a temporary shutdown of publishing. + +## Cleanup + +The cleanup task lists the named cluster within the shared resource group. Only +a successful empty result means there is nothing to delete. Lookup and deletion +errors remain failures, so authorization or network problems cannot be reported +as successful cleanup. It deletes only the per-build cluster, never the resource +group. The existing candidate-validation condition still applies. + +Run the checkout, bundle, and cleanup tests without network access, Azure +credentials, or cluster operations: + +```bash +python3 -B -m unittest discover -s .azure-pipelines/tests -v +```