#!/usr/bin/env python3 """exe-login: sign in to Mattermost with your exe.dev login. Mattermost Team Edition can sign people in with GitLab (OAuth 2.0). This plays GitLab's part, standard library only. exe.dev's HTTPS proxy tells every request who is signed in (the X-ExeDev-Email and X-ExeDev-UserID headers, which it sets and strips from anything else), so /authorize trusts them and hands Mattermost a one-time code. Mattermost trades the code for a token at /token and asks /user who it belongs to, over Docker's network. Only /authorize may be reachable from outside, through nginx; keep /token and /user on Docker's network. Settings come from the environment: EXE_LOGIN_SECRET (shared with Mattermost), MM_SITEURL, and optionally EXE_LOGIN_ALLOWED: email addresses or @domains allowed to sign in, separated by commas or spaces (default: everyone who reaches the VM). """ import hashlib, hmac, json, os, secrets, sys, threading, time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlencode, urlsplit SECRET = os.environ["EXE_LOGIN_SECRET"] SITE = os.environ["MM_SITEURL"].rstrip("/") CLIENT_ID = "mattermost" ALLOWED = os.environ.get("EXE_LOGIN_ALLOWED", "").replace(",", " ").lower().split() TTL = 120 # seconds a code or token stays valid pending = {} # code or token -> (expiry, who) lock = threading.Lock() def remember(who): key = secrets.token_urlsafe(32) with lock: now = time.time() for k in [k for k, (exp, _) in pending.items() if exp < now]: del pending[k] pending[key] = (now + TTL, who) return key def take(key): with lock: exp, who = pending.pop(key, (0, None)) return who if exp > time.time() else None def allowed(email): if not ALLOWED: return True domain = "@" + email.rsplit("@", 1)[-1] return email in ALLOWED or domain in ALLOWED class Handler(BaseHTTPRequestHandler): def send(self, code, body=None, headers=()): data = json.dumps(body).encode() if body is not None else b"" self.send_response(code) for k, v in headers: self.send_header(k, v) if body is not None: self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(data) def send_text(self, code, text): data = text.encode() self.send_response(code) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def do_GET(self): url = urlsplit(self.path) q = {k: v[0] for k, v in parse_qs(url.query).items()} if url.path == "/exe-login/authorize": return self.authorize(q) if url.path == "/exe-login/user": auth = self.headers.get("Authorization", "") who = take(auth[7:]) if auth.startswith("Bearer ") else None if not who: return self.send(401, {"error": "invalid_token"}) return self.send(200, who) self.send(404, {"error": "not_found"}) def authorize(self, q): email = (self.headers.get("X-ExeDev-Email") or "").strip().lower() if not email: # Not signed in to exe.dev: the proxy's login page sends them back. return self.send(302, headers=[("Location", "/__exe.dev/login?" + urlencode({"redirect": self.path}))]) if q.get("client_id") != CLIENT_ID or q.get("redirect_uri") != SITE + "/signup/gitlab/complete": return self.send(400, {"error": "invalid_request", "error_description": "check MM_SITEURL"}) if not allowed(email): msg = f"{email} may not sign in to this Mattermost. Ask its owner to add you to EXE_LOGIN_ALLOWED.\n" return self.send_text(403, msg) uid = self.headers.get("X-ExeDev-UserID") or email local = email.split("@")[0] who = { # GitLab user ids are numbers; this one is stable per exe.dev user. "id": int.from_bytes(hashlib.sha256(uid.encode()).digest()[:6], "big") + 1, "username": local, "name": local, "email": email, } code = remember(who) query = urlencode({"code": code, "state": q.get("state", "")}) self.send(302, headers=[("Location", q["redirect_uri"] + "?" + query)]) def do_POST(self): if urlsplit(self.path).path != "/exe-login/token": return self.send(404, {"error": "not_found"}) n = int(self.headers.get("Content-Length") or 0) f = {k: v[0] for k, v in parse_qs(self.rfile.read(n).decode()).items()} if f.get("client_id") != CLIENT_ID or not hmac.compare_digest(f.get("client_secret", ""), SECRET): return self.send(401, {"error": "invalid_client"}) who = take(f.get("code", "")) if not who: return self.send(400, {"error": "invalid_grant"}) self.send(200, {"access_token": remember(who), "token_type": "bearer", "expires_in": TTL}) def log_request(self, code="-", size="-"): # Leave out the query: it holds one-time codes and OAuth state. who = self.headers.get("X-ExeDev-Email") or "-" sys.stderr.write(f"exe-login: {self.command} {urlsplit(self.path).path} {code} {who}\n") if __name__ == "__main__": print("exe-login: listening on :8080", file=sys.stderr, flush=True) ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()