{"id":"XE-0032","kind":"bounty","visibility":"public","source":"github","source_repo":"xeprotocol/xe","source_ref":"49","source_url":"https://github.com/xeprotocol/xe/issues/49","reporter_id":13,"title":"dao/api: unauthenticated inbox POST serializes every DAO write behind one hash-chain lock (High)","area":"dao-harness","claimed_tier":"high","assessed_tier":"high","verdict":"valid","duplicate_of":null,"tracked":true,"internal_ref":"#1071","internal_url":"https://github.com/xeprotocol/core/issues/1071","status":"awarded","closed_reason":null,"github_state":"open","disclosed_at":null,"award_xe":6000000000,"award_approved":true,"paid_ref":"","created_at":"2026-10-29T13:57:16.757240+00:00","updated_at":"2026-11-10T00:11:26.101028+00:00","source_created_at":"2026-10-25T11:12:19+00:00","told_at":"2026-10-30T08:21:57+00:00","status_changed_at":"2026-11-03T19:42:01.857184+00:00","url":"https://bounty.xe.network/XE-0032","body":"## Summary\nThe DAO HTTP inbox endpoint requires only a signed request (any generated key) and performs no proof of work and no rate limiting, while every accepted message appends a public event to the hash-chained log under a row-level lock on the single log head row. Votes, fee settlement, session submission and worker jobs all append through the same lock. One client generating keys and posting messages as fast as the API accepts serializes all DAO writes for everyone.\n\n## Affected component\ndao/api/public.py, inbox_post at lines 190 to 195; dao/services/inbox.py, http_submit at lines 63 to 74 (pow_nonce=0); dao/log.py, append path with SELECT FOR UPDATE on log head at lines 53 to 56; no rate limiter exists anywhere in the dao tree, at dao commit c60cf81522e3eb9e258b353e77164a3f7634cd98.\n\n## Impact\nOne client with a key generation loop holds the single log-head lock continuously: every DAO write (vote receipt, fee settle, session submit) queues behind it, and the SSE event fanout amplifies the flood to all subscribers. This is an application-layer lock on the DAO, not the ledger, and not hosting-layer volumetric DDoS.\n\nSuggested severity: High (degradation one client can cause). Confirmed by read-only source review at the dao pin.\n\n## PoC\n## Scope note\nThe dao service is the governance backend named in the program's \"state chain and multisig governance\" scope row; flagging that the dao repository itself is not separately named on the bounty page.\n\n**Script** (clone the dao repository as a sibling checkout directory and adjust the path line inside the script if your layout differs):\n\n```python\n#!/usr/bin/env python3\n\"\"\"F15: unauthenticated DAO inbox POST serializes every DAO write on log_head.\n\nPOST /v1/inbox (ws/dao/dao/api/public.py) calls inbox.http_submit, which\nappends inbox.received through EventLog.append. append takes\nSELECT log_head ... FOR UPDATE on the single id=1 row (ws/dao/dao/log.py).\nVotes, fees, sessions, pause, and worker jobs append through the same lock.\n\nSQLite's compiler drops FOR UPDATE, so this harness keeps a clean in-process\nsession fake (same style as poc/f21_unfinalized_fee.py) that honours the\nstatement's _for_update_arg until commit — the Postgres row-lock lifetime.\nN unique signed inbox submits plus one concurrent vote.cast all go through\nthe real EventLog.append / http_submit / verify_signed path.\n\"\"\"\nfrom __future__ import annotations\n\nimport asyncio\nimport os\nimport sys\nimport time\nfrom dataclasses import dataclass, field\nfrom types import SimpleNamespace\n\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), \"..\", \"ws\", \"dao\"))\n\nfrom sqlalchemy import select\nfrom sqlalchemy.dialects import postgresql\n\nfrom dao.auth import SignedRequest, verify_signed\nfrom dao.canonical import DOMAIN_INBOX_HTTP, digest\nfrom dao.log import ZERO, EventLog, event_hash\nfrom dao.models import Event, InboxMessage, LogHead\nfrom dao.services.inbox import http_submit\nfrom dao.signer import Signer\nfrom xe.keys import KeyPair\n\nN_INBOX = 8\nHOLD_S = 0.03  # keep the txn (and therefore the row lock) open after append\n\n\ndef _entity(stmt):\n    descs = getattr(stmt, \"column_descriptions\", None) or []\n    if not descs:\n        return None\n    return descs[0].get(\"entity\")\n\n\ndef _pg_sql(stmt) -> str:\n    return str(stmt.compile(dialect=postgresql.dialect()))\n\n\nclass FakeResult:\n    def __init__(self, rows):\n        self._rows = list(rows)\n\n    def scalar_one(self):\n        if len(self._rows) != 1:\n            raise RuntimeError(f\"scalar_one expected 1 row, got {len(self._rows)}\")\n        return self._rows[0]\n\n    def scalar_one_or_none(self):\n        return self._rows[0] if self._rows else None\n\n    def scalars(self):\n        return self\n\n    def all(self):\n        return list(self._rows)\n\n    def first(self):\n        return self._rows[0] if self._rows else None\n\n\n@dataclass\nclass Hold:\n    role: str\n    idx: int\n    wait_s: float\n    acquired_at: float\n    released_at: float | None = None\n    sql: str = \"\"\n\n\n@dataclass\nclass Store:\n    n_inbox: int\n    lock: asyncio.Lock = field(default_factory=asyncio.Lock)\n    head: LogHead = field(default_factory=lambda: LogHead(id=1, index=-1, hash=ZERO))\n    events: list[Event] = field(default_factory=list)\n    inbox: list[InboxMessage] = field(default_factory=list)\n    holds: list[Hold] = field(default_factory=list)\n    inbox_attempts: int = 0\n    all_inbox_attempted: asyncio.Event = field(default_factory=asyncio.Event)\n    vote_waiting: asyncio.Event = field(default_factory=asyncio.Event)\n    active_holders: int = 0\n    max_holders: int = 0\n\n\nclass FakeSession:\n    \"\"\"Minimal AsyncSession: SELECT FOR UPDATE on log_head held until commit.\"\"\"\n\n    def __init__(self, store: Store, role: str, idx: int):\n        self.store = store\n        self.role = role\n        self.idx = idx\n        self._hold: Hold | None = None\n\n    def add(self, obj) -> None:\n        if isinstance(obj, Event):\n            self.store.events.append(obj)\n        elif isinstance(obj, InboxMessage):\n            self.store.inbox.append(obj)\n        else:\n            raise TypeError(f\"unexpected add({type(obj)!r})\")\n\n    async def flush(self) -> None:\n        return None\n\n    async def execute(self, stmt):\n        entity = _entity(stmt)\n        for_update = getattr(stmt, \"_for_update_arg\", None) is not None\n        if entity is LogHead:\n            if for_update:\n                sql = _pg_sql(stmt)\n                if self.role == \"inbox\":\n                    self.store.inbox_attempts += 1\n                    if self.store.inbox_attempts >= self.store.n_inbox:\n                        self.store.all_inbox_attempted.set()\n                else:\n                    await self.store.all_inbox_attempted.wait()\n                    self.store.vote_waiting.set()\n                t0 = time.perf_counter()\n                await self.store.lock.acquire()\n                wait_s = time.perf_counter() - t0\n                if self.role == \"inbox\":\n                    await self.store.vote_waiting.wait()\n                self.store.active_holders += 1\n                self.store.max_holders = max(self.store.max_holders, self.store.active_holders)\n                self._hold = Hold(self.role, self.idx, wait_s, time.perf_counter(), sql=sql)\n                self.store.holds.append(self._hold)\n            return FakeResult([self.store.head])\n        if entity is Event:\n            return FakeResult(sorted(self.store.events, key=lambda e: e.index))\n        raise AssertionError(f\"unexpected execute entity={entity} stmt={stmt}\")\n\n    def _release(self) -> None:\n        if self._hold is None:\n            return\n        self._hold.released_at = time.perf_counter()\n        self.store.active_holders -= 1\n        self.store.lock.release()\n        self._hold = None\n\n    async def commit(self) -> None:\n        self._release()\n\n    async def rollback(self) -> None:\n        self._release()\n\n\ndef sign_inbox(i: int) -> tuple[KeyPair, object]:\n    kp = KeyPair.generate()\n    payload = {\"message\": f\"f15-inbox-{i}-{kp.pub_key_hex[:12]}\"}\n    ts = time.time_ns()\n    sig = kp.sign_hex(digest(DOMAIN_INBOX_HTTP, {\"payload\": payload, \"timestamp\": ts}))\n    req = SignedRequest(payload=payload, timestamp=ts, pub_key=kp.pub_key_hex, signature=sig)\n    v = verify_signed(req, DOMAIN_INBOX_HTTP)\n    return kp, v\n\n\ndef chain_ok(events: list[Event]) -> bool:\n    prev = ZERO\n    for i, ev in enumerate(sorted(events, key=lambda e: e.index)):\n        if ev.index != i or ev.prev_hash != prev:\n            return False\n        if event_hash(ev.index, ev.ts, ev.kind, ev.actor, ev.payload, ev.prev_hash) != ev.hash:\n            return False\n        prev = ev.hash\n    return True\n\n\ndef holds_overlap(holds: list[Hold]) -> bool:\n    iv = []\n    for h in holds:\n        if h.released_at is None:\n            return True\n        iv.append((h.acquired_at, h.released_at))\n    iv.sort()\n    for (a0, a1), (b0, b1) in zip(iv, iv[1:]):\n        if b0 < a1:\n            return True\n    return False\n\n\nasync def inbox_task(store: Store, ctx, i: int) -> dict:\n    db = FakeSession(store, \"inbox\", i)\n    try:\n        _kp, v = sign_inbox(i)\n        t0 = time.perf_counter()\n        m = await http_submit(ctx, db, v)\n        appended = time.perf_counter()\n        await asyncio.sleep(HOLD_S)\n        await db.commit()\n        return {\n            \"role\": \"inbox\",\n            \"idx\": i,\n            \"id\": m.id,\n            \"sig\": v.signature,\n            \"pub\": v.pub_key,\n            \"pow_nonce\": m.pow_nonce,\n            \"submit_s\": appended - t0,\n            \"actor\": v.actor,\n        }\n    except Exception:\n        await db.rollback()\n        raise\n\n\nasync def vote_task(store: Store, ctx) -> dict:\n    db = FakeSession(store, \"vote\", 0)\n    try:\n        t0 = time.perf_counter()\n        ev = await ctx.events.append(\n            db,\n            \"vote.cast\",\n            \"account:voter\",\n            {\"proposal\": \"ab\" * 32, \"choice\": \"for\", \"weight\": 0},\n            ref=\"proposal:f15\",\n        )\n        appended = time.perf_counter()\n        await db.commit()\n        return {\n            \"role\": \"vote\",\n            \"index\": ev.index,\n            \"kind\": ev.kind,\n            \"append_s\": appended - t0,\n        }\n    except Exception:\n        await db.rollback()\n        raise\n\n\nasync def run() -> int:\n    store = Store(n_inbox=N_INBOX)\n    signer = Signer.empty()\n    ctx = SimpleNamespace(\n        signer=signer,\n        events=EventLog(signer),\n        config=SimpleNamespace(accounts={\"dao\": \"dd\" * 32, \"fee\": \"ff\" * 32}),\n    )\n\n    demo = select(LogHead).where(LogHead.id == 1).with_for_update()\n    print(f\"log_head FOR UPDATE (postgresql): {_pg_sql(demo)}\")\n    print(f\"sqlite compiler drops FOR UPDATE (so this fake holds the row lock until commit)\")\n    print(f\"N_INBOX={N_INBOX} HOLD_S={HOLD_S} (txn held after inbox.http_submit, before commit)\")\n\n    inbox_futs = [asyncio.create_task(inbox_task(store, ctx, i)) for i in range(N_INBOX)]\n    vote_fut = asyncio.create_task(vote_task(store, ctx))\n    inbox_rows, vote = await asyncio.wait_for(\n        asyncio.gather(asyncio.gather(*inbox_futs), vote_fut),\n        timeout=10,\n    )\n\n    sigs = {r[\"sig\"] for r in inbox_rows}\n    ids = {r[\"id\"] for r in inbox_rows}\n    pubs = {r[\"pub\"] for r in inbox_rows}\n    pows = {r[\"pow_nonce\"] for r in inbox_rows}\n    kinds = [e.kind for e in sorted(store.events, key=lambda e: e.index)]\n    vote_hold = next(h for h in store.holds if h.role == \"vote\")\n    inbox_holds = [h for h in store.holds if h.role == \"inbox\"]\n    overlap = holds_overlap(store.holds)\n    ok_chain = chain_ok(store.events)\n    vote_last = kinds[-1] == \"vote.cast\" and vote[\"index\"] == N_INBOX\n    expected_wait = HOLD_S * N_INBOX * 0.5\n\n    print(\n        f\"inbox_n={len(inbox_rows)} unique_sigs={len(sigs)} unique_ids={len(ids)} \"\n        f\"unique_pubkeys={len(pubs)} pow_nonce={pows}\"\n    )\n    print(\n        f\"lock_acquires={len(store.holds)} max_concurrent_holders={store.max_holders} \"\n        f\"overlap={overlap}\"\n    )\n    print(\n        f\"inbox_lock_wait_s={[round(h.wait_s, 4) for h in inbox_holds]} \"\n        f\"inbox_hold_s={[round((h.released_at or 0) - h.acquired_at, 4) for h in inbox_holds]}\"\n    )\n    print(\n        f\"vote_lock_wait_s={vote_hold.wait_s:.4f} vote_event_index={vote['index']} \"\n        f\"vote_last={vote_last} expected_wait_gt={expected_wait:.3f}\"\n    )\n    print(f\"kinds={kinds}\")\n    print(\n        f\"chain_ok={ok_chain} head_index={store.head.index} head_hash={store.head.hash[:16]}... \"\n        f\"n_events={len(store.events)} n_inbox_rows={len(store.inbox)}\"\n    )\n    print(f\"for_update_sql_seen={inbox_holds[0].sql!r}\")\n\n    pass_ok = (\n        len(inbox_rows) == N_INBOX\n        and len(sigs) == N_INBOX\n        and len(ids) == N_INBOX\n        and len(pubs) == N_INBOX\n        and pows == {0}\n        and store.max_holders == 1\n        and len(store.holds) == N_INBOX + 1\n        and not overlap\n        and vote_hold.wait_s >= expected_wait\n        and vote_last\n        and kinds.count(\"inbox.received\") == N_INBOX\n        and kinds.count(\"vote.cast\") == 1\n        and ok_chain\n        and store.head.index == N_INBOX\n        and \"FOR UPDATE\" in inbox_holds[0].sql\n        and \"log_head\" in inbox_holds[0].sql\n    )\n    if pass_ok:\n        print(\n            \"PASS: F15 N unique signed inbox POSTs serialize on log_head FOR UPDATE; \"\n            \"vote append queued behind them\"\n        )\n        return 0\n    print(\"FAIL: F15 expected one log_head lock, unique inbox appends, and a queued vote\")\n    return 1\n\n\nif __name__ == \"__main__\":\n    raise SystemExit(asyncio.run(run()))\n```\n\n**Run** (run 1 of 5 consecutive runs, 5/5 PASS, exit 0):\n\n```\nlog_head FOR UPDATE (postgresql): SELECT log_head.id, log_head.index, log_head.hash \nFROM log_head \nWHERE log_head.id = %(id_1)s FOR UPDATE\nsqlite compiler drops FOR UPDATE (so this fake holds the row lock until commit)\nN_INBOX=8 HOLD_S=0.03 (txn held after inbox.http_submit, before commit)\ninbox_n=8 unique_sigs=8 unique_ids=8 unique_pubkeys=8 pow_nonce={0}\nlock_acquires=9 max_concurrent_holders=1 overlap=False\ninbox_lock_wait_s=[0.0, 0.0344, 0.0642, 0.0942, 0.1242, 0.1543, 0.1844, 0.2145] inbox_hold_s=[0.0304, 0.0305, 0.0306, 0.0305, 0.0305, 0.0305, 0.0306, 0.0305]\nvote_lock_wait_s=0.2448 vote_event_index=8 vote_last=True expected_wait_gt=0.120\nkinds=['inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'inbox.received', 'vote.cast']\nchain_ok=True head_index=8 head_hash=147f088abec2cf25... n_events=9 n_inbox_rows=8\nfor_update_sql_seen='SELECT log_head.id, log_head.index, log_head.hash \nFROM log_head \nWHERE log_head.id = %(id_1)s FOR UPDATE'\nPASS: F15 N unique signed inbox POSTs serialize on log_head FOR UPDATE; vote append queued behind them\n```\n\n## Fix suggestion\nRequire proof of work or a token bucket per source on inbox POST, and batch or shard the log append so the single head lock is not on every write path.","patch_refs":[{"id":214,"repo":"xeprotocol/dao","kind":"commit","ref":"fd2b0d5f0ed1a3dbf0a11a9b33ce3cb7a1741c8d","title":"","url":"https://github.com/xeprotocol/dao/commit/fd2b0d5f0ed1a3dbf0a11a9b33ce3cb7a1741c8d","note":"","state":"","author":"","added_by":"token:5","created_at":"2026-10-30T01:39:14.776458+00:00"},{"id":220,"repo":"xeprotocol/dao","kind":"commit","ref":"be43d38","title":"","url":"https://github.com/xeprotocol/dao/commit/be43d38","note":"","state":"","author":"","added_by":"token:5","created_at":"2026-10-30T08:39:19.311069+00:00"}],"thread":[{"id":57,"source":"github","source_ref":"6512422968","author":"Joseph Denne","team":false,"body":"Thanks, confirmed. The HTTP inbox has no proof of work and no rate limit, and every accepted message is a public log event behind the single log-head lock. The change in hand adds the chat-door proof of work to the HTTP door, per-IP and per-account rate limits on the signed write routes, and stops writing untriaged inbox messages to the public log on receipt. The three DAO inbox reports are being fixed in one change; we will post the commit here when it lands.","created_at":"2026-10-30T01:10:08+00:00"},{"id":61,"source":"github","source_ref":"6518124183","author":"josephdenne","team":true,"body":"Fix is on main: https://github.com/xeprotocol/dao/commit/fd2b0d5f0ed1a3dbf0a11a9b33ce3cb7a1741c8d. Deploying to dao.test.network next; this issue will be updated once it is live.","created_at":"2026-10-30T08:08:44+00:00"},{"id":65,"source":"github","source_ref":"6518391298","author":"josephdenne","team":true,"body":"This fix is now live on dao.test.network.","created_at":"2026-10-30T08:21:57+00:00"}]}