diff --git a/services/communication/bstein-force-leave-job.yaml b/services/communication/bstein-force-leave-job.yaml index 2052e42..5763290 100644 --- a/services/communication/bstein-force-leave-job.yaml +++ b/services/communication/bstein-force-leave-job.yaml @@ -2,48 +2,40 @@ apiVersion: batch/v1 kind: Job metadata: - name: bstein-force-leave-6 + name: bstein-leave-rooms-1 namespace: comms spec: backoffLimit: 0 template: spec: restartPolicy: Never + volumes: + - name: mas-admin-client + secret: + secretName: mas-admin-client-runtime + items: + - key: client_secret + path: client_secret containers: - - name: force-leave + - name: leave image: python:3.11-slim + volumeMounts: + - name: mas-admin-client + mountPath: /etc/mas-admin-client + readOnly: true env: - - name: POSTGRES_HOST - value: postgres-service.postgres.svc.cluster.local - - name: POSTGRES_PORT - value: "5432" - - name: POSTGRES_DB - value: synapse - - name: POSTGRES_USER - valueFrom: - secretKeyRef: - name: synapse-db - key: POSTGRES_USER - - name: POSTGRES_PASSWORD - valueFrom: - secretKeyRef: - name: synapse-db - key: POSTGRES_PASSWORD + - name: MAS_ADMIN_CLIENT_ID + value: 01KDXMVQBQ5JNY6SEJPZW6Z8BM + - name: MAS_ADMIN_CLIENT_SECRET_FILE + value: /etc/mas-admin-client/client_secret + - name: MAS_TOKEN_URL + value: http://matrix-authentication-service:8080/oauth2/token + - name: MAS_ADMIN_API_BASE + value: http://matrix-authentication-service:8081/api/admin/v1 - name: SYNAPSE_BASE value: http://othrys-synapse-matrix-synapse:8008 - - name: AUTH_BASE - value: http://matrix-authentication-service:8080 - - name: SERVER_NAME - value: live.bstein.dev - - name: SEEDER_USER - value: othrys-seeder - - name: SEEDER_PASS - valueFrom: - secretKeyRef: - name: atlasbot-credentials-runtime - key: seeder-password - - name: TARGET_USER_ID - value: "@bstein:live.bstein.dev" + - name: TARGET_USERNAME + value: bstein - name: TARGET_ROOMS value: "!OkltaJguODUnZrbcUp:live.bstein.dev,!pMKAVvSRheIOCPIjDM:live.bstein.dev" command: @@ -51,138 +43,132 @@ spec: - -c - | set -euo pipefail - pip install --no-cache-dir requests psycopg2-binary >/dev/null python - <<'PY' - import json, os, sys, urllib.parse - import requests - import psycopg2 + import base64 + import json + import os + import urllib.error + import urllib.parse + import urllib.request - DB = dict( - host=os.environ["POSTGRES_HOST"], - port=int(os.environ["POSTGRES_PORT"]), - dbname=os.environ["POSTGRES_DB"], - user=os.environ["POSTGRES_USER"], - password=os.environ["POSTGRES_PASSWORD"], - ) - - SYNAPSE_BASE = os.environ["SYNAPSE_BASE"] - AUTH_BASE = os.environ["AUTH_BASE"] - SEEDER_USER = os.environ["SEEDER_USER"] - SEEDER_PASS = os.environ["SEEDER_PASS"] - TARGET_USER_ID = os.environ["TARGET_USER_ID"] + MAS_ADMIN_CLIENT_ID = os.environ["MAS_ADMIN_CLIENT_ID"] + MAS_ADMIN_CLIENT_SECRET_FILE = os.environ["MAS_ADMIN_CLIENT_SECRET_FILE"] + MAS_TOKEN_URL = os.environ["MAS_TOKEN_URL"] + MAS_ADMIN_API_BASE = os.environ["MAS_ADMIN_API_BASE"].rstrip("/") + SYNAPSE_BASE = os.environ["SYNAPSE_BASE"].rstrip("/") + TARGET_USERNAME = os.environ["TARGET_USERNAME"] TARGET_ROOMS = [r.strip() for r in os.environ["TARGET_ROOMS"].split(",") if r.strip()] - def db_connect(): - return psycopg2.connect(**DB) + def http_json(method, url, *, headers=None, json_body=None, form=None, timeout=30): + req_headers = dict(headers or {}) + data = None - def db_get_admin(conn, user_id): - with conn.cursor() as cur: - cur.execute("SELECT admin FROM users WHERE name = %s", (user_id,)) - row = cur.fetchone() - if not row: - raise RuntimeError(f"user not found in synapse db: {user_id}") - # Synapse stores admin as an int (0/1) - return int(row[0]) + if json_body is not None and form is not None: + raise ValueError("choose json_body or form, not both") - def db_set_admin(conn, user_id, is_admin): - with conn.cursor() as cur: - cur.execute("UPDATE users SET admin = %s WHERE name = %s", (1 if is_admin else 0, user_id)) + if json_body is not None: + data = json.dumps(json_body).encode() + req_headers.setdefault("Content-Type", "application/json") - def login(user, password): - r = requests.post( - f"{AUTH_BASE}/_matrix/client/v3/login", - json={ - "type": "m.login.password", - "identifier": {"type": "m.id.user", "user": user}, - "password": password, - }, - timeout=20, - ) - if r.status_code != 200: - raise RuntimeError(f"login failed: {r.status_code} {r.text}") - return r.json()["access_token"] + if form is not None: + data = urllib.parse.urlencode(form).encode() + req_headers.setdefault("Content-Type", "application/x-www-form-urlencoded") - def whoami(token): - r = requests.get( - f"{SYNAPSE_BASE}/_matrix/client/v3/account/whoami", - headers={"Authorization": f"Bearer {token}"}, - timeout=20, - ) - r.raise_for_status() - return r.json()["user_id"] + req = urllib.request.Request(url, data=data, method=method, headers=req_headers) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read() + payload = json.loads(raw.decode("utf-8")) if raw else None + return resp.status, payload + except urllib.error.HTTPError as e: + raw = e.read() + try: + payload = json.loads(raw.decode("utf-8")) if raw else None + except Exception: + payload = None + return e.code, payload - def admin_delete_room(token, room_id): - url = f"{SYNAPSE_BASE}/_synapse/admin/v1/rooms/{urllib.parse.quote(room_id)}" - r = requests.delete( - url, - headers={"Authorization": f"Bearer {token}"}, - json={"purge": False, "block": False}, - timeout=60, - ) - if r.status_code != 200: - raise RuntimeError(f"admin delete room failed: {room_id}: {r.status_code} {r.text}") - return r.json() + with open(MAS_ADMIN_CLIENT_SECRET_FILE, "r", encoding="utf-8") as f: + mas_admin_client_secret = f.read().strip() + if not mas_admin_client_secret: + raise RuntimeError("MAS admin client secret file is empty") - def admin_joined_rooms(token, user_id): - url = f"{SYNAPSE_BASE}/_synapse/admin/v1/users/{urllib.parse.quote(user_id)}/joined_rooms" - r = requests.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=20) - if r.status_code != 200: - raise RuntimeError(f"admin joined_rooms failed: {r.status_code} {r.text}") - return r.json().get("joined_rooms", []) + basic = base64.b64encode(f"{MAS_ADMIN_CLIENT_ID}:{mas_admin_client_secret}".encode()).decode() + token_status, token_payload = http_json( + "POST", + MAS_TOKEN_URL, + headers={"Authorization": f"Basic {basic}"}, + form={"grant_type": "client_credentials", "scope": "urn:mas:admin"}, + timeout=30, + ) + if token_status != 200 or not token_payload or "access_token" not in token_payload: + raise RuntimeError(f"MAS admin token request failed (HTTP {token_status})") + mas_admin_token = token_payload["access_token"] - results = {"target_user_id": TARGET_USER_ID, "rooms": {}} + user_status, user_payload = http_json( + "GET", + f"{MAS_ADMIN_API_BASE}/users/by-username/{urllib.parse.quote(TARGET_USERNAME)}", + headers={"Authorization": f"Bearer {mas_admin_token}"}, + timeout=30, + ) + if user_status != 200 or not user_payload or "data" not in user_payload or "id" not in user_payload["data"]: + raise RuntimeError(f"MAS user lookup failed (HTTP {user_status})") + actor_user_id = user_payload["data"]["id"] + + sess_status, sess_payload = http_json( + "POST", + f"{MAS_ADMIN_API_BASE}/personal-sessions", + headers={"Authorization": f"Bearer {mas_admin_token}"}, + json_body={ + "actor_user_id": actor_user_id, + "human_name": "bstein room cleanup", + "scope": "urn:matrix:client:api:*", + "expires_in": 300, + }, + timeout=30, + ) + if sess_status != 201 or not sess_payload or "data" not in sess_payload: + raise RuntimeError(f"MAS personal session create failed (HTTP {sess_status})") + + personal_session_id = sess_payload["data"]["id"] + personal_token = (sess_payload.get("data", {}).get("attributes", {}) or {}).get("access_token") + if not personal_token: + raise RuntimeError("MAS personal session did not return an access token") + + results = {"rooms": {}, "revoke": None} + failures = [] - conn = db_connect() - conn.autocommit = False try: - try: - token = login(SEEDER_USER, SEEDER_PASS) - results["seeder_login"] = "ok" - except Exception as e: - results["seeder_login"] = "error" - results["seeder_login_error"] = str(e) - print(json.dumps(results, indent=2, sort_keys=True)) - raise - - try: - seeder_user_id = whoami(token) - results["seeder_user_id"] = seeder_user_id - except Exception as e: - results["seeder_user_id_error"] = str(e) - seeder_user_id = None - - if seeder_user_id: - try: - results["seeder_admin_db"] = db_get_admin(conn, seeder_user_id) - except Exception as e: - results["seeder_admin_db_error"] = str(e) - - if results.get("seeder_admin_db") == 0: - try: - db_set_admin(conn, seeder_user_id, True) - conn.commit() - results["seeder_admin_db_promoted"] = True - except Exception as e: - results["seeder_admin_db_promote_error"] = str(e) - else: - results["seeder_admin_db_promoted"] = False - for room_id in TARGET_ROOMS: - room_res = {} - results["rooms"][room_id] = room_res - try: - room_res["delete"] = admin_delete_room(token, room_id) - room_res["deleted"] = True - except Exception as e: - room_res["deleted"] = False - room_res["delete_error"] = str(e) - - try: - results["target_joined_rooms_after"] = admin_joined_rooms(token, TARGET_USER_ID) - except Exception as e: - results["target_joined_rooms_after_error"] = str(e) - - print(json.dumps(results, indent=2, sort_keys=True)) + room_q = urllib.parse.quote(room_id, safe="") + leave_status, _ = http_json( + "POST", + f"{SYNAPSE_BASE}/_matrix/client/v3/rooms/{room_q}/leave", + headers={"Authorization": f"Bearer {personal_token}"}, + json_body={}, + timeout=30, + ) + forget_status, _ = http_json( + "POST", + f"{SYNAPSE_BASE}/_matrix/client/v3/rooms/{room_q}/forget", + headers={"Authorization": f"Bearer {personal_token}"}, + json_body={}, + timeout=30, + ) + results["rooms"][room_id] = {"leave": leave_status, "forget": forget_status} + if leave_status != 200 or forget_status != 200: + failures.append(room_id) finally: - conn.close() + revoke_status, _ = http_json( + "POST", + f"{MAS_ADMIN_API_BASE}/personal-sessions/{urllib.parse.quote(personal_session_id)}/revoke", + headers={"Authorization": f"Bearer {mas_admin_token}"}, + json_body={}, + timeout=30, + ) + results["revoke"] = revoke_status + + print(json.dumps(results, indent=2, sort_keys=True)) + if failures: + raise SystemExit(f"failed to leave/forget rooms: {', '.join(failures)}") PY