:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(integrations): add integration-service for platform secrets (#79462)
Tom Owers61827dd6ee8d
diff --git a/.github/workflows/cd-integration-service-image.yml b/.github/workflows/cd-integration-service-image.ymlnew file mode 100644index 000000000000..d20a900e6bfa--- /dev/null+++ b/.github/workflows/cd-integration-service-image.yml@@ -0,0 +1,115 @@+name: Integration Service Container Image CD++on:+ push:+ branches:+ - master+ paths:+ - 'services/integration-service/**'+ - '.github/workflows/cd-integration-service-image.yml'+ workflow_dispatch:++jobs:+ build:+ name: Build and push container image+ if: |+ github.repository == 'PostHog/posthog' && (+ github.event_name == 'push' ||+ github.event_name == 'workflow_dispatch'+ )+ runs-on: depot-ubuntu-24.04+ timeout-minutes: 30+ permissions:+ contents: read+ packages: write+ id-token: write++ outputs:+ sha: ${{ steps.push.outputs.digest }}++ steps:+ - name: Check out+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ fetch-depth: 2++ - name: Docker meta and registry login+ id: docker-meta+ uses: ./.github/actions/docker-meta+ with:+ image-name: posthog-integration-service+ # Publishes only from the default branch — assume the role and touch ECR only there+ # (a non-default-branch workflow_dispatch builds nothing to push).+ aws-role-to-assume: ${{ vars.AWS_ECR_POSTHOG_MASTER_PUBLISH_IAM_ROLE }}+ push-to-ecr: ${{ github.ref == 'refs/heads/master' }}+ github-token: ${{ secrets.GITHUB_TOKEN }}+ dockerhub-username: ${{ secrets.DOCKERHUB_USER }}+ dockerhub-password: ${{ secrets.DOCKERHUB_TOKEN }}+ push-to-dockerhub: 'false'++ - name: Set up Depot CLI+ uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1++ - name: Build and push container image+ id: push+ uses: depot/build-push-action@5f3b3c2e5a00f0093de47f657aeaefcedff27d18 # v1.17.0+ with:+ project: ${{ vars.INTEGRATION_SERVICE_DEPOT_PROJECT_ID }}+ file: ./services/integration-service/Dockerfile+ buildx-fallback: false+ push: ${{ github.ref == 'refs/heads/master' }}+ tags: ${{ steps.docker-meta.outputs.tags }}+ labels: ${{ steps.docker-meta.outputs.labels }}+ platforms: linux/arm64,linux/amd64+ build-args: COMMIT_HASH=${{ github.sha }}++ deploy:+ name: Trigger integration-service deployment+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ needs: build+ if: github.ref == 'refs/heads/master'+ permissions: {}++ steps:+ - name: Get deployer token+ id: deployer+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1+ with:+ client-id: ${{ secrets.GH_APP_CHARTS_DEPLOYER_APP_ID }}+ private-key: ${{ secrets.GH_APP_CHARTS_DEPLOYER_PRIVATE_KEY }}+ owner: PostHog+ repositories: charts++ - name: Get PR labels+ id: labels+ uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1+ with:+ script: |+ const { data: pulls } = await github.rest.repos.listPullRequestsAssociatedWithCommit({+ owner: context.repo.owner,+ repo: context.repo.repo,+ commit_sha: context.sha,+ });+ const labels = pulls.flatMap(pr => pr.labels.map(l => l.name));+ return JSON.stringify([...new Set(labels)]);++ - name: Trigger integration-service deployment+ uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1+ with:+ token: ${{ steps.deployer.outputs.token }}+ repository: PostHog/charts+ event-type: commit_state_update+ client-payload: |+ {+ "values": {+ "image": {+ "sha": "${{ needs.build.outputs.sha }}"+ }+ },+ "release": "integration-service",+ "commit": ${{ toJson(github.event.head_commit) }},+ "repository": ${{ toJson(github.repository) }},+ "labels": ${{ steps.labels.outputs.result }},+ "timestamp": "${{ github.event.head_commit.timestamp }}"+ }diff --git a/.github/workflows/ci-integration-service.yml b/.github/workflows/ci-integration-service.ymlnew file mode 100644index 000000000000..be36b410adce--- /dev/null+++ b/.github/workflows/ci-integration-service.yml@@ -0,0 +1,93 @@+name: Integration Service CI++# Trigger-level `paths:` rather than the always-fire + in-workflow paths-filter shape+# agent-proxy uses. This whole workflow is skippable — it covers one isolated package with+# no cross-repo coupling — and an unscoped PR subscription spends the shared repo-wide+# dispatch budget (see tools/hogli-commands/.../pr_event_fanout.py). If this ever becomes+# a required status check, it needs the in-workflow filter + always-running gate instead,+# because branch protection treats a never-dispatched check as pending forever.+on:+ push:+ branches:+ - master+ paths:+ - 'services/integration-service/**'+ - '.github/workflows/ci-integration-service.yml'+ pull_request:+ paths:+ - 'services/integration-service/**'+ - '.github/workflows/ci-integration-service.yml'++concurrency:+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ integration-service:+ name: Integration Service checks+ runs-on: ubuntu-latest+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2++ - name: Install pnpm+ uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8++ - name: Set up Node.js+ uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0+ with:+ node-version-file: .nvmrc+ token: ${{ github.token }}++ - name: Get pnpm store path+ id: pnpm-store+ run: echo "path=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT"++ - name: Restore pnpm cache+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3+ with:+ path: ${{ steps.pnpm-store.outputs.path }}+ key: pnpm-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}+ restore-keys: pnpm-${{ runner.os }}-++ # --ignore-scripts: nothing in this package's dependency tree runs code at+ # install time. This service reads every platform integration credential we+ # own, so an install-time script in a transitive package is exactly the+ # supply-chain path worth closing.+ - name: Install dependencies+ run: pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/integration-service...++ - name: Save pnpm cache+ if: github.ref == 'refs/heads/master'+ uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3+ with:+ path: ${{ steps.pnpm-store.outputs.path }}+ key: pnpm-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}++ - name: Typecheck+ working-directory: services/integration-service+ run: pnpm typecheck++ - name: Unit tests+ working-directory: services/integration-service+ run: pnpm test:unit++ # Real Postgres via testcontainers; the ubuntu runner provides Docker.+ - name: Integration tests+ working-directory: services/integration-service+ run: pnpm test:integration++ - name: Lint+ working-directory: services/integration-service+ run: pnpm exec oxlint++ - name: Format check+ working-directory: services/integration-service+ run: pnpm format:check++ - name: Build+ working-directory: services/integration-service+ run: pnpm builddiff --git a/.github/workflows/ci-security.yaml b/.github/workflows/ci-security.yamlindex fb0a1333237c..c1887db035f5 100644--- a/.github/workflows/ci-security.yaml+++ b/.github/workflows/ci-security.yaml@@ -79,6 +79,7 @@ jobs:- 'frontend/**'- 'nodejs/**'- 'services/agent-proxy/**'+ - 'services/integration-service/**'- 'services/mcp/**'- 'services/oauth-proxy/**'- 'services/stripe-app/**'@@ -285,7 +286,7 @@ jobs:--metrics=off \--verbose \--timeout 300 \- frontend/ nodejs/ services/agent-proxy/ services/mcp/ services/oauth-proxy/ services/stripe-app/+ frontend/ nodejs/ services/agent-proxy/ services/integration-service/ services/mcp/ services/oauth-proxy/ services/stripe-app/semgrep-products-frontend:needs: changesdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex bed4b1123b39..ad53899e32a6 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4723,6 +4723,52 @@ importers:specifier: ^3.2.4version: 3.2.6(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])+ services/integration-service:+ dependencies:+ '@hono/node-server':+ specifier: ^2.0.2+ version: 2.0.2([email protected])+ hono:+ specifier: ^4.12.18+ version: 4.12.24+ jose:+ specifier: ^6.0.10+ version: 6.2.3+ pino:+ specifier: ^8.6.0+ version: 8.11.0+ prom-client:+ specifier: ^14.2.0+ version: 14.2.0+ devDependencies:+ '@types/node':+ specifier: ^22.17.2+ version: 22.18.8+ esbuild:+ specifier: ^0.25.11+ version: 0.25.12+ oxfmt:+ specifier: 'catalog:'+ version: 0.57.0+ oxlint:+ specifier: ^1.72.0+ version: 1.72.0+ pino-pretty:+ specifier: ^9.1.0+ version: 9.4.0+ tsx:+ specifier: ^4.20.5+ version: 4.20.5+ typescript:+ specifier: 6.0.3+ version: 6.0.3+ vite-tsconfig-paths:+ specifier: ^5.1.4+ version: 5.1.4([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest:+ specifier: ^3.2.4+ version: 3.2.6(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])+services/mcp:dependencies:'@hono/node-server':@@ -5067,6 +5113,20 @@ packages:resolution: {integrity: sha512-wNZZQQNlJ+hzD49cKdo+PY6rsTDElO8yDImnrI69p2PLBa7QomeUKAJWYp9xnaR38nlHqWhMHZuYLCQ3oSX+xg==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-CEkcQlMOQJCvul60U7wdAOACjtdgFWDsfJI+6wUOGdhGNV2lGbuJpi/R50QLpFG3Tp+sQxa/RmzC3X7KHbhuTA==}+ engines: {node: '>=20.0.0'}+ deprecated: |-+ Deprecated due to Document number parsing bug in JSON, see+ https://github.com/aws/aws-sdk-js-v3/issues/8246. Newer version available.++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-O5otOc1c6UZh5HsHAaPdYBcUUR9HL6mtnKqvc8nxN/CKDGUBUpsdh0q8K04Uz/dd1i0TaGyIQuQNqoO7+ad2TQ==}+ engines: {node: '>=20.0.0'}+ deprecated: |-+ Deprecated due to Document number parsing bug in JSON, see+ https://github.com/aws/aws-sdk-js-v3/issues/8246. Newer version available.+'@aws-sdk/[email protected]':resolution: {integrity: sha512-ThlLhTqX68jvoIVv+pryOdb5coP1cX1/MaTbB9xkGDCbWbsqQcLqzPxuSoW1DCnAAIacmXCWpzUNOB9pv+xXQw==}engines: {node: '>=20.0.0'}@@ -5131,6 +5191,10 @@ packages:resolution: {integrity: sha512-OK3cULuJl6c+RcDZfPpaK5o3deTOnKZbxm7pzhFNGA3fI2hF9yDih17fGRazJzGGWaDVlR9ejZrpDef4DJCEsw==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-Ps/f9USafScb6CSQTRPNMzdKL5x5XRwDIRgFvnuFWfClGZe7/fI7iCFqXdxKjc9LBxP28E7iUgNloGgfgw406w==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-ZkCxaFHN/v30ZLU/F/lok7yNNVwavaAM8IwDVmCAnCvb4bNIueCw40w5iI8DNGMmnRPa+mfp+rM1LIYVSjuMDQ==}engines: {node: '>=20.0.0'}@@ -5239,6 +5303,10 @@ packages:resolution: {integrity: sha512-TsWwKzb/2WHafAY0CE7uXgLj0FmnkBTgfioG9HO+7z/zCPcl1+YU+i7dW4o0y+aFxFgxTMG+ExBQpqT/k2ao8g==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-hEdHT0PBR4fkGxWhwKG5EtEYKnAM7HKkp0vD10ufk4YcXejH4r4q6G/XhPzjUc6Yxo5kBS2vHg7llj4ViR9VTQ==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-cuv5pX55JOlzKC/iLsB5nZ9eUyVgncim3VhhWHZA/KYPh7rLMjOEfZ+xyaE9uLJXGmzOJboFH7+YdTRdIcOgrg==}engines: {node: '>=18.0.0'}@@ -5263,6 +5331,10 @@ packages:resolution: {integrity: sha512-W6hTSOPiSbh4IdTYVxN7xHjpCh0qvfQU1GKGBzGQm0ZEIOaMmWqiDEvFfyGYKmfBvumT8vHKxQRTX0av9omtIg==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-lKekx8bLBXSv4O+cslk9Zfnw2XKSkWBs3uWL5QGhH2ZAQfNS7FE0vcSSN2vD/AhxX54ZTywWxR4STThoeOXlBA==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-I6SxcsvV7yinJZmPgGullFHS0tsTKa7K3jEc5dmyCz8X+kZPfsWNffZmtmnCvWXPqMXWBvK6hVaxwomx79yeHA==}engines: {node: '>=18.0.0'}@@ -5291,6 +5363,10 @@ packages:resolution: {integrity: sha512-43ajd1NF0RMgX5k0hxCNUyEdrtFUsb2aHT2QvpktSC/2Eyb2Jr/JPVqdp0XIoaHWikZJq5tNWSLO6kB5q2eMCA==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-3W6IUtSxFbH6X7Wb7DzGCV5QiFQsd0g8bOfntpmDxQlzBoKWUMBu/JPQR0DwkE+Hpnxd6db1tXbOwdeHddG6cA==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-wmBJqn1DRXnZu3b4EkE6CWnoWMo1ZMvlfkqU5zPz67xx1GMaXlDCchFvKAXMjk4jn/L1O3tKnoFDNsoLV1kgNQ==}engines: {node: '>=18.0.0'}@@ -5359,14 +5435,18 @@ packages:resolution: {integrity: sha512-POaGMcXnozzqBUyJM3HLUZ9GR6OKJWPGJEmhtTnxZXt8B6JcJ/6K3xRJ5H/j8oovVLz8Wg6vFxAHv8lvuASxMg==}engines: {node: '>=20.0.0'}- '@aws-sdk/[email protected]':- resolution: {integrity: sha512-0zJ05ANfYqI6+rGqj8samZBFod0dPPousBjLEqg8WdxSgbMAkRgLyn81lP215Do0rFJ/17LIXwr7q0yK24mP6Q==}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-zKq4HQum8JwDyEuyfuI4bbiAcU0KxP6qy+9PR/IsR92IyE/DaBAikzAS50tjxip4bqIIANpCcG+Yyj6CVhXupg==}engines: {node: '>=20.0.0'}'@aws/[email protected]':resolution: {integrity: sha512-oLvsaPMTBejkkmHhjf09xTgk71mOqyr/409NKhRIL08If7AhVfUsJhVsx386uJaqNd42v9kWamQ9lFbkoC2dYw==}engines: {node: '>=18.0.0'}+ '@aws/[email protected]':+ resolution: {integrity: sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==}+ engines: {node: '>=18.0.0'}+'@babel/[email protected]':resolution: {integrity: sha512-+mORf3ezU3p3qr+82WvJSnQNE1GAYeoCfEv4fik6B5/2cvKZ75AX8oawWQdXtM9MmndooQj15Jr9kelRFWsuRw==}engines: {node: '>=6.9.0'}@@ -11128,6 +11208,10 @@ packages:resolution: {integrity: sha512-I4UhmcTYXBrct03rwzQX1Y/iqQlzVQaPxWjCjula++5EmWq9YGBrx6bbGqluGc1f0XEfhSkiY4jhLgbsJUMKRA==}engines: {node: '>=18.0.0'}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-4fW86pEUOMbrD5nkbyl/tTvPHHWJFbuB2odl6ps9lWfHoXf9HWh3Q/Smh59qH1g7+c/BSZghX6bbUk4gsiMs8A==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-m80d/iicI7DlBDxyQP6Th7BW/ejDGiF0bgI754+tiwK0lgMkcaIBgvwwVc7OFbY4eUzpGtnig52MhPAEJ7iNYg==}engines: {node: '>=18.0.0'}@@ -11216,8 +11300,8 @@ packages:resolution: {integrity: sha512-DfQjxXQnzC5UbCUPeC3Ie8u+rIWZTvuDPAGU/BxzrOGhRvgUanaP68kDZA+jaT3ZI+djOf+4dERGlm9mWfFDrg==}engines: {node: '>=18.0.0'}- '@smithy/[email protected]':- resolution: {integrity: sha512-6A4vdGj7qKNRF16UIcO8HhHjKW27thsxYci+5r/uVRkdcBEkOEiY8OMPuydLX4QHSrJqGHPJzPRwwVTqbLZJhg==}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-I6KLtq3H0qqSuV9vLglfi8puHqzygzWHOnI4z/Rdoo+q50vvo18vBRdPAvvEtcaKROz7Zn6qnPa14kRfPH6PcQ==}engines: {node: '>=18.0.0'}'@smithy/[email protected]':@@ -11232,8 +11316,8 @@ packages:resolution: {integrity: sha512-9YcuJVTOBDjg9LWo23Qp0lTQ3D7fQsQtwle0jVfpbUHy9qBwCEgKuVH4FqFB3VYu0nwdHKiEMA+oXz7oV8X1kw==}engines: {node: '>=18.0.0'}- '@smithy/[email protected]':- resolution: {integrity: sha512-YupL0ZWmFtJexUN2cHzkvvF/b9pKrtAIfT1o7/oY/Ppu8IYeZ+lDPM5vZdQJaSeA132dJCqojjGC9NhXeF71VQ==}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-0JFs3V2y2M9tKW5na/qxe69Zv+uxLMO7QBbhxF/FHu/Gp2NFZAAL9tWl9PU02xxo07pb3G9FTyjNc6D5uZrJIg==}engines: {node: '>=18.0.0'}'@smithy/[email protected]':@@ -20390,10 +20474,6 @@ packages:resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}engines: {node: '>= 6'}- resolution: {integrity: sha512-MuEnA0lbSi7JS8XM+WNJlWZkHAAdm7gETHdFK//Q/mChGyj2akEFtdLZh32jSdkWGbRwCW9pn6g3LWDdDeZnBQ==}- engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}-resolution: {integrity: sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==}engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}@@ -23081,20 +23161,20 @@ snapshots:'@aws-crypto/[email protected]':dependencies:'@aws-crypto/util': 5.2.0- '@aws-sdk/types': 3.973.12+ '@aws-sdk/types': 3.974.2tslib: 2.8.1'@aws-crypto/[email protected]':dependencies:'@aws-crypto/util': 5.2.0- '@aws-sdk/types': 3.973.12+ '@aws-sdk/types': 3.974.2tslib: 2.8.1'@aws-crypto/[email protected]':dependencies:'@aws-crypto/supports-web-crypto': 5.2.0'@aws-crypto/util': 5.2.0- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@aws-sdk/util-locate-window': 3.310.0'@smithy/util-utf8': 2.3.0tslib: 2.8.1@@ -23104,7 +23184,7 @@ snapshots:'@aws-crypto/sha256-js': 5.2.0'@aws-crypto/supports-web-crypto': 5.2.0'@aws-crypto/util': 5.2.0- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@aws-sdk/util-locate-window': 3.310.0'@smithy/util-utf8': 2.3.0tslib: 2.8.1@@ -23112,7 +23192,7 @@ snapshots:'@aws-crypto/[email protected]':dependencies:'@aws-crypto/util': 5.2.0- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2tslib: 2.8.1'@aws-crypto/[email protected]':@@ -23121,7 +23201,7 @@ snapshots:'@aws-crypto/[email protected]':dependencies:- '@aws-sdk/types': 3.973.12+ '@aws-sdk/types': 3.974.2'@smithy/util-utf8': 2.3.0tslib: 2.8.1@@ -23190,7 +23270,7 @@ snapshots:'@aws-sdk/util-user-agent-node': 3.806.0'@smithy/config-resolver': 4.4.6'@smithy/core': 3.24.6- '@smithy/fetch-http-handler': 5.3.9+ '@smithy/fetch-http-handler': 5.6.13'@smithy/hash-node': 4.2.8'@smithy/invalid-dependency': 4.2.8'@smithy/middleware-content-length': 4.2.8@@ -23202,7 +23282,7 @@ snapshots:'@smithy/node-http-handler': 4.4.9'@smithy/protocol-http': 5.3.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-base64': 4.3.0'@smithy/util-body-length-browser': 4.2.0@@ -23221,38 +23301,38 @@ snapshots:dependencies:'@aws-crypto/sha256-browser': 5.2.0'@aws-crypto/sha256-js': 5.2.0- '@aws-sdk/core': 3.973.1+ '@aws-sdk/core': 3.973.7'@aws-sdk/credential-provider-node': 3.972.6- '@aws-sdk/middleware-host-header': 3.972.1- '@aws-sdk/middleware-logger': 3.972.1- '@aws-sdk/middleware-recursion-detection': 3.972.1- '@aws-sdk/middleware-user-agent': 3.972.2- '@aws-sdk/region-config-resolver': 3.972.1- '@aws-sdk/types': 3.973.0+ '@aws-sdk/middleware-host-header': 3.972.3+ '@aws-sdk/middleware-logger': 3.972.3+ '@aws-sdk/middleware-recursion-detection': 3.972.3+ '@aws-sdk/middleware-user-agent': 3.972.7+ '@aws-sdk/region-config-resolver': 3.972.3+ '@aws-sdk/types': 3.973.12'@aws-sdk/util-endpoints': 3.972.0- '@aws-sdk/util-user-agent-browser': 3.972.1- '@aws-sdk/util-user-agent-node': 3.972.1+ '@aws-sdk/util-user-agent-browser': 3.972.3+ '@aws-sdk/util-user-agent-node': 3.972.5'@smithy/config-resolver': 4.4.6'@smithy/core': 3.24.6'@smithy/fetch-http-handler': 5.3.9'@smithy/hash-node': 4.2.8'@smithy/invalid-dependency': 4.2.8'@smithy/middleware-content-length': 4.2.8- '@smithy/middleware-endpoint': 4.4.11- '@smithy/middleware-retry': 4.4.27+ '@smithy/middleware-endpoint': 4.4.13+ '@smithy/middleware-retry': 4.4.30'@smithy/middleware-serde': 4.2.9'@smithy/middleware-stack': 4.2.8'@smithy/node-config-provider': 4.3.8'@smithy/node-http-handler': 4.4.9'@smithy/protocol-http': 5.3.8- '@smithy/smithy-client': 4.10.12- '@smithy/types': 4.12.0+ '@smithy/smithy-client': 4.11.2+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-base64': 4.3.0'@smithy/util-body-length-browser': 4.2.0'@smithy/util-body-length-node': 4.2.1- '@smithy/util-defaults-mode-browser': 4.3.26- '@smithy/util-defaults-mode-node': 4.2.29+ '@smithy/util-defaults-mode-browser': 4.3.29+ '@smithy/util-defaults-mode-node': 4.2.32'@smithy/util-endpoints': 3.2.8'@smithy/util-middleware': 4.2.8'@smithy/util-retry': 4.2.8@@ -23280,7 +23360,7 @@ snapshots:'@aws-sdk/middleware-user-agent': 3.972.7'@aws-sdk/region-config-resolver': 3.972.3'@aws-sdk/signature-v4-multi-region': 3.972.0- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.973.12'@aws-sdk/util-endpoints': 3.972.0'@aws-sdk/util-user-agent-browser': 3.972.3'@aws-sdk/util-user-agent-node': 3.972.5@@ -23304,7 +23384,7 @@ snapshots:'@smithy/node-http-handler': 4.4.9'@smithy/protocol-http': 5.3.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-base64': 4.3.0'@smithy/util-body-length-browser': 4.2.0@@ -23382,7 +23462,7 @@ snapshots:'@aws-sdk/util-user-agent-node': 3.806.0'@smithy/config-resolver': 4.4.6'@smithy/core': 3.24.6- '@smithy/fetch-http-handler': 5.3.9+ '@smithy/fetch-http-handler': 5.6.13'@smithy/hash-node': 4.2.8'@smithy/invalid-dependency': 4.2.8'@smithy/middleware-content-length': 4.2.8@@ -23394,7 +23474,7 @@ snapshots:'@smithy/node-http-handler': 4.4.9'@smithy/protocol-http': 5.3.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-base64': 4.3.0'@smithy/util-body-length-browser': 4.2.0@@ -23413,19 +23493,19 @@ snapshots:dependencies:'@aws-crypto/sha256-browser': 5.2.0'@aws-crypto/sha256-js': 5.2.0- '@aws-sdk/core': 3.973.7+ '@aws-sdk/core': 3.977.4'@aws-sdk/middleware-host-header': 3.972.3'@aws-sdk/middleware-logger': 3.972.3'@aws-sdk/middleware-recursion-detection': 3.972.3'@aws-sdk/middleware-user-agent': 3.972.7'@aws-sdk/region-config-resolver': 3.972.3- '@aws-sdk/types': 3.973.12+ '@aws-sdk/types': 3.974.2'@aws-sdk/util-endpoints': 3.985.0'@aws-sdk/util-user-agent-browser': 3.972.3'@aws-sdk/util-user-agent-node': 3.972.5'@smithy/config-resolver': 4.4.6'@smithy/core': 3.24.6- '@smithy/fetch-http-handler': 5.3.9+ '@smithy/fetch-http-handler': 5.6.13'@smithy/hash-node': 4.2.8'@smithy/invalid-dependency': 4.2.8'@smithy/middleware-content-length': 4.2.8@@ -23437,7 +23517,7 @@ snapshots:'@smithy/node-http-handler': 4.4.9'@smithy/protocol-http': 5.3.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-base64': 4.3.0'@smithy/util-body-length-browser': 4.2.0@@ -23503,9 +23583,9 @@ snapshots:'@smithy/node-config-provider': 4.3.8'@smithy/property-provider': 4.2.8'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8+ '@smithy/signature-v4': 5.6.12'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/util-middleware': 4.2.8fast-xml-parser: 5.5.6tslib: 2.8.1@@ -23518,9 +23598,9 @@ snapshots:'@smithy/node-config-provider': 4.3.8'@smithy/property-provider': 4.2.8'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8+ '@smithy/signature-v4': 5.6.12'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/util-base64': 4.3.0'@smithy/util-middleware': 4.2.8'@smithy/util-utf8': 4.2.0@@ -23528,15 +23608,15 @@ snapshots:'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1- '@aws-sdk/xml-builder': 3.972.4+ '@aws-sdk/types': 3.974.2+ '@aws-sdk/xml-builder': 3.972.37'@smithy/core': 3.24.6'@smithy/node-config-provider': 4.3.8'@smithy/property-provider': 4.2.8'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8+ '@smithy/signature-v4': 5.6.12'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-base64': 4.3.0'@smithy/util-middleware': 4.2.8'@smithy/util-utf8': 4.2.0@@ -23544,23 +23624,45 @@ snapshots:'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1- '@aws-sdk/xml-builder': 3.972.4+ '@aws-sdk/types': 3.974.2+ '@aws-sdk/xml-builder': 3.972.37'@smithy/core': 3.24.6'@smithy/node-config-provider': 4.3.8'@smithy/property-provider': 4.2.8'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8+ '@smithy/signature-v4': 5.6.12'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-base64': 4.3.0'@smithy/util-middleware': 4.2.8'@smithy/util-utf8': 4.2.0tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.974.2+ '@aws-sdk/xml-builder': 3.972.37+ '@aws/lambda-invoke-store': 0.3.0+ '@smithy/core': 3.24.6+ '@smithy/signature-v4': 5.6.12+ '@smithy/types': 4.16.1+ bowser: 2.11.0+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.974.2+ '@aws-sdk/xml-builder': 3.972.37+ '@aws/lambda-invoke-store': 0.3.0+ '@smithy/core': 3.24.6+ '@smithy/signature-v4': 5.6.12+ '@smithy/types': 4.16.1+ bowser: 2.11.0+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -23568,40 +23670,40 @@ snapshots:'@aws-sdk/core': 3.806.0'@aws-sdk/types': 3.804.0'@smithy/property-provider': 4.2.8- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7- '@aws-sdk/types': 3.973.1+ '@aws-sdk/core': 3.977.4+ '@aws-sdk/types': 3.974.2'@smithy/property-provider': 4.2.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.806.0'@aws-sdk/types': 3.804.0- '@smithy/fetch-http-handler': 5.3.9+ '@smithy/fetch-http-handler': 5.6.13'@smithy/node-http-handler': 4.4.9'@smithy/property-provider': 4.2.8'@smithy/protocol-http': 5.3.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/util-stream': 4.5.11tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7- '@aws-sdk/types': 3.973.1- '@smithy/fetch-http-handler': 5.3.9+ '@aws-sdk/core': 3.977.4+ '@aws-sdk/types': 3.974.2+ '@smithy/fetch-http-handler': 5.6.13'@smithy/node-http-handler': 4.4.9'@smithy/property-provider': 4.2.8'@smithy/protocol-http': 5.3.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-stream': 4.5.11tslib: 2.8.1@@ -23618,39 +23720,39 @@ snapshots:'@smithy/credential-provider-imds': 4.2.8'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7+ '@aws-sdk/core': 3.977.4'@aws-sdk/credential-provider-env': 3.972.5'@aws-sdk/credential-provider-http': 3.972.7'@aws-sdk/credential-provider-login': 3.972.5'@aws-sdk/credential-provider-process': 3.972.5'@aws-sdk/credential-provider-sso': 3.972.5- '@aws-sdk/credential-provider-web-identity': 3.972.5+ '@aws-sdk/credential-provider-web-identity': 3.972.70'@aws-sdk/nested-clients': 3.985.0- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/credential-provider-imds': 4.2.8'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7+ '@aws-sdk/core': 3.977.4'@aws-sdk/nested-clients': 3.985.0- '@aws-sdk/types': 3.973.12+ '@aws-sdk/types': 3.974.2'@smithy/property-provider': 4.2.8'@smithy/protocol-http': 5.3.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt@@ -23667,7 +23769,7 @@ snapshots:'@smithy/credential-provider-imds': 4.2.8'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt@@ -23695,16 +23797,16 @@ snapshots:'@aws-sdk/types': 3.804.0'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7- '@aws-sdk/types': 3.973.1+ '@aws-sdk/core': 3.977.4+ '@aws-sdk/types': 3.974.2'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -23715,7 +23817,7 @@ snapshots:'@aws-sdk/types': 3.804.0'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt@@ -23723,12 +23825,12 @@ snapshots:'@aws-sdk/[email protected]':dependencies:'@aws-sdk/client-sso': 3.985.0- '@aws-sdk/core': 3.973.7+ '@aws-sdk/core': 3.977.4'@aws-sdk/token-providers': 3.985.0- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt@@ -23739,30 +23841,39 @@ snapshots:'@aws-sdk/nested-clients': 3.806.0'@aws-sdk/types': 3.804.0'@smithy/property-provider': 4.2.8- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7+ '@aws-sdk/core': 3.977.4'@aws-sdk/nested-clients': 3.985.0- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.977.4+ '@aws-sdk/nested-clients': 3.997.40+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.24.6+ '@smithy/types': 4.16.1+ tslib: 2.8.1+'@aws-sdk/[email protected](@aws-sdk/[email protected])':dependencies:'@aws-sdk/client-dynamodb': 3.975.0- '@aws-sdk/core': 3.973.7+ '@aws-sdk/core': 3.977.4'@smithy/core': 3.24.6'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-base64': 4.3.0tslib: 2.8.1@@ -23784,28 +23895,28 @@ snapshots:'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@aws-sdk/util-arn-parser': 3.972.2'@smithy/node-config-provider': 4.3.8'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-config-provider': 4.2.0tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/endpoint-cache': 3.972.2- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/node-config-provider': 4.3.8'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -23813,13 +23924,13 @@ snapshots:'@aws-crypto/crc32': 5.2.0'@aws-crypto/crc32c': 5.2.0'@aws-crypto/util': 5.2.0- '@aws-sdk/core': 3.973.7+ '@aws-sdk/core': 3.977.4'@aws-sdk/crc64-nvme': 3.972.0- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/is-array-buffer': 4.2.0'@smithy/node-config-provider': 4.3.8'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-middleware': 4.2.8'@smithy/util-stream': 4.5.11'@smithy/util-utf8': 4.2.0@@ -23829,68 +23940,68 @@ snapshots:dependencies:'@aws-sdk/types': 3.804.0'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1- '@smithy/types': 4.12.0+ '@aws-sdk/types': 3.974.2+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.804.0- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1- '@smithy/types': 4.12.0+ '@aws-sdk/types': 3.974.2+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1- '@smithy/types': 4.12.0+ '@aws-sdk/types': 3.974.2+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.804.0'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@aws/lambda-invoke-store': 0.2.3'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@aws/lambda-invoke-store': 0.2.3'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -23901,9 +24012,9 @@ snapshots:'@smithy/core': 3.24.6'@smithy/node-config-provider': 4.3.8'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8+ '@smithy/signature-v4': 5.6.12'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/util-config-provider': 4.2.0'@smithy/util-middleware': 4.2.8'@smithy/util-stream': 4.5.11@@ -23918,9 +24029,9 @@ snapshots:'@smithy/core': 3.24.6'@smithy/node-config-provider': 4.3.8'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8+ '@smithy/signature-v4': 5.6.12'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/util-config-provider': 4.2.0'@smithy/util-middleware': 4.2.8'@smithy/util-stream': 4.5.11@@ -23929,15 +24040,15 @@ snapshots:'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7- '@aws-sdk/types': 3.973.1+ '@aws-sdk/core': 3.977.4+ '@aws-sdk/types': 3.974.2'@aws-sdk/util-arn-parser': 3.972.2'@smithy/core': 3.24.6'@smithy/node-config-provider': 4.3.8'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8+ '@smithy/signature-v4': 5.6.12'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-config-provider': 4.2.0'@smithy/util-middleware': 4.2.8'@smithy/util-stream': 4.5.11@@ -23946,8 +24057,8 @@ snapshots:'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1- '@smithy/types': 4.12.0+ '@aws-sdk/types': 3.974.2+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -23957,27 +24068,27 @@ snapshots:'@aws-sdk/util-endpoints': 3.806.0'@smithy/core': 3.24.6'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7- '@aws-sdk/types': 3.973.1+ '@aws-sdk/core': 3.977.4+ '@aws-sdk/types': 3.974.2'@aws-sdk/util-endpoints': 3.972.0'@smithy/core': 3.24.6'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7- '@aws-sdk/types': 3.973.1+ '@aws-sdk/core': 3.977.4+ '@aws-sdk/types': 3.974.2'@aws-sdk/util-endpoints': 3.985.0'@smithy/core': 3.24.6'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -23996,7 +24107,7 @@ snapshots:'@aws-sdk/util-user-agent-node': 3.806.0'@smithy/config-resolver': 4.4.6'@smithy/core': 3.24.6- '@smithy/fetch-http-handler': 5.3.9+ '@smithy/fetch-http-handler': 5.6.13'@smithy/hash-node': 4.2.8'@smithy/invalid-dependency': 4.2.8'@smithy/middleware-content-length': 4.2.8@@ -24008,7 +24119,7 @@ snapshots:'@smithy/node-http-handler': 4.4.9'@smithy/protocol-http': 5.3.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-base64': 4.3.0'@smithy/util-body-length-browser': 4.2.0@@ -24027,19 +24138,19 @@ snapshots:dependencies:'@aws-crypto/sha256-browser': 5.2.0'@aws-crypto/sha256-js': 5.2.0- '@aws-sdk/core': 3.973.7+ '@aws-sdk/core': 3.977.4'@aws-sdk/middleware-host-header': 3.972.3'@aws-sdk/middleware-logger': 3.972.3'@aws-sdk/middleware-recursion-detection': 3.972.3'@aws-sdk/middleware-user-agent': 3.972.7'@aws-sdk/region-config-resolver': 3.972.3- '@aws-sdk/types': 3.973.12+ '@aws-sdk/types': 3.974.2'@aws-sdk/util-endpoints': 3.985.0'@aws-sdk/util-user-agent-browser': 3.972.3'@aws-sdk/util-user-agent-node': 3.972.5'@smithy/config-resolver': 4.4.6'@smithy/core': 3.24.6- '@smithy/fetch-http-handler': 5.3.9+ '@smithy/fetch-http-handler': 5.6.13'@smithy/hash-node': 4.2.8'@smithy/invalid-dependency': 4.2.8'@smithy/middleware-content-length': 4.2.8@@ -24051,7 +24162,7 @@ snapshots:'@smithy/node-http-handler': 4.4.9'@smithy/protocol-http': 5.3.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-base64': 4.3.0'@smithy/util-body-length-browser': 4.2.0@@ -24066,29 +24177,40 @@ snapshots:transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.977.5+ '@aws-sdk/signature-v4-multi-region': 3.996.43+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.24.6+ '@smithy/fetch-http-handler': 5.6.13+ '@smithy/node-http-handler': 4.4.9+ '@smithy/types': 4.16.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.804.0'@smithy/node-config-provider': 4.3.8- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/util-config-provider': 4.2.0'@smithy/util-middleware': 4.2.8tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/config-resolver': 4.4.6'@smithy/node-config-provider': 4.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/config-resolver': 4.4.6'@smithy/node-config-provider': 4.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -24096,8 +24218,8 @@ snapshots:'@aws-sdk/middleware-sdk-s3': 3.806.0'@aws-sdk/types': 3.804.0'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8- '@smithy/types': 4.14.3+ '@smithy/signature-v4': 5.6.12+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -24105,17 +24227,24 @@ snapshots:'@aws-sdk/middleware-sdk-s3': 3.972.0'@aws-sdk/types': 3.972.0'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/signature-v4': 5.6.12+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/middleware-sdk-s3': 3.972.7- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/protocol-http': 5.3.8- '@smithy/signature-v4': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/signature-v4': 5.6.12+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.974.2+ '@smithy/signature-v4': 5.6.12+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -24124,46 +24253,51 @@ snapshots:'@aws-sdk/types': 3.804.0'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/core': 3.973.7+ '@aws-sdk/core': 3.977.4'@aws-sdk/nested-clients': 3.985.0- '@aws-sdk/types': 3.973.12+ '@aws-sdk/types': 3.974.2'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1transitivePeerDependencies:- aws-crt'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -24181,22 +24315,22 @@ snapshots:'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.804.0- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/util-endpoints': 3.2.8tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.972.0- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-endpoints': 3.2.8tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1- '@smithy/types': 4.12.0+ '@aws-sdk/types': 3.974.2+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-endpoints': 3.2.8tslib: 2.8.1@@ -24208,21 +24342,21 @@ snapshots:'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.804.0- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1bowser: 2.11.0tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1- '@smithy/types': 4.12.0+ '@aws-sdk/types': 3.974.2+ '@smithy/types': 4.16.1bowser: 2.11.0tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@aws-sdk/types': 3.973.1- '@smithy/types': 4.12.0+ '@aws-sdk/types': 3.974.2+ '@smithy/types': 4.16.1bowser: 2.11.0tslib: 2.8.1@@ -24231,39 +24365,40 @@ snapshots:'@aws-sdk/middleware-user-agent': 3.806.0'@aws-sdk/types': 3.804.0'@smithy/node-config-provider': 4.3.8- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/middleware-user-agent': 3.972.7- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/node-config-provider': 4.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/middleware-user-agent': 3.972.7- '@aws-sdk/types': 3.973.1+ '@aws-sdk/types': 3.974.2'@smithy/node-config-provider': 4.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1fast-xml-parser: 5.5.6tslib: 2.8.1- '@aws-sdk/[email protected]':+ '@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.14.3- fast-xml-parser: 5.5.6+ '@smithy/types': 4.16.1tslib: 2.8.1'@aws/[email protected]': {}+ '@aws/[email protected]': {}+'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.29.0@@ -28373,7 +28508,7 @@ snapshots:fs-extra: 11.3.5jiti: 2.6.1remeda: 2.34.0- tinyglobby: 0.2.16+ tinyglobby: 0.2.17typedoc: 0.28.19([email protected])transitivePeerDependencies:- supports-color@@ -30578,7 +30713,7 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -30593,7 +30728,7 @@ snapshots:'@smithy/[email protected]':dependencies:'@smithy/node-config-provider': 4.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-config-provider': 4.2.0'@smithy/util-endpoints': 3.2.8'@smithy/util-middleware': 4.2.8@@ -30602,78 +30737,84 @@ snapshots:'@smithy/[email protected]':dependencies:'@aws-crypto/crc32': 5.2.0- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/node-config-provider': 4.3.8'@smithy/property-provider': 4.2.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8tslib: 2.8.1'@smithy/[email protected]':dependencies:'@aws-crypto/crc32': 5.2.0- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/util-hex-encoding': 4.2.0tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/eventstream-serde-universal': 4.2.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/eventstream-serde-universal': 4.2.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/eventstream-codec': 4.2.8- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/protocol-http': 5.3.8'@smithy/querystring-builder': 4.2.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-base64': 4.3.0tslib: 2.8.1+ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.24.6+ '@smithy/types': 4.16.1+ tslib: 2.8.1+'@smithy/[email protected]':dependencies:'@smithy/chunked-blob-reader': 5.2.0'@smithy/chunked-blob-reader-native': 4.2.1- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-buffer-from': 4.2.0'@smithy/util-utf8': 4.2.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-utf8': 4.2.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -30686,14 +30827,14 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-utf8': 4.2.0tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -30702,7 +30843,7 @@ snapshots:'@smithy/middleware-serde': 4.2.9'@smithy/node-config-provider': 4.3.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-middleware': 4.2.8tslib: 2.8.1@@ -30713,7 +30854,7 @@ snapshots:'@smithy/middleware-serde': 4.2.9'@smithy/node-config-provider': 4.3.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/url-parser': 4.2.8'@smithy/util-middleware': 4.2.8tslib: 2.8.1@@ -30724,7 +30865,7 @@ snapshots:'@smithy/protocol-http': 5.3.8'@smithy/service-error-classification': 4.2.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-middleware': 4.2.8'@smithy/util-retry': 4.2.8'@smithy/uuid': 1.1.0@@ -30736,7 +30877,7 @@ snapshots:'@smithy/protocol-http': 5.3.8'@smithy/service-error-classification': 4.2.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-middleware': 4.2.8'@smithy/util-retry': 4.2.8'@smithy/uuid': 1.1.0@@ -30745,19 +30886,19 @@ snapshots:'@smithy/[email protected]':dependencies:'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/property-provider': 4.2.8'@smithy/shared-ini-file-loader': 4.4.3- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -30770,43 +30911,38 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/util-uri-escape': 4.2.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.14.3+ '@smithy/types': 4.16.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1- '@smithy/[email protected]':+ '@smithy/[email protected]':dependencies:- '@smithy/is-array-buffer': 4.2.0- '@smithy/protocol-http': 5.3.8- '@smithy/types': 4.14.3- '@smithy/util-hex-encoding': 4.2.0- '@smithy/util-middleware': 4.2.8- '@smithy/util-uri-escape': 4.2.0- '@smithy/util-utf8': 4.2.0+ '@smithy/core': 3.24.6+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -30815,7 +30951,7 @@ snapshots:'@smithy/middleware-endpoint': 4.4.13'@smithy/middleware-stack': 4.2.8'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-stream': 4.5.11tslib: 2.8.1@@ -30825,7 +30961,7 @@ snapshots:'@smithy/middleware-endpoint': 4.4.13'@smithy/middleware-stack': 4.2.8'@smithy/protocol-http': 5.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-stream': 4.5.11tslib: 2.8.1@@ -30833,14 +30969,14 @@ snapshots:dependencies:tslib: 2.8.1- '@smithy/[email protected]':+ '@smithy/[email protected]':dependencies:tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/querystring-parser': 4.2.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -30875,14 +31011,14 @@ snapshots:dependencies:'@smithy/property-provider': 4.2.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/property-provider': 4.2.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -30892,7 +31028,7 @@ snapshots:'@smithy/node-config-provider': 4.3.8'@smithy/property-provider': 4.2.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -30902,13 +31038,13 @@ snapshots:'@smithy/node-config-provider': 4.3.8'@smithy/property-provider': 4.2.8'@smithy/smithy-client': 4.11.2- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/node-config-provider': 4.3.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -30917,20 +31053,20 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/service-error-classification': 4.2.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/fetch-http-handler': 5.3.9+ '@smithy/fetch-http-handler': 5.6.13'@smithy/node-http-handler': 4.4.9- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1'@smithy/util-base64': 4.3.0'@smithy/util-buffer-from': 4.2.0'@smithy/util-hex-encoding': 4.2.0@@ -30954,7 +31090,7 @@ snapshots:'@smithy/[email protected]':dependencies:'@smithy/abort-controller': 4.2.8- '@smithy/types': 4.12.0+ '@smithy/types': 4.16.1tslib: 2.8.1'@smithy/[email protected]':@@ -32565,7 +32701,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/pg': 8.6.6+ '@types/pg': 8.15.6'@types/[email protected]':dependencies:@@ -32881,7 +33017,7 @@ snapshots:debug: 4.4.3minimatch: 10.2.5semver: 7.8.0- tinyglobby: 0.2.16+ tinyglobby: 0.2.17ts-api-utils: 2.5.0([email protected])typescript: 6.0.3transitivePeerDependencies:@@ -40607,7 +40743,7 @@ snapshots:proc-log: 5.0.0semver: 7.8.0tar: 7.5.15- tinyglobby: 0.2.16+ tinyglobby: 0.2.17which: 5.0.0transitivePeerDependencies:- supports-color@@ -40621,7 +40757,7 @@ snapshots:proc-log: 6.1.0semver: 7.8.0tar: 7.5.15- tinyglobby: 0.2.16+ tinyglobby: 0.2.17undici: 6.25.0which: 6.0.0@@ -41274,7 +41410,7 @@ snapshots:dependencies:- readable-stream: 4.3.0+ readable-stream: 4.7.0split2: 4.2.0@@ -41289,7 +41425,7 @@ snapshots:on-exit-leak-free: 2.1.0pino-abstract-transport: 1.0.0pump: 3.0.4- readable-stream: 4.3.0+ readable-stream: 4.7.0secure-json-parse: 2.7.0sonic-boom: 3.3.0strip-json-comments: 3.1.1@@ -42834,13 +42970,6 @@ snapshots:string_decoder: 1.3.0util-deprecate: 1.0.2- dependencies:- abort-controller: 3.0.0- buffer: 6.0.3- events: 3.3.0- process: 0.11.10-dependencies:abort-controller: 3.0.0@@ -45216,9 +45345,9 @@ snapshots:esbuild: 0.27.7fdir: 6.5.0([email protected])picomatch: 4.0.4- postcss: 8.5.15+ postcss: 8.5.16rollup: 4.60.4- tinyglobby: 0.2.16+ tinyglobby: 0.2.17optionalDependencies:'@types/node': 22.18.8fsevents: 2.3.3@@ -45323,7 +45452,7 @@ snapshots:std-env: 3.10.0tinybench: 2.9.0tinyexec: 0.3.2- tinyglobby: 0.2.16+ tinyglobby: 0.2.17tinypool: 1.1.1tinyrainbow: 2.0.0vite: 7.3.5(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 67adeb4600d4..4274d4a42200 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -20,6 +20,7 @@ packages:- '!products/desktop'- docs/onboarding- services/agent-proxy+ - services/integration-service- services/oauth-proxy- services/mcp- services/stripe-appdiff --git a/posthog/integration_secrets/__init__.py b/posthog/integration_secrets/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/integration_secrets/callers.py b/posthog/integration_secrets/callers.pynew file mode 100644index 000000000000..fcf2bfe49520--- /dev/null+++ b/posthog/integration_secrets/callers.py@@ -0,0 +1,26 @@+from enum import StrEnum+++class IntegrationCaller(StrEnum):+ """The product asking for a credential.++ Passed explicitly at every call site rather than read from a setting, so the code+ says which product wanted the credential instead of the pod it happened to run in.+ One pod hosts many products, and "Django read this" is not a useful answer during an+ incident.++ This is attribution, not authorization. The service does not trust it: Django holds+ one signing key and hosts every product below, so a compromised Django pod could name+ any of them. What bounds a request is the deployment's signing key, which decides+ whether the token verifies at all, and the `keys` claim inside it, which is the whole+ of the request scope. There is no per-deployment allowlist.++ The service keeps no list of these names. It writes the claim to its audit log and+ nowhere else, so adding a member here needs no change on the service side.+ """++ WAREHOUSE_SOURCES = "warehouse-sources"+ CDP = "cdp"+ MESSAGING = "messaging"+ TASKS = "tasks"+ WEB_ANALYTICS = "web-analytics"diff --git a/posthog/integration_secrets/client.py b/posthog/integration_secrets/client.pynew file mode 100644index 000000000000..c26fd6054cd6--- /dev/null+++ b/posthog/integration_secrets/client.py@@ -0,0 +1,218 @@+"""Client for the integration service — platform integration credentials over HTTP.++These are the OAuth app client ids/secrets and API keys PostHog itself owns, which used+to be injected as environment variables into every pod that might need one. Reading them+over HTTP means rotation happens in one place with no charts PR and no pod restart, and+every read is attributed.++Three behaviours are load-bearing:++1. **No caching, anywhere.** Every call resolves against the service. That makes the+ service a hard dependency on the credential path, which is the deliberate trade: it+ also makes a rotation land immediately, and it is what lets the service decide when an+ old value is safe to retire (a read after activation necessarily returned the new+ value, which is only true if nobody cached it).++2. **A failure is a failure.** With no cache there is no last known good, so an+ unreachable service raises rather than quietly serving something stale. The service+ needs an availability SLO before the environment variables come out.++3. **Environment fallback only when the client is off.** Unconfigured, flag disabled, or+ a flag check that errored means "read `os.environ` as before". That covers self-hosted+ deployments, local development, and the rollout window. It is not an outage path: once+ the client is on and the service is down, the call fails.++The token carries the request. `keys` is the exact set this call needs, so a token lifted+from a log unlocks those fields for five minutes rather than everything the deployment+may read. There is deliberately no request body.+"""++import os+from dataclasses import field+from datetime import timedelta+from typing import Any++from django.conf import settings++import structlog+import posthoganalytics+from prometheus_client import Counter++from posthog.dataclasses import frozen+from posthog.jwt import PosthogJwtAudience, encode_jwt+from posthog.security.outbound_proxy import internal_requests+from posthog.settings.utils import get_list++from .callers import IntegrationCaller+from .errors import SecretInRecoveryError, SecretMissingError++logger = structlog.get_logger(__name__)++RESOLVE_PATH = "/v1/secrets/resolve"+TOKEN_TTL = timedelta(minutes=5)+REQUEST_TIMEOUT_SECONDS = 5++# Rollout gate. Evaluated per call, so it can be turned off without a deploy if the+# service misbehaves. posthoganalytics evaluates locally when a personal API key is+# configured; if that ever stops being true this becomes a network hop on the credential+# path and should move to a settings-only gate.+INTEGRATION_SERVICE_FLAG = "integration-service-enabled"+INTEGRATION_SERVICE_FLAG_DISTINCT_ID = "integration_service"++INTEGRATION_SECRET_FETCH_COUNTER = Counter(+ "posthog_integration_secret_fetch_total",+ "Credential fetches from the integration service, by outcome",+ labelnames=["outcome"],+)++INTEGRATION_SECRET_ENV_FALLBACK_COUNTER = Counter(+ "posthog_integration_secret_env_fallback_total",+ "Credential reads served from the local environment instead of the integration service",+ labelnames=["reason"],+)+++@frozen+class SecretValue:+ """One credential field as the service resolved it.++ Both values are repr=False: one of these sits in a frame on every traceback raised+ below _fetch, and a repr would put the credential in the log or in Sentry.+ """++ state: str+ value: str | None = field(repr=False)+ previous: str | None = field(repr=False)+++@frozen+class RotatingSecret:+ """Current value plus the outgoing one, so the two cannot be transposed silently."""++ current: str = field(repr=False)+ previous: str | None = field(repr=False)+++def integration_service_signing_keys() -> list[str]:+ """The comma-separated `new_key,old_key` set, newest first, whitespace-trimmed.++ Same convention as RECORDING_API_JWT_SECRET: sign with the first. The service accepts+ every key it holds for this deployment, so a key rotation is zero-downtime.+ """+ return [key for key in get_list(settings.INTEGRATION_SERVICE_JWT_SECRET or "") if key]+++def _disabled_reason() -> str | None:+ """Why the environment fallback is in use, or None when the service should be called.++ The flag fails closed: closed means the old environment-variable path, because a flag+ service blip must not take out credential reads. The three reasons matter separately+ during the rollout — "flag_error" is the fail-closed path that quietly keeps a pod on+ environment variables while the flag service is unhealthy, and it must not look like+ a deliberate opt-out.+ """+ if not settings.INTEGRATION_SERVICE_URL or not integration_service_signing_keys():+ return "unconfigured"+ try:+ enabled = bool(posthoganalytics.feature_enabled(INTEGRATION_SERVICE_FLAG, INTEGRATION_SERVICE_FLAG_DISTINCT_ID))+ except Exception:+ logger.warning("integration_secrets.flag_check_failed_defaulting_off", exc_info=True)+ return "flag_error"+ return None if enabled else "flag_off"+++def integration_service_enabled() -> bool:+ """True when the service is configured and the rollout flag is on."""+ return _disabled_reason() is None+++class IntegrationSecretsClient:+ def get(self, key: str, caller: IntegrationCaller) -> str:+ return self.get_many([key], caller)[key]++ def get_many(self, keys: list[str], caller: IntegrationCaller) -> dict[str, str]:+ resolved = self._resolve(keys, caller)+ out: dict[str, str] = {}+ for key in keys:+ secret = resolved[key]+ if secret.state == "recovery" or secret.value is None:+ raise SecretInRecoveryError(key)+ out[key] = secret.value+ return out++ def get_with_previous(self, key: str, caller: IntegrationCaller) -> RotatingSecret:+ """Current value plus the outgoing one while a rotation is in flight.++ For callers that can retry against a third party: try current, and on an auth+ failure retry with previous. Nothing is reported back — the service works out for+ itself when the old value is safe to retire.+ """+ secret = self._resolve([key], caller)[key]+ if secret.state == "recovery" or secret.value is None:+ raise SecretInRecoveryError(key)+ return RotatingSecret(current=secret.value, previous=secret.previous)++ def _resolve(self, keys: list[str], caller: IntegrationCaller) -> dict[str, SecretValue]:+ reason = _disabled_reason()+ if reason is not None:+ INTEGRATION_SECRET_ENV_FALLBACK_COUNTER.labels(reason=reason).inc()+ return {key: self._from_environment(key) for key in keys}+ return self._fetch(keys, caller)++ def _fetch(self, keys: list[str], caller: IntegrationCaller) -> dict[str, SecretValue]:+ response = internal_requests.post(+ f"{settings.INTEGRATION_SERVICE_URL.rstrip('/')}{RESOLVE_PATH}",+ headers=self._auth_headers(keys, caller),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ body: dict[str, Any] = response.json()++ missing = set(body.get("missing") or [])+ secrets: dict[str, Any] = body.get("secrets") or {}++ resolved: dict[str, SecretValue] = {}+ for key in keys:+ if key in missing or key not in secrets:+ INTEGRATION_SECRET_FETCH_COUNTER.labels(outcome="missing").inc()+ raise SecretMissingError(key)++ payload = secrets[key]+ resolved[key] = SecretValue(+ state=payload.get("state", "steady"),+ value=payload.get("value"),+ previous=payload.get("previous"),+ )+ INTEGRATION_SECRET_FETCH_COUNTER.labels(outcome="ok").inc()++ return resolved++ def _auth_headers(self, keys: list[str], caller: IntegrationCaller) -> dict[str, str]:+ token = encode_jwt(+ {"caller": str(caller), "keys": sorted(set(keys))},+ TOKEN_TTL,+ PosthogJwtAudience.INTEGRATION_SERVICE,+ signing_key=integration_service_signing_keys()[0],+ )+ return {"Authorization": f"Bearer {token}"}++ def _from_environment(self, key: str) -> SecretValue:+ value = os.environ.get(key) or getattr(settings, key, "")+ if not value:+ raise SecretMissingError(key)+ return SecretValue(state="steady", value=value, previous=None)+++_client = IntegrationSecretsClient()+++def get(key: str, caller: IntegrationCaller) -> str:+ return _client.get(key, caller)+++def get_many(keys: list[str], caller: IntegrationCaller) -> dict[str, str]:+ return _client.get_many(keys, caller)+++def get_with_previous(key: str, caller: IntegrationCaller) -> RotatingSecret:+ return _client.get_with_previous(key, caller)diff --git a/posthog/integration_secrets/errors.py b/posthog/integration_secrets/errors.pynew file mode 100644index 000000000000..89a129a97881--- /dev/null+++ b/posthog/integration_secrets/errors.py@@ -0,0 +1,22 @@+class IntegrationSecretError(Exception):+ def __init__(self, key: str, message: str) -> None:+ self.key = key+ super().__init__(message)+++class SecretMissingError(IntegrationSecretError):+ """The key is unknown to the service, or has no value in this environment."""++ def __init__(self, key: str) -> None:+ super().__init__(key, f"{key} is not available from the integration service")+++class SecretInRecoveryError(IntegrationSecretError):+ """The credential is known-burned and has no valid replacement yet.++ Raised instead of returning a value that cannot work, so the caller surfaces+ "reconnect needed" rather than hammering a third party with a dead credential.+ """++ def __init__(self, key: str) -> None:+ super().__init__(key, f"{key} is in recovery — the credential needs to be re-provisioned")diff --git a/posthog/integration_secrets/test/__init__.py b/posthog/integration_secrets/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/integration_secrets/test/test_client.py b/posthog/integration_secrets/test/test_client.pynew file mode 100644index 000000000000..bdae12719f3c--- /dev/null+++ b/posthog/integration_secrets/test/test_client.py@@ -0,0 +1,236 @@+from typing import Any++import pytest+from unittest.mock import patch++from django.test import SimpleTestCase, override_settings++import jwt+import requests+from parameterized import parameterized++from posthog.integration_secrets.callers import IntegrationCaller+from posthog.integration_secrets.client import (+ IntegrationSecretsClient,+ integration_service_enabled,+ integration_service_signing_keys,+)+from posthog.integration_secrets.errors import SecretInRecoveryError, SecretMissingError+from posthog.jwt import PosthogJwtAudience++SERVICE_SETTINGS: dict[str, Any] = {+ "INTEGRATION_SERVICE_URL": "http://integration-service.posthog.svc.cluster.local",+ "INTEGRATION_SERVICE_JWT_SECRET": "signing-key-new,signing-key-old",+}++KEY = "HUBSPOT_APP_CLIENT_SECRET"+CALLER = IntegrationCaller.WAREHOUSE_SOURCES++FLAG = "posthog.integration_secrets.client.posthoganalytics.feature_enabled"+POST = "posthog.integration_secrets.client.internal_requests.post"+++class FakeResponse:+ def __init__(self, payload: dict[str, Any]) -> None:+ self._payload = payload++ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict[str, Any]:+ return self._payload+++def body(secrets: dict[str, Any] | None = None, missing: list[str] | None = None) -> dict[str, Any]:+ return {"secrets": secrets or {}, "missing": missing or []}+++def steady(value: str) -> dict[str, Any]:+ return {"state": "steady", "value": value, "version_id": "v1", "fetched_at": "now"}+++@override_settings(**SERVICE_SETTINGS)+class TestIntegrationSecretsClient(SimpleTestCase):+ def setUp(self) -> None:+ self.secrets = IntegrationSecretsClient()+ flag = patch(FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ def test_returns_the_value_the_service_resolved(self) -> None:+ with patch(POST, return_value=FakeResponse(body({KEY: steady("sec")}))):+ assert self.secrets.get(KEY, CALLER) == "sec"++ # No cache anywhere: a rotation has to land on the very next read, and the service's+ # "safe to retire the old value" verdict depends on nobody holding a stale copy.+ def test_reads_the_service_every_time(self) -> None:+ responses = [FakeResponse(body({KEY: steady("old")})), FakeResponse(body({KEY: steady("new")}))]+ with patch(POST, side_effect=responses) as post:+ assert self.secrets.get(KEY, CALLER) == "old"+ assert self.secrets.get(KEY, CALLER) == "new"+ assert post.call_count == 2++ def test_batches_several_keys_into_one_request(self) -> None:+ keys = [KEY, "HUBSPOT_APP_CLIENT_ID"]+ with patch(POST, return_value=FakeResponse(body({k: steady(f"v-{k}") for k in keys}))) as post:+ assert self.secrets.get_many(keys, CALLER) == {k: f"v-{k}" for k in keys}+ assert post.call_count == 1++ @parameterized.expand(+ [+ ("missing", {"missing": [KEY]}, SecretMissingError),+ ("absent from the response", {}, SecretMissingError),+ ]+ )+ def test_raises_a_typed_error_for(self, _name: str, response: dict[str, Any], expected: type[Exception]) -> None:+ with patch(POST, return_value=FakeResponse(body(**response))):+ with pytest.raises(expected):+ self.secrets.get(KEY, CALLER)++ # Platform client ids and secrets are what authenticate us to the third party, so a+ # burned one cannot be "reconnected" by a user — the integration is down until an+ # engineer re-provisions it. Failing immediately keeps that distinguishable from a+ # third-party outage.+ def test_recovery_raises_rather_than_returning_a_dead_credential(self) -> None:+ payload = {"state": "recovery", "version_id": "v1", "fetched_at": "now"}+ with patch(POST, return_value=FakeResponse(body({KEY: payload}))):+ with pytest.raises(SecretInRecoveryError):+ self.secrets.get(KEY, CALLER)++ def test_get_with_previous_exposes_the_outgoing_value_during_a_rotation(self) -> None:+ rotating = {"state": "rotating", "value": "new", "previous": "old", "version_id": "v1", "fetched_at": "now"}+ with patch(POST, return_value=FakeResponse(body({KEY: rotating}))):+ secret = self.secrets.get_with_previous(KEY, CALLER)+ assert secret.current == "new"+ assert secret.previous == "old"++ # The 503 contract: the service answers 503 rather than all-missing on a cold start,+ # and only raise_for_status keeps that from surfacing as SecretMissingError, which+ # callers treat as terminal.+ def test_a_service_error_status_propagates_rather_than_reading_as_missing(self) -> None:+ class ErrorResponse:+ def raise_for_status(self) -> None:+ raise requests.HTTPError("503 Server Error", response=requests.Response())++ def json(self) -> dict[str, Any]:+ return {"error": "Secret store unavailable"}++ with patch(POST, return_value=ErrorResponse()):+ with pytest.raises(requests.HTTPError):+ self.secrets.get(KEY, CALLER)++ # With no cache there is no last known good, so an outage is an outage. This is the+ # trade for immediate rotations, and it is why the service needs an availability SLO+ # before the environment variables come out.+ def test_an_unreachable_service_raises_rather_than_serving_something_stale(self) -> None:+ with patch(POST, return_value=FakeResponse(body({KEY: steady("sec")}))):+ self.secrets.get(KEY, CALLER)++ with patch(POST, side_effect=ConnectionError("integration service is down")):+ with pytest.raises(ConnectionError):+ self.secrets.get(KEY, CALLER)++ def test_does_not_fall_back_to_the_environment_when_the_service_is_down(self) -> None:+ with (+ patch(POST, side_effect=ConnectionError("integration service is down")),+ patch.dict("os.environ", {KEY: "from-env"}),+ ):+ with pytest.raises(ConnectionError):+ self.secrets.get(KEY, CALLER)+++@override_settings(**SERVICE_SETTINGS)+class TestRolloutFlag(SimpleTestCase):+ def setUp(self) -> None:+ self.secrets = IntegrationSecretsClient()++ def test_reads_the_environment_while_the_flag_is_off(self) -> None:+ with (+ patch(FLAG, return_value=False),+ patch(POST) as post,+ patch.dict("os.environ", {KEY: "from-env"}),+ ):+ assert self.secrets.get(KEY, CALLER) == "from-env"+ post.assert_not_called()++ # Closed means the old path, not a failed read. A flag service blip must not take out+ # credential reads while the environment variables are still in place.+ def test_a_failing_flag_check_falls_back_to_the_environment(self) -> None:+ with (+ patch(FLAG, side_effect=RuntimeError("flag service unavailable")),+ patch(POST) as post,+ patch.dict("os.environ", {KEY: "from-env"}),+ ):+ assert self.secrets.get(KEY, CALLER) == "from-env"+ post.assert_not_called()++ @parameterized.expand(+ [+ ("both unset", "", "", True, False),+ ("url only", "http://svc", "", True, False),+ ("key only", "", "key", True, False),+ ("configured but flag off", "http://svc", "key", False, False),+ ("configured and flag on", "http://svc", "key", True, True),+ ]+ )+ def test_enabled_requires_url_key_and_flag(+ self, _name: str, url: str, key: str, flag: bool, expected: bool+ ) -> None:+ with (+ override_settings(INTEGRATION_SERVICE_URL=url, INTEGRATION_SERVICE_JWT_SECRET=key),+ patch(FLAG, return_value=flag),+ ):+ assert integration_service_enabled() is expected+++class TestUnconfigured(SimpleTestCase):+ """Self-hosted and local dev: no service, read the environment exactly as before."""++ @override_settings(INTEGRATION_SERVICE_URL="", INTEGRATION_SERVICE_JWT_SECRET="")+ def test_raises_when_unconfigured_and_the_environment_has_nothing_either(self) -> None:+ with pytest.raises(SecretMissingError):+ IntegrationSecretsClient().get("A_KEY_NOBODY_SET", CALLER)+++@override_settings(**SERVICE_SETTINGS)+class TestMintedToken(SimpleTestCase):+ """The token IS the request — there is no body, so these claims are the whole scope."""++ def setUp(self) -> None:+ self.secrets = IntegrationSecretsClient()+ flag = patch(FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ def _claims_from_call(self, post: Any) -> dict[str, Any]:+ header = post.call_args.kwargs["headers"]["Authorization"]+ return jwt.decode(+ header.removeprefix("Bearer "),+ integration_service_signing_keys()[0],+ audience=PosthogJwtAudience.INTEGRATION_SERVICE.value,+ algorithms=["HS256"],+ )++ def test_carries_only_the_keys_this_call_needs(self) -> None:+ with patch(POST, return_value=FakeResponse(body({KEY: steady("sec")}))) as post:+ self.secrets.get(KEY, CALLER)+ claims = self._claims_from_call(post)++ assert claims["keys"] == [KEY]+ assert claims["aud"] == PosthogJwtAudience.INTEGRATION_SERVICE.value++ # Attribution, not authorization: the service records it but grants nothing on it.+ def test_names_the_product_that_asked_rather_than_the_pod(self) -> None:+ with patch(POST, return_value=FakeResponse(body({KEY: steady("sec")}))) as post:+ self.secrets.get(KEY, IntegrationCaller.CDP)+ assert self._claims_from_call(post)["caller"] == "cdp"++ def test_signs_with_the_newest_key_so_rotation_is_zero_downtime(self) -> None:+ with patch(POST, return_value=FakeResponse(body({KEY: steady("sec")}))) as post:+ self.secrets.get(KEY, CALLER)+ token = post.call_args.kwargs["headers"]["Authorization"].removeprefix("Bearer ")++ audience = PosthogJwtAudience.INTEGRATION_SERVICE.value+ jwt.decode(token, "signing-key-new", audience=audience, algorithms=["HS256"])+ with pytest.raises(jwt.InvalidSignatureError):+ jwt.decode(token, "signing-key-old", audience=audience, algorithms=["HS256"])diff --git a/posthog/jwt.py b/posthog/jwt.pyindex eff16b26d696..291ca41b4d7c 100644--- a/posthog/jwt.py+++ b/posthog/jwt.py@@ -18,6 +18,7 @@ class PosthogJwtAudience(Enum):EXPORT_RENDERER = "posthog:export_renderer"LIVESTREAM = "posthog:livestream"SHARING_PASSWORD_PROTECTED = "posthog:sharing_password_protected"+ INTEGRATION_SERVICE = "posthog:integration_service"def signing_key_fingerprint(key: str) -> str:@@ -32,9 +33,15 @@ def _verification_keys() -> list[str]:return [_signing_key(), *settings.JWT_SIGNING_KEY_FALLBACKS]-def encode_jwt(payload: dict, expiry_delta: timedelta, audience: PosthogJwtAudience) -> str:+def encode_jwt(+ payload: dict, expiry_delta: timedelta, audience: PosthogJwtAudience, signing_key: str | None = None+) -> str:"""- Create a JWT ensuring that the correct audience and signing token is used+ Create a JWT ensuring that the correct audience and signing token is used.++ `signing_key` overrides the fleet-wide JWT_SIGNING_KEY with a per-audience key, so a+ leak of one audience's key cannot mint tokens for another. New service-to-service+ audiences should always pass one."""if not isinstance(audience, PosthogJwtAudience):raise Exception("Audience must be in the list of PostHog-supported audiences")@@ -45,7 +52,7 @@ def encode_jwt(payload: dict, expiry_delta: timedelta, audience: PosthogJwtAudie"exp": datetime.now(tz=UTC) + expiry_delta,"aud": audience.value,},- _signing_key(),+ signing_key or _signing_key(),algorithm=JWT_ALGORITHM,)diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.pyindex 5693c77cb5fb..d075cae06776 100644--- a/posthog/settings/integrations.py+++ b/posthog/settings/integrations.py@@ -1,5 +1,11 @@from posthog.settings.utils import get_from_env, get_list, str_to_bool+# Integration service. Both unset (the default) means credential reads fall back to the+# local environment; see posthog/integration_secrets/client.py for the contract.+INTEGRATION_SERVICE_URL = get_from_env("INTEGRATION_SERVICE_URL", "")+# Comma-separated `new,old`, newest first. Per deployment, not fleet-wide.+INTEGRATION_SERVICE_JWT_SECRET = get_from_env("INTEGRATION_SERVICE_JWT_SECRET", "")+HUBSPOT_APP_CLIENT_ID = get_from_env("HUBSPOT_APP_CLIENT_ID", "")HUBSPOT_APP_CLIENT_SECRET = get_from_env("HUBSPOT_APP_CLIENT_SECRET", "")diff --git a/services/integration-service/.gitignore b/services/integration-service/.gitignorenew file mode 100644index 000000000000..1033542be9f8--- /dev/null+++ b/services/integration-service/.gitignore@@ -0,0 +1,5 @@+node_modules/+dist/+*.mjs.map+.env+.env.localdiff --git a/services/integration-service/.oxlintrc.json b/services/integration-service/.oxlintrc.jsonnew file mode 100644index 000000000000..ac6ca60b78df--- /dev/null+++ b/services/integration-service/.oxlintrc.json@@ -0,0 +1,45 @@+{+ "$schema": "../../node_modules/oxlint/configuration_schema.json",+ "rules": {+ "no-restricted-imports": [+ "error",+ {+ "patterns": [+ {+ "group": [+ "**/nodejs",+ "**/nodejs/**",+ "**/frontend",+ "**/frontend/**",+ "**/common",+ "**/common/**",+ "**/ee",+ "**/ee/**",+ "**/products",+ "**/products/**",+ "**/packages",+ "**/packages/**",+ "**/services/**",+ "**/plugin-server/**",+ "../../*",+ "../../**",+ "@posthog/*",+ "@posthog/**"+ ],+ "message": "integration-service must not import from the rest of the monorepo \u2014 copy the small piece you need instead"+ }+ ]+ }+ ],+ "node/no-process-env": "error"+ },+ "plugins": ["typescript", "unicorn", "oxc", "node"],+ "overrides": [+ {+ "files": ["src/lib/config.ts", "src/lib/logging.ts", "tests/**", "scripts/**"],+ "rules": {+ "node/no-process-env": "off"+ }+ }+ ]+}diff --git a/services/integration-service/Dockerfile b/services/integration-service/Dockerfilenew file mode 100644index 000000000000..77f87c433150--- /dev/null+++ b/services/integration-service/Dockerfile@@ -0,0 +1,65 @@+# PostHog integration-service (Hono / Node.js). Serves the platform integration+# credentials PostHog itself owns over HTTP; see README.md.+#+# Build from repo root (the build context must be the workspace root so pnpm can+# resolve cross-package deps):+#+# docker build -f services/integration-service/Dockerfile -t posthog-integration-service .++# Pin the same Node version as the rest of the monorepo (.nvmrc).+# The digest wins over the tag; update both together when bumping NODE_VERSION.+ARG NODE_VERSION=24.13.0+ARG NODE_IMAGE=node:${NODE_VERSION}-bookworm-slim@sha256:4660b1ca8b28d6d1906fd644abe34b2ed81d15434d26d845ef0aced307cf4b6f++#+# Build stage: install workspace deps, bundle the entry into a single self-contained+# .mjs, so the runtime stage ships with no node_modules at all.+#+FROM ${NODE_IMAGE} AS build+WORKDIR /code++# `corepack enable` reads the `packageManager` field in package.json to pick the+# pnpm version; `corepack prepare pnpm@latest` would be non-deterministic.+RUN corepack enable++# Copy lockfile + workspace manifests first so the install layer caches across+# unrelated source changes. `patches/` is needed because pnpm-lock.yaml may+# reference workspace-level patch files.+COPY pnpm-lock.yaml pnpm-workspace.yaml package.json tsconfig.json ./+COPY patches/ patches/++# pnpm needs the workspace package's manifest before install to build the+# dependency graph; copying only the manifest keeps the layer cache-friendly.+COPY services/integration-service/package.json services/integration-service/package.json++# --ignore-scripts: nothing in this tree needs an install-time script, and for a+# service holding every platform integration credential that is the supply-chain+# path worth closing.+RUN --mount=type=cache,id=pnpm,target=/pnpm/store \+ pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/integration-service...++COPY services/integration-service/ services/integration-service/+WORKDIR /code/services/integration-service+RUN pnpm build++#+# Runtime stage: the slim image plus the self-contained bundle.+#+FROM ${NODE_IMAGE}+WORKDIR /code++# Commit hash burned in for incident triage.+ARG COMMIT_HASH+RUN echo "${COMMIT_HASH:-unknown}" > /code/commit.txt++COPY --from=build --chown=node:node /code/services/integration-service/dist/integration-service.mjs ./integration-service.mjs+COPY --from=build --chown=node:node /code/services/integration-service/dist/integration-service.mjs.map ./integration-service.mjs.map++ENV NODE_ENV=production \+ PORT=8004++EXPOSE 8004++USER node++CMD ["node", "integration-service.mjs"]diff --git a/services/integration-service/README.md b/services/integration-service/README.mdnew file mode 100644index 000000000000..ed10ca737af7--- /dev/null+++ b/services/integration-service/README.md@@ -0,0 +1,233 @@+# integration-service++Serves PostHog's **platform integration credentials** — the OAuth app client ids/secrets and API+keys PostHog itself owns, as opposed to a customer's — over HTTP, so they stop being injected as+environment variables into every pod that might need one. Today those keys are duplicated across+the Django stack and each temporal worker's chart values, and adding one means a `PostHog/charts`+PR plus knowing in advance which pods need which key.++This is phase 1. The per-team `Integration` model, the OAuth flows and token refresh come later;+nothing here touches them.++## What it does and does not buy++An attacker who has compromised a pod still holds that pod's JWT signing key, and can ask for any+credential on the mount. Per-request key scoping contains a _leaked token_, not a _compromised+pod_. The wins are:++1. Environment dumps stop containing credentials — `/proc/self/environ`, crash reports, a stray+ `printenv` in a log, and environments inherited by subprocesses.+2. Every read is attributed, so rotating after a suspected exposure is scoped to what was actually+ accessed.+3. A compromised deployment is cut off by revoking one signing key, without disturbing any other+ deployment.+4. Rotation stops needing a charts PR and a rolling restart.++Nothing here stops a compromised pod reading credentials it is entitled to read, and no list is+maintained pretending otherwise.++## API++```text+GET /_liveness 200 always+GET /_readiness 200 once the pod holds credentials+POST /v1/secrets/resolve++GET /metrics prometheus text, on its own port (INTEGRATION_SERVICE_METRICS_PORT)+```++**The request scope lives in the JWT and there is no request body.** The token _is_ the request,+so a body and a claim cannot diverge, and a token lifted from a log unlocks only the fields that+one call needed:++```jsonc+// Authorization: Bearer <token>+{+ "caller": "warehouse-sources", // the product that asked; logged, not trusted+ "keys": ["GOOGLE_ADS_APP_CLIENT_ID", "GOOGLE_ADS_APP_CLIENT_SECRET"],+ "aud": "posthog:integration_service",+ "exp": 1786035932,+}+```++```jsonc+{+ "secrets": {+ "GOOGLE_ADS_APP_CLIENT_SECRET": {+ "state": "rotating",+ "value": "…",+ "previous": "…",+ "version_id": "…",+ "fetched_at": "…",+ },+ },+ "missing": [], // name not on the mount, or reserved+}+```++An unresolvable field is reported per key in `missing` rather than as a 4xx over the whole batch,+so a mistyped name reads as one named field a human can act on while the rest still succeeds.++Callers do not cache, so there is no freshness hint to send. A rotation reaches every caller on+their next read.++## Auth++Per-deployment HS256 JWT, following the `recording-api` scheme (PostHog/posthog#67476) — the+pattern `.agents/security.md` names as strongly preferred, not `INTERNAL_API_SECRET`.++Two identities, deliberately not conflated:++| | What it is | Trusted? |+| -------------- | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |+| **Deployment** | The pod set that signed the token (`posthog-django`, a temporal worker) | Yes. It is derived from _which key verified the token_, never from a claim, so there is nothing in the token to forge |+| **Caller** | The code path that wanted the credential (`warehouse-sources`, `cdp`), from a code enum at the call site | No. Django holds one key and hosts many products, so a compromised Django pod could name any of them |++Authorization hangs off the deployment. The caller claim reaches the audit log so an incident can+ask "which product read this", and reaches nothing else — in particular it is never a metric+label, because prom-client keeps every series in process memory for the pod's lifetime.++**There is no per-deployment allowlist.** Every authenticated deployment may read any credential+on the mount: a list bounds nothing the signing key does not already bound, and a compromised+deployment is contained by revoking its key. What a deployment actually read is in the audit+log.++So one thing bounds a request: the `keys` claim, which _is_ the request, for as long as the token+has left to run — the verifier requires an `exp`.++Signing keys live in the same secret as the credentials, one flat entry per deployment+(`__CALLER_KEY_<DEPLOYMENT>`). Deployment names are derived from the entries present, not declared+in code, so onboarding a caller or revoking a compromised one is a secrets edit with no deploy.+The same value goes into that deployment's own secret as `INTEGRATION_SERVICE_JWT_SECRET`.++## Storage and rotation++**One secret holds everything**: `integration-service-secrets`, a flat map of `KEY: value` pairs.+Flat and uppercase because the `PostHog/secrets` CLI and UI only manage `[A-Z0-9_]+` keys with+plain string values.++External Secrets Operator syncs that secret into a Kubernetes Secret, and kubelet mounts it as a+directory of one file per key. Kubelet rewrites the mount in place and swaps the `..data` symlink+atomically, so a rotation reaches the pod without a restart and a read never sees a half-written+set. The service re-reads on a timer (`src/mount.ts`), every+`INTEGRATION_SERVICE_RELOAD_SECONDS`, and holds the parsed set in memory.++A pod holding no credentials fails its readiness probe rather than exiting, so an empty mount+recovers on its own once ESO syncs instead of crash-looping. A mount that stops being readable+keeps what is already held, with `integration_secret_serving_stale_seconds` as the only sign.++```text+integration-service-secrets+ STRIPE_APP_SECRET_KEY = "<credential>"+ STRIPE_APP_SECRET_KEY_FALLBACKS = "<outgoing value, only while rotating>"+ INTEGRATION_RECOVERY_KEYS = "<comma-separated key names>"+ __CALLER_KEY_POSTHOG_DJANGO = "<new>,<old>"+```++**Rotation rides an explicit `<KEY>_FALLBACKS` sibling, not AWS staging labels.** `AWSPREVIOUS`+applies to a whole secret version, so with everything in one secret, rotating Google — or adding+an unrelated key — would consume the slot Stripe's in-flight rotation was using and end its+overlap silently. A sibling key is unaffected by edits to anything else, and it is the convention+PostHog already uses for rotatable keys (`SECRET_KEY_FALLBACKS`), so the rotation guard in+`PostHog/secrets` grades these automatically.++Starting a rotation means writing the new value and moving the outgoing one into the sibling.+Completing it means deleting the sibling. Two rotations can be in flight at once without+interfering.++| State | Condition | Response |+| ---------- | ------------------------------------------------ | ------------------------------------- |+| `steady` | no `_FALLBACKS` sibling, or it repeats the value | `value` only |+| `rotating` | the sibling holds a different value | `value` + `previous` |+| `recovery` | field named in `INTEGRATION_RECOVERY_KEYS` | no value; caller raises a typed error |++`recovery` covers a credential that is known-burned with no valid replacement yet. These+credentials authenticate _PostHog_ to the third party, so there is no per-user "reconnect": the+integration is down for everyone until an engineer re-provisions the app. The state buys callers+an immediate, distinct error, so the outage is attributable instead of looking like a third-party+problem.++### What gets served++**Whatever is on the mount, except entries whose name starts with `__`.** There is no manifest in+code, so adding a credential is a secrets edit and needs no deploy.++The corollary is a rule on the secret: **only outbound credentials belong on it.** Every entry is+readable by every deployment holding a signing key. For an OAuth app secret we present to a third+party that is no expansion — the pod already had its own copy in its environment. For an+inbound-request authenticator such as a webhook signing secret it would be one, so those stay as+plain env vars on the deployment that checks them. `STRIPE_SIGNING_SECRET`, which authenticates+requests arriving at `ee/partners/stripe/api/provisioning/`, is the worked example: keep it off+this secret.++`__` is the one thing the mount will not serve, whatever a token asks for. The caller signing keys+carry that prefix, which is why they can share a secret with the credentials they protect.++## Metrics++No label value comes from a request. A key name becomes a label only once the mount is known to+carry it; anything else collapses to a constant, and the `caller` claim is not a label at all.++| Metric | What it answers |+| ------------------------------------------------------------------------ | ------------------------------------------------------------- |+| `integration_secret_resolve_total{deployment,key,result}` | who read what, and whether it resolved |+| `integration_secret_last_resolved_timestamp{key}` | which credentials nothing reads any more |+| `integration_secret_previous_version_served_total{key}` | how much traffic is reading a key mid-rotation |+| `integration_secret_serving_stale_seconds` | how long this pod has served credentials it could not refresh |+| `integration_secret_store_errors_total` | mount reads that returned nothing |+| `integration_service_signing_keys_last_loaded_timestamp` | staleness means a revocation has not landed on this pod |+| `integration_service_signing_key_reload_failures_total` | reloads that kept the previous key set |+| `integration_service_auth_failures_total{reason}` | rejected tokens, by why |+| `integration_service_http_requests_total{method,route,status}` | request volume, with an unmatched path collapsed to `other` |+| `integration_service_http_request_duration_seconds{method,route,status}` | request latency |+| `integration_service_shutting_down` | 1 while draining |++Two of these exist because a fail-open needs to be visible: the signing-key reload keeps the+previous keys when an edit is malformed, and an unreadable mount keeps what is already held. Alert+on the two staleness signals, or neither degradation is observable.++`/metrics` listens on its own port, which the chart keeps off the ingress; in-cluster Prometheus+scrapes it unauthenticated, the same shape as every other service.++## Isolation++This package must not depend on the rest of the monorepo. It shares the pnpm workspace only for+resolution — nothing from `nodejs/`, `frontend/` or `common/`. The package's own+`.oxlintrc.json` enforces that with a `no-restricted-imports` rule over static import specifiers+that name another part of the monorepo. It does not see `require()`, dynamic `import()`, or a new+npm dependency, so those still rest on review of `package.json` and the lockfile.++Installs run `--ignore-scripts`; nothing in the tree needs an install-time script, and that is+the npm-specific supply-chain path worth closing here.++## Local development++```bash+pnpm --filter @posthog/integration-service dev # tsx watch, pretty logs+pnpm --filter @posthog/integration-service typecheck+pnpm --filter @posthog/integration-service test:unit+pnpm --filter @posthog/integration-service test:integration # boots a real server on a temp mount+```++The integration suite boots a real `IntegrationServer` against a temp-dir mount and a real+socket, so it covers the wiring the unit suite fakes. Neither suite needs a database or Docker.++Point `INTEGRATION_SERVICE_SECRETS_DIR` at a directory of files, one per key, to stand in for the+mount.++## Configuration++| Variable | Default | Notes |+| ------------------------------------ | -------------------------- | ------------------------------------------------------- |+| `INTEGRATION_SERVICE_ENV` | `dev` | Logical env, recorded on every startup log line |+| `INTEGRATION_SERVICE_SECRETS_DIR` | `/etc/integration-secrets` | Where the Kubernetes Secret is mounted |+| `INTEGRATION_SERVICE_RELOAD_SECONDS` | `30` | How often to re-read the mount |+| `INTEGRATION_SERVICE_METRICS_PORT` | `9090` | Dedicated `/metrics` listener, kept off the ingress |+| `INTEGRATION_SERVICE_LOG_LEVEL` | by `NODE_ENV` | `debug`, `info`, `warn` or `error` |+| `PORT` | `8004` | |+| `HOST` | `0.0.0.0` | |+| `SHUTDOWN_PRESTOP_DELAY_MS` | `5000` | Wait before draining, for the Kubernetes prestop window |++The service exits at boot rather than starting degraded: a missing production variable, or a+numeric variable that does not parse. An empty secret mount does not exit; the pod fails its+readiness probe and recovers on its own once External Secrets Operator syncs.diff --git a/services/integration-service/package.json b/services/integration-service/package.jsonnew file mode 100644index 000000000000..64beb1225ae0--- /dev/null+++ b/services/integration-service/package.json@@ -0,0 +1,39 @@+{+ "name": "@posthog/integration-service",+ "version": "1.0.0",+ "description": "PostHog integration service — serves platform integration credentials over HTTP",+ "license": "MIT",+ "author": "PostHog Inc.",+ "type": "module",+ "scripts": {+ "build": "tsx scripts/build.ts",+ "dev": "tsx watch src/index.ts | pino-pretty --colorize --ignore pid,hostname --messageKey event --translateTime SYS:HH:MM:ss.l",+ "test": "vitest",+ "test:unit": "vitest run tests/unit",+ "test:integration": "vitest run tests/integration",+ "typecheck": "tsc --noEmit",+ "lint": "oxlint --quiet",+ "lint:fix": "oxlint --fix --quiet",+ "format": "oxfmt \"./**/*.{js,mjs,ts,tsx,json,yaml,yml}\"",+ "format:check": "oxfmt --check \"./**/*.{js,mjs,ts,tsx,json,yaml,yml}\"",+ "fix": "pnpm lint:fix; s=$?; pnpm format && exit $s"+ },+ "dependencies": {+ "@hono/node-server": "^2.0.2",+ "hono": "^4.12.18",+ "jose": "^6.0.10",+ "pino": "^8.6.0",+ "prom-client": "^14.2.0"+ },+ "devDependencies": {+ "@types/node": "^22.17.2",+ "esbuild": "^0.25.11",+ "oxfmt": "catalog:",+ "oxlint": "^1.72.0",+ "pino-pretty": "^9.1.0",+ "tsx": "^4.20.5",+ "typescript": "catalog:",+ "vite-tsconfig-paths": "^5.1.4",+ "vitest": "^3.2.4"+ }+}diff --git a/services/integration-service/scripts/build.ts b/services/integration-service/scripts/build.tsnew file mode 100644index 000000000000..a78453c8c8f0--- /dev/null+++ b/services/integration-service/scripts/build.ts@@ -0,0 +1,13 @@+import { build } from 'esbuild'++await build({+ entryPoints: ['src/index.ts'],+ bundle: true,+ platform: 'node',+ target: 'node22',+ format: 'esm',+ outfile: 'dist/integration-service.mjs',+ sourcemap: true,+ // Bundled CJS deps (pino) call a global `require`, which ESM does not have.+ banner: { js: `import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);` },+})diff --git a/services/integration-service/src/auth/jwt.ts b/services/integration-service/src/auth/jwt.tsnew file mode 100644index 000000000000..934e201ff48b--- /dev/null+++ b/services/integration-service/src/auth/jwt.ts@@ -0,0 +1,94 @@+// HS256 JWT verification, following the recording-api scheme (PostHog/posthog#67476).+//+// The deployment is WHICH KEY VERIFIES the token, never a claim, so there is nothing in the+// token an attacker could edit to become a different deployment. The `keys` claim is the+// whole request scope, so a token lifted from a log unlocks one call's fields.++import { jwtVerify } from 'jose'++import type { CallerIdentity } from '../types'+import type { SigningKeyLoader } from './registry'+import { AUDIENCE, AuthError, type AuthFailureReason } from './types'++/**+ * Map a jose failure to a rejection reason, or null when it only means "not this key". Only+ * the key that verifies the signature reaches the claim checks, so at most one is non-null.+ */+function rejectionReason(err: unknown): AuthFailureReason | null {+ const code = (err as { code?: string }).code+ switch (code) {+ case 'ERR_JWS_INVALID':+ case 'ERR_JWT_INVALID':+ return 'malformed'+ case 'ERR_JWT_EXPIRED':+ return 'expired'+ case 'ERR_JWT_CLAIM_VALIDATION_FAILED':+ return (err as { claim?: string }).claim === 'exp' ? 'no_expiry' : 'bad_audience'+ default:+ return null+ }+}++function stringArray(value: unknown): string[] {+ if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) {+ return []+ }+ return value as string[]+}++export class JwtVerifier {+ constructor(private readonly keys: SigningKeyLoader) {}++ async verify(token: string): Promise<CallerIdentity> {+ let payload: Record<string, unknown> | undefined+ let deployment = ''+ let reason: AuthFailureReason = 'bad_signature'++ outer: for (const [candidate, candidateKeys] of this.keys.entries()) {+ for (const key of candidateKeys) {+ try {+ const result = await jwtVerify(token, new TextEncoder().encode(key), {+ algorithms: ['HS256'],+ audience: AUDIENCE,+ // jose only checks `exp` when the claim is present, so without this+ // a token minted without one verifies and never expires.+ requiredClaims: ['exp'],+ })+ payload = result.payload as Record<string, unknown>+ deployment = candidate+ break outer+ } catch (err) {+ reason = rejectionReason(err) ?? reason+ }+ }+ }++ if (!payload) {+ throw new AuthError(reason, 'token was not accepted')+ }++ const requested = stringArray(payload['keys'])+ if (requested.length === 0) {+ throw new AuthError('no_keys_claim', 'token carries no keys claim — the request scope is the token')+ }++ return {+ deployment,+ caller: typeof payload['caller'] === 'string' ? payload['caller'] : '',+ // A repeat would otherwise be resolved, counted and logged once per occurrence.+ requestedKeys: [...new Set(requested)],+ }+ }+}++/** Pull the bearer token out of an Authorization header. */+export function bearerToken(header: string | undefined): string {+ if (!header?.startsWith('Bearer ')) {+ throw new AuthError('missing_token', 'no bearer token')+ }+ const token = header.slice('Bearer '.length).trim()+ if (!token) {+ throw new AuthError('missing_token', 'empty bearer token')+ }+ return token+}diff --git a/services/integration-service/src/auth/registry.ts b/services/integration-service/src/auth/registry.tsnew file mode 100644index 000000000000..d0a53c66337d--- /dev/null+++ b/services/integration-service/src/auth/registry.ts@@ -0,0 +1,104 @@+// The service's signing keys, one flat `__CALLER_KEY_<DEPLOYMENT>` entry per caller in the+// same mounted secret as the secrets. The same value goes into that deployment's own+// secret as INTEGRATION_SERVICE_JWT_SECRET.+//+// Deployment names are DERIVED from the entries present, not declared in code, so revoking+// a compromised caller is a secrets edit with no deploy, and it leaves every other caller+// working. That containment is what this design relies on instead of an allowlist.++import { logger } from '../lib/logging'+import { signingKeyReloadFailuresTotal, signingKeysLastLoadedTimestamp } from '../metrics'+import { RESERVED_PREFIX, readMount } from '../mount'+import type { SigningKeys } from './types'++/** Reserved-prefixed, so the mount never serves a signing key as a secret. */+export const CALLER_KEY_PREFIX = `${RESERVED_PREFIX}CALLER_KEY_`++/**+ * Reject a value listed under two deployments: the verifier stops at the first entry that+ * verifies, so they collapse into one identity, revoking either fails to cut it off, and+ * every attribution names the wrong caller. Invisible in an opaque value, so fail at load.+ */+export function assertNoSharedKeys(keys: SigningKeys): void {+ const owner = new Map<string, string>()+ for (const [deployment, values] of Object.entries(keys)) {+ for (const value of values) {+ const existing = owner.get(value)+ if (existing && existing !== deployment) {+ throw new Error(`signing key for ${deployment} is also listed for ${existing}`)+ }+ owner.set(value, deployment)+ }+ }+}++/** Every signing key on the mount, keyed by deployment. */+export async function readSigningKeys(dir: string): Promise<SigningKeys> {+ const values = (await readMount(dir)) ?? {}+ const keys: SigningKeys = {}+ for (const [entry, value] of Object.entries(values)) {+ if (!entry.startsWith(CALLER_KEY_PREFIX)) {+ continue+ }+ const listed = value+ .split(',')+ .map((part) => part.trim())+ .filter(Boolean)+ if (listed.length === 0) {+ continue+ }+ const deployment = entry.slice(CALLER_KEY_PREFIX.length).toLowerCase().replaceAll('_', '-')+ if (keys[deployment]) {+ // Silently keeping the last entry would drop a key set a revocation had just+ // edited, so the revocation would look like it landed and would not have.+ throw new Error(`two mount entries both name the deployment ${deployment}`)+ }+ keys[deployment] = listed+ }+ return keys+}++export class SigningKeyLoader {+ private keys: SigningKeys = {}+ private loaded = false++ constructor(private readonly dir: string) {}++ /** Replace the in-memory key set. Throws on the first load so boot fails closed. */+ async load(): Promise<void> {+ const keys = await readSigningKeys(this.dir)+ if (Object.keys(keys).length === 0) {+ throw new Error(`no ${CALLER_KEY_PREFIX}* entries on the secret mount at ${this.dir}`)+ }+ assertNoSharedKeys(keys)+ this.keys = keys+ this.loaded = true+ signingKeysLastLoadedTimestamp.set(Date.now() / 1000)+ logger.info('auth:signing_keys_loaded', { deployments: Object.keys(keys).sort() })+ }++ /**+ * Reload, keeping the previous keys if the mount is unreadable or invalid, so a+ * malformed edit cannot lock a running fleet out. The metrics make that fail-open+ * visible when a revocation does not land.+ */+ async reload(): Promise<void> {+ try {+ await this.load()+ } catch (err) {+ signingKeyReloadFailuresTotal.inc()+ logger.error('auth:signing_keys_reload_failed', {+ error: err instanceof Error ? err.message : String(err),+ })+ }+ }++ get isLoaded(): boolean {+ return this.loaded+ }++ /** Every deployment and its accepted keys, for the verifier to try in turn. */+ entries(): [string, string[]][] {+ return Object.entries(this.keys)+ }+}diff --git a/services/integration-service/src/auth/types.ts b/services/integration-service/src/auth/types.tsnew file mode 100644index 000000000000..9e7dab14bb31--- /dev/null+++ b/services/integration-service/src/auth/types.ts@@ -0,0 +1,30 @@+export const AUDIENCE = 'posthog:integration_service'++/** Why a token was rejected. A metric label, so keep the set small and stable. */+export type AuthFailureReason =+ | 'missing_token'+ | 'malformed'+ | 'bad_signature'+ | 'expired'+ | 'no_expiry'+ | 'bad_audience'+ | 'no_keys_claim'++export class AuthError extends Error {+ constructor(+ readonly reason: AuthFailureReason,+ message: string+ ) {+ super(message)+ this.name = 'AuthError'+ }+}++/**+ * Signing keys per deployment, newest first. All are accepted for verification; the+ * deployment signs with the first, so a key rotation is zero-downtime.+ *+ * The deployment a token belongs to is whichever key set verifies it. Nothing in the+ * token asserts it, so it cannot be forged by editing a claim.+ */+export type SigningKeys = Record<string, string[]>diff --git a/services/integration-service/src/http/app.ts b/services/integration-service/src/http/app.tsnew file mode 100644index 000000000000..ea47db286c84--- /dev/null+++ b/services/integration-service/src/http/app.ts@@ -0,0 +1,77 @@+// HTTP surface. One functional route: the request scope lives entirely in the JWT, so+// `resolve` takes no body (see auth/jwt.ts). It is a POST so no intermediary treats a+// secret response as cacheable.++import { Hono } from 'hono'++import { bearerToken, type JwtVerifier } from '../auth/jwt'+import { AuthError } from '../auth/types'+import { logger } from '../lib/logging'+import { authFailuresTotal, httpRequestDurationSeconds, httpRequestsTotal } from '../metrics'+import { resolveKeys } from '../resolve'+import type { Lifecycle, MountedSecrets } from '../types'++export interface AppOptions {+ verifier: JwtVerifier+ lifecycle: Lifecycle+ secrets: () => MountedSecrets | null+}++export function createApp(opts: AppOptions): Hono {+ const app = new Hono()++ app.use('*', async (c, next) => {+ const start = performance.now()+ try {+ await next()+ } finally {+ // The registered route pattern, not the raw path: an unmatched request labels+ // as the router's catch-all, so nobody can grow the series set with URLs.+ const labels = { method: c.req.method, route: c.req.routePath, status: String(c.res.status) }+ httpRequestsTotal.labels(labels).inc()+ httpRequestDurationSeconds.labels(labels).observe((performance.now() - start) / 1000)+ }+ })++ app.get('/_liveness', (c) => c.json({ status: 'ok' }))++ // Not ready until the pod holds secrets: one that does not would answer every+ // resolve all-missing, which callers treat as terminal rather than retryable.+ app.get('/_readiness', (c) => {+ if (opts.lifecycle.shuttingDown) {+ return c.json({ status: 'shutting_down' }, 503)+ }+ if (!opts.lifecycle.ready) {+ return c.json({ status: 'starting' }, 503)+ }+ return c.json({ status: 'ok' })+ })++ app.post('/v1/secrets/resolve', async (c) => {+ let identity+ try {+ identity = await opts.verifier.verify(bearerToken(c.req.header('Authorization')))+ } catch (err) {+ if (err instanceof AuthError) {+ authFailuresTotal.labels({ reason: err.reason }).inc()+ logger.warn('auth:rejected', { reason: err.reason })+ return c.json({ error: 'Unauthorized' }, 401)+ }+ throw err+ }++ // Never answered as an all-`missing` response: a caller treats a missing key as+ // terminal, so answering that way during a cold start would turn an unavailable+ // service into what looks like a deleted secret. A failed re-read keeps the+ // secrets already held and never lands here.+ const mounted = opts.secrets()+ if (!mounted) {+ logger.error('resolve:no_secrets_held', { deployment: identity.deployment })+ return c.json({ error: 'Secret store unavailable' }, 503)+ }++ return c.json(resolveKeys(identity, mounted))+ })++ return app+}diff --git a/services/integration-service/src/index.ts b/services/integration-service/src/index.tsnew file mode 100644index 000000000000..59c97faa3d0d--- /dev/null+++ b/services/integration-service/src/index.ts@@ -0,0 +1,12 @@+import { loadConfig } from './lib/config'+import { logger } from './lib/logging'+import { IntegrationServer } from './server'++async function main(): Promise<void> {+ await new IntegrationServer(loadConfig()).start()+}++main().catch((err: unknown) => {+ logger.error('fatal', { error: err instanceof Error ? err.message : String(err) })+ process.exit(1)+})diff --git a/services/integration-service/src/lib/config.ts b/services/integration-service/src/lib/config.tsnew file mode 100644index 000000000000..1787ec308d92--- /dev/null+++ b/services/integration-service/src/lib/config.ts@@ -0,0 +1,58 @@+// Configuration, read from the environment once at boot. Anything missing or malformed+// that the service cannot safely run without fails the boot rather than a request later.++export interface Config {+ port: number+ host: string+ /** Wait before draining, so Kubernetes has removed the pod from its endpoints first. */+ shutdownPrestopDelayMs: number++ /** Logical environment (dev | prod-us | prod-eu). */+ env: string++ /** Directory the Kubernetes Secret is mounted at. */+ mountDir: string++ /** How often to re-read the mount. Kubelet updates it in roughly 60-90s. */+ reloadSeconds: number++ /** Serves /metrics on its own listener, kept off the ingress like every other service. */+ metricsPort: number+}++function intFromEnv(key: string, fallback: number, min = 0): number {+ const raw = process.env[key]+ if (!raw) {+ return fallback+ }+ // Fail loudly rather than default or truncate: "30abc" must not run as 30, and a+ // zero reload interval would re-read the mount in a 1ms setInterval loop.+ if (!/^\d+$/.test(raw) || Number.parseInt(raw, 10) < min) {+ throw new Error(`${key} must be an integer >= ${min}, got ${JSON.stringify(raw)}`)+ }+ return Number.parseInt(raw, 10)+}++export function loadConfig(): Config {+ const config: Config = {+ port: intFromEnv('PORT', 8004),+ host: process.env.HOST ?? '0.0.0.0',+ shutdownPrestopDelayMs: intFromEnv('SHUTDOWN_PRESTOP_DELAY_MS', 5000),++ env: process.env.INTEGRATION_SERVICE_ENV ?? 'dev',++ mountDir: process.env.INTEGRATION_SERVICE_SECRETS_DIR ?? '/etc/integration-secrets',++ // Shorter than kubelet's own sync so a rotation is visible within about a minute+ // of the mount changing.+ reloadSeconds: intFromEnv('INTEGRATION_SERVICE_RELOAD_SECONDS', 30, 1),++ metricsPort: intFromEnv('INTEGRATION_SERVICE_METRICS_PORT', 9090),+ }++ if (process.env.NODE_ENV === 'production' && !process.env.INTEGRATION_SERVICE_ENV) {+ throw new Error('missing required configuration: INTEGRATION_SERVICE_ENV')+ }++ return config+}diff --git a/services/integration-service/src/lib/logging.ts b/services/integration-service/src/lib/logging.tsnew file mode 100644index 000000000000..b6a0d3586fc1--- /dev/null+++ b/services/integration-service/src/lib/logging.ts@@ -0,0 +1,37 @@+// Leveled logger backed by pino.+//+// Never constructs a pino transport: prod runs the esbuild bundle, and a transport spawns+// a worker needing lib/worker.js + __dirname, neither of which exists in a single-file ESM+// bundle. Dev pipes this JSON through the pino-pretty CLI instead.++import pino from 'pino'++type LogLevel = 'debug' | 'info' | 'warn' | 'error'++function resolveLevel(): LogLevel {+ const explicit = process.env.INTEGRATION_SERVICE_LOG_LEVEL?.toLowerCase()+ if (explicit === 'debug' || explicit === 'info' || explicit === 'warn' || explicit === 'error') {+ return explicit+ }+ switch (process.env.NODE_ENV) {+ case 'production':+ return 'info'+ case 'test':+ return 'warn'+ default:+ return 'debug'+ }+}++const pinoOptions: pino.LoggerOptions = { level: resolveLevel() }+if (process.env.NODE_ENV === 'production') {+ pinoOptions.formatters = { level: (label) => ({ level: label }) }+}+const pinoLogger = pino(pinoOptions)++export const logger = {+ debug: (event: string, fields?: Record<string, unknown>): void => pinoLogger.debug({ event, ...fields }),+ info: (event: string, fields?: Record<string, unknown>): void => pinoLogger.info({ event, ...fields }),+ warn: (event: string, fields?: Record<string, unknown>): void => pinoLogger.warn({ event, ...fields }),+ error: (event: string, fields?: Record<string, unknown>): void => pinoLogger.error({ event, ...fields }),+}diff --git a/services/integration-service/src/metrics.ts b/services/integration-service/src/metrics.tsnew file mode 100644index 000000000000..8bdec82cd3f0--- /dev/null+++ b/services/integration-service/src/metrics.ts@@ -0,0 +1,99 @@+// No label value ever comes from a request: a key name becomes a label only once the mount+// is known to carry it, anything else collapses to a constant, and the untrusted `caller`+// claim is not a label at all. prom-client holds every series for the pod's lifetime, so an+// unbounded label set is a memory leak a caller could drive.++import { Counter, Gauge, Histogram, Registry, collectDefaultMetrics } from 'prom-client'++import type { ResolveOutcome } from './types'++export const register = new Registry()++collectDefaultMetrics({ register, prefix: 'integration_service_' })++export const resolveTotal = new Counter({+ name: 'integration_secret_resolve_total',+ help: 'Secret resolutions, by deployment, key and outcome',+ labelNames: ['deployment', 'key', 'result'],+ registers: [register],+})++export const lastResolvedTimestamp = new Gauge({+ name: 'integration_secret_last_resolved_timestamp',+ help: 'Unix timestamp of the last successful resolution of a secret',+ labelNames: ['key'],+ registers: [register],+})++// How much traffic is reading a secret that is mid-rotation. Says nothing about whether+// anyone needed the previous value.+export const previousVersionServedTotal = new Counter({+ name: 'integration_secret_previous_version_served_total',+ help: 'Responses in which a previous (<KEY>_FALLBACKS) value was included alongside the current one',+ labelNames: ['key'],+ registers: [register],+})++// An unreadable mount keeps the secrets already held rather than failing every read, so+// this gauge is the only sign of that degradation. Alert on it.+export const servingStaleSeconds = new Gauge({+ name: 'integration_secret_serving_stale_seconds',+ help: 'Age of the secrets still being served because the mount could not be re-read (0 when healthy)',+ registers: [register],+})++export const mountErrorsTotal = new Counter({+ name: 'integration_secret_store_errors_total',+ help: 'Reads of the secret mount that returned nothing',+ registers: [register],+})++export const httpRequestsTotal = new Counter({+ name: 'integration_service_http_requests_total',+ help: 'Total HTTP requests received',+ labelNames: ['method', 'route', 'status'],+ registers: [register],+})++export const httpRequestDurationSeconds = new Histogram({+ name: 'integration_service_http_request_duration_seconds',+ help: 'HTTP request duration in seconds',+ labelNames: ['method', 'route', 'status'],+ buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],+ registers: [register],+})++export const authFailuresTotal = new Counter({+ name: 'integration_service_auth_failures_total',+ help: 'Rejected requests, by why the token was not accepted',+ labelNames: ['reason'],+ registers: [register],+})++// The signing-key reload fails open so a malformed edit cannot lock a running fleet out.+// These two make that alertable: staleness on the gauge means a revocation has not landed+// on this pod.+export const signingKeysLastLoadedTimestamp = new Gauge({+ name: 'integration_service_signing_keys_last_loaded_timestamp',+ help: 'Unix timestamp of the last successful load of the caller signing keys',+ registers: [register],+})++export const signingKeyReloadFailuresTotal = new Counter({+ name: 'integration_service_signing_key_reload_failures_total',+ help: 'Background signing-key reloads that failed, leaving the previous key set in place',+ registers: [register],+})++export const shuttingDown = new Gauge({+ name: 'integration_service_shutting_down',+ help: '1 if the service is in the process of shutting down, 0 otherwise',+ registers: [register],+})++export function observeResolve(deployment: string, key: string, result: ResolveOutcome): void {+ resolveTotal.labels({ deployment, key, result }).inc()+ if (result === 'ok') {+ lastResolvedTimestamp.labels({ key }).set(Date.now() / 1000)+ }+}diff --git a/services/integration-service/src/mount.ts b/services/integration-service/src/mount.tsnew file mode 100644index 000000000000..6ab3a9babcbd--- /dev/null+++ b/services/integration-service/src/mount.ts@@ -0,0 +1,160 @@+// The mounted Kubernetes Secret: reads it and holds the secrets it carries.+//+// Kubelet projects the secret as a directory, one file per key, and rewrites it in place+// when the content changes, swapping the `..data` symlink atomically. So a rotation reaches+// the pod without a restart and a read never sees a half-written set.++import { createHash } from 'node:crypto'+import { readFile, readdir, readlink } from 'node:fs/promises'+import { join } from 'node:path'++import { logger } from './lib/logging'+import { mountErrorsTotal, servingStaleSeconds } from './metrics'+import type { Secret, MountedSecrets } from './types'++/**+ * Marks an entry that is never served as a secret, whatever a token asks for. Secret+ * names are the third party's own environment-variable names, so a double underscore cannot+ * collide with one.+ */+export const RESERVED_PREFIX = '__'++/** Comma-separated names of the secrets that are in recovery. */+export const RECOVERY_KEYS = 'INTEGRATION_RECOVERY_KEYS'++/** Suffix holding the outgoing value during a rotation, comma-separated, newest first. */+export const FALLBACK_SUFFIX = '_FALLBACKS'++function commaList(value: string | undefined): string[] {+ if (!value) {+ return []+ }+ return value+ .split(',')+ .map((part) => part.trim())+ .filter(Boolean)+}++/** Every file on the mount, by name. Kubelet's own dot-prefixed bookkeeping is skipped. */+export async function readMount(dir: string): Promise<Record<string, string> | null> {+ // Kubelet swaps `..data` atomically between versions. Reading through the resolved+ // target pins one version for the whole loop, so a swap mid-read cannot hand back a+ // mix of old and new entries.+ let root = dir+ try {+ root = join(dir, await readlink(join(dir, '..data')))+ } catch {+ // Not a kubelet projection (tests, local dev): read the directory as-is.+ }++ let entries: string[]+ try {+ entries = await readdir(root)+ } catch (err) {+ logger.error('mount:unreadable', { dir, error: err instanceof Error ? err.message : String(err) })+ return null+ }++ const values: Record<string, string> = {}+ for (const entry of entries.filter((name) => !name.startsWith('.'))) {+ try {+ // Trailing newlines are easy to introduce by hand and would silently break an+ // API call, so trim rather than trust the file byte for byte.+ values[entry] = (await readFile(join(root, entry), 'utf8')).trim()+ } catch (err) {+ logger.warn('mount:entry_unreadable', {+ key: entry,+ error: err instanceof Error ? err.message : String(err),+ })+ }+ }++ return values+}++export interface SecretMountOptions {+ /** Directory the Kubernetes Secret is mounted at. */+ dir: string+ now?: () => number+}++/**+ * Holds the last successfully parsed secret set. A reload that fails keeps serving what+ * is already held, so a mount blip does not take a warm pod out of rotation; the staleness+ * gauge is what makes that visible.+ */+export class SecretMount {+ private held: MountedSecrets | null = null++ constructor(private readonly opts: SecretMountOptions) {}++ /**+ * The secrets currently being served. Null until the first successful read, which is+ * what the server's readiness probe reports: a pod with no secrets must not serve,+ * because it would answer every resolve all-missing, which callers treat as terminal.+ */+ current(): MountedSecrets | null {+ return this.held+ }++ async reload(): Promise<void> {+ const now = this.opts.now ?? Date.now+ const values = await readMount(this.opts.dir)+ const next = values ? this.build(values) : null+ if (next) {+ this.held = next+ servingStaleSeconds.set(0)+ } else {+ mountErrorsTotal.inc()+ if (this.held) {+ servingStaleSeconds.set((now() - Date.parse(this.held.fetchedAt)) / 1000)+ }+ }+ }++ private build(values: Record<string, string>): MountedSecrets | null {+ // Sorted so the same content always hashes to the same version id.+ const contentHash = createHash('sha256')+ .update(+ Object.keys(values)+ .sort()+ .map((key) => `${key}=${values[key]}`)+ .join('\n')+ )+ .digest('hex')+ .slice(0, 16)++ const inRecovery = new Set(commaList(values[RECOVERY_KEYS]))+ const fetchedAt = new Date().toISOString()+ const secrets: Record<string, Secret> = {}++ for (const [key, value] of Object.entries(values)) {+ // Signing keys, the recovery list and rotation siblings are the mount's own+ // machinery; served as secrets they would leak the outgoing value of a+ // rotation and the list of burned keys.+ if (key.startsWith(RESERVED_PREFIX) || key === RECOVERY_KEYS || key.endsWith(FALLBACK_SUFFIX)) {+ continue+ }+ if (inRecovery.has(key)) {+ secrets[key] = { state: 'recovery', versionId: contentHash, fetchedAt }+ continue+ }+ const previous = commaList(values[`${key}${FALLBACK_SUFFIX}`])[0]+ if (previous !== undefined && previous !== value) {+ secrets[key] = { state: 'rotating', value, previous, versionId: contentHash, fetchedAt }+ continue+ }+ secrets[key] = { state: 'steady', value, versionId: contentHash, fetchedAt }+ }++ if (Object.keys(secrets).length === 0) {+ // Counting files rather than secrets would call a mount holding nothing but+ // signing keys healthy, and every resolve would answer all-missing, which a+ // caller treats as a deleted secret.+ logger.warn('mount:no_secrets', { dir: this.opts.dir })+ return null+ }++ return { fetchedAt, versionId: contentHash, secrets }+ }+}diff --git a/services/integration-service/src/resolve.ts b/services/integration-service/src/resolve.tsnew file mode 100644index 000000000000..586bec424dd9--- /dev/null+++ b/services/integration-service/src/resolve.ts@@ -0,0 +1,69 @@+// Turns a verified token plus what the mount holds into a response.+//+// The `keys` claim alone bounds what a request may read. There is no per-deployment+// allowlist, because a list bounds nothing the deployment's signing key does not already+// bound: a compromised deployment is contained by revoking that key.+//+// `missing` covers both a name the mount does not carry and a reserved entry it refuses to+// serve, reported per key rather than failing the batch.++import { logger } from './lib/logging'+import { observeResolve, previousVersionServedTotal } from './metrics'+import type { CallerIdentity, MountedSecrets, ResolveOutcome } from './types'++/** Stand-in label for a name the mount does not carry, which is caller-supplied text. */+const UNKNOWN_KEY = 'unknown'++/** Wire shape of one resolved secret. snake_case because Python is the primary consumer. */+export interface WireSecret {+ state: string+ value?: string+ previous?: string+ version_id: string+ fetched_at: string+}++export interface ResolveResponse {+ secrets: Record<string, WireSecret>+ missing: string[]+}++export function resolveKeys(identity: CallerIdentity, mounted: MountedSecrets): ResolveResponse {+ const secrets: Record<string, WireSecret> = {}+ const missing: string[] = []+ const served: string[] = []++ for (const key of identity.requestedKeys) {+ const secret = mounted.secrets[key]+ if (!secret) {+ missing.push(key)+ observeResolve(identity.deployment, UNKNOWN_KEY, 'missing')+ continue+ }++ const outcome: ResolveOutcome = secret.state === 'recovery' ? 'recovery' : 'ok'+ const wire: WireSecret = {+ state: secret.state,+ version_id: secret.versionId,+ fetched_at: secret.fetchedAt,+ }+ if (secret.value !== undefined) {+ wire.value = secret.value+ }+ if (secret.previous !== undefined) {+ wire.previous = secret.previous+ previousVersionServedTotal.labels({ key }).inc()+ }+ secrets[key] = wire+ observeResolve(identity.deployment, key, outcome)+ if (outcome === 'ok') {+ served.push(key)+ }+ }++ // One audit line per request rather than per key, so Loki keeps the whole request+ // together. The key list is bounded by the token scope, so it stays readable.+ logger.info('secrets:resolved', { deployment: identity.deployment, caller: identity.caller, served, missing })++ return { secrets, missing }+}diff --git a/services/integration-service/src/server.ts b/services/integration-service/src/server.tsnew file mode 100644index 000000000000..0bfd80e72165--- /dev/null+++ b/services/integration-service/src/server.ts@@ -0,0 +1,189 @@+// Wires the service together and owns its lifecycle.+//+// Shutdown order is fixed: mark draining, wait out the prestop delay so Kubernetes has+// stopped routing here, drain the HTTP server, exit. unhandledRejection and+// uncaughtException take the same path rather than dropping in-flight requests.++import { serve } from '@hono/node-server'+import type { Hono } from 'hono'+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'++import { JwtVerifier } from './auth/jwt'+import { SigningKeyLoader } from './auth/registry'+import { createApp } from './http/app'+import type { Config } from './lib/config'+import { logger } from './lib/logging'+import { register, shuttingDown } from './metrics'+import { SecretMount } from './mount'+import type { Lifecycle } from './types'++/** How long a drain may take once the prestop window has passed. */+const DRAIN_TIMEOUT_MS = 10_000++interface DrainableServer {+ close(cb: () => void): void+}++type ServeFn = (+ options: { fetch: Hono['fetch']; port: number; hostname: string },+ listeningListener: (info: { port: number }) => void+) => DrainableServer++/** Test seams. Production construction passes none of these. */+export interface IntegrationServerOverrides {+ serve?: ServeFn+ exit?: (code: number) => void+}++const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))++/** Run `task` every `intervalMs`. The timer is unref'd; the return value cancels it. */+export function every(intervalMs: number, task: () => Promise<void>): () => void {+ // A rejecting task would otherwise reach the unhandledRejection handler and exit the+ // process, so a blip in whatever the task talks to would take the pod down.+ const timer = setInterval(() => {+ task().catch((err: unknown) => {+ logger.error('timer:task_failed', { error: err instanceof Error ? err.message : String(err) })+ })+ }, intervalMs)+ timer.unref()+ return () => clearInterval(timer)+}++export class IntegrationServer {+ private readonly lifecycle: Lifecycle = { shuttingDown: false, ready: false }+ private server: DrainableServer | undefined+ private metricsServer: Server | undefined+ private mount: SecretMount | undefined+ private signingKeys: SigningKeyLoader | undefined+ private cancelTimers: (() => void)[] = []+ private processListeners = new Map<string, (...args: unknown[]) => void>()+ private stopping = false++ constructor(+ private readonly config: Config,+ private readonly overrides: IntegrationServerOverrides = {}+ ) {}++ /** For probes and tests. The object is live; do not mutate it. */+ lifecycleState(): Lifecycle {+ return this.lifecycle+ }++ /** The port the metrics listener bound, once start() has run. */+ metricsPort(): number | undefined {+ const address = this.metricsServer?.address()+ return address && typeof address === 'object' ? (address as AddressInfo).port : undefined+ }++ /** Re-read the signing keys and the mount now, without waiting for the timer. */+ async reload(): Promise<void> {+ // Keys before secrets: a revocation and a rotation can land in one secret+ // edit, and the revoked caller must not see the new values in the gap between.+ await this.signingKeys?.reload()+ await this.mount?.reload()+ this.lifecycle.ready = this.mount?.current() != null+ }++ async start(): Promise<void> {+ const config = this.config++ const signingKeys = new SigningKeyLoader(config.mountDir)+ this.signingKeys = signingKeys+ await signingKeys.load()++ const mount = new SecretMount({ dir: config.mountDir })+ this.mount = mount++ const app = createApp({+ verifier: new JwtVerifier(signingKeys),+ lifecycle: this.lifecycle,+ secrets: () => mount.current(),+ })++ await mount.reload()+ this.lifecycle.ready = mount.current() != null+ if (!this.lifecycle.ready) {+ logger.error('startup:no_secrets_on_mount', { dir: config.mountDir })+ }++ const serveFn = this.overrides.serve ?? serve+ this.server = serveFn({ fetch: app.fetch, port: config.port, hostname: config.host }, (info) => {+ logger.info('server:started', { host: config.host, port: info.port, env: config.env })+ })++ // Its own listener, never the serving port: the chart exposes only `port`, so the+ // scrape stays in-cluster the same way every other service's does.+ this.metricsServer = createServer((req, res) => {+ if (req.url !== '/metrics') {+ res.statusCode = 404+ res.end()+ return+ }+ shuttingDown.set(this.lifecycle.shuttingDown ? 1 : 0)+ register.metrics().then(+ (body) => {+ res.setHeader('Content-Type', register.contentType)+ res.end(body)+ },+ () => {+ res.statusCode = 500+ res.end()+ }+ )+ })+ this.metricsServer.listen(config.metricsPort, config.host)++ this.cancelTimers.push(every(config.reloadSeconds * 1000, () => this.reload()))++ this.setupProcessListeners()+ }++ async stop(signal: string, error?: Error): Promise<void> {+ if (this.stopping) {+ return+ }+ this.stopping = true++ for (const [event, handler] of this.processListeners) {+ process.removeListener(event, handler)+ }+ this.processListeners.clear()++ logger.info('shutdown:start', { signal })+ this.lifecycle.shuttingDown = true+ for (const cancel of this.cancelTimers) {+ cancel()+ }++ await sleep(this.config.shutdownPrestopDelayMs)+ const server = this.server+ if (server) {+ await Promise.race([new Promise<void>((resolve) => server.close(() => resolve())), sleep(DRAIN_TIMEOUT_MS)])+ }+ this.metricsServer?.close()++ logger.info('shutdown:complete', {})+ const exit = this.overrides.exit ?? process.exit+ exit(error ? 1 : 0)+ }++ private setupProcessListeners(): void {+ const on = (event: string, handler: (...args: unknown[]) => void): void => {+ this.processListeners.set(event, handler)+ process.on(event, handler)+ }+ on('SIGTERM', () => void this.stop('SIGTERM'))+ on('SIGINT', () => void this.stop('SIGINT'))+ on('unhandledRejection', (reason) => {+ logger.error('fatal:unhandled_rejection', { error: String(reason) })+ void this.stop('unhandledRejection', reason instanceof Error ? reason : new Error(String(reason)))+ })+ on('uncaughtException', (err) => {+ const error = err instanceof Error ? err : new Error(String(err))+ logger.error('fatal:uncaught_exception', { error: error.message })+ void this.stop('uncaughtException', error)+ })+ }+}diff --git a/services/integration-service/src/types.ts b/services/integration-service/src/types.tsnew file mode 100644index 000000000000..aea36af97196--- /dev/null+++ b/services/integration-service/src/types.ts@@ -0,0 +1,54 @@+/**+ * Where a secret stands relative to a rotation.+ *+ * - `steady`: one live value, with no `<KEY>_FALLBACKS` sibling holding a different one.+ * - `rotating`: the sibling holds a different value, and both are served, because a third+ * party may still hand back tokens minted against the old one.+ * - `recovery`: the value is known-burned with no replacement yet, so nothing is served and+ * callers raise a typed error rather than calling out with a secret that cannot work.+ */+export type SecretState = 'steady' | 'rotating' | 'recovery'++/** One secret as the mount holds it. */+export interface Secret {+ state: SecretState+ /** Absent only in `recovery`. */+ value?: string+ /** Present only in `rotating`. */+ previous?: string+ versionId: string+ /** When the mount this value came from was last read. */+ fetchedAt: string+}++/** Every secret on the mount, as one read of it saw them. */+export interface MountedSecrets {+ fetchedAt: string+ /** Hash of the whole mounted key set, so unchanged content keeps one id. */+ versionId: string+ secrets: Record<string, Secret>+}++/** What a verified request is allowed to do, and who to attribute it to. */+export interface CallerIdentity {+ /**+ * The pod set that signed the token, established by which key verified it. This is the+ * authenticated identity and the authorization boundary.+ */+ deployment: string+ /**+ * The product code path that wanted the secret. Caller-supplied and unverified, so+ * it reaches the audit log and nothing else — never a metric label.+ */+ caller: string+ /** The exact keys this one request asked for, from the token's `keys` claim. */+ requestedKeys: readonly string[]+}++/** Per-key outcome, used for both metrics and the usage rollup. */+export type ResolveOutcome = 'ok' | 'missing' | 'recovery'++export interface Lifecycle {+ shuttingDown: boolean+ ready: boolean+}diff --git a/services/integration-service/tests/integration/server.e2e.test.ts b/services/integration-service/tests/integration/server.e2e.test.tsnew file mode 100644index 000000000000..71d31144bd63--- /dev/null+++ b/services/integration-service/tests/integration/server.e2e.test.ts@@ -0,0 +1,193 @@+// End to end over a real mount directory and a real listening socket. Catches wiring+// regressions between the mount, the secrets it holds, auth and the routes that the+// per-module unit tests cannot see.++import { serve } from '@hono/node-server'+import { SignJWT } from 'jose'+import { mkdtemp, rename, rm, unlink, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'++import { AUDIENCE } from '@/auth/types'+import type { Config } from '@/lib/config'+import { IntegrationServer } from '@/server'++const KEY = 'HUBSPOT_APP_CLIENT_SECRET'+const BURNED_KEY = 'STRIPE_APP_SECRET_KEY'+const SIGNING_KEY_ENTRY = '__CALLER_KEY_TEST_DEPLOYMENT'+const CALLER_SIGNING_KEY = 'e2e-caller-signing-key'+const OTHER_SIGNING_KEY = 'e2e-other-signing-key'++function config(mountDir: string): Config {+ return {+ port: 0,+ host: '127.0.0.1',+ shutdownPrestopDelayMs: 0,+ env: 'test',+ mountDir,+ reloadSeconds: 3600,+ metricsPort: 0,+ }+}++async function mint(opts: { signingKey: string; keys?: string[]; expiresIn?: string }): Promise<string> {+ return new SignJWT({ caller: 'warehouse-sources', keys: opts.keys ?? [KEY] })+ .setProtectedHeader({ alg: 'HS256' })+ .setAudience(AUDIENCE)+ .setIssuedAt()+ .setExpirationTime(opts.expiresIn ?? '5m')+ .sign(new TextEncoder().encode(opts.signingKey))+}++function resolve(port: number, token: string): Promise<Response> {+ return fetch(`http://127.0.0.1:${port}/v1/secrets/resolve`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}` },+ })+}++async function mountDir(values: Record<string, string>): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), 'integration-e2e-'))+ await Promise.all(Object.entries(values).map(([key, value]) => writeFile(join(dir, key), value)))+ return dir+}++interface Booted {+ server: IntegrationServer+ port: number+ exitCode: () => number | undefined+}++async function boot(dir: string): Promise<Booted> {+ let exitCode: number | undefined+ let announce!: (port: number) => void+ const listening = new Promise<number>((r) => {+ announce = r+ })+ const server = new IntegrationServer(config(dir), {+ serve: (options, listener) =>+ serve(options, (info) => {+ listener(info)+ announce(info.port)+ }),+ exit: (code) => {+ exitCode = code+ },+ })+ await server.start()+ return { server, port: await listening, exitCode: () => exitCode }+}++describe('integration server end to end', () => {+ it('serves, rotates, recovers and revokes against a live mount', async () => {+ const dir = await mountDir({+ // A trailing newline is what a human editing the secret by hand leaves behind.+ [KEY]: 'current-value-1\n',+ [BURNED_KEY]: 'sk-live-value',+ [SIGNING_KEY_ENTRY]: CALLER_SIGNING_KEY,+ __CALLER_KEY_OTHER_DEPLOYMENT: OTHER_SIGNING_KEY,+ })+ const { server, port, exitCode } = await boot(dir)+ const token = await mint({ signingKey: CALLER_SIGNING_KEY })++ try {+ const steady = await resolve(port, token)+ expect(steady.status).toBe(200)+ expect(await steady.json()).toMatchObject({+ secrets: { [KEY]: { state: 'steady', value: 'current-value-1' } },+ missing: [],+ })++ // A reserved entry is unservable even when a valid token names it, which is+ // what lets the signing keys share a mount with the secrets they protect.+ const reserved = await resolve(+ port,+ await mint({ signingKey: CALLER_SIGNING_KEY, keys: [SIGNING_KEY_ENTRY] })+ )+ const reservedBody = await reserved.text()+ expect(JSON.parse(reservedBody)).toEqual({ secrets: {}, missing: [SIGNING_KEY_ENTRY] })+ expect(reservedBody).not.toContain(CALLER_SIGNING_KEY)++ const expired = await resolve(port, await mint({ signingKey: CALLER_SIGNING_KEY, expiresIn: '-1s' }))+ expect(expired.status).toBe(401)++ const garbage = await resolve(port, 'not-a-jwt')+ expect(garbage.status).toBe(401)++ // A name nothing on the mount carries comes back in `missing`, per key, while+ // the rest of the request still succeeds.+ const unknown = await resolve(+ port,+ await mint({ signingKey: CALLER_SIGNING_KEY, keys: [KEY, 'NO_SUCH_INTEGRATION_KEY'] })+ )+ expect(await unknown.json()).toMatchObject({+ secrets: { [KEY]: { value: 'current-value-1' } },+ missing: ['NO_SUCH_INTEGRATION_KEY'],+ })++ // Start a rotation on the mount; the running server picks it up on reload.+ await writeFile(join(dir, `${KEY}_FALLBACKS`), 'previous-value-0')+ await server.reload()+ expect(await (await resolve(port, token)).json()).toMatchObject({+ secrets: { [KEY]: { state: 'rotating', value: 'current-value-1', previous: 'previous-value-0' } },+ })++ // Completing a rotation is deleting the sibling, and that has to end the+ // overlap rather than serving the retired value forever.+ await unlink(join(dir, `${KEY}_FALLBACKS`))+ await server.reload()+ const settled = (await (await resolve(port, token)).json()) as { secrets: Record<string, unknown> }+ expect(settled.secrets[KEY]).toMatchObject({ state: 'steady', value: 'current-value-1' })+ expect(settled.secrets[KEY]).not.toHaveProperty('previous')++ await writeFile(join(dir, 'INTEGRATION_RECOVERY_KEYS'), BURNED_KEY)+ await server.reload()+ const recovery = await resolve(port, await mint({ signingKey: CALLER_SIGNING_KEY, keys: [BURNED_KEY] }))+ const recoveryBody = await recovery.text()+ expect(JSON.parse(recoveryBody).secrets[BURNED_KEY]).toEqual(expect.objectContaining({ state: 'recovery' }))+ expect(JSON.parse(recoveryBody).secrets[BURNED_KEY]).not.toHaveProperty('value')+ expect(recoveryBody).not.toContain('sk-live-value')++ // The mount vanishing must not take a warm pod out: it keeps serving what it+ // holds, and readiness stays up.+ const held = join(tmpdir(), `integration-e2e-moved-${port}`)+ await rename(dir, held)+ await server.reload()+ expect((await resolve(port, token)).status).toBe(200)+ await rename(held, dir)+ await server.reload()++ // Revoke the caller: the same token must stop working, other callers must not.+ await unlink(join(dir, SIGNING_KEY_ENTRY))+ await server.reload()+ expect((await resolve(port, token)).status).toBe(401)+ expect((await resolve(port, await mint({ signingKey: OTHER_SIGNING_KEY }))).status).toBe(200)++ // The scrape lives on its own listener and never carries a secret value.+ const metricsPort = server.metricsPort()+ expect(metricsPort).toBeDefined()+ expect(metricsPort).not.toBe(port)+ const scrape = await fetch(`http://127.0.0.1:${metricsPort}/metrics`)+ expect(scrape.status).toBe(200)+ const scrapeBody = await scrape.text()+ expect(scrapeBody).toContain('integration_service_http_requests_total')+ expect(scrapeBody).not.toContain('current-value-1')+ } finally {+ await server.stop('SIGTERM')+ await rm(dir, { recursive: true, force: true })+ }+ expect(exitCode()).toBe(0)+ })++ // Boot has to fail closed. A pod that started with no signing keys would reject every+ // caller while reporting itself healthy, which reads as a caller-side outage.+ it('refuses to boot against a mount carrying no caller keys', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'integration-e2e-empty-'))+ try {+ await expect(boot(dir)).rejects.toThrow(/no __CALLER_KEY_\* entries/)+ } finally {+ await rm(dir, { recursive: true, force: true })+ }+ })+})diff --git a/services/integration-service/tests/unit/app.test.ts b/services/integration-service/tests/unit/app.test.tsnew file mode 100644index 000000000000..eeb89247cbef--- /dev/null+++ b/services/integration-service/tests/unit/app.test.ts@@ -0,0 +1,175 @@+import { SignJWT } from 'jose'+import { beforeEach, describe, expect, it } from 'vitest'++import { JwtVerifier } from '@/auth/jwt'+import type { SigningKeyLoader } from '@/auth/registry'+import { AUDIENCE, type SigningKeys } from '@/auth/types'+import { createApp } from '@/http/app'+import { httpRequestsTotal, register } from '@/metrics'+import type { Lifecycle, MountedSecrets } from '@/types'++const RESOLVE_PATH = '/v1/secrets/resolve'++const DEPLOYMENT = 'temporal-worker-data-warehouse'+const SIGNING_KEY = 'a-signing-key'+const KEYS: SigningKeys = { [DEPLOYMENT]: [SIGNING_KEY] }+const KEY = 'HUBSPOT_APP_CLIENT_SECRET'++const MOUNTED: MountedSecrets = {+ fetchedAt: '2026-08-06T00:00:00.000Z',+ versionId: 'v1',+ secrets: { [KEY]: { state: 'steady', value: 'hunter2-zx9q', versionId: 'v1', fetchedAt: 'now' } },+}++async function mint(+ opts: { key?: string; keys?: string[]; expiresIn?: string; audience?: string } = {}+): Promise<string> {+ return new SignJWT({ caller: 'warehouse-sources', keys: opts.keys ?? [KEY] })+ .setProtectedHeader({ alg: 'HS256' })+ .setAudience(opts.audience ?? AUDIENCE)+ .setIssuedAt()+ .setExpirationTime(opts.expiresIn ?? '5m')+ .sign(new TextEncoder().encode(opts.key ?? SIGNING_KEY))+}++function build(+ overrides: {+ lifecycle?: Partial<Lifecycle>+ secrets?: () => MountedSecrets | null+ } = {}+): { app: ReturnType<typeof createApp>; lifecycle: Lifecycle } {+ const lifecycle: Lifecycle = { shuttingDown: false, ready: true, ...overrides.lifecycle }+ const app = createApp({+ verifier: new JwtVerifier({ entries: () => Object.entries(KEYS) } as SigningKeyLoader),+ lifecycle,+ secrets: overrides.secrets ?? ((): MountedSecrets | null => MOUNTED),+ })+ return { app, lifecycle }+}++const authed = async (token?: string): Promise<Request> =>+ new Request(`http://svc${RESOLVE_PATH}`, {+ method: 'POST',+ headers: token ? { Authorization: `Bearer ${token}` } : {},+ })++describe('http surface', () => {+ beforeEach(() => {+ register.resetMetrics()+ })++ describe('resolve', () => {+ it('serves the requested secret to a valid token', async () => {+ const { app } = build()+ const res = await app.request(await authed(await mint()))++ expect(res.status).toBe(200)+ await expect(res.json()).resolves.toMatchObject({ secrets: { [KEY]: { value: 'hunter2-zx9q' } } })+ })++ // Every rejection is a flat 401 with no detail: the reason is a metric label and a+ // log line, not something an unauthenticated caller gets to enumerate.+ it.each([+ ['no Authorization header', undefined],+ ['a garbage token', 'not-a-jwt'],+ ['a token signed with an unknown key', 'wrong-key'],+ ['an expired token', 'expired'],+ ['a token for another audience', 'audience'],+ ])('rejects %s with 401 and no detail', async (_label, kind) => {+ let token: string | undefined+ if (kind === 'not-a-jwt') {+ token = 'not-a-jwt'+ } else if (kind === 'wrong-key') {+ token = await mint({ key: 'nobody-lists-this' })+ } else if (kind === 'expired') {+ token = await mint({ expiresIn: '-1s' })+ } else if (kind === 'audience') {+ token = await mint({ audience: 'posthog:recording_api' })+ }++ const res = await build().app.request(await authed(token))++ expect(res.status).toBe(401)+ await expect(res.json()).resolves.toEqual({ error: 'Unauthorized' })+ })++ // A pod that holds no secrets must not answer all-missing: callers treat a+ // missing key as terminal, so an empty answer would look like a deleted secret+ // rather than an unavailable service.+ it('answers 503 rather than all-missing when it holds no secrets', async () => {+ const { app } = build({ secrets: () => null })+ const res = await app.request(await authed(await mint()))++ expect(res.status).toBe(503)+ })++ it('never returns a secret value on a rejected request', async () => {+ const res = await build().app.request(await authed('not-a-jwt'))+ expect(await res.text()).not.toContain('hunter2-zx9q')+ })+ })++ describe('probes', () => {+ it('reports liveness regardless of readiness', async () => {+ const { app } = build({ lifecycle: { ready: false } })+ expect((await app.request('http://svc/_liveness')).status).toBe(200)+ })++ it.each([+ ['starting', { ready: false, shuttingDown: false }, 503],+ ['ready', { ready: true, shuttingDown: false }, 200],+ ['shutting down', { ready: true, shuttingDown: true }, 503],+ ])('reports %s as %i', async (_label, lifecycle, status) => {+ const { app } = build({ lifecycle })+ expect((await app.request('http://svc/_readiness')).status).toBe(status)+ })++ // Draining has to win over readiness, or Kubernetes keeps routing to a pod that is+ // already closing its listener.+ it('reports not-ready while shutting down even though a snapshot is held', async () => {+ const { app, lifecycle } = build()+ expect((await app.request('http://svc/_readiness')).status).toBe(200)++ lifecycle.shuttingDown = true+ expect((await app.request('http://svc/_readiness')).status).toBe(503)+ })+ })++ // The request scope is the token, full stop. A route change that read a body and+ // merged its key names into the scope would fail here, not in resolve.test.ts, because+ // resolveKeys never sees the HTTP request.+ it('ignores a request body naming keys outside the token scope', async () => {+ const { app } = build()+ const res = await app.request(+ new Request('http://svc/v1/secrets/resolve', {+ method: 'POST',+ headers: { Authorization: `Bearer ${await mint()}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ keys: ['STRIPE_APP_SECRET_KEY'] }),+ })+ )++ expect(res.status).toBe(200)+ const body = (await res.json()) as { secrets: Record<string, unknown> }+ expect(Object.keys(body.secrets)).toEqual([KEY])+ })++ it('never exposes a secret value in the scrape', async () => {+ const { app } = build()+ await app.request(await authed(await mint()))++ expect(await register.metrics()).not.toContain('hunter2-zx9q')+ })++ // An unmatched path must not become a label value, or anyone can grow the series set+ // by requesting random URLs.+ it('collapses every unknown route to one constant metric label', async () => {+ const { app } = build()+ await app.request('http://svc/definitely-not-a-route-9f2a')+ await app.request('http://svc/another-invented-route-c81d')++ const labels = (await httpRequestsTotal.get()).values.map((v) => String(v.labels['route']))+ expect(labels).not.toContain('/definitely-not-a-route-9f2a')+ expect(labels).not.toContain('/another-invented-route-c81d')+ expect(new Set(labels).size).toBe(1)+ })+})diff --git a/services/integration-service/tests/unit/auth.test.ts b/services/integration-service/tests/unit/auth.test.tsnew file mode 100644index 000000000000..5e49c494f7f7--- /dev/null+++ b/services/integration-service/tests/unit/auth.test.ts@@ -0,0 +1,244 @@+import { SignJWT } from 'jose'+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'++import { JwtVerifier, bearerToken } from '@/auth/jwt'+import { SigningKeyLoader } from '@/auth/registry'+import { AUDIENCE, AuthError, type SigningKeys } from '@/auth/types'++const DW = 'temporal-worker-data-warehouse'+const DJANGO = 'posthog-django'++const DW_KEY_NEW = 'dw-signing-key-new'+const DW_KEY_OLD = 'dw-signing-key-old'+const DJANGO_KEY = 'django-signing-key'++const KEYS: SigningKeys = {+ [DW]: [DW_KEY_NEW, DW_KEY_OLD],+ [DJANGO]: [DJANGO_KEY],+}++function verifier(keys: SigningKeys = KEYS): JwtVerifier {+ return new JwtVerifier({ entries: () => Object.entries(keys) } as SigningKeyLoader)+}++async function mint(opts: {+ key: string+ caller?: string+ keys?: unknown+ audience?: string+ expiresIn?: string+ /** Mint with no `exp` at all — the shape jose accepts unless `exp` is required. */+ omitExpiry?: boolean+ omitKeys?: boolean+}): Promise<string> {+ const builder = new SignJWT({+ caller: opts.caller ?? 'warehouse-sources',+ ...(opts.omitKeys ? {} : { keys: opts.keys ?? ['GOOGLE_ADS_APP_CLIENT_SECRET'] }),+ })+ .setProtectedHeader({ alg: 'HS256' })+ .setAudience(opts.audience ?? AUDIENCE)+ .setIssuedAt()+ if (!opts.omitExpiry) {+ builder.setExpirationTime(opts.expiresIn ?? '5m')+ }+ return builder.sign(new TextEncoder().encode(opts.key))+}++// Resolves to the rejection reason, or throws if the token was accepted. Asserts by+// throwing rather than with `expect` inside a catch, which would make the assertion+// conditional on the rejection happening at all.+async function reasonFor(promise: Promise<unknown>): Promise<string> {+ const outcome = await promise.then(+ () => null,+ (err: unknown) => err+ )+ if (!(outcome instanceof AuthError)) {+ throw new Error(`expected the token to be rejected with an AuthError, got ${String(outcome)}`)+ }+ return outcome.reason+}++describe('jwt verification', () => {+ it('accepts a well-formed token and returns the requested keys', async () => {+ const identity = await verifier().verify(await mint({ key: DW_KEY_NEW }))++ expect(identity.deployment).toBe(DW)+ expect(identity.requestedKeys).toEqual(['GOOGLE_ADS_APP_CLIENT_SECRET'])+ })++ // The deployment is whichever key verified, never a claim. There is therefore nothing+ // in the token an attacker could edit to become a different deployment.+ it('derives the deployment from the verifying key, not from the token', async () => {+ const signedByDjango = await verifier().verify(await mint({ key: DJANGO_KEY }))+ const signedByWorker = await verifier().verify(await mint({ key: DW_KEY_NEW }))++ expect(signedByDjango.deployment).toBe(DJANGO)+ expect(signedByWorker.deployment).toBe(DW)+ })++ it('accepts a token signed with a retired key still listed for that deployment', async () => {+ await expect(verifier().verify(await mint({ key: DW_KEY_OLD }))).resolves.toBeDefined()+ })++ it('rejects a token signed with a key no deployment lists', async () => {+ expect(await reasonFor(verifier().verify(await mint({ key: 'nobody-lists-this' })))).toBe('bad_signature')+ })++ it.each([+ ['an expired token', { expiresIn: '-1s' }, 'expired'],+ ['a token for another audience', { audience: 'posthog:recording_api' }, 'bad_audience'],+ ['a token with no keys claim', { keys: [] }, 'no_keys_claim'],+ // A bare string would spread through `new Set(...)` into one requested key per+ // character; a non-string element would slip past validation entirely.+ ['a token whose keys claim is a bare string', { keys: 'STRIPE_APP_SECRET_KEY' }, 'no_keys_claim'],+ ['a token whose keys claim holds a non-string', { keys: ['GOOGLE_ADS_APP_CLIENT_SECRET', 7] }, 'no_keys_claim'],+ ['a token with the keys claim absent', { omitKeys: true }, 'no_keys_claim'],+ // jose validates `exp` only when it is present, so a token minted without one+ // would otherwise verify and never expire. The bound has to live here rather than+ // in whichever client happens to mint today.+ ['a token that never expires', { omitExpiry: true }, 'no_expiry'],+ ])('rejects %s', async (_label, overrides, reason) => {+ const token = await mint({ key: DW_KEY_NEW, ...overrides })+ expect(await reasonFor(verifier().verify(token))).toBe(reason)+ })++ // Widening or dropping `algorithms: ['HS256']` is the classic algorithm-confusion+ // regression, and that one line is all that stands between the service and it.+ it('rejects a token signed with a wider HMAC', async () => {+ const token = await new SignJWT({ caller: 'warehouse-sources', keys: ['A_KEY'] })+ .setProtectedHeader({ alg: 'HS512' })+ .setAudience(AUDIENCE)+ .setIssuedAt()+ .setExpirationTime('5m')+ .sign(new TextEncoder().encode(DW_KEY_NEW))++ await expect(verifier().verify(token)).rejects.toBeInstanceOf(AuthError)+ })++ // Hand-built, because jose refuses to mint one: an unsigned token must not verify.+ it('rejects an unsigned token', async () => {+ const b64 = (value: object): string => Buffer.from(JSON.stringify(value)).toString('base64url')+ const token = `${b64({ alg: 'none' })}.${b64({+ aud: AUDIENCE,+ exp: Math.floor(Date.now() / 1000) + 300,+ keys: ['A_KEY'],+ })}.`++ await expect(verifier().verify(token)).rejects.toBeInstanceOf(AuthError)+ })++ // Two mount entries that normalize onto one deployment name would silently drop a key+ // set, so a revocation would look like it landed and would not have.+ it('rejects a garbage token', async () => {+ expect(await reasonFor(verifier().verify('not-a-jwt'))).toBe('malformed')+ })++ // Untrusted after the registry went away: Django holds one key and hosts many+ // products, so the claim is carried to the audit log and is never a metric label.+ it.each([+ ['a name we would once have recognised', 'cdp'],+ ['a name nobody has ever used', 'something-invented'],+ ])('carries %s through as the caller without touching the deployment', async (_label, caller) => {+ const identity = await verifier().verify(await mint({ key: DW_KEY_NEW, caller }))++ expect(identity.caller).toBe(caller)+ expect(identity.deployment).toBe(DW)+ })++ it('deduplicates a repeated key rather than resolving it twice', async () => {+ const token = await mint({ key: DW_KEY_NEW, keys: ['A_KEY', 'A_KEY'] })+ expect((await verifier().verify(token)).requestedKeys).toEqual(['A_KEY'])+ })+})++describe('signing key registry', () => {+ const dirs: string[] = []++ afterEach(async () => {+ await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true })))+ })++ /** A directory shaped the way kubelet projects a Kubernetes Secret: one file per key. */+ async function mount(values: Record<string, string>): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), 'signing-keys-'))+ dirs.push(dir)+ await Promise.all(Object.entries(values).map(([k, v]) => writeFile(join(dir, k), v)))+ return dir+ }++ it('derives one deployment per __CALLER_KEY_ entry and ignores everything else', async () => {+ const keys = new SigningKeyLoader(+ await mount({+ __CALLER_KEY_POSTHOG_DJANGO: DJANGO_KEY,+ __CALLER_KEY_TEMPORAL_WORKER_DATA_WAREHOUSE: `${DW_KEY_NEW}, ${DW_KEY_OLD}`,+ STRIPE_APP_SECRET_KEY: 'not-a-signing-key',+ })+ )+ await keys.load()++ expect(Object.fromEntries(keys.entries())).toEqual(KEYS)+ })++ it('refuses to boot when the mount carries no caller keys at all', async () => {+ const keys = new SigningKeyLoader(await mount({ STRIPE_APP_SECRET_KEY: 'sec' }))+ await expect(keys.load()).rejects.toThrow(/no __CALLER_KEY_\* entries/)+ expect(keys.isLoaded).toBe(false)+ })++ // The verifier stops at the first key set that verifies, so two deployments sharing a+ // value collapse into one identity: revoking either leaves the other working, and every+ // attribution names the wrong caller. A paste error is invisible in an opaque value, so+ // it has to fail at boot.+ it('refuses to load when two deployments are given the same signing key', async () => {+ const keys = new SigningKeyLoader(+ await mount({+ __CALLER_KEY_POSTHOG_DJANGO: DJANGO_KEY,+ __CALLER_KEY_TEMPORAL_WORKER_DATA_WAREHOUSE: `${DW_KEY_NEW},${DJANGO_KEY}`,+ })+ )++ await expect(keys.load()).rejects.toThrow(/also listed for/)+ expect(keys.isLoaded).toBe(false)+ })++ it('refuses to load when two entries normalize onto one deployment name', async () => {+ const keys = new SigningKeyLoader(+ await mount({ __CALLER_KEY_FOO_BAR: DJANGO_KEY, '__CALLER_KEY_FOO-BAR': DW_KEY_NEW })+ )++ await expect(keys.load()).rejects.toThrow(/both name the deployment foo-bar/)+ expect(keys.isLoaded).toBe(false)+ })++ // A malformed edit must not lock a running fleet out, so reload keeps the previous+ // keys. That makes it the one path a revocation travels and it fails open — see the+ // last-loaded gauge and the failure counter in metrics.ts.+ it('keeps the previous keys when a reload fails', async () => {+ const dir = await mount({ __CALLER_KEY_POSTHOG_DJANGO: DJANGO_KEY })+ const keys = new SigningKeyLoader(dir)+ await keys.load()++ await rm(dir, { recursive: true, force: true })+ await keys.reload()++ expect(Object.fromEntries(keys.entries())).toEqual({ [DJANGO]: [DJANGO_KEY] })+ })+})++describe('bearerToken', () => {+ it.each([+ ['undefined header', undefined],+ ['empty header', ''],+ ['non-bearer scheme', 'Basic abc'],+ ['bearer with no token', 'Bearer '],+ ])('rejects %s', (_label, header) => {+ expect(() => bearerToken(header)).toThrow(AuthError)+ })++ it('extracts the token from a well-formed header', () => {+ expect(bearerToken('Bearer abc.def.ghi')).toBe('abc.def.ghi')+ })+})diff --git a/services/integration-service/tests/unit/config.test.ts b/services/integration-service/tests/unit/config.test.tsnew file mode 100644index 000000000000..4b9b371f546b--- /dev/null+++ b/services/integration-service/tests/unit/config.test.ts@@ -0,0 +1,49 @@+import { afterEach, describe, expect, it } from 'vitest'++import { loadConfig } from '@/lib/config'++const VAR = 'INTEGRATION_SERVICE_RELOAD_SECONDS'++describe('loadConfig integers', () => {+ afterEach(() => {+ delete process.env[VAR]+ })++ it.each([+ ['unset falls back to the default', undefined, 30],+ ['a valid value parses', '45', 45],+ ])('%s', (_label, value, expected) => {+ if (value !== undefined) {+ process.env[VAR] = value+ }+ expect(loadConfig().reloadSeconds).toBe(expected)+ })++ // Boot is fail-fast everywhere else; a malformed number must not silently run a+ // cadence the operator did not set.+ it('throws on a malformed value instead of silently defaulting', () => {+ process.env[VAR] = 'not-a-number'+ expect(() => loadConfig()).toThrow(VAR)+ })+})++describe('loadConfig production guards', () => {+ const PROD_VARS = ['NODE_ENV', 'INTEGRATION_SERVICE_ENV']++ afterEach(() => {+ for (const key of PROD_VARS) {+ delete process.env[key]+ }+ })++ it('refuses to boot in production without INTEGRATION_SERVICE_ENV', () => {+ process.env.NODE_ENV = 'production'+ expect(() => loadConfig()).toThrow('INTEGRATION_SERVICE_ENV')+ })++ it('boots in production once every required variable is set', () => {+ process.env.NODE_ENV = 'production'+ process.env.INTEGRATION_SERVICE_ENV = 'prod-us'+ expect(loadConfig().env).toBe('prod-us')+ })+})diff --git a/services/integration-service/tests/unit/mount.test.ts b/services/integration-service/tests/unit/mount.test.tsnew file mode 100644index 000000000000..2cf5db1fde6e--- /dev/null+++ b/services/integration-service/tests/unit/mount.test.ts@@ -0,0 +1,215 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { register, servingStaleSeconds } from '@/metrics'+import { SecretMount } from '@/mount'+import type { MountedSecrets } from '@/types'++const AN_HOUR_MS = 60 * 60 * 1000++const dirs: string[] = []++afterEach(async () => {+ await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true })))+ vi.restoreAllMocks()+})++/** A directory shaped the way kubelet projects a Kubernetes Secret: one file per key. */+async function mount(values: Record<string, string>): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), 'integration-mount-'))+ dirs.push(dir)+ await Promise.all(Object.entries(values).map(([key, value]) => writeFile(join(dir, key), value)))+ return dir+}++function secretMount(dir: string, opts: { now?: () => number } = {}): SecretMount {+ return new SecretMount({ dir, ...(opts.now && { now: opts.now }) })+}++async function load(values: Record<string, string>): Promise<MountedSecrets | null> {+ const m = secretMount(await mount(values))+ await m.reload()+ return m.current()+}++describe('reading the mount', () => {+ beforeEach(() => {+ register.resetMetrics()+ })++ it('serves every entry the mount carries, with no manifest to declare it in', async () => {+ const held = await load({+ HUBSPOT_APP_CLIENT_SECRET: 'sec',+ STRIPE_APP_SECRET_KEY: 'sk',+ A_CREDENTIAL_NOBODY_HAS_HEARD_OF: 'new',+ })++ expect(held?.secrets['HUBSPOT_APP_CLIENT_SECRET']).toMatchObject({ state: 'steady', value: 'sec' })+ expect(held?.secrets['STRIPE_APP_SECRET_KEY']).toMatchObject({ state: 'steady', value: 'sk' })+ expect(held?.secrets['A_CREDENTIAL_NOBODY_HAS_HEARD_OF']).toMatchObject({ state: 'steady', value: 'new' })+ })++ // THE property that replaced the manifest filter: the mount's own machinery is never a+ // secret — signing keys, the recovery list, and rotation siblings, which would+ // otherwise hand out a rotation's outgoing value under its own name.+ it.each([+ ['a caller signing key', '__CALLER_KEY_POSTHOG_DJANGO'],+ ['any other reserved entry', '__SOMETHING_ELSE'],+ ['the recovery list', 'INTEGRATION_RECOVERY_KEYS'],+ ['a rotation sibling', 'HUBSPOT_APP_CLIENT_SECRET_FALLBACKS'],+ ])('never exposes %s as a secret', async (_label, key) => {+ const held = await load({ HUBSPOT_APP_CLIENT_SECRET: 'sec', [key]: 'not-a-secret' })+ // The positive alongside the negative, so this cannot pass by load() returning null.+ expect(held?.secrets).toHaveProperty('HUBSPOT_APP_CLIENT_SECRET')+ expect(held?.secrets).not.toHaveProperty(key)+ })++ // A trailing newline is easy to introduce by hand and would silently break an API call.+ it('trims whitespace a human left in the value', async () => {+ const held = await load({ HUBSPOT_APP_CLIENT_SECRET: 'sec\n' })+ expect(held?.secrets['HUBSPOT_APP_CLIENT_SECRET']?.value).toBe('sec')+ })++ it.each([+ ['steady with no fallback sibling', { HUBSPOT_APP_CLIENT_SECRET: 'sec' }, { state: 'steady', value: 'sec' }],+ [+ 'rotating when the sibling holds the outgoing value',+ { HUBSPOT_APP_CLIENT_SECRET: 'new', HUBSPOT_APP_CLIENT_SECRET_FALLBACKS: 'old' },+ { state: 'rotating', value: 'new', previous: 'old' },+ ],+ [+ 'the newest entry when the fallback list holds several',+ { HUBSPOT_APP_CLIENT_SECRET: 'new', HUBSPOT_APP_CLIENT_SECRET_FALLBACKS: 'old, older' },+ { state: 'rotating', previous: 'old' },+ ],+ [+ 'steady when the fallback repeats the current value',+ { HUBSPOT_APP_CLIENT_SECRET: 'same', HUBSPOT_APP_CLIENT_SECRET_FALLBACKS: 'same' },+ { state: 'steady', value: 'same' },+ ],+ ])('reports %s', async (_label, values, expected) => {+ const held = await load(values)+ expect(held?.secrets['HUBSPOT_APP_CLIENT_SECRET']).toMatchObject(expected)+ })++ // The reason rotation uses a sibling rather than AWS staging labels: rotating one+ // secret must leave every other one alone.+ it('leaves other secrets steady while one is mid-rotation', async () => {+ const held = await load({+ HUBSPOT_APP_CLIENT_SECRET: 'new',+ HUBSPOT_APP_CLIENT_SECRET_FALLBACKS: 'old',+ STRIPE_APP_SECRET_KEY: 'sk',+ })++ expect(held?.secrets['HUBSPOT_APP_CLIENT_SECRET']?.state).toBe('rotating')+ expect(held?.secrets['STRIPE_APP_SECRET_KEY']?.state).toBe('steady')+ })++ it('serves no value at all for a key named in the recovery list', async () => {+ const held = await load({+ HUBSPOT_APP_CLIENT_SECRET: 'burned',+ INTEGRATION_RECOVERY_KEYS: 'HUBSPOT_APP_CLIENT_SECRET',+ })++ expect(held?.secrets['HUBSPOT_APP_CLIENT_SECRET']?.state).toBe('recovery')+ expect(held?.secrets['HUBSPOT_APP_CLIENT_SECRET']?.value).toBeUndefined()+ })++ it('handles several keys in recovery from one comma-separated value', async () => {+ const held = await load({+ STRIPE_APP_CLIENT_ID: 'id',+ STRIPE_APP_SECRET_KEY: 'burned',+ HUBSPOT_APP_CLIENT_SECRET: 'also-burned',+ INTEGRATION_RECOVERY_KEYS: 'STRIPE_APP_SECRET_KEY, HUBSPOT_APP_CLIENT_SECRET',+ })++ expect(held?.secrets['STRIPE_APP_SECRET_KEY']?.state).toBe('recovery')+ expect(held?.secrets['HUBSPOT_APP_CLIENT_SECRET']?.state).toBe('recovery')+ expect(held?.secrets['STRIPE_APP_CLIENT_ID']?.state).toBe('steady')+ })++ // kubelet keeps its own bookkeeping in the volume; reading it as a secret would be+ // wrong and reading it into the content hash would make the hash churn.+ it('ignores kubelet bookkeeping entries', async () => {+ const held = await load({ HUBSPOT_APP_CLIENT_SECRET: 'sec', '..data': 'internal' })+ expect(Object.keys(held?.secrets ?? {})).toEqual(['HUBSPOT_APP_CLIENT_SECRET'])+ })++ describe('the content hash', () => {+ it('is stable across reads of unchanged content', async () => {+ const m = secretMount(await mount({ HUBSPOT_APP_CLIENT_SECRET: 'sec' }))+ await m.reload()+ const first = m.current()?.versionId+ await m.reload()+ expect(m.current()?.versionId).toBe(first)+ })++ it('changes when a value changes', async () => {+ const before = await load({ HUBSPOT_APP_CLIENT_SECRET: 'one' })+ const after = await load({ HUBSPOT_APP_CLIENT_SECRET: 'two' })+ expect(before?.versionId).not.toBe(after?.versionId)+ })+ })++ it.each([+ ['the mount is absent', '/nonexistent/mount', undefined],+ ['the mount is empty', null, {}],+ // Counting files rather than secrets would call this healthy, and every resolve+ // would answer all-missing, which a caller treats as a deleted secret.+ ['the mount carries only reserved entries', null, { __CALLER_KEY_POSTHOG_DJANGO: 'k' }],+ ])('holds nothing when %s', async (_label, path, values) => {+ const m = secretMount(path ?? (await mount(values ?? {})))+ await m.reload()++ expect(m.current()).toBeNull()+ })+})++describe('holding secrets across reloads', () => {+ beforeEach(() => {+ register.resetMetrics()+ })++ it('keeps serving what it holds when a reload finds nothing, and says so on the gauge', async () => {+ const dir = await mount({ HUBSPOT_APP_CLIENT_SECRET: 'sec' })+ // A clock an hour ahead of the read, so the gauge has a value to report.+ const m = secretMount(dir, { now: () => Date.now() + AN_HOUR_MS })+ await m.reload()+ const held = m.current()++ await rm(dir, { recursive: true, force: true })+ await m.reload()++ expect(m.current()).toBe(held)+ const stale = (await servingStaleSeconds.get()).values[0]?.value ?? 0+ expect(Math.round(stale)).toBe(3600)+ })++ it('resets the staleness gauge once the mount reads again', async () => {+ const dir = await mount({ HUBSPOT_APP_CLIENT_SECRET: 'sec' })+ const m = secretMount(dir, { now: () => Date.now() + AN_HOUR_MS })+ await m.reload()++ await rm(join(dir, 'HUBSPOT_APP_CLIENT_SECRET'))+ await m.reload()+ expect((await servingStaleSeconds.get()).values[0]?.value).toBeGreaterThan(0)++ await writeFile(join(dir, 'HUBSPOT_APP_CLIENT_SECRET'), 'sec-again')+ await m.reload()+ expect((await servingStaleSeconds.get()).values[0]?.value).toBe(0)+ })++ it('recovers once a mount appears, without ever crashing', async () => {+ const dir = await mount({})+ const m = secretMount(dir)++ await m.reload()+ expect(m.current()).toBeNull()++ await writeFile(join(dir, 'HUBSPOT_APP_CLIENT_SECRET'), 'sec')+ await m.reload()+ expect(m.current()).not.toBeNull()+ })+})diff --git a/services/integration-service/tests/unit/resolve.test.ts b/services/integration-service/tests/unit/resolve.test.tsnew file mode 100644index 000000000000..40ed2e8204c0--- /dev/null+++ b/services/integration-service/tests/unit/resolve.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from 'vitest'++import { register, resolveTotal } from '@/metrics'+import { resolveKeys } from '@/resolve'+import type { CallerIdentity, MountedSecrets } from '@/types'++function mounted(secrets: MountedSecrets['secrets']): MountedSecrets {+ return { fetchedAt: '2026-08-06T00:00:00.000Z', versionId: 'v1', secrets }+}++const MOUNTED = mounted({+ GOOGLE_ADS_APP_CLIENT_ID: { state: 'steady', value: 'ga-id', versionId: 'v1', fetchedAt: 'now' },+ GOOGLE_ADS_APP_CLIENT_SECRET: {+ state: 'rotating',+ value: 'ga-new',+ previous: 'ga-old',+ versionId: 'v1',+ fetchedAt: 'now',+ },+ STRIPE_APP_SECRET_KEY: { state: 'steady', value: 'sk-live', versionId: 'v1', fetchedAt: 'now' },+})++function identity(requestedKeys: string[]): CallerIdentity {+ return { deployment: 'temporal-worker-data-warehouse', caller: 'warehouse-sources', requestedKeys }+}++describe('resolve', () => {+ // There is no per-deployment allowlist: any authenticated deployment may read anything+ // on the mount. Containment is revoking that deployment's signing key, not a list+ // somebody has to keep current.+ it('serves anything on the mount to an authenticated deployment', async () => {+ const response = resolveKeys(identity(['GOOGLE_ADS_APP_CLIENT_ID', 'STRIPE_APP_SECRET_KEY']), MOUNTED)++ expect(Object.keys(response.secrets).sort()).toEqual(['GOOGLE_ADS_APP_CLIENT_ID', 'STRIPE_APP_SECRET_KEY'])+ expect(response.missing).toEqual([])+ })++ it('serves the requested fields with their rotation state', async () => {+ const response = resolveKeys(identity(['GOOGLE_ADS_APP_CLIENT_ID', 'GOOGLE_ADS_APP_CLIENT_SECRET']), MOUNTED)++ expect(response.secrets['GOOGLE_ADS_APP_CLIENT_ID']).toMatchObject({ state: 'steady', value: 'ga-id' })+ expect(response.secrets['GOOGLE_ADS_APP_CLIENT_SECRET']).toMatchObject({+ state: 'rotating',+ value: 'ga-new',+ previous: 'ga-old',+ })+ })++ // THE containment property at this layer: the scope is the identity's key list and+ // nothing else. The route-level half — a request body cannot widen it — is pinned in+ // app.test.ts, since this function never sees an HTTP request.+ it('serves nothing outside the token scope even though the caller may read it', async () => {+ const response = resolveKeys(identity(['GOOGLE_ADS_APP_CLIENT_ID']), MOUNTED)++ expect(Object.keys(response.secrets)).toEqual(['GOOGLE_ADS_APP_CLIENT_ID'])+ expect(response.secrets).not.toHaveProperty('STRIPE_APP_SECRET_KEY')+ })++ it.each([+ ['a name nothing on the mount carries', 'NOT_A_REAL_KEY'],+ // The mount never puts a reserved entry in the secret set, so a token naming a+ // signing key gets the same answer as a token naming nonsense.+ ['a reserved entry a token asked for by name', '__CALLER_KEY_POSTHOG_DJANGO'],+ ])('reports %s as missing rather than failing the request', async (_label, key) => {+ const response = resolveKeys(identity([key, 'GOOGLE_ADS_APP_CLIENT_ID']), MOUNTED)++ expect(response.missing).toContain(key)+ expect(response.secrets).not.toHaveProperty(key)+ expect(response.secrets).toHaveProperty('GOOGLE_ADS_APP_CLIENT_ID')+ })++ it('serves a recovery field with no value so the caller fails fast', async () => {+ const response = resolveKeys(+ identity(['STRIPE_APP_SECRET_KEY']),+ mounted({ STRIPE_APP_SECRET_KEY: { state: 'recovery', versionId: 'v1', fetchedAt: 'now' } })+ )++ expect(response.secrets['STRIPE_APP_SECRET_KEY']).toMatchObject({ state: 'recovery' })+ expect(response.secrets['STRIPE_APP_SECRET_KEY']?.value).toBeUndefined()+ })++ // prom-client keeps every series in process memory for the lifetime of the pod, so a+ // caller holding a signing key could otherwise grow the heap and the scrape payload+ // without bound. Nothing a caller types may become a label: not an invented key name,+ // and not the `caller` claim.+ it('never puts caller-supplied text on a metric label', async () => {+ register.resetMetrics()+ const invented = 'TOTALLY_MADE_UP_KEY_NAME_9f2a'+ const claimedCaller = 'a-product-nobody-registered-4b81'++ const response = resolveKeys(+ { deployment: 'posthog-django', caller: claimedCaller, requestedKeys: [invented] },+ MOUNTED+ )++ const labelValues = (await resolveTotal.get()).values.flatMap((v) => Object.values(v.labels).map(String))+ expect(labelValues).not.toContain(invented)+ expect(labelValues).not.toContain(claimedCaller)+ // The real name still reaches the caller, just not the metric.+ expect(response.missing).toContain(invented)+ })+})diff --git a/services/integration-service/tests/unit/server.test.ts b/services/integration-service/tests/unit/server.test.tsnew file mode 100644index 000000000000..19405497b387--- /dev/null+++ b/services/integration-service/tests/unit/server.test.ts@@ -0,0 +1,177 @@+import { SignJWT } from 'jose'+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { AUDIENCE } from '@/auth/types'+import type { Config } from '@/lib/config'+import { every, IntegrationServer } from '@/server'++const KEY = 'HUBSPOT_APP_CLIENT_SECRET'+const SIGNING_KEY = 'server-test-signing-key'++const dirs: string[] = []++afterEach(async () => {+ await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true })))+})++async function secretsDir(): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), 'integration-server-'))+ dirs.push(dir)+ await writeFile(join(dir, KEY), 'hunter2-zx9q')+ await writeFile(join(dir, '__CALLER_KEY_TEST_DEPLOYMENT'), SIGNING_KEY)+ return dir+}++function config(mountDir: string, prestopDelayMs: number): Config {+ return {+ port: 0,+ host: '127.0.0.1',+ shutdownPrestopDelayMs: prestopDelayMs,+ env: 'test',+ mountDir,+ reloadSeconds: 3600,+ metricsPort: 0,+ }+}++async function mint(): Promise<string> {+ return new SignJWT({ caller: 'warehouse-sources', keys: [KEY] })+ .setProtectedHeader({ alg: 'HS256' })+ .setAudience(AUDIENCE)+ .setIssuedAt()+ .setExpirationTime('5m')+ .sign(new TextEncoder().encode(SIGNING_KEY))+}++interface Started {+ server: IntegrationServer+ events: string[]+ fetch: (req: Request) => Response | Promise<Response>+ exitCode: () => number | undefined+}++/** Start a real IntegrationServer with a fake listener and a captured exit. */+async function startServer(prestopDelayMs = 0): Promise<Started> {+ const events: string[] = []+ let exitCode: number | undefined+ let fetch!: Started['fetch']++ const server = new IntegrationServer(config(await secretsDir(), prestopDelayMs), {+ serve: (options) => {+ fetch = options.fetch as Started['fetch']+ return {+ close: (cb) => {+ events.push(`drain draining=${server.lifecycleState().shuttingDown}`)+ cb()+ },+ }+ },+ exit: (code) => {+ exitCode = code+ },+ })+ await server.start()+ return { server, events, fetch, exitCode: () => exitCode }+}++describe('integration server', () => {+ it('marks itself draining and waits out the prestop delay before draining the server', async () => {+ const { server, events, fetch } = await startServer(30)++ const res = await fetch(+ new Request('http://svc/v1/secrets/resolve', {+ method: 'POST',+ headers: { Authorization: `Bearer ${await mint()}` },+ })+ )+ expect(res.status).toBe(200)++ const stoppedAt = Date.now()+ await server.stop('SIGTERM')++ expect(events).toEqual(['drain draining=true'])+ // Kubernetes has to see the pod leave its endpoints before the listener closes.+ expect(Date.now() - stoppedAt).toBeGreaterThanOrEqual(25)+ })++ it('exits non-zero through the same graceful path on a crash', async () => {+ const { server, events, exitCode } = await startServer()++ await server.stop('uncaughtException', new Error('boom'))++ expect(events).toEqual(['drain draining=true'])+ expect(exitCode()).toBe(1)+ })++ it('stops only once and removes its process listeners', async () => {+ const before = process.listenerCount('SIGTERM')+ const { server, events, exitCode } = await startServer()+ expect(process.listenerCount('SIGTERM')).toBe(before + 1)++ await server.stop('SIGTERM')+ await server.stop('SIGTERM')++ expect(process.listenerCount('SIGTERM')).toBe(before)+ expect(events).toHaveLength(1)+ expect(exitCode()).toBe(0)+ })+})++// The reload is how a signing-key revocation reaches a running pod, so the cadence must+// never stretch past the configured interval.+describe('every', () => {+ afterEach(() => {+ vi.useRealTimers()+ })++ it('runs on exactly the configured period', async () => {+ vi.useFakeTimers()+ const runs: number[] = []+ const start = Date.now()++ const cancel = every(10_000, () => {+ runs.push(Date.now() - start)+ return Promise.resolve()+ })+ await vi.advanceTimersByTimeAsync(30_000)+ cancel()++ expect(runs).toEqual([10_000, 20_000, 30_000])+ })++ // An escaped rejection reaches the unhandledRejection handler, which exits the process.+ // A blip in whatever the task talks to must not take the pod down.+ it('swallows a rejecting task and keeps running', async () => {+ vi.useFakeTimers()+ const task = vi.fn().mockRejectedValue(new Error('boom'))+ const unhandled: unknown[] = []+ const onUnhandled = (reason: unknown): void => {+ unhandled.push(reason)+ }+ process.on('unhandledRejection', onUnhandled)++ const cancel = every(10_000, task)+ await vi.advanceTimersByTimeAsync(20_000)+ cancel()+ process.removeListener('unhandledRejection', onUnhandled)++ expect(task).toHaveBeenCalledTimes(2)+ expect(unhandled).toEqual([])+ })++ it('stops running once cancelled', async () => {+ vi.useFakeTimers()+ const task = vi.fn().mockResolvedValue(undefined)++ const cancel = every(10_000, task)+ await vi.advanceTimersByTimeAsync(10_000)+ expect(task).toHaveBeenCalledTimes(1)++ cancel()+ await vi.advanceTimersByTimeAsync(60_000)+ expect(task).toHaveBeenCalledTimes(1)+ })+})diff --git a/services/integration-service/tsconfig.json b/services/integration-service/tsconfig.jsonnew file mode 100644index 000000000000..5c4953faeb84--- /dev/null+++ b/services/integration-service/tsconfig.json@@ -0,0 +1,26 @@+{+ "compilerOptions": {+ "target": "es2021",+ "lib": ["es2021"],+ "module": "es2022",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "allowJs": false,+ "noEmit": true,+ "isolatedModules": true,+ "allowSyntheticDefaultImports": true,+ "forceConsistentCasingInFileNames": true,+ "strict": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true,+ "skipLibCheck": true,+ "types": ["node"],+ "paths": {+ "@/*": ["./src/*", "./tests/*"]+ }+ },+ "include": ["src/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts"],+ "exclude": ["node_modules", "dist"]+}diff --git a/services/integration-service/vitest.config.mts b/services/integration-service/vitest.config.mtsnew file mode 100644index 000000000000..900be47f3c9c--- /dev/null+++ b/services/integration-service/vitest.config.mts@@ -0,0 +1,13 @@+import tsconfigPaths from 'vite-tsconfig-paths'+import { defineConfig } from 'vitest/config'++export default defineConfig({+ plugins: [tsconfigPaths({ root: '.' })],+ test: {+ globals: true,+ environment: 'node',+ testTimeout: 30000,+ include: ['tests/**/*.test.ts'],+ exclude: ['node_modules/**', 'dist/**'],+ },+})