Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

fix(chat): open and delete Google Chat chats from the web (#526)

Rufusb3600f197565
diff --git a/packages/core/openexecutive/api/path_ids.py b/packages/core/openexecutive/api/path_ids.py
new file mode 100644
index 00000000..bbe35c28
--- /dev/null
+++ b/packages/core/openexecutive/api/path_ids.py
@@ -0,0 +1,56 @@
+"""Chat ids that hold a slash, in a URL path.
+
+A Google Chat chat's id carries the space's name (``google_chat:spaces/AAQA…``,
+``…:spaces/AAQA…/threads/…``). Percent-encoded, that slash is decoded before
+routing, so ``/sessions/{session_id}`` never matches and the chat can't be
+opened, renamed or deleted. Such an id travels as one segment instead: ``~``
+and its base64url (the web proxy writes it, ``lib/proxySegments.ts``). A
+route reads it back with ``{session_id:session}``. Every other id passes
+through unchanged; none starts with ``~``.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import re
+
+from starlette.convertors import Convertor, register_url_convertor
+
+ENCODED_PREFIX = "~"
+_BASE64URL = re.compile(r"[A-Za-z0-9_-]+")
+
+
+def encode_path_id(value: str) -> str:
+ """The segment for ``value``: itself, or ``~`` + base64url when it holds a slash."""
+ if "/" not in value:
+ return value
+ raw = base64.urlsafe_b64encode(value.encode("utf-8")).decode("ascii").rstrip("=")
+ return ENCODED_PREFIX + raw
+
+
+def decode_path_id(segment: str) -> str:
+ """The id a path segment names. A ``~`` segment that isn't valid base64url
+ stays as it is, so it simply matches no chat."""
+ if not segment.startswith(ENCODED_PREFIX):
+ return segment
+ raw = segment[len(ENCODED_PREFIX):]
+ if not _BASE64URL.fullmatch(raw):
+ return segment
+ try:
+ return base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4)).decode("utf-8")
+ except (binascii.Error, UnicodeDecodeError, ValueError):
+ return segment
+
+
+class SessionIdConvertor(Convertor[str]):
+ regex = "[^/]+"
+
+ def convert(self, value: str) -> str:
+ return decode_path_id(value)
+
+ def to_string(self, value: str) -> str:
+ return encode_path_id(value)
+
+
+register_url_convertor("session", SessionIdConvertor())
diff --git a/packages/core/openexecutive/api/routes/audit.py b/packages/core/openexecutive/api/routes/audit.py
index 8140abb8..2f40625e 100644
--- a/packages/core/openexecutive/api/routes/audit.py
+++ b/packages/core/openexecutive/api/routes/audit.py
@@ -30,6 +30,7 @@ from typing import Any
from fastapi import APIRouter, HTTPException, Query, Request
from pydantic import BaseModel
+from openexecutive.api import path_ids # noqa: F401 (registers the {…:session} convertor)
from openexecutive.audit import AuditLogger, get_audit_logger
from openexecutive.audit.logger import EVENT_TYPES
@@ -663,7 +664,7 @@ def _compute_degradations(events: list[Any]) -> list[Degradation]:
@router.get(
- "/audit/sessions/{session_id}",
+ "/audit/sessions/{session_id:session}",
response_model=AuditSessionResponse,
)
def get_audit_session(session_id: str, request: Request) -> AuditSessionResponse:
diff --git a/packages/core/openexecutive/api/routes/sessions.py b/packages/core/openexecutive/api/routes/sessions.py
index 28f9c269..4e9e6cc7 100644
--- a/packages/core/openexecutive/api/routes/sessions.py
+++ b/packages/core/openexecutive/api/routes/sessions.py
@@ -11,7 +11,10 @@ from fastapi import APIRouter, HTTPException, Request, Response, status
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
-from openexecutive.api import chat_live
+from openexecutive.api import (
+ chat_live,
+ path_ids, # noqa: F401 (registers the {…:session} convertor)
+)
from openexecutive.api.models import SessionSummary
from openexecutive.api.routes import chat as chat_route
from openexecutive.api.routes.chat import (
@@ -261,7 +264,7 @@ def get_shared_sessions(request: Request) -> list[SessionSummary]:
return out
[email protected]("/sessions/{session_id}", response_model=SessionSummary, response_model_exclude_none=True)
[email protected]("/sessions/{session_id:session}", response_model=SessionSummary, response_model_exclude_none=True)
def get_session(session_id: str, request: Request) -> SessionSummary:
_, member = _require_chat_access(request, session_id)
meta = get_session_metadata(session_id)
@@ -278,7 +281,7 @@ def get_session(session_id: str, request: Request) -> SessionSummary:
return summary
[email protected]("/sessions/{session_id}/messages")
[email protected]("/sessions/{session_id:session}/messages")
def get_session_messages(session_id: str, request: Request) -> list[dict]:
"""The chat's messages. In a shared chat each person's message also says
who wrote it (``sender_person_id``, ``sender_name``)."""
@@ -316,7 +319,7 @@ class ChatPeople(BaseModel):
people: list[ChatPerson]
[email protected]("/sessions/{session_id}/people", response_model=ChatPeople)
[email protected]("/sessions/{session_id:session}/people", response_model=ChatPeople)
def get_session_people(session_id: str, request: Request) -> ChatPeople:
"""Everyone in the chat, its owner first, for anyone in it."""
caller, _ = _require_chat_access(request, session_id)
@@ -326,7 +329,7 @@ def get_session_people(session_id: str, request: Request) -> ChatPeople:
)
[email protected]("/sessions/{session_id}/typing", status_code=status.HTTP_204_NO_CONTENT)
[email protected]("/sessions/{session_id:session}/typing", status_code=status.HTTP_204_NO_CONTENT)
def post_session_typing(session_id: str, request: Request) -> Response:
"""Tell the others in a shared chat that the caller is writing. Sent at
most every couple of seconds while they type; a chat of one has nobody to
@@ -350,7 +353,7 @@ def _still_in(request: Request, session_id: str, caller: int | None, member: boo
return _session_access(request, session_id, caller) == "allowed"
[email protected]("/sessions/{session_id}/live")
[email protected]("/sessions/{session_id:session}/live")
async def live_session(session_id: str, request: Request) -> StreamingResponse:
"""The chat as it happens, for a page that has it open: someone's
message and the reply as it is written, who is typing, and who joined
@@ -415,7 +418,7 @@ class SessionUpdate(BaseModel):
topic_name: str | None = Field(default=None, min_length=1, max_length=chat_topics.MAX_TOPIC_CHARS)
[email protected]("/sessions/{session_id}", response_model=SessionSummary, response_model_exclude_none=True)
[email protected]("/sessions/{session_id:session}", response_model=SessionSummary, response_model_exclude_none=True)
def update_session(session_id: str, body: SessionUpdate, request: Request) -> SessionSummary:
"""The owner names their chat (the automatic title never replaces it
after) or pins it to the top of their list."""
@@ -468,14 +471,14 @@ def _share_list(session_id: str) -> list[ShareEntry]:
return out
[email protected]("/sessions/{session_id}/shares", response_model=list[ShareEntry])
[email protected]("/sessions/{session_id:session}/shares", response_model=list[ShareEntry])
def get_session_shares(session_id: str, request: Request) -> list[ShareEntry]:
"""Who the owner shared this chat with."""
_require_owner(request, session_id)
return _share_list(session_id)
[email protected]("/sessions/{session_id}/shares", response_model=list[ShareEntry])
[email protected]("/sessions/{session_id:session}/shares", response_model=list[ShareEntry])
def put_session_shares(session_id: str, body: SharesUpdate, request: Request) -> list[ShareEntry]:
"""Share the chat with exactly these team members, who then read it and
write in it with its owner. Only a chat started here: a chat app's
@@ -516,7 +519,7 @@ def put_session_shares(session_id: str, body: SharesUpdate, request: Request) ->
return _share_list(session_id)
[email protected]("/sessions/{session_id}/shares/me", status_code=status.HTTP_204_NO_CONTENT)
[email protected]("/sessions/{session_id:session}/shares/me", status_code=status.HTTP_204_NO_CONTENT)
def leave_session(session_id: str, request: Request) -> Response:
"""Leave a chat someone shared with the caller. It goes from their list;
its owner can add them again."""
@@ -539,7 +542,7 @@ def leave_session(session_id: str, request: Request) -> Response:
return Response(status_code=status.HTTP_204_NO_CONTENT)
[email protected]("/sessions/{session_id}/export")
[email protected]("/sessions/{session_id:session}/export")
def export_session(session_id: str, request: Request) -> Response:
"""The chat as a Markdown file, for anyone in it."""
_require_chat_access(request, session_id)
@@ -570,7 +573,7 @@ class RewindResponse(BaseModel):
message: str
[email protected]("/sessions/{session_id}/rewind", response_model=RewindResponse)
[email protected]("/sessions/{session_id:session}/rewind", response_model=RewindResponse)
async def rewind_session(session_id: str, body: RewindRequest, request: Request) -> RewindResponse:
"""Take back the chat's last turn so the owner can ask it again, as it
was (Try again) or edited. The page then sends the message as a normal
@@ -611,7 +614,7 @@ async def rewind_session(session_id: str, body: RewindRequest, request: Request)
return RewindResponse(message="\n\n".join(asked))
[email protected]("/sessions/{session_id}", status_code=status.HTTP_204_NO_CONTENT)
[email protected]("/sessions/{session_id:session}", status_code=status.HTTP_204_NO_CONTENT)
def delete_session_route(session_id: str, request: Request) -> Response:
_require_session_access(request, session_id)
deleted = delete_session(session_id)
@@ -631,7 +634,7 @@ class MessageFeedback(BaseModel):
@router.post(
- "/sessions/{session_id}/messages/{message_id}/feedback",
+ "/sessions/{session_id:session}/messages/{message_id}/feedback",
status_code=status.HTTP_204_NO_CONTENT,
)
def post_message_feedback(
@@ -684,7 +687,7 @@ _FOLLOWUP_CACHE_MAX = 512
_followup_cache: dict[tuple[str, int], tuple[float, str]] = {}
[email protected]("/sessions/{session_id}/followup")
[email protected]("/sessions/{session_id:session}/followup")
async def get_followup_suggestion(session_id: str, request: Request) -> dict[str, Any]:
"""One suggested next message for the chat composer.
diff --git a/packages/core/tests/unit/test_path_ids.py b/packages/core/tests/unit/test_path_ids.py
new file mode 100644
index 00000000..545c069d
--- /dev/null
+++ b/packages/core/tests/unit/test_path_ids.py
@@ -0,0 +1,38 @@
+"""Chat ids that hold a slash travel as one path segment (api/path_ids.py)."""
+from __future__ import annotations
+
+import pytest
+
+from openexecutive.api.path_ids import decode_path_id, encode_path_id
+
+
+ "sid",
+ [
+ "google_chat:spaces/6U3LSqAAAAE~6",
+ "google_chat:spaces/AAQAU-9BHIY:spaces/AAQAU-9BHIY/threads/-C-x6xYbH6U",
+ "a/é/b",
+ ],
+)
+def test_slashed_ids_round_trip(sid: str) -> None:
+ segment = encode_path_id(sid)
+ assert segment.startswith("~")
+ assert "/" not in segment and "=" not in segment
+ assert decode_path_id(segment) == sid
+
+
[email protected]("sid", ["4b43cebb-8031-4187-a0d1-43801fb9b22b", "telegram:42", "slack:dm:U1"])
+def test_other_ids_pass_through(sid: str) -> None:
+ assert encode_path_id(sid) == sid
+ assert decode_path_id(sid) == sid
+
+
+def test_matches_the_web_proxy() -> None:
+ # packages/ui/src/lib/proxySegments.ts: "~" + Buffer.toString("base64url").
+ assert encode_path_id("google_chat:spaces/AAQA") == "~Z29vZ2xlX2NoYXQ6c3BhY2VzL0FBUUE"
+
+
+def test_a_bad_encoded_segment_stays_as_is() -> None:
+ assert decode_path_id("~not base64!") == "~not base64!"
+ assert decode_path_id("~/w") == "~/w"
+ assert decode_path_id("~a!b") == "~a!b"
diff --git a/packages/core/tests/unit/test_sessions_route_delete.py b/packages/core/tests/unit/test_sessions_route_delete.py
index e2829d77..be5d64f1 100644
--- a/packages/core/tests/unit/test_sessions_route_delete.py
+++ b/packages/core/tests/unit/test_sessions_route_delete.py
@@ -46,3 +46,21 @@ def test_delete_session_success(client: TestClient) -> None:
def test_delete_session_not_found(client: TestClient) -> None:
resp = client.delete("/sessions/does-not-exist")
assert resp.status_code == 404
+
+
+def test_a_chat_whose_id_holds_a_slash_opens_and_deletes(client: TestClient) -> None:
+ # A Google Chat chat's id carries the space's name. The web proxy sends it
+ # as `~` + base64url (api/path_ids.py); a `%2F` never routes.
+ from openexecutive.api.path_ids import encode_path_id
+
+ principal_id = people_store.upsert_person(full_name="Alex", is_principal=True)
+ sid = "google_chat:spaces/AAQA~6"
+ session_store.create_session(sid, "Offers", "2024-01-01T00:00:00", caller_person_id=principal_id)
+ session_store.save_message(sid, "user", "hi")
+ segment = encode_path_id(sid)
+ assert "/" not in segment
+
+ assert client.get(f"/sessions/{segment}").json()["session_id"] == sid
+ assert [m["content"] for m in client.get(f"/sessions/{segment}/messages").json()] == ["hi"]
+ assert client.delete(f"/sessions/{segment}").status_code == 204
+ assert session_store.get_session_metadata(sid) is None
diff --git a/packages/ui/scripts/proxySegments.test.mjs b/packages/ui/scripts/proxySegments.test.mjs
new file mode 100644
index 00000000..527dd178
--- /dev/null
+++ b/packages/ui/scripts/proxySegments.test.mjs
@@ -0,0 +1,21 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { upstreamSegment } from "../src/lib/proxySegments.ts";
+
+test("ordinary segments go on unchanged", () => {
+ assert.equal(upstreamSegment("sessions"), "sessions");
+ assert.equal(upstreamSegment("telegram:42"), "telegram:42");
+});
+
+test("an id holding a slash goes on as one base64url segment", () => {
+ const id = "google_chat:spaces/AAQA:spaces/AAQA/threads/x1";
+ const out = upstreamSegment(id);
+ assert.ok(out.startsWith("~"));
+ assert.match(out.slice(1), /^[A-Za-z0-9_-]+$/);
+ assert.equal(Buffer.from(out.slice(1), "base64url").toString("utf8"), id);
+});
+
+test("a slashed segment can't walk out of the path", () => {
+ const out = upstreamSegment("../../auth/accounts");
+ assert.ok(!out.includes("/") && !out.includes("."));
+});
diff --git a/packages/ui/src/app/api/backend/[...path]/route.ts b/packages/ui/src/app/api/backend/[...path]/route.ts
index 7458454d..ffc5b5cb 100644
--- a/packages/ui/src/app/api/backend/[...path]/route.ts
+++ b/packages/ui/src/app/api/backend/[...path]/route.ts
@@ -8,6 +8,7 @@ import {
} from "@/lib/callerAssertion";
import { isCrossSiteWrite } from "@/lib/crossSite";
import { localLoginSessionAllowed } from "@/lib/localLogin";
+import { upstreamSegment } from "@/lib/proxySegments";
// Streaming-aware proxy to the FastAPI backend. Replaces the `rewrites()` rule
// in next.config.ts, which buffers SSE responses in dev so the chat stream
@@ -70,7 +71,8 @@ async function proxy(req: NextRequest, params: { path: string[] }): Promise<Resp
});
}
- const path = params.path.join("/");
+ // An id holding a slash goes on as one segment (proxySegments.ts).
+ const path = params.path.map(upstreamSegment).join("/");
const url = new URL(`${BACKEND_BASE}/${path}`);
// Preserve query string.
req.nextUrl.searchParams.forEach((v, k) => url.searchParams.append(k, v));
diff --git a/packages/ui/src/lib/proxySegments.ts b/packages/ui/src/lib/proxySegments.ts
new file mode 100644
index 00000000..7fa391c0
--- /dev/null
+++ b/packages/ui/src/lib/proxySegments.ts
@@ -0,0 +1,14 @@
+// How the backend proxy (app/api/backend/[...path]) forwards each path
+// segment. Kept apart from the route so the rule can be tested.
+
+/** The segment to send upstream. Next.js hands the segments decoded, so an id
+ * the caller sent with `%2F` (a Google Chat chat, `google_chat:spaces/…`)
+ * arrives holding a slash and, joined back, would become several segments
+ * that route nowhere. It goes on as one opaque segment instead: `~` and its
+ * base64url, which the API reads back (`api/path_ids.py`). */
+export function upstreamSegment(segment: string): string {
+ if (segment.includes("/")) {
+ return "~" + Buffer.from(segment, "utf8").toString("base64url");
+ }
+ return segment;
+}