# Authentication, Configuration, and Infrastructure

LLMS index: [llms.txt](https://hummingbird-project.io/llms.txt) | Full content: [llms-full.txt](https://hummingbird-project.io/llms-full.txt)

---

How callers authenticate and authorize, how the service is configured,
and the audit and deployment infrastructure. Part of the
[design decision registry](https://hummingbird-project.io/docs/background/tools/workqueue-service/design-decisions/).

## DDR-18: Agent direction — dumber, not smarter

**Decision**: The hummingbird-agent should become a pure compute engine.
The work queue service is the MR lifecycle orchestrator. The agent never
calls the work queue service; the work queue service calls the agent.

**Context**: HUM-857 proposed adding `create_merge_request` as a new
action in the agent's `actions.py`. This was the wrong direction.

**Alternatives**: (a) Agent gains more actions (push, merge, MR
management). (b) Agent becomes stateless compute; work queue service
orchestrates.

**Rationale**: Option (b). The agent keeps LLM loop, tool registry, and
sandbox — nothing else. Event routing, rate limiting, placeholder notes,
result posting, session management, and all GitLab writes move to the
work queue service. HUM-857 closed as Obsolete.

## DDR-19: Shared database

**Decision**: The work queue service uses the same `events` PostgreSQL
database as hummingbird-status and hummingbird-dashboard.

**Context**: Cross-service joins (e.g. `work_items` JOIN
`gitlab_merge_requests` JOIN `pipelineruns`) are useful for the dashboard.

**Alternatives**: Separate database per service.

**Rationale**: Shared DB with service-specific Alembic migration chains
(`alembic_version_mr_service`). Each service manages its own tables
independently. The migration chain is isolated so one service can evolve
its schema without affecting others.

## DDR-20: Pydantic config over cki-lib/jsonschema

**Decision**: Use Pydantic for config validation. Load config from a
YAML file at startup.

**Context**: Needed structured config for authorization rules and
per-type operational settings. Alternatives: cki-lib config helpers,
jsonschema, or plain dicts.

**Alternatives**: (a) cki-lib — adds a dependency, the service stays
self-contained without it. (b) jsonschema — separate schema file,
no type-safe access. (c) Pydantic — already a dependency (API schemas).

**Rationale**: Option (c). Pydantic provides type-safe attribute access,
defaults, cross-field validators (e.g. mutual exclusivity of groups vs
issuer+claims), and optional JSON Schema export. No new dependencies.

## DDR-21: Claim-based rules (Vault bound_claims pattern)

**Decision**: Authorization rules match on arbitrary JWT claims, not
just `sub`. All claim conditions AND; list values OR.

**Context**: Studied JWT trust/authz config from AWS API Gateway,
HashiCorp Vault, Kubernetes Structured Auth, Istio, Traefik Hub, and
oauth2-proxy. All support matching on arbitrary claims.

**Alternatives**: (a) Subject allowlist — rigid, requires exact `sub`
values. (b) Claim-based matching — flexible, supports `project_path`,
`ref`, `groups`, etc.

**Rationale**: Option (b). Vault's `bound_claims` pattern is proven and
simple. Values are coerced to lowercase strings before comparison to
handle int/string mismatches (GitLab's numeric `project_id`) and
bool/string mismatches (`ref_protected: true`).

## DDR-22: Issuer per rule, audience as claim

**Decision**: `issuer` is the only special field on a token rule — it
determines which JWKS keys to use. All other JWT conditions (including
`aud`) are standard claim matches in the `claims` dict.

**Context**: Considered a separate `jwt.issuers` section and/or treating
`aud` as a first-class field alongside `issuer`.

**Alternatives**: (a) Global `jwt` section with trusted issuers +
separate `rules` section. (b) `aud` as a dedicated field on each rule.
(c) Issuer per rule, audience as a claim.

**Rationale**: Option (c). Keeps each rule self-contained and
self-documenting. The Pydantic validator enforces that every issuer rule
includes `aud` in claims to prevent cross-service token reuse.

## DDR-23: Unified rule model for groups and tokens

**Decision**: A single `rules` list where every rule maps a remote
identity (groups or issuer+claims) to local permissions.

**Context**: The original design had `admin_groups`/`retry_groups`
(local permission → remote groups) alongside `rules` (remote identity →
local permissions) — opposite mapping directions.

**Alternatives**: Keep separate group and token rule formats.

**Rationale**: Unified model. Every rule follows the same structure:
remote identity → local permissions. Pydantic cross-field validators
enforce mutual exclusivity.

## DDR-24: Bearer-only auth with users/~ self-authentication

**Decision**: All API auth uses `Authorization: Bearer` tokens. Opaque
OCP tokens (`sha256~...`) are validated by calling the OCP `users/~`
API with the user's own token (self-authenticating).

**Context**: The oauth-proxy cannot simultaneously forward cookie-session
tokens AND pass through non-OCP Bearer tokens on the same path. The
TokenReview API would be cleaner but requires `system:auth-delegator`
ClusterRoleBinding — a cluster-scoped permission not available on
managed OCP clusters.

**Alternatives**: (a) Trust `X-Forwarded-User` from the proxy on all
paths — injection risk on bypassed paths. (b) TokenReview API —
requires cluster RBAC. (c) `users/~` self-authentication.

**Rationale**: Option (c). No special RBAC needed. The `users/~`
endpoint returns username and groups. Results are cached with a
thread-safe TTL cache (5 minutes). The `/me` endpoint bridges OAuth
cookie sessions to Bearer tokens.

## DDR-25: handled_types as explicit opt-in

**Decision**: `handled_types` declares which work item types this
instance serves. Empty means handle nothing.

**Context**: Different deployments may serve different types from the
same container image. Types carry per-type config (e.g. `gitlab_url`
for MR).

**Alternatives**: (a) Handle all types by default. (b) Explicit opt-in.

**Rationale**: Option (b). Prevents accidental catch-all deployments.
The sweep returns early when `handled_types` is empty — no items stolen
from other instances in a shared-database deployment.

## DDR-26: k8s shorthand skipped when not in-cluster

**Decision**: Rules with `issuer: k8s` are silently skipped when the
in-cluster CA bundle is absent.

**Context**: The K8s OIDC issuer URL varies by cluster and is
auto-detected at runtime. Local development doesn't have a cluster.

**Alternatives**: (a) Error on startup if `k8s` issuer can't be
resolved. (b) Skip silently.

**Rationale**: Option (b). Allows using a production config file for
local development and testing without startup errors.

## DDR-27: OAuth proxy as login-only bridge with /me endpoint and cookie refresh

**Decision**: The oauth-proxy sidecar handles only the OAuth login flow.
API endpoints bypass the proxy. A proxy-protected `/me` endpoint
bridges cookie sessions to Bearer tokens. The proxy must be configured
with `--cookie-refresh=1h` to prevent stale-token failures.

**Context**: The OCP oauth-proxy cannot simultaneously forward
cookie-session tokens AND pass through non-OCP Bearer tokens on the
same path. Protected paths validate Bearer tokens via TokenReview
(requires cluster RBAC we cannot obtain) or reject non-OCP tokens.
Bypassed paths pass all Bearer tokens through but ignore cookies.
Additionally, the OCP access token embedded in the proxy's session
cookie has its own expiry (default 24h), independent of the cookie
lifetime. Without `--cookie-refresh`, the cookie outlives the token,
causing the proxy to forward expired credentials while still reporting
the user as authenticated — the "logged in but not authorized" failure
observed in the hummingbird-dashboard deployment.

**Alternatives**: (a) All paths protected — blocks non-OCP Bearer
tokens. (b) `--openshift-delegate-urls` — requires
`system:auth-delegator` ClusterRoleBinding. (c) App reads proxy cookies
directly — tight coupling to proxy internals. (d) Login-only proxy
with `/me` bridge.

**Rationale**: Option (d). The `/me` endpoint is the only
proxy-protected API path. It reads `X-Forwarded-Access-Token` (set by
the proxy from the cookie session) and returns the OCP access token to
the caller. Subsequent API calls use `Authorization: Bearer sha256~...`
on bypassed paths, where the app validates via the OCP `users/~` API.
`--cookie-refresh=1h` keeps the embedded token fresh. TTL-bounded
caching (5 minutes) on `users/~` results ensures expired-token failures
are never permanent (unlike `@functools.cache` which caches failures
indefinitely).

## DDR-28: Audit log with logging + optional S3 archival

**Decision**: Always log audit entries via Python `logging` at INFO
level, and optionally archive to S3 as gzipped JSON objects when
`WORKQUEUE_SERVICE_AUDIT_S3_BUCKET` is set.

**Context**: Needed an immutable record of state transitions, action
outcomes, and auth decisions for compliance and debugging.

**Alternatives**: (a) Database table — bloats the operational DB with
a different concern. (b) S3-only — no visibility without querying
Athena; loses events if S3 is unreachable.

**Why logging + S3**: Logging to stdout is zero-config and integrates
with existing container log collection for real-time visibility. S3
provides the durable, queryable archive (Athena) for compliance.

**Key design rules**:

- Audit failures never propagate — `write_audit_entry()` catches all
  exceptions and logs them, but never raises.
- S3 keys use `YYYY/MM/DD/HH/MM/` prefix for Athena partitioning.
- `ContentEncoding: gzip` set so S3 API consumers get transparent
  decompression.

**Field conventions**: See [Audit Log Field Conventions](https://hummingbird-project.io/l/workqueue-service#field-conventions)
in the operational documentation.
