A Smaller Bedrock Gateway, Part 4: The Hardened Gateway Image
Build the hardened LiteLLM image on the latest stable release, pinned by digest, and check its scan in Amazon ECR.
Series: A Smaller Bedrock Gateway (8 articles)
- …
- 4A Smaller Bedrock Gateway, Part 4: The Hardened Gateway Image This article
Last updated: 2026-11-13 (Fri) 18:22 GST
In Part 3, I deployed a network with no route to the internet. Everything that runs inside it must therefore arrive as an image in your own Amazon ECR repository, and the gateway is only as trustworthy as that image. In this part, I will show you the hardened wrapper around the upstream LiteLLM image, how it stays on the newest stable LiteLLM release, and how to build it without Docker on your workstation.
Always build on the latest stable release
The image is meant to run the newest stable LiteLLM release, not whatever was current when this series was written. The helper below finds the highest version among the project's GitHub releases that are neither drafts nor pre-releases, looks up that release's
linux/amd64 digest, and rewrites the pin. Run it with --check in a scheduled job to learn about new releases (it exits with code 3), and with --write before you build. A new release is a new deployment, so rebuild, rescan, and repeat the checks in Part 8.#!/usr/bin/env python3"""Pin the gateway to the latest stable LiteLLM release, by linux/amd64 digest.
python3 update_litellm_pin.py --check # exit 3 if a newer stable release exists python3 update_litellm_pin.py --write # rewrite every pin to the latest release
Stable means the highest semantic version among GitHub releases that are neitherdrafts nor pre-releases. Standard library only. A bump is a source change: rebuildthe image and run the full validation before using it."""import argparseimport hashlibimport jsonimport pathlibimport reimport sysimport urllib.request
ASSETS = pathlib.Path(__file__).resolve().parentREPO = "berriai/litellm"PINNED = ("Dockerfile.litellm-hardened", "validate_deployment.py", "image-lock.example.json", "07-02-litellm-gateway.yaml")FROM_RE = re.compile(r"ghcr\.io/berriai/litellm:(v\d+\.\d+\.\d+)@(sha256:[0-9a-f]{64})")INDEX_TYPES = ("application/vnd.oci.image.index.v1+json," "application/vnd.docker.distribution.manifest.list.v2+json")
def get(url, headers=None): request = urllib.request.Request(url, headers={"User-Agent": "article07-pin", **(headers or {})}) with urllib.request.urlopen(request, timeout=30) as response: return json.load(response)
def latest_stable(): releases = get(f"https://api.github.com/repos/{REPO}/releases?per_page=100", {"Accept": "application/vnd.github+json"}) tags = [r["tag_name"] for r in releases if not r["draft"] and not r["prerelease"] and re.fullmatch(r"v\d+\.\d+\.\d+", r["tag_name"])] return max(tags, key=lambda tag: tuple(map(int, tag[1:].split("."))))
def amd64_digest(tag): token = get(f"https://ghcr.io/token?scope=repository:{REPO}:pull")["token"] index = get(f"https://ghcr.io/v2/{REPO}/manifests/{tag}", {"Authorization": f"Bearer {token}", "Accept": INDEX_TYPES}) digests = [m["digest"] for m in index.get("manifests", []) if m.get("platform", {}).get("os") == "linux" and m["platform"].get("architecture") == "amd64"] if len(digests) != 1: raise SystemExit(f"{tag}: expected one linux/amd64 manifest, found {len(digests)}") return digests[0]
def write(old_tag, old_digest, tag, digest): """Move the pin (a no-op when current) and refresh the example lock's source hashes.""" for name in PINNED: path = ASSETS / name text = path.read_text(encoding="utf-8") new = text.replace(old_digest, digest).replace(f"LiteLLM {old_tag}", f"LiteLLM {tag}") new = new.replace(f"litellm:{old_tag}", f"litellm:{tag}") new = new.replace(f'version="{old_tag}"', f'version="{tag}"') if new != text: path.write_text(new, encoding="utf-8") print(f"updated {name}") lock_path = ASSETS / "image-lock.example.json" lock = json.loads(lock_path.read_text(encoding="utf-8")) for relative in lock["gateway"]["source_sha256"]: lock["gateway"]["source_sha256"][relative] = hashlib.sha256( (ASSETS / relative).read_bytes()).hexdigest() lock_path.write_text(json.dumps(lock, indent=2) + "\n", encoding="utf-8")
def main(): parser = argparse.ArgumentParser(description=__doc__) mode = parser.add_mutually_exclusive_group(required=True) mode.add_argument("--check", action="store_true") mode.add_argument("--write", action="store_true") args = parser.parse_args() dockerfile = (ASSETS / "Dockerfile.litellm-hardened").read_text(encoding="utf-8") old_tag, old_digest = FROM_RE.search(dockerfile).groups() tag = latest_stable() digest = amd64_digest(tag) print(json.dumps({"pinned": f"{old_tag}@{old_digest}", "latest": f"{tag}@{digest}"})) current = (old_tag, old_digest) == (tag, digest) if args.check: return 0 if current else 3 write(old_tag, old_digest, tag, digest) if not current: print("Pin updated. Rebuild the image and run the full validation before use.") return 0
if __name__ == "__main__": sys.exit(main())What the Dockerfile does
The Dockerfile starts from the LiteLLM v1.109.1 image, pinned by digest. It uses root only for three build steps, then runs as an unprivileged user (UID and GID 65534):
- A downgrade guard. Each extra Python wheel must be strictly newer than the version the base image already ships. If upstream has caught up, the build fails and tells you to drop the line.
- Security patches. The LiteLLM virtual environment has no pip, so the build runs pip from the base image's own wheel and installs the hash-pinned patches, then removes pip.
- Operating system fixes. The base image pins exact package versions, which would block upgrades, so the build removes those pins and runs
apk upgrade. It also deletes a bundled admin-agent environment that this gateway never runs.
The build also bundles the Amazon RDS certificate bundle and the database bootstrap program, and labels the image with the hash of every input so you can trace any running image back to its sources.
# LiteLLM v1.109.1 linux/amd64 manifest. update_litellm_pin.py moves this pin to# the latest stable release; never edit the tag or digest by hand.# The platform-specific digest prevents an ARM workstation from publishing an# image that the X86_64 Fargate task cannot start.FROM --platform=linux/amd64 ghcr.io/berriai/litellm:v1.109.1@sha256:192404922cf3ede22cfef2692a0f0e9915413c2d72e623b5d3cf0eabb0bc5eb9
# The build command supplies four reviewed local-source hashes. The Dockerfile# hash covers this static source with ARG placeholders, avoiding circularity.# Labels bind the image to the lock; the requirements hash also gates install.ARG ARTICLE07_DOCKERFILE_SHA256ARG ARTICLE07_REQUIREMENTS_SECURITY_PATCHES_SHA256ARG ARTICLE07_BOOTSTRAP_DB_SHA256ARG ARTICLE07_CA_BUNDLE_SHA256ARG ARTICLE07_BASE_IMAGE_DIGEST=sha256:192404922cf3ede22cfef2692a0f0e9915413c2d72e623b5d3cf0eabb0bc5eb9ARG ARTICLE07_PLATFORM=linux/amd64
LABEL org.opencontainers.image.source="https://github.com/BerriAI/litellm" \ org.opencontainers.image.version="v1.109.1" \ org.opencontainers.image.base.name="ghcr.io/berriai/litellm:v1.109.1" \ com.amazonaws.article07.dockerfile.sha256="${ARTICLE07_DOCKERFILE_SHA256}" \ com.amazonaws.article07.requirements-security-patches.sha256="${ARTICLE07_REQUIREMENTS_SECURITY_PATCHES_SHA256}" \ com.amazonaws.article07.bootstrap-db.sha256="${ARTICLE07_BOOTSTRAP_DB_SHA256}" \ com.amazonaws.article07.ca-bundle.sha256="${ARTICLE07_CA_BUNDLE_SHA256}" \ com.amazonaws.article07.base-image.digest="${ARTICLE07_BASE_IMAGE_DIGEST}" \ com.amazonaws.article07.platform="${ARTICLE07_PLATFORM}"
USER 0
RUN install -d -o 65534 -g 65534 -m 0755 /opt/litellm \ && install -d -o 65534 -g 65534 -m 1777 /tmp \ && install -d -o 65534 -g 65534 -m 0700 \ /tmp/.cache /tmp/pycache
# The public Amazon RDS trust bundle and security patch requirements are# checked into the build context so the validator can bind both to the image.COPY --chown=65534:65534 --chmod=0444 image/global-bundle.pem /etc/ssl/certs/aws-rds-global-bundle.pemCOPY --chown=0:0 --chmod=0444 requirements-security-patches.txt /tmp/requirements-security-patches.txtCOPY --chown=65534:65534 --chmod=0555 bootstrap_db.py /opt/litellm/bootstrap_db.py
RUN printf '%s %s\n' '90a6f1a7978a1b1b096dca6c57511ca48d3b8cf052f8e704baf358f34ea2f21b' '/etc/ssl/certs/aws-rds-global-bundle.pem' | sha256sum -c - # pragma: allowlist secret
# Build-time patching needs outbound HTTPS; the runtime does not, and it keeps# neither pip nor the temporary requirements file. Every step below is written# to survive a base bump by update_litellm_pin.py without edits.## 1. Downgrade guard: a pinned wheel must be strictly newer than the version the# base already ships. If upstream caught up, the build fails and the line must# be removed from requirements-security-patches.txt.RUN python -c "import importlib.metadata as md, re; key=lambda s: tuple(int(n) for n in re.findall('[0-9]+', s)); have=lambda n: next((d.version for d in md.distributions() if d.metadata['Name'].lower().replace('_', '-') == n.lower()), None); rows=[line.split()[0].split('==') for line in open('/tmp/requirements-security-patches.txt') if '==' in line]; stale=[f'{n} {v} is not newer than base {have(n)}; drop it' for n, v in rows if have(n) and key(v) <= key(have(n))]; print(*stale, sep=chr(10)); raise SystemExit(1 if stale else 0)"
# 2. The LiteLLM virtualenv has no pip, so pip runs from the base image's own pip# wheel. The wheel is covered by the digest-pinned FROM; exactly one must exist.RUN printf '%s %s\n' "${ARTICLE07_REQUIREMENTS_SECURITY_PATCHES_SHA256}" '/tmp/requirements-security-patches.txt' | sha256sum -c - \ && PIP_WHEELS="$(find /usr/share/python-wheels -maxdepth 1 -name 'pip-*-py3-none-any.whl')" \ && [ "$(printf '%s\n' "${PIP_WHEELS}" | grep -c .)" -eq 1 ] \ && python "${PIP_WHEELS}/pip" install --disable-pip-version-check --only-binary=:all: --require-hashes --no-deps --no-cache-dir -r /tmp/requirements-security-patches.txt \ && apk del --no-network py3-pip-wheel \ && rm -f /tmp/requirements-security-patches.txt
# 3. OS fixes: the base pins exact versions in /etc/apk/world, which blocks# `apk upgrade`. Drop those version pins (names stay), then upgrade every# package to the newest build in the base image's own signed repositories.# apk upgrade never downgrades. The bundled admin-agent virtualenv is never# run by this gateway and lags on Python package fixes, so it is removed.RUN sed -i -E 's/^([^=[:space:]]+)=[^[:space:]]+$/\1/' /etc/apk/world \ && apk upgrade --no-cache \ && rm -rf /opt/liteadmin
ENV HOME=/tmp \ XDG_CACHE_HOME=/tmp/.cache \ PYTHONDONTWRITEBYTECODE=1 \ PYTHONPYCACHEPREFIX=/tmp/pycache \ PYTHONUNBUFFERED=1 \ TMPDIR=/tmp
# Do not rely on this prepared mode surviving into the task: Fargate 1.4.0 has# presented the task-local /tmp volume both as root:root 0755 and as a copy of# this directory. The task definitions run a non-essential root# `tmp-permissions` container (all capabilities dropped) that sets 1777 only# when it is missing, before the UID 65534 containers start.VOLUME ["/tmp"]
HEALTHCHECK --interval=30s --timeout=10s --start-period=300s --retries=3 \ CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4000/health/readiness', timeout=5)" || exit 1
USER 65534:65534The security patches the build installs:
filelock==4.2.1 --hash=sha256:7be2662e9e826b9bba28afc0f843a123280d799a2ea44bb5d35ccec67905ae44oauthlib==4.0.1 --hash=sha256:498a298876e996301950a5b053d12c31628bb7b895db03666430c69ce182eb61The database bootstrap program
The migration task you will see in Part 7 runs this program. It applies the LiteLLM schema with the administrator credential, then creates two restricted database roles for the running gateway, so the runtime tasks never receive the administrator password.
#!/usr/bin/env python3"""Migrate LiteLLM and reconcile its constrained runtime database roles.
The one-shot ECS migration task runs this program with an RDS-managed administratorcredential and two application credential slots. The program serializes itself,runs LiteLLM's official migration-only command, then creates or updates bothruntime login roles. It never prints credentials, connection strings, SQL, orraw migration output."""
from __future__ import annotations
import osimport reimport subprocessimport sysfrom collections.abc import Mapping, Sequencefrom pathlib import Pathfrom urllib.parse import quote
import psycopgfrom psycopg import sql
_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")_HOSTNAME = re.compile( r"^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$")_RUNTIME_GROUP_ROLE = "litellm_v2_runtime"_APP_ROLES = ( ("litellm_v2_app_a", "APP_DATABASE_USER_A", "APP_DATABASE_PASSWORD_A"), ("litellm_v2_app_b", "APP_DATABASE_USER_B", "APP_DATABASE_PASSWORD_B"),)_SCHEMA = "public"_MIGRATION_COMMAND = ("litellm", "--skip_server_startup")_MIGRATION_ENV_ALLOWLIST = { "CHECKPOINT_DISABLE", "HOME", "LANG", "LC_ALL", "LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS", "LITELLM_LOCAL_MODEL_COST_MAP", "LITELLM_OFFLINE_MODE", "LITELLM_PRISMA_MIGRATE_DEPLOY_TIMEOUT", "LITELLM_RELEASE_TAG", "LITELLM_TELEMETRY_DISABLED", "PATH", "PRISMA_BINARY_CACHE_DIR", "PRISMA_BINARY_PLATFORM", "PRISMA_CLI_PATH", "PRISMA_CLI_QUERY_ENGINE_TYPE", "PRISMA_OFFLINE_MODE", "PRISMA_QUERY_ENGINE_BINARY", "PYTHONPATH", "PYTHONPYCACHEPREFIX", "PYTHONUNBUFFERED", "SSL_CERT_FILE", "TMPDIR", "XDG_CACHE_HOME",}
def _required_env(name: str, environ: Mapping[str, str]) -> str: value = environ.get(name) if not value or "\x00" in value: raise RuntimeError( f"required environment variable is missing or invalid: {name}" ) return value
def _validated_identifier(value: str, label: str) -> str: if not _IDENTIFIER.fullmatch(value): raise ValueError(f"{label} is not a valid PostgreSQL identifier") return value
def _connection_settings(environ: Mapping[str, str]) -> dict[str, object]: host = _required_env("DATABASE_HOST", environ) if not _HOSTNAME.fullmatch(host): raise ValueError("DATABASE_HOST is not a valid DNS hostname")
try: port = int(_required_env("DATABASE_PORT", environ)) except ValueError as error: raise ValueError("DATABASE_PORT is not an integer") from error if not 1 <= port <= 65535: raise ValueError("DATABASE_PORT is outside the valid TCP port range")
database = _validated_identifier( _required_env("DATABASE_NAME", environ), "DATABASE_NAME" ) ca_bundle = Path(_required_env("RDS_CA_BUNDLE", environ)) if not ca_bundle.is_absolute() or not ca_bundle.is_file(): raise ValueError("RDS_CA_BUNDLE must name a readable absolute file")
return { "host": host, "port": port, "dbname": database, "user": _required_env("ADMIN_DATABASE_USER", environ), "password": _required_env("ADMIN_DATABASE_PASSWORD", environ), "sslmode": "verify-full", "sslrootcert": str(ca_bundle), "connect_timeout": 15, "keepalives": 1, "keepalives_idle": 30, "keepalives_interval": 10, "keepalives_count": 3, }
def _database_url(settings: Mapping[str, object]) -> str: """Build the migration URL without exposing unescaped secret material."""
user = quote(str(settings["user"]), safe="") password = quote(str(settings["password"]), safe="") database = quote(str(settings["dbname"]), safe="") ca_bundle = quote(str(settings["sslrootcert"]), safe="/") return ( f"postgresql://{user}:{password}@{settings['host']}:{settings['port']}/" f"{database}?sslmode=verify-full&sslrootcert={ca_bundle}" )
def _run_migrations(environ: Mapping[str, str], settings: Mapping[str, object]) -> None: """Run the supported migration-only command with private process output.
There is deliberately no wrapper-level timeout. LiteLLM applies its own bounded Prisma timeout, while the ECS run-task caller bounds the whole task. Killing only the direct LiteLLM child could orphan its detached Prisma engine inside the task. """
child_env = { name: value for name, value in environ.items() if name in _MIGRATION_ENV_ALLOWLIST } child_env.update( { "DATABASE_URL": _database_url(settings), "DISABLE_SCHEMA_UPDATE": "false", } )
result = subprocess.run( _MIGRATION_COMMAND, check=False, env=child_env, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) if result.returncode != 0: print( f"LiteLLM migration failed (exit_code={result.returncode}).", file=sys.stderr, ) raise RuntimeError("LiteLLM migration returned a nonzero exit code")
print("LiteLLM database migrations completed.")
def _role_exists(cursor: psycopg.Cursor[object], role_name: str) -> bool: cursor.execute("SELECT 1 FROM pg_roles WHERE rolname = %s", (role_name,)) return cursor.fetchone() is not None
def _ensure_group_role(cursor: psycopg.Cursor[object]) -> None: role = sql.Identifier(_RUNTIME_GROUP_ROLE) options = sql.SQL( "NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE " "NOINHERIT NOREPLICATION NOBYPASSRLS" ) statement = sql.SQL("ALTER ROLE {} WITH ").format(role) if not _role_exists(cursor, _RUNTIME_GROUP_ROLE): statement = sql.SQL("CREATE ROLE {} WITH ").format(role) cursor.execute(statement + options)
def _ensure_login_role( cursor: psycopg.Cursor[object], role_name: str, password: str) -> None: role = sql.Identifier(role_name) # PostgreSQL utility statements cannot bind PASSWORD as a query parameter. # The value is safely quoted as a SQL literal. The RDS parameter group # suppresses routine statement logging so the credential is not emitted # during normal migration processing. options = sql.SQL( "LOGIN PASSWORD {} NOSUPERUSER NOCREATEDB NOCREATEROLE " "INHERIT NOREPLICATION NOBYPASSRLS" ).format(sql.Literal(password)) statement = sql.SQL("ALTER ROLE {} WITH ").format(role) if not _role_exists(cursor, role_name): statement = sql.SQL("CREATE ROLE {} WITH ").format(role) cursor.execute(statement + options) cursor.execute( sql.SQL("ALTER ROLE {} SET search_path TO pg_catalog, public").format(role) )
def _remove_unexpected_parent_memberships( cursor: psycopg.Cursor[object], member_name: str, allowed: Sequence[str]) -> None: cursor.execute( """ SELECT granted.rolname FROM pg_auth_members AS membership JOIN pg_roles AS granted ON granted.oid = membership.roleid JOIN pg_roles AS member_role ON member_role.oid = membership.member WHERE member_role.rolname = %s """, (member_name,), ) allowed_names = set(allowed) for row in cursor.fetchall(): parent_name = str(row[0]) if parent_name not in allowed_names: cursor.execute( sql.SQL("REVOKE {} FROM {}").format( sql.Identifier(parent_name), sql.Identifier(member_name) ) )
def _remove_unexpected_group_members( cursor: psycopg.Cursor[object], allowed_members: Sequence[str]) -> None: cursor.execute( """ SELECT member_role.rolname FROM pg_auth_members AS membership JOIN pg_roles AS granted ON granted.oid = membership.roleid JOIN pg_roles AS member_role ON member_role.oid = membership.member WHERE granted.rolname = %s """, (_RUNTIME_GROUP_ROLE,), ) allowed_names = set(allowed_members) for row in cursor.fetchall(): member_name = str(row[0]) if member_name not in allowed_names: cursor.execute( sql.SQL("REVOKE {} FROM {}").format( sql.Identifier(_RUNTIME_GROUP_ROLE), sql.Identifier(member_name), ) )
def _grant_normalized_membership( cursor: psycopg.Cursor[object], member_name: str) -> None: cursor.execute( sql.SQL("GRANT {} TO {} WITH ADMIN FALSE, INHERIT TRUE, SET FALSE").format( sql.Identifier(_RUNTIME_GROUP_ROLE), sql.Identifier(member_name), ) )
def _revoke_direct_privileges( cursor: psycopg.Cursor[object], database: str, role_name: str) -> None: database_id = sql.Identifier(database) schema_id = sql.Identifier(_SCHEMA) role_id = sql.Identifier(role_name) cursor.execute( sql.SQL("REVOKE ALL PRIVILEGES ON DATABASE {} FROM {}").format( database_id, role_id ) ) cursor.execute( sql.SQL("REVOKE ALL PRIVILEGES ON SCHEMA {} FROM {}").format(schema_id, role_id) ) cursor.execute( sql.SQL("REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA {} FROM {}").format( schema_id, role_id ) ) cursor.execute( sql.SQL("REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA {} FROM {}").format( schema_id, role_id ) ) cursor.execute( sql.SQL("REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA {} FROM {}").format( schema_id, role_id ) )
def _revoke_default_privileges( cursor: psycopg.Cursor[object], object_owner: str, role_name: str) -> None: owner_id = sql.Identifier(object_owner) schema_id = sql.Identifier(_SCHEMA) role_id = sql.Identifier(role_name) for object_type in ("TABLES", "SEQUENCES", "FUNCTIONS"): cursor.execute( sql.SQL( "ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA {} " "REVOKE ALL PRIVILEGES ON " + object_type + " FROM {}" ).format(owner_id, schema_id, role_id) )
def _grant_runtime_privileges( cursor: psycopg.Cursor[object], database: str, object_owner: str, app_roles: Sequence[str],) -> None: database_id = sql.Identifier(database) schema_id = sql.Identifier(_SCHEMA) owner_id = sql.Identifier(object_owner) runtime_id = sql.Identifier(_RUNTIME_GROUP_ROLE)
# The database is dedicated to LiteLLM. Remove PostgreSQL's broad defaults # before granting only the runtime operations the proxy needs. cursor.execute( sql.SQL("REVOKE CONNECT, TEMPORARY ON DATABASE {} FROM PUBLIC").format( database_id ) ) cursor.execute( sql.SQL("REVOKE ALL PRIVILEGES ON SCHEMA {} FROM PUBLIC").format(schema_id) ) cursor.execute( sql.SQL("REVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA {} FROM PUBLIC").format( schema_id ) )
for role_name in (_RUNTIME_GROUP_ROLE, *app_roles): _revoke_default_privileges(cursor, object_owner, role_name) _revoke_direct_privileges(cursor, database, _RUNTIME_GROUP_ROLE) cursor.execute( sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(database_id, runtime_id) ) cursor.execute( sql.SQL("GRANT USAGE ON SCHEMA {} TO {}").format(schema_id, runtime_id) ) cursor.execute( sql.SQL( "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA {} TO {}" ).format(schema_id, runtime_id) ) cursor.execute( sql.SQL( "GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA {} TO {}" ).format(schema_id, runtime_id) ) cursor.execute( sql.SQL( "ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA {} " "REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC" ).format(owner_id, schema_id) ) cursor.execute( sql.SQL( "ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA {} " "GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO {}" ).format(owner_id, schema_id, runtime_id) ) cursor.execute( sql.SQL( "ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA {} " "GRANT USAGE, SELECT, UPDATE ON SEQUENCES TO {}" ).format(owner_id, schema_id, runtime_id) )
def _reconcile_runtime_roles( connection: psycopg.Connection[object], environ: Mapping[str, str]) -> None: credentials: list[tuple[str, str]] = [] for expected_role, user_variable, password_variable in _APP_ROLES: role_name = _validated_identifier( _required_env(user_variable, environ), user_variable ) if role_name != expected_role: raise ValueError(f"{user_variable} must be {expected_role}") credentials.append((role_name, _required_env(password_variable, environ)))
with connection.transaction(), connection.cursor() as cursor: cursor.execute("SELECT current_database(), current_user") current = cursor.fetchone() if current is None: raise RuntimeError("database identity query returned no row") database = _validated_identifier(str(current[0]), "current database") object_owner = _validated_identifier(str(current[1]), "current user")
_ensure_group_role(cursor) _remove_unexpected_parent_memberships(cursor, _RUNTIME_GROUP_ROLE, ()) for role_name, password in credentials: _ensure_login_role(cursor, role_name, password) _remove_unexpected_parent_memberships( cursor, role_name, (_RUNTIME_GROUP_ROLE,) ) _grant_normalized_membership(cursor, role_name) _revoke_direct_privileges(cursor, database, role_name) app_role_names = tuple(role_name for role_name, _password in credentials) _remove_unexpected_group_members(cursor, app_role_names) _grant_runtime_privileges(cursor, database, object_owner, app_role_names)
def bootstrap(environ: Mapping[str, str] = os.environ) -> None: settings = _connection_settings(environ) with psycopg.connect(**settings, autocommit=True) as connection: with connection.cursor() as cursor: cursor.execute( "SELECT pg_try_advisory_lock(hashtext(%s))", ("article07-litellm-bootstrap",), ) lock_row = cursor.fetchone() if lock_row is None or lock_row[0] is not True: raise RuntimeError("another LiteLLM bootstrap task is already running")
_run_migrations(environ, settings) _reconcile_runtime_roles(connection, environ)
print("LiteLLM runtime database roles are ready.")
def main() -> int: try: bootstrap() except Exception as error: # noqa: BLE001 - fail closed without leaking driver text # Exception text is intentionally omitted because drivers can include a DSN. print(f"database bootstrap failed ({type(error).__name__})", file=sys.stderr) return 1 return 0
if __name__ == "__main__": raise SystemExit(main())Build the image with AWS CodeBuild
If you do not run Docker locally, this template creates a temporary CodeBuild project that builds the Dockerfile for
linux/amd64 and pushes it to your ECR repository. Upload the Dockerfile, the requirements file, the bootstrap program, and the RDS certificate bundle ( image/global-bundle.pem ) as context.zip to the bucket it creates, start a build with an IMAGE_TAG , and delete the stack afterwards. The build needs outbound internet access for the base image and wheels; the gateway itself does not.AWSTemplateFormatVersion: '2010-09-09'Description: >- Article 07 build-only helper. A CodeBuild project that runs the real Dockerfile.litellm-hardened for linux/amd64 and pushes it to the existing same-account ECR repository. Build-time package retrieval needs outbound HTTPS; the gateway runtime does not. Delete this stack after the build.
Parameters: RepositoryName: Type: String Default: litellm AllowedPattern: '^[a-z0-9][a-z0-9._/-]{1,254}$' BuildId: Type: String AllowedPattern: '^[a-z0-9-]{3,40}$' Description: Run-scoped identifier used in names.
Resources: SourceBucket: Type: AWS::S3::Bucket Properties: BucketEncryption: ServerSideEncryptionConfiguration: - ServerSideEncryptionByDefault: SSEAlgorithm: AES256 PublicAccessBlockConfiguration: BlockPublicAcls: true BlockPublicPolicy: true IgnorePublicAcls: true RestrictPublicBuckets: true OwnershipControls: Rules: - ObjectOwnership: BucketOwnerEnforced LifecycleConfiguration: Rules: - Id: expire-build-context Status: Enabled ExpirationInDays: 3
SourceBucketPolicy: Type: AWS::S3::BucketPolicy Properties: Bucket: !Ref SourceBucket PolicyDocument: Version: '2012-10-17' Statement: - Sid: DenyInsecureTransport Effect: Deny Principal: '*' Action: 's3:*' Resource: - !GetAtt SourceBucket.Arn - !Sub '${SourceBucket.Arn}/*' Condition: Bool: aws:SecureTransport: 'false'
BuildLogGroup: Type: AWS::Logs::LogGroup Properties: LogGroupName: !Sub '/article07/image-build/${BuildId}' RetentionInDays: 14
BuildRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: codebuild.amazonaws.com Action: sts:AssumeRole Condition: StringEquals: aws:SourceAccount: !Ref AWS::AccountId Policies: - PolicyName: build PolicyDocument: Version: '2012-10-17' Statement: - Sid: Logs Effect: Allow Action: - logs:CreateLogStream - logs:PutLogEvents Resource: !Sub '${BuildLogGroup.Arn}' - Sid: ReadContext Effect: Allow Action: - s3:GetObject - s3:GetObjectVersion Resource: !Sub '${SourceBucket.Arn}/*' - Sid: EcrAuth Effect: Allow Action: ecr:GetAuthorizationToken Resource: '*' - Sid: EcrPushOneRepository Effect: Allow Action: - ecr:BatchCheckLayerAvailability - ecr:BatchGetImage - ecr:CompleteLayerUpload - ecr:GetDownloadUrlForLayer - ecr:InitiateLayerUpload - ecr:PutImage - ecr:UploadLayerPart Resource: !Sub 'arn:${AWS::Partition}:ecr:${AWS::Region}:${AWS::AccountId}:repository/${RepositoryName}'
BuildProject: Type: AWS::CodeBuild::Project Properties: Name: !Sub 'article07-image-${BuildId}' ServiceRole: !GetAtt BuildRole.Arn TimeoutInMinutes: 30 Artifacts: Type: NO_ARTIFACTS Source: Type: S3 Location: !Sub '${SourceBucket}/context.zip' BuildSpec: | version: 0.2 env: shell: bash phases: pre_build: commands: - set -euo pipefail - REGISTRY="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com" - aws ecr get-login-password --region "$AWS_REGION" | docker login --username AWS --password-stdin "$REGISTRY" - sha256sum Dockerfile.litellm-hardened requirements-security-patches.txt bootstrap_db.py image/global-bundle.pem build: commands: - set -euo pipefail - REGISTRY="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com" - | DOCKER_BUILDKIT=1 docker build \ --platform linux/amd64 \ --pull \ --file Dockerfile.litellm-hardened \ --build-arg ARTICLE07_DOCKERFILE_SHA256="$(sha256sum Dockerfile.litellm-hardened | awk '{print $1}')" \ --build-arg ARTICLE07_REQUIREMENTS_SECURITY_PATCHES_SHA256="$(sha256sum requirements-security-patches.txt | awk '{print $1}')" \ --build-arg ARTICLE07_BOOTSTRAP_DB_SHA256="$(sha256sum bootstrap_db.py | awk '{print $1}')" \ --build-arg ARTICLE07_CA_BUNDLE_SHA256="$(sha256sum image/global-bundle.pem | awk '{print $1}')" \ --tag "$REGISTRY/$REPOSITORY_NAME:$IMAGE_TAG" \ . - docker push "$REGISTRY/$REPOSITORY_NAME:$IMAGE_TAG" | tee push.log - echo "ARTICLE07_PUSHED_DIGEST=$(grep -o 'sha256:[a-f0-9]\{64\}' push.log | tail -n 1)" Environment: Type: LINUX_CONTAINER ComputeType: BUILD_GENERAL1_MEDIUM Image: aws/codebuild/amazonlinux-x86_64-standard:5.0 PrivilegedMode: true EnvironmentVariables: - Name: REPOSITORY_NAME Value: !Ref RepositoryName - Name: AWS_ACCOUNT_ID Value: !Ref AWS::AccountId LogsConfig: CloudWatchLogs: Status: ENABLED GroupName: !Ref BuildLogGroup
Outputs: SourceBucketName: Value: !Ref SourceBucket ProjectName: Value: !Ref BuildProject LogGroupName: Value: !Ref BuildLogGroupRecord the digest and check the scan
The stacks reference the image by digest, never by tag. In the shell from Part 3, record the digest the build pushed.
IMAGE_DIGEST=YOUR_PUSHED_IMAGE_DIGEST # sha256:...CONTAINER_IMAGE="$IMAGE_REPOSITORY@$IMAGE_DIGEST"Then open the image in the Amazon ECR console and check its scan results. For the image validated in this series, the scan reported no critical and no high findings, and one medium finding (CVE-2025-4565 in protobuf). Review the remaining findings against your own policy before you promote an image.

Figure 1. The Amazon ECR scan results for the hardened gateway image.
A quick recap of activities
In this part, we:
- Pinned the image to the newest stable LiteLLM release with a helper you can schedule.
- Built a non-root, read-only-ready image with a downgrade guard, hash-pinned patches, and operating system upgrades.
- Bundled the database bootstrap program that creates restricted runtime roles.
- Built and pushed the image with a temporary CodeBuild project, recorded its digest, and checked its scan.
Conclusion
You now have a hardened image in your own repository, referenced by digest. In Part 5, I will start the gateway stack with its inputs, its secrets, and the data tier that holds keys, spend, and shared rate-limit state.
This is Part 4 of the eight-part A Smaller Bedrock Gateway series. Part 1 covers the design, Parts 2 and 3 the network stack, Part 4 the hardened image, Parts 5 to 7 the gateway stack, and Part 8 the deployment, validation, and day-two operations.
Series: A Smaller Bedrock Gateway (8 articles)
- …
- 4A Smaller Bedrock Gateway, Part 4: The Hardened Gateway Image This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article