# Container Catalog

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

---

Per-distro serverless catalog API for Hummingbird container images.

## Features

- **Image Directory** - Browse all container images with metadata
- **Tag Browser** - View tags, digests, architectures per image
- **Specifications** - Per-architecture OCI config details (env, cmd, user, labels)
- **SBOM** - Per-architecture package lists from SPDX attestations
- **Vulnerabilities** - CVE scanning results via Grype
- **CVE Metrics** - Catalog-wide vulnerability aggregate
- **Provenance** - Source traceability from SLSA attestations
- **Release History** - Timeline of past builds with drill-down
- **Deprecation status** - Stream and release status from OCI labels
- **OpenAPI Spec** - Machine-readable API documentation at /v1/openapi.json
- **Swagger UI** - Interactive API explorer at /v1/docs/
- **External Images** - CVE comparison with external image sources

## Architecture

Rust serverless stack deployed as two isolated per-distro stacks:

- **API Lambda** - DynamoDB pass-through (~10ms response)
- **Sync Lambda** - Incremental DynamoDB sync from SNS Release events (~22 registry calls per release)
- **Index Lambda** (`index-lambda`) - SNS-triggered Syft JSON generation,
  uploads native Syft JSON to S3 for scanner consumption
- **Scan Lambda** (`scan-lambda`) - SQS-triggered CVE scanning via Grype from
  native Syft JSON in S3, per-digest processing with `first_seen` tracking
  and partial batch failure reporting
- **Enqueue Lambda** (`enqueue-lambda`) - Hourly EventBridge-triggered fan-out
  that checks Grype DB for updates and enqueues non-superseded digests to SQS
- **Metrics Lambda** (`metrics-lambda`) - DynamoDB Stream-triggered vulnerability
  aggregate
- **External Release Lambda** (`external-release-lambda`) - Scheduled trigger
  feeding the external sync queue
- **External Sync Lambda** (`external-sync-lambda`) - Registry tag resolution and
  DynamoDB metadata writes for external images
- **External Index Lambda** (`external-index-lambda`) - Syft SBOM generation for
  external images, uploads to S3 for Grype scanning
- **DynamoDB** - Pre-computed JSON items (single-table PK/SK design, Streams: KEYS_ONLY)
- **S3 ScanDataBucket** - Native Syft JSON storage for scanner data (gzipped,
  keyed by `grype/{image}/{digest_hex}.json.gz` for Hummingbird and
  `grype-external/{registry}/{digest_hex}.json.gz` for external images; SPDX
  SBOMs for external images are stored at `sbom-external/{registry}/{digest_hex}.json.gz`)
- **SQS ScanQueue** - Central queue for scan tasks (fed by both `grype/` and
  `grype-external/` S3 event notifications and Enqueue Lambda)
- **CloudFront** - CDN with per-endpoint cache TTLs
- **catalog sync** - Full DynamoDB population from GitLab + Quay.io OCI v2 registry
- **catalog scan** - CLI CVE scanning via Grype; reads native Syft JSON from
  S3 (with `--bucket`) or builds synthetic JSON from DynamoDB SBOMs (fallback)
- **catalog index** - CLI Syft JSON generation for backfilling S3
- **Catalog SPA** - Lit 3 web app served from S3 via CloudFront

### Scanner Architecture

CVE vulnerability data must match direct `grype <image>` scans exactly for all
images. Synthetic Syft JSON (built from stored SBOM packages) cannot reliably
reproduce the native output because Grype relies on metadata fields, artifact
relationships, and deduplication logic that are lost in the SPDX-to-API
roundtrip. Additionally, raw SPDX from the build system contains package bloat
(e.g. Go sub-modules, empty-version entries) that native Syft filters out
when scanning a compiled binary directly.

To guarantee exact-match results, the scanner chain stores native Syft JSON
in S3 rather than DynamoDB: a single image's Syft JSON is typically 1-10 MB
(gzipped to 100 KB - 1 MB), which exceeds DynamoDB's 400 KB item limit. S3
has no per-object size constraint, avoids provisioned throughput costs for
large blobs, and supports event notifications for triggering downstream
scanners. An independent Index Lambda runs `syft <image>` on each new
release and uploads the full output to
`s3://{bucket}/grype/{image}/{hex}.json.gz`. The S3 upload fires an event
notification to SQS, which triggers the Scan Lambda to read the native JSON,
run Grype, and write per-canonical vulnerability data to DynamoDB.

Each syft run extracts image layers into its own temp directory, passed to
the syft child via `TMPDIR` and removed when the run finishes; concurrent
runs never share temp data. Dirs left behind by killed runs are swept before
each new run (age-gated to never touch a possibly-active run).

The scanner chain is intentionally independent of the catalog data chain:
the same SNS Release event triggers both the Sync Lambda (catalog data to
DynamoDB) and the Index Lambda (Syft JSON to S3), with no ordering dependency
between them.

Grype runs with `--by-cve`: some ecosystems (e.g. Go modules) are otherwise
reported using their native GHSA or Go vulnerability DB ID rather than a
CVE. `--by-cve` reports the CVE ID instead wherever grype's own local
vulnerability database has that cross-reference, with no added network
call. An ID with no known CVE anywhere in that database is returned as-is.

Vulnerability components include the source RPM filename from the input SBOM
when available. Consumers can group affected binary RPMs by this value.

### CVE Data Flow

```mermaid
graph TD
    subgraph Hummingbird
        Konflux([Konflux Release])
        Konflux -->|SNS| Index[IndexFunction]
        Index -->|upload| S3Syft[(S3 grype/)]
        Konflux -->|SNS| Sync[SyncFunction]
        Sync -->|update| Tags[(Tags)]
    end

    subgraph External Images
        ExtSchedule([Schedule 6h]) -->|invoke| ExtRelease[ExternalReleaseFunction]
        ExtRelease -->|"per registry via SQS"| ExtSync[ExternalSyncFunction]
        ExtSync -->|"per-tag release events via SQS"| ExtIndex[ExternalIndexFunction]
        ExtIndex -->|upload| S3Ext[(S3 grype-external/)]
        ExtSync -->|update| ExtTags[(External Tags)]
    end

    Tags -->|read| Scan[ScanFunction]
    ExtTags -->|read| Scan
    S3Syft -->|"S3 event via SQS"| Scan
    S3Ext -->|"S3 event via SQS"| Scan
    Hourly([Schedule 1h]) -->|invoke| Enqueue[EnqueueFunction]
    Enqueue --> Gate[check Grype DB]
    Gate -->|"fan out via SQS"| Scan
    Scan -->|update| Vulns[(Vulnerabilities)]
    Vulns -->|"stream via ESM"| Metrics[MetricsFunction]
    Tags -->|"stream via ESM"| Metrics
    Metrics -->|"write aggregate"| CatalogVulns[(Catalog Vulnerabilities)]

    classDef lambda fill:#d4e6f1,stroke:#2980b9
    classDef dynamo fill:#fdebd0,stroke:#e67e22
    classDef trigger fill:#d5f5e3,stroke:#27ae60
    classDef gate fill:#e5e7e9,stroke:#7f8c8d
    class Sync,Scan,Enqueue,Metrics,Index,ExtRelease,ExtSync,ExtIndex lambda
    class Vulns,Tags,ExtTags,CatalogVulns,S3Syft,S3Ext dynamo
    class Konflux,Hourly,ExtSchedule trigger
    class Gate gate
```

## Prerequisites

- Rust 1.75+ (for building backend)
- Node.js 22+ (for building frontend)
- AWS credentials (for DynamoDB access and deployment)
- SAM CLI (for deployment)

## API Endpoints

Both namespaces share the same response types and URL structure. The
Hummingbird prefix is `/v1/images/{name}`, the external prefix is
`/v1/external-images/{name}` where `{name}` is a percent-encoded registry
reference (e.g. `docker.io%2Flibrary%2Fnginx`). DynamoDB partition keys are
`IMAGE#{name}` and `EXTERNAL#{registry}` respectively.

| Suffix                                   | Response type                    | HB  | Ext |
| ---------------------------------------- | -------------------------------- | --- | --- |
| _(directory)_                            | `DirectoryResponse`              | ✅  | ✅  |
| _(config)_                               | `ExternalImagesConfig`           |     | ✅  |
| `/{…}`                                   | `ImageResponse`                  | ✅  | ✅  |
| `/{…}/tags`                              | `TagsResponse`                   | ✅  | ✅  |
| `/{…}/details/{canonical}`               | `DetailsResponse`                | ✅  | ✅  |
| `/{…}/sbom/{canonical}`                  | `SbomResponse`                   | ✅  | ✅  |
| `/{…}/vulnerabilities/{canonical}`       | `VulnerabilitiesResponse`        | ✅  | ✅  |
| `/{…}/history/{stream}/{variant}`        | `HistoryResponse`                | ✅  | ✅  |
| `/{…}/releases/details/{digest}`         | `DetailsResponse`                | ✅  | ✅  |
| `/{…}/releases/sbom/{digest}`            | `SbomResponse`                   | ✅  | ✅  |
| `/{…}/releases/vulnerabilities/{digest}` | `VulnerabilitiesResponse`        | ✅  | ✅  |
| `/v1/vulnerabilities`                    | `CatalogVulnerabilitiesResponse` | ✅  |     |

`GET /v1/openapi.json` and `GET /v1/docs/` serve the OpenAPI 3.1 spec and
Swagger UI for all endpoints.

### Response types

#### `DirectoryResponse`

Catalog-level image listing with aggregate statistics. Used for both
Hummingbird (`CATALOG/DIRECTORY`) and external (`CATALOG/EXTERNAL_DIRECTORY`)
image directories.

| Field                  | Type             | Description                                  |
| ---------------------- | ---------------- | -------------------------------------------- |
| `images`               | `ImageSummary[]` | All images in the catalog                    |
| `image_count`          | `u32`            | Total number of images                       |
| `variant_count`        | `u32`            | Total unique variant names across all images |
| `stream_variant_count` | `u32`            | Total published (stream, variant) pairs      |
| `stream_count`         | `u32`            | Total version streams across all images      |
| `tag_count`            | `u32`            | Total tags across all images                 |
| `release_count`        | `u32`            | Total releases across all images             |

#### `ImageSummary`

Per-image summary used in both directory listings and as the base of
`ImageResponse`.

| Field                  | Type                   | Hummingbird                                                 | External                                                    |
| ---------------------- | ---------------------- | ----------------------------------------------------------- | ----------------------------------------------------------- |
| `name`                 | `String`               | Image name (e.g. `python`)                                  | Registry reference (e.g. `docker.io/library/nginx`)         |
| `summary`              | `String`               | From `summary` OCI label                                    | Omitted — no OCI labels available from upstream registries  |
| `application_category` | `String`               | From `io.hummingbird-project.application-category` label    | Omitted — Hummingbird-specific label                        |
| `description`          | `String`               | From `org.opencontainers.image.description` label or README | Omitted — no README available from upstream registries      |
| `latest_tag`           | `String`               | Most recent canonical tag                                   | Same                                                        |
| `pull_url`             | `String`               | `quay.io/…/{name}:latest`                                   | `{registry}:{latest_tag}`                                   |
| `oldest_created`       | `String?`              | Earliest OCI `created` timestamp                            | Same                                                        |
| `architectures`        | `String[]`             | From OCI manifest list                                      | Same                                                        |
| `variants`             | `VariantDescription[]` | From containers repo                                        | From config                                                 |
| `stream_variant_count` | `u32`                  | Computed from tags                                          | Same                                                        |
| `streams`              | `String[]`             | From containers repo directory names                        | From config                                                 |
| `deprecated_streams`   | `String[]`             | Streams with `deprecated=true` label                        | Always `[]` — external images have no deprecation mechanism |
| `tag_count`            | `u32`                  | Number of tags                                              | Same                                                        |
| `release_count`        | `u32`                  | Sum of history entries                                      | Same                                                        |

#### `ImageResponse`

Full image detail — flattens `ImageSummary` into the top level with
additional fields.

| Field                         | Type       | Hummingbird                        | External                                       |
| ----------------------------- | ---------- | ---------------------------------- | ---------------------------------------------- |
| _(all `ImageSummary` fields)_ |            | _(see above)_                      | _(see above)_                                  |
| `readme_html`                 | `String`   | README rendered as HTML            | Omitted — no README available from upstream    |
| `licenses`                    | `String[]` | SPDX identifiers from image labels | Omitted — no license labels on upstream images |

#### `TagsResponse`

| Field      | Type                   | Description                           |
| ---------- | ---------------------- | ------------------------------------- |
| `tags`     | `Tag[]`                | Tags ordered by `oldest_created` desc |
| `variants` | `VariantDescription[]` | Available variant descriptions        |

#### `Tag`

| Field            | Type            | Hummingbird                              | External                                                      |
| ---------------- | --------------- | ---------------------------------------- | ------------------------------------------------------------- |
| `name`           | `String`        | Tag name (e.g. `3.14.2`)                 | Same                                                          |
| `canonical`      | `String`        | Most specific tag for this release       | Same (by semver specificity)                                  |
| `variant`        | `String`        | From containers repo                     | From config                                                   |
| `pull_url`       | `String`        | `quay.io/…:{tag}`                        | `{registry}:{tag}`                                            |
| `digest`         | `String`        | Manifest list digest                     | Same                                                          |
| `sizes`          | `{arch: bytes}` | Compressed layer sizes from OCI manifest | Same                                                          |
| `architectures`  | `String[]`      | From OCI manifest list                   | Same                                                          |
| `oldest_created` | `String?`       | Earliest OCI `created` timestamp         | Same                                                          |
| `stream`         | `String`        | From containers repo directory name      | From config                                                   |
| `deprecated`     | `bool`          | From `deprecated=true` OCI label         | Always `false` — no deprecation mechanism for external images |
| `superseded`     | `bool`          | Computed by `mark_superseded`            | Same                                                          |

#### `DetailsResponse` / `ArchDetails`

Per-architecture OCI container configuration keyed by architecture name
(e.g. `{"amd64": {...}, "arm64": {...}}`).

| Field           | Type           | Hummingbird           | External                                            |
| --------------- | -------------- | --------------------- | --------------------------------------------------- |
| `user`          | `String`       | From OCI config       | Same                                                |
| `env`           | `{key: value}` | From OCI config       | Same                                                |
| `entrypoint`    | `String[]`     | From OCI config       | Same                                                |
| `cmd`           | `String[]`     | From OCI config       | Same                                                |
| `exposed_ports` | `String[]`     | From OCI config       | Same                                                |
| `volumes`       | `String[]`     | From OCI config       | Same                                                |
| `working_dir`   | `String`       | From OCI config       | Same                                                |
| `stop_signal`   | `String`       | From OCI config       | Same                                                |
| `labels`        | `{key: value}` | From OCI config       | Same                                                |
| `created`       | `String?`      | From OCI config root  | Same                                                |
| `source_repo`   | `String`       | From SLSA attestation | Omitted — no signed attestations on upstream images |
| `source_commit` | `String`       | From SLSA attestation | Omitted — no signed attestations on upstream images |
| `containerfile` | `String`       | From SLSA attestation | Omitted — no signed attestations on upstream images |
| `slsa_level`    | `String`       | From SLSA attestation | Omitted — no signed attestations on upstream images |
| `build_system`  | `String`       | From SLSA attestation | Omitted — no signed attestations on upstream images |

#### `SbomResponse` / `ArchSbom`

Per-architecture package list keyed by architecture name.

| Field           | Type            | Hummingbird             | External                                                                 |
| --------------- | --------------- | ----------------------- | ------------------------------------------------------------------------ |
| `runtime_count` | `u32`           | From Syft               | Same                                                                     |
| `build_count`   | `u32`           | From Hermeto            | Always `0` — Hermeto is a Konflux-specific build tool                    |
| `source_count`  | `u32`           | From Hermeto (arch=src) | Always `0` — Hermeto is a Konflux-specific build tool                    |
| `packages`      | `SbomPackage[]` | All architectures       | All known architectures — one `ArchSbom` per arch from the manifest list |

#### `HistoryResponse` / `HistorySummary`

Release timeline for a specific (stream, variant) combination.

| Field            | Type       | Hummingbird            | External                                            |
| ---------------- | ---------- | ---------------------- | --------------------------------------------------- |
| `digest`         | `String`   | Manifest list digest   | Same                                                |
| `oldest_created` | `String`   | Earliest OCI `created` | Same                                                |
| `architectures`  | `String[]` | From OCI manifest list | Same                                                |
| `source_commit`  | `String`   | From SLSA attestation  | Omitted — no signed attestations on upstream images |
| `source_repo`    | `String`   | From SLSA attestation  | Omitted — no signed attestations on upstream images |

#### `VulnerabilitiesResponse`

Vulnerability scan results are identical in structure. The only behavioral
difference: `ignore_list` (CPE-based false-positive suppression) is populated
for Hummingbird images but empty for external images, since suppression rules
are maintained per Hummingbird image.

## Timestamp Fields

The `oldest_created` field on `ImageSummary`, `Tag`, and `HistorySummary` is
the earliest OCI `created` timestamp across all architectures in the release.
All architectures were built at or after this date, making it useful for
conservative staleness detection.

The specifications endpoint returns per-architecture data keyed by architecture
name. Each architecture's `created` field is the direct OCI config root
timestamp for that specific architecture.

## Deprecation status

The containers repository can mark an image stream with the
`io.hummingbird-project.deprecated=true` OCI label. The catalog exposes this
status in two places:

- `Tag.deprecated` identifies a release carrying the label.
- `ImageSummary.deprecated_streams` lists streams whose current release is
  deprecated.

Both fields are additive API fields. Older DynamoDB items without these fields
are read as active releases with no deprecated streams.

## Usage

All tools are built as a single `catalog` binary with subcommands (`api`,
`sync`, `sync-lambda`, `scan`, `scan-lambda`, `index`, `index-lambda`,
`enqueue-lambda`, `metrics`, `metrics-lambda`). The binary is built in the
Rust container and CLI subcommands are run in the gitlab-ci container (which
provides grype, syft, and other tools). Only `make` and `podman` are required.

### Sync

```bash
# Dry run (print items to stdout)
make container-catalog/sync ARGS="--distro rawhide --dry-run"

# Populate DynamoDB
make container-catalog/sync ARGS="--distro rawhide --table-name <table>"
```

### Sync Lambda

The `sync-lambda` subcommand runs as an AWS Lambda function triggered by SNS
Release events from [kubernetes-event-forwarder](https://hummingbird-project.io/docs/background/tools/kubernetes-event-forwarder/).
It incrementally syncs a single image release to DynamoDB (~22 registry API
calls per release vs ~104 for a full sync).

The Lambda:

1. Decodes gzip+base64 SNS messages
2. Filters for Succeeded releases targeting the configured Quay.io namespace.
   Ignores `DELETED` events and releases with a non-null `deletionTimestamp`.
3. Fetches OCI manifest data for the new digest
4. Writes per-digest items (DETAILS, SBOM, RELEASE_DETAILS, RELEASE_SBOM)
5. Merges into aggregate items (TAGS, HISTORY, OVERVIEW, DIRECTORY)
6. Fetches README from GitLab for OVERVIEW content (uses `README.md` for
   Hummingbird, `rawhide/README.md` for Rawhide)

Registry fetch errors (manifest, SBOM, attestation) propagate as hard failures
so the Lambda retries automatically (up to 2 retries with backoff) before
sending to the DLQ. GitLab README failures are non-fatal -- the existing README
is preserved if the fetch fails.

| Environment Variable | Description                            |
| -------------------- | -------------------------------------- |
| `TABLE_NAME`         | DynamoDB table name                    |
| `DISTRO`             | `rawhide` or `hummingbird`             |
| `SENTRY_DSN`         | Optional Sentry DSN for error tracking |

### Index

The index subcommand generates native Syft JSON for all non-superseded image
digests and uploads them to S3 for scanner consumption. It reads the image
directory and TAGS from DynamoDB, checks S3 for existing objects (dedup via
HeadObject), runs `syft <image> --platform linux/amd64`, gzips the output,
and uploads to `s3://{bucket}/grype/{image}/{hex}.json.gz`.

```bash
# Dry run (show what would be uploaded)
make container-catalog/index ARGS="--distro hummingbird --table-name <table> --bucket <bucket> --dry-run"

# Backfill S3 for all images
make container-catalog/index ARGS="--distro hummingbird --table-name <table> --bucket <bucket>"

# Backfill a single image
make container-catalog/index ARGS="--distro hummingbird --table-name <table> --bucket <bucket> --image caddy"
```

### Index Lambda

The `index-lambda` subcommand runs as an AWS Lambda function triggered by the
same SNS Release events as the Sync Lambda. It operates independently of the
catalog chain (no DynamoDB access) and generates native Syft JSON for scanner
consumption.

The Lambda:

1. Decodes gzip+base64 SNS messages (shared with Sync Lambda via `release_event` module)
2. Filters for Succeeded releases targeting the configured Quay.io namespace.
   Ignores `DELETED` events and releases with a non-null `deletionTimestamp`.
3. Checks S3 for existing objects (HeadObject dedup by digest)
4. Runs `syft <image>@<digest> --platform linux/amd64 --output syft-json`
5. Gzips and uploads to `s3://{bucket}/grype/{image}/{hex}.json.gz`

Failures propagate for Lambda retry (up to 2 retries) before sending to the
IndexDLQ. The `catalog index` CLI backfills any gaps.

| Environment Variable | Description                            |
| -------------------- | -------------------------------------- |
| `SCAN_DATA_BUCKET`   | S3 bucket for scanner data             |
| `DISTRO`             | `rawhide` or `hummingbird`             |
| `SENTRY_DSN`         | Optional Sentry DSN for error tracking |

### Scan

The scan subcommand reads image listings, tags, and SBOMs from DynamoDB
(no registry access needed) and runs Grype against each image's stored SBOM
packages. Results include a `first_seen` timestamp per CVE, tracked at the
group+variant+stream level and carried across releases for SLI computation.

```bash
# Dry run (print items to stdout)
make container-catalog/scan ARGS="--distro hummingbird --table-name <table> --dry-run"

# Scan and write to DynamoDB (purge stale vuln data first, implies --scope=all)
make container-catalog/scan ARGS="--distro hummingbird --table-name <table> --purge"

# Scan only non-superseded (current) tags
make container-catalog/scan ARGS="--distro hummingbird --table-name <table> --scope non-superseded"

# Scan all releases including historic (tagless) releases
make container-catalog/scan ARGS="--distro hummingbird --table-name <table> --scope all"

# Scan a single image
make container-catalog/scan ARGS="--distro hummingbird --table-name <table> --image caddy --dry-run"
```

### Scan Lambda

The `scan-lambda` subcommand runs as an AWS Lambda function triggered by SQS
messages. Two paths feed the ScanQueue for Hummingbird images, and two
parallel paths for external images:

1. **Real-time** (S3 event notification): When the Index Lambda uploads a new
   Syft JSON to S3, an `s3:ObjectCreated` event (filtered on `grype/` prefix)
   is sent directly to SQS
2. **Hourly** (Enqueue Lambda): Fans out all non-superseded digests when the
   Grype vulnerability database has been updated, sending
   `{"bucket": "...", "key": "grype/{image}/{hex}.json.gz"}` messages
3. **External real-time**: When the External Index Lambda uploads Syft JSON
   to `grype-external/{registry}/{hex}.json.gz`, the same ScanQueue
   receives the event
4. **External hourly**: The Enqueue Lambda also fans out external re-scans
   using `grype-external/{registry}/{hex}.json.gz` keys

The Lambda accepts both S3 event notification JSON and direct
`{"bucket", "key"}` messages. It detects the S3 key prefix to dispatch
between two code paths:

- `grype/` prefix → Hummingbird path: writes `IMAGE#{name}/VULNERABILITIES#{canonical}` and
  `IMAGE#{name}/RELEASE_VULNERABILITIES#{hex}`
- `grype-external/` prefix → external path: parses `(registry, hex)` from the key,
  then writes `EXTERNAL#{registry}/VULNERABILITIES#{canonical}` and
  `EXTERNAL#{registry}/RELEASE_VULNERABILITIES#{hex}` using the same Grype scan and
  `first_seen` tracking logic as Hummingbird

For each message the Lambda:

1. Downloads and decompresses the native Syft JSON from S3
2. Runs Grype on the raw bytes
3. Looks up all canonical tags matching the digest from the TAGS item
4. Writes `VULNERABILITIES#{canonical}` for each matching tag (with
   `first_seen` tracking) and `RELEASE_VULNERABILITIES#{hex}` once per digest

Processing is per-digest: a single Syft JSON serves all canonicals sharing
that digest, avoiding redundant Grype invocations.

The Lambda downloads and hydrates the Grype DB on the first handler invocation
of each cold start (cached in `/tmp` for warm invocations), processes one
message per batch, and reports partial batch failures so failed records return
to the queue.

Concurrency is capped at 100 concurrent invocations (`ScalingConfig` on the
SQS event source). Every Grype DB update triggers a full-catalog rescan
fan-out of several hundred scans, and without a cap the event source scales
with that backlog — measured at ~490 concurrent executions, about half the
account's shared 1000-execution limit, with each cold container downloading
the multi-GB Grype DB. The cap keeps one function at ~10% of the account
budget and amortizes the DB setup across warm invocations. The template
deploys to both the hummingbird and rawhide stacks, so the theoretical
simultaneous maximum is 2 × 100 from the scan Lambdas plus 2 × 5 from the
external index Lambdas — 210 of the account limit.

| Environment Variable | Description                            |
| -------------------- | -------------------------------------- |
| `TABLE_NAME`         | DynamoDB table name                    |
| `DISTRO`             | `rawhide` or `hummingbird`             |
| `SENTRY_DSN`         | Optional Sentry DSN for error tracking |

### Enqueue Lambda

The `enqueue-lambda` subcommand runs hourly via EventBridge Schedule. On each
invocation it performs a lightweight HTTP GET of the public Grype DB listing
(`latest.json`, ~200 bytes) and compares the `built` timestamp against the
stored `CATALOG/LAST_FULL_SCAN_DB` item in DynamoDB. If the DB hasn't changed,
it returns early (~23 of 24 hourly invocations short-circuit). When an update
is detected it runs two fan-out loops:

1. **Hummingbird images**: reads the image directory and all TAGS items,
   deduplicates by digest, and sends one SQS message per unique digest.
   Messages use `{"bucket": "...", "key": "grype/{image}/{hex}.json.gz"}`.
2. **External images**: reads the external-images config from DynamoDB
   (`CATALOG/EXTERNAL_CONFIG`), then for each configured registry reads
   `EXTERNAL#{registry}/TAGS` and fans out non-superseded digests with
   `grype-external/{registry}/{hex}.json.gz` keys. If no TAGS item exists
   (first run, before External Sync Lambda), the registry is skipped.
   A malformed or missing `EXTERNAL_CONFIG` degrades gracefully — a warning
   is logged and the Hummingbird fan-out already sent is unaffected.

Both loops use the same `SendMessageBatch` batching and `!superseded` digest
filter.

| Environment Variable  | Description                                 |
| --------------------- | ------------------------------------------- |
| `TABLE_NAME`          | DynamoDB table name                         |
| `DISTRO`              | `rawhide` or `hummingbird`                  |
| `SCAN_QUEUE_URL`      | SQS queue URL for scan messages             |
| `SCAN_DATA_BUCKET`    | S3 bucket for scanner data                  |
| `GRYPE_DB_LATEST_URL` | Grype DB listing URL (has sensible default) |
| `SENTRY_DSN`          | Optional Sentry DSN for error tracking      |

### Metrics

The `metrics` subcommand performs a one-shot read of all non-superseded
vulnerability data from DynamoDB and writes the catalog-wide vulnerability
aggregate to DynamoDB (`PK=CATALOG, SK=VULNERABILITIES`).

```bash
make container-catalog/metrics ARGS="--table-name <table>"
```

### Metrics Lambda

The `metrics-lambda` subcommand runs as a DynamoDB Stream-triggered Lambda that
writes a catalog-wide vulnerability aggregate to DynamoDB (served by
`GET /v1/vulnerabilities`).

#### How It Works

The Lambda is triggered by DynamoDB Stream events filtered on `VULNERABILITIES#`
and `TAGS` changes, with a 60-second batching window and reserved concurrency
of 1 (single instance). It maintains an in-memory active CVE table across warm
invocations:

- **Cold start**: Reads `CATALOG/DIRECTORY`, all `TAGS`, and all non-superseded
  `VULNERABILITIES#` items from DynamoDB to build the full table (~2-3s at
  10000 tags)
- **Warm invocations**: Incrementally updates the table from stream event keys
  (~50-100 GetItem calls per batch)
- **After each invocation**: Recomputes the aggregate

Stream events for `EXTERNAL#` PKs (external images) are intentionally
excluded from the aggregate. The `incremental_update` path filters on
`pk.starts_with("IMAGE#")` so that external-image `VULNERABILITIES#` stream
events do not pollute the Hummingbird-only `CATALOG/VULNERABILITIES` item.
The `GET /v1/vulnerabilities` endpoint reflects only Hummingbird CVE data.

| Environment Variable | Description                |
| -------------------- | -------------------------- |
| `TABLE_NAME`         | DynamoDB table name        |
| `DISTRO`             | `rawhide` or `hummingbird` |
| `SENTRY_DSN`         | Optional Sentry DSN        |

### Deployment

```bash
make container-catalog/build
make container-catalog/deploy
```

## External Images

The external images feature enables CVE comparison between Hummingbird and
external image sources (e.g. standard upstream registries). External image data
is exposed under the `/v1/external-images/` namespace, which is fully additive —
existing `/v1/images/` clients are unaffected.

### Overview

External images share the same DynamoDB table as Hummingbird images but use
an `EXTERNAL#{registry}` PK prefix instead of `IMAGE#{name}`, where `{registry}`
is the full registry pull reference (e.g. `docker.io/library/nginx`). The same
response types, SK patterns, and API conventions apply: tags, details, SBOM,
vulnerabilities, history, and release snapshots all work identically. Provenance
fields (`source_repo`, `source_commit`, `containerfile`, `slsa_level`,
`build_system`) are empty strings for external images — they are not available
from upstream registries.

The `/v1/external-images/config` endpoint returns the config that maps
Hummingbird images to their external sources. The join key for a given image
detail page (`IMAGE#{repository}`) is the `repository` on each tag entry
(resolved from the source-level default when not set per-tag). Clients filter
tag entries by repository, then match `stream` and `variant` values against
the page's stream/variant selection to construct the
`/v1/external-images/{percent-encoded-registry}/…` URLs (registry refs
containing `/` must be percent-encoded in the URL path).

All Docker Hub access goes through the `mirror.gcr.io` pull-through cache —
tag resolution and detail fetches in the External Sync Lambda
(`external_sync_lambda::api_host`) as well as the syft image pulls in the
External Index Lambda (`scanner::pull_ref`). Docker Hub's anonymous rate
limit (100 requests/hour per IP) is too small for the Lambdas' shared NAT IP.
Tags, digests, and image content served by the mirror are identical to Docker
Hub's, so all stored `docker.io/...` references are unchanged. Other
registries are accessed directly.

### Configuration Format

The external-images configuration is stored in DynamoDB at
`CATALOG/EXTERNAL_CONFIG` and served at `GET /v1/external-images/config`.
The JSON config is maintained outside this repo (e.g. in the infrastructure
repo) and applied to DynamoDB via the `catalog config set` CLI command.

The config is a flat list of sources. Each source maps registry tags to
`(repository, stream, variant)` triples — the same concepts Hummingbird uses
for canonical determination and `mark_superseded`. Stream and repository values
are whatever the corresponding Hummingbird image uses. Variant names use
Hummingbird names where an equivalent exists (e.g. `builder` for upstream dev
images); upstream-only variants like `slim` or `alpine` keep their upstream
names.

Each tag carries its own `repository` — the Hummingbird repository the tag's
comparison belongs to. This allows tags from the same upstream registry to
join different Hummingbird repositories (e.g. `docker.io/library/caddy` tags
`2` → repository `caddy` and `2-builder` → repository `xcaddy`):

```json
{
  "sources": [
    {
      "registry": "docker.io/library/caddy",
      "tags": [
        {
          "tag": "2",
          "repository": "caddy",
          "stream": "2",
          "variant": "default"
        },
        {
          "tag": "2-builder",
          "repository": "xcaddy",
          "stream": "2",
          "variant": "builder"
        }
      ],
      "variants": [
        {
          "name": "default",
          "description": "Caddy server",
          "base": "default",
          "builder": false,
          "fips": false
        },
        {
          "name": "builder",
          "description": "Build image with xcaddy",
          "base": "default",
          "builder": true,
          "fips": false
        }
      ]
    }
  ]
}
```

Every tag must carry a `repository` — the per-tag form is the only shape.
The older source-level `repository` field (a default inherited by all tags)
was transitional and has been removed: configs are parsed with
`deny_unknown_fields`, so a source-level `repository` is now a parse error.
The containers aggregation emits per-tag `repository` on every tag.

### Stream Assignment

External image stream values follow the same rules as Hummingbird images
(see [Choosing a Stream Value][stream-docs] in the containers repo). Key
rules for external image config:

- If the Hummingbird image uses numbered streams (e.g. `"1.27"`, `"3.14"`),
  external image tags must map to the same stream values. A Docker Hub `latest`
  tag maps to the current numbered stream — it is never a separate `"latest"`
  stream alongside numbered ones.
- Use `"latest"` as a stream value only for sources where no meaningful version
  series exists (rolling releases, date-based versions).
- The `assign_canonicals` function groups tags by `(stream, variant, digest)`.
  Within each group, the most semver-specific tag becomes canonical. When
  `latest` and `1.27` both map to stream `"1.27"` and resolve to the same
  digest, `1.27` wins by specificity.

Variant values share the Hummingbird vocabulary where equivalents exist: use
`"builder"` for upstream dev images that add a shell and package manager
(e.g. Chainguard's `latest-dev`), and `"default"` for plain runtime images.
Upstream-only variants with no Hummingbird equivalent (e.g. `"slim"`,
`"alpine"` on Docker Hub) keep their upstream names. CVE data for all
tracked variants is served the same way, so clients can present them
however fits.

[stream-docs]: https://gitlab.com/redhat/hummingbird/containers/-/blob/main/documentation/contributing/adding-images.md#choosing-a-stream-value

To add a new image or source, update the config JSON and run
`catalog config set --file <path> --table-name <table>` to apply the change
to DynamoDB (no Lambda redeploy needed).

### External Release Lambda

Triggered by EventBridge on a schedule (every 6 hours). Reads the
external-images config from DynamoDB and sends one SQS message per configured
registry to `ExternalSyncQueue` via `send_batch`. Sends unconditionally —
change detection is handled downstream by External Sync Lambda.

The Lambda is lightweight: one DynamoDB GetItem and one or two SQS
`SendMessageBatch` calls per invocation. No registry calls, no S3 access.

| Environment Variable      | Description                             |
| ------------------------- | --------------------------------------- |
| `TABLE_NAME`              | DynamoDB table name                     |
| `DISTRO`                  | `hummingbird` (no-op on `rawhide`)      |
| `EXTERNAL_SYNC_QUEUE_URL` | SQS queue URL for per-registry messages |
| `SENTRY_DSN`              | Optional Sentry DSN for error tracking  |

### External Sync Lambda

Triggered by `ExternalSyncQueue` (SQS, `BatchSize: 1`). Each invocation
processes one registry reference — identical scope to SyncFunction processing
one Konflux release.

1. Resolves all configured tags to digests via registry HEAD requests.
   Digests are validated (`sha256:[0-9a-f]{64}`) before use. Attestation
   manifests (`platform.architecture = "unknown"`) are filtered out.
   All configured tags must resolve successfully; partial resolution aborts
   the write to prevent silently shrinking the TAGS item.
2. Compares with current `EXTERNAL#{registry}/TAGS` in DynamoDB;
   early-returns if no digests changed (no-op on most invocations).
3. Groups tags by digest within each `(stream, variant)` pair; picks canonical
   by semver specificity (`1.27.2` beats `1.27`).
4. Writes DETAILS, RELEASE_DETAILS, HISTORY, OVERVIEW, and
   EXTERNAL_DIRECTORY to DynamoDB.
5. Emits one SQS message per non-superseded digest to `ExternalIndexQueue`.
   Emission is unconditional rather than change-detection based: the index
   Lambda's S3 existence check makes an event for an already-indexed digest a
   cheap no-op, and unconditional emission restores the self-healing of the
   old per-registry topology — canonical renames with unchanged digests get
   their SBOM records backfilled on the next sync write. When several
   canonicals resolve to the same digest, they share one event and one scan.
   Each message carries everything External Index Lambda needs: `registry`,
   `canonicals`, `digest`, `architectures`.
6. Writes TAGS last so it serves as a completion marker — a crashed
   invocation will be retried in full, and an SQS send failure in step 5 is
   retried without the early-exit firing (TAGS still holds the old state).

The moment sync observes a changed digest is the release event for an
external image — sync stands where the Hummingbird build system stands.

| Environment Variable       | Description                            |
| -------------------------- | -------------------------------------- |
| `TABLE_NAME`               | DynamoDB table name                    |
| `DISTRO`                   | `rawhide` or `hummingbird`             |
| `EXTERNAL_INDEX_QUEUE_URL` | SQS queue URL for per-tag index events |
| `SENTRY_DSN`               | Optional Sentry DSN for error tracking |

### External Index Lambda

Triggered by `ExternalIndexQueue` (SQS, `BatchSize: 1`). Each invocation
processes **one digest** from a release event emitted by External Sync
Lambda. The event carries everything needed — `registry`, `canonicals`,
`digest`, `architectures` — so TAGS is not read, eliminating the first-run
race between the two lambdas.

1. Validates the event at the queue boundary (registry, digest, canonicals,
   architectures). Checks S3 for an existing
   `grype-external/{registry}/{hex}.json.gz` object; skips if already present
   (idempotent, mirrors IndexFunction). If the S3 object exists but a
   canonical's DynamoDB SBOM item is missing (e.g. a canonical rename after
   the last syft run), the SBOM is backfilled from the persisted SPDX at
   `sbom-external/{registry}/{hex}.json.gz` — one scan serves every canonical
   of the digest.
2. Runs Syft with dual output for the primary architecture (`amd64` when
   present, otherwise the first architecture of the event — some upstream
   images are single-arch non-amd64): `syft-json` for Grype, `spdx-json` for
   the SBOM. Then one `spdx-json` run per remaining architecture; one
   `ArchSbom` per arch is stored in the `SbomResponse`.
3. Re-verifies the registry digest has not changed during the Syft run.
   If the digest changed, the output is discarded to avoid indexing a stale
   digest. SBOM writes happen only after this verification.
4. Writes one `SBOM#{canonical}` per canonical of the digest (all from this
   single scan) plus `RELEASE_SBOM#{hex}` to DynamoDB.
5. Uploads the gzipped Syft JSON to S3; the S3 event notification triggers
   the Scan Lambda via SQS. SPDX is stored separately at
   `sbom-external/{registry}/{hex}.json.gz` (different prefix to avoid
   triggering a spurious scan).

Each invocation is bounded to one digest's architecture matrix (minutes, not
the whole registry), so timeout and OOM blast radius are per-digest rather
than per-registry. DLQ entries are single-digest releases — replayable and
meaningful. DLQ entries are not retried automatically: recover via SQS DLQ
redrive, or wait for the registry's next change (any change re-emits every
non-superseded digest).

| Environment Variable | Description                            |
| -------------------- | -------------------------------------- |
| `TABLE_NAME`         | DynamoDB table name                    |
| `SCAN_DATA_BUCKET`   | S3 bucket for scanner data             |
| `DISTRO`             | `rawhide` or `hummingbird`             |
| `SENTRY_DSN`         | Optional Sentry DSN for error tracking |

### Data Freshness and Known Asymmetries

- External images are polled every 6 hours. Grype DB re-scans run hourly, same
  as Hummingbird images.
- The `CATALOG/VULNERABILITIES` aggregate (`GET /v1/vulnerabilities`) reflects
  only Hummingbird CVE data. There is no external-images catalog-wide CVE
  aggregate.
- Sources that offer only a `latest` tag and have no numbered version series
  will always have `"latest"` as their canonical.

For per-field availability differences between the two namespaces, see the
response type tables in the [API Endpoints](#api-endpoints) section.

## Configuration

### catalog sync

| Argument             | Description                     |
| -------------------- | ------------------------------- |
| `--distro`           | `rawhide` or `hummingbird`      |
| `--table-name`       | DynamoDB table name             |
| `--purge`            | Delete all items before writing |
| `--cache-dir`        | Cache directory (auto-detected) |
| `--image`            | Sync only a specific repo       |
| `--legacy-discovery` | Use GitLab-based repo discovery |

### catalog index

| Argument       | Description                                    |
| -------------- | ---------------------------------------------- |
| `--distro`     | `rawhide` or `hummingbird`                     |
| `--table-name` | DynamoDB table name (for image/tag discovery)  |
| `--bucket`     | S3 bucket for scanner data                     |
| `--dry-run`    | Print what would be uploaded without uploading |
| `--image`      | Index only a specific image                    |
| `--parallel`   | Number of concurrent operations (default: 2)   |

### catalog scan

| Argument       | Description                                            |
| -------------- | ------------------------------------------------------ |
| `--distro`     | `rawhide` or `hummingbird`                             |
| `--table-name` | DynamoDB table name (required)                         |
| `--bucket`     | S3 bucket with native Syft JSON (uses S3 scan path)    |
| `--scope`      | `non-superseded`, `tags` (default), or `all`           |
| `--dry-run`    | Print items without writing                            |
| `--purge`      | Purge vuln data before writing (implies `--scope all`) |
| `--cache-dir`  | Cache directory (auto-detected)                        |
| `--parallel`   | Number of concurrent scans (default: 4)                |
| `--image`      | Scan only a specific image                             |
| `--tag`        | Scan only a specific tag (requires `--image`)          |

### catalog config

`catalog config set --file <path> --table-name <table>`
reads the external-images JSON config and writes it to the DynamoDB item
`CATALOG/EXTERNAL_CONFIG`. Run once on initial setup and after each config
change. No Lambda redeploy is needed — all External\* Lambdas read config from
DynamoDB at invocation time.

| Argument       | Description                       |
| -------------- | --------------------------------- |
| `--table-name` | DynamoDB table name               |
| `--file`       | Path to external-images JSON file |

### SAM Parameters

| Parameter           | Description                                                            |
| ------------------- | ---------------------------------------------------------------------- |
| `Distro`            | `rawhide` or `hummingbird`                                             |
| `CacheEnabled`      | Enable CloudFront caching                                              |
| `CatalogDomainName` | Catalog web UI domain                                                  |
| `ApiDomainName`     | API domain                                                             |
| `HostedZoneId`      | Route53 hosted zone                                                    |
| `CorsOrigins`       | Comma-separated CORS origins (default `*`)                             |
| `SnsTopicArn`       | SNS topic ARN for Release events (enables sync/index/external Lambdas) |

The External Release, Sync, and Index Lambdas are all conditioned on
`HasSnsTopicArn` (a feature flag historically tied to the Release-events topic)
and are only deployed for the `hummingbird` stack. The external chain itself is
queue-based: the `EXTERNAL_SYNC_QUEUE_URL` and `EXTERNAL_INDEX_QUEUE_URL`
environment variables are set automatically from the queue resources defined
in the same SAM template.

## Frontend

The catalog web UI is a Lit 3 SPA (Web Components) with Tailwind CSS, built
per-distro with Vite. Source is in `container-catalog/frontend/`.

Only `make` and `podman` are required (no local Node.js needed).
Defaults from `.envrc.defaults` are applied automatically.

```bash
# Install dependencies
make container-catalog/frontend/setup

# Development server at http://localhost:5173
make container-catalog/frontend/dev

# Production build
make container-catalog/frontend/build
```

Host variants (`*-host`) run without podman (for CI or local Node.js).

### Frontend Build Variables

| Variable                       | Description                                                       |
| ------------------------------ | ----------------------------------------------------------------- |
| `VITE_API_URL`                 | API base URL for the distro                                       |
| `VITE_DISTRO`                  | `rawhide` or `hummingbird`                                        |
| `VITE_DISTRO_LABEL`            | Display label for current distro                                  |
| `VITE_OTHER_CATALOG_URL`       | URL of the other distro's catalog (optional, hides link if unset) |
| `VITE_OTHER_DISTRO_LABEL`      | Display label for other distro (optional)                         |
| `VITE_VULNERABILITIES_ENABLED` | Show vulnerabilities tab                                          |

## Development

```bash
# Backend
cargo test                    # Run tests
cargo clippy --all-targets   # Lint
cargo fmt                     # Format

# Frontend (host variants, requires local Node.js)
cd container-catalog/frontend
npm run typecheck             # Type check
npm run build                 # Production build
```

## License

This project is licensed under the GNU General Public License v3.0 or later -
see the [LICENSE][license] file for details.

[license]: https://gitlab.com/redhat/hummingbird/tools/-/blob/main/LICENSE
