From d19fc6c395701a2a11f918b740fc2bf4f18e0d4b Mon Sep 17 00:00:00 2001 From: Roland Heusser Date: Tue, 1 Dec 2026 13:54:14 -0800 Subject: [PATCH 1/2] llm-helper: the stores sign in with a token instead of a password llm.transcript.redis.auth and llm.transcript.audit.postgres.auth take password (the default, unchanged) or a token source. With a source, each new connection 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. Proposed in #96. The stores know only a user and a token (StoreToken: cached, renewed a minute before it expires). A source is a function in TOKEN_SOURCES that receives the store's endpoint, so another cloud's source joins without a change to the stores. - Redis: redis-py's credential provider returns the user and a current token at each connection. - PostgreSQL: psycopg_pool's callable kwargs give each new connection a current token as its password (psycopg-pool 3.3 or later). - Checks every source shares, at start and by name: a user, no password beside the token, TLS. - The first source, 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. Tests: tests/test_llm_store_auth.py pins the ElastiCache token against botocore's RequestSigner with fixed credentials and a fixed clock, the RDS token's form, the renewal, a made-up source signing in both stores, both stores' construction and every refusal. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 + extensions/llm-helper/README.md | 36 ++ extensions/llm-helper/llm_helper.py | 238 +++++++++- .../llm-helper/resources/application.yml | 8 + pyproject.toml | 3 + tests/test_llm_store_auth.py | 445 ++++++++++++++++++ 6 files changed, 732 insertions(+), 11 deletions(-) create mode 100644 tests/test_llm_store_auth.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b8353f..30cfa66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/extensions/llm-helper/README.md b/extensions/llm-helper/README.md index 60fa0b9..bcb7bc5 100644 --- a/extensions/llm-helper/README.md +++ b/extensions/llm-helper/README.md @@ -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. @@ -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, diff --git a/extensions/llm-helper/llm_helper.py b/extensions/llm-helper/llm_helper.py index 371c2a1..57ff22a 100644 --- a/extensions/llm-helper/llm_helper.py +++ b/extensions/llm-helper/llm_helper.py @@ -41,6 +41,7 @@ import io import json import re +import threading import time import uuid from collections.abc import Callable @@ -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 ``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 + ``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 + ``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 @@ -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 @@ -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, @@ -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 diff --git a/extensions/llm-helper/resources/application.yml b/extensions/llm-helper/resources/application.yml index 3aba8fc..fdd003f 100644 --- a/extensions/llm-helper/resources/application.yml +++ b/extensions/llm-helper/resources/application.yml @@ -83,6 +83,11 @@ llm.transcript.store: 'memory' # llm.transcript.redis.ssl: false # llm.transcript.redis.database: 0 # llm.transcript.redis.timeout.ms: 5000 +# sign in with the AWS identity instead of a password (ElastiCache IAM authentication): a token at +# each new connection, for the username above, on the replication group named here; needs ssl true +# and the [aws] extra - leave the password unset +# llm.transcript.redis.auth: 'aws' +# llm.transcript.redis.aws.cache: 'my-replication-group' # --- the transcript audit store (RFC-0012): every model turn, durable and queryable --------- # unset: no audit, the helper as above. postgres: the transcript.audit function records every turn @@ -111,6 +116,9 @@ llm.transcript.audit.postgres.password: '${POSTGRES_PASSWORD:}' # llm.transcript.audit.postgres.database: 'mercury' # llm.transcript.audit.postgres.ssl: true # llm.transcript.audit.postgres.timeout.ms: 5000 +# sign in with the AWS identity instead of a password (RDS IAM database authentication): a token at +# each new connection, for a role granted rds_iam; needs the [aws] extra - leave the password unset +# llm.transcript.audit.postgres.auth: 'aws' # OpenTelemetry forwarder (opt-in) - the engines' opentelemetry-forwarder twin. Switch it on # at run time with -Dotel.forwarding=true; the endpoint and credential come from the diff --git a/pyproject.toml b/pyproject.toml index 5f15a7a..74ae625 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,6 +48,9 @@ redis = ["redis>=5,<9"] # PostgreSQL as the helper's transcript audit store (llm.transcript.audit: postgres) - psycopg 3 # with its binary wheel and its asynchronous pool; the helper runs without it when no audit is set postgres = ["psycopg[binary,pool]>=3.2,<4"] +# the helper's stores signing in with the AWS identity instead of a password (llm.transcript.redis.auth +# and llm.transcript.audit.postgres.auth: aws) - boto3 presigns an IAM authentication token locally +aws = ["boto3>=1.28,<2"] # the MCP binding (extensions/mcp-binding) - the official MCP SDK's client, one route per # allowlisted remote tool; the package itself stays SDK-free mcp = ["mcp>=2,<3"] diff --git a/tests/test_llm_store_auth.py b/tests/test_llm_store_auth.py new file mode 100644 index 0000000..62b3662 --- /dev/null +++ b/tests/test_llm_store_auth.py @@ -0,0 +1,445 @@ +"""The LLM helper's stores signing in with the cloud's workload identity - no network, no AWS account. + +A store's ``auth`` setting is ``password`` (the default, the password setting as before) or ``aws``: +an IAM authentication token from the AWS credential chain at each new connection, which Amazon +ElastiCache and Amazon RDS for PostgreSQL accept in place of a password. The tests pin the token's +form against botocore's own presigner with fixed credentials and a fixed clock, the renewal of a +cached token, how each store is built with it, and that every setting it needs is checked when the +helper starts, by name. +""" + +from __future__ import annotations + +import datetime +import logging +from typing import Any +from urllib.parse import parse_qs, urlsplit + +import botocore.auth +import pytest +from botocore.credentials import Credentials +from botocore.hooks import HierarchicalEmitter +from botocore.model import ServiceId +from botocore.signers import RequestSigner +from test_llm_helper import helper + +from mercury_composable import AppException + +_NOW = datetime.datetime(2026, 12, 1, 12, 0, 0) +_REGION = "us-east-1" +_CREDENTIALS = Credentials( + "AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY", "session-token" +) + + +class _Session: + """A boto3 session with fixed credentials, or none.""" + + def __init__(self, credentials: Credentials | None = _CREDENTIALS) -> None: + self._credentials = credentials + + def get_credentials(self) -> Credentials | None: + return self._credentials + + def client(self, name: str, region_name: str) -> Any: + import boto3 + + return boto3.client( + name, + region_name=region_name, + aws_access_key_id=_CREDENTIALS.access_key, + aws_secret_access_key=_CREDENTIALS.secret_key, + aws_session_token=_CREDENTIALS.token, + ) + + +@pytest.fixture +def fixed_clock(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(botocore.auth, "get_current_datetime", lambda *_args, **_kw: _NOW) + + +def _settings(monkeypatch: pytest.MonkeyPatch, settings: dict[str, str]) -> None: + monkeypatch.setattr(helper, "_store", None) + monkeypatch.setattr(helper, "_audit", None) + monkeypatch.setattr(helper, "_prop", lambda key, default=None: settings.get(key, default)) + + +# --- the tokens ------------------------------------------------------------------------------ + + +def test_an_elasticache_token_is_the_presigned_connect_request_botocore_makes( + fixed_clock: None, +) -> None: + """AWS's documented form: GET http:///?Action=connect&User=, presigned with SigV4 + for elasticache, 900 seconds, without the scheme. Checked against botocore's RequestSigner, + the other way to make it, with the same credentials and clock.""" + token = helper.elasticache_signer("transcripts", "llm-helper", _REGION, _Session())() + + events = HierarchicalEmitter() # held here: the signer keeps only a weak reference to it + signer = RequestSigner( + ServiceId("elasticache"), _REGION, "elasticache", "v4", _CREDENTIALS, events + ) + presigned = signer.generate_presigned_url( + { + "method": "GET", + "url": "http://transcripts/?Action=connect&User=llm-helper", + "body": {}, + "headers": {}, + "context": {}, + }, + operation_name="connect", + expires_in=900, + region_name=_REGION, + ) + assert token == str(presigned).removeprefix("http://") + assert not token.startswith("http") + query = parse_qs(urlsplit("http://" + token).query) + assert query["Action"] == ["connect"] + assert query["User"] == ["llm-helper"] + assert query["X-Amz-Expires"] == ["900"] + assert query["X-Amz-Credential"] == [f"AKIDEXAMPLE/20261201/{_REGION}/elasticache/aws4_request"] + assert query["X-Amz-Security-Token"] == ["session-token"] + + +def test_an_rds_token_is_boto3s_auth_token_for_the_user_on_the_host(fixed_clock: None) -> None: + token = helper.rds_signer("db.internal", 5432, "llm_helper", _REGION, _Session())() + assert token.startswith("db.internal:5432/?") + query = parse_qs(urlsplit("http://" + token).query) + assert query["Action"] == ["connect"] + assert query["DBUser"] == ["llm_helper"] + assert query["X-Amz-Expires"] == ["900"] + assert query["X-Amz-Credential"] == [f"AKIDEXAMPLE/20261201/{_REGION}/rds-db/aws4_request"] + + +@pytest.mark.parametrize( + "signer", + [ + lambda session: helper.elasticache_signer("transcripts", "u", _REGION, session), + lambda session: helper.rds_signer("db.internal", 5432, "u", _REGION, session), + ], + ids=["elasticache", "rds"], +) +def test_a_token_without_aws_credentials_is_a_503_that_names_the_chain(signer: Any) -> None: + with pytest.raises(AppException) as raised: + signer(_Session(credentials=None))() + assert raised.value.status == 503 + assert raised.value.message == helper.MISSING_AWS_CREDENTIAL + + +def test_a_token_is_signed_once_and_renewed_a_minute_before_it_expires() -> None: + signed: list[float] = [] + now = [1000.0] + + def sign() -> str: + signed.append(now[0]) + return f"token-{len(signed)}" + + token = helper.StoreToken(sign, 900, clock=lambda: now[0]) + assert token.get() == "token-1" + now[0] += 900 - 60 - 1 # 13 min 59 s later: still the same token + assert token.get() == "token-1" + now[0] += 1 # 14 minutes after signing: renewed + assert token.get() == "token-2" + assert signed == [1000.0, 1840.0] + + +async def test_a_token_is_signed_off_the_event_loop() -> None: + import threading + + threads: list[str] = [] + + def sign() -> str: + threads.append(threading.current_thread().name) + return "token" + + assert await helper.StoreToken(sign, 900).get_async() == "token" + assert threads != [threading.main_thread().name] + + +# --- the seam: a store knows a user and a token, never the cloud -------------------------------- + + +async def test_any_token_source_signs_in_both_stores_with_no_change_to_them( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A source registered beside aws is offered by the auth setting and used by both stores: the + stores see a user and a token, never which cloud made it.""" + seen: list[Any] = [] + + def source(endpoint: Any) -> Any: + seen.append(endpoint) + return helper.StoreToken(lambda: f"{endpoint.kind}-token", 3600) + + monkeypatch.setitem(helper.TOKEN_SOURCES, "test", source) + _settings( + monkeypatch, + { + "llm.transcript.store": "redis", + "llm.transcript.redis.host": "cache.internal", + "llm.transcript.redis.username": "llm-helper", + "llm.transcript.redis.ssl": "true", + "llm.transcript.redis.auth": "test", + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.host": "db.internal", + "llm.transcript.audit.postgres.username": "llm_helper", + "llm.transcript.audit.postgres.auth": "test", + }, + ) + provider = helper.get_store()._client.connection_pool.connection_kwargs["credential_provider"] + assert await provider.get_credentials_async() == ("llm-helper", "redis-token") + settings = await helper.get_audit_store()._pool._resolve_kwargs() + assert (settings["user"], settings["password"]) == ("llm_helper", "postgres-token") + assert [(e.kind, e.prefix, e.host, e.port, e.user) for e in seen] == [ + ("redis", "llm.transcript.redis.", "cache.internal", 6379, "llm-helper"), + ("postgres", "llm.transcript.audit.postgres.", "db.internal", 5432, "llm_helper"), + ] + + +def test_the_auth_setting_names_every_source_it_offers(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setitem(helper.TOKEN_SOURCES, "test", lambda _endpoint: None) + _settings(monkeypatch, {**_REDIS_AWS, "llm.transcript.redis.auth": "azure"}) + with pytest.raises(AppException) as raised: + helper.get_store() + assert raised.value.message == ("llm.transcript.redis.auth must be one of: password, aws, test") + + +# --- the transcript store on Redis ------------------------------------------------------------- + +_REDIS_AWS = { + "llm.transcript.store": "redis", + "llm.transcript.redis.host": "transcripts.cache.internal", + "llm.transcript.redis.username": "llm-helper", + "llm.transcript.redis.ssl": "true", + "llm.transcript.redis.auth": "aws", + "llm.transcript.redis.aws.cache": "transcripts", + "llm.aws.region": _REGION, +} + + +def _fixed_signer(made: list[tuple[Any, ...]]) -> Any: + def signer(*args: Any) -> Any: + made.append(args[:-1]) # the session is the last argument + return lambda: "test-token" + + return signer + + +async def test_the_redis_store_signs_in_with_a_token_from_its_credential_provider( + monkeypatch: pytest.MonkeyPatch, +) -> None: + made: list[tuple[Any, ...]] = [] + monkeypatch.setattr(helper, "elasticache_signer", _fixed_signer(made)) + _settings(monkeypatch, _REDIS_AWS) + store = helper.get_store() + kwargs = store._client.connection_pool.connection_kwargs + assert "password" not in kwargs or kwargs["password"] is None + provider = kwargs["credential_provider"] + assert provider.get_credentials() == ("llm-helper", "test-token") + assert await provider.get_credentials_async() == ("llm-helper", "test-token") + assert made == [("transcripts", "llm-helper", _REGION)] + assert store._client.connection_pool.connection_class.__name__ == "SSLConnection" + + +def test_the_redis_store_signs_in_with_its_password_by_default( + monkeypatch: pytest.MonkeyPatch, +) -> None: + settings = { + "llm.transcript.store": "redis", + "llm.transcript.redis.username": "llm-helper", + "llm.transcript.redis.password": "test-only-password", + } + _settings(monkeypatch, settings) + kwargs = helper.get_store()._client.connection_pool.connection_kwargs + assert (kwargs["username"], kwargs["password"]) == ("llm-helper", "test-only-password") + assert kwargs.get("credential_provider") is None + + +_REDIS_REFUSALS = [ + ( + {"llm.transcript.redis.auth": "azure"}, + 500, + "llm.transcript.redis.auth must be one of: password, aws", + ), + ( + {"llm.transcript.redis.username": ""}, + 500, + ( + "llm.transcript.redis.auth aws needs llm.transcript.redis.username - the user the token " + "signs in" + ), + ), + ( + {"llm.transcript.redis.password": "test-only-password"}, + 500, + "llm.transcript.redis.auth aws signs in with a token - remove llm.transcript.redis.password", + ), + ( + {"llm.transcript.redis.ssl": "false"}, + 500, + ( + "llm.transcript.redis.auth aws needs llm.transcript.redis.ssl true - the token must travel " + "over TLS" + ), + ), + ( + {"llm.transcript.redis.aws.cache": ""}, + 500, + ( + "llm.transcript.redis.auth aws needs llm.transcript.redis.aws.cache - the replication " + "group the token names" + ), + ), +] + + +@pytest.mark.parametrize( + ("change", "status", "message"), + _REDIS_REFUSALS, + ids=["unknown-auth", "no-user", "password-too", "no-tls", "no-cache"], +) +def test_the_redis_store_refuses_a_sign_in_setting_by_name( + change: dict[str, str], status: int, message: str, monkeypatch: pytest.MonkeyPatch +) -> None: + _settings(monkeypatch, {**_REDIS_AWS, **change}) + with pytest.raises(AppException) as raised: + helper.get_store() + assert (raised.value.status, raised.value.message) == (status, message) + + +def test_signing_in_with_aws_without_a_region_is_a_503_that_names_the_settings( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +) -> None: + for name in ("AWS_REGION", "AWS_DEFAULT_REGION", "AWS_PROFILE"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("AWS_CONFIG_FILE", str(tmp_path / "none")) + settings = {key: value for key, value in _REDIS_AWS.items() if key != "llm.aws.region"} + _settings(monkeypatch, settings) + with pytest.raises(AppException) as raised: + helper.get_store() + assert (raised.value.status, raised.value.message) == (503, helper.MISSING_AWS_REGION) + + +def test_signing_in_with_aws_without_boto3_is_a_503_that_names_the_extra( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real = helper.importlib.util.find_spec + monkeypatch.setattr( + helper.importlib.util, "find_spec", lambda name: None if name == "boto3" else real(name) + ) + _settings(monkeypatch, _REDIS_AWS) + with pytest.raises(AppException) as raised: + helper.get_store() + assert raised.value.status == 503 + assert "mercury-composable[aws]" in raised.value.message + + +async def test_a_wrong_sign_in_setting_stops_the_start_by_name( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + _settings(monkeypatch, {**_REDIS_AWS, "llm.transcript.redis.ssl": "false"}) + monkeypatch.setattr(helper, "_check_settings", lambda: None) + caplog.set_level(logging.ERROR) + with pytest.raises(SystemExit): + await helper.settings_boot() + errors = [record.getMessage() for record in caplog.records if record.levelno >= logging.ERROR] + assert errors == [ + ( + "llm.helper cannot start - llm.transcript.redis.auth aws needs llm.transcript.redis.ssl " + "true - the token must travel over TLS" + ) + ] + + +# --- the audit store on PostgreSQL --------------------------------------------------------------- + +_POSTGRES_AWS = { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.host": "audit.db.internal", + "llm.transcript.audit.postgres.port": "5432", + "llm.transcript.audit.postgres.database": "mercury", + "llm.transcript.audit.postgres.username": "llm_helper", + "llm.transcript.audit.postgres.auth": "aws", + "llm.aws.region": _REGION, +} + + +async def test_the_audit_store_gives_every_new_connection_a_fresh_token( + monkeypatch: pytest.MonkeyPatch, +) -> None: + made: list[tuple[Any, ...]] = [] + monkeypatch.setattr(helper, "rds_signer", _fixed_signer(made)) + _settings(monkeypatch, _POSTGRES_AWS) + pool = helper.get_audit_store()._pool + assert callable(pool.kwargs) # psycopg_pool calls it for each connection it opens + settings = await pool._resolve_kwargs() + assert settings["password"] == "test-token" + assert (settings["host"], settings["port"], settings["user"]) == ( + "audit.db.internal", + 5432, + "llm_helper", + ) + assert settings["sslmode"] == "require" + assert made == [("audit.db.internal", 5432, "llm_helper", _REGION)] + + +def test_the_audit_store_signs_in_with_its_password_by_default( + monkeypatch: pytest.MonkeyPatch, +) -> None: + settings = { + key: value + for key, value in _POSTGRES_AWS.items() + if key != "llm.transcript.audit.postgres.auth" + } + _settings(monkeypatch, {**settings, "llm.transcript.audit.postgres.password": "test-only"}) + kwargs = helper.get_audit_store()._pool.kwargs + assert isinstance(kwargs, dict) + assert kwargs["password"] == "test-only" + + +@pytest.mark.parametrize( + ("change", "message"), + [ + ( + {"llm.transcript.audit.postgres.ssl": "false"}, + ( + "llm.transcript.audit.postgres.auth aws needs llm.transcript.audit.postgres.ssl true - " + "the token must travel over TLS" + ), + ), + ( + {"llm.transcript.audit.postgres.password": "test-only"}, + ( + "llm.transcript.audit.postgres.auth aws signs in with a token - remove " + "llm.transcript.audit.postgres.password" + ), + ), + ( + {"llm.transcript.audit.postgres.username": ""}, + ( + "llm.transcript.audit.postgres.auth aws needs llm.transcript.audit.postgres.username - " + "the user the token signs in" + ), + ), + ], + ids=["no-tls", "password-too", "no-user"], +) +def test_the_audit_store_refuses_a_sign_in_setting_by_name( + change: dict[str, str], message: str, monkeypatch: pytest.MonkeyPatch +) -> None: + _settings(monkeypatch, {**_POSTGRES_AWS, **change}) + with pytest.raises(AppException) as raised: + helper.get_audit_store() + assert (raised.value.status, raised.value.message) == (500, message) + + +def test_the_helper_logs_no_token(caplog: pytest.LogCaptureFixture, fixed_clock: None) -> None: + """The helper's own log never carries a token. botocore logs the signature it computes at + DEBUG (``botocore.auth``), as it does for every request it signs; that logger is the + installation's to keep above DEBUG.""" + caplog.set_level(logging.DEBUG) + token = helper.StoreToken( + helper.elasticache_signer("transcripts", "llm-helper", _REGION, _Session()), 900 + ).get() + signature = parse_qs(urlsplit("http://" + token).query)["X-Amz-Signature"][0] + own = [record for record in caplog.records if not record.name.startswith("botocore")] + assert all(signature not in record.getMessage() for record in own) From 15b6a5824909ab460e8c433b0a0ef6ee2cb9c4f7 Mon Sep 17 00:00:00 2001 From: Roland Heusser Date: Tue, 1 Dec 2026 14:52:32 -0800 Subject: [PATCH 2/2] memory: session 2026-12-01 - the LLM helper's stores sign in with a token (#96) Co-Authored-By: Claude Opus 5.5 --- .../thread-store-token-sign-in.md | 9 +++ memory/sessions/2026-12-01-225210.md | 55 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 memory/open-threads/thread-store-token-sign-in.md create mode 100644 memory/sessions/2026-12-01-225210.md diff --git a/memory/open-threads/thread-store-token-sign-in.md b/memory/open-threads/thread-store-token-sign-in.md new file mode 100644 index 0000000..06bb87d --- /dev/null +++ b/memory/open-threads/thread-store-token-sign-in.md @@ -0,0 +1,9 @@ +- [ ] **The LLM helper's stores sign in with a token instead of a password (#96): the Python helper's seam and its + first source, `aws`, are in review; what is left.** (1) The Node.js twin, with the same settings and messages. + (2) Another cloud's source in `TOKEN_SOURCES`: Google Cloud's OAuth 2.0 access token (Memorystore, Cloud SQL) and + Microsoft Entra ID's (Azure Cache for Redis, Azure Database for PostgreSQL); Azure's Redis also needs an open + connection re-authenticated with `AUTH` before its token expires, which the seam does not do yet. (3) ElastiCache + Serverless. (4) A live drive against ElastiCache and RDS. (5) Whether the engines' own Redis and PostgreSQL + connections follow. **How to apply:** a new cloud is a source function and its extra, never a change to the + stores; the checks every source shares stay in `store_token()`. + diff --git a/memory/sessions/2026-12-01-225210.md b/memory/sessions/2026-12-01-225210.md new file mode 100644 index 0000000..1f83b7d --- /dev/null +++ b/memory/sessions/2026-12-01-225210.md @@ -0,0 +1,55 @@ +# Session (2026-12-01T22:52:10.000Z) + +**Agent:** Claude Code +**Title:** The LLM helper's stores sign in with a token instead of a password - a token-source seam, with `aws` as +its first source (issue #96) +**User:** a contributor, after the maintainer agreed to the proposal in #96: "start a PR to implement the token +support for mercury"; then "make it as agnostic as possible. Just do Python." + +## What was done + +- **Issue #96 posted** (the proposal: the helper's Redis and PostgreSQL stores sign in with a short-lived token from + the deployment's cloud identity instead of a stored password; the token types of AWS, Google Cloud and Azure + compared from their documentation). +- **Branch `feat/llm-helper-workload-identity`, one commit** over `main` at 4.12.31: + - `llm.transcript.redis.auth` and `llm.transcript.audit.postgres.auth`: `password` (the default, unchanged) or a + token source named in `TOKEN_SOURCES`. + - The stores know only a user and a token: `StoreToken` caches the token and renews it a minute before it + expires; `store_token()` makes the checks every source shares (a user, no password beside the token, TLS) and + hands the source a `StoreEndpoint` (kind, prefix, host, port, user). Redis takes it through redis-py's + credential provider, PostgreSQL through `psycopg_pool`'s callable `kwargs` (psycopg-pool 3.3 or later, + checked at start only when a source is set; 3.2.6 takes a dictionary only, 3.3.0 a function - read in both + sources). + - The source `aws`: an IAM authentication token presigned locally with SigV4 from the AWS credential chain, + valid 15 minutes - ElastiCache's `connect` request for the user on `llm.transcript.redis.aws.cache` (AWS's + documented form, without the scheme), RDS's `generate_db_auth_token` for the host and port. The `aws` extra + adds boto3. + - README "Signing in to the stores with a token", the configuration table, the sample `application.yml`, the + CHANGELOG's Unreleased entry. + - `tests/test_llm_store_auth.py`, 24 tests: the ElastiCache token equals botocore's `RequestSigner` presign with + fixed credentials and a fixed clock; the RDS token's form; the renewal; a made-up source signing in both + stores (the seam); both stores' construction; every refusal; no token in the helper's own log. +- **Gates:** `pytest` 3040 passed, 76 skipped; `ruff check` clean; `basedpyright` 0 errors. `llm_helper.py` is not + `ruff format` clean on `main` and was not reformatted; the new lines are. + +## Learned + +- redis-py's asynchronous client asks a credential provider synchronously in 5.x and through + `get_credentials_async` from 6.0 (read in 5.0.8, 5.1.0, 5.2.1 and 6.0.0): on 5.x a token is signed on the event + loop. The `redis` extra's floor stays 5. +- `botocore.auth` logs every signature it computes at DEBUG, the Bedrock calls' included; documented, not + silenced. +- botocore's `RequestSigner` keeps only a weak reference to its event emitter: a test that builds one inline gets + `ReferenceError`. + +## Not done + +- The Node.js twin; another cloud's source (Google Cloud, Azure); ElastiCache Serverless (its token adds + `ResourceType=ServerlessCache`, and the client reaches a single server only); a live drive against ElastiCache + and RDS. Thread [[store-token-sign-in]]. + +## Memory References + +- Relied on: conv-python-quality-gates, conv-github-flow-changelog, conv-kept-finding-says-why-and-rescan, + conv-one-rule-and-a-bound, transcript-audit-store-python, stack-deps-aiohttp-msgpack +- Created: store-token-sign-in (thread, `tier: working`)