From 662b6ec9a8a1c0aa2d1a72212c1842757ec8ec69 Mon Sep 17 00:00:00 2001 From: danielpmchugh <3751810+danielpmchugh@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:19:03 +0000 Subject: [PATCH] Sync core from 94394ed23b70 Signed-off-by: danielpmchugh <3751810+danielpmchugh@users.noreply.github.com> --- .github/scripts/actionlint.sh | 2 +- .github/scripts/gitleaks.sh | 2 +- .github/scripts/install-helm-kind.sh | 4 +- .github/scripts/install-iac-tools.sh | 36 + .github/workflows/templates.yml | 39 ++ deploy/azure-container-apps/bicepconfig.json | 40 ++ .../key-vault-access.bicep | 37 ++ deploy/azure-container-apps/main.bicep | 629 ++++++++++++++++++ .../main.example.bicepparam | 10 + deploy/azure-container-apps/test-template.sh | 388 +++++++++++ docs/deploy/README.md | 2 +- docs/deploy/azure-container-apps.md | 78 +++ docs/operations.md | 2 +- .../Modules/ICustomerSiteModule.cs | 6 +- .../SqliteFormNonceStore.cs | 2 +- .../CoreImageTests.cs | 23 +- .../CoreWorkflowTests.cs | 75 ++- .../DockerfileCheck.cs | 167 +++++ .../AdminSiteHardeningTests.cs | 2 +- .../ConformanceVectorLoaderTests.cs | 2 +- .../Packmoat.Host.Tests/ReviewFixesM2Tests.cs | 2 +- .../Packmoat.Host.Tests/ReviewFixesM5Tests.cs | 2 +- .../Contracts/FormNonceStoreContract.cs | 19 + .../Contracts/StoreContract.cs | 9 + .../Contracts/contract-tests.txt | 1 + .../MasterKeyCheckTests.cs | 2 +- .../Postgres/PostgresMigratorTests.cs | 4 +- .../Postgres/PostgresPlumbingTests.cs | 46 ++ .../Postgres/PostgresServerTests.cs | 2 +- .../Postgres/PostgresSqlEngine.cs | 13 + .../ReviewFixesM5Tests.cs | 2 +- .../SqlitePoolsCollectionTests.cs | 177 +++++ dotnet/tests/Shared/TempLeakGuard.cs | 13 +- dotnet/tests/Shared/TempLeakGuardTests.cs | 32 +- 34 files changed, 1830 insertions(+), 40 deletions(-) create mode 100755 .github/scripts/install-iac-tools.sh create mode 100644 .github/workflows/templates.yml create mode 100644 deploy/azure-container-apps/bicepconfig.json create mode 100644 deploy/azure-container-apps/key-vault-access.bicep create mode 100644 deploy/azure-container-apps/main.bicep create mode 100644 deploy/azure-container-apps/main.example.bicepparam create mode 100755 deploy/azure-container-apps/test-template.sh create mode 100644 dotnet/tests/Packmoat.Architecture.Tests/DockerfileCheck.cs create mode 100644 dotnet/tests/Packmoat.Infrastructure.Tests/SqlitePoolsCollectionTests.cs diff --git a/.github/scripts/actionlint.sh b/.github/scripts/actionlint.sh index 20b4f8f..fdabb36 100755 --- a/.github/scripts/actionlint.sh +++ b/.github/scripts/actionlint.sh @@ -9,7 +9,7 @@ sha256=8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 dir="$(mktemp -d)" trap 'rm -rf "$dir"' EXIT -curl -fsSL --retry 3 -o "$dir/actionlint.tar.gz" \ +curl -fsSL --retry 6 --retry-all-errors --retry-max-time 120 -o "$dir/actionlint.tar.gz" \ "https://github.com/rhysd/actionlint/releases/download/v${version}/actionlint_${version}_linux_amd64.tar.gz" echo "${sha256} $dir/actionlint.tar.gz" | sha256sum --check --strict - tar -xzf "$dir/actionlint.tar.gz" -C "$dir" actionlint diff --git a/.github/scripts/gitleaks.sh b/.github/scripts/gitleaks.sh index 4d79c76..3a2c3ba 100755 --- a/.github/scripts/gitleaks.sh +++ b/.github/scripts/gitleaks.sh @@ -12,7 +12,7 @@ sha256=551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb dir="$(mktemp -d)" trap 'rm -rf "$dir"' EXIT -curl -fsSL --retry 3 -o "$dir/gitleaks.tar.gz" \ +curl -fsSL --retry 6 --retry-all-errors --retry-max-time 120 -o "$dir/gitleaks.tar.gz" \ "https://github.com/gitleaks/gitleaks/releases/download/v${version}/gitleaks_${version}_linux_x64.tar.gz" echo "${sha256} $dir/gitleaks.tar.gz" | sha256sum --check --strict - tar -xzf "$dir/gitleaks.tar.gz" -C "$dir" gitleaks diff --git a/.github/scripts/install-helm-kind.sh b/.github/scripts/install-helm-kind.sh index 1ba503c..9a2864e 100755 --- a/.github/scripts/install-helm-kind.sh +++ b/.github/scripts/install-helm-kind.sh @@ -31,12 +31,12 @@ check() { if command -v sha256sum > /dev/null; then sha256sum --check --strict - dir="$(mktemp -d)" trap 'rm -rf "$dir"' EXIT -curl -fsSL --retry 3 -o "$dir/helm.tar.gz" "https://get.helm.sh/helm-v${helm_version}-${platform}.tar.gz" +curl -fsSL --retry 6 --retry-all-errors --retry-max-time 120 -o "$dir/helm.tar.gz" "https://get.helm.sh/helm-v${helm_version}-${platform}.tar.gz" echo "${helm_sha256} $dir/helm.tar.gz" | check tar -xzf "$dir/helm.tar.gz" -C "$dir" "${platform}/helm" install -m 755 "$dir/${platform}/helm" "$bin/helm" -curl -fsSL --retry 3 -o "$dir/kind" "https://github.com/kubernetes-sigs/kind/releases/download/v${kind_version}/kind-${platform}" +curl -fsSL --retry 6 --retry-all-errors --retry-max-time 120 -o "$dir/kind" "https://github.com/kubernetes-sigs/kind/releases/download/v${kind_version}/kind-${platform}" echo "${kind_sha256} $dir/kind" | check install -m 755 "$dir/kind" "$bin/kind" diff --git a/.github/scripts/install-iac-tools.sh b/.github/scripts/install-iac-tools.sh new file mode 100755 index 0000000..c46ae7a --- /dev/null +++ b/.github/scripts/install-iac-tools.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Install the pinned tools the platform templates are checked with into a folder, each checked by sha256 before it is used: the versions +# and checksums are pinned here, never read from the download site at run time. Today that is bicep (deploy/azure-container-apps). +# Usage: install-iac-tools.sh (Linux x86-64, or macOS on Apple silicon for a local run; then put the folder on PATH) +set -euo pipefail + +bicep_version=0.49.2 + +case "$(uname -s)-$(uname -m)" in + Linux-x86_64) + bicep_asset=bicep-linux-x64 + bicep_sha256=0ab9de90c2493f206f8281bae74f9ee2d5ed3605548dab1adf41fef185e1f7c5 + ;; + Darwin-arm64) + bicep_asset=bicep-osx-arm64 + bicep_sha256=8ae74a6cf9cbba0cb220c40cf0e955f98d59df950afab07c21b7bcb78c9c5d68 + ;; + *) echo "install-iac-tools.sh: no pinned checksums for $(uname -s)-$(uname -m)" >&2; exit 1 ;; +esac + +if [[ $# -ne 1 ]]; then echo "Usage: install-iac-tools.sh " >&2; exit 2; fi +bin="$1" +mkdir -p "$bin" + +# sha256sum on Linux, shasum on macOS. +check() { if command -v sha256sum > /dev/null; then sha256sum --check --strict -; else shasum -a 256 --check --strict -; fi; } + +dir="$(mktemp -d)" +trap 'rm -rf "$dir"' EXIT + +# bicep is one self-contained binary, published on the project's GitHub releases. +curl -fsSL --retry 6 --retry-all-errors --retry-max-time 120 -o "$dir/bicep" "https://github.com/Azure/bicep/releases/download/v${bicep_version}/${bicep_asset}" +echo "${bicep_sha256} $dir/bicep" | check +install -m 755 "$dir/bicep" "$bin/bicep" + +"$bin/bicep" --version diff --git a/.github/workflows/templates.yml b/.github/workflows/templates.yml new file mode 100644 index 0000000..fd55021 --- /dev/null +++ b/.github/workflows/templates.yml @@ -0,0 +1,39 @@ +# The platform templates, checked offline: no cloud account, no sign-in, nothing deployed. Today the Azure Container Apps template +# (deploy/azure-container-apps): bicep lint and build, then its tests (jq on the compiled template and on the resources bicep snapshot +# predicts, and what it refuses), then each test's mutation, which it must catch. bicep is a pinned release, checked by sha256 +# (.github/scripts/install-iac-tools.sh); jq is the runner's own. No secrets, a read-only token. Actions are pinned to full commit SHAs. +# Every path here is relative to this repository's root. +name: templates + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: templates-${{ github.ref }} + cancel-in-progress: true + +jobs: + templates: + name: templates + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install the pinned bicep (checked by sha256) + run: | + .github/scripts/install-iac-tools.sh "$RUNNER_TEMP/bin" + echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH" + - name: Azure Container Apps template tests (bicep lint and build; what it makes and what it refuses) + run: deploy/azure-container-apps/test-template.sh + - name: Each Azure Container Apps template test catches its mutation + env: + MUTATION_JOBS: "4" + run: deploy/azure-container-apps/test-template.sh --mutations diff --git a/deploy/azure-container-apps/bicepconfig.json b/deploy/azure-container-apps/bicepconfig.json new file mode 100644 index 0000000..b3a04ab --- /dev/null +++ b/deploy/azure-container-apps/bicepconfig.json @@ -0,0 +1,40 @@ +{ + "analyzers": { + "core": { + "enabled": true, + "rules": { + "secure-parameter-default": { "level": "error" }, + "secure-params-in-nested-deploy": { "level": "error" }, + "outputs-should-not-contain-secrets": { "level": "error" }, + "use-secure-value-for-secure-inputs": { "level": "error" }, + "protect-commandtoexecute-secrets": { "level": "error" }, + "no-hardcoded-env-urls": { "level": "error" }, + "no-unused-params": { "level": "error" }, + "no-unused-vars": { "level": "error" }, + "no-unused-existing-resources": { "level": "error" }, + "no-unnecessary-dependson": { "level": "error" }, + "use-resource-id-functions": { "level": "error" }, + "use-stable-resource-identifiers": { "level": "error" }, + "use-stable-vm-image": { "level": "error" }, + "simplify-interpolation": { "level": "error" }, + "prefer-interpolation": { "level": "error" }, + "secure-secrets-in-params": { "level": "error" }, + "use-recent-api-versions": { "level": "warning" }, + "use-resource-symbol-reference": { "level": "error" }, + "no-deployments-resources": { "level": "error" }, + "no-loc-expr-outside-params": { "level": "error" }, + "explicit-values-for-loc-params": { "level": "error" }, + "max-outputs": { "level": "error" }, + "max-params": { "level": "error" }, + "max-resources": { "level": "error" }, + "max-variables": { "level": "error" }, + "adminusername-should-not-be-literal": { "level": "error" }, + "artifacts-parameters": { "level": "error" }, + "decompiler-cleanup": { "level": "error" }, + "nested-deployment-template-scoping": { "level": "error" }, + "use-parent-property": { "level": "error" }, + "what-if-short-circuiting": { "level": "error" } + } + } + } +} diff --git a/deploy/azure-container-apps/key-vault-access.bicep b/deploy/azure-container-apps/key-vault-access.bicep new file mode 100644 index 0000000..d6d2851 --- /dev/null +++ b/deploy/azure-container-apps/key-vault-access.bicep @@ -0,0 +1,37 @@ +// Key Vault Secrets User on named secrets of one existing vault, for one identity: it may read those secrets' values, and no other secret +// in the vault. Deployed to the vault's own resource group by main.bicep. The vault must use Azure role-based access control, and each +// secret must exist before the deploy. + +@description('The existing Key Vault.') +param keyVaultName string + +@description('The identity\'s resource id, known before the deploy, which names the role assignments.') +param identityId string + +@description('The identity\'s principal (object) id.') +param principalId string + +@description('The names of the secrets the identity may read.') +param secretNames array + +// Key Vault Secrets User, a built-in role: read secrets' values. Not Key Vault Administrator, not Secrets Officer. +var builtInRoleGuid = '4633458b-17de-408a-b874-0445c86b69e6' + +resource vault 'Microsoft.KeyVault/vaults@2025-05-01' existing = { + name: keyVaultName +} + +resource secrets 'Microsoft.KeyVault/vaults/secrets@2025-05-01' existing = [for s in secretNames: { + parent: vault + name: s +}] + +resource secretsUser 'Microsoft.Authorization/roleAssignments@2022-04-01' = [for (s, i) in secretNames: { + name: guid(secrets[i].id, identityId, builtInRoleGuid) + scope: secrets[i] + properties: { + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', builtInRoleGuid) + principalId: principalId + principalType: 'ServicePrincipal' + } +}] diff --git a/deploy/azure-container-apps/main.bicep b/deploy/azure-container-apps/main.bicep new file mode 100644 index 0000000..b518c4f --- /dev/null +++ b/deploy/azure-container-apps/main.bicep @@ -0,0 +1,629 @@ +// Packmoat on Azure Container Apps: the server as a Container App, on an existing PostgreSQL 17 database, with its secrets read from an +// existing Key Vault. docs/deploy/azure-container-apps.md explains each parameter and the steps around a deploy. +// +// What it makes, in the resource group it is deployed to: a virtual network with one subnet for a workload-profiles Container Apps +// environment; a Log Analytics workspace for its logs; two user-assigned identities, the server's and the job's, each given Key Vault +// Secrets User on its own secrets only (one secret at a time, never the vault), and given to no code in the containers; the Container App +// (the server); and a Container Apps job, run by hand, that migrates the database. A NAT gateway and a static public IP for +// a fixed outbound address only when enableNatGateway is true (off by default: it costs money every month). +// +// No secret is ever a parameter, an output or a plain environment value: each one is a Key Vault secret its resource's identity reads, mounted as a +// file under /run/secrets/packmoat, and the server reads it through the setting's _FILE form. Only the job gets the owner role's +// connection string; the server gets only the app role's. deploy/azure-container-apps/test-template.sh checks all of this on the +// compiled template. + +targetScope = 'resourceGroup' + +@description('The Azure region. Default: the resource group\'s.') +param location string = resourceGroup().location + +@description('The prefix of every resource\'s name: lower-case letters, digits and hyphens, starting with a letter.') +@minLength(2) +@maxLength(20) +param name string = 'packmoat' + +@description('The server\'s image, by digest: ghcr.io/packmoat/packmoat-core@sha256:, or your registry\'s copy. Set it after running the migrate job with the same image.') +param serviceImage string + +@description('The migrate job\'s image, by digest. On an upgrade: set this to the new image, run the job, then set serviceImage to it.') +param jobImage string + +@description('PACKMOAT_HOSTS: the feed host names, separated by spaces. Never the admin or customer site host (set those in settings).') +param hosts string + +@description('The PostgreSQL app role the server signs in as. The migrate job grants it its rows (db migrate --grant-to).') +@minLength(1) +@maxLength(63) +param appRoleName string = 'packmoat_app' + +@description('The existing Key Vault that holds the secrets. It must use Azure role-based access control, not access policies.') +param keyVaultName string + +@description('The existing Key Vault\'s resource group. Default: this one.') +param keyVaultResourceGroup string = resourceGroup().name + +@description('The Key Vault secret that holds the master key (packmoat-admin keygen). Mounted for the server only.') +param masterKeySecretName string = 'packmoat-master-key' + +@description('The Key Vault secret that holds the app role\'s connection string. Mounted for the server only.') +param appDatabaseSecretName string = 'packmoat-db-app' + +@description('The Key Vault secret that holds the owner role\'s connection string. Mounted for the migrate job only.') +param ownerDatabaseSecretName string = 'packmoat-db-owner' + +@description('Optional: the Key Vault secret that holds the database server\'s certificate authority (PEM), mounted as /run/secrets/packmoat/db-ca.crt for the server and the job, for Root Certificate= in the connection strings. Empty: none.') +param databaseCaSecretName string = '' + +@description('Optional: the Key Vault secret that holds the customer site\'s sign-in certificate and key (PEM), mounted as /run/secrets/packmoat/app-signin.pem and named by PACKMOAT_APP_CERT. Empty: none.') +param appCertSecretName string = '' + +@description('Optional secret settings, read through their _FILE form: the setting\'s name to the Key Vault secret\'s name, such as {"PACKMOAT_ADMIN_CLIENT_SECRET": "packmoat-admin-client-secret"}. Server only.') +param fileSettings object = {} + +@description('Other settings that are not secret, such as {"PACKMOAT_ADMIN_HOST": "admin.example.com"}. PACKMOAT_ settings only: a setting this template sets, a secret setting and a _FILE setting are refused.') +param settings object = {} + +@description('The fewest copies of the server. On PostgreSQL more than one may run.') +@minValue(1) +@maxValue(30) +param minReplicas int = 1 + +@description('The most copies of the server. Budget database connections for it (docs/operations.md).') +@minValue(1) +@maxValue(30) +param maxReplicas int = 1 + +@description('CPU cores for each copy of the server.') +param cpu string = '0.5' + +@description('Memory for each copy of the server, matching cpu (0.5 cores: 1Gi).') +param memory string = '1Gi' + +@description('A NAT gateway and a static public IP, so that outbound traffic comes from one fixed address: needed only when your customers allowlist the address Packmoat reads their feeds from. It costs money every month.') +param enableNatGateway bool = false + +@description('The virtual network\'s address space.') +param vnetAddressPrefix string = '10.40.0.0/16' + +@description('The Container Apps environment\'s subnet (at least /27), inside vnetAddressPrefix. The platform\'s proxy runs in it, so it is PACKMOAT_TRUSTED_PROXIES.') +param environmentSubnetPrefix string = '10.40.0.0/24' + +@description('How many days the Log Analytics workspace keeps logs.') +@minValue(30) +@maxValue(730) +param logRetentionDays int = 30 + +// --- Checks on the parameters. fail() stops the deploy, naming the parameter, never its value. + +// An image by digest only: a tag can move between the job and the server, so the job could migrate for one release and the server run another. +var digestPattern = '@sha256:' +var checkedServiceImage = contains(serviceImage, digestPattern) ? serviceImage : fail('serviceImage must name the image by digest (@sha256:).') +var checkedJobImage = contains(jobImage, digestPattern) ? jobImage : fail('jobImage must name the image by digest (@sha256:).') +var checkedMaxReplicas = maxReplicas >= minReplicas ? maxReplicas : fail('maxReplicas must be at least minReplicas.') +// A role name, as the job passes it on the command line: lower-case letters, digits and underscores, starting with a letter or underscore. +var roleNameCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789_' +var checkedAppRoleName = empty(filter(range(0, length(appRoleName)), i => !contains(roleNameCharacters, substring(appRoleName, i, 1)))) && !contains('0123456789', first(appRoleName)) + ? appRoleName + : fail('appRoleName must be a PostgreSQL role name: lower-case letters, digits and underscores, starting with a letter or underscore.') + +// The settings this template sets itself, and the secret ones, which may only ever be files from Key Vault. +var templateSettings = [ + 'PACKMOAT_DB_ENGINE' + 'PACKMOAT_COOKIE_KEYS' + 'PACKMOAT_BACKGROUND_JOBS' + 'PORT' + 'PACKMOAT_HOSTS' + 'PACKMOAT_TRUSTED_PROXIES' + 'PACKMOAT_APP_CERT' + 'PACKMOAT_DB_SINGLE_ROLE' +] +var secretSettingNames = [ + 'PACKMOAT_MASTER_KEY' + 'PACKMOAT_DB' + 'PACKMOAT_ADMIN_CLIENT_SECRET' +] +var refusedSettings = filter(objectKeys(settings), k => contains(templateSettings, k) || contains(secretSettingNames, k) || endsWith(k, '_FILE') || !startsWith(k, 'PACKMOAT_')) +var checkedSettings = empty(refusedSettings) ? settings : fail('settings may not set ${join(refusedSettings, ', ')}: the template sets it, it is a secret (use fileSettings), or it is not a PACKMOAT_ setting.') +var refusedFileSettings = filter(objectKeys(fileSettings), k => contains(templateSettings, k) || contains(['PACKMOAT_MASTER_KEY', 'PACKMOAT_DB'], k) || endsWith(k, '_FILE') || !startsWith(k, 'PACKMOAT_')) +var checkedFileSettings = empty(refusedFileSettings) ? fileSettings : fail('fileSettings may not set ${join(refusedFileSettings, ', ')}: the template sets it, or it is not a PACKMOAT_ setting.') + +// The owner's connection string is the job's alone: no other secret parameter may name its secret. +var serverSecretNames = concat([masterKeySecretName, appDatabaseSecretName, databaseCaSecretName, appCertSecretName], map(items(fileSettings), s => s.value)) +var checkedOwnerSecretName = contains(serverSecretNames, ownerDatabaseSecretName) + ? fail('ownerDatabaseSecretName may not also be the server\'s secret (masterKeySecretName, appDatabaseSecretName, databaseCaSecretName, appCertSecretName or fileSettings).') + : ownerDatabaseSecretName + +// --- Where the secrets are mounted, in every container that has them. +var secretsPath = '/run/secrets/packmoat' +var secretsVolume = 'secrets' + +var environmentSubnetName = 'container-apps' + +// --- The network, and the optional fixed outbound address. + +resource outboundIp 'Microsoft.Network/publicIPAddresses@2025-05-01' = if (enableNatGateway) { + name: '${name}-outbound-ip' + location: location + sku: { + name: 'Standard' + } + properties: { + publicIPAllocationMethod: 'Static' + publicIPAddressVersion: 'IPv4' + } +} + +resource natGateway 'Microsoft.Network/natGateways@2025-05-01' = if (enableNatGateway) { + name: '${name}-nat' + location: location + sku: { + name: 'Standard' + } + properties: { + idleTimeoutInMinutes: 4 + publicIpAddresses: [ + { + id: outboundIp.id + } + ] + } +} + +resource vnet 'Microsoft.Network/virtualNetworks@2025-05-01' = { + name: '${name}-vnet' + location: location + properties: { + addressSpace: { + addressPrefixes: [ + vnetAddressPrefix + ] + } + subnets: [ + { + name: environmentSubnetName + properties: { + addressPrefix: environmentSubnetPrefix + // A workload-profiles environment needs its subnet delegated to it. + delegations: [ + { + name: 'container-apps' + properties: { + serviceName: 'Microsoft.App/environments' + } + } + ] + natGateway: enableNatGateway ? { id: natGateway.id } : null + } + } + ] + } +} + +// --- Logs. + +resource logs 'Microsoft.OperationalInsights/workspaces@2025-02-01' = { + name: '${name}-logs' + location: location + properties: { + sku: { + name: 'PerGB2018' + } + retentionInDays: logRetentionDays + } +} + +// --- The identities that read the secrets, and their roles on those secrets in the existing vault. + +// Two identities, each able to read only its own secrets: the server's cannot read the owner's connection string, the job's cannot read the +// master key or the app role's. +resource serviceIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30' = { + name: '${name}-identity' + location: location +} + +resource jobIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2024-11-30' = { + name: '${name}-migrate-identity' + location: location +} + +var caSecretNames = empty(databaseCaSecretName) ? [] : [databaseCaSecretName] +var appCertSecretNames = empty(appCertSecretName) ? [] : [appCertSecretName] + +module serviceVaultAccess 'key-vault-access.bicep' = { + name: '${name}-key-vault-access' + scope: resourceGroup(keyVaultResourceGroup) + params: { + keyVaultName: keyVaultName + identityId: serviceIdentity.id + principalId: serviceIdentity.properties.principalId + secretNames: union([masterKeySecretName, appDatabaseSecretName], caSecretNames, appCertSecretNames, map(items(checkedFileSettings), s => s.value)) + } +} + +module jobVaultAccess 'key-vault-access.bicep' = { + name: '${name}-migrate-key-vault-access' + scope: resourceGroup(keyVaultResourceGroup) + params: { + keyVaultName: keyVaultName + identityId: jobIdentity.id + principalId: jobIdentity.properties.principalId + secretNames: union([checkedOwnerSecretName], caSecretNames) + } +} + +// A Key Vault reference: the secret's latest version, read by the identity. Container Apps reads it again about every 30 minutes. +var vaultSecrets = 'https://${keyVaultName}${environment().suffixes.keyvaultDns}/secrets/' + +// --- The Container Apps environment. + +resource appEnvironment 'Microsoft.App/managedEnvironments@2025-07-01' = { + name: '${name}-env' + location: location + properties: { + appLogsConfiguration: { + destination: 'log-analytics' + logAnalyticsConfiguration: { + customerId: logs.properties.customerId + sharedKey: logs.listKeys().primarySharedKey + } + } + vnetConfiguration: { + infrastructureSubnetId: resourceId('Microsoft.Network/virtualNetworks/subnets', vnet.name, environmentSubnetName) + internal: false + } + workloadProfiles: [ + { + name: 'Consumption' + workloadProfileType: 'Consumption' + } + ] + zoneRedundant: false + } +} + +// --- The server's secrets and settings. + +// The secrets the server reads: the master key and the app role's connection string, always; the database's certificate authority, the +// customer site's certificate and any fileSettings when given. Never the owner's connection string. +var caSecret = empty(databaseCaSecretName) ? [] : [ + { + name: 'db-ca' + keyVaultUrl: '${vaultSecrets}${databaseCaSecretName}' + identity: serviceIdentity.id + } +] +var jobCaSecret = empty(databaseCaSecretName) ? [] : [ + { + name: 'db-ca' + keyVaultUrl: '${vaultSecrets}${databaseCaSecretName}' + identity: jobIdentity.id + } +] +var caFile = empty(databaseCaSecretName) ? [] : [ + { + secretRef: 'db-ca' + path: 'db-ca.crt' + } +] +var appCertSecret = empty(appCertSecretName) ? [] : [ + { + name: 'app-cert' + keyVaultUrl: '${vaultSecrets}${appCertSecretName}' + identity: serviceIdentity.id + } +] +var appCertFile = empty(appCertSecretName) ? [] : [ + { + secretRef: 'app-cert' + path: 'app-signin.pem' + } +] +var appCertEnv = empty(appCertSecretName) ? [] : [ + { + name: 'PACKMOAT_APP_CERT' + value: '${secretsPath}/app-signin.pem' + } +] +// fileSettings: each setting's secret is named after it (PACKMOAT_ADMIN_CLIENT_SECRET: packmoat-admin-client-secret), as a file of that name. +var extraSecrets = [for s in items(checkedFileSettings): { + name: toLower(replace(s.key, '_', '-')) + keyVaultUrl: '${vaultSecrets}${s.value}' + identity: serviceIdentity.id +}] +var extraFiles = [for s in items(checkedFileSettings): { + secretRef: toLower(replace(s.key, '_', '-')) + path: toLower(replace(s.key, '_', '-')) +}] +var extraFileEnv = [for s in items(checkedFileSettings): { + name: '${s.key}_FILE' + value: '${secretsPath}/${toLower(replace(s.key, '_', '-'))}' +}] +var extraEnv = [for s in items(checkedSettings): { + name: s.key + value: string(s.value) +}] + +var serviceSecrets = [ + { + name: 'master-key' + keyVaultUrl: '${vaultSecrets}${masterKeySecretName}' + identity: serviceIdentity.id + } + { + name: 'db-app' + keyVaultUrl: '${vaultSecrets}${appDatabaseSecretName}' + identity: serviceIdentity.id + } +] +var serviceFiles = [ + { + secretRef: 'master-key' + path: 'master-key' + } + { + secretRef: 'db-app' + path: 'db-app' + } +] +// The server's own settings. Every secret is a _FILE path; none is a value. +var serviceEnv = [ + { + name: 'PACKMOAT_DB_ENGINE' + value: 'postgres' + } + { + name: 'PACKMOAT_COOKIE_KEYS' + value: 'database' + } + { + name: 'PACKMOAT_BACKGROUND_JOBS' + value: 'on' + } + { + name: 'PORT' + value: '8080' + } + { + name: 'PACKMOAT_HOSTS' + value: hosts + } + { + // The platform's proxy (Envoy) runs in the environment's subnet. + name: 'PACKMOAT_TRUSTED_PROXIES' + value: environmentSubnetPrefix + } + { + name: 'PACKMOAT_MASTER_KEY_FILE' + value: '${secretsPath}/master-key' + } + { + name: 'PACKMOAT_DB_FILE' + value: '${secretsPath}/db-app' + } +] + +// The server answers its health checks only for a host name it serves, localhost or 127.0.0.1, so each probe sends Host: localhost. +var probeHost = [ + { + name: 'Host' + value: 'localhost' + } +] + +// --- The server. + +resource app 'Microsoft.App/containerApps@2025-07-01' = { + name: name + location: location + identity: { + type: 'UserAssigned' + userAssignedIdentities: { + '${serviceIdentity.id}': {} + } + } + properties: { + environmentId: appEnvironment.id + workloadProfileName: 'Consumption' + configuration: { + // The identity reads the Key Vault references only: the server's own code gets no token for it. + identitySettings: [ + { + identity: serviceIdentity.id + lifecycle: 'None' + } + ] + // One revision at a time: a new one takes the traffic once its copies are ready (/readyz), and only then does the old one stop. + activeRevisionsMode: 'Single' + ingress: { + external: true + targetPort: 8080 + transport: 'auto' + allowInsecure: false + traffic: [ + { + latestRevision: true + weight: 100 + } + ] + } + secrets: concat(serviceSecrets, caSecret, appCertSecret, extraSecrets) + } + template: { + containers: [ + { + name: 'packmoat' + image: checkedServiceImage + resources: { + cpu: json(cpu) + memory: memory + } + env: concat(serviceEnv, appCertEnv, extraFileEnv, extraEnv) + volumeMounts: [ + { + volumeName: secretsVolume + mountPath: secretsPath + } + ] + probes: [ + { + type: 'Liveness' + httpGet: { + path: '/healthz' + port: 8080 + httpHeaders: probeHost + } + timeoutSeconds: 5 + periodSeconds: 10 + failureThreshold: 3 + } + { + type: 'Readiness' + httpGet: { + path: '/readyz' + port: 8080 + httpHeaders: probeHost + } + timeoutSeconds: 5 + periodSeconds: 10 + failureThreshold: 3 + } + { + // A new copy is started only once the database is at its schema (the migrate job ran first): until then /readyz answers + // 503, the new revision never becomes ready and the old one keeps serving. Container Apps allows at most 10 failures. + type: 'Startup' + httpGet: { + path: '/readyz' + port: 8080 + httpHeaders: probeHost + } + timeoutSeconds: 5 + periodSeconds: 10 + failureThreshold: 10 + } + ] + } + ] + volumes: [ + { + name: secretsVolume + storageType: 'Secret' + secrets: concat(serviceFiles, caFile, appCertFile, extraFiles) + } + ] + scale: { + minReplicas: minReplicas + maxReplicas: checkedMaxReplicas + } + } + } + dependsOn: [ + serviceVaultAccess + ] +} + +// --- The migrate job: run by hand before each upgrade, with the owner role's connection string, which nothing else gets. + +var jobSecrets = [ + { + name: 'db-owner' + keyVaultUrl: '${vaultSecrets}${checkedOwnerSecretName}' + identity: jobIdentity.id + } +] +var jobFiles = [ + { + secretRef: 'db-owner' + path: 'db-owner' + } +] +var jobEnv = [ + { + name: 'PACKMOAT_DB_ENGINE' + value: 'postgres' + } + { + name: 'PACKMOAT_DB_FILE' + value: '${secretsPath}/db-owner' + } +] + +resource migrate 'Microsoft.App/jobs@2025-07-01' = { + name: '${name}-migrate' + location: location + identity: { + type: 'UserAssigned' + userAssignedIdentities: { + '${jobIdentity.id}': {} + } + } + properties: { + environmentId: appEnvironment.id + workloadProfileName: 'Consumption' + configuration: { + identitySettings: [ + { + identity: jobIdentity.id + lifecycle: 'None' + } + ] + triggerType: 'Manual' + manualTriggerConfig: { + parallelism: 1 + replicaCompletionCount: 1 + } + replicaTimeout: 1800 + replicaRetryLimit: 0 + secrets: concat(jobSecrets, jobCaSecret) + } + template: { + containers: [ + { + name: 'migrate' + image: checkedJobImage + command: [ + 'packmoat-admin' + ] + args: [ + 'db' + 'migrate' + '--grant-to' + checkedAppRoleName + ] + resources: { + cpu: json('0.5') + memory: '1Gi' + } + env: jobEnv + volumeMounts: [ + { + volumeName: secretsVolume + mountPath: secretsPath + } + ] + } + ] + volumes: [ + { + name: secretsVolume + storageType: 'Secret' + secrets: concat(jobFiles, caFile) + } + ] + } + } + dependsOn: [ + jobVaultAccess + ] +} + +@description('The server\'s own address on Container Apps (*.azurecontainerapps.io). Point your host names at it, then add them to the app (docs/deploy/azure-container-apps.md).') +output appFqdn string = app.properties.configuration.ingress.fqdn + +@description('The environment\'s domain verification id, for the asuid TXT record of a custom domain.') +output customDomainVerificationId string = app.properties.customDomainVerificationId + +@description('The fixed outbound address, when enableNatGateway is true; empty otherwise.') +output outboundIpAddress string = enableNatGateway ? outboundIp!.properties.ipAddress : '' + +@description('The migrate job\'s name, for az containerapp job start.') +output migrateJobName string = migrate.name diff --git a/deploy/azure-container-apps/main.example.bicepparam b/deploy/azure-container-apps/main.example.bicepparam new file mode 100644 index 0000000..d2050a0 --- /dev/null +++ b/deploy/azure-container-apps/main.example.bicepparam @@ -0,0 +1,10 @@ +// An example of the parameters: copy it, change each value to yours, and deploy with +// az deployment group create --resource-group --parameters .bicepparam +// It holds no secret, and never may: every secret is a Key Vault secret, named here only by its name. +// deploy/azure-container-apps/test-template.sh also uses it, unchanged, to check the template. +using 'main.bicep' + +param serviceImage = 'ghcr.io/packmoat/packmoat-core@sha256:0000000000000000000000000000000000000000000000000000000000000000' +param jobImage = 'ghcr.io/packmoat/packmoat-core@sha256:0000000000000000000000000000000000000000000000000000000000000000' +param hosts = 'packages.example.com' +param keyVaultName = 'example-packmoat-kv' diff --git a/deploy/azure-container-apps/test-template.sh b/deploy/azure-container-apps/test-template.sh new file mode 100755 index 0000000..b763d31 --- /dev/null +++ b/deploy/azure-container-apps/test-template.sh @@ -0,0 +1,388 @@ +#!/usr/bin/env bash +# The Azure Container Apps template's tests, offline: no Azure sign-in, no cloud resources. bicep lint and bicep build, then checks with +# jq on the compiled template (main.json) and on the resources bicep snapshot predicts for a few sets of parameters (the template's +# expressions evaluated, as a deploy would), and on what the template refuses. +# Needs bicep and jq on PATH (core/.github/scripts/install-iac-tools.sh installs the pinned bicep). +# Usage: deploy/azure-container-apps/test-template.sh the checks; exits 1 when any fails, after running them all +# deploy/azure-container-apps/test-template.sh --mutations each check's mutation: the template changed, in a copy, so that the +# check must fail; exits 1 when a check does not catch its mutation +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +script="$here/$(basename "$0")" +settings_doc="$here/../../docs/operations.md" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +failed=0 + +ok() { echo "ok: $1"; } +bad() { echo "FAIL: $1" >&2; failed=1; } + +# --- Mutations: each one changes one text in a copy of the template, runs the checks on the copy, and needs the named check to fail. +# They run MUTATION_JOBS at a time (default 2). +labels=(); files=(); froms=(); tos=() +# mutation : adds one to the list. +mutation() { labels+=("$1"); files+=("$2"); froms+=("$3"); tos+=("$4"); } +# run_mutation : prints one ok or FAIL line. +run_mutation() { + local label="${labels[$1]}" file="${files[$1]}" from="${froms[$1]}" to="${tos[$1]}" copy="$work/mutant-$1" text before out + cp -R "$here" "$copy" + text="$(cat "$copy/$file")" + if [[ "$text" != *"$from"* ]]; then bad "mutation for \"$label\": $file has no \"$from\" to change"; return 0; fi + # The first occurrence only, as plain text (not ${text/.../...}, whose replacement each bash version reads differently). + before="${text%%"$from"*}" + printf '%s\n' "${before}${to}${text:$(( ${#before} + ${#from} ))}" > "$copy/$file" + out="$("$script" --dir "$copy" --only "$label" 2>&1 || true)" + if grep -Fq -- "FAIL: $label" <<< "$out"; then ok "caught: $label ($(grep -c '^FAIL: ' <<< "$out") checks failed)"; else bad "not caught: $label (mutation: $file \"$from\" -> \"$to\")"; fi +} + +if [[ "${1:-}" == "--mutations" ]]; then + echo "--- each check, with the template changed so that it must fail" + mutation "bicep lint: no errors" main.bicep "output migrateJobName string = migrate.name" \ + "output migrateJobName string = migrate.name +output ownerConnection string = ownerDatabaseSecretName +@secure() +param leaked string = 'x'" + mutation "no parameter is secure (a secret is never a parameter)" main.bicep "param databaseCaSecretName string = ''" "@secure() +param databaseCaSecretName string" + mutation "no parameter is named like a secret value" main.bicep "param hosts string" "param hosts string +param masterKey string = '' +var unusedKey = masterKey +output o string = unusedKey" + mutation "the NAT gateway is off by default" main.bicep "param enableNatGateway bool = false" "param enableNatGateway bool = true" + mutation "by default: no NAT gateway and no public IP" main.bicep "resource natGateway 'Microsoft.Network/natGateways@2025-05-01' = if (enableNatGateway) {" \ + "resource natGateway 'Microsoft.Network/natGateways@2025-05-01' = {" + mutation "with enableNatGateway: the subnet goes out through the NAT gateway" main.bicep "natGateway: enableNatGateway ? { id: natGateway.id } : null" "natGateway: null" + mutation "one copy by default (min and max replicas 1)" main.bicep "param maxReplicas int = 1" "param maxReplicas int = 2" + mutation "the server scales between the replica parameters" main.bicep "minReplicas: minReplicas" "minReplicas: 0" + mutation "liveness probes /healthz" main.bicep "path: '/healthz'" "path: '/readyz'" + mutation "readiness and startup probe /readyz" main.bicep "type: 'Startup' + httpGet: { + path: '/readyz'" "type: 'Startup' + httpGet: { + path: '/healthz'" + mutation "every probe sends Host: localhost on port 8080" main.bicep "value: 'localhost'" "value: 'packages.example.com'" + mutation "the server's settings: postgres, cookie keys in the database, background jobs on, PORT 8080" main.bicep "value: 'database'" "value: 'folder'" + mutation "PACKMOAT_HOSTS and PACKMOAT_TRUSTED_PROXIES (the environment's subnet)" main.bicep "value: environmentSubnetPrefix" "value: vnetAddressPrefix" + mutation "ingress to port 8080, HTTPS only, one revision at a time" main.bicep "activeRevisionsMode: 'Single'" "activeRevisionsMode: 'Multiple'" + mutation "the server runs serviceImage and the job runs jobImage" main.bicep "? jobImage : fail(" "? serviceImage : fail(" + mutation "every secret is a Key Vault reference read by its own resource's identity, never a value" main.bicep "keyVaultUrl: '\${vaultSecrets}\${masterKeySecretName}'" "value: masterKeySecretName" + mutation "no environment value is a secret (no secretRef, no secret setting by value)" main.bicep "value: '\${secretsPath}/db-app'" "secretRef: 'db-app'" + mutation "no secret setting is set by value, in the server or the job" main.bicep "name: 'PACKMOAT_MASTER_KEY_FILE'" "name: 'PACKMOAT_MASTER_KEY'" + mutation "the owner's connection string is the job's only (the server never gets it)" main.bicep "secrets: concat(serviceSecrets, caSecret" "secrets: concat(serviceSecrets, jobSecrets, caSecret" + mutation "the job signs in as the owner, from its file" main.bicep "value: '\${secretsPath}/db-owner'" "value: '\${secretsPath}/db-app'" + mutation "the secrets are files under /run/secrets/packmoat, and each _FILE names one" main.bicep "path: 'master-key'" "path: 'master.key'" + mutation "the job is run by hand and runs packmoat-admin db migrate --grant-to the app role" main.bicep "'--grant-to'" "'--single-role'" + mutation "each identity is Key Vault Secrets User on its own secrets only, never the whole vault" key-vault-access.bicep \ + "var builtInRoleGuid = '4633458b-17de-408a-b874-0445c86b69e6'" "var builtInRoleGuid = '00482a5a-887f-4fb3-b363-3b7fe8e74483'" + mutation "every PACKMOAT_ setting the template names is in docs/operations.md's table" main.bicep "name: 'PACKMOAT_BACKGROUND_JOBS'" "name: 'PACKMOAT_BACKGROUND_JOB'" + mutation "with every option: the CA for both, the site's certificate and file settings for the server only" main.bicep "secrets: concat(jobFiles, caFile)" "secrets: jobFiles" + mutation "refused: a settings entry that is a secret" main.bicep "|| contains(secretSettingNames, k) " "|| empty(secretSettingNames) " + mutation "refused: the service image by tag" main.bicep "var checkedServiceImage = contains(serviceImage, digestPattern)" "var checkedServiceImage = !empty(serviceImage)" + mutation "refused: an app role name that is not one" main.bicep "!contains(roleNameCharacters, substring(appRoleName, i, 1))" "contains(roleNameCharacters, '!')" + mutation "bicep build" main.bicep "targetScope = 'resourceGroup'" "targetScope = 'resourceGroup' +" + mutation "the outputs name no secret" main.bicep "output migrateJobName string = migrate.name" "output migrateJobName string = migrate.name +output ownerSecretName string = ownerDatabaseSecretName" + mutation "by default: the subnet has no NAT gateway, and is delegated to Container Apps" main.bicep "serviceName: 'Microsoft.App/environments'" \ + "serviceName: 'Microsoft.Web/serverFarms'" + mutation "the environment has workload profiles, in the subnet" main.bicep "vnet.name, environmentSubnetName)" "vnet.name, 'other')" + mutation "the server reads the master key and the app role's connection string from files" main.bicep "value: '\${secretsPath}/master-key'" \ + "value: '/data/master-key'" + mutation "the example parameters are accepted" main.example.bicepparam "param jobImage = 'ghcr.io/packmoat/packmoat-core@sha256:" \ + "param jobImage = 'ghcr.io/packmoat/packmoat-core:main' // @sha256:" + mutation "with enableNatGateway: a NAT gateway and one static Standard public IP" main.bicep "publicIPAllocationMethod: 'Static'" \ + "publicIPAllocationMethod: 'Dynamic'" + mutation "with every option: plain settings are passed on, as text" main.bicep "value: string(s.value)" "value: s.key" + mutation "with every option: the replica parameters" main.bicep "maxReplicas: checkedMaxReplicas" "maxReplicas: min(checkedMaxReplicas, minReplicas)" + mutation "refused: the job image by tag" main.bicep "var checkedJobImage = contains(jobImage, digestPattern)" "var checkedJobImage = !empty(jobImage)" + mutation "refused: the database connection string in settings" main.bicep "|| contains(secretSettingNames, k) " "|| empty(secretSettingNames) " + mutation "refused: a _FILE setting in settings" main.bicep "|| endsWith(k, '_FILE') || !startsWith(k, 'PACKMOAT_'))" "|| !startsWith(k, 'PACKMOAT_'))" + mutation "refused: a setting the template sets, in settings" main.bicep "filter(objectKeys(settings), k => contains(templateSettings, k)" \ + "filter(objectKeys(settings), k => empty(templateSettings)" + mutation "refused: the master key in fileSettings (the template mounts it)" main.bicep "contains(['PACKMOAT_MASTER_KEY', 'PACKMOAT_DB'], k)" \ + "contains(['PACKMOAT_DB'], k)" + mutation "refused: maxReplicas under minReplicas" main.bicep "maxReplicas >= minReplicas ?" "maxReplicas >= 0 ?" + mutation "each identity is Key Vault Secrets User on its own secrets only, never the whole vault" key-vault-access.bicep "scope: secrets[i]" "scope: vault" + mutation "each identity may read exactly the secrets its own resource references" main.bicep \ + "union([masterKeySecretName, appDatabaseSecretName]" "union([masterKeySecretName, appDatabaseSecretName, ownerDatabaseSecretName]" + mutation "no token for the containers' code: each identity's lifecycle is None" main.bicep "identity: serviceIdentity.id + lifecycle: 'None'" "identity: serviceIdentity.id + lifecycle: 'All'" + mutation "no token for the containers' code: each identity's lifecycle is None" main.bicep "identity: jobIdentity.id + lifecycle: 'None'" "identity: jobIdentity.id + lifecycle: 'All'" + mutation "no single role: no PACKMOAT_DB_SINGLE_ROLE for the server, no --single-role in the job" main.bicep "'--grant-to'" "'--single-role'" + mutation "refused: the owner's secret is also the master key's" main.bicep "contains(serverSecretNames, ownerDatabaseSecretName)" "empty(serverSecretNames)" + mutation "refused: the owner's secret is also a fileSettings secret" main.bicep "contains(serverSecretNames, ownerDatabaseSecretName)" "empty(serverSecretNames)" + mutation "refused: a setting that is not a PACKMOAT_ one (ASPNETCORE_FORWARDEDHEADERS_ENABLED)" main.bicep "|| !startsWith(k, 'PACKMOAT_'))" "|| empty(k))" + mutation "refused: a setting that is not a PACKMOAT_ one (DOTNET_STARTUP_HOOKS)" main.bicep "|| !startsWith(k, 'PACKMOAT_'))" "|| empty(k))" + mutation "refused: PACKMOAT_DB_SINGLE_ROLE in settings" main.bicep " 'PACKMOAT_DB_SINGLE_ROLE' +]" "]" + mutation "refused: PACKMOAT_DB_SINGLE_ROLE in fileSettings" main.bicep " 'PACKMOAT_DB_SINGLE_ROLE' +]" "]" + mutation "refused: PACKMOAT_HOSTS in fileSettings" main.bicep "filter(objectKeys(fileSettings), k => contains(templateSettings, k)" \ + "filter(objectKeys(fileSettings), k => empty(templateSettings)" + mutation "refused: PACKMOAT_DB_FILE in fileSettings" main.bicep "endsWith(k, '_FILE') || !startsWith(k, 'PACKMOAT_')) +var checkedFileSettings" "!startsWith(k, 'PACKMOAT_')) +var checkedFileSettings" + jobs_at_once="${MUTATION_JOBS:-2}" + for (( start = 0; start < ${#labels[@]}; start += jobs_at_once )); do + for (( i = start; i < start + jobs_at_once && i < ${#labels[@]}; i++ )); do run_mutation "$i" > "$work/result-$i" 2>&1 & done + wait + done + for (( i = 0; i < ${#labels[@]}; i++ )); do + cat "$work/result-$i" + if grep -q '^FAIL: ' "$work/result-$i"; then failed=1; fi + done + if [[ "$failed" -ne 0 ]]; then echo "template mutations: some not caught" >&2; exit 1; fi + echo "template mutations: all caught" + exit 0 +fi + +# --dir --only