Secrets Management

Secrets Management

Huitzo uses a three-tier secrets management system that separates platform-level, pack-level, and user-level secrets. This enables secure handling of API keys and credentials while maintaining proper access boundaries.

Overview

┌─────────────────────────────────────────────────────────────────────┐
│                      Three-Tier Secrets Model                       │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌─────────────────────────────────────────────────────────────┐    │
│  │  TIER 1: Platform Secrets                                   │    │
│  │  Owner: Platform Admin                                      │    │
│  │  Scope: Platform services - no pack-facing SDK API          │    │
│  │  Examples: SENDGRID_API_KEY, ELEVENLABS_API_KEY             │    │
│  │  (LLM provider keys: registry data, set at /admin/llm)      │    │
│  │  Access: no pack-facing API. Consumed internally by         │    │
│  │          ctx.llm / ctx.email / ctx.tts / ctx.telegram       │    │
│  └─────────────────────────────────────────────────────────────┘    │
│                                                                     │
│  ┌─────────────────────────────────────────────────────────────┐    │
│  │  TIER 2: Pack Configuration                                 │    │
│  │  Owner: Pack Developer                                      │    │
│  │  Scope: Single pack                                         │    │
│  │  Examples: Pack-specific settings, feature flags            │    │
│  │  Access: ctx.config.get(...)  [NOT YET AVAILABLE]           │    │
│  └─────────────────────────────────────────────────────────────┘    │
│                                                                     │
│  ┌─────────────────────────────────────────────────────────────┐    │
│  │  TIER 3: User Secrets                                       │    │
│  │  Owner: End User                                            │    │
│  │  Scope: User + Pack                                         │    │
│  │  Examples: User's external API keys                         │    │
│  │  Access: await ctx.secrets.require("FIN_API_KEY")           │    │
│  └─────────────────────────────────────────────────────────────┘    │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Tier Comparison

Aspect Platform Secrets Pack Config User Secrets
Owner Platform admin Pack developer End user
Scope Platform services (packs reach them only indirectly) Single pack User + Pack
Managed By .env / platform config; LLM provider keys at /admin/llm (registry) Pack configuration Hub Integrations page (how)
Examples SendGrid, ElevenLabs, LLM provider keys (registry) Feature flags, thresholds User's CRM API key
Access Method No SDK accessor — consumed inside ctx.llm / ctx.email / ctx.tts / ctx.telegram. ctx.config.get() — not yet available await ctx.secrets.get()
Encryption At rest At rest At rest
Visibility Platform only — nothing in the SDK surfaces them (not a sandbox) Pack developer User only

Tier 1: Platform Secrets

Platform secrets are API keys and credentials managed by the platform administrator. The SDK exposes no accessor for a Tier 1 secret, by design: a pack asks for a capability, and the platform reads the credential itself when it services a ctx.llm, ctx.email, ctx.tts, or ctx.telegram call on the pack's behalf.

There is no ctx.env. Earlier revisions of this page showed ctx.env.require("OPENAI_API_KEY") as the Tier 1 access method. That was wrong in two ways: ctx.env is not implemented (accessing it raises ConfigurationError — see ctx.env), and no environment accessor is planned that would hand platform credentials to pack code. Tier 1 credentials are addressed by capability, never by name.

This is an API-surface contract, not a sandbox

"No SDK accessor" describes the shape of the SDK, not on its own an enforced runtime boundary. The API and worker processes never import a pack, and every call of a pack command (single commands on every surface, pipeline stages, nested ctx.commands calls) runs in a per-execution child process with an env-scrubbed allowlist (ADR-039): no DATABASE_URL, no decrypted platform secret in the child's OWN os.environ. That closes the trivial env-read, not the credential on its own. Where the image ships the sandbox helper (ADR-039 Sandbox UID), the child runs under a separate UID and the parent's /proc/<ppid>/environ is closed to it. Without the helper the child runs under the SAME uid as the parent with no PID-namespace or filesystem separation, so a same-uid adversary recovers the parent's real credentials via /proc/<ppid>/environ (test_same_uid_child_can_read_the_platform_dsn_via_proc_ppid_environ, apps/backend/tests/test_commands_isolation_hub_escape.py) and imports backend/backend.metering directly (shared interpreter and site-packages). Without the helper this is not a confinement boundary; with it, the boundary covers only the parent's credentials, not other tenants or the network.

So: treat installing an untrusted pack as granting it the deployment's platform credentials wherever the sandbox helper is missing, and vet marketplace packs accordingly. Turning this contract into a real boundary anywhere (a distinct uid or PID namespace per execution, or microVM-per-pack execution) is tracked under Isolation Strategy.

Configuration

Platform secrets are ordinary backend environment variables under the HUITZO_ prefix — except LLM provider API keys, which are registry data: stored encrypted (under HUITZO_SECRETS_ENCRYPTION_KEY) on the provider's row and set at /admin/llm (ADR-038 §3.5), never read from the environment. See Configuration Reference → Services for the authoritative list of the environment ones.

# pseudocode — .env / deploy environment, backend-side only.
# The backend reads settings with env_prefix="HUITZO_", so the bare
# (unprefixed) names never bind and are silently ignored.
HUITZO_SENDGRID_API_KEY=<sendgrid key>
HUITZO_ELEVENLABS_API_KEY=<elevenlabs key>

How a Pack Consumes Tier 1

A pack asks for a capability, not a credential. The platform picks the key.

Pack calls Platform reads (Tier 1) Notes
await ctx.llm.complete(...) The provider's platform key in the LLM registry, set at /admin/llm (ADR-038 §3.5) — not an environment variable A tenant BYOK key takes precedence; the platform key is the fallback (see BYOK below).
await ctx.email.send(...) HUITZO_SENDGRID_API_KEY SMTP providers are configured through the integrations registry instead.
await ctx.tts.synthesize(...) HUITZO_ELEVENLABS_API_KEY Unset → the call raises a typed IntegrationError (ADR-029).
await ctx.telegram.send(...) HUITZO_TELEGRAM_BOT_TOKEN
# pseudocode — a pack never names the credential
@command("analyze", namespace="analytics")
async def analyze(args: Args, ctx: Context) -> dict:
    # Pass a profile (not a model name, and never a key); the platform resolves
    # which Tier 1 credential to use.
    response = await ctx.llm.complete(prompt="...", profile="default")
    return {"analysis": response}

If your pack genuinely needs its own credential for a third-party service, that is a Tier 3 user secret (ctx.secrets), not a platform secret.

When to Use Platform Secrets

  • LLM API keys (OpenAI, Anthropic) for all packs
  • Email service keys (SendGrid, Mailgun)
  • Platform-wide external service credentials
  • Services billed at the platform level

Required platform secrets

A handful of platform secrets are not optional — the backend refuses to boot in non-debug mode without them, or the relevant flow fails at request time. Set these in the GitHub Environment that owns each deploy (gh secret set <NAME> --env staging and --env production). Runtime application secrets are provisioned to the environment's host-side secret files/configuration; ADR-032's signed deploy request carries identity and evidence only and rejects runtime configuration in the request. See Production Release Identity — credential scope.

Plan prerequisite. Environments, environment secrets, and deployment-branch policies require GitHub Team or higher on a private organization repository. Huitzo-Inc is on the Free plan as of 2026-08-05, so the --env commands above do not work yet and the environment-scoped credential boundary below is not implementable until the organization upgrades. This is already a non-waivable GATE-2 prerequisite for other reasons (organization runner groups); it also gates every secret in this section.

Variable Format Purpose What breaks if missing
HUITZO_JWT_SECRET_KEY random string, ≥32 chars Signs access/refresh tokens. All authentication.
HUITZO_AUDIT_PEPPER random string, ≥32 chars HMAC pepper for redacted admin audit logs. Backend boot fails (config.py).
HUITZO_SECRETS_ENCRYPTION_KEY 64-char hex (32 bytes) Column-level AES-256-GCM key for every EncryptedString column (e.g. platform_secrets.value_encrypted and the SaaS extension's Stripe customer ids), integration secrets, and the LLM provider API keys stored in the registry (llm_providers.api_key_ciphertext). It also keys the HMAC lookup hashes unless HUITZO_SECRETS_LOOKUP_HASH_KEY is set (key rotation). /api/v1/auth/register raises RuntimeError at request time; backend boot rejects in non-debug mode. Rotation: in place with python -m backend.manage rekey-secrets and HUITZO_SECRETS_ENCRYPTION_KEY_PREVIOUS; see rotating the key. Pin HUITZO_SECRETS_LOOKUP_HASH_KEY to the original key first.
HUITZO_STRIPE_SECRET_KEY sk_test_… / sk_live_… Stripe API access for wallet top-ups and Team billing. Top-up and Team billing calls fail.
HUITZO_STRIPE_WEBHOOK_SECRET whsec_… Verifies the billing webhook signature (POST /api/v1/billing/webhook). Webhook events are rejected.
HUITZO_SENDGRID_API_KEY SendGrid token Sends transactional email (coupon delivery, email verification, password reset, dispute notices). The worker dead-letters each email; nothing is delivered.
HUITZO_SENDGRID_TEMPLATE_COUPON, HUITZO_SENDGRID_TEMPLATE_VERIFY_EMAIL SendGrid template id Optional templates for the coupon delivery and verification emails (configuration). The worker sends a plain text and HTML body.

Generate HUITZO_SECRETS_ENCRYPTION_KEY with:

openssl rand -hex 32

Use the same value in staging and production unless you have a deliberate reason to differ (for example, isolating staging Stripe customers from production-decrypt access). Rotating later is an in-place re-key, see rotating the secrets encryption key.

Production release-control secrets (ADR-032 target)

These control the internal production release workflow; they are not application runtime configuration. The GitHub Team-or-higher plan prerequisite noted above governs this section too: none of the environment storage below — including the policy environment — exists on the Free plan for a private organization repository.

Variable Only permitted storage Purpose
PROD_WEBHOOK_TOKEN Huitzo-Inc/huitzo environment secret on production Constant-time transport gate for every authenticated receiver call; signatures remain mutation authority
PROD_SMOKE_EMAIL same environment Mandatory production smoke login identity
PROD_SMOKE_PASSWORD same environment Mandatory production smoke login credential

There are no repository- or organization-level copies. Any job that references one of these names or a receiver /webhook/ URL declares environment: production. validate, rollback policy, and notify contain neither. Fence nonces are masked and job-local; they are never outputs or artifacts.

Environment-only storage is not sufficient on its own. GitHub delivers environment secrets to any job naming the environment, on whatever ref the run was dispatched from — so an actor with contents: write plus actions: write can push a branch carrying a modified release.yml, dispatch it, and read every credential above. Branch protection on main does not prevent this, because the malicious run never touches main. The control that does is the deployment branches and tags policy on the production and policy environments, which must be set to main only. GATE-2 asserts it per environment with two recorded calls — GET /repos/Huitzo-Inc/huitzo/environments/<name> (expecting protected_branches == false and custom_branch_policies == true) and GET /repos/Huitzo-Inc/huitzo/environments/<name>/deployment-branch-policies (expecting exactly one branch policy named main) — both requiring HTTP 200, where 403/404 is a failure rather than a skip. A null, absent, or partially populated deployment_branch_policy is likewise a failure: that is what GitHub returns for an environment with no branch restriction at all, the default and most permissive state. Set that policy at the same time you create the environment, not afterwards. This is a non-waivable GATE-2 prerequisite; see credential scope.

PROD_SMOKE_EMAIL must name a dedicated non-admin account in a dedicated smoke tenant — no admin or platform-staff role, no billing access, no kill-switch authority, no cross-tenant visibility.

RELEASE_POLICY_APP_ID and RELEASE_POLICY_APP_PRIVATE_KEY are the deliberate exception to the production environment rule — not to environments generally. They mint only a short-lived, read-only policy App token for branch/rules/runner checks. No PAT or GITHUB_TOKEN fallback is permitted.

They are not organization secrets. Held that way, the same branch-dispatch read path applies: any branch in the core repo could read the private key and obtain read access to Administration and self-hosted-runner configuration across huitzo and infra — a precise map of the trust substrate. They live instead in a dedicated policy environment carrying the same main-only deployment-branch policy, and the validate and rollback policy jobs declare environment: policy to read them. Neither job ever declares environment: production, so the credential separation above is preserved while the branch-level read path is closed.


Tier 2: Pack Configuration

Not yet available in this SDK version. Accessing ctx.config raises ConfigurationError at runtime — see ctx.config. This section describes the intended Tier 2 design; until the accessor ships, express per-deployment knobs as command arguments or Tier 3 user secrets.

Pack configuration stores pack-specific settings that developers can adjust per deployment.

Configuration

# pseudocode — planned pack installation configuration
packs:
  "@acme/claims":
    config:
      auto_approve_threshold: 1000
      notification_email: "[email protected]"
      features:
        premium_analytics: true

SDK Access (planned)

# pseudocode — the shape ctx.config will expose once implemented
@command("process", namespace="claims")
async def process(args: Args, ctx: Context) -> dict:
    threshold = ctx.config.get("auto_approve_threshold", default=500)   # NOT YET AVAILABLE
    premium = ctx.config.get("features.premium_analytics", default=False)
    ...

When to Use Pack Configuration

  • Per-deployment thresholds and limits
  • Feature flags
  • Integration endpoints
  • Non-sensitive settings

Tier 3: User Secrets

User secrets are API keys and credentials that end users provide for their own external services.

What "scoped" means

Three independent boundaries apply to every ctx.secrets read, and all must pass:

Boundary Enforced by Effect
Who — tenant + user Postgres RLS on integrations, plus a tenant_id predicate and a user_id IS NULL OR user_id = <caller> visibility filter on every query A pack can only ever reach the calling user's own rows and rows their tenant shares. Another tenant's credentials are unreachable.
What — declared names The declared-secret authorization gate, checked before any query runs A pack can only read secret names its own active manifest declares under secrets.user_required or secrets.user_optional.
Whether — the admin kill-switch A disabled_at IS NULL predicate on every query the read path issues A row an operator disabled is unreadable, and looks to the pack exactly like a row that was never configured.

The second boundary is what makes "scoped to the pack" true rather than aspirational. A tenant-shared row (user_id IS NULL) and a llm_byok row are visible to every pack the user can execute, so without the declared-name check any pack could ask for OPENAI_API_KEY and get it. With the check, a pack that did not declare the name is refused before the lookup happens.

The third boundary closes the admin kill-switch gap: ctx.secrets used to serve rows an operator had disabled — including llm_byok rows that ctx.llm was already correctly refusing — because none of its queries filtered disabled_at. Both paths now agree. See disabled_at enforcement for the invariant and the paths it binds.

Which row a name resolves to is a separate question from all three boundaries, and is fixed by the secrets resolution precedence contract: your own pack-scoped row beats a tenant-shared one, a pack-scoped row beats a global one, and a secret_value row beats a BYOK row. Two rows of equal standing that both hold the same name are a configuration ambiguity and fail the read loudly rather than resolving to whichever the database returned first.

Declared names are read from the pack's own stored manifest at context construction, on every execution route — REST, MCP, the async worker, cron, and pipeline stages (where a stage is authorized against the target pack's declarations, never the calling pack's). The set is a required input with no permissive default, so a route that fails to supply it denies every read.

A denied name is indistinguishable from an unconfigured one. get() and exists() behave exactly as if the secret did not exist; require() raises the same SecretsError. That is deliberate — a distinct "declared but not yours" error would tell a hostile pack which credentials a tenant holds. Denials are logged server-side (secrets.denied_undeclared, with tenant, pack, and requested name) so operators can see probing.

Republish after upgrading. Declared names are read from the stored manifest projection, which only started carrying the secrets: block when this gate shipped. A pack version published before then declares nothing and is denied every secret read until it is republished. The denial log names the pack.

As of v0.3 (Integrations Subsystem v2): Tier-3 secrets are stored in the unified integrations table as Integration(type='secret_value') rows, not the legacy user_secrets table. Migration 025 (a PR-era name from the pre-00NN numbering — no 025 revision exists in today's 0001–0021 chain) preserved the legacy AAD f"{tenant_id}:{user_id}:{pack_id}:{key}" byte-for-byte so existing ciphertexts decrypted unchanged; migration 0021 has since re-encrypted those blobs under f"{tenant_id}:{user_id}:{integration_id}:{key}" (scheme aes_gcm_aad_v2), which unbinds the ciphertext from pack_id and lets that column be re-keyed to the stable Pack.id. The pack-facing API (ctx.secrets) is unchanged throughout. See AAD identity rotation and Pack identity for details.

Declaring User Secrets in Manifest

# huitzo.yaml
pack:
  name: "financial-sync"
  namespace: "finance"

secrets:
  user_required:
    - name: "QUICKBOOKS_API_KEY"
      description: "Your QuickBooks Online API key"
      help_url: "https://developer.intuit.com/app/developer/qbo/docs/get-started"

    - name: "PLAID_CLIENT_ID"
      description: "Your Plaid client ID"
      help_url: "https://dashboard.plaid.com/developers/keys"

    - name: "PLAID_SECRET"
      description: "Your Plaid secret key"
      help_url: "https://dashboard.plaid.com/developers/keys"

  user_optional:
    - name: "PREMIUM_DATA_KEY"
      description: "Optional: Premium financial data provider API key"
      help_url: "https://premium-data.example.com/api"

SDK Access

The secrets API provides three access methods:

Method Behavior Use When
await ctx.secrets.require(name) Returns value or raises SecretsError Secret is mandatory
await ctx.secrets.get(name) Returns value or None Secret is optional
await ctx.secrets.exists(name) Returns bool Checking before conditional logic

All three additionally raise IntegrationError(service="secrets") when the secret is configured but unresolvable — an ambiguous configuration, or a stored value that fails to decrypt. That is a distinct outcome from "not configured", on purpose: see IntegrationError from ctx.secrets.

# pseudocode — accessing secrets in a command

# Require a secret (raises SecretsError if user hasn't configured it)
credential = await ctx.secrets.require("SECRET_NAME")

# Optional secret (returns None if not set)
optional_key = await ctx.secrets.get("OPTIONAL_SECRET_NAME")

# Check existence before branching
if await ctx.secrets.exists("OPTIONAL_SECRET_NAME"):
    # use premium features
    ...
else:
    # use standard features
    ...

# Use the credential to call an external service
result = await external_client.call(credential=credential, ...)

How Users Configure a Secret

A Tier-3 secret is an Integration row of type secret_value (§Tier 3 above). Users create it themselves, in the Hub:

  1. Open Settings → Connections → Manage integrations. (There is no Integrations item in a top nav bar — the other two ways in are the command palette, which lists "Integrations", and the System Monitor's Integrations tab. The Integrations entry in the admin sidebar is a different, cross-tenant oversight console, not this form.)
  2. + Add integration (the button on that page), type Secret value.
  3. Add one key/value row per secret name, using the name the pack declares (PLAID_CLIENT_ID). Resolution is by name: a typo is indistinguishable from an unset secret.
  4. Save. The value is encrypted at rest on write and the API never returns it again.

Scope follows your role, not a form control. The Hub form renders no scope selector and never sends user_id at all, so the same submission resolves two different ways server-side (POST /api/v1/integrations: target_user_id = None if _is_admin(user) else user.user_id):

Creator's role Row the Hub form creates Who resolves it
member their own (user_id set) that member only
admin / owner tenant-shared (user_id IS NULL) every member of the tenant

So an admin following the steps above creates a tenant-shared credential. The form gives no signal before you save; afterwards the detail page you land on labels the row · Tenant-shared and the list marks it shared. An admin who wants a personal-only secret must call the REST API with an explicit user_id: <their-own-id>; the form cannot express it. Conversely a non-admin who explicitly sends user_id: null is not refused — the row is silently narrowed to their own.

Either way the pack still reads only the names it declared — see What "scoped" means.

huitzo secrets is a local developer store, not this. The CLI's huitzo secrets set NAME --value <v> [--pack <pack>] writes to the OS keyring, or failing that a plaintext <pack>.json under ~/.huitzo/secrets/ (%APPDATA%\huitzo\secrets\ on Windows), on the developer's own machine, and says so when it runs. Nothing syncs it to a deployment, so it does not feed ctx.secrets for an installed pack. To configure the secret_value integration a deployed pack reads without leaving a terminal, use huitzo integrations secrets set/remove instead — see huitzo integrations.

Installation Flow

Note: Installing a pack registers it in your tenant's database. Packs are not loaded as persistent processes; commands execute on-demand when invoked. See Resource Lifecycle Management for details.

Installation neither collects secrets nor is blocked on them. Declaring a name under user_required does two things, and neither is an install-time gate:

  1. Authorization — the name enters the pack's read allowlist. A name the manifest does not declare is refused before any lookup. This is the actual boundary; see What "scoped" means.
  2. Documentation — description / help_url tell a human which credential to go get. They are publish-time UX metadata, never authorization inputs.

What actually happens:

Step Behaviour
User installs the pack Succeeds, however many declared secrets are unset
User configures a secret On their own initiative, via Integrations — any time, before or after install
A command reads the secret await ctx.secrets.require("PLAID_CLIENT_ID") — configured ⇒ value; unset ⇒ SecretsError at the point of use; undeclared ⇒ the same SecretsError, deliberately indistinguishable from unset

There is no pack-level pre-flight refusal, by design: secrets.user_required is declared once for the whole pack, not per command, so refusing execution up front would block commands that never read the value. See Required secrets and the missing-secret experience.

Proposed, not implemented. No install-time surface renders a pack's declared secrets to the user for approval, and no error response carries a Configure {name} deep-link — both are tracked as follow-up UX work. Write packs on the assumption that users are never prompted: catch SecretsError and return the guidance yourself (the manifest's help_url is the string worth surfacing).


Bring Your Own Key (BYOK)

Huitzo supports a "Bring Your Own Key" model that allows users to override Platform Secrets with their own credentials. This is primarily used for LLM API keys (e.g., OpenAI, Anthropic) to bypass platform usage limits.

How Precedence Works

Both ctx.llm and ctx.secrets honor a tenant's bring-your-own LLM key, but they resolve it through different paths (issue #527); ctx.secrets' own-before-shared BYOK fallback is ranks 5–6 of the full secrets resolution precedence contract:

  • ctx.llm uses only an llm_byok integration for the routed provider, and only when the ModelRouter resolves to a cloud provider (OpenAI/Anthropic) — local routes use no key. Admin-disabled rows are excluded. When a tenant key is present it is used on the wire; otherwise the platform-managed key is used (and consumes platform quota). A plain secret_value named OPENAI_API_KEY does not feed ctx.llm.
  • ctx.secrets surfaces a tenant's llm_byok rows under the canonical names (OPENAI_API_KEY / ANTHROPIC_API_KEY) as its lowest-precedence fallback — a secret_value row set under the same name wins — and, like ctx.llm, excludes admin-disabled rows.

The tenant key always takes precedence over the platform key for the owning tenant, and a BYOK row works even when the platform-default key is unset. Tenant isolation is enforced at resolution time (Postgres RLS), so one tenant's key is never visible to another.

ctx.llm resolves BYOK automatically

A pack does not implement the resolution itself for LLM calls — it simply calls ctx.llm, and the platform threads the resolved tenant key into the provider request:

# pseudocode — pack code is provider-agnostic; the platform resolves the key.
reply = await ctx.llm.chat(messages=[...], profile="default")
# If the tenant configured an `llm_byok` row for the routed provider, that key
# is on the wire (tenant quota); otherwise the platform key is used.

Conceptually, the platform applies the precedence above before dispatching:

# pseudocode — platform-side resolution (NOT pack code)
key = tenant_byok_key(provider) or platform_key(provider)  # tenant wins

Example: Overriding the OpenAI key

If a user wants to use their own OpenAI subscription (e.g., a fine-tuned model or to avoid platform rate limits): they add an llm_byok integration (provider openai, secret api_key) under their account. From then on every ctx.llm call routed to OpenAI for that tenant uses the BYOK key, with no change to pack code. (A plain secret_value named OPENAI_API_KEY only reaches ctx.secrets, not ctx.llm.)


Security Model

Encryption

All secrets are encrypted at rest:

User provides secret
        │
        ▼
┌──────────────────┐
│ Frontend (HTTPS) │
└────────┬─────────┘
         │ TLS encrypted
         ▼
┌──────────────────┐
│   Huitzo API     │
│  Encrypts with   │
│  per-user key    │
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│   PostgreSQL     │
│  (AES-256-GCM)   │
└──────────────────┘

Access Control

Actor Platform Secrets Pack Config User Secrets
Platform Admin ✅ Read/Write ✅ Read/Write ❌
Pack Developer ❌ ✅ Read/Write ❌
End User ❌ ❌ ✅ Own secrets only
Pack (Runtime) ✅ ✅ ✅ For current user
Other Packs ✅ Platform only ❌ ❌

Logging and Auditing

  • Secrets are NEVER logged - Masked in all logs
  • Access is audited - Who accessed which secret, when
  • Error messages sanitized - No secret values in errors
# Example log output (secret masked)
INFO: Command sync-transactions accessed secret PLAID_CLIENT_ID
DEBUG: HTTP request to api.plaid.com (credentials: <masked>)

Rotation

Users can rotate secrets without reinstalling packs, through either of two paths:

  • Hub (whole-blob replace): open the secret_value integration (Settings → Connections → Manage integrations) and re-enter every key/value row the integration holds, not just the one you are rotating — the form submits the full map.
  • CLI (per-key, no re-entry): huitzo integrations secrets set <INTEGRATION_ID> <KEY> upserts just that key; the rest of the row's keys keep their existing values untouched. See huitzo integrations.

Either way, the next execution reads the new value — resolution happens per read, so nothing is cached across runs.

Saving with any rows present replaces the whole blob. The update path rewrites secrets_encrypted in full from what you submit, so a key you omit is silently deleted, not left alone. (Submitting the edit form with no new rows leaves all existing secrets unchanged — that is the no-op, not a partial update.) A dropped key is especially expensive to diagnose here: by the deliberate no-oracle design above, the pack sees it as identical to "never configured" and to "undeclared", and no secrets.denied_undeclared event fires because the name is declared. Keeping one credential per secret_value integration bounds the blast radius.


Error Handling

SecretsError

Raised when a required secret is missing:

from huitzo_sdk.errors import SecretsError

@command("sync", namespace="finance")
async def sync(args: Args, ctx: Context) -> dict:
    try:
        api_key = await ctx.secrets.require("FINANCIAL_API_KEY")
    except SecretsError as e:
        # Return helpful error message
        return {
            "error": "Missing API key",
            "help": "Add this key on the Integrations page (+ Add integration → Secret value)",
            "secret_name": e.secret_name
        }

IntegrationError from ctx.secrets

A declared secret that exists but cannot be resolved raises IntegrationError(service="secrets") from get(), exists(), and require() alike. Two conditions produce it, both platform-side configuration faults rather than pack bugs:

Condition What the user must do
Ambiguous configuration — two rows of equal precedence rank both hold the requested name Remove or re-scope one of them so exactly one row of a given standing carries the name
Undecryptable value — the stored ciphertext fails AES-GCM/AAD verification (tampering, a key rotated without keeping the old one as HUITZO_SECRETS_ENCRYPTION_KEY_PREVIOUS, a row edited out of band) Re-enter the secret so it is re-encrypted under the current key. To rotate without this, follow rotating the key

Neither condition falls back to a lower-precedence row. A corrupted user-owned credential silently downgrading to a tenant-shared or platform one would be a change of whose credential is on the wire, which is worse than a loud failure. The pack-facing message is deliberately generic and is the same string for both conditions, so a pack cannot tell them apart; the error's details carries {"secret_name": <the name you asked for>} and nothing more. The diagnostic detail (which rows collided, which row failed to decrypt) is server-side only, since row identifiers would hand a pack a partial inventory of credentials it is not authorized to enumerate.

A pack does not normally need to catch this — the fault is the operator's to fix, not the pack's. Catch it only to add context, and never to substitute a different credential.

How the fault reaches a human. Server-side, every occurrence emits a structured audit event carrying tenant, pack, the requested name, and the offending row ids — that is the operator's authoritative signal. What each execution route does with the error itself is specified once, under As implemented; the message text reaches no user, because every route replaces it with the fixed text An integration call failed..

ExternalAPIError

Use when an external API call fails due to invalid credentials:

from huitzo_sdk.errors import ExternalAPIError

@command("fetch-data", namespace="data")
async def fetch_data(args: Args, ctx: Context) -> dict:
    api_key = await ctx.secrets.require("DATA_API_KEY")

    try:
        response = await ctx.http.get(
            "https://api.external.com/data",
            headers={"Authorization": f"Bearer {api_key}"}
        )
    except HTTPError as e:
        if e.status_code == 401:
            raise ExternalAPIError(
                service="external-data",
                message="Invalid API key. Verify it on the Integrations page."
            )
        raise

    return response.json()

Best Practices

For Pack Developers

  1. Minimize required secrets - Only require what's truly necessary

```yaml # ✅ Good: Only essential secrets required secrets: user_required: - name: "API_KEY" description: "Main API key for data access"

# ❌ Avoid: Too many required secrets secrets: user_required: - name: "API_KEY" - name: "API_SECRET" - name: "API_REGION" - name: "API_VERSION" ```

  1. Provide clear descriptions and help URLs

yaml secrets: user_required: - name: "STRIPE_API_KEY" description: "Your Stripe secret API key (starts with sk_)" help_url: "https://dashboard.stripe.com/apikeys"

  1. Use optional secrets for premium features

python if await ctx.secrets.exists("PREMIUM_API_KEY"): # Enable premium features pass else: # Graceful fallback pass

  1. Document which commands use which secrets

```yaml commands: - name: "basic-lookup" description: "Basic data lookup" # Uses: API_KEY only

 - name: "premium-analytics"
   description: "Advanced analytics (requires PREMIUM_API_KEY)"
   # Uses: API_KEY, PREMIUM_API_KEY

```

For Platform Administrators

  1. Use environment variables or secrets manager

```bash # pseudocode # Development export HUITZO_SENDGRID_API_KEY=

# Production (use secrets manager) aws secretsmanager get-secret-value --secret-id huitzo/sendgrid ```

LLM provider keys are the exception: set them at /admin/llm, where they are stored encrypted in the registry, never in the environment.

  1. Rotate secrets regularly

  2. Use separate keys for dev/staging/production

For End Users

  1. Never share secrets - Each user should have their own API keys

  2. Use least-privilege keys - Create API keys with minimal required permissions

  3. Rotate compromised keys immediately

  4. Review which packs have access to your secrets


API Reference

ctx.secrets Methods

class SecretsService:
    def get(self, name: str, default: str | None = None) -> str | None:
        """Get a user secret by name.

        Args:
            name: Secret name (UPPER_SNAKE_CASE)
            default: Value to return if secret not set

        Returns:
            Secret value or default
        """

    def require(self, name: str) -> str:
        """Get a required user secret.

        Args:
            name: Secret name (UPPER_SNAKE_CASE)

        Returns:
            Secret value

        Raises:
            SecretsError: If secret is not set
        """

    def exists(self, name: str) -> bool:
        """Check if a user secret exists.

        Args:
            name: Secret name

        Returns:
            True if secret is set
        """

Error Classes

class SecretsError(HuitzoError):
    """Raised when a required secret is missing."""

    def __init__(self, secret_name: str):
        self.secret_name = secret_name
        super().__init__(f"Missing required secret: {secret_name}")


class ExternalAPIError(HuitzoError):
    """Raised when an external API call fails."""

    def __init__(self, service: str, message: str):
        self.service = service
        super().__init__(f"External API error ({service}): {message}")