|
| 1 | +import asyncio |
| 2 | +import asyncio.subprocess as sp |
| 3 | +import httpx |
| 4 | +import os |
| 5 | + |
| 6 | +from base58 import BITCOIN_ALPHABET |
| 7 | +from contextlib import asynccontextmanager |
| 8 | +from fastapi import FastAPI, Request, HTTPException |
| 9 | +from fastapi.responses import StreamingResponse, FileResponse |
| 10 | +from pydantic import BaseModel, model_validator, AfterValidator |
| 11 | +from starlette.background import BackgroundTask |
| 12 | +from string import ascii_letters, digits |
| 13 | +from tempfile import TemporaryDirectory |
| 14 | + |
| 15 | +from Crypto.Signature import pkcs1_15 |
| 16 | +from Crypto.Hash import SHA256 |
| 17 | +from Crypto.PublicKey import RSA |
| 18 | + |
| 19 | +from typing import Annotated |
| 20 | + |
| 21 | +IPFS_API = "http://ipfs:5001" |
| 22 | +IPFS_API_MULTIADDR = "/dns4/ipfs/tcp/5001" |
| 23 | + |
| 24 | +key = RSA.generate(2048) |
| 25 | + |
| 26 | + |
| 27 | +@asynccontextmanager |
| 28 | +async def lifespan(app: FastAPI): |
| 29 | + async with httpx.AsyncClient(base_url=IPFS_API) as client: |
| 30 | + yield {"client": client} |
| 31 | + |
| 32 | + |
| 33 | +app = FastAPI(lifespan=lifespan) |
| 34 | + |
| 35 | + |
| 36 | +# ---- Reverse Proxy ---- |
| 37 | + |
| 38 | + |
| 39 | +async def _reverse_proxy(request: Request): |
| 40 | + client = request.state.client |
| 41 | + url = httpx.URL(path=request.url.path, query=request.url.query.encode()) |
| 42 | + headers = [(k, v) for k, v in request.headers.raw if k != b"host"] |
| 43 | + req = client.build_request( |
| 44 | + request.method, url, headers=headers, content=request.stream() |
| 45 | + ) |
| 46 | + r = await client.send(req, stream=True) |
| 47 | + return StreamingResponse( |
| 48 | + r.aiter_raw(), |
| 49 | + status_code=r.status_code, |
| 50 | + headers=r.headers, |
| 51 | + background=BackgroundTask(r.aclose), |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +app.add_route("/api/v0/{path:path}", _reverse_proxy, ["POST"]) |
| 56 | + |
| 57 | + |
| 58 | +# ---- Main API ---- |
| 59 | + |
| 60 | + |
| 61 | +class IPVMError(HTTPException): |
| 62 | + def __init__(self, message: str): |
| 63 | + super().__init__(status_code=400, detail=message) |
| 64 | + |
| 65 | + |
| 66 | +class Config(BaseModel): |
| 67 | + name: str |
| 68 | + author: str | None = None |
| 69 | + version: str | None = None |
| 70 | + description: str | None = None |
| 71 | + |
| 72 | + entrypoint: str = "_start" |
| 73 | + |
| 74 | + @model_validator(mode="after") |
| 75 | + def verify(self): |
| 76 | + if not ( |
| 77 | + all(c in (ascii_letters + "_") for c in self.entrypoint) |
| 78 | + and 0 < len(self.entrypoint) <= 10 |
| 79 | + ): |
| 80 | + raise ValueError("Invalid entrypoint") |
| 81 | + |
| 82 | + return self |
| 83 | + |
| 84 | + |
| 85 | +def verify_cid(cid): |
| 86 | + cs = cid.encode() |
| 87 | + if not (all(c in BITCOIN_ALPHABET for c in cs) and len(cs) == 46): |
| 88 | + raise ValueError("Invalid CID") |
| 89 | + |
| 90 | + return cid |
| 91 | + |
| 92 | + |
| 93 | +Cid = Annotated[str, AfterValidator(verify_cid)] |
| 94 | + |
| 95 | + |
| 96 | +async def check_output(cmd, stdout=sp.PIPE, stderr=sp.DEVNULL, timeout=None, **kwargs): |
| 97 | + proc = await sp.create_subprocess_exec(*cmd, stdout=stdout, stderr=stderr, **kwargs) |
| 98 | + stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout) |
| 99 | + if proc.returncode != 0: |
| 100 | + raise IPVMError(f"Command {cmd[0]} failed with return code {proc.returncode}") |
| 101 | + |
| 102 | + return stdout |
| 103 | + |
| 104 | + |
| 105 | +async def ipfs_call(args): |
| 106 | + return await check_output(["ipfs", "--api", IPFS_API_MULTIADDR, *args], timeout=30) |
| 107 | + |
| 108 | + |
| 109 | +async def ipfs_read(path): |
| 110 | + return await ipfs_call(["cat", path]) |
| 111 | + |
| 112 | + |
| 113 | +async def check_package(cid, allowed: set[str]): |
| 114 | + content = (await ipfs_call(["ls", cid])).decode() |
| 115 | + total_size = 0 |
| 116 | + for line in content.splitlines(): |
| 117 | + _, size, filename = line.split(maxsplit=2) |
| 118 | + assert filename in allowed, f"Invalid file: {filename}" |
| 119 | + total_size += int(size) |
| 120 | + |
| 121 | + if total_size > 128 * 1024: |
| 122 | + raise IPVMError("Package too large") |
| 123 | + |
| 124 | + |
| 125 | +class BuildRequest(BaseModel): |
| 126 | + cid: Cid |
| 127 | + |
| 128 | + |
| 129 | +@app.post("/build") |
| 130 | +async def build_request(request: BuildRequest): |
| 131 | + cid = request.cid |
| 132 | + Config.model_validate_json(await ipfs_read(f"{cid}/config.json")) |
| 133 | + |
| 134 | + await check_package(cid, {"config.json", "main.wat", "main.wasm"}) |
| 135 | + |
| 136 | + with TemporaryDirectory() as td: |
| 137 | + await ipfs_call(["get", cid, "-o", td]) |
| 138 | + if os.path.exists(f"{td}/main.wat"): |
| 139 | + await check_output( |
| 140 | + ["wat2wasm", "main.wat", "-o", "main.wasm"], |
| 141 | + cwd=td, |
| 142 | + timeout=5, |
| 143 | + ) |
| 144 | + os.remove(f"{td}/main.wat") |
| 145 | + |
| 146 | + if not os.path.exists(f"{td}/main.wasm"): |
| 147 | + raise IPVMError("No wasm file found") |
| 148 | + |
| 149 | + await check_output( |
| 150 | + ["wasmtime", "compile", "main.wasm"], |
| 151 | + cwd=td, |
| 152 | + timeout=5, |
| 153 | + ) |
| 154 | + os.remove(f"{td}/main.wasm") |
| 155 | + |
| 156 | + with open(f"{td}/main.cwasm", "rb") as f: |
| 157 | + h = SHA256.new(f.read()) |
| 158 | + signature = pkcs1_15.new(key).sign(h) |
| 159 | + |
| 160 | + with open(f"{td}/main.cwasm.sig", "wb") as f: |
| 161 | + f.write(signature) |
| 162 | + |
| 163 | + output = (await ipfs_call(["add", "-r", td])).decode() |
| 164 | + line = output.strip().splitlines()[-1] |
| 165 | + package_cid = line.split()[1] |
| 166 | + |
| 167 | + return { |
| 168 | + "cid": package_cid, |
| 169 | + } |
| 170 | + |
| 171 | + |
| 172 | +class RunRequest(BaseModel): |
| 173 | + cid: Cid |
| 174 | + args: str = "" |
| 175 | + |
| 176 | + @model_validator(mode="after") |
| 177 | + def verify(self): |
| 178 | + if not (all(a in (digits + " ") for a in self.args) and len(self.args) <= 20): |
| 179 | + raise ValueError("Invalid args") |
| 180 | + |
| 181 | + return self |
| 182 | + |
| 183 | + |
| 184 | +@app.post("/run") |
| 185 | +async def run_request(request: RunRequest): |
| 186 | + cid = request.cid |
| 187 | + config = Config.model_validate_json(await ipfs_read(f"{cid}/config.json")) |
| 188 | + |
| 189 | + await check_package(cid, {"config.json", "main.cwasm", "main.cwasm.sig"}) |
| 190 | + |
| 191 | + signature = await ipfs_read(f"{cid}/main.cwasm.sig") |
| 192 | + h = SHA256.new(await ipfs_read(f"{cid}/main.cwasm")) |
| 193 | + pkcs1_15.new(key).verify(h, signature) |
| 194 | + |
| 195 | + with TemporaryDirectory() as td: |
| 196 | + await ipfs_call(["get", cid, "-o", td]) |
| 197 | + output = await check_output( |
| 198 | + [ |
| 199 | + "wasmtime", |
| 200 | + "run", |
| 201 | + "--allow-precompiled", |
| 202 | + "--invoke", |
| 203 | + config.entrypoint, |
| 204 | + "main.cwasm", |
| 205 | + *request.args.split(), |
| 206 | + ], |
| 207 | + cwd=td, |
| 208 | + timeout=5, |
| 209 | + ) |
| 210 | + |
| 211 | + return {"output": output.decode()} |
| 212 | + |
| 213 | + |
| 214 | +@app.get("/") |
| 215 | +async def read_index(): |
| 216 | + return FileResponse("index.html") |
0 commit comments