Skip to content

: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.

refactor(credentials-service): rename integration service to credentials service (#116086)

Tom Owers0e63e71c772c
diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.js
index c197d816952c..d3414de02a59 100644
--- a/.github/scripts/trunk-impacted-targets.js
+++ b/.github/scripts/trunk-impacted-targets.js
@@ -386,7 +386,7 @@ const TRIPWIRE_RULES = [
['.github/workflows/ci-phrocs.yml', 'phrocs-suite'],
['.github/workflows/terragrunt-posthog.yaml', 'terraform-suite'],
['.github/workflows/build-hobby-installer.yml', HOBBY],
- ['.github/workflows/ci-integration-service.yml', 'service:integration-service'],
+ ['.github/workflows/ci-credentials-service.yml', 'service:credentials-service'],
['.github/workflows/ci-openapi-codegen.yml', PRODUCT_SURFACE],
// Publish and CD workflows found after the first deploy pass.
['.github/workflows/llm-gateway-cd.yml', DEPLOY],
@@ -1886,7 +1886,7 @@ const DOMAIN_LANES = new Map([
['repo-config-lane', laneOf('repo-config')],
['agents-lane', laneOf('agents')],
])
-for (const service of ['llm-gateway', 'oauth-proxy', 'agent-proxy', 'integration-service']) {
+for (const service of ['llm-gateway', 'oauth-proxy', 'agent-proxy', 'credentials-service']) {
DOMAIN_LANES.set(`service:${service}`, addServiceSuiteLane(service))
}
diff --git a/.github/workflows/cd-credentials-service-image.yml b/.github/workflows/cd-credentials-service-image.yml
new file mode 100644
index 000000000000..16415c9600b7
--- /dev/null
+++ b/.github/workflows/cd-credentials-service-image.yml
@@ -0,0 +1,278 @@
+name: Credentials Service Container Image CD
+
+on:
+ push:
+ branches:
+ - master
+ paths:
+ - 'services/credentials-service/**'
+ - '.github/workflows/cd-credentials-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-credentials-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/credentials-service/Dockerfile
+ buildx-fallback: false
+ push: ${{ github.ref == 'refs/heads/master' }}
+ tags: ${{ steps.docker-meta.outputs.tags }}
+ labels: ${{ steps.docker-meta.outputs.labels }}
+ annotations: ${{ steps.docker-meta.outputs.annotations }}
+ platforms: linux/arm64,linux/amd64
+ build-args: COMMIT_HASH=${{ github.sha }}
+
+ ordered_image_alias:
+ name: Publish ordered image alias
+ needs: build
+ # Kargo promotes images by this tag (^r[0-9]{12}-[0-9a-f]{6}$). Best effort:
+ # a missing alias delays Kargo for that build and never fails the deploy.
+ if: ${{ needs.build.result == 'success' && github.repository_owner == 'PostHog' && vars.CD_DEPLOY_ENABLED == 'true' && vars.ORDERED_IMAGE_ALIAS_PAUSED != 'true' && github.ref == 'refs/heads/master' }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ continue-on-error: true
+ permissions:
+ contents: read
+ packages: write
+
+ steps:
+ - name: Check out
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Compute ordered release tag
+ id: ordered-release
+ timeout-minutes: 2
+ shell: bash
+ env:
+ ORDERED_RELEASE_TAG_REGEX: ^r[0-9]{12}-[0-9a-f]{6}$
+ run: |
+ set -uo pipefail
+
+ if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
+ fetch_status=0
+ timeout --kill-after=10s 90s git fetch \
+ --no-tags \
+ --prune \
+ --no-recurse-submodules \
+ --unshallow \
+ --filter=tree:0 \
+ origin \
+ "+${GITHUB_REF}:refs/remotes/origin/${GITHUB_REF_NAME}" || fetch_status=$?
+ if [ "$fetch_status" -ne 0 ]; then
+ echo "::warning title=Ordered release tag skipped::Source history could not be fetched (status $fetch_status)."
+ exit 0
+ fi
+ fi
+
+ if [ "$(git rev-parse --is-shallow-repository 2>/dev/null)" != "false" ]; then
+ echo "::warning title=Ordered release tag skipped::Complete source history is unavailable."
+ exit 0
+ fi
+
+ if ! head_revision="$(git rev-parse HEAD)" || [ "$head_revision" != "$GITHUB_SHA" ]; then
+ echo "::warning title=Ordered release tag skipped::The checked-out revision does not match GITHUB_SHA."
+ exit 0
+ fi
+
+ if ! position="$(git rev-list --first-parent --count "$GITHUB_SHA")"; then
+ echo "::warning title=Ordered release tag skipped::The source position could not be computed."
+ exit 0
+ fi
+
+ if ! [[ "$position" =~ ^[1-9][0-9]{0,11}$ ]]; then
+ echo "::warning title=Ordered release tag skipped::The source position is out of range."
+ exit 0
+ fi
+
+ if ! printf -v tag 'r%012d-%.6s' "$position" "$GITHUB_SHA"; then
+ echo "::warning title=Ordered release tag skipped::The source position could not be formatted."
+ exit 0
+ fi
+
+ if ! [[ "$tag" =~ $ORDERED_RELEASE_TAG_REGEX ]]; then
+ echo "::warning title=Ordered release tag skipped::${tag} does not match the required format."
+ exit 0
+ fi
+
+ echo "tag=${tag}" >> "$GITHUB_OUTPUT"
+
+ - name: Warn when ordered image alias tag is unavailable
+ if: ${{ steps.ordered-release.outputs.tag == '' }}
+ shell: bash
+ run: echo "::warning title=Ordered image alias tag unavailable::Ordered image alias publication was skipped because no ordered release tag was generated."
+
+ - name: Set up Docker Buildx for ordered image alias
+ if: ${{ steps.ordered-release.outputs.tag != '' }}
+ uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
+
+ - name: Login to ghcr.io
+ if: ${{ steps.ordered-release.outputs.tag != '' }}
+ uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Publish and reconcile ordered image alias
+ if: ${{ steps.ordered-release.outputs.tag != '' }}
+ timeout-minutes: 5
+ shell: bash
+ env:
+ IMAGE: ghcr.io/posthog/posthog-credentials-service
+ DIGEST: ${{ needs.build.outputs.sha }}
+ ORDERED_ALIAS: ${{ steps.ordered-release.outputs.tag }}
+ # Read the alias before publishing, accept it when it already resolves to this
+ # build, and never move it when it resolves elsewhere. Kargo caches the alias
+ # as immutable, and a rebuild at the same commit can yield a new index digest.
+ run: |
+ set -uo pipefail
+
+ if ! [[ "$DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]]; then
+ echo "::warning title=Ordered image alias skipped::No image digest was resolved for this build."
+ exit 0
+ fi
+
+ inspect_digest() {
+ local output
+ output="$(timeout --kill-after=10s 20s docker buildx imagetools inspect \
+ --format '{{json .Manifest.Digest}}' "$1" 2>/dev/null)" || return $?
+ [[ "$output" =~ ^\"(sha256:[0-9a-f]{64})\"$ ]] || return 65
+ printf '%s\n' "${BASH_REMATCH[1]}"
+ }
+
+ # present-at-expected-digest | integrity-mismatch | absent | unknown
+ classify_alias() {
+ local observed
+ if observed="$(inspect_digest "$TARGET_IMAGE")" || observed="$(inspect_digest "$TARGET_IMAGE")"; then
+ if [ "$observed" = "$DIGEST" ]; then echo present-at-expected-digest; else echo integrity-mismatch; fi
+ elif inspect_digest "$SOURCE_IMAGE" >/dev/null; then
+ echo absent
+ else
+ echo unknown
+ fi
+ }
+
+ SOURCE_IMAGE="${IMAGE}@${DIGEST}"
+ TARGET_IMAGE="${IMAGE}:${ORDERED_ALIAS}"
+
+ state="$(classify_alias)"
+ if [ "$state" = "absent" ]; then
+ # --prefer-index=false re-tags the existing index by digest, so the
+ # alias resolves to the same digest and keeps its annotations.
+ timeout --kill-after=10s 35s docker buildx imagetools create \
+ --prefer-index=false \
+ --tag "$TARGET_IMAGE" \
+ "$SOURCE_IMAGE" >&2 || echo "::warning::Alias publication client exited $?"
+ state="$(classify_alias)"
+ fi
+
+ case "$state" in
+ present-at-expected-digest)
+ echo "::notice title=Ordered image alias present::${TARGET_IMAGE} resolves to ${DIGEST}."
+ ;;
+ integrity-mismatch)
+ echo "::error title=Ordered image alias integrity mismatch::${TARGET_IMAGE} resolves to a different digest; left untouched."
+ exit 1
+ ;;
+ absent)
+ echo "::warning title=Ordered image alias absent::${TARGET_IMAGE} is absent after publication."
+ exit 1
+ ;;
+ *)
+ echo "::error title=Ordered image alias read-back unavailable::${TARGET_IMAGE} could not be read back from ghcr."
+ exit 1
+ ;;
+ esac
+
+ deploy:
+ name: Trigger credentials-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@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
+ 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 credentials-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": "credentials-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/cd-integration-service-image.yml b/.github/workflows/cd-integration-service-image.yml
deleted file mode 100644
index 4891f9825dcd..000000000000
--- a/.github/workflows/cd-integration-service-image.yml
+++ /dev/null
@@ -1,116 +0,0 @@
-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 }}
- annotations: ${{ steps.docker-meta.outputs.annotations }}
- 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@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- 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-credentials-service.yml
similarity index 73%
rename from .github/workflows/ci-integration-service.yml
rename to .github/workflows/ci-credentials-service.yml
index 0f80e43efc0c..2c16df3df3ec 100644
--- a/.github/workflows/ci-integration-service.yml
+++ b/.github/workflows/ci-credentials-service.yml
@@ -1,4 +1,4 @@
-name: Integration Service CI
+name: Credentials 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
@@ -11,12 +11,12 @@ on:
branches:
- master
paths:
- - 'services/integration-service/**'
- - '.github/workflows/ci-integration-service.yml'
+ - 'services/credentials-service/**'
+ - '.github/workflows/ci-credentials-service.yml'
pull_request:
paths:
- - 'services/integration-service/**'
- - '.github/workflows/ci-integration-service.yml'
+ - 'services/credentials-service/**'
+ - '.github/workflows/ci-credentials-service.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
@@ -31,8 +31,8 @@ env:
NPM_CONFIG_FUND: 'false'
jobs:
- integration-service:
- name: Integration Service checks
+ credentials-service:
+ name: Credentials Service checks
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
@@ -45,29 +45,29 @@ jobs:
- name: Install pnpm dependencies
uses: ./.github/actions/pnpm-install
with:
- install-command: pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/integration-service...
+ install-command: pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/credentials-service...
- name: Typecheck
- working-directory: services/integration-service
+ working-directory: services/credentials-service
run: pnpm typecheck
- name: Unit tests
- working-directory: services/integration-service
+ working-directory: services/credentials-service
run: pnpm test:unit
# Real Postgres via testcontainers; the ubuntu runner provides Docker.
- name: Integration tests
- working-directory: services/integration-service
+ working-directory: services/credentials-service
run: pnpm test:integration
- name: Lint
- working-directory: services/integration-service
+ working-directory: services/credentials-service
run: pnpm exec oxlint
- name: Format check
- working-directory: services/integration-service
+ working-directory: services/credentials-service
run: pnpm format:check
- name: Build
- working-directory: services/integration-service
+ working-directory: services/credentials-service
run: pnpm build
diff --git a/.github/workflows/ci-security.yaml b/.github/workflows/ci-security.yaml
index e4161b433aac..5e49996cfa2a 100644
--- a/.github/workflows/ci-security.yaml
+++ b/.github/workflows/ci-security.yaml
@@ -89,7 +89,7 @@ jobs:
- 'nodejs/**'
- 'packages/**'
- 'services/agent-proxy/**'
- - 'services/integration-service/**'
+ - 'services/credentials-service/**'
- 'services/mcp/**'
- 'services/oauth-proxy/**'
- 'services/stripe-app/**'
@@ -306,7 +306,7 @@ jobs:
--include /nodejs
--include /packages
--include /services/agent-proxy
- --include /services/integration-service
+ --include /services/credentials-service
--include /services/mcp
--include /services/oauth-proxy
--include /services/stripe-app
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 45d05dae575a..3073662690fa 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -5537,12 +5537,12 @@ importers:
version: 6.0.3
vite-tsconfig-paths:
specifier: ^5.1.4
vitest:
specifier: ^3.2.4
- services/integration-service:
+ services/credentials-service:
dependencies:
'@hono/node-server':
specifier: ^2.0.2
@@ -5583,7 +5583,7 @@ importers:
version: 6.0.3
vite-tsconfig-paths:
specifier: ^5.1.4
vitest:
specifier: ^3.2.4
@@ -20567,6 +20567,7 @@ packages:
resolution: {integrity: sha512-sF308EhTenb/pDRPakm+WgiN+VdM/T1RaHj1x+MvAuT8UiQP8JmOEbxVqtkbfR4LrvOg5n7ic01kRBDGXjYikA==}
engines: {node: '>=10'}
+ deprecated: prom-client has been replaced by @prometheus-io/client
resolution: {integrity: sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==}
@@ -23056,8 +23057,8 @@ packages:
resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}
engines: {node: '>= 10.0.0'}
- resolution: {integrity: sha512-O7GS0zHHTkhYKYhpLGaRNX1bLxD38xsg1NE6/8fG5IkYOy6JsPW4J7p6gyx1klseJiHJD/lLTx9iskaqv1GRTw==}
+ resolution: {integrity: sha512-06xGpGXJI+roTGrXhrVOUSuPfaqNVw8bhRfTJue8D+LdBBXhmOfaspTLvOcLebcr2ayGvmyLGzwRwWKbsXQ+NQ==}
resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}
@@ -43513,7 +43514,7 @@ snapshots:
dependencies:
react: 18.3.1
- unlayer-types: 1.513.0
+ unlayer-types: 1.514.0
dependencies:
@@ -45832,7 +45833,7 @@ snapshots:
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index be3594c48177..d1e2993bc280 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -22,7 +22,7 @@ packages:
- '!products/desktop'
- docs/onboarding
- services/agent-proxy
- - services/integration-service
+ - services/credentials-service
- services/oauth-proxy
- services/mcp
- services/stripe-app
diff --git a/posthog/integration_secrets/__init__.py b/posthog/credentials_service/__init__.py
similarity index 100%
rename from posthog/integration_secrets/__init__.py
rename to posthog/credentials_service/__init__.py
diff --git a/posthog/integration_secrets/callers.py b/posthog/credentials_service/callers.py
similarity index 96%
rename from posthog/integration_secrets/callers.py
rename to posthog/credentials_service/callers.py
index fcf2bfe49520..f893721336ef 100644
--- a/posthog/integration_secrets/callers.py
+++ b/posthog/credentials_service/callers.py
@@ -1,7 +1,7 @@
from enum import StrEnum
-class IntegrationCaller(StrEnum):
+class CredentialsCaller(StrEnum):
"""The product asking for a credential.
Passed explicitly at every call site rather than read from a setting, so the code
diff --git a/posthog/integration_secrets/client.py b/posthog/credentials_service/client.py
similarity index 82%
rename from posthog/integration_secrets/client.py
rename to posthog/credentials_service/client.py
index 64322d446f30..c8a6405a05ea 100644
--- a/posthog/integration_secrets/client.py
+++ b/posthog/credentials_service/client.py
@@ -1,4 +1,4 @@
-"""Client for the integration service — platform integration credentials over HTTP.
+"""Client for the credentials 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
@@ -52,10 +52,10 @@ 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 .callers import CredentialsCaller
from .errors import (
- IntegrationServiceMisconfiguredError,
- IntegrationServiceUnreachableError,
+ CredentialsServiceMisconfiguredError,
+ CredentialsServiceUnreachableError,
SecretInRecoveryError,
SecretMissingError,
)
@@ -70,18 +70,18 @@ REQUEST_TIMEOUT_SECONDS = 5
# 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"
+CREDENTIALS_SERVICE_FLAG = "credentials-service-enabled"
+CREDENTIALS_SERVICE_FLAG_DISTINCT_ID = "credentials_service"
-INTEGRATION_SECRET_FETCH_COUNTER = Counter(
- "posthog_integration_secret_fetch_total",
- "Credential fetches from the integration service, by outcome",
+CREDENTIALS_SERVICE_FETCH_COUNTER = Counter(
+ "posthog_credentials_service_fetch_total",
+ "Credential fetches from the credentials 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",
+CREDENTIALS_SERVICE_ENV_FALLBACK_COUNTER = Counter(
+ "posthog_credentials_service_env_fallback_total",
+ "Credential reads served from the local environment instead of the credentials service",
labelnames=["reason"],
)
@@ -114,13 +114,13 @@ class RotatingSecret:
incoming: str | None = field(repr=False)
-def integration_service_signing_keys() -> list[str]:
+def credentials_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]
+ return [key for key in get_list(settings.CREDENTIALS_SERVICE_JWT_SECRET or "") if key]
def _missing_config() -> str | None:
@@ -128,11 +128,11 @@ def _missing_config() -> str | None:
Both set, or both unset, are the two states someone can mean. Exactly one is neither.
"""
- has_url = bool(settings.INTEGRATION_SERVICE_URL)
- has_keys = bool(integration_service_signing_keys())
+ has_url = bool(settings.CREDENTIALS_SERVICE_URL)
+ has_keys = bool(credentials_service_signing_keys())
if has_url == has_keys:
return None
- return "INTEGRATION_SERVICE_JWT_SECRET" if has_url else "INTEGRATION_SERVICE_URL"
+ return "CREDENTIALS_SERVICE_JWT_SECRET" if has_url else "CREDENTIALS_SERVICE_URL"
def _disabled_reason() -> str | None:
@@ -144,17 +144,17 @@ def _disabled_reason() -> str | None:
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():
+ if not settings.CREDENTIALS_SERVICE_URL or not credentials_service_signing_keys():
return "unconfigured"
try:
- enabled = bool(posthoganalytics.feature_enabled(INTEGRATION_SERVICE_FLAG, INTEGRATION_SERVICE_FLAG_DISTINCT_ID))
+ enabled = bool(posthoganalytics.feature_enabled(CREDENTIALS_SERVICE_FLAG, CREDENTIALS_SERVICE_FLAG_DISTINCT_ID))
except Exception:
- logger.warning("integration_secrets.flag_check_failed_defaulting_off", exc_info=True)
+ logger.warning("credentials_service.flag_check_failed_defaulting_off", exc_info=True)
return "flag_error"
return None if enabled else "flag_off"
-def integration_service_enabled() -> bool:
+def credentials_service_enabled() -> bool:
"""True when the service is configured and the rollout flag is on."""
return _disabled_reason() is None
@@ -162,7 +162,7 @@ def integration_service_enabled() -> bool:
def _log_resolve(
url: str,
keys: list[str],
- caller: IntegrationCaller,
+ caller: CredentialsCaller,
started_at_monotonic: float,
*,
response: Any = None,
@@ -212,21 +212,21 @@ def _log_resolve(
}
if error is not None or (status_code is not None and status_code >= 400):
- logger.warning("integration_secrets.resolve", **fields)
+ logger.warning("credentials_service.resolve", **fields)
elif missing or any(state != "steady" for state in states.values()):
# A rotating or recovered key, or one the service doesn't hold, is the case worth
# seeing without turning debug on — it explains a failure, or a value changing under
# a caller that did nothing differently.
- logger.info("integration_secrets.resolve", **fields)
+ logger.info("credentials_service.resolve", **fields)
else:
# Steady reads are the overwhelming majority and say nothing new, so they sit at
# debug, the same level the warehouse observer gives an ordinary 2xx.
- logger.debug("integration_secrets.resolve", **fields)
+ logger.debug("credentials_service.resolve", **fields)
except Exception:
- logger.debug("integration_secrets.resolve_log_failed", exc_info=True)
+ logger.debug("credentials_service.resolve_log_failed", exc_info=True)
-class IntegrationSecretsClient:
+class CredentialsServiceClient:
def __init__(self, session: requests.Session | None = None) -> None:
"""`session` swaps the transport without changing anything else.
@@ -242,10 +242,10 @@ class IntegrationSecretsClient:
"""
self._session = session or internal_requests
- def get(self, key: str, caller: IntegrationCaller) -> str:
+ def get(self, key: str, caller: CredentialsCaller) -> str:
return self.get_many([key], caller)[key]
- def get_many(self, keys: list[str], caller: IntegrationCaller) -> dict[str, str]:
+ def get_many(self, keys: list[str], caller: CredentialsCaller) -> dict[str, str]:
resolved = self._resolve(keys, caller)
out: dict[str, str] = {}
for key in keys:
@@ -255,7 +255,7 @@ class IntegrationSecretsClient:
out[key] = secret.value
return out
- def get_with_incoming(self, key: str, caller: IntegrationCaller) -> RotatingSecret:
+ def get_with_incoming(self, key: str, caller: CredentialsCaller) -> RotatingSecret:
"""The live value plus the staged replacement, while a rotation is in flight.
For callers that can retry against a third party: try current, and on an auth failure
@@ -268,17 +268,17 @@ class IntegrationSecretsClient:
raise SecretInRecoveryError(key)
return RotatingSecret(current=secret.value, incoming=secret.incoming)
- def _resolve(self, keys: list[str], caller: IntegrationCaller) -> dict[str, SecretValue]:
+ def _resolve(self, keys: list[str], caller: CredentialsCaller) -> dict[str, SecretValue]:
missing = _missing_config()
if missing is not None:
- raise IntegrationServiceMisconfiguredError(missing)
+ raise CredentialsServiceMisconfiguredError(missing)
reason = _disabled_reason()
if reason is not None:
- INTEGRATION_SECRET_ENV_FALLBACK_COUNTER.labels(reason=reason).inc()
+ CREDENTIALS_SERVICE_ENV_FALLBACK_COUNTER.labels(reason=reason).inc()
return {key: self._from_environment(key, reason) for key in keys}
return self._fetch(keys, caller)
- def _fetch(self, keys: list[str], caller: IntegrationCaller) -> dict[str, SecretValue]:
+ def _fetch(self, keys: list[str], caller: CredentialsCaller) -> dict[str, SecretValue]:
body = self._post(keys, caller)
missing = set(body.get("missing") or [])
@@ -287,7 +287,7 @@ class IntegrationSecretsClient:
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()
+ CREDENTIALS_SERVICE_FETCH_COUNTER.labels(outcome="missing").inc()
raise SecretMissingError(key)
payload = secrets[key]
@@ -299,24 +299,24 @@ class IntegrationSecretsClient:
# correction stops at this boundary rather than propagating the wrong idea.
incoming=payload.get("previous"),
)
- INTEGRATION_SECRET_FETCH_COUNTER.labels(outcome="ok").inc()
+ CREDENTIALS_SERVICE_FETCH_COUNTER.labels(outcome="ok").inc()
return resolved
- def _post(self, keys: list[str], caller: IntegrationCaller) -> dict[str, Any]:
+ def _post(self, keys: list[str], caller: CredentialsCaller) -> dict[str, Any]:
"""The request itself, with every transport failure wearing this client's own type.
No `requests` exception may escape. Callers sit in the middle of talking to some third
party, so a bare `HTTPError` from here is indistinguishable from one raised by the API
they were actually calling — and the difference decides whose problem it is. A misrouted
- `INTEGRATION_SERVICE_URL` answering 404 is our deploy error, not a dead endpoint of
+ `CREDENTIALS_SERVICE_URL` answering 404 is our deploy error, not a dead endpoint of
theirs, and a caller reading the status code alone cannot tell.
"""
# Minted outside the try: signing is local work, and a failure there is a bug in this
# process, not the service being unreachable. Catching it here would file it under the
# one label nobody investigates.
headers = self._auth_headers(keys, caller)
- url = f"{settings.INTEGRATION_SERVICE_URL.rstrip('/')}{RESOLVE_PATH}"
+ url = f"{settings.CREDENTIALS_SERVICE_URL.rstrip('/')}{RESOLVE_PATH}"
started = time.monotonic()
try:
response = self._session.post(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
@@ -326,20 +326,20 @@ class IntegrationSecretsClient:
# surfaces on older paths, and nothing else in this block raises one.
body: dict[str, Any] = response.json()
except (requests.RequestException, ValueError) as e:
- INTEGRATION_SECRET_FETCH_COUNTER.labels(outcome="unreachable").inc()
+ CREDENTIALS_SERVICE_FETCH_COUNTER.labels(outcome="unreachable").inc()
_log_resolve(url, keys, caller, started, response=getattr(e, "response", None), error=e)
- raise IntegrationServiceUnreachableError(
- f"The integration service did not answer a credential request: {e}"
+ raise CredentialsServiceUnreachableError(
+ f"The credentials service did not answer a credential request: {e}"
) from e
_log_resolve(url, keys, caller, started, response=response, body=body)
return body
- def _auth_headers(self, keys: list[str], caller: IntegrationCaller) -> dict[str, str]:
+ def _auth_headers(self, keys: list[str], caller: CredentialsCaller) -> 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],
+ PosthogJwtAudience.CREDENTIALS_SERVICE,
+ signing_key=credentials_service_signing_keys()[0],
)
return {"Authorization": f"Bearer {token}"}
@@ -352,16 +352,16 @@ class IntegrationSecretsClient:
return SecretValue(state="steady", value=value, incoming=None)
-_client = IntegrationSecretsClient()
+_client = CredentialsServiceClient()
-def get(key: str, caller: IntegrationCaller) -> str:
+def get(key: str, caller: CredentialsCaller) -> str:
return _client.get(key, caller)
-def get_many(keys: list[str], caller: IntegrationCaller) -> dict[str, str]:
+def get_many(keys: list[str], caller: CredentialsCaller) -> dict[str, str]:
return _client.get_many(keys, caller)
-def get_with_incoming(key: str, caller: IntegrationCaller) -> RotatingSecret:
+def get_with_incoming(key: str, caller: CredentialsCaller) -> RotatingSecret:
return _client.get_with_incoming(key, caller)
diff --git a/posthog/integration_secrets/errors.py b/posthog/credentials_service/errors.py
similarity index 86%
rename from posthog/integration_secrets/errors.py
rename to posthog/credentials_service/errors.py
index 7b58d83e75a9..d658aa227de4 100644
--- a/posthog/integration_secrets/errors.py
+++ b/posthog/credentials_service/errors.py
@@ -1,5 +1,5 @@
-class IntegrationSecretsFailure(Exception):
- """Base for everything the integration secrets client raises.
+class CredentialsServiceFailure(Exception):
+ """Base for everything the credentials service client raises.
One base type so a caller states the policy once, instead of listing subclasses it will
forget to update when a new one appears. Every failure below shares two properties, and
@@ -21,7 +21,7 @@ class IntegrationSecretsFailure(Exception):
reportable: bool = True
-class IntegrationSecretError(IntegrationSecretsFailure):
+class CredentialsSecretError(CredentialsServiceFailure):
"""A failure about one specific credential, which names it."""
def __init__(self, key: str, message: str) -> None:
@@ -29,7 +29,7 @@ class IntegrationSecretError(IntegrationSecretsFailure):
super().__init__(message)
-class SecretMissingError(IntegrationSecretError):
+class SecretMissingError(CredentialsSecretError):
"""The key is unknown to the service, or has no value in this environment.
Reportable: nothing resolves this on its own. Either a key never made it into the service
@@ -39,18 +39,18 @@ class SecretMissingError(IntegrationSecretError):
def __init__(self, key: str, disabled_reason: str | None = None) -> None:
if disabled_reason is None:
- super().__init__(key, f"{key} is not available from the integration service")
+ super().__init__(key, f"{key} is not available from the credentials service")
return
- # The service was never called, so saying "not available from the integration service"
+ # The service was never called, so saying "not available from the credentials service"
# would send the reader to look for a key that is sitting right there. Name the fallback.
super().__init__(
key,
- f"{key} is not set in this environment, and the integration service was not called "
+ f"{key} is not set in this environment, and the credentials service was not called "
f"({disabled_reason}) — so a key that exists only in the service cannot resolve here",
)
-class IntegrationServiceMisconfiguredError(IntegrationSecretsFailure):
+class CredentialsServiceMisconfiguredError(CredentialsServiceFailure):
"""Half-configured: one of the two variables is set and the other is not.
Both unset is a valid state — self-hosted and local development don't run the service, and
@@ -65,13 +65,13 @@ class IntegrationServiceMisconfiguredError(IntegrationSecretsFailure):
def __init__(self, missing: str) -> None:
self.missing = missing
super().__init__(
- f"{missing} is not set. The integration service client needs both "
- f"INTEGRATION_SERVICE_URL and INTEGRATION_SERVICE_JWT_SECRET, or neither "
+ f"{missing} is not set. The credentials service client needs both "
+ f"CREDENTIALS_SERVICE_URL and CREDENTIALS_SERVICE_JWT_SECRET, or neither "
f"(which reads credentials from the environment, as self-hosted does)."
)
-class SecretInRecoveryError(IntegrationSecretError):
+class SecretInRecoveryError(CredentialsSecretError):
"""The credential is known-burned and has no valid replacement yet.
Raised instead of returning a value that cannot work, so the caller surfaces
@@ -88,13 +88,13 @@ class SecretInRecoveryError(IntegrationSecretError):
super().__init__(key, f"{key} is in recovery — the credential needs to be re-provisioned")
-class IntegrationServiceUnreachableError(IntegrationSecretsFailure):
+class CredentialsServiceUnreachableError(CredentialsServiceFailure):
"""The service could not be reached, refused the request, or did not answer with usable JSON.
Exists so no `requests` exception escapes this client. A caller that catches a bare
`HTTPError` cannot tell our own service refusing a request from the third-party API the
caller was actually trying to reach — and at least one caller reads a bare 404 as "the
- user's endpoint is gone" and stops their work over it. A misrouted `INTEGRATION_SERVICE_URL`
+ user's endpoint is gone" and stops their work over it. A misrouted `CREDENTIALS_SERVICE_URL`
returns 404 too, so without this type our own deploy error would be reported as their
mistake.
diff --git a/posthog/integration_secrets/test/__init__.py b/posthog/credentials_service/test/__init__.py
similarity index 100%
rename from posthog/integration_secrets/test/__init__.py
rename to posthog/credentials_service/test/__init__.py
diff --git a/posthog/integration_secrets/test/test_client.py b/posthog/credentials_service/test/test_client.py
similarity index 82%
rename from posthog/integration_secrets/test/test_client.py
rename to posthog/credentials_service/test/test_client.py
index 44938b1a148b..d55949cd1636 100644
--- a/posthog/integration_secrets/test/test_client.py
+++ b/posthog/credentials_service/test/test_client.py
@@ -11,31 +11,31 @@ 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.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.client import (
+ CredentialsServiceClient,
+ credentials_service_enabled,
+ credentials_service_signing_keys,
)
-from posthog.integration_secrets.errors import (
- IntegrationSecretsFailure,
- IntegrationServiceMisconfiguredError,
- IntegrationServiceUnreachableError,
+from posthog.credentials_service.errors import (
+ CredentialsServiceFailure,
+ CredentialsServiceMisconfiguredError,
+ CredentialsServiceUnreachableError,
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",
+ "CREDENTIALS_SERVICE_URL": "http://credentials-service.credentials-service.svc.cluster.local",
+ "CREDENTIALS_SERVICE_JWT_SECRET": "signing-key-new,signing-key-old",
}
KEY = "HUBSPOT_APP_CLIENT_SECRET"
-CALLER = IntegrationCaller.WAREHOUSE_SOURCES
+CALLER = CredentialsCaller.WAREHOUSE_SOURCES
-FLAG = "posthog.integration_secrets.client.posthoganalytics.feature_enabled"
-POST = "posthog.integration_secrets.client.internal_requests.post"
+FLAG = "posthog.credentials_service.client.posthoganalytics.feature_enabled"
+POST = "posthog.credentials_service.client.internal_requests.post"
class FakeResponse:
@@ -58,9 +58,9 @@ def steady(value: str) -> dict[str, Any]:
@override_settings(**SERVICE_SETTINGS)
-class TestIntegrationSecretsClient(SimpleTestCase):
+class TestCredentialsServiceClient(SimpleTestCase):
def setUp(self) -> None:
- self.secrets = IntegrationSecretsClient()
+ self.secrets = CredentialsServiceClient()
flag = patch(FLAG, return_value=True)
flag.start()
self.addCleanup(flag.stop)
@@ -127,13 +127,13 @@ class TestIntegrationSecretsClient(SimpleTestCase):
return {"error": "Secret store unavailable"}
with patch(POST, return_value=ErrorResponse()):
- with pytest.raises(IntegrationServiceUnreachableError):
+ with pytest.raises(CredentialsServiceUnreachableError):
self.secrets.get(KEY, CALLER)
# No `requests` exception may escape, whatever the status. A caller is mid-conversation with
# some third party, so a bare HTTPError from here is indistinguishable from one that API
# raised — and callers act on that difference. The 404 is the case that bites: a misrouted
- # INTEGRATION_SERVICE_URL is our deploy error, but a caller seeing a raw 404 reads it as the
+ # CREDENTIALS_SERVICE_URL is our deploy error, but a caller seeing a raw 404 reads it as the
# user's endpoint being gone and can stop their work over it.
@parameterized.expand(
[
@@ -155,7 +155,7 @@ class TestIntegrationSecretsClient(SimpleTestCase):
side_effect = raised if isinstance(raised, requests.ConnectionError | requests.Timeout) else None
patched = patch(POST, side_effect=side_effect) if side_effect else patch(POST, return_value=ErrorResponse())
with patched:
- with pytest.raises(IntegrationServiceUnreachableError) as exc_info:
+ with pytest.raises(CredentialsServiceUnreachableError) as exc_info:
self.secrets.get(KEY, CALLER)
# The cause is kept so error tracking and logs still show what actually went wrong.
assert exc_info.value.__cause__ is raised
@@ -172,7 +172,7 @@ class TestIntegrationSecretsClient(SimpleTestCase):
raise ValueError("Expecting value: line 1 column 1 (char 0)")
with patch(POST, return_value=HtmlResponse()):
- with pytest.raises(IntegrationServiceUnreachableError):
+ with pytest.raises(CredentialsServiceUnreachableError):
self.secrets.get(KEY, CALLER)
# With no cache there is no last known good, so an outage is an outage. This is the
@@ -182,16 +182,16 @@ class TestIntegrationSecretsClient(SimpleTestCase):
with patch(POST, return_value=FakeResponse(body({KEY: steady("sec")}))):
self.secrets.get(KEY, CALLER)
- with patch(POST, side_effect=requests.ConnectionError("integration service is down")):
- with pytest.raises(IntegrationServiceUnreachableError):
+ with patch(POST, side_effect=requests.ConnectionError("credentials service is down")):
+ with pytest.raises(CredentialsServiceUnreachableError):
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=requests.ConnectionError("integration service is down")),
+ patch(POST, side_effect=requests.ConnectionError("credentials service is down")),
patch.dict("os.environ", {KEY: "from-env"}),
):
- with pytest.raises(IntegrationServiceUnreachableError):
+ with pytest.raises(CredentialsServiceUnreachableError):
self.secrets.get(KEY, CALLER)
# The base type is the whole contract a caller depends on: catch one thing, and a subclass
@@ -200,21 +200,21 @@ class TestIntegrationSecretsClient(SimpleTestCase):
[
("missing", SecretMissingError(KEY), True),
("in recovery", SecretInRecoveryError(KEY), False),
- ("half-configured", IntegrationServiceMisconfiguredError("INTEGRATION_SERVICE_URL"), True),
- ("unreachable", IntegrationServiceUnreachableError("no answer"), False),
+ ("half-configured", CredentialsServiceMisconfiguredError("CREDENTIALS_SERVICE_URL"), True),
+ ("unreachable", CredentialsServiceUnreachableError("no answer"), False),
]
)
def test_every_failure_shares_the_base_type_and_declares_reportability(
self, _name: str, error: Exception, reportable: bool
) -> None:
- assert isinstance(error, IntegrationSecretsFailure)
+ assert isinstance(error, CredentialsServiceFailure)
assert error.reportable is reportable
@override_settings(**SERVICE_SETTINGS)
class TestRolloutFlag(SimpleTestCase):
def setUp(self) -> None:
- self.secrets = IntegrationSecretsClient()
+ self.secrets = CredentialsServiceClient()
def test_reads_the_environment_while_the_flag_is_off(self) -> None:
with (
@@ -249,26 +249,26 @@ class TestRolloutFlag(SimpleTestCase):
self, _name: str, url: str, key: str, flag: bool, expected: bool
) -> None:
with (
- override_settings(INTEGRATION_SERVICE_URL=url, INTEGRATION_SERVICE_JWT_SECRET=key),
+ override_settings(CREDENTIALS_SERVICE_URL=url, CREDENTIALS_SERVICE_JWT_SECRET=key),
patch(FLAG, return_value=flag),
):
- assert integration_service_enabled() is expected
+ assert credentials_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="")
+ @override_settings(CREDENTIALS_SERVICE_URL="", CREDENTIALS_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)
+ CredentialsServiceClient().get("A_KEY_NOBODY_SET", CALLER)
- @override_settings(INTEGRATION_SERVICE_URL="", INTEGRATION_SERVICE_JWT_SECRET="")
+ @override_settings(CREDENTIALS_SERVICE_URL="", CREDENTIALS_SERVICE_JWT_SECRET="")
def test_the_error_says_the_service_was_never_called(self) -> None:
- # "not available from the integration service" sends the reader to look for a key that is
+ # "not available from the credentials service" sends the reader to look for a key that is
# sitting in the service already. The reason it did not resolve is that nothing asked.
with pytest.raises(SecretMissingError) as excinfo:
- IntegrationSecretsClient().get("A_KEY_NOBODY_SET", CALLER)
+ CredentialsServiceClient().get("A_KEY_NOBODY_SET", CALLER)
assert "was not called" in str(excinfo.value)
assert "unconfigured" in str(excinfo.value)
@@ -278,37 +278,37 @@ class TestHalfConfigured(SimpleTestCase):
@parameterized.expand(
[
- ("url without a signing key", "http://svc", "", "INTEGRATION_SERVICE_JWT_SECRET"),
- ("signing key without a url", "", "signing-key", "INTEGRATION_SERVICE_URL"),
+ ("url without a signing key", "http://svc", "", "CREDENTIALS_SERVICE_JWT_SECRET"),
+ ("signing key without a url", "", "signing-key", "CREDENTIALS_SERVICE_URL"),
]
)
def test_raises_naming_the_variable_still_needed(self, _name: str, url: str, key: str, missing: str) -> None:
with (
- override_settings(INTEGRATION_SERVICE_URL=url, INTEGRATION_SERVICE_JWT_SECRET=key),
+ override_settings(CREDENTIALS_SERVICE_URL=url, CREDENTIALS_SERVICE_JWT_SECRET=key),
patch(POST) as post,
patch(FLAG, return_value=True),
):
- with pytest.raises(IntegrationServiceMisconfiguredError) as excinfo:
- IntegrationSecretsClient().get(KEY, CALLER)
+ with pytest.raises(CredentialsServiceMisconfiguredError) as excinfo:
+ CredentialsServiceClient().get(KEY, CALLER)
assert missing in str(excinfo.value)
post.assert_not_called()
- @override_settings(INTEGRATION_SERVICE_URL="http://svc", INTEGRATION_SERVICE_JWT_SECRET="")
+ @override_settings(CREDENTIALS_SERVICE_URL="http://svc", CREDENTIALS_SERVICE_JWT_SECRET="")
def test_a_mounted_environment_variable_does_not_paper_over_it(self) -> None:
# The failure this exists to catch. Half-configured, the fallback would have returned the
# value from the pod's environment and the deployment would look wired up — until someone
# asks for a credential that only exists in the service.
with patch.dict(os.environ, {KEY: "still-mounted-on-the-pod"}):
- with pytest.raises(IntegrationServiceMisconfiguredError):
- IntegrationSecretsClient().get(KEY, CALLER)
+ with pytest.raises(CredentialsServiceMisconfiguredError):
+ CredentialsServiceClient().get(KEY, CALLER)
- @override_settings(INTEGRATION_SERVICE_URL="http://svc", INTEGRATION_SERVICE_JWT_SECRET="")
+ @override_settings(CREDENTIALS_SERVICE_URL="http://svc", CREDENTIALS_SERVICE_JWT_SECRET="")
def test_the_flag_does_not_rescue_a_half_configured_deployment(self) -> None:
# Turning the flag off is how you disable the client deliberately; it is not a way to make
# a misconfiguration legal, or the rollout gate would hide it.
with patch(FLAG, return_value=False):
- with pytest.raises(IntegrationServiceMisconfiguredError):
- IntegrationSecretsClient().get(KEY, CALLER)
+ with pytest.raises(CredentialsServiceMisconfiguredError):
+ CredentialsServiceClient().get(KEY, CALLER)
@override_settings(**SERVICE_SETTINGS)
@@ -316,7 +316,7 @@ 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()
+ self.secrets = CredentialsServiceClient()
flag = patch(FLAG, return_value=True)
flag.start()
self.addCleanup(flag.stop)
@@ -325,8 +325,8 @@ class TestMintedToken(SimpleTestCase):
header = post.call_args.kwargs["headers"]["Authorization"]
return jwt.decode(
header.removeprefix("Bearer "),
- integration_service_signing_keys()[0],
- audience=PosthogJwtAudience.INTEGRATION_SERVICE.value,
+ credentials_service_signing_keys()[0],
+ audience=PosthogJwtAudience.CREDENTIALS_SERVICE.value,
algorithms=["HS256"],
)
@@ -336,12 +336,12 @@ class TestMintedToken(SimpleTestCase):
claims = self._claims_from_call(post)
assert claims["keys"] == [KEY]
- assert claims["aud"] == PosthogJwtAudience.INTEGRATION_SERVICE.value
+ assert claims["aud"] == PosthogJwtAudience.CREDENTIALS_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)
+ self.secrets.get(KEY, CredentialsCaller.CDP)
assert self._claims_from_call(post)["caller"] == "cdp"
def test_signs_with_the_newest_key_so_rotation_is_zero_downtime(self) -> None:
@@ -349,7 +349,7 @@ class TestMintedToken(SimpleTestCase):
self.secrets.get(KEY, CALLER)
token = post.call_args.kwargs["headers"]["Authorization"].removeprefix("Bearer ")
- audience = PosthogJwtAudience.INTEGRATION_SERVICE.value
+ audience = PosthogJwtAudience.CREDENTIALS_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"])
@@ -360,7 +360,7 @@ class TestResolveLogging(SimpleTestCase):
"""The credential read is otherwise the one invisible hop in a job's HTTP traffic."""
def setUp(self) -> None:
- self.secrets = IntegrationSecretsClient()
+ self.secrets = CredentialsServiceClient()
flag = patch(FLAG, return_value=True)
flag.start()
self.addCleanup(flag.stop)
@@ -375,14 +375,14 @@ class TestResolveLogging(SimpleTestCase):
# Same names as data_imports.http.request, so a credential read shows up in the same
# query as the rest of a job's traffic rather than needing its own.
with patch(POST, return_value=self._response(body({KEY: steady("sec")}))):
- with patch("posthog.integration_secrets.client.logger") as log:
+ with patch("posthog.credentials_service.client.logger") as log:
self.secrets.get(KEY, CALLER)
fields = log.debug.call_args.kwargs
- assert log.debug.call_args.args[0] == "integration_secrets.resolve"
+ assert log.debug.call_args.args[0] == "credentials_service.resolve"
assert fields["method"] == "POST"
assert fields["status_code"] == 200
- assert fields["host"] == "integration-service.posthog.svc.cluster.local"
+ assert fields["host"] == "credentials-service.credentials-service.svc.cluster.local"
assert fields["error_class"] is None
assert fields["caller"] == str(CALLER)
assert fields["keys"] == [KEY]
@@ -399,7 +399,7 @@ class TestResolveLogging(SimpleTestCase):
"fetched_at": "now",
}
with patch(POST, return_value=self._response(body({KEY: rotating}))):
- with patch("posthog.integration_secrets.client.logger") as log:
+ with patch("posthog.credentials_service.client.logger") as log:
self.secrets.get(KEY, CALLER)
# info, not debug: a value changing under a caller that did nothing differently is the
@@ -421,7 +421,7 @@ class TestResolveLogging(SimpleTestCase):
)
def test_logs_at_info_for(self, _name: str, payload: dict[str, Any], expected: type[Exception]) -> None:
with patch(POST, return_value=self._response(body(**payload))):
- with patch("posthog.integration_secrets.client.logger") as log:
+ with patch("posthog.credentials_service.client.logger") as log:
with pytest.raises(expected):
self.secrets.get(KEY, CALLER)
@@ -430,8 +430,8 @@ class TestResolveLogging(SimpleTestCase):
def test_logs_a_transport_failure_at_warning_with_the_error_class(self) -> None:
with patch(POST, side_effect=requests.ConnectionError("connection refused")):
- with patch("posthog.integration_secrets.client.logger") as log:
- with pytest.raises(IntegrationServiceUnreachableError):
+ with patch("posthog.credentials_service.client.logger") as log:
+ with pytest.raises(CredentialsServiceUnreachableError):
self.secrets.get(KEY, CALLER)
fields = log.warning.call_args.kwargs
@@ -451,7 +451,7 @@ class TestResolveLogging(SimpleTestCase):
"fetched_at": "now",
}
with patch(POST, return_value=self._response(body({KEY: rotating}))):
- with patch("posthog.integration_secrets.client.logger") as log:
+ with patch("posthog.credentials_service.client.logger") as log:
assert self.secrets.get(KEY, CALLER) == secret_value
emitted = repr([c.kwargs for c in log.info.call_args_list + log.debug.call_args_list])
@@ -464,7 +464,7 @@ class TestResolveLogging(SimpleTestCase):
def test_a_broken_logger_cannot_fail_a_credential_read(self) -> None:
# Same contract as the warehouse observer: telemetry must never become an outage.
with patch(POST, return_value=self._response(body({KEY: steady("sec")}))):
- with patch("posthog.integration_secrets.client.logger") as log:
+ with patch("posthog.credentials_service.client.logger") as log:
log.debug.side_effect = [RuntimeError("log pipeline is down"), None]
assert self.secrets.get(KEY, CALLER) == "sec"
@@ -484,12 +484,12 @@ class TestInjectedSession(SimpleTestCase):
session.post.return_value = FakeResponse(body({KEY: steady("sec")}))
with patch(POST) as shared_post:
- assert IntegrationSecretsClient(session=session).get(KEY, CALLER) == "sec"
+ assert CredentialsServiceClient(session=session).get(KEY, CALLER) == "sec"
session.post.assert_called_once()
shared_post.assert_not_called()
def test_defaults_to_the_shared_internal_session(self) -> None:
with patch(POST, return_value=FakeResponse(body({KEY: steady("sec")}))) as shared_post:
- assert IntegrationSecretsClient().get(KEY, CALLER) == "sec"
+ assert CredentialsServiceClient().get(KEY, CALLER) == "sec"
shared_post.assert_called_once()
diff --git a/posthog/jwt.py b/posthog/jwt.py
index 8f1b34a2dcff..63935b45299a 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -31,7 +31,7 @@ class PosthogJwtAudience(Enum):
WORKFLOWS_CANCEL_INVOCATIONS = "posthog:workflows:cancel_invocations"
WORKFLOWS_CANCEL_BATCH = "posthog:workflows:cancel_batch"
WORKFLOWS_STEP_RESUME = "posthog:workflows:step_resume"
- INTEGRATION_SERVICE = "posthog:integration_service"
+ CREDENTIALS_SERVICE = "posthog:credentials_service"
TASKS_CREATE = "posthog:tasks:create"
CUSTOMER_TASKS_CREATE = "posthog:customer-tasks:create"
WORKFLOW_SCOUT_RUN = "posthog:workflows:scout_run"
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index 157b1a994eb4..f68bf99450f1 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -3,11 +3,11 @@ import os
from posthog.settings.base_variables import BASE_DIR
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", "")
+# Credentials service. Both unset (the default) means credential reads fall back to the
+# local environment; see posthog/credentials_service/client.py for the contract.
+CREDENTIALS_SERVICE_URL = get_from_env("CREDENTIALS_SERVICE_URL", "")
# Comma-separated `new,old`, newest first. Per deployment, not fleet-wide.
-INTEGRATION_SERVICE_JWT_SECRET = get_from_env("INTEGRATION_SERVICE_JWT_SECRET", "")
+CREDENTIALS_SERVICE_JWT_SECRET = get_from_env("CREDENTIALS_SERVICE_JWT_SECRET", "")
# Bot token and channel for the staff-only UI feedback widget. Empty token disables delivery.
INTERNAL_FEEDBACK_SLACK_BOT_TOKEN = get_from_env("INTERNAL_FEEDBACK_SLACK_BOT_TOKEN", "")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py
index 36b330c4163e..694418c2d925 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py
@@ -10,7 +10,7 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldOauthConfig,
SuggestedTable,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
MARKETING_ANALYTICS_SUGGESTED_TABLE_TOOLTIP,
FieldType,
@@ -282,7 +282,7 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], O
"The linked Bing Ads integration could not be found. Please reconnect your Bing Ads integration."
) from e
- developer_token = integration_secrets.get_secret("BING_ADS_DEVELOPER_TOKEN")
+ developer_token = credentials_service.get_secret("BING_ADS_DEVELOPER_TOKEN")
if not developer_token:
raise ValueError("Bing Ads developer token not configured")
if not integration.access_token:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py
index 6535f985ef3d..a4a24b6a7363 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py
@@ -250,7 +250,7 @@ class TestBingAdsSource:
],
)
@mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.source.integration_secrets.get_secret",
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.source.credentials_service.get_secret",
return_value="dev-token",
)
@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.source.BingAdsClient")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_secrets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/credentials_service.py
similarity index 90%
rename from products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_secrets.py
rename to products/warehouse_sources/backend/temporal/data_imports/sources/common/credentials_service.py
index c0c82a078e44..cca46086f5bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_secrets.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/credentials_service.py
@@ -8,7 +8,7 @@ means rotating one is a charts PR and a restart of everything that mounts it.
This module is the single place sources go instead. It binds the two things every warehouse call
would otherwise repeat, and gets wrong differently each time:
-- **The caller identity.** `IntegrationCaller.WAREHOUSE_SOURCES` is what the service writes to its
+- **The caller identity.** `CredentialsCaller.WAREHOUSE_SOURCES` is what the service writes to its
audit log, so it is how "who read this credential" gets answered. Pinning it here means a new
source cannot label its reads as something else by copying the wrong line.
- **The transport.** A session that meters and logs like the rest of a job's HTTP traffic, with
@@ -37,20 +37,20 @@ import structlog
from prometheus_client import Counter
from urllib3.util.retry import Retry
-from posthog.integration_secrets import client as integration_secrets_client
-from posthog.integration_secrets.callers import IntegrationCaller
-from posthog.integration_secrets.client import RotatingSecret
-from posthog.integration_secrets.errors import SecretMissingError
+from posthog.credentials_service import client as credentials_service_client
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.client import RotatingSecret
+from posthog.credentials_service.errors import SecretMissingError
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
logger = structlog.get_logger(__name__)
-CALLER = IntegrationCaller.WAREHOUSE_SOURCES
+CALLER = CredentialsCaller.WAREHOUSE_SOURCES
SETTINGS_FALLBACK_COUNTER = Counter(
- "posthog_warehouse_integration_secret_settings_fallback_total",
- "Platform credential reads the integration service could not serve, by what happened instead",
+ "posthog_warehouse_credentials_service_settings_fallback_total",
+ "Platform credential reads the credentials service could not serve, by what happened instead",
# outcome="settings": the key is still only in settings, so the rollout isn't finished for it.
# outcome="unset": the credential isn't configured anywhere, which is the normal state of an
# integration a deployment doesn't use. Separated because only the first is a rollout gap.
@@ -66,7 +66,7 @@ def _build_session() -> requests.Session:
they can be read back while debugging a source, and the name-based scrubbers cannot recognise
a value they have never seen. Metering and the log line survive; only the body capture is off.
- `trust_env=False` — the integration service is an internal, in-cluster address. Warehouse
+ `trust_env=False` — the credentials service is an internal, in-cluster address. Warehouse
outbound traffic goes through the Smokescreen egress proxy, which re-resolves every hop and
blocks internal and metadata hosts. That is exactly right for a customer's API and exactly
wrong here: left on, every credential read would be handed to a proxy whose job is to refuse
@@ -88,7 +88,7 @@ def _build_session() -> requests.Session:
# context from contextvars at request time, so a single session still labels each request with the
# team and source it was made for.
_session = _build_session()
-_client = integration_secrets_client.IntegrationSecretsClient(session=_session)
+_client = credentials_service_client.CredentialsServiceClient(session=_session)
def _from_settings(key: str) -> str | None:
@@ -100,7 +100,7 @@ def _resolve_one(key: str) -> str:
"""One credential, falling back to settings while the key is still on its way into the service.
TEMPORARY, and the removal condition is exact: when
- `posthog_warehouse_integration_secret_settings_fallback_total` has been zero across a full sync
+ `posthog_warehouse_credentials_service_settings_fallback_total` has been zero across a full sync
cycle, every key has moved and this function collapses back to `_client.get`.
It exists because the call sites and the keys cannot move at the same instant. The service is
@@ -127,7 +127,7 @@ def _resolve_one(key: str) -> str:
value = _from_settings(key)
if value is not None:
SETTINGS_FALLBACK_COUNTER.labels(key=key, outcome="settings").inc()
- logger.warning("warehouse_integration_secret.settings_fallback", key=key)
+ logger.warning("warehouse_credentials_service.settings_fallback", key=key)
return value
# Configured nowhere. Before this migration the call site read `settings.X` and got the
@@ -138,7 +138,7 @@ def _resolve_one(key: str) -> str:
# self-hosted, local development, and every test that never set it — which is a much wider
# blast radius than the migration itself, and no part of what it is for.
SETTINGS_FALLBACK_COUNTER.labels(key=key, outcome="unset").inc()
- logger.debug("warehouse_integration_secret.unset", key=key)
+ logger.debug("warehouse_credentials_service.unset", key=key)
return ""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_integration_secrets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_credentials_service.py
similarity index 80%
rename from products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_integration_secrets.py
rename to products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_credentials_service.py
index 443d015a7db3..1335d5394e94 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_integration_secrets.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_credentials_service.py
@@ -8,20 +8,20 @@ from django.test import SimpleTestCase, override_settings
import jwt
import requests
-from posthog.integration_secrets.callers import IntegrationCaller
-from posthog.integration_secrets.errors import IntegrationServiceUnreachableError, SecretInRecoveryError
+from posthog.credentials_service.callers import CredentialsCaller
+from posthog.credentials_service.errors import CredentialsServiceUnreachableError, SecretInRecoveryError
from posthog.jwt import PosthogJwtAudience
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import TrackedHTTPAdapter
SERVICE_SETTINGS: dict[str, Any] = {
- "INTEGRATION_SERVICE_URL": "http://integration-service.posthog.svc.cluster.local",
- "INTEGRATION_SERVICE_JWT_SECRET": "signing-key",
+ "CREDENTIALS_SERVICE_URL": "http://credentials-service.credentials-service.svc.cluster.local",
+ "CREDENTIALS_SERVICE_JWT_SECRET": "signing-key",
}
KEY = "GOOGLE_ADS_DEVELOPER_TOKEN"
-FLAG = "posthog.integration_secrets.client.posthoganalytics.feature_enabled"
+FLAG = "posthog.credentials_service.client.posthoganalytics.feature_enabled"
class _FakeResponse:
@@ -52,7 +52,7 @@ class TestSessionProperties(SimpleTestCase):
# recognise a value they've never seen — so capture must be off at the adapter, not filtered
# afterwards.
def test_http_sample_capture_is_disabled(self) -> None:
- session = integration_secrets._build_session()
+ session = credentials_service._build_session()
adapters = [session.get_adapter("https://x"), session.get_adapter("http://x")]
assert adapters, "expected tracked adapters to be mounted"
for adapter in adapters:
@@ -64,12 +64,12 @@ class TestSessionProperties(SimpleTestCase):
# customer's API, and the exact wrong thing here: every credential read would be handed to a
# proxy whose job is to refuse it.
def test_the_egress_proxy_is_bypassed(self) -> None:
- assert integration_secrets._build_session().trust_env is False
+ assert credentials_service._build_session().trust_env is False
# No cache means no last known good, so a retry here only delays a failure Temporal already
# retries with backoff. Matches the shared internal session, whose adapter also doesn't retry.
def test_the_transport_does_not_retry(self) -> None:
- session = integration_secrets._build_session()
+ session = credentials_service._build_session()
adapter = session.get_adapter("https://x")
assert isinstance(adapter, TrackedHTTPAdapter)
assert adapter.max_retries.total == 0
@@ -85,7 +85,7 @@ class TestHelper(SimpleTestCase):
@staticmethod
def _patched_post(payload: dict[str, Any] | None = None, **kwargs: Any) -> Any:
return mock.patch.object(
- integration_secrets._session,
+ credentials_service._session,
"post",
return_value=_FakeResponse(payload or _body("token")),
**kwargs,
@@ -96,16 +96,16 @@ class TestHelper(SimpleTestCase):
# source can't label its reads as something else by copying the wrong line.
def test_every_read_is_attributed_to_warehouse_sources(self) -> None:
with self._patched_post() as post:
- assert integration_secrets.get_secret(KEY) == "token"
+ assert credentials_service.get_secret(KEY) == "token"
token = post.call_args.kwargs["headers"]["Authorization"].removeprefix("Bearer ")
claims = jwt.decode(
token,
"signing-key",
algorithms=["HS256"],
- audience=PosthogJwtAudience.INTEGRATION_SERVICE.value,
+ audience=PosthogJwtAudience.CREDENTIALS_SERVICE.value,
)
- assert claims["caller"] == str(IntegrationCaller.WAREHOUSE_SOURCES)
+ assert claims["caller"] == str(CredentialsCaller.WAREHOUSE_SOURCES)
assert claims["keys"] == [KEY]
def test_several_keys_resolve_in_one_request(self) -> None:
@@ -117,7 +117,7 @@ class TestHelper(SimpleTestCase):
"missing": [],
}
with self._patched_post(payload) as post:
- assert integration_secrets.get_secrets(keys) == {k: f"v-{k}" for k in keys}
+ assert credentials_service.get_secrets(keys) == {k: f"v-{k}" for k in keys}
assert post.call_count == 1
def test_a_rotation_exposes_both_values(self) -> None:
@@ -134,7 +134,7 @@ class TestHelper(SimpleTestCase):
"missing": [],
}
with self._patched_post(payload):
- secret = integration_secrets.get_secret_with_incoming(KEY)
+ secret = credentials_service.get_secret_with_incoming(KEY)
assert (secret.current, secret.incoming) == ("live", "staged")
# A key the service holds is read from the service, not from the environment it also still
@@ -142,31 +142,31 @@ class TestHelper(SimpleTestCase):
def test_the_service_wins_over_a_value_still_in_the_environment(self) -> None:
with mock.patch.dict("os.environ", {KEY: "stale-copy-in-settings"}):
with self._patched_post():
- assert integration_secrets.get_secret(KEY) == "token"
+ assert credentials_service.get_secret(KEY) == "token"
class TestServiceOff(SimpleTestCase):
# With the service unconfigured — self-hosted, local development — the client reads the same
# environment value the source reads today. This is what makes a migrated call site a no-op
# until the key actually moves.
- @override_settings(INTEGRATION_SERVICE_URL=None, INTEGRATION_SERVICE_JWT_SECRET=None)
+ @override_settings(CREDENTIALS_SERVICE_URL=None, CREDENTIALS_SERVICE_JWT_SECRET=None)
def test_falls_back_to_the_environment_without_calling_out(self) -> None:
- with mock.patch.object(integration_secrets._session, "post", side_effect=AssertionError("called out")):
+ with mock.patch.object(credentials_service._session, "post", side_effect=AssertionError("called out")):
with mock.patch.dict("os.environ", {KEY: "from-env"}):
- assert integration_secrets.get_secret(KEY) == "from-env"
+ assert credentials_service.get_secret(KEY) == "from-env"
class TestNoRequestsExceptionEscapes(SimpleTestCase):
@override_settings(**SERVICE_SETTINGS)
def test_transport_failure_is_typed(self) -> None:
- from posthog.integration_secrets.errors import IntegrationServiceUnreachableError
+ from posthog.credentials_service.errors import CredentialsServiceUnreachableError
with mock.patch(FLAG, return_value=True):
with mock.patch.object(
- integration_secrets._session, "post", side_effect=requests.ConnectionError("refused")
+ credentials_service._session, "post", side_effect=requests.ConnectionError("refused")
):
- with pytest.raises(IntegrationServiceUnreachableError):
- integration_secrets.get_secret(KEY)
+ with pytest.raises(CredentialsServiceUnreachableError):
+ credentials_service.get_secret(KEY)
@override_settings(**SERVICE_SETTINGS)
@@ -181,11 +181,11 @@ class TestSettingsFallbackBridge(SimpleTestCase):
flag = mock.patch(FLAG, return_value=True)
flag.start()
self.addCleanup(flag.stop)
- integration_secrets.SETTINGS_FALLBACK_COUNTER.clear()
+ credentials_service.SETTINGS_FALLBACK_COUNTER.clear()
def _missing(self) -> Any:
return mock.patch.object(
- integration_secrets._session,
+ credentials_service._session,
"post",
return_value=_FakeResponse({"secrets": {}, "missing": [KEY]}),
)
@@ -195,37 +195,37 @@ class TestSettingsFallbackBridge(SimpleTestCase):
def test_a_key_not_in_the_service_falls_back_to_settings(self) -> None:
with self._missing():
with mock.patch.dict("os.environ", {KEY: "still-in-settings"}):
- assert integration_secrets.get_secret(KEY) == "still-in-settings"
+ assert credentials_service.get_secret(KEY) == "still-in-settings"
# The fallback is what you watch to know the rollout is done, so it has to be countable and
# name the key. A silent one would be the failure mode the client refuses to have.
def test_the_fallback_is_counted_and_named(self) -> None:
with self._missing():
with mock.patch.dict("os.environ", {KEY: "still-in-settings"}):
- with mock.patch.object(integration_secrets, "logger") as log:
- integration_secrets.get_secret(KEY)
+ with mock.patch.object(credentials_service, "logger") as log:
+ credentials_service.get_secret(KEY)
- assert integration_secrets.SETTINGS_FALLBACK_COUNTER.labels(key=KEY, outcome="settings")._value.get() == 1
+ assert credentials_service.SETTINGS_FALLBACK_COUNTER.labels(key=KEY, outcome="settings")._value.get() == 1
assert log.warning.call_args.kwargs["key"] == KEY
# Recovery means the credential is known-burned. The settings copy is the burned value, so
# falling back would turn the kill switch into a no-op — worse than the sync stopping.
def test_recovery_does_not_fall_back(self) -> None:
payload = {"secrets": {KEY: {"state": "recovery", "version_id": "v1", "fetched_at": "now"}}, "missing": []}
- with mock.patch.object(integration_secrets._session, "post", return_value=_FakeResponse(payload)):
+ with mock.patch.object(credentials_service._session, "post", return_value=_FakeResponse(payload)):
with mock.patch.dict("os.environ", {KEY: "the-burned-value"}):
with pytest.raises(SecretInRecoveryError):
- integration_secrets.get_secret(KEY)
+ credentials_service.get_secret(KEY)
- assert integration_secrets.SETTINGS_FALLBACK_COUNTER.labels(key=KEY, outcome="settings")._value.get() == 0
+ assert credentials_service.SETTINGS_FALLBACK_COUNTER.labels(key=KEY, outcome="settings")._value.get() == 0
# An outage is not a rollout gap. There is no last known good here, and treating "no answer"
# as "the key isn't there" would quietly serve stale credentials through an incident.
def test_an_unreachable_service_does_not_fall_back(self) -> None:
- with mock.patch.object(integration_secrets._session, "post", side_effect=requests.ConnectionError("refused")):
+ with mock.patch.object(credentials_service._session, "post", side_effect=requests.ConnectionError("refused")):
with mock.patch.dict("os.environ", {KEY: "still-in-settings"}):
- with pytest.raises(IntegrationServiceUnreachableError):
- integration_secrets.get_secret(KEY)
+ with pytest.raises(CredentialsServiceUnreachableError):
+ credentials_service.get_secret(KEY)
# Configured nowhere is the normal state of an integration a deployment doesn't use, and it
# is what `settings.X` already returned. This migration moves where a credential comes from;
@@ -234,9 +234,9 @@ class TestSettingsFallbackBridge(SimpleTestCase):
def test_configured_nowhere_returns_what_settings_returned(self) -> None:
with self._missing():
with mock.patch.dict("os.environ", {}, clear=True):
- assert integration_secrets.get_secret(KEY) == ""
+ assert credentials_service.get_secret(KEY) == ""
- counter = integration_secrets.SETTINGS_FALLBACK_COUNTER
+ counter = credentials_service.SETTINGS_FALLBACK_COUNTER
assert counter.labels(key=KEY, outcome="unset")._value.get() == 1
# Not a rollout gap, so it must not be counted as one.
assert counter.labels(key=KEY, outcome="settings")._value.get() == 0
@@ -255,9 +255,9 @@ class TestSettingsFallbackBridge(SimpleTestCase):
return _FakeResponse({"secrets": {other: in_service}, "missing": []})
return _FakeResponse({"secrets": {}, "missing": [KEY]})
- with mock.patch.object(integration_secrets._session, "post", side_effect=post):
+ with mock.patch.object(credentials_service._session, "post", side_effect=post):
with mock.patch.dict("os.environ", {KEY: "still-in-settings"}):
- assert integration_secrets.get_secrets([KEY, other]) == {
+ assert credentials_service.get_secrets([KEY, other]) == {
KEY: "still-in-settings",
other: "from-service",
}
@@ -268,6 +268,6 @@ def _keys_asked_for(authorization: str) -> list[str]:
authorization.removeprefix("Bearer "),
"signing-key",
algorithms=["HS256"],
- audience=PosthogJwtAudience.INTEGRATION_SERVICE.value,
+ audience=PosthogJwtAudience.CREDENTIALS_SERVICE.value,
)
return list(claims["keys"])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
index 0ef1640d5cb3..21e58ce302c5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
@@ -37,7 +37,7 @@ from posthog.models.integration import Integration
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.grpc import tracked_interceptors
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource
@@ -241,7 +241,7 @@ def google_ads_client(config: GoogleAdsSourceConfigUnion, team_id: int) -> Googl
if config.is_mcc_account and config.is_mcc_account.enabled:
login_customer_id = clean_customer_id(config.is_mcc_account.mcc_client_id)
- resolved = integration_secrets.get_secrets(
+ resolved = credentials_service.get_secrets(
["GOOGLE_ADS_DEVELOPER_TOKEN", "GOOGLE_ADS_APP_CLIENT_ID", "GOOGLE_ADS_APP_CLIENT_SECRET"]
)
config_dict: dict[str, object] = {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py
index 00638ede0e7c..a140b389dddd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py
@@ -16,7 +16,7 @@ from posthog.dataclasses import frozen
from posthog.models.integration import Integration
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapter
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -110,7 +110,7 @@ def _get_integration(integration_id: int, team_id: int) -> Integration:
def _credentials(integration_id: int, team_id: int) -> OAuthCredentials:
integration = _get_integration(integration_id, team_id)
- resolved = integration_secrets.get_secrets(["GOOGLE_ANALYTICS_APP_CLIENT_ID", "GOOGLE_ANALYTICS_APP_CLIENT_SECRET"])
+ resolved = credentials_service.get_secrets(["GOOGLE_ANALYTICS_APP_CLIENT_ID", "GOOGLE_ANALYTICS_APP_CLIENT_SECRET"])
return OAuthCredentials(
token=None,
refresh_token=integration.refresh_token,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py
index 9709b7a01aed..140d5ed57392 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py
@@ -17,7 +17,7 @@ from google.oauth2.credentials import Credentials as OAuthCredentials
from posthog.models.integration import Integration
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapter
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -266,7 +266,7 @@ def _get_integration(integration_id: int, team_id: int) -> Integration:
def _credentials(integration_id: int, team_id: int) -> OAuthCredentials:
integration = _get_integration(integration_id, team_id)
- resolved = integration_secrets.get_secrets(
+ resolved = credentials_service.get_secrets(
["GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID", "GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET"]
)
return OAuthCredentials(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py
index 8f439ce502f4..014909ac1e5e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py
@@ -17,7 +17,7 @@ from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapter
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googlesheets import (
@@ -45,7 +45,7 @@ GOOGLE_SHEETS_API_VERSION_V4 = "v4"
def google_sheets_client() -> gspread.Client:
- resolved = integration_secrets.get_secrets(
+ resolved = credentials_service.get_secrets(
[
"GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY",
"GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY_ID",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py
index 80edb0b601e6..bd09784587a6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py
@@ -2,7 +2,7 @@ import requests
import structlog
from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
logger = structlog.get_logger(__name__)
@@ -53,7 +53,7 @@ def _error_message_from_response(res: requests.Response) -> str:
def _hubspot_app_credentials() -> dict[str, str]:
"""PostHog's own HubSpot app id and secret, as the token endpoint wants them named."""
- resolved = integration_secrets.get_secrets(["HUBSPOT_APP_CLIENT_ID", "HUBSPOT_APP_CLIENT_SECRET"])
+ resolved = credentials_service.get_secrets(["HUBSPOT_APP_CLIENT_ID", "HUBSPOT_APP_CLIENT_SECRET"])
return {
"client_id": resolved["HUBSPOT_APP_CLIENT_ID"],
"client_secret": resolved["HUBSPOT_APP_CLIENT_SECRET"],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py
index 54e00c31274b..1f05cf6ac204 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py
@@ -11,7 +11,7 @@ from requests.exceptions import (
Timeout as RequestsTimeout,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.deadline import (
DeadlineExceededError,
run_with_deadline,
@@ -130,7 +130,7 @@ _MAX_TOKEN_REFRESH_ATTEMPTS = 4
def _salesforce_app_credentials() -> dict[str, str]:
"""PostHog's own Salesforce connected-app key and secret, named as the token endpoint wants."""
- resolved = integration_secrets.get_secrets(["SALESFORCE_CONSUMER_KEY", "SALESFORCE_CONSUMER_SECRET"])
+ resolved = credentials_service.get_secrets(["SALESFORCE_CONSUMER_KEY", "SALESFORCE_CONSUMER_SECRET"])
return {
"client_id": resolved["SALESFORCE_CONSUMER_KEY"],
"client_secret": resolved["SALESFORCE_CONSUMER_SECRET"],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py
index 33c0e21cfed7..4c51632b6187 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py
@@ -8,7 +8,7 @@ from dateutil import parser
from requests import PreparedRequest, Request, Response
from requests.exceptions import HTTPError, RequestException, Timeout
-from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
@@ -60,7 +60,7 @@ def list_advertisers(access_token: str) -> list[dict]:
# Mask the app secret (a query param) and the access token (a header) so neither lands in
# request telemetry / captured samples. `timeout` guards the oauth_accounts web worker: TikTok
# has no default timeout, so a hung connection would otherwise pin the worker indefinitely.
- resolved = integration_secrets.get_secrets(["TIKTOK_ADS_CLIENT_ID", "TIKTOK_ADS_CLIENT_SECRET"])
+ resolved = credentials_service.get_secrets(["TIKTOK_ADS_CLIENT_ID", "TIKTOK_ADS_CLIENT_SECRET"])
app_secret = resolved["TIKTOK_ADS_CLIENT_SECRET"]
session = make_tracked_session(
headers={"Access-Token": access_token, "Content-Type": "application/json"},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index 591bec74422a..11b22e811417 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -19,9 +19,9 @@ from structlog.typing import FilteringBoundLogger
from temporalio import activity
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.credentials_service.errors import CredentialsServiceFailure
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
-from posthog.integration_secrets.errors import IntegrationSecretsFailure
from posthog.models.integration import UndecryptedIntegrationSecretError
from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.activity_context import current_activity_attempt
@@ -674,7 +674,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
try:
config = new_source.parse_config(model.pipeline.job_inputs)
- except IntegrationSecretsFailure as e:
+ except CredentialsServiceFailure as e:
# A source whose config carries a PostHog-owned credential resolves it here, so a
# failure at this point is ours and not a corrupt `job_inputs`. Route it through the
# shared policy: the branch below would read it as an unparseable config and disable
@@ -945,7 +945,7 @@ async def _handle_import_error(
job_inputs.team_id, str(job_inputs.source_id), job_inputs.run_id, error_msg, logger, error
)
- # Every credential the integration service holds is PostHog's own — the OAuth app secrets and
+ # Every credential the credentials service holds is PostHog's own — the OAuth app secrets and
# API keys we own, not anything the customer configured. So none of its failure states are
# theirs to fix, and none are permanent: a key in recovery is re-provisioned, a missing key is
# added, an unreachable service comes back. Retry, and if the budget runs out let the run fail
@@ -958,10 +958,10 @@ async def _handle_import_error(
# hand — turning a reversible platform action into a wide manual recovery.
#
# Checked before the bare-404 rule below on purpose. That rule reads a 404 as "the customer's
- # endpoint is gone", and a misrouted INTEGRATION_SERVICE_URL answers 404 as well; the client
+ # endpoint is gone", and a misrouted CREDENTIALS_SERVICE_URL answers 404 as well; the client
# wraps its transport failures so the two can't be confused, and this ordering keeps that true
# even if something later leaks a raw HTTPError.
- if isinstance(error, IntegrationSecretsFailure):
+ if isinstance(error, CredentialsServiceFailure):
if error.reportable:
# A gap only PostHog can close (a key never added for this environment, a
# half-configured deployment). Capture explicitly rather than letting it escape raw:
@@ -971,7 +971,7 @@ async def _handle_import_error(
await logger.aexception(error_msg)
else:
await logger.awarning(error_msg)
- await logger.adebug("Integration service credential unavailable - re-raising for Temporal retry")
+ await logger.adebug("Credentials service credential unavailable - re-raising for Temporal retry")
raise NonReportableError(INTEGRATION_CREDENTIAL_UNAVAILABLE_MESSAGE) from error
# A 404 from the shared REST engine's fallback `raise_for_status()` path means the configured
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
index 14808247ae21..96f4de00b760 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
@@ -6,8 +6,8 @@ from django.db import close_old_connections
from structlog.contextvars import bind_contextvars
from temporalio import activity
+from posthog.credentials_service.errors import CredentialsServiceFailure
from posthog.exceptions_capture import capture_exception
-from posthog.integration_secrets.errors import IntegrationSecretsFailure
from posthog.models.integration import UndecryptedIntegrationSecretError
from posthog.temporal.common.errors import NonReportableError
from posthog.temporal.common.logger import get_logger
@@ -116,7 +116,7 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:
return
error_msg = str(e)
- # Every credential the integration service holds is PostHog's own (OAuth app secrets,
+ # Every credential the credentials service holds is PostHog's own (OAuth app secrets,
# API keys), never the customer's, and none of its failure states are permanent — a
# burned key gets re-provisioned, an unreachable service comes back. Unlike the skips
# above, this isn't ours to give up on: re-raise wrapped in NonReportableError so the
@@ -124,7 +124,7 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:
# same recovery import_data_sync.py's _handle_import_error already gives the per-schema
# sync path, without minting an error tracking issue per credential read for a platform
# blip the service's own availability alerting already covers.
- if isinstance(e, IntegrationSecretsFailure):
+ if isinstance(e, CredentialsServiceFailure):
if e.reportable:
capture_exception(e)
logger.exception(error_msg)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index b257f0fbc97c..5ae680585a61 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -20,9 +20,9 @@ from jsonpath_ng.exceptions import JsonPathParserError
from parameterized import parameterized
from requests.exceptions import HTTPError, ProxyError
-from posthog.integration_secrets.errors import (
- IntegrationServiceMisconfiguredError,
- IntegrationServiceUnreachableError,
+from posthog.credentials_service.errors import (
+ CredentialsServiceMisconfiguredError,
+ CredentialsServiceUnreachableError,
SecretInRecoveryError,
SecretMissingError,
)
@@ -1506,7 +1506,7 @@ async def test_probe_never_runs_when_not_eligible_or_resetting(overrides: dict[s
source.source_for_pipeline.assert_called_once()
-# Credentials the integration service holds are PostHog's own — the OAuth app secrets and API keys
+# Credentials the credentials service holds are PostHog's own — the OAuth app secrets and API keys
# we own, not anything a customer configured. Every failure state it has is therefore ours, and
# every one of them ends on its own (a key in recovery is re-provisioned, a missing key is added, an
# unreachable service comes back). The classification has to reflect both facts: retry, and never
@@ -1520,11 +1520,11 @@ async def test_probe_never_runs_when_not_eligible_or_resetting(overrides: dict[s
(SecretInRecoveryError("HUBSPOT_APP_CLIENT_SECRET"), False),
(SecretMissingError("HUBSPOT_APP_CLIENT_SECRET"), True),
(SecretMissingError("HUBSPOT_APP_CLIENT_SECRET", disabled_reason="unconfigured"), True),
- (IntegrationServiceMisconfiguredError("INTEGRATION_SERVICE_URL"), True),
- (IntegrationServiceUnreachableError("connection refused"), False),
+ (CredentialsServiceMisconfiguredError("CREDENTIALS_SERVICE_URL"), True),
+ (CredentialsServiceUnreachableError("connection refused"), False),
],
)
-async def test_integration_secret_failure_retries_without_disabling_the_schema(error, reported):
+async def test_credentials_service_failure_retries_without_disabling_the_schema(error, reported):
source = mock.MagicMock(spec=SimpleSource)
source.get_non_retryable_errors.return_value = {}
source.get_retryable_errors.return_value = set()
@@ -1549,7 +1549,7 @@ async def test_integration_secret_failure_retries_without_disabling_the_schema(e
# The customer reads a message that names no internal credential and asks nothing of them.
assert str(exc_info.value) == module.INTEGRATION_CREDENTIAL_UNAVAILABLE_MESSAGE
assert "HUBSPOT_APP_CLIENT_SECRET" not in str(exc_info.value)
- assert "INTEGRATION_SERVICE_URL" not in str(exc_info.value)
+ assert "CREDENTIALS_SERVICE_URL" not in str(exc_info.value)
# Reported only when a person has to act. NonReportableError already keeps the activity
# interceptor from capturing on escape, so an explicit capture is the only way these reach
@@ -1564,12 +1564,12 @@ async def test_integration_secret_failure_retries_without_disabling_the_schema(e
# The bare-404 rule below this branch reads a 404 as "the customer's configured endpoint is gone"
-# and stops the sync for good. A misrouted INTEGRATION_SERVICE_URL answers 404 too, so ordering
+# and stops the sync for good. A misrouted CREDENTIALS_SERVICE_URL answers 404 too, so ordering
# decides whether our own deploy error is charged to the customer. The client wraps its transport
# failures precisely so the two can't collide; this pins the ordering that keeps it true anyway.
@pytest.mark.asyncio
async def test_integration_failure_is_classified_before_the_bare_404_rule():
- error = IntegrationServiceUnreachableError("404 Client Error: Not Found for url: http://integration-service")
+ error = CredentialsServiceUnreachableError("404 Client Error: Not Found for url: http://credentials-service")
source = mock.MagicMock(spec=SimpleSource)
source.get_non_retryable_errors.return_value = {}
source.get_retryable_errors.return_value = set()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py
index cb30b576470c..d9815e1a794f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py
@@ -5,7 +5,7 @@ from unittest import mock
from django.db import OperationalError
-from posthog.integration_secrets.errors import IntegrationServiceUnreachableError, SecretMissingError
+from posthog.credentials_service.errors import CredentialsServiceUnreachableError, SecretMissingError
from posthog.models.integration import UndecryptedIntegrationSecretError
from posthog.temporal.common.errors import NonReportableError
@@ -217,13 +217,13 @@ def test_undecrypted_integration_secret_error_is_skipped():
@pytest.mark.parametrize(
"error,expect_capture",
[
- (IntegrationServiceUnreachableError("connect timeout"), False),
+ (CredentialsServiceUnreachableError("connect timeout"), False),
(SecretMissingError("some_key"), True),
],
ids=["non_reportable_service_unreachable", "reportable_secret_missing"],
)
-def test_integration_secrets_failure_is_retried_and_reported_by_reportable(error, expect_capture):
- # An integration-service failure is never the customer's fault, so discovery must not disable
+def test_credentials_service_failure_is_retried_and_reported_by_reportable(error, expect_capture):
+ # A credentials-service failure is never the customer's fault, so discovery must not disable
# the source (would need `handle_non_retryable_error`) — it must re-raise as NonReportableError
# so the workflow's retry policy picks it back up. `reportable` alone decides whether a person
# hears about it: capturing an unreachable service opens an issue per credential read for what
diff --git a/services/integration-service/.gitignore b/services/credentials-service/.gitignore
similarity index 100%
rename from services/integration-service/.gitignore
rename to services/credentials-service/.gitignore
diff --git a/services/integration-service/.oxlintrc.json b/services/credentials-service/.oxlintrc.json
similarity index 95%
rename from services/integration-service/.oxlintrc.json
rename to services/credentials-service/.oxlintrc.json
index ac6ca60b78df..41205af92a83 100644
--- a/services/integration-service/.oxlintrc.json
+++ b/services/credentials-service/.oxlintrc.json
@@ -26,7 +26,7 @@
"@posthog/*",
"@posthog/**"
],
- "message": "integration-service must not import from the rest of the monorepo \u2014 copy the small piece you need instead"
+ "message": "credentials-service must not import from the rest of the monorepo \u2014 copy the small piece you need instead"
}
]
}
diff --git a/services/integration-service/Dockerfile b/services/credentials-service/Dockerfile
similarity index 73%
rename from services/integration-service/Dockerfile
rename to services/credentials-service/Dockerfile
index 77f87c433150..eac0e094c533 100644
--- a/services/integration-service/Dockerfile
+++ b/services/credentials-service/Dockerfile
@@ -1,10 +1,10 @@
-# PostHog integration-service (Hono / Node.js). Serves the platform integration
+# PostHog credentials-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 .
+# docker build -f services/credentials-service/Dockerfile -t posthog-credentials-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.
@@ -30,16 +30,16 @@ 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
+COPY services/credentials-service/package.json services/credentials-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...
+ pnpm install --frozen-lockfile --ignore-scripts --filter @posthog/credentials-service...
-COPY services/integration-service/ services/integration-service/
-WORKDIR /code/services/integration-service
+COPY services/credentials-service/ services/credentials-service/
+WORKDIR /code/services/credentials-service
RUN pnpm build
#
@@ -52,8 +52,8 @@ WORKDIR /code
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
+COPY --from=build --chown=node:node /code/services/credentials-service/dist/credentials-service.mjs ./credentials-service.mjs
+COPY --from=build --chown=node:node /code/services/credentials-service/dist/credentials-service.mjs.map ./credentials-service.mjs.map
ENV NODE_ENV=production \
PORT=8004
@@ -62,4 +62,4 @@ EXPOSE 8004
USER node
-CMD ["node", "integration-service.mjs"]
+CMD ["node", "credentials-service.mjs"]
diff --git a/services/integration-service/README.md b/services/credentials-service/README.md
similarity index 85%
rename from services/integration-service/README.md
rename to services/credentials-service/README.md
index 40ce99b6e8ea..fd6258a8dc2a 100644
--- a/services/integration-service/README.md
+++ b/services/credentials-service/README.md
@@ -1,4 +1,4 @@
-# integration-service
+# credentials-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
@@ -33,7 +33,7 @@ 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)
+GET /metrics prometheus text, on its own port (CREDENTIALS_SERVICE_METRICS_PORT)
```
**The request scope lives in the JWT and there is no request body.** The token _is_ the request,
@@ -45,7 +45,7 @@ one call needed:
{
"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",
+ "aud": "posthog:credentials_service",
"exp": 1786035932,
}
```
@@ -98,16 +98,16 @@ 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`.
+The same value goes into that deployment's own secret as `CREDENTIALS_SERVICE_JWT_SECRET`.
## Storage and rotation
-**One secret holds everything**: `integration-service-secrets`, a flat map of `KEY: value` pairs.
+**One secret holds everything**: `credentials-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.
-The service reads it from one of two sources, set by `INTEGRATION_SERVICE_SECRET_SOURCE` (`src/source.ts`):
+The service reads it from one of two sources, set by `CREDENTIALS_SERVICE_SECRET_SOURCE` (`src/source.ts`):
- **`kubernetes`**: the service lists the Secret through the API server, then watches it (`src/kubernetes.ts`).
Every replica gets an edit within about a second of ESO writing it.
@@ -126,7 +126,7 @@ The kubernetes source:
- After a normal close, it watches again from the last `resourceVersion` it saw.
- After `410 Gone`, it lists again and watches from the new `resourceVersion`.
- After an error, it reconnects with capped exponential backoff.
-- Every `INTEGRATION_SERVICE_RELOAD_SECONDS`, it lists the Secret again as a safety check.
+- Every `CREDENTIALS_SERVICE_RELOAD_SECONDS`, it lists the Secret again as a safety check.
If the list finds a change that the watch did not deliver, the service applies it and replaces the watch.
- Reads the service account token again for each request, because the projected token rotates.
- Connects straight to `KUBERNETES_SERVICE_HOST:KUBERNETES_SERVICE_PORT`.
@@ -137,15 +137,15 @@ With `resourceNames`, RBAC allows a list or watch only when it carries the field
A pod holding no credentials fails its readiness probe rather than exiting.
So an empty mount, or an API server it cannot reach at boot, recovers on its own instead of crash-looping.
-A source that stops being readable keeps what is already held, with `integration_secret_serving_stale_seconds` as the only sign.
+A source that stops being readable keeps what is already held, with `credentials_service_serving_stale_seconds` as the only sign.
A deleted Secret also keeps what is held: an empty set would answer every resolve all-missing, which callers treat as deleted credentials.
-`integration_secret_watch_restarts_total{reason}` counts watch restarts by why the previous watch ended.
+`credentials_service_watch_restarts_total{reason}` counts watch restarts by why the previous watch ended.
```text
-integration-service-secrets
+credentials-service-secrets
STRIPE_APP_SECRET_KEY = "<credential>"
STRIPE_APP_SECRET_KEY_FALLBACKS = "<staged replacement, only while rotating>"
- INTEGRATION_RECOVERY_KEYS = "<comma-separated key names>"
+ CREDENTIALS_RECOVERY_KEYS = "<comma-separated key names>"
__CALLER_KEY_POSTHOG_DJANGO = "<new>,<old>"
```
@@ -170,7 +170,7 @@ pick it up before completing.
| ---------- | ------------------------------------------------ | ------------------------------------- |
| `steady` | no `_FALLBACKS` sibling, or it repeats the value | `value` only |
| `rotating` | the sibling holds a different, staged value | `value` + `previous` (the staged one) |
-| `recovery` | field named in `INTEGRATION_RECOVERY_KEYS` | no value; caller raises a typed error |
+| `recovery` | field named in `CREDENTIALS_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
@@ -201,18 +201,18 @@ carry it; anything else collapses to a constant, and the `caller` claim is not a
| 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` | source reads that returned nothing |
-| `integration_secret_watch_restarts_total{reason}` | Kubernetes watch restarts, by why the previous watch ended |
-| `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 |
+| `credentials_service_resolve_total{deployment,key,result}` | who read what, and whether it resolved |
+| `credentials_service_last_resolved_timestamp{key}` | which credentials nothing reads any more |
+| `credentials_service_previous_version_served_total{key}` | how much traffic is reading a key mid-rotation |
+| `credentials_service_serving_stale_seconds` | how long this pod has served credentials it could not refresh |
+| `credentials_service_store_errors_total` | source reads that returned nothing |
+| `credentials_service_watch_restarts_total{reason}` | Kubernetes watch restarts, by why the previous watch ended |
+| `credentials_service_signing_keys_last_loaded_timestamp` | staleness means a revocation has not landed on this pod |
+| `credentials_service_signing_key_reload_failures_total` | reloads that kept the previous key set |
+| `credentials_service_auth_failures_total{reason}` | rejected tokens, by why |
+| `credentials_service_http_requests_total{method,route,status}` | request volume, with an unmatched path collapsed to `other` |
+| `credentials_service_http_request_duration_seconds{method,route,status}` | request latency |
+| `credentials_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
@@ -235,30 +235,30 @@ 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
+pnpm --filter @posthog/credentials-service dev # tsx watch, pretty logs
+pnpm --filter @posthog/credentials-service typecheck
+pnpm --filter @posthog/credentials-service test:unit
+pnpm --filter @posthog/credentials-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
+The integration suite boots a real `CredentialsServer` 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
+Point `CREDENTIALS_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_SECRET_SOURCE` | `directory` | `directory` or `kubernetes`; anything else fails boot |
-| `INTEGRATION_SERVICE_SECRETS_DIR` | `/etc/integration-secrets` | Where the Kubernetes Secret is mounted (`directory`) |
-| `INTEGRATION_SERVICE_SECRET_NAME` | `integration-service-secrets` | The Secret to watch (`kubernetes`) |
-| `INTEGRATION_SERVICE_SECRET_NAMESPACE` | the pod's namespace | Read from the service account when unset (`kubernetes`) |
-| `INTEGRATION_SERVICE_RELOAD_SECONDS` | `30` | Re-read interval; a safety re-list next to the watch |
-| `INTEGRATION_SERVICE_METRICS_PORT` | `9090` | Dedicated `/metrics` listener, kept off the ingress |
-| `INTEGRATION_SERVICE_LOG_LEVEL` | by `NODE_ENV` | `debug`, `info`, `warn` or `error` |
+| `CREDENTIALS_SERVICE_ENV` | `dev` | Logical env, recorded on every startup log line |
+| `CREDENTIALS_SERVICE_SECRET_SOURCE` | `directory` | `directory` or `kubernetes`; anything else fails boot |
+| `CREDENTIALS_SERVICE_SECRETS_DIR` | `/etc/credentials-secrets` | Where the Kubernetes Secret is mounted (`directory`) |
+| `CREDENTIALS_SERVICE_SECRET_NAME` | `credentials-service-secrets` | The Secret to watch (`kubernetes`) |
+| `CREDENTIALS_SERVICE_SECRET_NAMESPACE` | the pod's namespace | Read from the service account when unset (`kubernetes`) |
+| `CREDENTIALS_SERVICE_RELOAD_SECONDS` | `30` | Re-read interval; a safety re-list next to the watch |
+| `CREDENTIALS_SERVICE_METRICS_PORT` | `9090` | Dedicated `/metrics` listener, kept off the ingress |
+| `CREDENTIALS_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 |
diff --git a/services/integration-service/package.json b/services/credentials-service/package.json
similarity index 92%
rename from services/integration-service/package.json
rename to services/credentials-service/package.json
index 64beb1225ae0..d1bb3d39b97d 100644
--- a/services/integration-service/package.json
+++ b/services/credentials-service/package.json
@@ -1,7 +1,7 @@
{
- "name": "@posthog/integration-service",
+ "name": "@posthog/credentials-service",
"version": "1.0.0",
- "description": "PostHog integration service — serves platform integration credentials over HTTP",
+ "description": "PostHog credentials service — serves platform integration credentials over HTTP",
"license": "MIT",
"author": "PostHog Inc.",
"type": "module",
diff --git a/services/integration-service/scripts/build.ts b/services/credentials-service/scripts/build.ts
similarity index 89%
rename from services/integration-service/scripts/build.ts
rename to services/credentials-service/scripts/build.ts
index a78453c8c8f0..621ea19709b0 100644
--- a/services/integration-service/scripts/build.ts
+++ b/services/credentials-service/scripts/build.ts
@@ -6,7 +6,7 @@ await build({
platform: 'node',
target: 'node22',
format: 'esm',
- outfile: 'dist/integration-service.mjs',
+ outfile: 'dist/credentials-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/credentials-service/src/auth/jwt.ts
similarity index 100%
rename from services/integration-service/src/auth/jwt.ts
rename to services/credentials-service/src/auth/jwt.ts
diff --git a/services/integration-service/src/auth/registry.ts b/services/credentials-service/src/auth/registry.ts
similarity index 99%
rename from services/integration-service/src/auth/registry.ts
rename to services/credentials-service/src/auth/registry.ts
index f5493ff6845e..380206949fd6 100644
--- a/services/integration-service/src/auth/registry.ts
+++ b/services/credentials-service/src/auth/registry.ts
@@ -1,6 +1,6 @@
// 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.
+// secret as CREDENTIALS_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
diff --git a/services/integration-service/src/auth/types.ts b/services/credentials-service/src/auth/types.ts
similarity index 93%
rename from services/integration-service/src/auth/types.ts
rename to services/credentials-service/src/auth/types.ts
index 9e7dab14bb31..ac15f4fbc95f 100644
--- a/services/integration-service/src/auth/types.ts
+++ b/services/credentials-service/src/auth/types.ts
@@ -1,4 +1,4 @@
-export const AUDIENCE = 'posthog:integration_service'
+export const AUDIENCE = 'posthog:credentials_service'
/** Why a token was rejected. A metric label, so keep the set small and stable. */
export type AuthFailureReason =
diff --git a/services/integration-service/src/http/app.ts b/services/credentials-service/src/http/app.ts
similarity index 100%
rename from services/integration-service/src/http/app.ts
rename to services/credentials-service/src/http/app.ts
diff --git a/services/integration-service/src/index.ts b/services/credentials-service/src/index.ts
similarity index 72%
rename from services/integration-service/src/index.ts
rename to services/credentials-service/src/index.ts
index 59c97faa3d0d..eb5c452cf969 100644
--- a/services/integration-service/src/index.ts
+++ b/services/credentials-service/src/index.ts
@@ -1,9 +1,9 @@
import { loadConfig } from './lib/config'
import { logger } from './lib/logging'
-import { IntegrationServer } from './server'
+import { CredentialsServer } from './server'
async function main(): Promise<void> {
- await new IntegrationServer(loadConfig()).start()
+ await new CredentialsServer(loadConfig()).start()
}
main().catch((err: unknown) => {
diff --git a/services/integration-service/src/kubernetes.ts b/services/credentials-service/src/kubernetes.ts
similarity index 100%
rename from services/integration-service/src/kubernetes.ts
rename to services/credentials-service/src/kubernetes.ts
diff --git a/services/integration-service/src/lib/config.ts b/services/credentials-service/src/lib/config.ts
similarity index 83%
rename from services/integration-service/src/lib/config.ts
rename to services/credentials-service/src/lib/config.ts
index 88b13dc5eefe..76a0feb60992 100644
--- a/services/integration-service/src/lib/config.ts
+++ b/services/credentials-service/src/lib/config.ts
@@ -35,7 +35,7 @@ export interface Config {
mountDir: string
/**
- * Set when INTEGRATION_SERVICE_SECRET_SOURCE is `kubernetes`: the service then reads the
+ * Set when CREDENTIALS_SERVICE_SECRET_SOURCE is `kubernetes`: the service then reads the
* Secret through the API server instead of from `mountDir`.
*/
kubernetes?: KubernetesSourceConfig
@@ -65,14 +65,14 @@ function intFromEnv(key: string, fallback: number, min = 0): number {
}
function secretSourceFromEnv(): SecretSourceKind {
- const raw = process.env.INTEGRATION_SERVICE_SECRET_SOURCE
+ const raw = process.env.CREDENTIALS_SERVICE_SECRET_SOURCE
if (!raw) {
return 'directory'
}
const kind = SECRET_SOURCES.find((source) => source === raw)
if (!kind) {
throw new Error(
- `INTEGRATION_SERVICE_SECRET_SOURCE must be one of ${SECRET_SOURCES.join(', ')}, got ${JSON.stringify(raw)}`
+ `CREDENTIALS_SERVICE_SECRET_SOURCE must be one of ${SECRET_SOURCES.join(', ')}, got ${JSON.stringify(raw)}`
)
}
return kind
@@ -88,25 +88,25 @@ function kubernetesFromEnv(serviceAccountDir: string): KubernetesSourceConfig {
const port = process.env.KUBERNETES_SERVICE_PORT
if (!host || !port) {
throw new Error(
- 'INTEGRATION_SERVICE_SECRET_SOURCE=kubernetes needs KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT'
+ 'CREDENTIALS_SERVICE_SECRET_SOURCE=kubernetes needs KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT'
)
}
if (!/^\d+$/.test(port)) {
throw new Error(`KUBERNETES_SERVICE_PORT must be an integer, got ${JSON.stringify(port)}`)
}
- const secretName = process.env.INTEGRATION_SERVICE_SECRET_NAME || 'integration-service-secrets'
+ const secretName = process.env.CREDENTIALS_SERVICE_SECRET_NAME || 'credentials-service-secrets'
if (!DNS_SUBDOMAIN.test(secretName)) {
- throw new Error(`INTEGRATION_SERVICE_SECRET_NAME is not a valid Secret name: ${JSON.stringify(secretName)}`)
+ throw new Error(`CREDENTIALS_SERVICE_SECRET_NAME is not a valid Secret name: ${JSON.stringify(secretName)}`)
}
- let namespace = process.env.INTEGRATION_SERVICE_SECRET_NAMESPACE
+ let namespace = process.env.CREDENTIALS_SERVICE_SECRET_NAMESPACE
if (!namespace) {
const namespaceFile = join(serviceAccountDir, 'namespace')
try {
namespace = readFileSync(namespaceFile, 'utf8').trim()
} catch {
- throw new Error(`INTEGRATION_SERVICE_SECRET_NAMESPACE is unset and ${namespaceFile} is unreadable`)
+ throw new Error(`CREDENTIALS_SERVICE_SECRET_NAMESPACE is unset and ${namespaceFile} is unreadable`)
}
}
if (!DNS_LABEL.test(namespace)) {
@@ -129,24 +129,24 @@ export function loadConfig(serviceAccountDir = SERVICE_ACCOUNT_DIR): Config {
host: process.env.HOST ?? '0.0.0.0',
shutdownPrestopDelayMs: intFromEnv('SHUTDOWN_PRESTOP_DELAY_MS', 5000),
- env: process.env.INTEGRATION_SERVICE_ENV ?? 'dev',
+ env: process.env.CREDENTIALS_SERVICE_ENV ?? 'dev',
- mountDir: process.env.INTEGRATION_SERVICE_SECRETS_DIR ?? '/etc/integration-secrets',
+ mountDir: process.env.CREDENTIALS_SERVICE_SECRETS_DIR ?? '/etc/credentials-secrets',
// Kubelet syncs a mounted Secret on each node on its own schedule, so for the directory
// source a change lands on different pods up to a minute or more apart whatever this
// is. The kubernetes source gets changes from its watch within about a second.
- reloadSeconds: intFromEnv('INTEGRATION_SERVICE_RELOAD_SECONDS', 30, 1),
+ reloadSeconds: intFromEnv('CREDENTIALS_SERVICE_RELOAD_SECONDS', 30, 1),
- metricsPort: intFromEnv('INTEGRATION_SERVICE_METRICS_PORT', 9090),
+ metricsPort: intFromEnv('CREDENTIALS_SERVICE_METRICS_PORT', 9090),
}
if (secretSourceFromEnv() === 'kubernetes') {
config.kubernetes = kubernetesFromEnv(serviceAccountDir)
}
- if (process.env.NODE_ENV === 'production' && !process.env.INTEGRATION_SERVICE_ENV) {
- throw new Error('missing required configuration: INTEGRATION_SERVICE_ENV')
+ if (process.env.NODE_ENV === 'production' && !process.env.CREDENTIALS_SERVICE_ENV) {
+ throw new Error('missing required configuration: CREDENTIALS_SERVICE_ENV')
}
return config
diff --git a/services/integration-service/src/lib/logging.ts b/services/credentials-service/src/lib/logging.ts
similarity index 95%
rename from services/integration-service/src/lib/logging.ts
rename to services/credentials-service/src/lib/logging.ts
index b6a0d3586fc1..0284e766fb73 100644
--- a/services/integration-service/src/lib/logging.ts
+++ b/services/credentials-service/src/lib/logging.ts
@@ -9,7 +9,7 @@ import pino from 'pino'
type LogLevel = 'debug' | 'info' | 'warn' | 'error'
function resolveLevel(): LogLevel {
- const explicit = process.env.INTEGRATION_SERVICE_LOG_LEVEL?.toLowerCase()
+ const explicit = process.env.CREDENTIALS_SERVICE_LOG_LEVEL?.toLowerCase()
if (explicit === 'debug' || explicit === 'info' || explicit === 'warn' || explicit === 'error') {
return explicit
}
diff --git a/services/integration-service/src/metrics.ts b/services/credentials-service/src/metrics.ts
similarity index 83%
rename from services/integration-service/src/metrics.ts
rename to services/credentials-service/src/metrics.ts
index 9b0ee397e3ae..cce9c5980960 100644
--- a/services/integration-service/src/metrics.ts
+++ b/services/credentials-service/src/metrics.ts
@@ -9,17 +9,17 @@ import type { ResolveOutcome } from './types'
export const register = new Registry()
-collectDefaultMetrics({ register, prefix: 'integration_service_' })
+collectDefaultMetrics({ register, prefix: 'credentials_service_' })
export const resolveTotal = new Counter({
- name: 'integration_secret_resolve_total',
+ name: 'credentials_service_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',
+ name: 'credentials_service_last_resolved_timestamp',
help: 'Unix timestamp of the last successful resolution of a secret',
labelNames: ['key'],
registers: [register],
@@ -28,7 +28,7 @@ export const lastResolvedTimestamp = new Gauge({
// 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',
+ name: 'credentials_service_previous_version_served_total',
// Metric name kept as-is: renaming it would break every dashboard and alert already reading
// it. The help text carries the correction.
help: 'Responses in which a staged, incoming (<KEY>_FALLBACKS) value was included alongside the live one',
@@ -39,13 +39,13 @@ export const previousVersionServedTotal = new Counter({
// An unreadable secret source 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',
+ name: 'credentials_service_serving_stale_seconds',
help: 'Age of the secrets still being served because the secret source could not be re-read (0 when healthy)',
registers: [register],
})
export const mountErrorsTotal = new Counter({
- name: 'integration_secret_store_errors_total',
+ name: 'credentials_service_store_errors_total',
help: 'Reads of the secret source (mount or Kubernetes API) that returned nothing',
registers: [register],
})
@@ -53,21 +53,21 @@ export const mountErrorsTotal = new Counter({
// A watch that restarts often is a source of lag between pods. `stalled` means the safety
// re-fetch found a change the watch never delivered.
export const secretWatchRestartsTotal = new Counter({
- name: 'integration_secret_watch_restarts_total',
+ name: 'credentials_service_watch_restarts_total',
help: 'Restarts of the Kubernetes Secret watch, by why the previous watch ended',
labelNames: ['reason'],
registers: [register],
})
export const httpRequestsTotal = new Counter({
- name: 'integration_service_http_requests_total',
+ name: 'credentials_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',
+ name: 'credentials_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],
@@ -75,7 +75,7 @@ export const httpRequestDurationSeconds = new Histogram({
})
export const authFailuresTotal = new Counter({
- name: 'integration_service_auth_failures_total',
+ name: 'credentials_service_auth_failures_total',
help: 'Rejected requests, by why the token was not accepted',
labelNames: ['reason'],
registers: [register],
@@ -85,19 +85,19 @@ export const authFailuresTotal = new Counter({
// 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',
+ name: 'credentials_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',
+ name: 'credentials_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',
+ name: 'credentials_service_shutting_down',
help: '1 if the service is in the process of shutting down, 0 otherwise',
registers: [register],
})
diff --git a/services/integration-service/src/mount.ts b/services/credentials-service/src/mount.ts
similarity index 99%
rename from services/integration-service/src/mount.ts
rename to services/credentials-service/src/mount.ts
index b1baedfed67b..306a3b520d15 100644
--- a/services/integration-service/src/mount.ts
+++ b/services/credentials-service/src/mount.ts
@@ -21,7 +21,7 @@ import type { Secret, MountedSecrets } from './types'
export const RESERVED_PREFIX = '__'
/** Comma-separated names of the secrets that are in recovery. */
-export const RECOVERY_KEYS = 'INTEGRATION_RECOVERY_KEYS'
+export const RECOVERY_KEYS = 'CREDENTIALS_RECOVERY_KEYS'
/** Suffix holding the staged (incoming) value during a rotation, comma-separated, newest first. */
export const FALLBACK_SUFFIX = '_FALLBACKS'
diff --git a/services/integration-service/src/resolve.ts b/services/credentials-service/src/resolve.ts
similarity index 100%
rename from services/integration-service/src/resolve.ts
rename to services/credentials-service/src/resolve.ts
diff --git a/services/integration-service/src/server.ts b/services/credentials-service/src/server.ts
similarity index 98%
rename from services/integration-service/src/server.ts
rename to services/credentials-service/src/server.ts
index 40ca95aad318..ca921b8f6374 100644
--- a/services/integration-service/src/server.ts
+++ b/services/credentials-service/src/server.ts
@@ -32,7 +32,7 @@ type ServeFn = (
) => DrainableServer
/** Test seams. Production construction passes none of these. */
-export interface IntegrationServerOverrides {
+export interface CredentialsServerOverrides {
serve?: ServeFn
exit?: (code: number) => void
source?: SecretSource
@@ -53,7 +53,7 @@ export function every(intervalMs: number, task: () => Promise<void>): () => void
return () => clearInterval(timer)
}
-export class IntegrationServer {
+export class CredentialsServer {
private readonly lifecycle: Lifecycle = { shuttingDown: false, ready: false }
private server: DrainableServer | undefined
private metricsServer: Server | undefined
@@ -66,7 +66,7 @@ export class IntegrationServer {
constructor(
private readonly config: Config,
- private readonly overrides: IntegrationServerOverrides = {}
+ private readonly overrides: CredentialsServerOverrides = {}
) {}
/** For probes and tests. The object is live; do not mutate it. */
diff --git a/services/integration-service/src/source.ts b/services/credentials-service/src/source.ts
similarity index 100%
rename from services/integration-service/src/source.ts
rename to services/credentials-service/src/source.ts
diff --git a/services/integration-service/src/types.ts b/services/credentials-service/src/types.ts
similarity index 100%
rename from services/integration-service/src/types.ts
rename to services/credentials-service/src/types.ts
diff --git a/services/integration-service/tests/integration/server.e2e.test.ts b/services/credentials-service/tests/integration/server.e2e.test.ts
similarity index 92%
rename from services/integration-service/tests/integration/server.e2e.test.ts
rename to services/credentials-service/tests/integration/server.e2e.test.ts
index 6e8fc3f4c6e9..2456b64a07ef 100644
--- a/services/integration-service/tests/integration/server.e2e.test.ts
+++ b/services/credentials-service/tests/integration/server.e2e.test.ts
@@ -11,7 +11,7 @@ import { describe, expect, it } from 'vitest'
import { AUDIENCE } from '@/auth/types'
import type { Config } from '@/lib/config'
-import { IntegrationServer } from '@/server'
+import { CredentialsServer } from '@/server'
const KEY = 'HUBSPOT_APP_CLIENT_SECRET'
const BURNED_KEY = 'STRIPE_APP_SECRET_KEY'
@@ -48,13 +48,13 @@ function resolve(port: number, token: string): Promise<Response> {
}
async function mountDir(values: Record<string, string>): Promise<string> {
- const dir = await mkdtemp(join(tmpdir(), 'integration-e2e-'))
+ const dir = await mkdtemp(join(tmpdir(), 'credentials-e2e-'))
await Promise.all(Object.entries(values).map(([key, value]) => writeFile(join(dir, key), value)))
return dir
}
interface Booted {
- server: IntegrationServer
+ server: CredentialsServer
port: number
exitCode: () => number | undefined
}
@@ -65,7 +65,7 @@ async function boot(dir: string): Promise<Booted> {
const listening = new Promise<number>((r) => {
announce = r
})
- const server = new IntegrationServer(config(dir), {
+ const server = new CredentialsServer(config(dir), {
serve: (options, listener) =>
serve(options, (info) => {
listener(info)
@@ -79,7 +79,7 @@ async function boot(dir: string): Promise<Booted> {
return { server, port: await listening, exitCode: () => exitCode }
}
-describe('integration server end to end', () => {
+describe('credentials 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.
@@ -119,11 +119,11 @@ describe('integration server end to end', () => {
// the rest of the request still succeeds.
const unknown = await resolve(
port,
- await mint({ signingKey: CALLER_SIGNING_KEY, keys: [KEY, 'NO_SUCH_INTEGRATION_KEY'] })
+ await mint({ signingKey: CALLER_SIGNING_KEY, keys: [KEY, 'NO_SUCH_CREDENTIALS_KEY'] })
)
expect(await unknown.json()).toMatchObject({
secrets: { [KEY]: { value: 'current-value-1' } },
- missing: ['NO_SUCH_INTEGRATION_KEY'],
+ missing: ['NO_SUCH_CREDENTIALS_KEY'],
})
// Start a rotation on the mount; the running server picks it up on reload.
@@ -141,7 +141,7 @@ describe('integration server end to end', () => {
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 writeFile(join(dir, 'CREDENTIALS_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()
@@ -151,7 +151,7 @@ describe('integration server end to end', () => {
// 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}`)
+ const held = join(tmpdir(), `credentials-e2e-moved-${port}`)
await rename(dir, held)
await server.reload()
expect((await resolve(port, token)).status).toBe(200)
@@ -171,7 +171,7 @@ describe('integration server end to end', () => {
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).toContain('credentials_service_http_requests_total')
expect(scrapeBody).not.toContain('current-value-1')
} finally {
await server.stop('SIGTERM')
@@ -183,7 +183,7 @@ describe('integration server end to end', () => {
// 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-'))
+ const dir = await mkdtemp(join(tmpdir(), 'credentials-e2e-empty-'))
try {
await expect(boot(dir)).rejects.toThrow(/no __CALLER_KEY_\* entries/)
} finally {
diff --git a/services/integration-service/tests/unit/app.test.ts b/services/credentials-service/tests/unit/app.test.ts
similarity index 100%
rename from services/integration-service/tests/unit/app.test.ts
rename to services/credentials-service/tests/unit/app.test.ts
diff --git a/services/integration-service/tests/unit/auth.test.ts b/services/credentials-service/tests/unit/auth.test.ts
similarity index 100%
rename from services/integration-service/tests/unit/auth.test.ts
rename to services/credentials-service/tests/unit/auth.test.ts
diff --git a/services/integration-service/tests/unit/config.test.ts b/services/credentials-service/tests/unit/config.test.ts
similarity index 74%
rename from services/integration-service/tests/unit/config.test.ts
rename to services/credentials-service/tests/unit/config.test.ts
index 01c5a0ec4fb0..7971192ad1ed 100644
--- a/services/integration-service/tests/unit/config.test.ts
+++ b/services/credentials-service/tests/unit/config.test.ts
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from 'vitest'
import { loadConfig } from '@/lib/config'
-const VAR = 'INTEGRATION_SERVICE_RELOAD_SECONDS'
+const VAR = 'CREDENTIALS_SERVICE_RELOAD_SECONDS'
describe('loadConfig integers', () => {
afterEach(() => {
@@ -31,7 +31,7 @@ describe('loadConfig integers', () => {
})
describe('loadConfig production guards', () => {
- const PROD_VARS = ['NODE_ENV', 'INTEGRATION_SERVICE_ENV']
+ const PROD_VARS = ['NODE_ENV', 'CREDENTIALS_SERVICE_ENV']
afterEach(() => {
for (const key of PROD_VARS) {
@@ -39,23 +39,23 @@ describe('loadConfig production guards', () => {
}
})
- it('refuses to boot in production without INTEGRATION_SERVICE_ENV', () => {
+ it('refuses to boot in production without CREDENTIALS_SERVICE_ENV', () => {
process.env.NODE_ENV = 'production'
- expect(() => loadConfig()).toThrow('INTEGRATION_SERVICE_ENV')
+ expect(() => loadConfig()).toThrow('CREDENTIALS_SERVICE_ENV')
})
it('boots in production once every required variable is set', () => {
process.env.NODE_ENV = 'production'
- process.env.INTEGRATION_SERVICE_ENV = 'prod-us'
+ process.env.CREDENTIALS_SERVICE_ENV = 'prod-us'
expect(loadConfig().env).toBe('prod-us')
})
})
describe('loadConfig secret source', () => {
const SOURCE_VARS = [
- 'INTEGRATION_SERVICE_SECRET_SOURCE',
- 'INTEGRATION_SERVICE_SECRET_NAME',
- 'INTEGRATION_SERVICE_SECRET_NAMESPACE',
+ 'CREDENTIALS_SERVICE_SECRET_SOURCE',
+ 'CREDENTIALS_SERVICE_SECRET_NAME',
+ 'CREDENTIALS_SERVICE_SECRET_NAMESPACE',
'KUBERNETES_SERVICE_HOST',
'KUBERNETES_SERVICE_PORT',
]
@@ -69,7 +69,7 @@ describe('loadConfig secret source', () => {
})
async function serviceAccountDir(namespace: string | null): Promise<string> {
- const dir = await mkdtemp(join(tmpdir(), 'integration-sa-'))
+ const dir = await mkdtemp(join(tmpdir(), 'credentials-sa-'))
dirs.push(dir)
if (namespace !== null) {
await writeFile(join(dir, 'namespace'), `${namespace}\n`)
@@ -79,24 +79,24 @@ describe('loadConfig secret source', () => {
it.each([
['unset reads the mount directory', {}, undefined],
- ['directory reads the mount directory', { INTEGRATION_SERVICE_SECRET_SOURCE: 'directory' }, undefined],
+ ['directory reads the mount directory', { CREDENTIALS_SERVICE_SECRET_SOURCE: 'directory' }, undefined],
[
'kubernetes reads the service account namespace and the default secret name',
- { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes' },
- { apiUrl: 'https://10.0.0.1:443', namespace: 'from-file', secretName: 'integration-service-secrets' },
+ { CREDENTIALS_SERVICE_SECRET_SOURCE: 'kubernetes' },
+ { apiUrl: 'https://10.0.0.1:443', namespace: 'from-file', secretName: 'credentials-service-secrets' },
],
[
'kubernetes prefers an explicit namespace and secret name',
{
- INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes',
- INTEGRATION_SERVICE_SECRET_NAMESPACE: 'explicit',
- INTEGRATION_SERVICE_SECRET_NAME: 'other-secret',
+ CREDENTIALS_SERVICE_SECRET_SOURCE: 'kubernetes',
+ CREDENTIALS_SERVICE_SECRET_NAMESPACE: 'explicit',
+ CREDENTIALS_SERVICE_SECRET_NAME: 'other-secret',
},
{ namespace: 'explicit', secretName: 'other-secret' },
],
[
'kubernetes brackets an IPv6 service host',
- { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes', KUBERNETES_SERVICE_HOST: 'fd00::1' },
+ { CREDENTIALS_SERVICE_SECRET_SOURCE: 'kubernetes', KUBERNETES_SERVICE_HOST: 'fd00::1' },
{ apiUrl: 'https://[fd00::1]:443' },
],
])('%s', async (_label, env: Record<string, string>, expected) => {
@@ -117,23 +117,23 @@ describe('loadConfig secret source', () => {
})
it.each([
- ['an unknown source', { INTEGRATION_SERVICE_SECRET_SOURCE: 'kube' }, 'INTEGRATION_SERVICE_SECRET_SOURCE', true],
+ ['an unknown source', { CREDENTIALS_SERVICE_SECRET_SOURCE: 'kube' }, 'CREDENTIALS_SERVICE_SECRET_SOURCE', true],
[
'kubernetes outside a cluster',
- { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes', KUBERNETES_SERVICE_HOST: '' },
+ { CREDENTIALS_SERVICE_SECRET_SOURCE: 'kubernetes', KUBERNETES_SERVICE_HOST: '' },
'KUBERNETES_SERVICE_HOST',
true,
],
[
'kubernetes with no namespace anywhere',
- { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes' },
- 'INTEGRATION_SERVICE_SECRET_NAMESPACE',
+ { CREDENTIALS_SERVICE_SECRET_SOURCE: 'kubernetes' },
+ 'CREDENTIALS_SERVICE_SECRET_NAMESPACE',
false,
],
[
'a secret name the API path cannot carry',
- { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes', INTEGRATION_SERVICE_SECRET_NAME: '../configmaps/x' },
- 'INTEGRATION_SERVICE_SECRET_NAME',
+ { CREDENTIALS_SERVICE_SECRET_SOURCE: 'kubernetes', CREDENTIALS_SERVICE_SECRET_NAME: '../configmaps/x' },
+ 'CREDENTIALS_SERVICE_SECRET_NAME',
true,
],
])('refuses to boot with %s', async (_label, env: Record<string, string>, message, namespaceFile) => {
diff --git a/services/integration-service/tests/unit/kubernetes.test.ts b/services/credentials-service/tests/unit/kubernetes.test.ts
similarity index 98%
rename from services/integration-service/tests/unit/kubernetes.test.ts
rename to services/credentials-service/tests/unit/kubernetes.test.ts
index 85f147b66c3e..eb2947f8e385 100644
--- a/services/integration-service/tests/unit/kubernetes.test.ts
+++ b/services/credentials-service/tests/unit/kubernetes.test.ts
@@ -10,11 +10,11 @@ import { AUDIENCE } from '@/auth/types'
import { KubernetesSecretSource } from '@/kubernetes'
import type { Config } from '@/lib/config'
import { mountErrorsTotal, register, secretWatchRestartsTotal, servingStaleSeconds } from '@/metrics'
-import { IntegrationServer } from '@/server'
+import { CredentialsServer } from '@/server'
import type { SecretSnapshot } from '@/source'
const NAMESPACE = 'posthog'
-const SECRET_NAME = 'integration-service-secrets'
+const SECRET_NAME = 'credentials-service-secrets'
const KEY = 'HUBSPOT_APP_CLIENT_SECRET'
const SIGNING_KEY = 'k8s-test-signing-key'
const NEW_SIGNING_KEY = 'k8s-test-signing-key-new'
@@ -138,7 +138,7 @@ async function fakeApi(values: Record<string, string> | null): Promise<{ api: Fa
}
async function tokenFile(token: string): Promise<string> {
- const dir = await mkdtemp(join(tmpdir(), 'integration-k8s-'))
+ const dir = await mkdtemp(join(tmpdir(), 'credentials-k8s-'))
cleanups.push(() => rm(dir, { recursive: true, force: true }))
const file = join(dir, 'token')
await writeFile(file, token)
@@ -363,7 +363,7 @@ describe('kubernetes secret source', () => {
})
})
-describe('integration server on the kubernetes source', () => {
+describe('credentials server on the kubernetes source', () => {
beforeEach(() => {
register.resetMetrics()
})
@@ -390,11 +390,11 @@ describe('integration server on the kubernetes source', () => {
}
async function boot(apiUrl: string): Promise<{
- server: IntegrationServer
+ server: CredentialsServer
resolve: (signingKey: string) => Promise<Response>
}> {
let fetch!: (req: Request) => Response | Promise<Response>
- const server = new IntegrationServer(config(), {
+ const server = new CredentialsServer(config(), {
source: await kubernetesSource(apiUrl),
serve: (options) => {
fetch = options.fetch as typeof fetch
diff --git a/services/integration-service/tests/unit/mount.test.ts b/services/credentials-service/tests/unit/mount.test.ts
similarity index 97%
rename from services/integration-service/tests/unit/mount.test.ts
rename to services/credentials-service/tests/unit/mount.test.ts
index 5a7142f01d08..d457088e1d92 100644
--- a/services/integration-service/tests/unit/mount.test.ts
+++ b/services/credentials-service/tests/unit/mount.test.ts
@@ -18,7 +18,7 @@ afterEach(async () => {
/** 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-'))
+ const dir = await mkdtemp(join(tmpdir(), 'credentials-mount-'))
dirs.push(dir)
await Promise.all(Object.entries(values).map(([key, value]) => writeFile(join(dir, key), value)))
return dir
@@ -57,7 +57,7 @@ describe('reading the mount', () => {
it.each([
['a caller signing key', '__CALLER_KEY_POSTHOG_DJANGO'],
['any other reserved entry', '__SOMETHING_ELSE'],
- ['the recovery list', 'INTEGRATION_RECOVERY_KEYS'],
+ ['the recovery list', 'CREDENTIALS_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' })
@@ -110,7 +110,7 @@ describe('reading the mount', () => {
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',
+ CREDENTIALS_RECOVERY_KEYS: 'HUBSPOT_APP_CLIENT_SECRET',
})
expect(held?.secrets['HUBSPOT_APP_CLIENT_SECRET']?.state).toBe('recovery')
@@ -122,7 +122,7 @@ describe('reading the mount', () => {
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',
+ CREDENTIALS_RECOVERY_KEYS: 'STRIPE_APP_SECRET_KEY, HUBSPOT_APP_CLIENT_SECRET',
})
expect(held?.secrets['STRIPE_APP_SECRET_KEY']?.state).toBe('recovery')
diff --git a/services/integration-service/tests/unit/resolve.test.ts b/services/credentials-service/tests/unit/resolve.test.ts
similarity index 100%
rename from services/integration-service/tests/unit/resolve.test.ts
rename to services/credentials-service/tests/unit/resolve.test.ts
diff --git a/services/integration-service/tests/unit/server.test.ts b/services/credentials-service/tests/unit/server.test.ts
similarity index 94%
rename from services/integration-service/tests/unit/server.test.ts
rename to services/credentials-service/tests/unit/server.test.ts
index 19405497b387..a4cb1ecc92ef 100644
--- a/services/integration-service/tests/unit/server.test.ts
+++ b/services/credentials-service/tests/unit/server.test.ts
@@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { AUDIENCE } from '@/auth/types'
import type { Config } from '@/lib/config'
-import { every, IntegrationServer } from '@/server'
+import { every, CredentialsServer } from '@/server'
const KEY = 'HUBSPOT_APP_CLIENT_SECRET'
const SIGNING_KEY = 'server-test-signing-key'
@@ -18,7 +18,7 @@ afterEach(async () => {
})
async function secretsDir(): Promise<string> {
- const dir = await mkdtemp(join(tmpdir(), 'integration-server-'))
+ const dir = await mkdtemp(join(tmpdir(), 'credentials-server-'))
dirs.push(dir)
await writeFile(join(dir, KEY), 'hunter2-zx9q')
await writeFile(join(dir, '__CALLER_KEY_TEST_DEPLOYMENT'), SIGNING_KEY)
@@ -47,19 +47,19 @@ async function mint(): Promise<string> {
}
interface Started {
- server: IntegrationServer
+ server: CredentialsServer
events: string[]
fetch: (req: Request) => Response | Promise<Response>
exitCode: () => number | undefined
}
-/** Start a real IntegrationServer with a fake listener and a captured exit. */
+/** Start a real CredentialsServer 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), {
+ const server = new CredentialsServer(config(await secretsDir(), prestopDelayMs), {
serve: (options) => {
fetch = options.fetch as Started['fetch']
return {
@@ -77,7 +77,7 @@ async function startServer(prestopDelayMs = 0): Promise<Started> {
return { server, events, fetch, exitCode: () => exitCode }
}
-describe('integration server', () => {
+describe('credentials server', () => {
it('marks itself draining and waits out the prestop delay before draining the server', async () => {
const { server, events, fetch } = await startServer(30)
diff --git a/services/integration-service/tsconfig.json b/services/credentials-service/tsconfig.json
similarity index 100%
rename from services/integration-service/tsconfig.json
rename to services/credentials-service/tsconfig.json
diff --git a/services/integration-service/vitest.config.mts b/services/credentials-service/vitest.config.mts
similarity index 100%
rename from services/integration-service/vitest.config.mts
rename to services/credentials-service/vitest.config.mts