Skip to content

Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.

fix(chat): only let a conversation ID be created by the account it names (#224)

Karlo Kajba Šimanić4235a4b89e6f
diff --git a/docs/api.md b/docs/api.md
index b96a0fb..72c43e4 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -43,7 +43,7 @@ All paths are relative to `/api` when going through the frontend/nginx.
| `POST /monitoring/collectors/register/poll` | poll secret | Collector checks approval; returns its token once approved. |
| `POST /monitoring/collectors/enroll` | enrollment key | Join without approval. |
| `POST /monitoring/metrics/ingest` | collector token | Collector reports host, container and system metrics. |
-| `GET /conversations`, `POST /conversations`, `DELETE /conversations/{id}`, `POST /agent/chat` | session | Chats with the incident agent (403 for users chat isn't allowed for). `POST /agent/chat` returns `message` and `steps` (as in a report); each message in `GET /conversations` carries its `steps`. |
+| `GET /conversations`, `POST /conversations`, `DELETE /conversations/{id}`, `POST /agent/chat` | session | Chats with the incident agent (403 for users chat isn't allowed for). `POST /agent/chat` returns `message` and `steps` (as in a report); each message in `GET /conversations` carries its `steps`. A new conversation's `conversation_id` must end with `-u<your user id>` (the page uses `general-u<id>` and `incident-<incident id>-u<id>`), so nobody can take another person's ID first; anything else is refused with 400. |
| `GET /logs`, `POST /logs`, `GET /dashboard/summary` | session | Audit log and summary counts (`agent_lookups`: the agent's tool calls). `POST /logs` adds an entry to your own log (level from a fixed list, message up to 2000 characters, at most 120 an hour); its source is always `dashboard`, and system event types such as `agent_tool_call` are refused. |
The four collector endpoints above exist only on the collector gate in the server
diff --git a/src/backend/routes/chat.py b/src/backend/routes/chat.py
index 6820dd5..c543809 100644
--- a/src/backend/routes/chat.py
+++ b/src/backend/routes/chat.py
@@ -63,6 +63,11 @@ def create_conversation(payload: main.ConversationRequest, session_id: Annotated
if not user:
raise HTTPException(status_code=401, detail="Session is invalid or expired.")
main.enforce_limit(main.redis_client, scope="conversation-user", subject=user["id"], limit=main.CONVERSATION_CREATE_LIMIT, window_seconds=3600)
+ # IDs are unique across all accounts and the page builds them from the account's id ("general-u1",
+ # "incident-42-u1"), so each must end with its creator's: otherwise anyone could take another person's ID first
+ # and lock them out of their own chat (#201).
+ if not payload.conversation_id.endswith(f"-u{user['id']}"):
+ raise HTTPException(status_code=400, detail="Conversation ID is not valid.")
if db.query(Conversation).filter(Conversation.id == payload.conversation_id).first():
raise HTTPException(status_code=409, detail="Conversation already exists.")
if db.query(func.count(Conversation.id)).filter(Conversation.user_id == user["id"]).scalar() >= main.MAX_CONVERSATIONS_PER_USER:
diff --git a/tests/accounts/test_new_pages.py b/tests/accounts/test_new_pages.py
index 041c8a0..6c5cc86 100644
--- a/tests/accounts/test_new_pages.py
+++ b/tests/accounts/test_new_pages.py
@@ -440,7 +440,7 @@ def _fake_agent(monkeypatch, tokens=(1000, 200), fail=None):
monkeypatch.setattr(main, "is_agent_chat_enabled", lambda db: True)
-def _ask(client, conversation="c1"):
+def _ask(client, conversation="c1-u1"):
client.post("/conversations", json={"conversation_id": conversation, "title": "t"})
return client.post("/agent/chat", json={"conversation_id": conversation, "message": "Why did it restart?", "incident_id": 42})
@@ -502,7 +502,7 @@ def test_the_daily_limit_counts_messages_per_person(app, monkeypatch):
owner.put("/admin/settings", json={"agent_daily_chat_limit": 2})
assert [_ask(owner).status_code for _ in range(3)] == [200, 200, 429]
- assert _ask(signed_in(app, 2), conversation="c2").status_code == 200 # someone else still can
+ assert _ask(signed_in(app, 2), conversation="c2-u2").status_code == 200 # someone else still can
def test_a_failed_call_is_recorded_without_tokens(app, monkeypatch):
@@ -618,13 +618,31 @@ def test_hidden_diagnoses_stay_hidden_from_users_in_the_page_the_overview_and_no
assert outbox and all(b"Agent:" not in message[1] for message in outbox)
+def test_nobody_can_take_another_persons_conversation_id(app, monkeypatch):
+ monkeypatch.setattr(main, "send_agent_message", lambda *args, **kwargs: Answer("ok"))
+ monkeypatch.setattr(main, "get_provider", lambda db: object())
+ monkeypatch.setattr(main, "is_agent_chat_enabled", lambda db: True)
+ owner, viewer = signed_in(app, 1), signed_in(app, 3)
+
+ # The IDs the page builds for the owner (#201): the viewer can't create them first, nor one that only looks alike.
+ for taken in ("general-u1", "incident-42-u1", "general-u11", "general"):
+ assert viewer.post("/conversations", json={"conversation_id": taken}).status_code == 400, taken
+ assert viewer.post("/conversations", json={"conversation_id": "general-u3"}).status_code == 200 # their own is fine
+
+ assert owner.post("/conversations", json={"conversation_id": "general-u1"}).status_code == 200
+ assert owner.post("/agent/chat", json={"conversation_id": "general-u1", "message": "hi"}).status_code == 200
+ assert viewer.post("/agent/chat", json={"conversation_id": "general-u1", "message": "hi"}).status_code in (403, 404)
+ assert viewer.delete("/conversations/general-u1").status_code == 404 # deleting still only touches your own
+ assert [item["id"] for item in owner.get("/conversations").json()["conversations"]] == ["general-u1"]
+
+
def test_chat_is_for_admins_unless_allowed_per_user(app, monkeypatch):
monkeypatch.setattr(main, "send_agent_message", lambda *args, **kwargs: Answer("ok"))
monkeypatch.setattr(main, "get_provider", lambda db: object())
monkeypatch.setattr(main, "is_agent_chat_enabled", lambda db: True)
owner, viewer = signed_in(app, 1), signed_in(app, 3)
- viewer.post("/conversations", json={"conversation_id": "v1"})
- ask = lambda: viewer.post("/agent/chat", json={"conversation_id": "v1", "message": "hi"}) # noqa: E731
+ viewer.post("/conversations", json={"conversation_id": "v1-u3"})
+ ask = lambda: viewer.post("/agent/chat", json={"conversation_id": "v1-u3", "message": "hi"}) # noqa: E731
assert ask().status_code == 403 and viewer.get("/agent/config").json()["may_chat"] is False # admins only, the default
assert owner.put("/admin/settings", json={"agent_chat_access": "per_user", **confirmed(app, owner)}).status_code == 200
@@ -692,10 +710,10 @@ def test_a_chat_message_looks_things_up_and_the_look_ups_outlive_the_conversatio
assert provider.started[0]["tools"] and json.loads(provider.results[0][0].content)["hostname"] == "alpha"
assert app.db.query(AgentRun).count() == 2
looked = app.db.query(AuditLog).filter(AuditLog.event_type == "agent_tool_call").one()
- assert (looked.user_id, looked.conversation_id, looked.task_title) == (1, "c1", "Why did it restart?")
+ assert (looked.user_id, looked.conversation_id, looked.task_title) == (1, "c1-u1", "Why did it restart?")
assert owner.get("/dashboard/summary").json()["agent_lookups"] == 1
- assert owner.delete("/conversations/c1").status_code == 200
+ assert owner.delete("/conversations/c1-u1").status_code == 200
kept = app.db.query(AuditLog).filter(AuditLog.event_type == "agent_tool_call").one()
assert kept.conversation_id is None
diff --git a/tests/security/test_second_review.py b/tests/security/test_second_review.py
index 20098ad..1fc08f5 100644
--- a/tests/security/test_second_review.py
+++ b/tests/security/test_second_review.py
@@ -173,9 +173,9 @@ def test_a_correct_password_below_the_limit_still_works_and_clears_the_count(app
def test_chat_messages_are_limited_per_user_per_hour(app):
client = sign_in(app)
- client.post("/conversations", json={"conversation_id": "c1"})
+ client.post("/conversations", json={"conversation_id": "c1-u1"})
- codes = [client.post("/agent/chat", json={"conversation_id": "c1", "message": f"hello {i}"}).status_code for i in range(main.CHAT_MESSAGE_LIMIT + 3)]
+ codes = [client.post("/agent/chat", json={"conversation_id": "c1-u1", "message": f"hello {i}"}).status_code for i in range(main.CHAT_MESSAGE_LIMIT + 3)]
assert codes[:main.CHAT_MESSAGE_LIMIT] == [200] * main.CHAT_MESSAGE_LIMIT and codes[-3:] == [429] * 3
@@ -184,7 +184,7 @@ def test_a_user_can_only_hold_so_many_conversations(app, monkeypatch):
monkeypatch.setattr(main, "MAX_CONVERSATIONS_PER_USER", 5)
monkeypatch.setattr(main, "CONVERSATION_CREATE_LIMIT", 10_000)
client = sign_in(app)
- codes = [client.post("/conversations", json={"conversation_id": f"c{i}"}).status_code for i in range(main.MAX_CONVERSATIONS_PER_USER + 3)]
+ codes = [client.post("/conversations", json={"conversation_id": f"c{i}-u1"}).status_code for i in range(main.MAX_CONVERSATIONS_PER_USER + 3)]
assert codes[:main.MAX_CONVERSATIONS_PER_USER] == [200] * main.MAX_CONVERSATIONS_PER_USER and set(codes[-3:]) <= {409, 429}
with app.Session() as db:
@@ -194,7 +194,7 @@ def test_a_user_can_only_hold_so_many_conversations(app, monkeypatch):
def test_creating_conversations_is_rate_limited_too(app, monkeypatch):
monkeypatch.setattr(main, "MAX_CONVERSATIONS_PER_USER", 10_000)
client = sign_in(app)
- codes = [client.post("/conversations", json={"conversation_id": f"c{i}"}).status_code for i in range(main.CONVERSATION_CREATE_LIMIT + 2)]
+ codes = [client.post("/conversations", json={"conversation_id": f"c{i}-u1"}).status_code for i in range(main.CONVERSATION_CREATE_LIMIT + 2)]
assert codes[-2:] == [429, 429]