"""Entry points. ``poorbird check`` is the one to reach for first on a fresh machine: it validates config, storage paths and database connectivity and prints what it found, without starting anything. """ from __future__ import annotations import argparse import json import os import sys from pathlib import Path from . import __version__ from .config import get_settings from .logging_setup import configure_logging def _alembic_config(): from alembic.config import Config candidate = Path(os.environ.get("POORBIRD_ALEMBIC_INI", "alembic.ini")) if not candidate.is_absolute(): candidate = Path.cwd() / candidate if not candidate.exists(): raise SystemExit( f"alembic.ini not found at {candidate}. Run from the server/ directory, " "or set POORBIRD_ALEMBIC_INI." ) cfg = Config(str(candidate)) cfg.set_main_option("script_location", str(candidate.parent / "migrations")) return cfg def cmd_serve(args: argparse.Namespace) -> int: import uvicorn settings = get_settings() uvicorn.run( "poorbird.api.app:app", host=args.host or settings.api_host, port=args.port or settings.api_port, reload=args.reload, log_config=None, # our own stdout logging, see logging_setup ) return 0 def cmd_worker(_args: argparse.Namespace) -> int: from .worker import run return run() def cmd_migrate(_args: argparse.Namespace) -> int: from alembic import command command.upgrade(_alembic_config(), "head") return 0 def cmd_enqueue(args: argparse.Namespace) -> int: from .db import SessionLocal from .worker.queue import enqueue payload = json.loads(args.payload) if args.payload else {} with SessionLocal() as session: job = enqueue(session, args.kind, payload) session.commit() print(f"queued job {job.id} ({args.kind})") return 0 # --- users ------------------------------------------------------------------ # # Accounts are created here, not over HTTP. There is no public registration and # no "first run" web form: both are bootstrap paths that stay reachable forever # and have to be defended forever. A CLI command needs shell access on the # server, which is already the trust boundary. def _read_new_password(from_stdin: bool) -> str: """Prompt twice, or read one line from stdin. Never a command-line argument: that lands in shell history, in the process table, and in any log that records commands. """ import getpass from .passwords import WeakPassword, validate_password_strength if from_stdin: # Two line-ending hazards, both silent, both only discoverable by # failing to log in with a password you know is right: # # rstrip("\r\n") rather than rstrip("\n"), or a CRLF pipe leaves the # carriage return inside the password. # # lstrip("") because Windows PowerShell prepends a UTF-8 BOM # when it pipes to a native executable. A BOM is never part of an # intended password, and this cost a debugging session to find. password = sys.stdin.readline().rstrip("\r\n").lstrip("") else: password = getpass.getpass("password: ") if password != getpass.getpass("repeat: "): raise SystemExit("passwords did not match") try: validate_password_strength(password) except WeakPassword as exc: raise SystemExit(f"{exc}") from exc return password def cmd_user_add(args: argparse.Namespace) -> int: from sqlalchemy import select from .db import SessionLocal from .models import User from .passwords import hash_password from .totp import new_secret, provisioning_uri password = _read_new_password(args.password_stdin) # TODO 3.0: 2FA is enforced for admin. Enforcing that at login instead # would mean the only admin could be locked out by their own account -- so # it is enforced at creation, where the secret can still be handed over. with_totp = args.totp if with_totp is None: with_totp = args.role == "admin" if args.role == "admin" and not with_totp: print("warning: creating an admin without TOTP, against the TODO 3.0 policy") with SessionLocal() as session: if session.scalar(select(User).where(User.username == args.username)) is not None: raise SystemExit(f"user {args.username!r} already exists") secret = new_secret() if with_totp else None session.add( User( username=args.username, email=args.email, password_hash=hash_password(password), role=args.role, totp_secret=secret, ) ) session.commit() print(f"created {args.role} {args.username!r}") if secret is not None: # Shown exactly once. It is stored so the server can verify codes, but # printing it again later would turn a one-time handover into a # standing way to mint a second authenticator. print("\nScan this in an authenticator app now -- it is not shown again:") print(f" {provisioning_uri(secret, args.username)}") print(f"\n (manual entry key: {secret})") return 0 def cmd_user_list(_args: argparse.Namespace) -> int: from sqlalchemy import select from .db import SessionLocal from .models import User with SessionLocal() as session: users = session.scalars(select(User).order_by(User.id)).all() if not users: print("no users. Create one with: poorbird user add --role admin") return 0 print(f"{'id':>4} {'username':<20} {'role':<8} {'2fa':<4} {'active':<7} last login") for u in users: last = u.last_login_at.strftime("%Y-%m-%d %H:%M") if u.last_login_at else "never" print( f"{u.id:>4} {u.username:<20} {u.role:<8} " f"{'yes' if u.totp_secret else 'no':<4} " f"{'yes' if u.is_active else 'NO':<7} {last}" ) return 0 def cmd_user_passwd(args: argparse.Namespace) -> int: from sqlalchemy import select from .db import SessionLocal from .models import Session as UserSession from .models import User from .passwords import hash_password password = _read_new_password(args.password_stdin) with SessionLocal() as session: user = session.scalar(select(User).where(User.username == args.username)) if user is None: raise SystemExit(f"no such user: {args.username!r}") user.password_hash = hash_password(password) # A password change has to end existing sessions, or the old # credential effectively still works through any browser that is # already signed in -- which is the main reason people change it. killed = ( session.query(UserSession) .filter(UserSession.user_id == user.id) .delete(synchronize_session=False) ) session.commit() print(f"password updated for {args.username!r}; {killed} session(s) signed out") return 0 def cmd_seed(args: argparse.Namespace) -> int: from .db import SessionLocal from .seed import clear, generate with SessionLocal() as session: if args.clear: captures, devices = clear(session) print(f"removed {captures} seeded capture(s) and {devices} seed device(s)") return 0 print(f"generating {args.captures} capture(s) over {args.days} day(s)...") made = generate( session, count=args.captures, days=args.days, device_name=args.device_name, thumbnails=not args.no_thumbnails, ) print(f"\ndone: {made} capture(s) on device {args.device_name!r}") print("Remove them again with: poorbird seed --clear") return 0 def cmd_check(_args: argparse.Namespace) -> int: settings = get_settings() problems: list[str] = [] print(f"poorbird {__version__}") print(f" python {sys.version.split()[0]}") # Never print the password. if not settings.database_url_is_set: print(" database_url NOT SET (POORBIRD_DATABASE_URL)") problems.append("POORBIRD_DATABASE_URL not set") else: url = settings.database_url if "@" in url: scheme, _, rest = url.partition("://") url = f"{scheme}://***@{rest.rpartition('@')[2]}" print(f" database_url {url}") try: from sqlalchemy import text from .db import engine with engine.connect() as conn: version = conn.execute(text("SHOW server_version")).scalar() print(f" database reachable (PostgreSQL {version})") except Exception as exc: # noqa: BLE001 print(f" database UNREACHABLE: {type(exc).__name__}: {exc}") problems.append("database unreachable") try: from alembic import command print(" migrations ", end="") command.current(_alembic_config()) except SystemExit as exc: print(f"not checked ({exc})") except Exception as exc: # noqa: BLE001 print(f"error: {type(exc).__name__}: {exc}") for path in settings.storage_paths(): if not path.exists(): print(f" path {path} MISSING") problems.append(f"{path} missing") elif not os.access(path, os.W_OK): print(f" path {path} NOT WRITABLE") problems.append(f"{path} not writable") else: print(f" path {path} ok") if not settings.enroll_secret_is_set: print(" enroll_secret NOT SET (device enrollment will refuse requests)") # The Caddy handoff (SPEC 3.3) needs the app and the proxy to agree on the # layout: Caddy serves the PARENT of both roots and the app sends paths # under /images and /thumbs. If the directories are not siblings with # those names, every image 404s from Caddy with nothing in the app's log # to explain it -- so it is worth saying here rather than discovering in a # browser. if settings.serve_images_directly: print(" images served by the app (development only)") else: from .api.delivery import IMAGE_URL_PREFIX, THUMB_URL_PREFIX image_root, thumb_root = settings.image_root, settings.thumb_root expected_image = IMAGE_URL_PREFIX.lstrip("/") expected_thumb = THUMB_URL_PREFIX.lstrip("/") if ( image_root.parent != thumb_root.parent or image_root.name != expected_image or thumb_root.name != expected_thumb ): print( f" images LAYOUT MISMATCH: Caddy expects " f"/{expected_image} and /{expected_thumb}, " f"got {image_root} and {thumb_root}" ) problems.append("image/thumb roots do not match the Caddy handoff layout") else: print(f" images handed off to Caddy from {image_root.parent}") if problems: print(f"\n{len(problems)} problem(s): " + "; ".join(problems)) return 1 print("\nall checks passed") return 0 def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="poorbird", description="poorBird server") parser.add_argument("--version", action="version", version=__version__) sub = parser.add_subparsers(dest="command", required=True) p = sub.add_parser("serve", help="run the HTTP API") p.add_argument("--host") p.add_argument("--port", type=int) p.add_argument("--reload", action="store_true", help="development only") p.set_defaults(func=cmd_serve) p = sub.add_parser("worker", help="run the job queue worker and scheduler") p.set_defaults(func=cmd_worker) p = sub.add_parser("migrate", help="apply migrations (alembic upgrade head)") p.set_defaults(func=cmd_migrate) p = sub.add_parser("check", help="validate config, storage and database") p.set_defaults(func=cmd_check) p = sub.add_parser("enqueue", help="put a job on the queue (smoke test)") p.add_argument("kind") p.add_argument("payload", nargs="?", help="JSON object") p.set_defaults(func=cmd_enqueue) p = sub.add_parser( "seed", help="generate synthetic captures for gallery development", description=( "Creates captures on a dedicated seed device, with real JPEGs on disk. " "--clear removes them again, and is scoped to seed devices only, so a " "real camera's captures are never in scope." ), ) p.add_argument("--captures", type=int, default=500, help="how many frames (default 500)") p.add_argument("--days", type=int, default=14, help="spread them over this many days") p.add_argument("--device-name", default="seed-cam") p.add_argument( "--no-thumbnails", action="store_true", help="leave thumb_path NULL so the worker generates them, which is how to " "exercise the queue at volume", ) p.add_argument("--clear", action="store_true", help="delete all seeded data instead") p.set_defaults(func=cmd_seed) p = sub.add_parser("user", help="manage UI accounts (there is no web signup)") usersub = p.add_subparsers(dest="user_command", required=True) q = usersub.add_parser("add", help="create an account") q.add_argument("username") q.add_argument("--role", choices=["admin", "editor", "viewer"], default="viewer") q.add_argument("--email") q.add_argument( "--totp", dest="totp", action="store_true", default=None, help="enable TOTP (the default for --role admin)", ) q.add_argument("--no-totp", dest="totp", action="store_false", help="disable TOTP") q.add_argument( "--password-stdin", action="store_true", help="read the password from stdin, not a prompt" ) q.set_defaults(func=cmd_user_add) q = usersub.add_parser("list", help="list accounts") q.set_defaults(func=cmd_user_list) q = usersub.add_parser("passwd", help="set a password and sign out that user's sessions") q.add_argument("username") q.add_argument("--password-stdin", action="store_true") q.set_defaults(func=cmd_user_passwd) args = parser.parse_args(argv) settings = get_settings() configure_logging(settings.log_level, settings.log_format) return args.func(args) if __name__ == "__main__": raise SystemExit(main())