Coverage for scripts/manage_ai_users.py: 57.69%

88 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 14:44 +0000

1#!/usr/bin/env python3 

2"""API-only users (SB-1145, SB-1493): create them and mint their /api/ai/* tokens. 

3 

4An API account is a user_profiles row with is_api_account=true. Prod requires 

5an auth.users row behind every profile (SB-1150), so each account has one with 

6no password, an undeliverable @missingtable.local email and a permanent ban: 

7it cannot log in to the web app. Its only credential is a short-lived token 

8this script mints, whose audience is accepted on /api/ai/* and rejected 

9everywhere else. 

10 

11 APP_ENV=local uv run python scripts/manage_ai_users.py ensure 

12 APP_ENV=local uv run python scripts/manage_ai_users.py list 

13 APP_ENV=local uv run python scripts/manage_ai_users.py token ai_eval_real --out ~/.config/mt/ai_eval_real.local.jwt 

14 

15Prod: run inside the backend pod, so the token is signed with the secret prod 

16actually verifies against, and redirect stdout to a file. `--out -` refuses to 

17write a token to a terminal, so it never lands in a transcript: 

18 

19 kubectl exec deploy/missing-table-backend -n missing-table -- \\ 

20 /app/.venv/bin/python scripts/manage_ai_users.py token ai_eval_real --out - \\ 

21 > ~/.config/mt/ai_eval_real.prod.jwt 

22""" 

23 

24import os 

25import sys 

26from dataclasses import dataclass 

27from datetime import UTC, datetime, timedelta 

28from pathlib import Path 

29 

30import typer 

31from dotenv import load_dotenv 

32 

33sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) 

34 

35from auth import AI_API_TOKEN_DEFAULT_DAYS, AI_API_TOKEN_MAX_DAYS, AuthManager, username_to_internal_email 

36 

37app = typer.Typer(help=__doc__.split("\n")[0]) 

38 

39# Non-admin: an admin sees test data, which is exactly what the eval must not 

40# assume. team-fan is the default role and the least privileged. 

41API_ROLE = "team-fan" 

42 

43# ~100 years. Supabase refuses sign-in and token refresh for a banned user; the 

44# /api/ai/* token is ours, not Supabase's, so the ban does not touch it. 

45PERMANENT_BAN = "876000h" 

46 

47 

48@dataclass(frozen=True) 

49class ApiAccount: 

50 username: str 

51 is_test: bool 

52 display_name: str 

53 

54 

55# ai_eval_real sees what a real fan sees; ai_eval_test also sees the TSC test 

56# world. Together they let an eval prove the partition in prod. 

57AI_EVAL_ACCOUNTS = ( 

58 ApiAccount("ai_eval_real", is_test=False, display_name="MT AI eval (real viewer)"), 

59 ApiAccount("ai_eval_test", is_test=True, display_name="MT AI eval (test viewer)"), 

60) 

61 

62# sb-agents' mt-agent (SB-1493) reads public MT data over mt-mcp for channels with 

63# no MT identity (Slack, Telegram). A real viewer, and mt-mcp caps its client 

64# (`X-MT-Client: sb-agents`) to the read tier whatever this account's role becomes. 

65SB_AGENTS_ACCOUNT = ApiAccount("sb_agents_public", is_test=False, display_name="sb-agents (public read-only)") 

66 

67API_ACCOUNTS = (*AI_EVAL_ACCOUNTS, SB_AGENTS_ACCOUNT) 

68 

69 

70def missing_accounts(existing_usernames: set[str]) -> list[ApiAccount]: 

71 return [a for a in API_ACCOUNTS if a.username not in existing_usernames] 

72 

73 

74def auth_user_attributes(account: ApiAccount) -> dict: 

75 """No password, no deliverable email, banned: nothing can sign in as this user.""" 

76 return { 

77 "email": username_to_internal_email(account.username), 

78 "email_confirm": False, 

79 "ban_duration": PERMANENT_BAN, 

80 "user_metadata": {"display_name": account.display_name, "api_account": True}, 

81 } 

82 

83 

84def profile_row(account: ApiAccount, user_id: str) -> dict: 

85 return { 

86 "id": user_id, 

87 "username": account.username, 

88 "display_name": account.display_name, 

89 "role": API_ROLE, 

90 "is_test": account.is_test, 

91 "is_api_account": True, 

92 "auth_provider": "api", 

93 } 

94 

95 

96def write_token(token: str, out: str, stdout_is_tty: bool) -> str: 

97 """Write the token to a 0600 file, or to stdout only when stdout is redirected.""" 

98 if out == "-": 

99 if stdout_is_tty: 

100 raise typer.BadParameter("refusing to print a token to a terminal; redirect stdout to a file") 

101 sys.stdout.write(token + "\n") 

102 return "stdout" 

103 path = Path(out).expanduser() 

104 path.parent.mkdir(parents=True, exist_ok=True) 

105 fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) 

106 with os.fdopen(fd, "w") as f: 

107 f.write(token + "\n") 

108 path.chmod(0o600) 

109 return str(path) 

110 

111 

112def create_api_account(client, account: ApiAccount) -> str: 

113 """Create the auth user, then upsert its profile; undo the auth user if that fails. 

114 

115 Upsert, not insert: in prod the on_auth_user_created trigger has already 

116 made a bare team-fan profile for the new id. Locally there is no trigger. 

117 """ 

118 user_id = str(client.auth.admin.create_user(auth_user_attributes(account)).user.id) 

119 try: 

120 client.table("user_profiles").upsert(profile_row(account, user_id)).execute() 

121 except Exception: 

122 client.auth.admin.delete_user(user_id) 

123 raise 

124 return user_id 

125 

126 

127def _client(): 

128 load_dotenv() 

129 env_file = Path(__file__).resolve().parent.parent / f".env.{os.getenv('APP_ENV', 'local')}" 

130 if env_file.exists(): 

131 load_dotenv(env_file, override=True) 

132 from supabase import create_client 

133 

134 return create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_SERVICE_KEY"]) 

135 

136 

137def _api_profiles(client) -> list[dict]: 

138 return ( 

139 client.table("user_profiles") 

140 .select("id, username, role, is_test, is_api_account") 

141 .eq("is_api_account", True) 

142 .execute() 

143 .data 

144 ) 

145 

146 

147def _err(message: str) -> None: 

148 # Status goes to stderr so `token --out -` leaves stdout holding the token alone. 

149 typer.echo(message, err=True) 

150 

151 

152@app.command() 

153def ensure() -> None: 

154 """Create the API accounts that do not exist yet. Safe to re-run.""" 

155 client = _client() 

156 taken = ( 

157 client.table("user_profiles") 

158 .select("username, is_api_account") 

159 .in_("username", [a.username for a in API_ACCOUNTS]) 

160 .execute() 

161 .data 

162 ) 

163 clash = [r["username"] for r in taken if not r.get("is_api_account")] 

164 if clash: 

165 _err(f"username taken by a non-API account: {', '.join(clash)}") 

166 raise typer.Exit(1) 

167 for account in missing_accounts({r["username"] for r in taken}): 

168 user_id = create_api_account(client, account) 

169 _err(f"created {account.username} (is_test={account.is_test}) id={user_id}") 

170 _err(f"{os.getenv('APP_ENV', 'local')}: {len(API_ACCOUNTS)} API accounts present") 

171 

172 

173@app.command("list") 

174def list_accounts() -> None: 

175 """List API accounts.""" 

176 for row in _api_profiles(_client()): 

177 _err(f"{row['username']:<16} {row['role']:<10} is_test={row['is_test']} id={row['id']}") 

178 

179 

180@app.command() 

181def token( 

182 username: str, 

183 out: str = typer.Option(..., help="File to write (0600), or '-' for redirected stdout."), 

184 days: int = typer.Option(AI_API_TOKEN_DEFAULT_DAYS, min=1, max=AI_API_TOKEN_MAX_DAYS), 

185) -> None: 

186 """Mint a short-lived /api/ai/* token for an API account.""" 

187 client = _client() 

188 if not os.getenv("SERVICE_ACCOUNT_SECRET"): 

189 # AuthManager would fall back to a random secret: a token no server accepts. 

190 _err("SERVICE_ACCOUNT_SECRET is not set; the token would be unverifiable") 

191 raise typer.Exit(1) 

192 match = [r for r in _api_profiles(client) if r["username"] == username] 

193 if not match: 

194 _err(f"no API account named {username}; run `ensure` first") 

195 raise typer.Exit(1) 

196 minted = AuthManager(client).create_ai_api_token(match[0]["id"], expires_days=days) 

197 where = write_token(minted, out, sys.stdout.isatty()) 

198 expires = (datetime.now(UTC) + timedelta(days=days)).strftime("%Y-%m-%d %H:%M UTC") 

199 _err(f"token for {username} written to {where}; expires {expires}; valid on /api/ai/* only") 

200 

201 

202if __name__ == "__main__": 

203 app()