release gate / check (push) Canceled after 4m12s
Implements DESIGN_MCP_HUB_AUTH.md phase 1, executed on erwin: - hub_entrypoint.py override: _AuthMiddleware authenticates every /sse and /messages/ request against hash-only mhub_ tokens (hub_tokens.json, mtime-cached, revocation without restart), binds sessions to the credential that opened them, and keeps ?as_user= as an admin-only override; legacy Basic-auth (traefik) and container loopback map to a legacy admin identity during the transition (HUB_ALLOW_LEGACY_BASIC). - _guarded_call_tool: non-admin tokens refused nextcloud_admin_*, superbrain_*, gitea_* and superpanel mutations; nextcloud_user_* pinned to the token's own user; per-call audit log without arguments. - mcphub-token CLI: add/list/revoke, Superpanel user verification, admin from group membership, --with-nextcloud mints the DAV app token too. - Dockerfile COPYs the hub override; STRATEGY.md records the rollout, the Traefik v3 HeaderRegexp spelling, and the nc_tokens.json directory bug fixed en passant. Verified on the public endpoint: invalid/revoked tokens 401, operator 232 tools, non-admin scoping refusals, own-user reads, cross-token session riding 401.
141 lines
4.4 KiB
Python
141 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
|
"""mcphub-token — issue/list/revoke per-user bearer tokens for the core MCP
|
|
hub (DESIGN_MCP_HUB_AUTH.md). Host-side, run as root.
|
|
|
|
mcphub-token add <user> [--admin] [--label X] [--with-nextcloud]
|
|
mcphub-token list
|
|
mcphub-token revoke <user|hash-prefix>
|
|
|
|
Tokens are mhub_<random>, stored SHA-256-only in
|
|
/federated/apps/mcpserver/hub_tokens.json (mounted into the hub). The
|
|
plaintext is printed ONCE on add. --admin defaults from the user's
|
|
Superpanel group membership; --with-nextcloud also mints the Nextcloud
|
|
app token into nc_tokens.json so personal tools work immediately.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import secrets
|
|
import subprocess
|
|
import sys
|
|
import urllib.request
|
|
from datetime import datetime, timezone
|
|
|
|
TOKENS_FILE = "/federated/apps/mcpserver/hub_tokens.json"
|
|
NC_TOKENS_FILE = "/federated/apps/mcpserver/nc_tokens.json"
|
|
SUPERPANEL_URL = "http://192.168.0.85:8080"
|
|
ADMIN_SECRET_FILE = "/federated/apps/superpanel/.admin.secret"
|
|
|
|
|
|
def load(path):
|
|
try:
|
|
with open(path) as f:
|
|
return json.load(f)
|
|
except (OSError, json.JSONDecodeError):
|
|
return {}
|
|
|
|
|
|
def save(path, data):
|
|
with open(path, "w") as f:
|
|
json.dump(data, f, indent=2)
|
|
os.chmod(path, 0o600)
|
|
|
|
|
|
def superpanel_api(path):
|
|
key = open(ADMIN_SECRET_FILE).read().strip()
|
|
req = urllib.request.Request(
|
|
SUPERPANEL_URL + path, headers={"Authorization": f"Bearer {key}"})
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
return json.loads(r.read().decode())
|
|
|
|
|
|
def find_user(username):
|
|
users = superpanel_api("/api/users")
|
|
for u in users:
|
|
if u.get("username") == username:
|
|
return u
|
|
return None
|
|
|
|
|
|
def cmd_add(args):
|
|
user = find_user(args.user)
|
|
if not user:
|
|
sys.exit(f"no such Superpanel user: {args.user}")
|
|
admin = args.admin
|
|
if admin is None:
|
|
admin = "admins" in (user.get("groups") or [])
|
|
token = "mhub_" + secrets.token_urlsafe(32)
|
|
h = hashlib.sha256(token.encode()).hexdigest()
|
|
tokens = load(TOKENS_FILE)
|
|
tokens[h] = {
|
|
"user": args.user,
|
|
"admin": bool(admin),
|
|
"label": args.label or "",
|
|
"created": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
}
|
|
save(TOKENS_FILE, tokens)
|
|
if args.with_nextcloud:
|
|
out = subprocess.run(
|
|
["docker", "exec", "-u", "33", "nextcloud",
|
|
"/var/www/html/occ", "user:auth-tokens:add", "-n", args.user],
|
|
capture_output=True, text=True)
|
|
nc_token = out.stdout.strip().split("\n")[-1].strip()
|
|
if out.returncode != 0 or not nc_token:
|
|
print(f"warning: nextcloud token mint failed: {out.stderr.strip()}",
|
|
file=sys.stderr)
|
|
else:
|
|
nc = load(NC_TOKENS_FILE)
|
|
nc[args.user] = nc_token
|
|
save(NC_TOKENS_FILE, nc)
|
|
print(f"nextcloud app token minted for {args.user}")
|
|
print(f"user={args.user} admin={bool(admin)}")
|
|
print(token)
|
|
|
|
|
|
def cmd_list(_args):
|
|
tokens = load(TOKENS_FILE)
|
|
if not tokens:
|
|
print("no tokens issued")
|
|
return
|
|
for h, e in tokens.items():
|
|
print(f"{h[:12]}… user={e.get('user')} admin={e.get('admin')} "
|
|
f"label={e.get('label') or '-'} created={e.get('created')}")
|
|
|
|
|
|
def cmd_revoke(args):
|
|
tokens = load(TOKENS_FILE)
|
|
keep, removed = {}, 0
|
|
for h, e in tokens.items():
|
|
if e.get("user") == args.target or h.startswith(args.target):
|
|
removed += 1
|
|
else:
|
|
keep[h] = e
|
|
if not removed:
|
|
sys.exit(f"no token matches: {args.target}")
|
|
save(TOKENS_FILE, keep)
|
|
print(f"revoked {removed} token(s); the hub picks this up without a restart")
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
sub = p.add_subparsers(dest="cmd", required=True)
|
|
a = sub.add_parser("add")
|
|
a.add_argument("user")
|
|
a.add_argument("--admin", dest="admin", action="store_true", default=None)
|
|
a.add_argument("--no-admin", dest="admin", action="store_false")
|
|
a.add_argument("--label", default="")
|
|
a.add_argument("--with-nextcloud", action="store_true")
|
|
a.set_defaults(fn=cmd_add)
|
|
l = sub.add_parser("list")
|
|
l.set_defaults(fn=cmd_list)
|
|
r = sub.add_parser("revoke")
|
|
r.add_argument("target")
|
|
r.set_defaults(fn=cmd_revoke)
|
|
args = p.parse_args()
|
|
args.fn(args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|