110 lines
4.8 KiB
Python
110 lines
4.8 KiB
Python
"""Isolated domain bridge for qualification, never a deployed server.
|
|
|
|
Actual VPS SQLite, SharedAPI, CLI and permission code. OAuth provider and root
|
|
privilege are simulated; no network socket, production state or hardware.
|
|
Pass the independently checked-out VPS repository as argv[1].
|
|
"""
|
|
import base64
|
|
import contextlib
|
|
import io
|
|
import json
|
|
import sys
|
|
import tempfile
|
|
import uuid
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
from urllib.parse import urlsplit, unquote_plus
|
|
|
|
sys.path.insert(0, str(Path(sys.argv[1]).resolve() / "server"))
|
|
from ndc_vps import admin
|
|
from ndc_vps.access_admin import provision
|
|
from ndc_vps.contours import Conflict
|
|
from ndc_vps.host_management import HostManagement, bootstrap
|
|
from ndc_vps.service import Service
|
|
from ndc_vps.shared_api import SharedAPI
|
|
from ndc_vps.store import Store
|
|
|
|
|
|
class Provider:
|
|
def __init__(self):
|
|
self.clients, self.tokens = {}, {}
|
|
|
|
def create(self, client, *_):
|
|
secret = "synthetic-" + uuid.uuid4().hex
|
|
self.clients[client] = secret
|
|
return secret
|
|
|
|
def token(self, authorization):
|
|
client, secret = base64.b64decode(authorization.removeprefix("Basic ")).decode().split(":", 1)
|
|
client, secret = unquote_plus(client), unquote_plus(secret)
|
|
if self.clients.get(client) != secret:
|
|
raise ValueError(f"synthetic credential mismatch known={client in self.clients} secret_length={len(secret)}")
|
|
token = "synthetic-" + uuid.uuid4().hex
|
|
self.tokens[token] = client
|
|
return dict(access_token=token, token_type="Bearer", expires_in=300)
|
|
|
|
def authenticate(self, token):
|
|
if token not in self.tokens:
|
|
raise PermissionError
|
|
return self.tokens[token]
|
|
|
|
|
|
with tempfile.TemporaryDirectory(prefix="b2-flow-vps-") as temporary:
|
|
root = Path(temporary)
|
|
state = root / "state"
|
|
state.mkdir(mode=0o700)
|
|
exports = root / "exports"
|
|
exports.mkdir(mode=0o700)
|
|
(state / "host.json").write_text(json.dumps(dict(
|
|
host_id="vps_synthetic_flow", fingerprint="a" * 64,
|
|
endpoint="https://vps.example.invalid:19443", api_port=19443,
|
|
tracker=dict(host="vps.example.invalid", port=9922))))
|
|
store = Store(state)
|
|
store.contours.enable_fresh()
|
|
with store.db(write=True) as db:
|
|
db.execute("INSERT INTO state VALUES('b2_authority_v1',?)", (json.dumps(dict(admin_port=4445, public_port=4444)),))
|
|
provider = Provider()
|
|
administrator = bootstrap(store, "device-core-admin", "Device Core")
|
|
package = provision(store, provider, administrator, issuer=store.config["endpoint"])
|
|
service = Service(store)
|
|
api = SharedAPI(service, provider, HostManagement(store, provider))
|
|
for line in sys.stdin:
|
|
request = json.loads(line)
|
|
try:
|
|
kind = request["kind"]
|
|
if kind == "bootstrap":
|
|
result = package
|
|
elif kind == "http":
|
|
route = urlsplit(request["url"])
|
|
headers = request.get("headers", {})
|
|
if route.path == "/oauth2/token":
|
|
result = provider.token(headers["authorization"])
|
|
else:
|
|
result = api.dispatch(request["method"], route, request.get("body"), headers.get("authorization", "").removeprefix("Bearer "))
|
|
elif kind == "cli":
|
|
output = io.StringIO()
|
|
# Exercise the real parser and domain calls, with local root simulated.
|
|
args = ["--state", str(state), *request["args"]]
|
|
if request["args"][0] == "key-issue":
|
|
args += ["--output", str(exports / (uuid.uuid4().hex + ".json"))]
|
|
with patch.object(admin.os, "geteuid", return_value=0), patch.object(admin, "HydraAdmin", return_value=provider), contextlib.redirect_stdout(output):
|
|
admin.main(args)
|
|
result = json.loads(output.getvalue())
|
|
if "saved" in result:
|
|
result = json.loads(Path(result["saved"]).read_text())
|
|
elif kind == "append":
|
|
result = store.append(request["imei"], b"synthetic", [])
|
|
elif kind == "restart":
|
|
store = Store(state)
|
|
service = Service(store)
|
|
api = SharedAPI(service, provider, HostManagement(store, provider))
|
|
result = dict(ok=True)
|
|
else:
|
|
raise ValueError("fixture request")
|
|
response = dict(ok=True, result=result)
|
|
except (PermissionError, Conflict, ValueError) as error:
|
|
response = dict(ok=False, status=403 if isinstance(error, PermissionError) else 409 if isinstance(error, Conflict) else 400, error=type(error).__name__)
|
|
except Exception as error:
|
|
response = dict(ok=False, status=500, error=type(error).__name__, detail=str(error))
|
|
print(json.dumps(response), flush=True)
|