mirror of
https://github.com/hansjone/oclaw.git
synced 2026-10-11 00:43:18 +08:00
Harden attachment access controls and stabilize the Weixin bridge.
This persists referenced media safely, adds explicit attachment ACL/backfill flows, and fixes the Weixin sidecar so official login state can bridge reliably into oclaw without duplicate replays or dropped replies. Made-with: Cursor
This commit is contained in:
parent
6cfaff06f6
commit
31e3962c74
22 changed files with 1885 additions and 55 deletions
97
tests/test_attachment_acl_backfill.py
Normal file
97
tests/test_attachment_acl_backfill.py
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from oclaw.interfaces.http.fastapi_app import create_app
|
||||
from oclaw.platform.files.attachment_assets import AttachmentAssetStore
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
|
||||
def _pw_hash(pw: str) -> str:
|
||||
return hashlib.sha256(pw.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
class AttachmentAclBackfillTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
|
||||
self.db = Path(self._tmp.name) / "ops.sqlite"
|
||||
os.environ["OPS_ASSISTANT_DB_PATH"] = str(self.db)
|
||||
os.environ["OPS_ASSISTANT_PASSWORD"] = "test-admin-pass"
|
||||
store = SqliteStore(str(self.db))
|
||||
t = store.create_tenant("Team")
|
||||
self.tenant_id = str(t["id"])
|
||||
store.create_user_account(
|
||||
tenant_id=self.tenant_id,
|
||||
username="administrator",
|
||||
display_name="Admin",
|
||||
role="owner",
|
||||
password_hash=_pw_hash("test-admin-pass"),
|
||||
is_active=True,
|
||||
)
|
||||
store.create_user_account(
|
||||
tenant_id=self.tenant_id,
|
||||
username="alice",
|
||||
display_name="Alice",
|
||||
role="member",
|
||||
password_hash=_pw_hash("alice-pass"),
|
||||
is_active=True,
|
||||
)
|
||||
self.alice_id = str(store.get_user_by_username(tenant_id=self.tenant_id, username="alice")["id"])
|
||||
self.client = TestClient(create_app())
|
||||
self.client.post("/admin/api/auth/bootstrap", json={})
|
||||
tok = self.client.post(
|
||||
"/admin/api/auth/login",
|
||||
json={"tenant_id": self.tenant_id, "username": "alice", "password": "alice-pass", "purpose": "chat"},
|
||||
).json()
|
||||
self.token = str(tok.get("token") or "")
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self._tmp.cleanup()
|
||||
|
||||
def _h(self) -> dict[str, str]:
|
||||
return {"authorization": f"Bearer {self.token}"}
|
||||
|
||||
def test_backfill_enables_strict_acl_download(self) -> None:
|
||||
store = SqliteStore(str(self.db))
|
||||
sess = store.create_session_for_user(title="t", tenant_id=self.tenant_id, user_id=self.alice_id)
|
||||
ast = AttachmentAssetStore()
|
||||
blob = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==")
|
||||
meta = ast.save_bytes(blob, filename="x.png", mime="image/png")
|
||||
aid = str(meta.attachment_id or "").strip()
|
||||
store.add_message(
|
||||
session_id=str(sess.id),
|
||||
role="assistant",
|
||||
content="here",
|
||||
attachments=[{"type": "image_ref", "attachment_id": aid, "mime": "image/png", "name": "x.png"}],
|
||||
)
|
||||
|
||||
prev = os.environ.get("AIA_ATTACHMENT_ACL_STRICT")
|
||||
os.environ["AIA_ATTACHMENT_ACL_STRICT"] = "1"
|
||||
try:
|
||||
# Strict mode: without backfill, this should be forbidden (not avatar).
|
||||
r0 = self.client.get(f"/admin/api/chat/attachments/{aid}", headers=self._h())
|
||||
self.assertEqual(r0.status_code, 403, r0.text)
|
||||
|
||||
# Backfill ACL for tenant, then strict download should succeed.
|
||||
res = store.backfill_attachment_acl_from_messages(tenant_id=self.tenant_id, limit_messages=5000)
|
||||
self.assertTrue(res.get("ok"), res)
|
||||
r1 = self.client.get(f"/admin/api/chat/attachments/{aid}", headers=self._h())
|
||||
self.assertEqual(r1.status_code, 200, r1.text)
|
||||
self.assertTrue(len(r1.content) > 10)
|
||||
finally:
|
||||
if prev is None:
|
||||
os.environ.pop("AIA_ATTACHMENT_ACL_STRICT", None)
|
||||
else:
|
||||
os.environ["AIA_ATTACHMENT_ACL_STRICT"] = prev
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
|
@ -47,6 +47,25 @@ class ChatProfileApiTests(unittest.TestCase):
|
|||
)
|
||||
self.assertEqual(resp.status_code, 200, resp.text)
|
||||
self.token = str(resp.json().get("token") or "")
|
||||
store.create_user_account(
|
||||
tenant_id=self.tenant_id,
|
||||
username="alice",
|
||||
display_name="Alice",
|
||||
role="member",
|
||||
password_hash=hashlib.sha256("alice-pass".encode("utf-8")).hexdigest(),
|
||||
is_active=True,
|
||||
)
|
||||
resp_alice = self.client.post(
|
||||
"/admin/api/auth/login",
|
||||
json={
|
||||
"tenant_id": self.tenant_id,
|
||||
"username": "alice",
|
||||
"password": "alice-pass",
|
||||
"purpose": "console",
|
||||
},
|
||||
)
|
||||
self.assertEqual(resp_alice.status_code, 200, resp_alice.text)
|
||||
self.alice_token = str(resp_alice.json().get("token") or "")
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self._tmp.cleanup()
|
||||
|
|
@ -54,6 +73,9 @@ class ChatProfileApiTests(unittest.TestCase):
|
|||
def _h(self) -> dict[str, str]:
|
||||
return {"authorization": f"Bearer {self.token}"}
|
||||
|
||||
def _h_alice(self) -> dict[str, str]:
|
||||
return {"authorization": f"Bearer {self.alice_token}"}
|
||||
|
||||
def test_profile_get_patch_avatar_delete(self) -> None:
|
||||
g = self.client.get("/admin/api/chat/profile", headers=self._h())
|
||||
self.assertEqual(g.status_code, 200, g.text)
|
||||
|
|
@ -92,6 +114,50 @@ class ChatProfileApiTests(unittest.TestCase):
|
|||
g3 = self.client.get("/admin/api/chat/profile", headers=self._h())
|
||||
self.assertFalse((g3.json().get("profile") or {}).get("avatar_attachment_id"))
|
||||
|
||||
def test_attachment_endpoint_rejects_invalid_attachment_id(self) -> None:
|
||||
r = self.client.get("/admin/api/chat/attachments/not-a-valid-id", headers=self._h())
|
||||
self.assertEqual(r.status_code, 400, r.text)
|
||||
self.assertEqual((r.json() or {}).get("detail"), "attachment_id_invalid")
|
||||
|
||||
def test_attachment_endpoint_forbids_unowned_attachment(self) -> None:
|
||||
up = self.client.post(
|
||||
"/admin/api/chat/profile/avatar",
|
||||
files={"file": ("x.png", MINI_PNG, "image/png")},
|
||||
headers=self._h(),
|
||||
)
|
||||
self.assertEqual(up.status_code, 200, up.text)
|
||||
aid = str((up.json() or {}).get("avatar_attachment_id") or "").strip()
|
||||
self.assertTrue(aid)
|
||||
|
||||
me = self.client.get(f"/admin/api/chat/attachments/{aid}", headers=self._h())
|
||||
self.assertEqual(me.status_code, 200, me.text)
|
||||
|
||||
other = self.client.get(f"/admin/api/chat/attachments/{aid}", headers=self._h_alice())
|
||||
self.assertEqual(other.status_code, 403, other.text)
|
||||
self.assertEqual((other.json() or {}).get("detail"), "attachment_forbidden")
|
||||
|
||||
def test_attachment_acl_strict_requires_backfill_or_acl(self) -> None:
|
||||
prev = os.environ.get("AIA_ATTACHMENT_ACL_STRICT")
|
||||
os.environ["AIA_ATTACHMENT_ACL_STRICT"] = "1"
|
||||
try:
|
||||
# Upload an avatar (this is not linked into ACL; access is via avatar_attachment_id).
|
||||
up = self.client.post(
|
||||
"/admin/api/chat/profile/avatar",
|
||||
files={"file": ("x.png", MINI_PNG, "image/png")},
|
||||
headers=self._h(),
|
||||
)
|
||||
self.assertEqual(up.status_code, 200, up.text)
|
||||
aid = str((up.json() or {}).get("avatar_attachment_id") or "").strip()
|
||||
self.assertTrue(aid)
|
||||
# Avatar download remains allowed under strict mode.
|
||||
att = self.client.get(f"/admin/api/chat/attachments/{aid}", headers=self._h())
|
||||
self.assertEqual(att.status_code, 200, att.text)
|
||||
finally:
|
||||
if prev is None:
|
||||
os.environ.pop("AIA_ATTACHMENT_ACL_STRICT", None)
|
||||
else:
|
||||
os.environ["AIA_ATTACHMENT_ACL_STRICT"] = prev
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
|
||||
from oclaw.runtime.chat.media_redact import ingest_embedded_image_blobs_as_refs, redact_embedded_image_blobs
|
||||
|
||||
|
|
@ -42,3 +43,22 @@ def test_ingest_embedded_binary_blob_as_binary_ref(tmp_path) -> None:
|
|||
assert str(block.get("attachment_id") or "")
|
||||
assert "base64" not in block
|
||||
assert refs and refs[0]["attachment_id"] == block["attachment_id"]
|
||||
|
||||
|
||||
def test_ingest_rejects_oversized_blob_by_env_limit(tmp_path) -> None:
|
||||
prev = os.environ.get("AIA_MAX_ATTACHMENT_BYTES")
|
||||
os.environ["AIA_MAX_ATTACHMENT_BYTES"] = "4"
|
||||
try:
|
||||
raw = base64.b64encode(b"12345").decode("ascii")
|
||||
obj = {"result": {"content": [{"type": "file", "mime": "application/octet-stream", "base64": raw, "name": "x.bin"}]}}
|
||||
out, refs = ingest_embedded_image_blobs_as_refs(obj, root_dir=str(tmp_path), filename_prefix="unit")
|
||||
finally:
|
||||
if prev is None:
|
||||
os.environ.pop("AIA_MAX_ATTACHMENT_BYTES", None)
|
||||
else:
|
||||
os.environ["AIA_MAX_ATTACHMENT_BYTES"] = prev
|
||||
block = out["result"]["content"][0]
|
||||
assert block["type"] == "binary_ref"
|
||||
assert block.get("error") == "attachment_too_large"
|
||||
assert int(block.get("actual_bytes") or 0) >= 5
|
||||
assert refs == []
|
||||
|
|
|
|||
84
tests/test_weixin_ilink_api.py
Normal file
84
tests/test_weixin_ilink_api.py
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from oclaw.interfaces.http.fastapi_app import create_app
|
||||
from oclaw.interfaces.http import weixin_ilink_api
|
||||
|
||||
|
||||
class WeixinIlinkApiTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.client = TestClient(create_app())
|
||||
self.headers = {
|
||||
"AuthorizationType": "ilink_bot_token",
|
||||
"Authorization": "Bearer test-ilink-token",
|
||||
}
|
||||
|
||||
def test_sendmessage_requires_account_id(self) -> None:
|
||||
r = self.client.post(
|
||||
"/ilink/bot/sendmessage",
|
||||
headers=self.headers,
|
||||
json={
|
||||
"channel": "wechat",
|
||||
"user_id": "wxid_u1",
|
||||
"text": "hello",
|
||||
},
|
||||
)
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
self.assertEqual((r.json() or {}).get("ret"), 400)
|
||||
|
||||
def test_sendmessage_enqueues_reply_for_getupdates(self) -> None:
|
||||
old_usecase = weixin_ilink_api.process_inbound_payload_usecase
|
||||
|
||||
def _fake_usecase(payload: dict[str, object]) -> dict[str, object]:
|
||||
text = str(payload.get("text") or "")
|
||||
return {
|
||||
"ok": True,
|
||||
"replies": [
|
||||
{
|
||||
"chat_id": str(payload.get("chat_id") or ""),
|
||||
"text": f"echo:{text}",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
try:
|
||||
weixin_ilink_api.process_inbound_payload_usecase = _fake_usecase # type: ignore[assignment]
|
||||
s = self.client.post(
|
||||
"/ilink/bot/sendmessage",
|
||||
headers=self.headers,
|
||||
json={
|
||||
"channel": "wechat",
|
||||
"account_id": "bot-1",
|
||||
"user_id": "wxid_u2",
|
||||
"chat_id": "room_1",
|
||||
"text": "ping",
|
||||
},
|
||||
)
|
||||
self.assertEqual(s.status_code, 200, s.text)
|
||||
self.assertEqual((s.json() or {}).get("ret"), 0)
|
||||
|
||||
g = self.client.post(
|
||||
"/ilink/bot/getupdates",
|
||||
headers=self.headers,
|
||||
json={
|
||||
"channel": "wechat",
|
||||
"account_id": "bot-1",
|
||||
"get_updates_buf": "0",
|
||||
"longpolling_timeout_ms": 1000,
|
||||
},
|
||||
)
|
||||
self.assertEqual(g.status_code, 200, g.text)
|
||||
data = g.json() or {}
|
||||
self.assertEqual(data.get("ret"), 0)
|
||||
msgs = data.get("msgs") if isinstance(data.get("msgs"), list) else []
|
||||
self.assertTrue(msgs, data)
|
||||
self.assertEqual(str((msgs[0] or {}).get("text") or ""), "echo:ping")
|
||||
finally:
|
||||
weixin_ilink_api.process_inbound_payload_usecase = old_usecase # type: ignore[assignment]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Add table
Add a link
Reference in a new issue