Internal Service API

This document describes the Bun monolith’s internal service-to-service HTTP surface: the dedicated private listener, its x-service-secret authentication, and the routes Go calls on it — including POST /api/internal/partner/api-keys/metadata for read-only partner API-key facts.

Overview

The monolith runs two independent HTTP listeners: apps/monolith/src/main.ts starts both with Bun.serve. apps/monolith/src/api-gateway/app.ts serves the public API; apps/monolith/src/api-gateway/internal-app.ts mounts createInternalRoutes on the internal app only.
Internal routes are never mounted on the public router or public app. A request to an internal path on PORT returns 404 even when it carries a valid x-service-secret. On Fly, INTERNAL_PORT itself is reachable through Fly Proxy (flycast, and the public IPv6), so x-service-secret is the only guard there.

Authentication

Every internal route compares the caller’s x-service-secret header against INTERNAL_SERVICE_SECRET with a constant-time comparison (SHA-256 digests compared via timingSafeEqual). A missing, wrong, or different-length secret is rejected before the request body is parsed or any authority read happens.
  • INTERNAL_SERVICE_SECRET must be at least 32 characters; DI refuses to boot without it.
  • Rotation is a coordinated Go/Bun restart (update the secret on both services and restart); there is no two-secret overlap window.

Routes

All paths are absolute (the internal app mounts the routes at /).

Partner test landlords

All test-landlord routes require x-service-secret. Partner IDs must be UUID strings. Migration 0010_partner_test_landlords.sql adds three identity columns to users: The database enforces CHECK (test_landlord = (test_partner_id IS NOT NULL)) and CHECK (test_email_label IS NULL OR test_landlord). Partial unique index uq_users_test_partner_email_label covers (test_partner_id, test_email_label) WHERE test_landlord; null labels may repeat. Synthetic users have reserved, generated landlord+<uuid>@sandbox.invalid emails. Input email labels are trimmed and lowercased, unique only within that partner’s test-landlord namespace. No real account is looked up by a supplied label.

Requests and responses

For B2, test must be boolean when present. Absent or false keeps the existing live path unchanged and ignores partner_id; live creation returns 201 {user_id, created: true}, and an existing live identity returns 200 {user_id, created: false, provisioning_id}. B2 retains its existing {error} envelope: 401 {error: "Unauthorized"}; malformed JSON returns 400 {error: "Invalid request body"}; invalid fields return 400 with Invalid or missing email, Invalid or missing name, Invalid or missing provisioning_id, Invalid test flag, or Invalid or missing partner_id. Unexpected failures follow the internal app’s 500 {error: {code: "INTERNAL_SERVER_ERROR", message: <localized message>}} contract rather than the new routes’ 503 envelope.

Transactions and lock namespaces

Creation and deletion serialize under pg_advisory_xact_lock(hashtext('partner_test_landlord_cap'), hashtext(partner_id)). At most 100 test landlords per partner exist, including standalone users and reset leftovers; an existing label is answered before the cap check. Standalone creation atomically adds one passwordless sandbox account. Simulated claim uses ADR-0072’s bare-landlord-ID lock, pg_advisory_xact_lock(hashtext(user_id)), exactly like real credential linking and Go’s claim path. Neither operation verifies email or sends mail. Deletion cascades user-owned rows and explicitly removes auth_versions (which has no foreign key) in the same transaction. Go’s per-partner lifecycle lock, pg_advisory_xact_lock(hashtext('partner_test_lifecycle'), hashtext(partner_id)), is distinct from Bun’s cap lock. PostgreSQL separates the one-key and two-key lock spaces, and the two namespace keys differ. Bun never takes Go’s lifecycle lock; all these locks are transaction-scoped and release automatically on commit or rollback.

Credential and authentication guards

The credential route refuses a test landlord with 409 {error: "test_landlord"} before password-policy checking, hashing, locking or writing (after validating the request). Test landlords cannot sign in, reset a password (including with a valid reset token and an existing planted credential), trigger authentication mail, or hold any non-sandbox account. Better Auth guards return 403 {code: "TEST_LANDLORD", message: "Test landlords cannot authenticate"}. Real users cannot hold sandbox accounts. The sandbox account has no password and is not a social provider: attempting sandbox social sign-in returns 404 PROVIDER_NOT_FOUND.

POST /api/internal/partner/api-keys/metadata

Authoritative, read-only partner API-key facts for the Go webhook worker. Go consults key state here without holding a raw key and without consuming the partner’s request quota.

Request

partner_id is the UUID-backed rental_partners.id. key_id is an opaque, non-empty Better Auth text identifier — it is not required to be a UUID. The request is validated after authentication and before any partner/key read.

Response (200)

Exactly these six fields, always. permissions preserves the stored string-array actions verbatim with no implied read and no issuance-ceiling rewrite; absent/null stored permissions produce {}. expires_at is a UTC RFC3339/ISO timestamp or null. There is no valid wrapper and no raw token/hash, key prefix/start, quota counter, service-user/reference identity, or arbitrary metadata in the body. A matching key returns its actual facts with 200 even when it is disabled (enabled: false), expired, write-only / read-less, or has no permissions. Go applies eligibility (partner activity, enabled/expiry, enquiries:read, grants, resource scope); Bun reports facts only.

Status and error contract

Ownership is established from the persisted partner service user and the key’s own stored fields: the key’s stored id must equal key_id, configId must be partner, and referenceId must equal the partner’s serviceUserId. Request fields or arbitrary key metadata cannot substitute for these checks. A failed authority read is never disguised as 404, and corrupt required fields are never papered over with an empty/full permission map or a defaulted enabled: true.

Quota and read-only contract

The lookup never calls verifyApiKey, never hashes a raw token, and never touches usage state. Repeated lookups — including against an exhausted-quota key — leave persisted requestCount, remaining, lastRequest, lastRefillAt, and updatedAt unchanged. Every call reads current authority: committed permission/enabled/expiry/ownership changes and deletions are reflected by the next lookup (no caching of successful decisions).

POST /api/internal/api-key/verify

Send {key, config_id} with x-service-secret; config_id: "partner" selects the partner configuration. Successful verification returns 200 {valid: true, ...} with the stored metadata, including metadata.mode. Partner keys require metadata.mode to be exactly test or live, and the stored prefix must equal grp_${mode}_ (grp_test_ or grp_live_). Missing, malformed or invalid mode metadata, legacy modeless grp_ keys, and mismatched prefixes return 401 {valid: false, code: "invalid_api_key"}; there is no default mode. Disabled and expired keys return 401 {valid: false, code: "key_disabled"} and 401 {valid: false, code: "key_expired"} respectively. Missing/wrong service secrets return 401 {error: "Unauthorized"} before parsing. An authority outage returns 503 {valid: false, code: "auth_unavailable"}, never an invalid-key decision.

Privacy and logging

The route returns fixed safe bodies and an explicit six-field projection. Provider exceptions (which may embed key material) are never returned and never logged: the handler logs only the fixed message partner api key metadata lookup failed and answers 503. The internal logging middleware records method, path, status, and timing — it does not log the x-service-secret header or request or response bodies.

Local development

Run the monolith from backend/bun with distinct ports and a local database:
The public listener answers 404 for every internal path; probe the internal route on INTERNAL_PORT only.
  • apps/monolith/src/api-gateway/internal-app.ts — internal Hono app and its logging boundary
  • apps/monolith/src/api-gateway/routes/internal.routes.ts — constant-time secret check and routes
  • apps/monolith/src/main.ts — public PORT + private INTERNAL_PORT servers
  • apps/monolith/src/api-gateway/routes/admin-partner-keys.routes.ts — partner + key ownership conventions
  • packages/auth-adapter/schema.ts — apikey / rental_partners schema
  • apps/monolith/src/services/auth/locked-auth-transaction.ts — transaction helper and advisory-lock namespaces
  • apps/monolith/src/services/auth/test-landlord.ts — synthetic identity creation, labels and cap
  • apps/monolith/src/services/auth/test-landlord-guard.ts — sign-in, reset, mail and account guards
  • apps/monolith/src/services/partner-portal/partner-key-mode.ts — modes and exact partner key prefixes
  • packages/auth-adapter/drizzle/0010_partner_test_landlords.sql — identity columns, CHECKs and label index