diff --git a/docs/requirements/037-per-user-agents.md b/docs/requirements/037-per-user-agents.md index a5c7ceafe1..f4f0fd7b67 100644 --- a/docs/requirements/037-per-user-agents.md +++ b/docs/requirements/037-per-user-agents.md @@ -18,7 +18,7 @@ As a platform user with agent access, I want Open WebUI to start my own Hermes o 1. Open WebUI sends `POST /v1/chat/completions` with `model: hermes` or `model: openclaw` to the broker, authenticated with the broker key and carrying the `X-OpenWebUI-User-*` headers (`ENABLE_FORWARD_USER_INFO_HEADERS=true`). 2. The broker rejects any request whose bearer is not the broker key, and any request without a user id header. -3. The broker resolves the caller's groups from Keycloak and refuses with HTTP 403 when the caller is not in the `agent-user` group of the requested platform. +3. The broker resolves the caller's groups from Keycloak on every completion and refuses with HTTP 403 when the caller is not in the `agent-user` group of the requested platform. 4. The broker looks up the caller's agent for that platform by name. When none exists it creates one; when it is stopped it starts it; it then waits until the agent answers its health endpoint. 5. The broker forwards the request to the agent with the agent's own bearer key and streams the answer back unchanged. 6. `GET /v1/models` lists both platforms; Open WebUI shows each only to its group through model access grants. @@ -49,7 +49,6 @@ With the broker deployed, Open WebUI runs with `BYPASS_MODEL_ACCESS_CONTROL=fals | `idle_minutes` | idle time before a stop | | `max_running` | upper bound of concurrently running agents; a request beyond it gets HTTP 503 | | `start_timeout` | seconds an agent gets to answer its health endpoint | -| `access_cache_seconds` | how long a Keycloak membership answer is reused | A stopped agent is started again on the next request with its volume re-attached. An agent serving a request is never stopped, and the idle time is re-read under the agent's lock before the stop. When a caller has lost the `agent-user` group, the broker refuses the request and stops that caller's running agent. diff --git a/roles/svc-ai-agent-broker/README.md b/roles/svc-ai-agent-broker/README.md index 2fa9db4134..2ddc847bdd 100644 --- a/roles/svc-ai-agent-broker/README.md +++ b/roles/svc-ai-agent-broker/README.md @@ -11,10 +11,10 @@ This role deploys the broker together with a container-API socket proxy in Compo ## Features - **Agents on demand:** The first completion of a user for `hermes` or `openclaw` creates that user's agent; later requests reuse it, and a stopped agent is started again with its state volume re-attached. -- **RBAC gate:** A user needs the `agent-user` role of `web-app-hermes` or `web-app-openclaw`. Open WebUI lists each agent model only to that group, and the broker refuses any other caller with HTTP 403 and stops a running agent of a user who lost the role. +- **RBAC gate:** A user needs the `agent-user` role of `web-app-hermes` or `web-app-openclaw`. Open WebUI lists each agent model only to that group, and the broker refuses any other caller with HTTP 403 and stops a running agent of a user who lost the role. Every completion reads the caller's group membership from Keycloak again, so a grant and a revocation both take effect on the next request. - **Isolation:** Every agent runs in its own container or single-replica service under the isolating runtime, with its own volume, its own network whose only other member is the broker, and its own bearer key; an agent that would start under `runc` is stopped and refused. In compose that network is created per agent and the broker attaches to it; in swarm, where a service task cannot be attached to a network it was not created with, the networks are a pool of `agents.max_running` overlays that the broker joins through its own service spec and each agent claims one of while it runs. - **Restricted engine access:** The broker reaches the container engine only through a filtered unix socket in a volume shared with the socket proxy, which publishes no port and runs with `network_mode: none` in compose. The proxy admits only the container, service, task, network, volume and image calls the broker makes, and refuses every other method and path, including exec and delete. It filters methods and paths, not request bodies: `volumes/create` stays open for the per-agent volume, so the isolation holds against a compromised agent, which reaches no socket at all, not against a compromised broker. - **Bind-mount allowlist:** One `-allowbindmountfrom` carries all four CA-trust files the deployment binds into every container as a comma-separated value, and nothing else; the flag is a plain string the proxy splits on commas, so a repeated flag keeps only its last occurrence. `ensure_pool` re-POSTs the broker's own service spec to attach the pool network, so the spec's own mounts have to pass that check; dropping them answers the update with 403 and the broker crash-loops. An empty allowlist is not an option because it switches the restriction off for every call. -- **Lifecycle settings:** `agents.idle_stop`, `agents.idle_minutes`, `agents.max_running`, `agents.start_timeout` and `agents.access_cache_seconds` in `meta/services.yml` control idle stops, the running-agent bound, the start wait and the membership cache; an inventory overrides them under `applications.svc-ai-agent-broker.services.agent-broker.agents`. An agent serving a request is never swept. +- **Lifecycle settings:** `agents.idle_stop`, `agents.idle_minutes`, `agents.max_running` and `agents.start_timeout` in `meta/services.yml` control idle stops, the running-agent bound and the start wait; an inventory overrides them under `applications.svc-ai-agent-broker.services.agent-broker.agents`. An agent serving a request is never swept. - **Model and context:** `agents.model` names the gateway alias every agent runs on and defaults to the gateway's chat model, so agents can run on a larger model than Open WebUI's default. The context window of that alias comes from the model's `context` in the inventory and is written into the agent config as Hermes `model.context_length` and OpenClaw `contextWindow`. An agent prompt runs to tens of thousands of tokens, so a CPU-only local model spends minutes per turn on it; point `agents.model` at a remote model for interactive use. Hermes refuses a window below 64000 tokens and answers HTTP 500 on every prompt, so a platform whose minimum the selected alias misses is not offered at all: it is left out of `/v1/models` and answers 404, and the deploy says which platform it dropped and why. The rest of the broker keeps working, which is what makes a small model and OpenClaw a valid pairing. An alias that declares no window is reported instead of filtered, because an agent that does not know its window runs. - **Model relay:** Agents call `http://agent-broker:/llm/v1` with their own key; the broker forwards the call to LiteLLM with the broker's virtual key, sets the OpenAI `user` field to the owner and logs a JSON `relay` event with owner, platform, path and upstream status. diff --git a/roles/svc-ai-agent-broker/files/python/access.py b/roles/svc-ai-agent-broker/files/python/access.py index 477ad1cff5..060f230a58 100644 --- a/roles/svc-ai-agent-broker/files/python/access.py +++ b/roles/svc-ai-agent-broker/files/python/access.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -import threading import time import urllib.error import urllib.parse @@ -19,21 +18,17 @@ class Keycloak: realm: realm holding the platform users. username: master-realm administrator. password: its password. - cache_seconds: how long a membership answer is reused. timeout: seconds per HTTP call. """ - def __init__(self, base_url, realm, username, password, cache_seconds, timeout): + def __init__(self, base_url, realm, username, password, timeout): self.base_url = base_url.rstrip("/") self.realm = realm self.username = username self.password = password - self.cache_seconds = cache_seconds self.timeout = timeout self._token = "" self._token_expiry = 0.0 - self._cache = {} - self._lock = threading.Lock() def _request(self, method, url, data=None, headers=None): request = urllib.request.Request(url, data=data, method=method) # noqa: S310 - https:// base fixed by KEYCLOAK_URL @@ -81,24 +76,16 @@ class Keycloak: return body def groups_of(self, email): - key = email.lower() - with self._lock: - cached = self._cache.get(key) - if cached and time.monotonic() - cached[0] < self.cache_seconds: - return cached[1] - users = self._get("/users", {"email": key, "exact": "true"}) - if len(users) != 1: - groups = frozenset() - else: - groups = frozenset( - group["path"] - for group in self._get( - f"/users/{users[0]['id']}/groups", - {"briefRepresentation": "true", "max": "1000"}, - ) - ) - self._cache[key] = (time.monotonic(), groups) - return groups + users = self._get("/users", {"email": email.lower(), "exact": "true"}) + if len(users) != 1: + return frozenset() + return frozenset( + group["path"] + for group in self._get( + f"/users/{users[0]['id']}/groups", + {"briefRepresentation": "true", "max": "1000"}, + ) + ) def allows(self, email, group_path): return bool(email) and group_path in self.groups_of(email) diff --git a/roles/svc-ai-agent-broker/files/python/server.py b/roles/svc-ai-agent-broker/files/python/server.py index 5c2ea007ed..961b5f6bc8 100644 --- a/roles/svc-ai-agent-broker/files/python/server.py +++ b/roles/svc-ai-agent-broker/files/python/server.py @@ -18,7 +18,6 @@ Environment: KEYCLOAK_REALM: realm of the platform users. KEYCLOAK_ADMIN_USERNAME: master-realm administrator. KEYCLOAK_ADMIN_PASSWORD: its password. - ACCESS_CACHE_SECONDS: reuse window of a membership answer. IDLE_STOP: ``true`` stops idle agents. IDLE_MINUTES: idle time before a stop. MAX_RUNNING: bound on concurrently running agents. @@ -84,7 +83,6 @@ ACCESS = Keycloak( ENV["KEYCLOAK_REALM"], ENV["KEYCLOAK_ADMIN_USERNAME"], ENV["KEYCLOAK_ADMIN_PASSWORD"], - cache_seconds=int(ENV["ACCESS_CACHE_SECONDS"]), timeout=15, ) diff --git a/roles/svc-ai-agent-broker/files/test/membership.py b/roles/svc-ai-agent-broker/files/test/membership.py index 85c51eae75..8675152ba7 100644 --- a/roles/svc-ai-agent-broker/files/test/membership.py +++ b/roles/svc-ai-agent-broker/files/test/membership.py @@ -20,7 +20,6 @@ keycloak = Keycloak( os.environ["KEYCLOAK_REALM"], os.environ["KEYCLOAK_ADMIN_USERNAME"], os.environ["KEYCLOAK_ADMIN_PASSWORD"], - 0, 60, ) users = keycloak._get("/users", {"username": os.environ["MEMBER"], "exact": "true"}) diff --git a/roles/svc-ai-agent-broker/files/test/test.sh b/roles/svc-ai-agent-broker/files/test/test.sh index d63871bcfb..740995d6b8 100644 --- a/roles/svc-ai-agent-broker/files/test/test.sh +++ b/roles/svc-ai-agent-broker/files/test/test.sh @@ -162,7 +162,6 @@ done kc_membership "${USER_A_NAME}" PUT "${AGENT_GROUP_PATH}" || fail "could not grant ${USER_A_NAME} ${AGENT_GROUP_PATH}" kc_membership "${USER_B_NAME}" PUT "${AGENT_GROUP_PATH}" || fail "could not grant ${USER_B_NAME} ${AGENT_GROUP_PATH}" kc_membership "${USER_A_NAME}" PUT "${AGENT_OPENCLAW_GROUP_PATH}" || fail "could not grant ${USER_A_NAME} ${AGENT_OPENCLAW_GROUP_PATH}" -sleep 65 since="$(date +%s)" output="$(probe "${BROKER_KEY}" "${OWNER_A}" "${USER_A_EMAIL}" hermes)" diff --git a/roles/svc-ai-agent-broker/meta/services.yml b/roles/svc-ai-agent-broker/meta/services.yml index 53a5bd6c5b..16329bc23c 100644 --- a/roles/svc-ai-agent-broker/meta/services.yml +++ b/roles/svc-ai-agent-broker/meta/services.yml @@ -34,7 +34,6 @@ agent-broker: idle_minutes: 30 max_running: 20 start_timeout: 900 - access_cache_seconds: 60 run_after: - svc-ai-litellm guide_companions: diff --git a/roles/svc-ai-agent-broker/templates/env.j2 b/roles/svc-ai-agent-broker/templates/env.j2 index aca9a7458e..f93533a442 100644 --- a/roles/svc-ai-agent-broker/templates/env.j2 +++ b/roles/svc-ai-agent-broker/templates/env.j2 @@ -17,7 +17,6 @@ KEYCLOAK_URL={{ lookup('tls', 'web-app-keycloak', 'url.base') }} KEYCLOAK_REALM={{ OIDC.CLIENT.REALM | dotenv_quote }} KEYCLOAK_ADMIN_USERNAME={{ OIDC.ADMIN.USERNAME | dotenv_quote }} KEYCLOAK_ADMIN_PASSWORD={{ OIDC.ADMIN.PASSWORD | dotenv_quote }} -ACCESS_CACHE_SECONDS={{ AGENT_BROKER_AGENTS.access_cache_seconds }} IDLE_STOP={{ AGENT_BROKER_AGENTS.idle_stop | bool | string | lower }} IDLE_MINUTES={{ AGENT_BROKER_AGENTS.idle_minutes }} MAX_RUNNING={{ AGENT_BROKER_AGENTS.max_running }} diff --git a/tests/unit/python/roles/svc-ai-agent-broker/files/test_access.py b/tests/unit/python/roles/svc-ai-agent-broker/files/test_access.py index f02932cabc..ab5604ebdb 100644 --- a/tests/unit/python/roles/svc-ai-agent-broker/files/test_access.py +++ b/tests/unit/python/roles/svc-ai-agent-broker/files/test_access.py @@ -14,18 +14,14 @@ GROUP = "/roles/web-app-hermes/agent-user" class FakeKeycloak(access.Keycloak): def __init__(self, users, groups): - super().__init__( - "https://auth", "realm", "admin", "pw", cache_seconds=60, timeout=5 - ) + super().__init__("https://auth", "realm", "admin", "pw", timeout=5) self.users = users self.groups = groups - self.lookups = 0 def _admin_token(self): return "token" def _get(self, path, query): - self.lookups += 1 if path == "/users": return self.users.get(query["email"], []) user_id = path.split("/")[2] @@ -46,12 +42,17 @@ class TestAllows(unittest.TestCase): self.assertFalse(keycloak.allows("", GROUP)) self.assertFalse(keycloak.allows("nobody@x", GROUP)) - def test_an_answer_is_reused_within_the_cache_window(self): + def test_a_grant_between_two_checks_is_seen_by_the_second(self): + keycloak = FakeKeycloak({"a@x": [{"id": "1"}]}, {"1": []}) + self.assertFalse(keycloak.allows("a@x", GROUP)) + keycloak.groups["1"] = [GROUP] + self.assertTrue(keycloak.allows("a@x", GROUP)) + + def test_a_revocation_between_two_checks_is_seen_by_the_second(self): keycloak = FakeKeycloak({"a@x": [{"id": "1"}]}, {"1": [GROUP]}) - keycloak.allows("a@x", GROUP) - lookups = keycloak.lookups - keycloak.allows("a@x", GROUP) - self.assertEqual(keycloak.lookups, lookups) + self.assertTrue(keycloak.allows("a@x", GROUP)) + keycloak.groups["1"] = [] + self.assertFalse(keycloak.allows("a@x", GROUP)) if __name__ == "__main__":