Source code for s365b.cli

"""The ``s365b`` command: one entry point for every container role.

Examples::

    s365b migrate              # apply database migrations
    s365b api                  # run the web API
    s365b worker               # run background jobs (and the scheduler tick)
    s365b generate-master-key  # print a new master key
"""

from __future__ import annotations

import asyncio
from pathlib import Path
from typing import Annotated, NoReturn

import typer

from s365b import __version__
from s365b.core.config import get_settings
from s365b.core.logging import configure_logging

[docs] app = typer.Typer(help="Mail Safehouse", no_args_is_help=True, add_completion=False)
def _fail(message: str) -> NoReturn: typer.echo(message, err=True) raise typer.Exit(1) def _setup() -> None: settings = get_settings() configure_logging(settings.log_level, settings.log_format) @app.command()
[docs] def version() -> None: """Print the version.""" typer.echo(__version__)
@app.command("generate-master-key")
[docs] def generate_master_key( output: Annotated[Path | None, typer.Option(help="Write to this file (mode 0600)")] = None, ) -> None: """Create a new master key for encrypting secrets in the database.""" from s365b.core.secrets import generate_master_key as gen key = gen() if output is None: typer.echo(key) return if output.exists(): raise typer.BadParameter(f"{output} already exists; refusing to overwrite") output.parent.mkdir(parents=True, exist_ok=True) output.touch(mode=0o600) output.write_text(key + "\n") typer.echo(f"master key written to {output}")
@app.command()
[docs] def migrate() -> None: """Apply database migrations (app schema and job queue schema).""" _setup() from s365b.db.migrate import upgrade upgrade() asyncio.run(_apply_queue_schema()) typer.echo("database is up to date")
async def _apply_queue_schema() -> None: from psycopg import AsyncConnection from s365b.jobs.tasks import build_app settings = get_settings() async with await AsyncConnection.connect(settings.libpq_url()) as conn: exists = await (await conn.execute("SELECT to_regclass('procrastinate_jobs')")).fetchone() if exists and exists[0]: return async with build_app(settings).open_async() as qapp: await qapp.schema_manager.apply_schema_async() @app.command()
[docs] def api( host: Annotated[str, typer.Option(help="Bind address")] = "0.0.0.0", # noqa: S104 - container port: Annotated[int, typer.Option(help="Port")] = 8000, ) -> None: """Run the web API.""" _setup() import uvicorn from s365b.api.app import create_app from s365b.core.services import Services uvicorn.run( create_app(Services.from_settings(get_settings())), host=host, port=port, proxy_headers=True, forwarded_allow_ips="*", log_config=None, )
@app.command()
[docs] def worker( queues: Annotated[str, typer.Option(help="Comma-separated queues; empty for all")] = "", concurrency: Annotated[int, typer.Option(help="Jobs run at the same time")] = 2, ) -> None: """Run background jobs and the scheduler tick.""" _setup() from s365b.core.runlog import collecting from s365b.jobs.tasks import build_app, services async def run() -> None: """Run the worker until stopped, keeping each job run's log.""" async with ( collecting(services().db), build_app(get_settings()).open_async() as qapp, ): selected = [q for q in queues.split(",") if q] if selected: await qapp.run_worker_async( queues=selected, concurrency=concurrency, install_signal_handlers=True ) return await qapp.run_worker_async( concurrency=concurrency, install_signal_handlers=True, ) asyncio.run(run())
@app.command("setup-token")
[docs] def setup_token() -> None: """Issue a new one-time setup token for creating the first admin in the web UI.""" _setup() from s365b.auth.local import has_local_admin, issue_setup_token from s365b.core.services import Services async def run() -> str | None: """Issue the token unless an admin exists.""" services = Services.from_settings(get_settings()) try: async with services.db.session() as s: if await has_local_admin(s): return None return await issue_setup_token(s) finally: await services.db.dispose() token = asyncio.run(run()) if token is None: _fail("a break-glass admin already exists; use reset-local-admin instead") typer.echo(token)
@app.command("create-local-admin")
[docs] def create_local_admin(username: str) -> None: """Create a break-glass admin from the command line (prompts for password and code). Use inside the api container: ``docker compose exec api s365b create-local-admin NAME``. """ _setup() password = typer.prompt("Password (14+ characters)", hide_input=True, confirmation_prompt=True) _enrol_interactive(username, password, reset=False)
@app.command("reset-local-admin")
[docs] def reset_local_admin( username: str, new_password: Annotated[bool, typer.Option(help="Also set a new password")] = False, ) -> None: """Reset a break-glass admin's authenticator and recovery codes (and unlock it). For when the authenticator is lost and no other admin can sign in. Requires shell access to the server, which is the trust boundary. """ _setup() password = ( typer.prompt("New password (14+ characters)", hide_input=True, confirmation_prompt=True) if new_password else None ) _enrol_interactive(username, password, reset=True)
def _enrol_interactive(username: str, password: str | None, *, reset: bool) -> None: from sqlalchemy import select from s365b.auth import local from s365b.core import settings_store from s365b.core.audit import audit from s365b.core.branding import Branding from s365b.core.services import Services from s365b.db.models import AuthSource, UserAccount async def run() -> None: """Create or reset the account, then confirm a code.""" services = Services.from_settings(get_settings()) try: async with services.db.session() as s: issuer = (await settings_store.load(s, Branding)).product_name if reset: user = ( await s.execute( select(UserAccount).where( UserAccount.username == username.lower(), UserAccount.source == AuthSource.LOCAL, ) ) ).scalar_one_or_none() if user is None: _fail(f"no local user {username!r}") enrol = await local.reset_credentials( s, services.secrets, user, password=password, issuer=issuer ) else: assert password is not None # noqa: S101 - prompted above enrol = await local.create_local_admin( s, services.secrets, username, password, issuer=issuer ) await audit( s, "cli", "users.local.reset" if reset else "users.local.create", target=username.lower(), ) typer.echo( "\nAdd this account to your authenticator app:\n" f" {enrol.totp_uri}\n secret: {enrol.totp_secret}" ) typer.echo("\nRecovery codes (each works once; store them with the password):") for c in enrol.recovery_codes: typer.echo(f" {c}") for _ in range(3): code = typer.prompt("\nEnter the current code from the authenticator to activate") async with services.db.session() as s: user = await s.get(UserAccount, enrol.user_id) assert user is not None # noqa: S101 if await local.confirm_totp(s, services.secrets, user, code): await local.clear_setup_token(s) typer.echo("activated") return typer.echo("that code is not right; try again") _fail("not activated; run the command again") finally: await services.db.dispose() asyncio.run(run()) @app.command("run-job")
[docs] def run_job(job_id: int) -> None: """Queue a backup job to run now.""" _setup() from s365b.jobs.tasks import build_app, run_backup_job async def run() -> None: """Queue the job.""" async with build_app(get_settings()).open_async(): await run_backup_job.defer_async(job_id=job_id, requested_by="cli") asyncio.run(run()) typer.echo(f"job {job_id} queued")
@app.command("repository-check")
[docs] def repository_check( repair: Annotated[bool, typer.Option(help="Repair around unreadable blobs")] = False, ) -> None: """Read every blob of every repository and report unreadable ones. With --repair: remove the versions that use them, reset the affected objects so the next backup stores those items again, and delete the unreadable blobs. Waits for no one: fails if a backup is running. """ _setup() from sqlalchemy import select from s365b.core.services import Services from s365b.db.models import RepositoryConfig from s365b.jobs.repair import check_repository async def run() -> int: """Check each repository.""" services = Services.from_settings(get_settings()) unhealthy = 0 try: async with services.db.session() as s: repos = (await s.execute(select(RepositoryConfig))).scalars().all() for r in repos: rep = await check_repository(services, r.id, repair=repair) typer.echo(f"{r.name}: {rep.blobs} blobs, {len(rep.unreadable)} unreadable") for obj, n in sorted(rep.objects.items()): typer.echo(f" {obj}: {n} version(s) affected") if rep.unreadable and not rep.repaired: unhealthy += 1 typer.echo(" run again with --repair to fix") elif rep.repaired: typer.echo(" repaired: run a backup to store the affected items again") finally: await services.aclose() return unhealthy raise typer.Exit(1 if asyncio.run(run()) else 0)
if __name__ == "__main__": app()