diff --git a/README.md b/README.md index d24b8dd4..b8b764f0 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,17 @@ python run.py Open http://localhost:5000 in your browser. +## API documentation + +- [Public API reference](docs/api/index.html) - authentication, pagination, + structured errors, webhook verification, and the registered endpoints. +- [OpenAPI 3.1 spec](docs/openapi.json) - regenerate both with + `python scripts/render_api_docs.py`. + +The reference is served by the running app at `/api/docs` and is linked from +the footer. Only `/api/v1` resources have frozen response schemas; other listed +paths keep their existing web-UI contracts. + ## Who it's for - Developers who want AI help grounded in their actual codebase diff --git a/app/__init__.py b/app/__init__.py index f07ca7d0..2bd17cb2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -103,6 +103,8 @@ def create_app(config_name: str | None = None) -> Flask: # Register blueprints. from app.admin import bp as admin_bp + from app.api.docs import bp as api_docs_bp + from app.api.v1 import bp as api_v1_bp from app.auth import bp as auth_bp from app.billing import bp as billing_bp from app.chat import bp as chat_bp @@ -130,6 +132,8 @@ def create_app(config_name: str | None = None) -> Flask: app.register_blueprint(main_bp) app.register_blueprint(chat_bp) app.register_blueprint(chat_api_bp) + app.register_blueprint(api_docs_bp) + app.register_blueprint(api_v1_bp) app.register_blueprint(prompts_bp) app.register_blueprint(tools_bp) app.register_blueprint(github_bp) diff --git a/app/api/docs.py b/app/api/docs.py new file mode 100644 index 00000000..e603c3b7 --- /dev/null +++ b/app/api/docs.py @@ -0,0 +1,16 @@ +"""Serve the generated public API reference (#655).""" + +from pathlib import Path + +from flask import Blueprint, send_from_directory + +bp = Blueprint("api_docs", __name__, url_prefix="/api") + +DOCS_DIR = Path(__file__).resolve().parents[2] / "docs" / "api" + + +@bp.route("/docs") +@bp.route("/docs/") +def api_docs(): + """Return the static reference generated by ``scripts/render_api_docs.py``.""" + return send_from_directory(DOCS_DIR, "index.html") diff --git a/app/api/v1.py b/app/api/v1.py new file mode 100644 index 00000000..8f6859fe --- /dev/null +++ b/app/api/v1.py @@ -0,0 +1,190 @@ +"""Stable public API v1 resources (#646). + + GET /api/v1/projects list the caller's projects + GET /api/v1/projects/ one project + GET /api/v1/reviews list the caller's reviews + GET /api/v1/reviews/ one review + GET /api/v1/usage bounded usage-ledger page + +Authorization matches the web UI exactly: projects and reviews are scoped to +``current_user.id`` and another user's row is reported as ``404`` (never as a +403 existence oracle). Usage is always scoped to the authenticated user. +Errors use the shared code catalog via :func:`error_response`. +""" + +from __future__ import annotations + +import functools + +from flask import Blueprint, jsonify, request +from flask_login import current_user + +from app.api.error_catalog import INVALID_INPUT, NOT_FOUND, UNAUTHORIZED, error_response +from app.models import Project, Review +from app.services import pagination, usage_ledger + +bp = Blueprint("api_v1", __name__, url_prefix="/api/v1") + + +def _login_required(view): + @functools.wraps(view) + def wrapper(*args, **kwargs): + if not current_user.is_authenticated: + return error_response(UNAUTHORIZED) + return view(*args, **kwargs) + + return wrapper + + +def _page_request(): + """Validate page/limit/cursor, returning ``(request, error_response)``.""" + try: + return pagination.parse_page_request(request.args), None + except pagination.PaginationError as exc: + return None, error_response(INVALID_INPUT, str(exc)) + + +def _cursor_id(page) -> int | None: + """Return the opaque cursor's ``id``, or ``None`` when absent.""" + if page.cursor is None: + return None + if set(page.cursor) != {"id"}: + raise pagination.PaginationError("Invalid cursor.") + value = page.cursor["id"] + if isinstance(value, bool) or not isinstance(value, int): + raise pagination.PaginationError("Invalid cursor.") + return value + + +def _paginate(query, model, page): + """Return ``(rows, total, next_cursor)`` for a stable id-ordered list.""" + total = query.count() + cursor_id = _cursor_id(page) + query = query.order_by(model.id.desc()) + if cursor_id is not None: + query = query.filter(model.id < cursor_id) + else: + query = query.offset((page.page - 1) * page.limit) + rows = query.limit(page.limit + 1).all() + has_more = len(rows) > page.limit + rows = rows[: page.limit] + next_cursor = pagination.encode_cursor({"id": rows[-1].id}) if has_more and rows else None + return rows, total, next_cursor + + +def _list_payload(items, total, page, next_cursor): + return { + "items": items, + "total": total, + "page": page.page, + "limit": page.limit, + "next_cursor": next_cursor, + } + + +def _optional_int(name: str): + """Parse an optional integer query argument, or return ``(None, error)``.""" + raw = request.args.get(name) + if raw in (None, ""): + return None, None + try: + return int(raw), None + except (TypeError, ValueError): + return None, error_response(INVALID_INPUT, f"{name} must be an integer.") + + +@bp.route("/projects", methods=["GET"]) +@_login_required +def list_projects(): + """List the caller's projects, newest id first.""" + page, error = _page_request() + if error is not None: + return error + + workspace_id, error = _optional_int("workspace_id") + if error is not None: + return error + query = Project.query.filter_by(user_id=current_user.id) + if workspace_id is not None: + query = query.filter_by(workspace_id=workspace_id) + try: + rows, total, next_cursor = _paginate(query, Project, page) + except pagination.PaginationError as exc: + return error_response(INVALID_INPUT, str(exc)) + return jsonify(_list_payload([row.to_dict() for row in rows], total, page, next_cursor)) + + +@bp.route("/projects/", methods=["GET"]) +@_login_required +def get_project(project_id: int): + """Return one project owned by the caller.""" + project = Project.query.filter_by(id=project_id, user_id=current_user.id).first() + if project is None: + return error_response(NOT_FOUND) + return jsonify(project.to_dict()) + + +@bp.route("/reviews", methods=["GET"]) +@_login_required +def list_reviews(): + """List the caller's reviews, newest id first.""" + page, error = _page_request() + if error is not None: + return error + + query = Review.query.filter_by(user_id=current_user.id) + for name in ("source", "kind", "status"): + value = request.args.get(name) + if value: + query = query.filter_by(**{name: value}) + project_id, error = _optional_int("project_id") + if error is not None: + return error + if project_id is not None: + query = query.filter_by(project_id=project_id) + + try: + rows, total, next_cursor = _paginate(query, Review, page) + except pagination.PaginationError as exc: + return error_response(INVALID_INPUT, str(exc)) + return jsonify(_list_payload([row.to_dict() for row in rows], total, page, next_cursor)) + + +@bp.route("/reviews/", methods=["GET"]) +@_login_required +def get_review(review_id: int): + """Return one review owned by the caller.""" + review = Review.query.filter_by(id=review_id, user_id=current_user.id).first() + if review is None: + return error_response(NOT_FOUND) + return jsonify(review.to_dict()) + + +@bp.route("/usage", methods=["GET"]) +@_login_required +def list_usage(): + """Return a bounded page of the caller's usage-ledger records.""" + page, error = _page_request() + if error is not None: + return error + if page.cursor is not None: + return error_response( + INVALID_INPUT, "Cursor pagination is not supported here; use page and limit." + ) + + workspace_id, error = _optional_int("workspace_id") + if error is not None: + return error + project_id, error = _optional_int("project_id") + if error is not None: + return error + + payload = usage_ledger.export_payload( + user_id=current_user.id, + workspace_id=workspace_id, + project_id=project_id, + source=request.args.get("source") or None, + page=page.page, + limit=page.limit, + ) + return jsonify(payload) diff --git a/app/auth/routes.py b/app/auth/routes.py index 98a06457..944e9df2 100644 --- a/app/auth/routes.py +++ b/app/auth/routes.py @@ -6,6 +6,7 @@ """ import json +from functools import wraps from urllib.parse import urljoin, urlparse from flask import Response, flash, jsonify, redirect, render_template, request, url_for @@ -13,16 +14,62 @@ from app.api.error_catalog import ( CONFLICT, + FORBIDDEN, GONE, INVALID_INPUT, NOT_FOUND, RATE_LIMITED, + UNAUTHORIZED, error_response, ) from app.auth import bp from app.extensions import db from app.models import User, UserDataExport -from app.services import audit, chat_audit, data_export +from app.services import audit, chat_audit, data_export, domain_verification + + +def _api_login_required(view): + """Reject unauthenticated JSON API calls with the catalog 401 shape.""" + + @wraps(view) + def wrapper(*args, **kwargs): + if not current_user.is_authenticated: + return error_response(UNAUTHORIZED) + return view(*args, **kwargs) + + return wrapper + + +def _domain_error_response(exc: Exception): + """Map a domain-verification failure to a structured catalog response.""" + if isinstance(exc, domain_verification.DomainPermissionDenied): + code = FORBIDDEN + elif isinstance(exc, domain_verification.ChallengeExpired): + code = GONE + elif isinstance( + exc, (domain_verification.DomainConflict, domain_verification.DomainNotVerified) + ): + code = CONFLICT + elif isinstance(exc, LookupError): + code = NOT_FOUND + else: + code = INVALID_INPUT + db.session.rollback() + return error_response(code, str(exc)) + + +def _domain_payload(data: dict | None) -> tuple[int, str] | None: + """Return ``(workspace_id, domain)`` from a JSON body, or ``None``.""" + if not isinstance(data, dict): + return None + try: + workspace_id = int(data.get("workspace_id")) + except (TypeError, ValueError): + return None + domain = data.get("domain") + if not isinstance(domain, str): + return None + return workspace_id, domain def _is_safe_redirect_target(target: str) -> bool: @@ -118,6 +165,22 @@ def login(): status="failure", reason="invalid_credentials", ) + elif domain_verification.is_email_domain_enforced(user.email): + error = ( + "Password sign-in is disabled for your organization. " + "Use single sign-on (SSO) to continue." + ) + audit.record( + audit.LOGIN_FAILURE, + user=user, + target_type="user", + target_id=user.id, + metadata={"email": email, "reason": "sso_enforced"}, + ) + db.session.commit() + chat_audit.log_event( + "chat.login", user_id=user.id, status="failure", reason="sso_enforced" + ) elif not user.is_active: error = "This account has been disabled. Contact support." audit.record( @@ -166,6 +229,105 @@ def me(): return render_template("auth/me.html") +@bp.route("/api/domains", methods=["GET"]) +@_api_login_required +def list_domains(): + """List the workspace's verified and pending domains (owner only).""" + workspace_id = request.args.get("workspace_id", type=int) + if workspace_id is None: + return error_response(INVALID_INPUT, "workspace_id must be an integer.") + try: + rows = domain_verification.list_domains(workspace_id) + except Exception as exc: + return _domain_error_response(exc) + return jsonify({"items": [row.to_dict() for row in rows]}) + + +@bp.route("/api/domains/challenge", methods=["POST"]) +@_api_login_required +def create_domain_challenge(): + """Create or refresh a bounded DNS TXT ownership challenge.""" + parsed = _domain_payload(request.get_json(silent=True)) + if parsed is None: + return error_response( + INVALID_INPUT, "workspace_id (integer) and domain (string) are required." + ) + workspace_id, domain = parsed + try: + row = domain_verification.create_challenge(workspace_id, domain) + except Exception as exc: + return _domain_error_response(exc) + + audit.record( + audit.DOMAIN_CHALLENGE_CREATED, + workspace_id=workspace_id, + user=current_user, + target_type="workspace_domain", + target_id=row.id, + metadata={"domain": row.domain}, + ) + db.session.commit() + payload = row.to_dict() + payload["txt_record_name"] = domain_verification.txt_record_name(row.domain) + payload["txt_record_value"] = domain_verification.expected_txt_value(row.verification_token) + return jsonify(payload), 201 + + +@bp.route("/api/domains/verify", methods=["POST"]) +@_api_login_required +def verify_domain(): + """Verify a challenge by reading the domain's DNS TXT record.""" + parsed = _domain_payload(request.get_json(silent=True)) + if parsed is None: + return error_response( + INVALID_INPUT, "workspace_id (integer) and domain (string) are required." + ) + workspace_id, domain = parsed + try: + row = domain_verification.verify_domain(workspace_id, domain) + except Exception as exc: + return _domain_error_response(exc) + + audit.record( + audit.DOMAIN_VERIFIED, + workspace_id=workspace_id, + user=current_user, + target_type="workspace_domain", + target_id=row.id, + metadata={"domain": row.domain}, + ) + db.session.commit() + return jsonify(row.to_dict()) + + +@bp.route("/api/domains/", methods=["PATCH"]) +@_api_login_required +def update_domain(domain_id: int): + """Enable or disable SSO enforcement for a verified domain.""" + data = request.get_json(silent=True) + if not isinstance(data, dict) or not isinstance(data.get("enforce_sso"), bool): + return error_response(INVALID_INPUT, "enforce_sso must be a boolean.") + try: + workspace_id = int(data.get("workspace_id")) + except (TypeError, ValueError): + return error_response(INVALID_INPUT, "workspace_id must be an integer.") + try: + row = domain_verification.set_enforcement(workspace_id, domain_id, data["enforce_sso"]) + except Exception as exc: + return _domain_error_response(exc) + + audit.record( + audit.DOMAIN_SSO_ENFORCEMENT_CHANGED, + workspace_id=workspace_id, + user=current_user, + target_type="workspace_domain", + target_id=row.id, + metadata={"domain": row.domain, "enforce_sso": row.enforce_sso}, + ) + db.session.commit() + return jsonify(row.to_dict()) + + @bp.route("/api/data-export", methods=["GET", "POST"]) @login_required def data_export_requests(): diff --git a/app/models/__init__.py b/app/models/__init__.py index 5bf7af80..0d400944 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -57,6 +57,7 @@ ) from app.models.workspace import Workspace from app.models.workspace_budget_override import WorkspaceBudgetOverride +from app.models.workspace_domain import WorkspaceDomain from app.models.workspace_member import WorkspaceMember from app.models.workspace_price_override import PriceOverride, WorkspacePriceOverride from app.models.workspace_settings import WorkspaceSettings @@ -116,6 +117,7 @@ "WebhookSubscriptionEvent", "Workspace", "WorkspaceBudgetOverride", + "WorkspaceDomain", "WorkspaceInvitation", "WorkspaceMember", "WorkspacePriceOverride", diff --git a/app/models/workspace_domain.py b/app/models/workspace_domain.py new file mode 100644 index 00000000..cf6fda2c --- /dev/null +++ b/app/models/workspace_domain.py @@ -0,0 +1,66 @@ +"""Verified email domains and SSO enforcement (Phase 11, #590). + +An organization (workspace) proves it owns an email domain by publishing a +short-lived DNS TXT challenge. Once verified, the domain can be marked +``enforce_sso``; password sign-in for accounts on that domain is then refused +until they authenticate through the organization's SSO flow. + +The challenge token is only an ownership proof, not an authentication secret: +someone who can publish the TXT record already controls the domain. It is +still bounded by :data:`~app.services.domain_verification.CHALLENGE_TTL` so an +abandoned challenge cannot be completed indefinitely. +""" + +from datetime import UTC, datetime + +from app.extensions import db + + +class WorkspaceDomain(db.Model): + """One email domain claimed by a workspace.""" + + __tablename__ = "workspace_domains" + __table_args__ = (db.UniqueConstraint("domain", name="uq_workspace_domains_domain"),) + + id = db.Column(db.Integer, primary_key=True) + workspace_id = db.Column( + db.Integer, + db.ForeignKey("workspaces.id", ondelete="CASCADE"), + nullable=False, + index=True, + ) + domain = db.Column(db.String(253), nullable=False, index=True) + verification_token = db.Column(db.String(128), nullable=False) + challenge_expires_at = db.Column(db.DateTime(timezone=True), nullable=False) + verified_at = db.Column(db.DateTime(timezone=True), nullable=True) + enforce_sso = db.Column(db.Boolean, nullable=False, default=False) + created_at = db.Column( + db.DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC) + ) + updated_at = db.Column( + db.DateTime(timezone=True), + nullable=False, + default=lambda: datetime.now(UTC), + onupdate=lambda: datetime.now(UTC), + ) + + @property + def is_verified(self) -> bool: + return self.verified_at is not None + + def to_dict(self) -> dict: + """Serialize the domain without exposing internal implementation detail.""" + return { + "id": self.id, + "workspace_id": self.workspace_id, + "domain": self.domain, + "verified_at": self.verified_at.isoformat() if self.verified_at else None, + "challenge_expires_at": ( + self.challenge_expires_at.isoformat() if self.challenge_expires_at else None + ), + "enforce_sso": bool(self.enforce_sso), + "created_at": self.created_at.isoformat() if self.created_at else None, + } + + def __repr__(self) -> str: # pragma: no cover - debugging aid + return f"" diff --git a/app/services/audit.py b/app/services/audit.py index 460b1cfb..2e14cd2e 100644 --- a/app/services/audit.py +++ b/app/services/audit.py @@ -43,6 +43,9 @@ DATA_EXPORT_EXPIRED = "data_export_expired" SIEM_ENDPOINT_CONFIGURED = "siem_endpoint_configured" SIEM_ENDPOINT_DELETED = "siem_endpoint_deleted" +DOMAIN_CHALLENGE_CREATED = "domain_challenge_created" +DOMAIN_VERIFIED = "domain_verified" +DOMAIN_SSO_ENFORCEMENT_CHANGED = "domain_sso_enforcement_changed" #: The "previous hash" of the first hashed row in a chain. GENESIS_HASH = "0" * 64 diff --git a/app/services/domain_verification.py b/app/services/domain_verification.py new file mode 100644 index 00000000..48fc18af --- /dev/null +++ b/app/services/domain_verification.py @@ -0,0 +1,252 @@ +"""DNS TXT domain verification and SSO enforcement (#590). + +The flow is deliberately small: + +1. A workspace owner creates a challenge for a domain. We store a random token + and an expiry (bounded by :data:`CHALLENGE_TTL`). +2. The owner publishes ``aica-verify=`` as a TXT record at + ``_aica-verification.``. +3. The owner asks us to verify. We read the TXT record and only mark the domain + verified when the exact expected value is present before the expiry. +4. The owner may then set ``enforce_sso``; password login for accounts on that + domain is blocked in :mod:`app.auth.routes`. + +Every mutating operation resolves the same ``manage_settings`` workspace +capability used by the web UI, so an API caller can never do more than the +owner could in the browser. +""" + +from __future__ import annotations + +import re +import secrets +from datetime import UTC, datetime, timedelta + +from flask_login import current_user +from sqlalchemy.exc import IntegrityError + +from app.extensions import db +from app.models import WorkspaceDomain +from app.services.permissions import can + +#: A challenge is valid for 24 hours; an abandoned verification must be redone. +CHALLENGE_TTL = timedelta(hours=24) + +#: Prefix of the TXT record the organization publishes. +TXT_RECORD_PREFIX = "_aica-verification" + +#: Value prefix inside that record. +TXT_VALUE_PREFIX = "aica-verify=" + +#: DNS lookups must not hang a request. +DNS_TIMEOUT_SECONDS = 5 + +_DOMAIN_RE = re.compile( + r"^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+" + r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$" +) + + +class DomainVerificationError(ValueError): + """Base class for a rejected domain operation.""" + + +class InvalidDomain(DomainVerificationError): + """The supplied domain is not a valid DNS name.""" + + +class DomainPermissionDenied(DomainVerificationError): + """The caller is not allowed to manage this workspace's domains.""" + + +class DomainConflict(DomainVerificationError): + """The domain is already claimed, verified, or otherwise conflicting.""" + + +class ChallengeExpired(DomainVerificationError): + """The DNS challenge is past its expiry.""" + + +class VerificationFailed(DomainVerificationError): + """The expected TXT record was not found.""" + + +class DomainNotVerified(DomainVerificationError): + """Enforcement requires a verified domain.""" + + +def _now(value: datetime | None = None) -> datetime: + moment = value or datetime.now(UTC) + if moment.tzinfo is None: + return moment.replace(tzinfo=UTC) + return moment.astimezone(UTC) + + +def normalize_domain(raw: str | None) -> str: + """Return a lowercase DNS domain, or raise :class:`InvalidDomain`.""" + domain = (raw or "").strip().lower().rstrip(".") + if not domain or len(domain) > 253 or not _DOMAIN_RE.match(domain): + raise InvalidDomain("Enter a valid domain name such as example.com.") + return domain + + +def txt_record_name(domain: str) -> str: + """Return the DNS name the organization must publish.""" + return f"{TXT_RECORD_PREFIX}.{normalize_domain(domain)}" + + +def expected_txt_value(token: str) -> str: + """Return the TXT value that proves the challenge.""" + return f"{TXT_VALUE_PREFIX}{token}" + + +def _default_resolver(name: str) -> list[str]: + """Read TXT values via dnspython (already installed for email-validator).""" + try: + import dns.resolver + except ImportError: # pragma: no cover - dependency is present in production + raise VerificationFailed("DNS lookups are not available on this server.") from None + + try: + answers = dns.resolver.resolve(name, "TXT", lifetime=DNS_TIMEOUT_SECONDS) + except Exception: # dnspython exception hierarchy is broad; treat as "not found" + return [] + + values: list[str] = [] + for rdata in answers: + try: + values.append("".join(part.decode("utf-8") for part in rdata.strings)) + except (AttributeError, UnicodeDecodeError): + continue + return values + + +def _resolve_txt(name: str, resolver=None) -> list[str]: + return list((resolver or _default_resolver)(name)) + + +def _require_manager(workspace_id: int, user=None) -> None: + if user is None: + user = current_user + if not can("manage_settings", workspace_id, user): + raise DomainPermissionDenied("You do not have permission to manage domains.") + + +def _for_workspace(workspace_id: int, domain: str) -> WorkspaceDomain | None: + return WorkspaceDomain.query.filter_by(workspace_id=workspace_id, domain=domain).first() + + +def create_challenge( + workspace_id: int, + raw_domain: str | None, + *, + user=None, + now: datetime | None = None, +) -> WorkspaceDomain: + """Create or refresh a bounded DNS challenge for ``raw_domain``.""" + domain = normalize_domain(raw_domain) + _require_manager(workspace_id, user) + moment = _now(now) + + row = _for_workspace(workspace_id, domain) + if row is not None and row.is_verified: + raise DomainConflict("This domain is already verified for the workspace.") + + claimed = WorkspaceDomain.query.filter( + WorkspaceDomain.domain == domain, + WorkspaceDomain.workspace_id != workspace_id, + ).first() + if claimed is not None: + raise DomainConflict("This domain is already claimed by another organization.") + + if row is None: + row = WorkspaceDomain(workspace_id=workspace_id, domain=domain) + db.session.add(row) + + row.verification_token = secrets.token_urlsafe(32) + row.challenge_expires_at = moment + CHALLENGE_TTL + row.verified_at = None + try: + db.session.commit() + except IntegrityError: + db.session.rollback() + raise DomainConflict("This domain is already claimed by another organization.") from None + return row + + +def verify_domain( + workspace_id: int, + raw_domain: str | None, + *, + user=None, + now: datetime | None = None, + resolver=None, +) -> WorkspaceDomain: + """Verify the challenge by reading the domain's TXT record.""" + domain = normalize_domain(raw_domain) + _require_manager(workspace_id, user) + moment = _now(now) + + row = _for_workspace(workspace_id, domain) + if row is None: + raise InvalidDomain("Create a verification challenge before verifying the domain.") + if row.is_verified: + return row + if _now(row.challenge_expires_at) <= moment: + raise ChallengeExpired("The verification challenge has expired. Create a new one.") + + expected = expected_txt_value(row.verification_token) + if expected not in _resolve_txt(txt_record_name(domain), resolver): + raise VerificationFailed( + f"Add a TXT record {txt_record_name(domain)} with the value {expected}." + ) + + row.verified_at = moment + db.session.commit() + return row + + +def set_enforcement( + workspace_id: int, + domain_id: int, + enforce: bool, + *, + user=None, +) -> WorkspaceDomain: + """Turn password-login blocking on or off for a verified domain.""" + _require_manager(workspace_id, user) + row = WorkspaceDomain.query.filter_by(id=domain_id, workspace_id=workspace_id).first() + if row is None: + raise LookupError("Domain not found.") + if enforce and not row.is_verified: + raise DomainNotVerified("Verify the domain before enforcing SSO.") + row.enforce_sso = bool(enforce) + db.session.commit() + return row + + +def list_domains(workspace_id: int, *, user=None) -> list[WorkspaceDomain]: + """List the workspace's domains for a manager.""" + _require_manager(workspace_id, user) + return ( + WorkspaceDomain.query.filter_by(workspace_id=workspace_id) + .order_by(WorkspaceDomain.domain.asc()) + .all() + ) + + +def enforced_domain_for_email(email: str) -> WorkspaceDomain | None: + """Return the verified, enforcing domain matching ``email``'s domain.""" + domain = (email or "").rsplit("@", 1)[-1].strip().lower() + if not domain: + return None + return ( + WorkspaceDomain.query.filter_by(domain=domain, enforce_sso=True) + .filter(WorkspaceDomain.verified_at.isnot(None)) + .first() + ) + + +def is_email_domain_enforced(email: str) -> bool: + """Return ``True`` when password login must be blocked for ``email``.""" + return enforced_domain_for_email(email) is not None diff --git a/app/templates/base.html b/app/templates/base.html index 3b018960..88b2806b 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -86,7 +86,9 @@
-

© {{ now.year }} {{ config.APP_NAME }}. {{ t('footer.built_with') }}

+

© {{ now.year }} {{ config.APP_NAME }}. {{ t('footer.built_with') }} + · API reference +

diff --git a/docs/api-docs.md b/docs/api-docs.md new file mode 100644 index 00000000..cceaf1be --- /dev/null +++ b/docs/api-docs.md @@ -0,0 +1,31 @@ +# Public API documentation site + +The published reference is [api/index.html](api/index.html), generated from +[openapi.json](openapi.json) by `scripts/render_api_docs.py`. The running app +serves it at `/api/docs`, and the README and app footer link to it. + +## Regenerating + +```bash +python scripts/render_api_docs.py +``` + +The generator has no third-party dependencies. It boots the application with +the testing configuration (no database access) and builds the OpenAPI document +from Flask's registered URL map, then renders one self-contained HTML page +with inline CSS. Re-run it whenever a public route changes. + +## Coverage + +- Paths are discovered automatically, so the endpoint inventory cannot drift + from the code. +- Request/response schemas are frozen only for `/api/v1` resources + ([v1 reference](api-v1.md)). Other + listed paths (for example `/api/conversations`) keep their existing + contracts and may change with the web UI; the reference says so. +- Module-private APIs under `/reviews/api`, `/workspaces/api` and similar + prefixes are intentionally not part of the public reference. +- Authentication, pagination, errors, and webhook verification are documented + on the generated page and link to their full guides: + [API errors](api-errors.md), [pagination](pagination.md), + [webhooks](webhooks.md). diff --git a/docs/api-v1.md b/docs/api-v1.md new file mode 100644 index 00000000..78d4c94f --- /dev/null +++ b/docs/api-v1.md @@ -0,0 +1,101 @@ +# Public API v1 + +Stable, versioned JSON resources for projects, reviews, and usage. The +implementation is `app/api/v1.py`; errors use the +[API error catalog](api-errors.md) and lists use the +[pagination contract](pagination.md). + +All endpoints require an authenticated session or API key. Unauthenticated +calls return `401 {"code": "unauthorized"}`. + +## Projects + +| Method | Path | Purpose | +| --- | --- | --- | +| `GET` | `/api/v1/projects` | List the caller's projects (newest id first). | +| `GET` | `/api/v1/projects/` | Return one project owned by the caller. | + +Query parameters: `workspace_id` (optional filter), plus `page`, `limit`, and +`cursor`. A project owned by another user is `404 not_found`, matching the web +UI's owner-scoped project lookup. + +Response item schema: + +```json +{ + "id": 12, + "workspace_id": 3, + "name": "my-project", + "source": "archive", + "source_url": null, + "status": "ready", + "error_message": null, + "progress": 100, + "file_count": 42, + "total_size_bytes": 123456, + "indexed_at": "2026-01-01T00:00:00+00:00", + "created_at": "2026-01-01T00:00:00+00:00", + "updated_at": "2026-01-01T00:00:00+00:00" +} +``` + +## Reviews + +| Method | Path | Purpose | +| --- | --- | --- | +| `GET` | `/api/v1/reviews` | List the caller's reviews (newest id first). | +| `GET` | `/api/v1/reviews/` | Return one review owned by the caller. | + +Query parameters: `source`, `kind`, `status`, `project_id`, plus pagination. +Only the caller's reviews are visible; another user's review is `404`. + +Response item schema: + +```json +{ + "id": 7, + "user_id": 1, + "project_id": 12, + "source": "project", + "kind": "quality", + "status": "completed", + "error_message": null, + "owner": null, + "repo": null, + "pr_number": null, + "pr_title": null, + "base_ref": null, + "head_ref": null, + "summary": {"overview": "..."}, + "findings_count": 3, + "created_at": "2026-01-01T00:00:00+00:00", + "updated_at": "2026-01-01T00:00:00+00:00" +} +``` + +## Usage + +`GET /api/v1/usage` returns a bounded page of the caller's usage-ledger rows. +It reuses the existing usage export service, so the schema is the same +`schema_version` document documented in +[usage privacy](usage-privacy.md): `filters`, `pagination`, `totals`, +`page_totals`, and `records`. Optional filters are `workspace_id`, +`project_id`, and `source`. Cursor pagination is not supported here; use +`page` and `limit` (a cursor returns `400 invalid_input` rather than being +silently ignored). + +## List envelope + +```json +{ + "items": [], + "total": 42, + "page": 1, + "limit": 50, + "next_cursor": null +} +``` + +`limit` defaults to 50 and is clamped to 100. A malformed `page`, `limit`, +cursor, or integer filter returns `400 invalid_input`. Treat `next_cursor` as +opaque; pass it back unchanged to continue after the last row. diff --git a/docs/api/index.html b/docs/api/index.html new file mode 100644 index 00000000..5cfda7c5 --- /dev/null +++ b/docs/api/index.html @@ -0,0 +1,99 @@ + + + + + +AI Code Assistant API reference + + + +

AI Code Assistant API reference

+
+

This page is generated from an OpenAPI 3.1 document. It covers +17 operations across 15 +public paths. Paths are discovered from the running application; only the +/api/v1 resources have stable, documented response schemas.

+ +

Authentication

+

Every public endpoint requires an authenticated session or API key, except +the documentation page itself. Unauthenticated requests receive +401 with {"code": "unauthorized"}. Requests are +authorized with the same ownership and workspace-role checks as the web UI.

+ +

Pagination

+

List endpoints accept page (1-based) and limit +(default 50, maximum 100) and return:

+
{"items": [], "total": 0, "page": 1, "limit": 50, "next_cursor": null}
+

Oversized limits are clamped; malformed values return a structured +400 invalid_input error. See docs/pagination.md for the +full contract.

+ +

Errors

+

Errors use one stable JSON shape:

+
{"error": "The request is invalid.", "kind": "invalid",
+"code": "invalid_input"}
+

Treat code as the contract. The catalog lives in +app/api/error_catalog.py; docs/api-errors.md lists every +code and HTTP status. Internal exception text is never exposed.

+ +

Webhook verification

+

Webhook deliveries are signed over the exact raw bytes sent: +<timestamp>.<body>, using HMAC-SHA256 with the +subscription secret. Verify the X-AICA-Signature: v1=<hex> +header against X-AICA-Timestamp with a constant-time comparison +and reject timestamps outside the 300-second tolerance window. Verify the raw +body before parsing or re-encoding JSON. See docs/webhooks.md.

+ +

Endpoints

+ + + + + + + + + + + + + + + + + + + + + +
MethodPathDescription
GET/api/conversationsList the caller's chat conversations.
POST/api/conversationsCreate a chat conversation.
DELETE/api/conversations/{conversation_id}DELETE /api/conversations/{conversation_id}
GET/api/conversations/{conversation_id}GET /api/conversations/{conversation_id}
POST/api/conversations/{conversation_id}/messagesPOST /api/conversations/{conversation_id}/messages
GET/api/docsGET /api/docs
GET/api/docs/GET /api/docs/
GET/api/usagePer-user token usage summary.
GET/api/usage/breakdownGET /api/usage/breakdown
GET/api/usage/exportGET /api/usage/export
GET/api/usage/export.csvGET /api/usage/export.csv
GET/api/usage/topGET /api/usage/top
GET/api/v1/projectsList the caller's projects with pagination.
GET/api/v1/projects/{project_id}Return one project owned by the caller.
GET/api/v1/reviewsList the caller's reviews, newest first, with pagination.
GET/api/v1/reviews/{review_id}Return one review and its summary.
GET/api/v1/usageReturn a paginated usage ledger summary for the caller.
+ +
+

Coverage and stability

+

The /api/v1 paths are stable and versioned. Other listed paths +keep their existing contracts and may change with the web UI. Automatic route +discovery guarantees the inventory is current; it does not imply that every +path has a frozen schema.

+
+
+ + diff --git a/docs/openapi.json b/docs/openapi.json new file mode 100644 index 00000000..6b40e456 --- /dev/null +++ b/docs/openapi.json @@ -0,0 +1,467 @@ +{ + "info": { + "description": "Machine-facing HTTP API. Paths are generated from the registered routes; detailed request and response schemas are documented for the /api/v1 resources only.", + "title": "AI Code Assistant public API", + "version": "1.0.0" + }, + "openapi": "3.1.0", + "paths": { + "/api/conversations": { + "get": { + "operationId": "chat_api_list_conversations_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "List the caller's chat conversations.", + "tags": [ + "chat" + ] + }, + "post": { + "operationId": "chat_api_create_conversation_post", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "Create a chat conversation.", + "tags": [ + "chat" + ] + } + }, + "/api/conversations/{conversation_id}": { + "delete": { + "operationId": "chat_api_delete_conversation_delete", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "DELETE /api/conversations/{conversation_id}", + "tags": [ + "chat" + ] + }, + "get": { + "operationId": "chat_api_get_conversation_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "GET /api/conversations/{conversation_id}", + "tags": [ + "chat" + ] + } + }, + "/api/conversations/{conversation_id}/messages": { + "post": { + "operationId": "chat_api_send_message_post", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "POST /api/conversations/{conversation_id}/messages", + "tags": [ + "chat" + ] + } + }, + "/api/docs": { + "get": { + "operationId": "api_docs_api_docs_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "GET /api/docs", + "tags": [ + "docs" + ] + } + }, + "/api/docs/": { + "get": { + "operationId": "api_docs_api_docs_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "GET /api/docs/", + "tags": [ + "docs" + ] + } + }, + "/api/usage": { + "get": { + "operationId": "chat_api_usage_summary_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "Per-user token usage summary.", + "tags": [ + "chat" + ] + } + }, + "/api/usage/breakdown": { + "get": { + "operationId": "chat_api_usage_breakdown_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "GET /api/usage/breakdown", + "tags": [ + "chat" + ] + } + }, + "/api/usage/export": { + "get": { + "operationId": "chat_api_usage_export_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "GET /api/usage/export", + "tags": [ + "chat" + ] + } + }, + "/api/usage/export.csv": { + "get": { + "operationId": "chat_api_usage_export_csv_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "GET /api/usage/export.csv", + "tags": [ + "chat" + ] + } + }, + "/api/usage/top": { + "get": { + "operationId": "chat_api_usage_top_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "GET /api/usage/top", + "tags": [ + "chat" + ] + } + }, + "/api/v1/projects": { + "get": { + "operationId": "api_v1_list_projects_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "List the caller's projects with pagination.", + "tags": [ + "v1" + ] + } + }, + "/api/v1/projects/{project_id}": { + "get": { + "operationId": "api_v1_get_project_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "Return one project owned by the caller.", + "tags": [ + "v1" + ] + } + }, + "/api/v1/reviews": { + "get": { + "operationId": "api_v1_list_reviews_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "List the caller's reviews, newest first, with pagination.", + "tags": [ + "v1" + ] + } + }, + "/api/v1/reviews/{review_id}": { + "get": { + "operationId": "api_v1_get_review_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "Return one review and its summary.", + "tags": [ + "v1" + ] + } + }, + "/api/v1/usage": { + "get": { + "operationId": "api_v1_list_usage_get", + "responses": { + "200": { + "description": "Successful response" + }, + "400": { + "description": "Structured invalid-input error" + }, + "401": { + "description": "Authentication required" + }, + "403": { + "description": "Permission denied" + }, + "404": { + "description": "Resource not found" + } + }, + "summary": "Return a paginated usage ledger summary for the caller.", + "tags": [ + "v1" + ] + } + } + }, + "servers": [ + { + "url": "/" + } + ], + "tags": [ + { + "description": "Stable, versioned public resources.", + "name": "v1" + }, + { + "description": "Conversation and usage endpoints.", + "name": "chat" + }, + { + "description": "Documentation endpoints.", + "name": "docs" + } + ] +} diff --git a/docs/sso-domain-verification.md b/docs/sso-domain-verification.md new file mode 100644 index 00000000..eda0a33c --- /dev/null +++ b/docs/sso-domain-verification.md @@ -0,0 +1,79 @@ +# Domain verification and SSO enforcement + +Organizations can prove they own an email domain and then block password +sign-in for accounts on that domain. The implementation is +`app/services/domain_verification.py`; the data lives in `workspace_domains` +(`app/models/workspace_domain.py`). + +## Verification flow + +1. A workspace owner requests a challenge: + + ```http + POST /auth/api/domains/challenge + {"workspace_id": 12, "domain": "example.com"} + ``` + + The response includes `txt_record_name` and `txt_record_value` + (`_aica-verification.example.com` and `aica-verify=`). Challenges + expire after **24 hours**; requesting another challenge replaces the token + and restarts the window. +2. The owner publishes that value as a DNS TXT record. +3. The owner verifies: + + ```http + POST /auth/api/domains/verify + {"workspace_id": 12, "domain": "example.com"} + ``` + + Verification reads the TXT record with a five-second DNS timeout. When the + exact `aica-verify=` value is present before expiry, the domain is + marked verified. A missing, mistyped, or stale record is rejected without + changing the stored state. + +## SSO enforcement + +Only a verified domain can be enforced: + +```http +PATCH /auth/api/domains/7 +{"workspace_id": 12, "enforce_sso": true} +``` + +`GET /auth/api/domains?workspace_id=12` lists pending and verified domains for +the owner. + +When `enforce_sso` is true, the password login form accepts the credentials but +refuses the session with: + +> Password sign-in is disabled for your organization. Use single sign-on (SSO) +> to continue. + +The failed attempt is audited with `reason=sso_enforced`. + +## Permissions and errors + +Every domain operation requires the same workspace `manage_settings` +capability as the web UI (currently the owner). Non-owners receive `403` +`forbidden`; unauthenticated callers receive `401` `unauthorized`. All +responses use the [API error catalog](api-errors.md): + +| Situation | HTTP | Code | +| --- | --- | --- | +| Missing/malformed workspace id or domain | 400 | `invalid_input` | +| Non-owner or missing capability | 403 | `forbidden` | +| Domain claimed by another workspace, already verified | 409 | `conflict` | +| Expired challenge | 410 | `gone` | +| TXT record absent or wrong | 400 | `invalid_input` | +| Enforce requested before verification | 409 | `conflict` | +| Domain id not in the workspace | 404 | `not_found` | + +## Scope notes + +- Verification proves DNS control only. It does not configure or run an SSO + identity provider; it makes the login policy ready for one. +- A domain can belong to only one workspace, so two organizations cannot both + enforce SSO for the same email domain. +- The migration is `migrations/versions/590a1b2c3d4e_add_workspace_domains.py`. + It sits on a merge revision that re-joins the two Phase 11 migration heads, + so `flask db heads` reports exactly one head. diff --git a/migrations/versions/590a1b2c3d4e_add_workspace_domains.py b/migrations/versions/590a1b2c3d4e_add_workspace_domains.py new file mode 100644 index 00000000..681a85df --- /dev/null +++ b/migrations/versions/590a1b2c3d4e_add_workspace_domains.py @@ -0,0 +1,42 @@ +"""add workspace verified domains + +Revision ID: 590a1b2c3d4e +Revises: c9d1e2f3a4b5 +Create Date: 2026-11-22 + +Phase 11 (#590): DNS TXT domain ownership challenges and SSO enforcement. +""" + +import sqlalchemy as sa +from alembic import op + +revision = "590a1b2c3d4e" +down_revision = "c9d1e2f3a4b5" +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + "workspace_domains", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("workspace_id", sa.Integer(), nullable=False), + sa.Column("domain", sa.String(length=253), nullable=False), + sa.Column("verification_token", sa.String(length=128), nullable=False), + sa.Column("challenge_expires_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("verified_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("enforce_sso", sa.Boolean(), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("domain", name="uq_workspace_domains_domain"), + ) + op.create_index("ix_workspace_domains_workspace_id", "workspace_domains", ["workspace_id"]) + op.create_index("ix_workspace_domains_domain", "workspace_domains", ["domain"]) + + +def downgrade(): + op.drop_index("ix_workspace_domains_domain", table_name="workspace_domains") + op.drop_index("ix_workspace_domains_workspace_id", table_name="workspace_domains") + op.drop_table("workspace_domains") diff --git a/migrations/versions/c9d1e2f3a4b5_merge_phase11_heads.py b/migrations/versions/c9d1e2f3a4b5_merge_phase11_heads.py new file mode 100644 index 00000000..46526c65 --- /dev/null +++ b/migrations/versions/c9d1e2f3a4b5_merge_phase11_heads.py @@ -0,0 +1,19 @@ +"""Merge the SIEM and webhook-secret branches before domain verification. + +Both ``e8f9a0b1c2d3`` (SIEM endpoints) and ``f4a5b6c7d8e9`` (webhook secret +rotation) landed on ``main`` as heads. A single descendant keeps +``flask db upgrade`` reachable from one head. +""" + +revision = "c9d1e2f3a4b5" +down_revision = ("e8f9a0b1c2d3", "f4a5b6c7d8e9") +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/scripts/render_api_docs.py b/scripts/render_api_docs.py new file mode 100644 index 00000000..b3e8df9d --- /dev/null +++ b/scripts/render_api_docs.py @@ -0,0 +1,235 @@ +"""Render the public API reference from the registered OpenAPI routes (#655). + +The generator is deliberately dependency-free: the OpenAPI document is built +from Flask's URL map and rendered with :mod:`html`. It is honest about +coverage: paths are discovered automatically, while request/response schemas +are only documented for the stable ``/api/v1`` resources. + +Usage:: + + python scripts/render_api_docs.py + +Writes ``docs/openapi.json`` and ``docs/api/index.html``. Re-run it after +adding or changing a public route. +""" + +from __future__ import annotations + +import html +import json +import re +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from app import create_app # noqa: E402 (path bootstrap must run first) + +SPEC_PATH = REPO_ROOT / "docs" / "openapi.json" +HTML_PATH = REPO_ROOT / "docs" / "api" / "index.html" + +#: Paths included in the public reference. Module-private APIs (for example +#: ``/reviews/api/...``) keep their existing internal contracts and are +#: intentionally out of scope until they are promoted. +PUBLIC_PREFIXES = ("/api/", "/api") + +#: Curated descriptions for the stable versioned resources. +DESCRIPTIONS = { + "get /api/v1/projects": "List the caller's projects with pagination.", + "get /api/v1/projects/{project_id}": "Return one project owned by the caller.", + "get /api/v1/reviews": "List the caller's reviews, newest first, with pagination.", + "get /api/v1/reviews/{review_id}": "Return one review and its summary.", + "get /api/v1/usage": "Return a paginated usage ledger summary for the caller.", + "get /api/conversations": "List the caller's chat conversations.", + "post /api/conversations": "Create a chat conversation.", + "get /api/usage": "Per-user token usage summary.", +} + +TAGS = [ + {"name": "v1", "description": "Stable, versioned public resources."}, + {"name": "chat", "description": "Conversation and usage endpoints."}, + {"name": "docs", "description": "Documentation endpoints."}, +] + + +def _openapi_path(rule_path: str) -> str: + """Convert Flask converters (```` / ``{int:id}``) to ``{id}``.""" + path = re.sub(r"<[^:>]+:([^>]+)>", r"{\1}", re.sub(r"<([^>]+)>", r"{\1}", rule_path)) + return re.sub(r"\{[^:}]+:([^}]+)\}", r"{\1}", path) + + +def _summary(endpoint: str, path: str, method: str) -> str: + description = DESCRIPTIONS.get(f"{method} {path}") + if description: + return description + return f"{method.upper()} {path}" + + +def _tag(path: str) -> str: + if path.startswith("/api/v1"): + return "v1" + if "docs" in path: + return "docs" + return "chat" + + +def build_spec(app) -> dict: + """Build an OpenAPI 3.1 document from the app's registered routes.""" + paths: dict[str, dict] = {} + for rule in sorted(app.url_map.iter_rules(), key=lambda item: str(item)): + rule_path = str(rule) + path = _openapi_path(rule_path) + if not path.startswith(PUBLIC_PREFIXES): + continue + if rule.endpoint == "static": + continue + for method in sorted(set(rule.methods) - {"HEAD", "OPTIONS"}): + method_lower = method.lower() + operation = { + "summary": _summary(rule.endpoint, path, method_lower), + "operationId": f"{rule.endpoint}_{method_lower}".replace(".", "_"), + "tags": [_tag(path)], + "responses": { + "200": {"description": "Successful response"}, + "400": {"description": "Structured invalid-input error"}, + "401": {"description": "Authentication required"}, + "403": {"description": "Permission denied"}, + "404": {"description": "Resource not found"}, + }, + } + paths.setdefault(path, {})[method_lower] = operation + + return { + "openapi": "3.1.0", + "info": { + "title": "AI Code Assistant public API", + "version": "1.0.0", + "description": ( + "Machine-facing HTTP API. Paths are generated from the registered " + "routes; detailed request and response schemas are documented for " + "the /api/v1 resources only." + ), + }, + "servers": [{"url": "/"}], + "tags": TAGS, + "paths": paths, + } + + +def _render_endpoints(paths: dict) -> str: + rows = [] + for path in sorted(paths): + for method, operation in sorted(paths[path].items()): + rows.append( + "" + f"{html.escape(method.upper())}" + f"{html.escape(path)}" + f"{html.escape(operation['summary'])}" + "" + ) + return "\n".join(rows) + + +def render_html(spec: dict) -> str: + """Render the whole reference as one self-contained HTML page.""" + endpoint_rows = _render_endpoints(spec["paths"]) + endpoint_count = sum(len(operations) for operations in spec["paths"].values()) + return f""" + + + + +AI Code Assistant API reference + + + +

AI Code Assistant API reference

+
+

This page is generated from an OpenAPI 3.1 document. It covers +{endpoint_count} operations across {len(spec["paths"])} +public paths. Paths are discovered from the running application; only the +/api/v1 resources have stable, documented response schemas.

+ +

Authentication

+

Every public endpoint requires an authenticated session or API key, except +the documentation page itself. Unauthenticated requests receive +401 with {{"code": "unauthorized"}}. Requests are +authorized with the same ownership and workspace-role checks as the web UI.

+ +

Pagination

+

List endpoints accept page (1-based) and limit +(default 50, maximum 100) and return:

+
{{"items": [], "total": 0, "page": 1, "limit": 50, "next_cursor": null}}
+

Oversized limits are clamped; malformed values return a structured +400 invalid_input error. See docs/pagination.md for the +full contract.

+ +

Errors

+

Errors use one stable JSON shape:

+
{{"error": "The request is invalid.", "kind": "invalid",
+"code": "invalid_input"}}
+

Treat code as the contract. The catalog lives in +app/api/error_catalog.py; docs/api-errors.md lists every +code and HTTP status. Internal exception text is never exposed.

+ +

Webhook verification

+

Webhook deliveries are signed over the exact raw bytes sent: +<timestamp>.<body>, using HMAC-SHA256 with the +subscription secret. Verify the X-AICA-Signature: v1=<hex> +header against X-AICA-Timestamp with a constant-time comparison +and reject timestamps outside the 300-second tolerance window. Verify the raw +body before parsing or re-encoding JSON. See docs/webhooks.md.

+ +

Endpoints

+ + + +{endpoint_rows} + +
MethodPathDescription
+ +
+

Coverage and stability

+

The /api/v1 paths are stable and versioned. Other listed paths +keep their existing contracts and may change with the web UI. Automatic route +discovery guarantees the inventory is current; it does not imply that every +path has a frozen schema.

+
+
+ + +""" + + +def main() -> None: + app = create_app("testing") + spec = build_spec(app) + SPEC_PATH.write_text(json.dumps(spec, indent=2, sort_keys=True) + "\n", encoding="utf-8") + HTML_PATH.parent.mkdir(parents=True, exist_ok=True) + HTML_PATH.write_text(render_html(spec), encoding="utf-8") + print(f"Wrote {SPEC_PATH.relative_to(REPO_ROOT)} and {HTML_PATH.relative_to(REPO_ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tests/test_api_docs.py b/tests/test_api_docs.py new file mode 100644 index 00000000..926020d5 --- /dev/null +++ b/tests/test_api_docs.py @@ -0,0 +1,50 @@ +"""Public API documentation site tests (#655).""" + +from __future__ import annotations + +import json +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +HTML_PATH = REPO_ROOT / "docs" / "api" / "index.html" +SPEC_PATH = REPO_ROOT / "docs" / "openapi.json" + + +class TestGeneratedReference: + def test_page_has_the_required_sections(self): + page = HTML_PATH.read_text(encoding="utf-8") + + for heading in ( + "Authentication", + "Pagination", + "Errors", + "Webhook verification", + "Endpoints", + ): + assert f">{heading}" in page or heading in page + assert "invalid_input" in page + assert "X-AICA-Signature" in page + + def test_spec_is_openapi_and_lists_public_routes(self): + spec = json.loads(SPEC_PATH.read_text(encoding="utf-8")) + + assert spec["openapi"].startswith("3.") + assert "/api/conversations" in spec["paths"] + assert spec["paths"]["/api/conversations"]["get"]["responses"]["404"] + + def test_readme_and_footer_link_to_the_reference(self): + readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8") + base = (REPO_ROOT / "app" / "templates" / "base.html").read_text(encoding="utf-8") + + assert "docs/api/index.html" in readme + assert "docs/openapi.json" in readme + assert "api_docs.api_docs" in base + + +class TestServedReference: + def test_route_serves_the_generated_page(self, client): + response = client.get("/api/docs") + + assert response.status_code == 200 + assert b"Webhook verification" in response.data + assert b"Authentication" in response.data diff --git a/tests/test_api_v1.py b/tests/test_api_v1.py new file mode 100644 index 00000000..63080a23 --- /dev/null +++ b/tests/test_api_v1.py @@ -0,0 +1,239 @@ +"""Public API v1 resource tests (#646).""" + +from __future__ import annotations + +import json +from pathlib import Path + +from app.extensions import db +from app.models import Project, Review, Workspace +from app.models.project import SOURCE_ARCHIVE, STATUS_READY +from app.models.review import SOURCE_PROJECT, STATUS_COMPLETED +from app.services import usage_ledger + + +def _workspace(user, name="Main"): + workspace = Workspace(user_id=user.id, name=name) + db.session.add(workspace) + db.session.commit() + return workspace + + +def _project(user, workspace, name="Project"): + project = Project( + workspace_id=workspace.id, + user_id=user.id, + name=name, + source=SOURCE_ARCHIVE, + status=STATUS_READY, + ) + db.session.add(project) + db.session.commit() + return project + + +def _review(user, project, source=SOURCE_PROJECT, kind="quality"): + review = Review( + user_id=user.id, + project_id=project.id, + source=source, + kind=kind, + status=STATUS_COMPLETED, + ) + db.session.add(review) + db.session.commit() + return review + + +class TestPublishedSpec: + def test_openapi_reference_lists_every_v1_resource(self): + spec_path = Path(__file__).resolve().parents[1] / "docs" / "openapi.json" + spec = json.loads(spec_path.read_text(encoding="utf-8")) + + for path in ( + "/api/v1/projects", + "/api/v1/projects/{project_id}", + "/api/v1/reviews", + "/api/v1/reviews/{review_id}", + "/api/v1/usage", + ): + assert path in spec["paths"] + + +class TestAuth: + def test_every_v1_resource_requires_authentication(self, client): + for path in ( + "/api/v1/projects", + "/api/v1/projects/1", + "/api/v1/reviews", + "/api/v1/reviews/1", + "/api/v1/usage", + ): + response = client.get(path) + assert response.status_code == 401 + assert response.get_json()["code"] == "unauthorized" + + +class TestProjects: + def test_list_is_owner_scoped_and_paginated(self, client, make_user, login): + user = make_user(username="owner", email="owner@example.com") + other = make_user(username="other", email="other@example.com") + login(email="owner@example.com") + workspace = _workspace(user) + other_workspace = _workspace(other, "Other") + first = _project(user, workspace, "First") + second = _project(user, workspace, "Second") + third = _project(user, workspace, "Third") + _project(other, other_workspace, "Not mine") + + response = client.get("/api/v1/projects?page=1&limit=2") + + assert response.status_code == 200 + payload = response.get_json() + assert payload["total"] == 3 + assert payload["page"] == 1 + assert payload["limit"] == 2 + assert [item["id"] for item in payload["items"]] == [third.id, second.id] + assert payload["next_cursor"] + + next_page = client.get(f"/api/v1/projects?limit=2&cursor={payload['next_cursor']}") + assert [item["id"] for item in next_page.get_json()["items"]] == [first.id] + assert next_page.get_json()["next_cursor"] is None + + def test_list_filters_by_owned_workspace(self, client, make_user, login): + user = make_user() + other = make_user(username="other", email="other@example.com") + login() + workspace = _workspace(user) + other_workspace = _workspace(other, "Other") + _project(user, workspace, "Mine") + _project(other, other_workspace, "Theirs") + + response = client.get(f"/api/v1/projects?workspace_id={workspace.id}") + assert [item["name"] for item in response.get_json()["items"]] == ["Mine"] + + hidden = client.get(f"/api/v1/projects?workspace_id={other_workspace.id}") + assert hidden.get_json()["items"] == [] + + def test_detail_returns_owned_project_and_404_for_others(self, client, make_user, login): + user = make_user() + other = make_user(username="other", email="other@example.com") + login() + workspace = _workspace(user) + other_workspace = _workspace(other, "Other") + project = _project(user, workspace) + foreign = _project(other, other_workspace, "Foreign") + + mine = client.get(f"/api/v1/projects/{project.id}") + assert mine.status_code == 200 + payload = mine.get_json() + assert payload["id"] == project.id + assert payload["workspace_id"] == workspace.id + assert "status" in payload and "file_count" in payload + + denied = client.get(f"/api/v1/projects/{foreign.id}") + assert denied.status_code == 404 + assert denied.get_json()["code"] == "not_found" + + def test_invalid_workspace_filter_is_structured(self, client, make_user, login): + make_user() + login() + + response = client.get("/api/v1/projects?workspace_id=nope") + + assert response.status_code == 400 + assert response.get_json()["code"] == "invalid_input" + + def test_malformed_cursor_is_structured(self, client, make_user, login): + make_user() + login() + + response = client.get("/api/v1/projects?cursor=not-a-cursor") + + assert response.status_code == 400 + assert response.get_json()["code"] == "invalid_input" + + +class TestReviews: + def test_list_is_owner_scoped_with_filters(self, client, make_user, login): + user = make_user() + other = make_user(username="other", email="other@example.com") + login() + workspace = _workspace(user) + other_workspace = _workspace(other, "Other") + project = _project(user, workspace) + quality = _review(user, project, kind="quality") + _review(user, project, kind="security") + _review(other, _project(other, other_workspace, "Foreign"), kind="quality") + + response = client.get("/api/v1/reviews?kind=quality") + payload = response.get_json() + + assert response.status_code == 200 + assert payload["total"] == 1 + assert payload["items"][0]["id"] == quality.id + + def test_detail_returns_owned_review_and_404_for_others(self, client, make_user, login): + user = make_user() + other = make_user(username="other", email="other@example.com") + login() + project = _project(user, _workspace(user)) + review = _review(user, project) + foreign = _review(other, _project(other, _workspace(other, "Other"))) + + response = client.get(f"/api/v1/reviews/{review.id}") + assert response.status_code == 200 + assert response.get_json()["id"] == review.id + assert "findings_count" in response.get_json() + + denied = client.get(f"/api/v1/reviews/{foreign.id}") + assert denied.status_code == 404 + assert denied.get_json()["code"] == "not_found" + + def test_invalid_project_filter_is_structured(self, client, make_user, login): + make_user() + login() + + response = client.get("/api/v1/reviews?project_id=abc") + + assert response.status_code == 400 + assert response.get_json()["code"] == "invalid_input" + + +class TestUsage: + def test_usage_is_scoped_to_the_caller(self, client, make_user, login): + user = make_user() + other = make_user(username="other", email="other@example.com") + login() + usage_ledger.record_usage(source="chat", user=user, prompt_tokens=10, total_tokens=10) + usage_ledger.record_usage(source="review", user=user, prompt_tokens=20, total_tokens=20) + usage_ledger.record_usage(source="chat", user=other, prompt_tokens=999, total_tokens=999) + + response = client.get("/api/v1/usage?page=1&limit=1&source=chat") + + assert response.status_code == 200 + payload = response.get_json() + assert payload["schema_version"] == usage_ledger.EXPORT_SCHEMA_VERSION + assert payload["pagination"]["total"] == 1 + assert payload["filters"]["source"] == "chat" + assert len(payload["records"]) == 1 + assert payload["records"][0]["user_id"] == user.id + assert payload["totals"]["total_tokens"] == 10 + + def test_usage_rejects_malformed_pagination(self, client, make_user, login): + make_user() + login() + + response = client.get("/api/v1/usage?page=nope") + + assert response.status_code == 400 + assert response.get_json()["code"] == "invalid_input" + + def test_usage_cursor_is_not_silently_ignored(self, client, make_user, login): + make_user() + login() + + response = client.get("/api/v1/usage?cursor=eyJpZCI6MX0") + + assert response.status_code == 400 + assert "Cursor" in response.get_json()["error"] diff --git a/tests/test_domain_verification.py b/tests/test_domain_verification.py new file mode 100644 index 00000000..d8dd9bb4 --- /dev/null +++ b/tests/test_domain_verification.py @@ -0,0 +1,267 @@ +"""Domain verification and SSO enforcement tests (#590).""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from unittest.mock import patch + +import pytest + +from app.extensions import db +from app.models import Workspace, WorkspaceDomain +from app.services import domain_verification +from app.services.domain_verification import ( + ChallengeExpired, + DomainConflict, + DomainNotVerified, + DomainPermissionDenied, + InvalidDomain, + VerificationFailed, +) + + +def _workspace(user_id, name="Acme"): + workspace = Workspace(user_id=user_id, name=name) + db.session.add(workspace) + db.session.commit() + return workspace + + +def _verified_domain(workspace_id, domain="example.com", enforce=True): + now = datetime.now(UTC) + row = WorkspaceDomain( + workspace_id=workspace_id, + domain=domain, + verification_token="token", + challenge_expires_at=now + timedelta(hours=1), + verified_at=now, + enforce_sso=enforce, + ) + db.session.add(row) + db.session.commit() + return row + + +class TestNormalization: + @pytest.mark.parametrize("value", ["example.com", "Sub.Example.COM.", "a-b.co.uk"]) + def test_accepts_valid_domains(self, value): + assert domain_verification.normalize_domain(value) == value.rstrip(".").lower() + + @pytest.mark.parametrize( + "value", + ["", "example", "https://example.com", "example.com/path", "*.example.com", "a..com"], + ) + def test_rejects_invalid_domains(self, value): + with pytest.raises(InvalidDomain): + domain_verification.normalize_domain(value) + + def test_txt_record_uses_the_domain(self): + assert domain_verification.txt_record_name("Example.com") == ( + "_aica-verification.example.com" + ) + assert domain_verification.expected_txt_value("abc") == "aica-verify=abc" + + +class TestChallengeAndVerification: + def test_owner_creates_a_bounded_challenge(self, make_user): + user = make_user() + workspace = _workspace(user.id) + now = datetime(2026, 1, 1, tzinfo=UTC) + + row = domain_verification.create_challenge(workspace.id, "Example.com", user=user, now=now) + + assert row.domain == "example.com" + assert row.verification_token + assert row.verified_at is None + assert row.challenge_expires_at.replace(tzinfo=UTC) == ( + now + domain_verification.CHALLENGE_TTL + ) + + def test_non_owner_cannot_create_a_challenge(self, make_user): + owner = make_user(username="owner", email="owner@example.com") + outsider = make_user(username="outsider", email="outsider@example.net") + workspace = _workspace(owner.id) + + with pytest.raises(DomainPermissionDenied): + domain_verification.create_challenge(workspace.id, "example.com", user=outsider) + + def test_verification_succeeds_with_matching_txt_record(self, make_user): + user = make_user() + workspace = _workspace(user.id) + row = domain_verification.create_challenge(workspace.id, "example.com", user=user) + expected = domain_verification.expected_txt_value(row.verification_token) + + verified = domain_verification.verify_domain( + workspace.id, + "example.com", + user=user, + resolver=lambda name: [expected], + ) + + assert verified.is_verified + assert verified.verified_at is not None + + def test_verification_fails_without_the_txt_record(self, make_user): + user = make_user() + workspace = _workspace(user.id) + domain_verification.create_challenge(workspace.id, "example.com", user=user) + + with pytest.raises(VerificationFailed): + domain_verification.verify_domain( + workspace.id, + "example.com", + user=user, + resolver=lambda name: ["aica-verify=wrong"], + ) + + stored = WorkspaceDomain.query.filter_by(workspace_id=workspace.id).one() + assert stored.verified_at is None + + def test_challenge_expiry_is_enforced(self, make_user): + user = make_user() + workspace = _workspace(user.id) + now = datetime(2026, 1, 1, tzinfo=UTC) + row = domain_verification.create_challenge(workspace.id, "example.com", user=user, now=now) + expected = domain_verification.expected_txt_value(row.verification_token) + + with pytest.raises(ChallengeExpired): + domain_verification.verify_domain( + workspace.id, + "example.com", + user=user, + now=now + domain_verification.CHALLENGE_TTL + timedelta(seconds=1), + resolver=lambda name: [expected], + ) + + def test_domain_cannot_be_claimed_by_two_workspaces(self, make_user): + first = make_user(username="first", email="first@example.com") + second = make_user(username="second", email="second@example.com") + first_workspace = _workspace(first.id, "First") + second_workspace = _workspace(second.id, "Second") + + domain_verification.create_challenge(first_workspace.id, "example.com", user=first) + with pytest.raises(DomainConflict): + domain_verification.create_challenge(second_workspace.id, "example.com", user=second) + + def test_enforcement_requires_a_verified_domain(self, make_user): + user = make_user() + workspace = _workspace(user.id) + row = domain_verification.create_challenge(workspace.id, "example.com", user=user) + + with pytest.raises(DomainNotVerified): + domain_verification.set_enforcement(workspace.id, row.id, True, user=user) + + +class TestDomainRoutes: + def test_challenge_route_returns_record_details(self, client, make_user, login): + user = make_user() + login() + workspace = _workspace(user.id) + + response = client.post( + "/auth/api/domains/challenge", + json={"workspace_id": workspace.id, "domain": "Example.com"}, + ) + + assert response.status_code == 201 + payload = response.get_json() + assert payload["domain"] == "example.com" + assert payload["txt_record_name"] == "_aica-verification.example.com" + assert payload["txt_record_value"].startswith("aica-verify=") + + def test_verify_route_uses_dns(self, client, make_user, login): + user = make_user() + login() + workspace = _workspace(user.id) + challenge = client.post( + "/auth/api/domains/challenge", + json={"workspace_id": workspace.id, "domain": "example.com"}, + ).get_json() + + with patch.object( + domain_verification, + "_resolve_txt", + return_value=[challenge["txt_record_value"]], + ): + response = client.post( + "/auth/api/domains/verify", + json={"workspace_id": workspace.id, "domain": "example.com"}, + ) + + assert response.status_code == 200 + assert response.get_json()["verified_at"] is not None + + def test_patch_enables_enforcement_after_verification(self, client, make_user, login): + user = make_user() + login() + workspace = _workspace(user.id) + row = _verified_domain(workspace.id, enforce=False) + + response = client.patch( + f"/auth/api/domains/{row.id}", + json={"workspace_id": workspace.id, "enforce_sso": True}, + ) + + assert response.status_code == 200 + assert response.get_json()["enforce_sso"] is True + + def test_non_owner_gets_structured_permission_error(self, client, make_user, login): + owner = make_user(username="owner", email="owner@example.com") + make_user(username="outsider", email="outsider@example.net") + workspace = _workspace(owner.id) + login(email="outsider@example.net") + + response = client.post( + "/auth/api/domains/challenge", + json={"workspace_id": workspace.id, "domain": "example.com"}, + ) + + assert response.status_code == 403 + assert response.get_json()["code"] == "forbidden" + + def test_invalid_input_gets_structured_error(self, client, make_user, login): + make_user() + login() + + response = client.post( + "/auth/api/domains/challenge", + json={"workspace_id": "not-an-int", "domain": "example.com"}, + ) + + assert response.status_code == 400 + assert response.get_json()["code"] == "invalid_input" + + def test_unauthenticated_call_gets_structured_401(self, client): + response = client.post("/auth/api/domains/challenge", json={}) + + assert response.status_code == 401 + assert response.get_json()["code"] == "unauthorized" + + +class TestPasswordLoginBlock: + def test_enforced_domain_blocks_password_login(self, client, make_user): + user = make_user(username="blocked", email="user@example.com") + workspace = _workspace(user.id) + _verified_domain(workspace.id, domain="example.com", enforce=True) + + response = client.post( + "/auth/login", + data={"email": "user@example.com", "password": "supersecret123"}, + ) + + assert response.status_code == 200 + assert b"Password sign-in is disabled" in response.data + assert client.get("/auth/me").status_code == 302 + + def test_other_domains_still_use_password_login(self, client, make_user): + user = make_user(username="allowed", email="user@other.com") + workspace = _workspace(user.id) + _verified_domain(workspace.id, domain="example.com", enforce=True) + + response = client.post( + "/auth/login", + data={"email": "user@other.com", "password": "supersecret123"}, + follow_redirects=True, + ) + + assert b"Welcome back" in response.data diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 775c6fb7..a93ea098 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -203,6 +203,35 @@ def test_budgets_table_upgraded(self): columns = {col["name"] for col in insp.get_columns("budgets")} assert columns == expected + def test_workspace_domains_table_upgraded(self): + expected = { + "id", + "workspace_id", + "domain", + "verification_token", + "challenge_expires_at", + "verified_at", + "enforce_sso", + "created_at", + "updated_at", + } + with _migration_db() as db_url, _inspect(db_url) as insp: + assert "workspace_domains" in set(insp.get_table_names()) + columns = {col["name"] for col in insp.get_columns("workspace_domains")} + assert columns == expected + + def test_workspace_domains_downgrade_removed(self): + with tempfile.TemporaryDirectory() as tmp: + db_url = f"sqlite:///{os.path.join(tmp, 'mig_domains.db')}" + up = _run_flask(["db", "upgrade"], {"DATABASE_URL": db_url}) + assert up.returncode == 0, up.stderr + down = _run_flask( + ["db", "downgrade", "c9d1e2f3a4b5"], {"DATABASE_URL": db_url} + ) + assert down.returncode == 0, down.stderr + with _inspect(db_url) as insp: + assert "workspace_domains" not in set(insp.get_table_names()) + def test_budgets_downgrade_removed(self): with tempfile.TemporaryDirectory() as tmp: db_url = f"sqlite:///{os.path.join(tmp, 'mig_budgets.db')}"