askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_identity_cli.py · 14.1 KB · 349 lines
| 1 | """Shell management for DBBASIC identity, in the spirit of Django manage.py. |
| 2 | |
| 3 | This CLI operates directly on the runtime data directory, so an operator on |
| 4 | the VM can bootstrap the first admin user and manage accounts, users, and |
| 5 | passwords over SSH without HTTP access or tokens. Passwords are prompted |
| 6 | without echo (or read from stdin for scripting) and are never printed. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import argparse |
| 12 | import getpass |
| 13 | import json |
| 14 | import os |
| 15 | import sys |
| 16 | from pathlib import Path |
| 17 | |
| 18 | import object_credentials |
| 19 | import object_identity |
| 20 | |
| 21 | DATA_DIR_ENV = "DBBASIC_DATA_DIR" |
| 22 | ADMIN_ROLE = "admin" |
| 23 | |
| 24 | |
| 25 | def main(argv: list[str] | None = None) -> int: |
| 26 | parser = argparse.ArgumentParser( |
| 27 | description="Manage DBBASIC identity accounts, users, and passwords from the shell." |
| 28 | ) |
| 29 | parser.add_argument( |
| 30 | "--data-dir", |
| 31 | type=Path, |
| 32 | default=None, |
| 33 | help=f"runtime data directory (default: ${DATA_DIR_ENV} or ./data)", |
| 34 | ) |
| 35 | subcommands = parser.add_subparsers(dest="command", required=True) |
| 36 | |
| 37 | create_account = subcommands.add_parser("create-account", help="create an account") |
| 38 | create_account.add_argument("--account-id", required=True) |
| 39 | create_account.add_argument("--name", default="") |
| 40 | |
| 41 | disable_account = subcommands.add_parser( |
| 42 | "disable-account", |
| 43 | help="disable an account: its users are refused and their sessions end; API keys are kept", |
| 44 | ) |
| 45 | disable_account.add_argument("--account-id", required=True) |
| 46 | |
| 47 | enable_account = subcommands.add_parser( |
| 48 | "enable-account", help="re-enable an account: its users sign in again, its API keys work again" |
| 49 | ) |
| 50 | enable_account.add_argument("--account-id", required=True) |
| 51 | |
| 52 | set_subscriptions = subcommands.add_parser( |
| 53 | "set-account-subscriptions", |
| 54 | help="replace an account's subscriptions (billing); applies on its users' next request, nobody is signed out", |
| 55 | ) |
| 56 | set_subscriptions.add_argument("--account-id", required=True) |
| 57 | set_subscriptions.add_argument( |
| 58 | "--subscriptions", |
| 59 | required=True, |
| 60 | help='comma-separated names, the whole list ("" removes them all)', |
| 61 | ) |
| 62 | |
| 63 | create_user = subcommands.add_parser("create-user", help="create a user") |
| 64 | create_user.add_argument("--user-id", required=True) |
| 65 | create_user.add_argument("--email") |
| 66 | create_user.add_argument("--display-name") |
| 67 | create_user.add_argument("--account-id") |
| 68 | create_user.add_argument("--roles", help="comma-separated roles") |
| 69 | create_user.add_argument( |
| 70 | "--identity-source", |
| 71 | help="link this user to an identity source by name (e.g. http_verify) so that " |
| 72 | "source's identity for the same user id is accepted as this user", |
| 73 | ) |
| 74 | |
| 75 | set_identity_source = subcommands.add_parser( |
| 76 | "set-identity-source", |
| 77 | help="link a user to an identity source (or --unlink); unlinked users refuse " |
| 78 | "remote identities naming their id", |
| 79 | ) |
| 80 | set_identity_source.add_argument("--user-id", required=True) |
| 81 | link = set_identity_source.add_mutually_exclusive_group(required=True) |
| 82 | link.add_argument("--source", help="identity source name, e.g. http_verify") |
| 83 | link.add_argument("--unlink", action="store_true") |
| 84 | |
| 85 | create_superuser = subcommands.add_parser( |
| 86 | "create-superuser", |
| 87 | help="create an admin-role user and prompt for its password", |
| 88 | ) |
| 89 | create_superuser.add_argument("--user-id", required=True) |
| 90 | create_superuser.add_argument("--email") |
| 91 | create_superuser.add_argument("--display-name") |
| 92 | create_superuser.add_argument("--account-id") |
| 93 | create_superuser.add_argument( |
| 94 | "--password-stdin", |
| 95 | action="store_true", |
| 96 | help="read the password from stdin instead of prompting", |
| 97 | ) |
| 98 | |
| 99 | set_password = subcommands.add_parser("set-password", help="set or replace a user password; ends their sessions, keeps API keys") |
| 100 | set_password.add_argument("--user-id", required=True) |
| 101 | set_password.add_argument( |
| 102 | "--password-stdin", |
| 103 | action="store_true", |
| 104 | help="read the password from stdin instead of prompting", |
| 105 | ) |
| 106 | |
| 107 | remove_password = subcommands.add_parser("remove-password", help="remove a user password; ends their sessions, keeps API keys") |
| 108 | remove_password.add_argument("--user-id", required=True) |
| 109 | |
| 110 | clear_leftovers = subcommands.add_parser( |
| 111 | "clear-leftovers", |
| 112 | help="for a user id with no user: remove its password, end its sessions, delete its API keys", |
| 113 | ) |
| 114 | clear_leftovers.add_argument("--user-id", required=True) |
| 115 | |
| 116 | list_accounts = subcommands.add_parser("list-accounts", help="list accounts") |
| 117 | list_accounts.add_argument("--json", action="store_true") |
| 118 | |
| 119 | list_users = subcommands.add_parser("list-users", help="list users") |
| 120 | list_users.add_argument("--account-id") |
| 121 | list_users.add_argument("--json", action="store_true") |
| 122 | |
| 123 | args = parser.parse_args(argv) |
| 124 | base_dir = _base_dir(args.data_dir) |
| 125 | |
| 126 | try: |
| 127 | if args.command == "create-account": |
| 128 | account = object_identity.create_account( |
| 129 | {"account_id": args.account_id, "name": args.name}, |
| 130 | base_dir=base_dir, |
| 131 | ) |
| 132 | print(f"Created account {account['account_id']}") |
| 133 | return 0 |
| 134 | |
| 135 | if args.command in {"disable-account", "enable-account"}: |
| 136 | disable = args.command == "disable-account" |
| 137 | result = object_identity.set_account_status( |
| 138 | args.account_id, |
| 139 | object_identity.DISABLED_STATUS if disable else object_identity.ACTIVE_STATUS, |
| 140 | base_dir=base_dir, |
| 141 | ) |
| 142 | account_id = result["account"]["account_id"] |
| 143 | print( |
| 144 | f"Disabled account {account_id}; {result['sessions_revoked']} session(s) " |
| 145 | "signed out (API keys kept, refused while disabled)" |
| 146 | if disable |
| 147 | else f"Enabled account {account_id}; its users can sign in and its API keys work again" |
| 148 | ) |
| 149 | return 0 |
| 150 | |
| 151 | if args.command == "set-account-subscriptions": |
| 152 | result = object_identity.set_account_subscriptions( |
| 153 | args.account_id, |
| 154 | _split_roles(args.subscriptions), |
| 155 | actor=_cli_actor(), |
| 156 | actor_method="cli", |
| 157 | base_dir=base_dir, |
| 158 | ) |
| 159 | before = ",".join(result["before"]) or "(none)" |
| 160 | after = ",".join(result["after"]) or "(none)" |
| 161 | print( |
| 162 | f"Account {result['account']['account_id']} subscriptions: {before} -> {after}" |
| 163 | if result["changed"] |
| 164 | else f"Account {result['account']['account_id']} subscriptions unchanged: {after}" |
| 165 | ) |
| 166 | return 0 |
| 167 | |
| 168 | if args.command == "create-user": |
| 169 | user = object_identity.create_user( |
| 170 | _user_payload(args, roles=_split_roles(args.roles)), |
| 171 | base_dir=base_dir, |
| 172 | ) |
| 173 | print(f"Created user {user['user_id']}") |
| 174 | return 0 |
| 175 | |
| 176 | if args.command == "set-identity-source": |
| 177 | user = object_identity.set_user_identity_source( |
| 178 | args.user_id, None if args.unlink else args.source, base_dir=base_dir |
| 179 | ) |
| 180 | print( |
| 181 | f"User {user['user_id']} linked to identity source {user['identity_source']}" |
| 182 | if user["identity_source"] |
| 183 | else f"User {user['user_id']} is not linked to any identity source" |
| 184 | ) |
| 185 | return 0 |
| 186 | |
| 187 | if args.command == "create-superuser": |
| 188 | password = _read_password(password_stdin=args.password_stdin) |
| 189 | user = _create_superuser(_user_payload(args, roles=[ADMIN_ROLE]), password, base_dir) |
| 190 | print(f"Created superuser {user['user_id']} with role {ADMIN_ROLE} and password set") |
| 191 | return 0 |
| 192 | |
| 193 | if args.command == "set-password": |
| 194 | object_identity.get_user(args.user_id, base_dir=base_dir) |
| 195 | password = _read_password(password_stdin=args.password_stdin) |
| 196 | result = object_credentials.set_password(args.user_id, password, base_dir=base_dir) |
| 197 | print( |
| 198 | f"Password {result['operation']} for user {result['user_id']}; " |
| 199 | f"{result['sessions_revoked']} session(s) signed out (API keys unchanged)" |
| 200 | ) |
| 201 | return 0 |
| 202 | |
| 203 | if args.command == "remove-password": |
| 204 | try: |
| 205 | object_identity.get_user(args.user_id, base_dir=base_dir) |
| 206 | except LookupError: |
| 207 | # a password left under an id with no user (create-user refuses to hand it on): let it go |
| 208 | if not object_credentials.has_password(args.user_id, base_dir=base_dir): |
| 209 | raise |
| 210 | object_credentials.remove_password(args.user_id, base_dir=base_dir) |
| 211 | print(f"Removed the password left under user id {args.user_id}, which has no user") |
| 212 | return 0 |
| 213 | removed = object_credentials.remove_password(args.user_id, base_dir=base_dir) |
| 214 | print( |
| 215 | f"Password removed for user {args.user_id}; their sessions were signed out (API keys unchanged)" |
| 216 | if removed |
| 217 | else f"User {args.user_id} had no password" |
| 218 | ) |
| 219 | return 0 |
| 220 | |
| 221 | if args.command == "clear-leftovers": |
| 222 | # what create-user refuses to hand on to a new user under this id |
| 223 | removed = object_identity.clear_leftover_credentials(args.user_id, base_dir=base_dir) |
| 224 | print( |
| 225 | f"Cleared what was left under user id {args.user_id}, which has no user: password " |
| 226 | f"{'removed' if removed['password'] else 'none'}, {removed['sessions']} session(s) signed out, " |
| 227 | f"{removed['api_keys']} API key(s) deleted" |
| 228 | ) |
| 229 | return 0 |
| 230 | |
| 231 | if args.command == "list-accounts": |
| 232 | accounts = object_identity.list_accounts(base_dir=base_dir) |
| 233 | if args.json: |
| 234 | print(json.dumps(accounts, indent=2)) |
| 235 | else: |
| 236 | for account in accounts: |
| 237 | print(f"{account['account_id']}\t{account['status']}\t{account['name']}") |
| 238 | print(f"{len(accounts)} account(s)") |
| 239 | return 0 |
| 240 | |
| 241 | if args.command == "list-users": |
| 242 | users = object_identity.list_users(account_id=args.account_id, base_dir=base_dir) |
| 243 | if args.json: |
| 244 | print(json.dumps(users, indent=2)) |
| 245 | else: |
| 246 | for user in users: |
| 247 | roles = ",".join(user["roles"]) |
| 248 | has_password = object_credentials.has_password( |
| 249 | user["user_id"], base_dir=base_dir |
| 250 | ) |
| 251 | password_state = "password" if has_password else "no-password" |
| 252 | print( |
| 253 | f"{user['user_id']}\t{user['status']}\t{user['email'] or '-'}" |
| 254 | f"\t{roles or '-'}\t{password_state}" |
| 255 | ) |
| 256 | print(f"{len(users)} user(s)") |
| 257 | return 0 |
| 258 | except ( |
| 259 | ValueError, |
| 260 | LookupError, |
| 261 | object_credentials.SessionRevocationError, |
| 262 | object_identity.AccountSessionsNotEndedError, |
| 263 | ) as exc: |
| 264 | print(f"Error: {exc}", file=sys.stderr) |
| 265 | return 1 |
| 266 | |
| 267 | parser.error(f"Unknown command: {args.command}") |
| 268 | return 2 |
| 269 | |
| 270 | |
| 271 | def _create_superuser(payload: dict[str, object], password: str, base_dir: Path) -> dict[str, object]: |
| 272 | """Create an admin with this password, or nothing. |
| 273 | |
| 274 | The password used to be set after the admin was made, so a failure there |
| 275 | (a bad password, an unwritable credentials file) left an admin with no |
| 276 | password. Now, as in first-time setup: refuse an id that is taken, write |
| 277 | the password (which replaces any left under the id by a removed user, and |
| 278 | ends sessions left under it), then create the user, and take the password |
| 279 | back if anything after the write fails.""" |
| 280 | user_id = str(payload["user_id"]) |
| 281 | object_credentials.hash_password(password) # a password that won't do is refused before anything is written |
| 282 | try: |
| 283 | object_identity.get_user(user_id, base_dir=base_dir) |
| 284 | except LookupError: |
| 285 | pass |
| 286 | else: |
| 287 | raise object_identity.InvalidIdentityPayloadError(f"User already exists: {user_id}") |
| 288 | try: |
| 289 | object_credentials.set_password(user_id, password, base_dir=base_dir) |
| 290 | return object_identity.create_user( |
| 291 | payload, base_dir=base_dir, leftover_password=object_identity.LEFTOVER_PASSWORD_KEEP) |
| 292 | except BaseException: |
| 293 | try: |
| 294 | object_credentials.remove_password(user_id, base_dir=base_dir) |
| 295 | except object_credentials.SessionRevocationError: |
| 296 | pass # the row is deleted before sessions are ended; no user was made to hold a session |
| 297 | raise |
| 298 | |
| 299 | |
| 300 | def _base_dir(data_dir: Path | None) -> Path: |
| 301 | if data_dir is not None: |
| 302 | return data_dir |
| 303 | return Path(os.environ.get(DATA_DIR_ENV, "data")) |
| 304 | |
| 305 | |
| 306 | def _user_payload(args: argparse.Namespace, *, roles: list[str]) -> dict[str, object]: |
| 307 | payload: dict[str, object] = {"user_id": args.user_id, "roles": roles} |
| 308 | if args.email: |
| 309 | payload["email"] = args.email |
| 310 | if args.display_name: |
| 311 | payload["display_name"] = args.display_name |
| 312 | if args.account_id: |
| 313 | payload["account_id"] = args.account_id |
| 314 | if getattr(args, "identity_source", None): |
| 315 | payload["identity_source"] = args.identity_source |
| 316 | return payload |
| 317 | |
| 318 | |
| 319 | def _cli_actor() -> str: |
| 320 | """Who ran the command, for the ops line: the OS user, or just "cli".""" |
| 321 | try: |
| 322 | user = getpass.getuser() |
| 323 | except (OSError, KeyError, ImportError): |
| 324 | user = "" |
| 325 | return f"cli:{user}" if user else "cli" |
| 326 | |
| 327 | |
| 328 | def _split_roles(value: str | None) -> list[str]: |
| 329 | if not value: |
| 330 | return [] |
| 331 | return [role.strip() for role in value.split(",") if role.strip()] |
| 332 | |
| 333 | |
| 334 | def _read_password(*, password_stdin: bool) -> str: |
| 335 | if password_stdin: |
| 336 | password = sys.stdin.readline().rstrip("\n") |
| 337 | if not password: |
| 338 | raise ValueError("password on stdin is empty") |
| 339 | return password |
| 340 | |
| 341 | password = getpass.getpass("Password: ") |
| 342 | confirmation = getpass.getpass("Password (again): ") |
| 343 | if password != confirmation: |
| 344 | raise ValueError("passwords do not match") |
| 345 | return password |
| 346 | |
| 347 | |
| 348 | if __name__ == "__main__": |
| 349 | raise SystemExit(main()) |