Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@

## Unreleased

### Added

1. **The LLM helper's stores sign in with a token instead of a password.** `llm.transcript.redis.auth` and
`llm.transcript.audit.postgres.auth` take `password` (the default, as before) or a token source: each new
connection then signs in as the store's user with a short-lived token made from the identity the deployment
already gives the process, so nothing is stored or rotated. The stores know only a user and a token, renewed a
minute before it expires; a source is a function in `TOKEN_SOURCES`, so another cloud's joins without a change to
them. The first source is `aws`: an IAM authentication token presigned locally from the AWS credential chain,
which Amazon ElastiCache and Amazon RDS for PostgreSQL accept for 15 minutes (`llm.transcript.redis.aws.cache`
names the replication group; the `aws` extra adds boto3). A missing user, a password beside the token, no TLS, or
what the source needs stops the start by name. `tests/test_llm_store_auth.py` pins the ElastiCache token against
botocore's own presigner with fixed credentials and a fixed clock.

## Version 4.12.31, 11/30/2026

The pack's half of the agent work the engines release as 4.12.31, in lockstep with the Node.js pack, and the pack as an
Expand Down
36 changes: 36 additions & 0 deletions extensions/llm-helper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,39 @@ function a role that may `INSERT`, `SELECT` and `UPDATE` the two tables and noth
keep TLS on (`llm.transcript.audit.postgres.ssl`, the default). The audit does not redact; a redaction policy is the
installation's, applied on read.

### Signing in to the stores with a token

Both stores sign in with a password by default. A store can instead sign in with a short-lived token made from the
identity the deployment already gives the process - a pod's role, a task role, a managed identity - so nothing is
stored, rotated or handed to the helper. The store's `auth` setting names where the token comes from:

| Setting | Values |
|---|---|
| `llm.transcript.redis.auth` | `password` (the default), or a token source |
| `llm.transcript.audit.postgres.auth` | `password` (the default), or a token source |

The stores know nothing of the source: they sign in as the store's `username`, with the token where the password
would go, and take a new token for each new connection. The helper keeps one token per store and renews it a minute
before it expires, so a burst of new connections makes one. A server checks the token when a connection opens, so
an open connection outlives its token. A token source is refused at start, by name, without a user to sign in as,
beside a password (one way to sign in, never two), or without TLS, since the token travels where a password would
(`llm.transcript.redis.ssl: true`; PostgreSQL's `ssl` is on by default). PostgreSQL needs `psycopg-pool` 3.3 or
later, which gives each new connection its own settings. A source is a function in `TOKEN_SOURCES` of
`llm_helper.py`; another cloud's (Google Cloud's OAuth 2.0 access token for Memorystore and Cloud SQL, Microsoft
Entra ID's for Azure Cache for Redis and Azure Database for PostgreSQL) is added there without a change to the stores.

| Source | Stores | Token | Needs |
|---|---|---|---|
| `aws` | Amazon ElastiCache (Valkey or Redis OSS), Amazon RDS for PostgreSQL | An IAM authentication token: the request `connect` presigned with SigV4 by the AWS credential chain, in this process and with no network call; valid 15 minutes | The `aws` extra (boto3); a region (`llm.aws.region`, else `AWS_REGION`); for Redis, `llm.transcript.redis.aws.cache`, the replication group the token names |

**`aws` in practice.** The user is the store's IAM-enabled user: an ElastiCache user whose authentication mode is
IAM (its name and id must be equal), or a PostgreSQL role granted `rds_iam`. The process's role needs
`elasticache:Connect` on the replication group and the user, or `rds-db:connect` on the database user. ElastiCache
closes an IAM connection after 12 hours, and the client then connects again with a new token. ElastiCache
Serverless is not covered: the client connects to a single server (see The transcript store). botocore, the
library under boto3 that signs AWS requests, logs each signature it computes at DEBUG (`botocore.auth`), as it does
for the helper's Bedrock calls; keep that logger above DEBUG where tokens matter.

## Configuration

`resources/application.yml`, or `-Dkey=value` at run time. A call's `params` win over these keys.
Expand Down Expand Up @@ -503,12 +536,15 @@ stops the application at start, by name: it is never read as off.
| `llm.transcript.ttl` | `7d` | A loop turn's `ttl` when the request carries none. |
| `llm.transcript.retention` | `0` | A loop turn's `retention` when the request carries none. |
| `llm.transcript.redis.host`, `.port`, `.username`, `.password`, `.ssl`, `.database`, `.timeout.ms` | `127.0.0.1`, `6379`, none, none, `false`, `0`, `5000` | The Redis connection: the engines' `redis.*` set under this store's own prefix. The password comes from the environment (`${REDIS_PASSWORD}`). `port` is at most 65535 and `timeout.ms` at most 2147483647. |
| `llm.transcript.redis.auth` | `password` | `password` or a token source (`aws`): how the transcript store signs in (see Signing in to the stores with a token). |
| `llm.transcript.redis.aws.cache` | unset | With the token source `aws`: the ElastiCache replication group the token names. |
| `llm.transcript.audit` | unset | `postgres`: record every model turn in the audit store (see The audit store). Unset, no audit. |
| `llm.transcript.audit.retention` | `365d` | Written as a conversation's `expires_at`; the purge is the installation's. At most `1000000d`: with it the date keeps a four-digit year, which both packs and the database write the same way. A value that is not a duration, or a longer one, stops the application at start, by name. |
| `llm.transcript.audit.grace` | `1d` | How long a closed working record waits for its integrity check before it expires unreleased. A value that is not a duration of a second or more stops the application at start, by name. |
| `llm.transcript.audit.sweep.ms` | `60000` | The sweep that repairs lost events and stopped runs; `0` disables it. At most 2147483647. |
| `llm.transcript.audit.single` | `false` | `true`: record a call without `tools` as a conversation of one turn (see The audit of a single call). Needs `llm.transcript.store`. |
| `llm.transcript.audit.postgres.host`, `.port`, `.database`, `.username`, `.password`, `.ssl`, `.timeout.ms` | `127.0.0.1`, `5432`, `mercury`, none, none, `true`, `5000` | The PostgreSQL connection, the engines' convention under this store's prefix. The shipped `application.yml` sets the user and the password from the environment (`${POSTGRES_USER:mercury}`, `${POSTGRES_PASSWORD}`); `ssl` `true` is `sslmode=require`, `false` `sslmode=disable`; `timeout.ms` bounds a connection attempt, a wait for the pool and, on the server, a statement (`statement_timeout`). `port` is at most 65535 and `timeout.ms` at most 2147483647. |
| `llm.transcript.audit.postgres.auth` | `password` | `password` or a token source (`aws`): how the audit store signs in (see Signing in to the stores with a token). |

The credential is never configured here. `ANTHROPIC_API_KEY` (or whatever the SDK resolves: an
auth token, or a profile) comes from the environment for the Claude API; the AWS credential chain,
Expand Down
238 changes: 227 additions & 11 deletions extensions/llm-helper/llm_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import io
import json
import re
import threading
import time
import uuid
from collections.abc import Callable
Expand Down Expand Up @@ -1497,6 +1498,178 @@ async def sweep_lock(self, _interval_ms: int) -> bool: # NOSONAR - async by con
return True # one process sweeps its own records


# --- signing in to a store with a token instead of a password -----------------------------------
# A store's ``auth`` setting chooses how the helper signs in. ``password`` (the default) reads the
# store's password setting, as before. Any other value names a token source: a function that makes a
# short-lived token from the identity the deployment already gives the process, sent where the
# password would go. The stores know only this seam - a user, and a token renewed before it expires -
# so another cloud's source joins TOKEN_SOURCES without a change to them (README.md, "Signing in to
# the stores with a token").
STORE_AUTH_PASSWORD = "password"
TOKEN_RENEW_S = 60 # a cached token is renewed a minute before it expires


@dataclass(frozen=True)
class StoreEndpoint:
"""What a token source may need to know about the store it signs in to: which kind of store,
the store's settings prefix (for a source's own keys and its messages), where it is, and the
user the token signs in as."""

kind: str # STORE_REDIS or AUDIT_POSTGRES
prefix: str
host: str
port: int
user: str


class StoreToken:
"""A store's sign-in token, cached and renewed a minute before it expires, so a burst of new
connections signs once. A source may reach the network to refresh its identity, so the
asynchronous path signs in a worker thread. A token is never logged."""

def __init__(
self,
sign: Callable[[], str],
lifetime_s: int,
clock: Callable[[], float] = time.monotonic,
) -> None:
self._sign = sign
self._lifetime_s = lifetime_s
self._clock = clock
self._token: str | None = None
self._signed_at = 0.0
self._lock = threading.Lock()

def get(self) -> str:
with self._lock:
now = self._clock()
if self._token is None or now - self._signed_at >= self._lifetime_s - TOKEN_RENEW_S:
self._token = self._sign()
self._signed_at = now
return self._token

async def get_async(self) -> str:
return await asyncio.to_thread(self.get)


def _store_auth(prefix: str) -> str:
"""How a store signs in: its ``<prefix>auth`` setting, password when none is set."""
key = prefix + "auth"
auth = str(_prop(key, STORE_AUTH_PASSWORD) or STORE_AUTH_PASSWORD).lower()
if auth != STORE_AUTH_PASSWORD and auth not in TOKEN_SOURCES:
allowed = ", ".join((STORE_AUTH_PASSWORD, *TOKEN_SOURCES))
raise AppException(500, f"{key} must be one of: {allowed}")
return auth


def store_token(
kind: str, prefix: str, host: str, port: int, ssl: bool
) -> tuple[str, StoreToken] | None:
"""None when the store signs in with its password; else the user and the token from the source
``<prefix>auth`` names, after the checks every source shares: a user to sign in as, no password
beside the token (one way to sign in, never two), and TLS, because the token travels where a
password would. A wrong setting is an AppException that names it."""
auth = _store_auth(prefix)
if auth == STORE_AUTH_PASSWORD:
return None
key = prefix + "auth"
user = _prop(prefix + "username")
if not user:
raise AppException(
500, f"{key} {auth} needs {prefix}username - the user the token signs in"
)
if _prop(prefix + "password"):
raise AppException(500, f"{key} {auth} signs in with a token - remove {prefix}password")
if not ssl:
raise AppException(
500, f"{key} {auth} needs {prefix}ssl true - the token must travel over TLS"
)
endpoint = StoreEndpoint(kind, prefix, host, port, str(user))
return endpoint.user, TOKEN_SOURCES[auth](endpoint)


# --- the token source aws: IAM authentication tokens for Amazon ElastiCache and Amazon RDS ----------
# The AWS credential chain - the role the deployment already gives the process, as for Bedrock -
# presigns the request ``connect`` with SigV4, in this process and with no network call; ElastiCache
# (Valkey or Redis OSS) and RDS for PostgreSQL accept it in place of a password for 15 minutes.
AWS_TOKEN_S = 900
MISSING_AWS_AUTH_SDK = "the token source aws needs boto3 - pip install 'mercury-composable[aws]'"


def _aws_credentials(session: Any) -> Any:
"""The chain's current credentials, frozen for one signature: a role's credentials renew
themselves before they expire, so each token is signed with live ones."""
credentials = session.get_credentials()
if credentials is None:
raise AppException(503, MISSING_AWS_CREDENTIAL)
return credentials.get_frozen_credentials()


def elasticache_signer(cache: str, user: str, region: str, session: Any) -> Callable[[], str]:
"""An ElastiCache IAM authentication token: the request ``connect`` for the user on the cache
(its replication group id), presigned with SigV4 for the service ``elasticache``, without its
scheme - AWS's documented form (ElastiCache User Guide, "Authenticating with IAM")."""
from botocore.auth import SigV4QueryAuth
from botocore.awsrequest import AWSRequest

def sign() -> str:
request = AWSRequest(
method="GET", url=f"http://{cache}/", params={"Action": "connect", "User": user}
)
SigV4QueryAuth(
_aws_credentials(session), "elasticache", region, expires=AWS_TOKEN_S
).add_auth(request)
return str(request.prepare().url).removeprefix("http://")

return sign


def rds_signer(host: str, port: int, user: str, region: str, session: Any) -> Callable[[], str]:
"""An RDS IAM authentication token for the user on the database host, from boto3's own
``generate_db_auth_token``, which presigns locally and calls nothing."""
client = session.client("rds", region_name=region)

def sign() -> str:
_aws_credentials(session) # a missing chain is named, not a botocore error
return str(
client.generate_db_auth_token(
DBHostname=host, Port=port, DBUsername=user, Region=region
)
)

return sign


def _aws_token_source(endpoint: StoreEndpoint) -> StoreToken:
"""The token source ``aws``: ElastiCache's token for Redis, on the replication group
``<prefix>aws.cache``; RDS's for PostgreSQL, on the store's host and port. The region is
llm.aws.region, else the AWS environment."""
if importlib.util.find_spec("boto3") is None:
raise AppException(503, MISSING_AWS_AUTH_SDK)
import boto3 # the [aws] extra; checked above

session = boto3.Session()
region = _prop("llm.aws.region") or session.region_name
if not region:
raise AppException(503, MISSING_AWS_REGION)
if endpoint.kind == STORE_REDIS:
cache = _prop(endpoint.prefix + "aws.cache")
if not cache:
raise AppException(
500,
f"{endpoint.prefix}auth aws needs {endpoint.prefix}aws.cache - the replication "
"group the token names",
)
sign = elasticache_signer(str(cache), endpoint.user, str(region), session)
else:
sign = rds_signer(endpoint.host, endpoint.port, endpoint.user, str(region), session)
return StoreToken(sign, AWS_TOKEN_S)


# the token sources by the value of a store's auth setting; another cloud's is added here
TOKEN_SOURCES: dict[str, Callable[[StoreEndpoint], StoreToken]] = {"aws": _aws_token_source}


# one script, one key: atomic on a standalone server and safe on a cluster. It writes the turn
# count and the record and sets the time to live - never the audited mark, which the audit
# function owns, so the two writers share a key and not a field
Expand Down Expand Up @@ -1597,24 +1770,48 @@ def _redis_store() -> RedisStore:
)
/ 1000
)
prefix = "llm.transcript.redis."
host = str(_prop(prefix + "host", "127.0.0.1"))
port = _whole_number(prefix + "port", _prop(prefix + "port", "6379"), 1, MAX_PORT)
ssl = _switch(prefix + "ssl", False)
# how it signs in: the password setting, or a token at each connection (redis-py asks its
# credential provider every time it connects)
sign_in: dict[str, Any] = {
"username": _prop(prefix + "username") or None,
"password": _prop(prefix + "password") or None,
}
token = store_token(STORE_REDIS, prefix, host, port, ssl)
if token is not None:
sign_in = {"credential_provider": _redis_token_credentials(*token)}
client = redis_async.Redis(
host=str(_prop("llm.transcript.redis.host", "127.0.0.1")),
port=_whole_number(
"llm.transcript.redis.port", _prop("llm.transcript.redis.port", "6379"), 1, MAX_PORT
),
username=_prop("llm.transcript.redis.username") or None,
password=_prop("llm.transcript.redis.password") or None,
ssl=_switch("llm.transcript.redis.ssl", False),
db=_whole_number(
"llm.transcript.redis.database", _prop("llm.transcript.redis.database", "0"), 0
),
host=host,
port=port,
ssl=ssl,
db=_whole_number(prefix + "database", _prop(prefix + "database", "0"), 0),
socket_timeout=timeout_s,
socket_connect_timeout=timeout_s,
decode_responses=True,
**sign_in,
)
return RedisStore(client)


def _redis_token_credentials(user: str, token: StoreToken) -> Any:
"""redis-py's credential provider over a store token: the user and a current token at each
connection. redis-py 6 and later asks asynchronously, so the token is signed off the event
loop; earlier versions ask synchronously."""
from redis.credentials import CredentialProvider

class _TokenCredentials(CredentialProvider):
def get_credentials(self) -> tuple[str, str]:
return user, token.get()

async def get_credentials_async(self) -> tuple[str, str]:
return user, await token.get_async()

return _TokenCredentials()


_store: TranscriptStore | None = None # built on first use - module-level so tests can inject


Expand Down Expand Up @@ -2098,8 +2295,12 @@ def _postgres_audit_store() -> PostgresAuditStore:
# outage's length, as the live drive of 2026-11-17 showed a stopped one does by itself
"options": f"-c statement_timeout={timeout_ms}",
}
kwargs: Any = {key: value for key, value in settings.items() if value is not None}
token = store_token(AUDIT_POSTGRES, prefix, settings["host"], settings["port"], ssl)
if token is not None:
kwargs = _postgres_token_kwargs(prefix, kwargs, token[1])
pool = AsyncConnectionPool(
kwargs={key: value for key, value in settings.items() if value is not None},
kwargs=kwargs,
min_size=1,
max_size=4,
open=False,
Expand All @@ -2108,6 +2309,21 @@ def _postgres_audit_store() -> PostgresAuditStore:
return PostgresAuditStore(pool, timeout_s)


def _postgres_token_kwargs(prefix: str, settings: dict[str, Any], token: StoreToken) -> Any:
"""The pool's connection settings as a function, so every new connection gets a current token
as its password: psycopg_pool calls ``kwargs`` when it is callable, from version 3.3. A server
checks the password when a connection opens, so an open connection outlives its token."""
import psycopg_pool

if tuple(int(part) for part in psycopg_pool.__version__.split(".")[:2]) < (3, 3):
raise AppException(503, f"{prefix}auth with a token needs psycopg-pool 3.3 or later")

async def connection_settings() -> dict[str, Any]:
return {**settings, "password": await token.get_async()}

return connection_settings


_post_office = PostOffice() # local sends to transcript.audit: no endpoint, the in-process bus
_audit: AuditStore | None = None # built at boot - module-level so tests can inject
_sweep_task: asyncio.Task[None] | None = None
Expand Down
Loading
Loading