#!/usr/bin/env python3 """exe-login: sign in to Plane with your exe.dev login. Plane's Community Edition can sign people in with Gitea. This small server speaks the part of Gitea's OAuth2 API that Plane uses, and answers with the person exe.dev's proxy says is visiting (the X-ExeDev-Email and X-ExeDev-UserID headers). It keeps no data; codes and tokens live in memory for a few minutes. Two listeners, both on 127.0.0.1, reached through nginx: PUBLIC_PORT (8002) GET /login/oauth/authorize. Trusts the exe.dev headers, so nginx sends it only requests that came in through exe.dev's proxy on port 8000. PRIVATE_PORT (8003) POST /login/oauth/access_token, GET /api/v1/user and /api/v1/user/emails, for Plane's server. Ignores the exe.dev headers. Settings come from ~/plane/.env: WEB_URL, GITEA_CLIENT_ID and GITEA_CLIENT_SECRET. """ import hmac import json import os import secrets import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlencode, urlsplit PUBLIC_PORT, PRIVATE_PORT = 8002, 8003 CODE_TTL, TOKEN_TTL = 120, 300 def read_env(path): env = {} with open(path) as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: key, value = line.split("=", 1) env[key] = value return env ENV = read_env(os.path.expanduser("~/plane/.env")) WEB_URL = ENV["WEB_URL"].rstrip("/") CLIENT_ID = ENV["GITEA_CLIENT_ID"] CLIENT_SECRET = ENV["GITEA_CLIENT_SECRET"] # Plane's two callbacks: the app, and published project views ("spaces"). REDIRECT_URIS = {WEB_URL + "/auth/gitea/callback/", WEB_URL + "/auth/spaces/gitea/callback/"} codes, tokens = {}, {} lock = threading.Lock() def issue(store, ttl, value): key = secrets.token_urlsafe(32) now = time.time() with lock: for k in [k for k, v in store.items() if v["expires"] < now]: del store[k] store[key] = dict(value, expires=now + ttl) return key def take(store, key, keep=False): with lock: value = store.get(key) if keep else store.pop(key, None) if value and value["expires"] >= time.time(): return value return None class Handler(BaseHTTPRequestHandler): server_version = "exe-login" def log_message(self, fmt, *args): pass # query strings carry codes; don't log them def send(self, status, body=None, location=None): data = json.dumps(body).encode() if body is not None else b"" self.send_response(status) if location: self.send_header("Location", location) self.send_header("Cache-Control", "no-store") self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def path_and_query(self): url = urlsplit(self.path) return url.path, {k: v[0] for k, v in parse_qs(url.query).items()} class Public(Handler): def do_GET(self): path, q = self.path_and_query() if path != "/login/oauth/authorize": return self.send(404, {"error": "not found"}) if q.get("client_id") != CLIENT_ID or q.get("redirect_uri") not in REDIRECT_URIS: return self.send(400, {"error": "unknown client or redirect_uri"}) if q.get("response_type") != "code": return self.send(400, {"error": "unsupported response_type"}) email = self.headers.get("X-ExeDev-Email", "").strip().lower() user_id = self.headers.get("X-ExeDev-UserID", "").strip() if not email or not user_id: # Not signed in to exe.dev (a public VM): sign in, then start again. back = "/auth/spaces/gitea/" if "/spaces/" in q["redirect_uri"] else "/auth/gitea/" return self.send(302, location=WEB_URL + "/__exe.dev/login?" + urlencode({"redirect": back})) code = issue(codes, CODE_TTL, {"email": email, "user_id": user_id, "redirect_uri": q["redirect_uri"]}) params = {"code": code} if "state" in q: params["state"] = q["state"] self.send(302, location=q["redirect_uri"] + "?" + urlencode(params)) class Private(Handler): def do_POST(self): path, _ = self.path_and_query() if path != "/login/oauth/access_token": return self.send(404, {"error": "not found"}) length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length).decode() if length else "" if "json" in self.headers.get("Content-Type", ""): form = json.loads(raw or "{}") else: form = {k: v[0] for k, v in parse_qs(raw).items()} if form.get("client_id") != CLIENT_ID or not hmac.compare_digest( str(form.get("client_secret", "")).encode(), CLIENT_SECRET.encode() ): return self.send(401, {"error": "invalid_client"}) grant = take(codes, str(form.get("code", ""))) if not grant or grant["redirect_uri"] != form.get("redirect_uri"): return self.send(400, {"error": "invalid_grant"}) token = issue(tokens, TOKEN_TTL, {"email": grant["email"], "user_id": grant["user_id"]}) self.send(200, {"access_token": token, "token_type": "bearer", "expires_in": TOKEN_TTL}) def do_GET(self): path, _ = self.path_and_query() auth = self.headers.get("Authorization", "") who = take(tokens, auth[7:], keep=True) if auth.lower().startswith("bearer ") else None if path not in ("/api/v1/user", "/api/v1/user/emails"): return self.send(404, {"error": "not found"}) if not who: return self.send(401, {"error": "invalid token"}) if path == "/api/v1/user/emails": return self.send(200, [{"email": who["email"], "primary": True, "verified": True}]) name = who["email"].split("@")[0] self.send(200, {"id": who["user_id"], "login": name, "full_name": name, "email": who["email"], "avatar_url": ""}) if __name__ == "__main__": servers = [ThreadingHTTPServer(("127.0.0.1", PUBLIC_PORT), Public), ThreadingHTTPServer(("127.0.0.1", PRIVATE_PORT), Private)] for s in servers[1:]: threading.Thread(target=s.serve_forever, daemon=True).start() servers[0].serve_forever()