diff --git a/backend/app/config.py b/backend/app/config.py index 23094fb..22883e6 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -43,6 +43,15 @@ class Settings: id_rate_window_seconds: int = int(os.getenv("ID_RATE_WINDOW_SECONDS", "60")) id_rate_target_limit: int = int(os.getenv("ID_RATE_TARGET_LIMIT", "10")) id_rate_ip_limit: int = int(os.getenv("ID_RATE_IP_LIMIT", "30")) + app_token_days: int = int(os.getenv("APP_TOKEN_DAYS", "30")) + app_code_seconds: int = int(os.getenv("APP_CODE_SECONDS", "60")) + app_history_limit: int = int(os.getenv("APP_HISTORY_LIMIT", "500")) + app_saved_limit: int = int(os.getenv("APP_SAVED_LIMIT", "500")) + app_box_max_bytes: int = int(os.getenv("APP_BOX_MAX_BYTES", str(200 * 1024))) + app_max_sessions: int = int(os.getenv("APP_MAX_SESSIONS", "5")) + app_request_window_seconds: int = int(os.getenv("APP_REQUEST_WINDOW_SECONDS", "60")) + app_request_limit: int = int(os.getenv("APP_REQUEST_LIMIT", "120")) + app_write_limit: int = int(os.getenv("APP_WRITE_LIMIT", "30")) require_signup_email_otp: bool = _enabled("REQUIRE_SIGNUP_EMAIL_OTP") require_sensitive_action_otp: bool = _enabled("REQUIRE_SENSITIVE_ACTION_OTP") require_account_delete_otp: bool = _enabled("REQUIRE_ACCOUNT_DELETE_OTP") diff --git a/backend/app/main.py b/backend/app/main.py index 37d9591..a2e3849 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,9 +1,13 @@ from __future__ import annotations +import base64 +import hashlib +import hmac import logging import re import time from typing import Annotated, Any, Literal +from urllib.parse import quote from uuid import uuid4 import boto3 @@ -16,6 +20,7 @@ from .config import settings from .emailer import EmailConfigurationError, EmailDeliveryError, SesEmailSender from .repository import ( + AppPausedError, AuthenticationError, AuthenticationRateLimitError, ConflictError, @@ -23,9 +28,10 @@ NotFoundError, OtpError, OtpRateLimitError, + PayloadTooLargeError, RequestRateLimitError, ) -from .security import challenge_digest, new_otp_code, otp_digest +from .security import challenge_digest, new_otp_code, new_verification_token, otp_digest, token_digest def build_repository() -> DynamoAccountRepository: @@ -37,6 +43,12 @@ def build_repository() -> DynamoAccountRepository: session_activity_update_seconds=settings.session_activity_update_seconds, otp_max_attempts=settings.otp_max_attempts, otp_verification_seconds=settings.otp_verification_seconds, + app_token_days=settings.app_token_days, + app_code_seconds=settings.app_code_seconds, + app_history_limit=settings.app_history_limit, + app_saved_limit=settings.app_saved_limit, + app_box_max_bytes=settings.app_box_max_bytes, + app_max_sessions=settings.app_max_sessions, ) @@ -238,6 +250,56 @@ class SupportRequest(BaseModel): message: str = Field(min_length=20, max_length=2000) +AppKey = Literal["SANKALPA", "EYESEARCH", "EYEBROWSE"] + + +class AppAuthorizeRequest(BaseModel): + redirect: str = Field(min_length=8, max_length=200) + code_challenge: str = Field(min_length=43, max_length=128, pattern=r"^[A-Za-z0-9_-]+$") + state: str = Field(default="", max_length=200) + + +class AppSessionExchange(BaseModel): + app: AppKey + code: str = Field(min_length=32, max_length=200) + code_verifier: str = Field(min_length=43, max_length=128, pattern=r"^[A-Za-z0-9._~-]+$") + device: str = Field(default="Indo app", max_length=120) + + +class AppStatusUpdate(BaseModel): + status: Literal["Active", "Paused"] + + +class AppPreferencesUpdate(BaseModel): + preferences: dict[str, Any] = Field(default_factory=dict) + + +class AppSavedCreate(BaseModel): + title: str = Field(default="", max_length=300) + url: str = Field(min_length=4, max_length=2000) + + +class AppHistoryEntry(BaseModel): + url: str | None = Field(default=None, max_length=2000) + origin: str | None = Field(default=None, max_length=2000) + title: str | None = Field(default=None, max_length=300) + visited_at: str | None = Field(default=None, max_length=40) + visits: int | None = Field(default=None, ge=1, le=1000) + + +class AppHistoryBatch(BaseModel): + entries: list[AppHistoryEntry] = Field(min_length=1, max_length=100) + + +# Registered first-party clients. The redirect prefix must match exactly; a +# redirect to any other scheme or host is refused. +APP_CLIENTS = { + "SANKALPA": {"name": "Sankalp", "redirect_prefixes": ("sankalp://", "https://sankalp.indoworkspace.in/")}, + "EYESEARCH": {"name": "Eyesearch Search Engine", "redirect_prefixes": ("eyesearch://", "https://eyesearch.indoworkspace.in/")}, + "EYEBROWSE": {"name": "Eyebrowse Browser", "redirect_prefixes": ("indobrowse://",)}, +} + + SECURITY_ACTION_LABELS = { "change_password": "changing your password", "disable_two_step": "turning off two-step protection", @@ -360,6 +422,46 @@ async def email_delivery_handler(_request, error: EmailDeliveryError): return JSONResponse(status_code=503, content={"detail": str(error)}) +@app.exception_handler(PayloadTooLargeError) +async def payload_too_large_handler(_request, error: PayloadTooLargeError): + return JSONResponse(status_code=413, content={"detail": str(error)}) + + +@app.exception_handler(AppPausedError) +async def app_paused_handler(_request, error: AppPausedError): + return JSONResponse(status_code=403, content={"detail": str(error)}) + + +def pkce_challenge(verifier: str) -> str: + digest = hashlib.sha256(verifier.encode()).digest() + return base64.urlsafe_b64encode(digest).decode().rstrip("=") + + +def app_session(authorization: Annotated[str | None, Header()] = None) -> tuple[str, str, str]: + credential = bearer_token(authorization) + try: + return repository.user_from_app_token(credential) + except AuthenticationError as error: + if credential.count(".") == 1: + raise HTTPException( + status.HTTP_403_FORBIDDEN, + "This endpoint requires an app session, not an account session.", + ) from error + raise HTTPException(status.HTTP_401_UNAUTHORIZED, str(error)) from error + + +def enforce_app_rate_limit(request: Request, user_id: str, app: str, *, write: bool) -> None: + repository.enforce_public_request_limits( + "app_write" if write else "app_read", + f"{app}:{user_id}", + request_client_ip(request), + now=int(time.time()), + window_seconds=settings.app_request_window_seconds, + subject_limit=settings.app_write_limit if write else settings.app_request_limit, + ip_limit=max(settings.app_request_limit * 3, 120), + ) + + @app.get("/health") def health() -> dict[str, Any]: details = repository.table_status() @@ -905,5 +1007,253 @@ def delete_me( return Response(status_code=status.HTTP_204_NO_CONTENT) -handler = Mangum(app, lifespan="off") +# --------------------------------------------------------------------------- +# App data — panel surface (authenticated with the account session) +# --------------------------------------------------------------------------- + + +@app.get("/api/v1/me/apps") +def list_apps(user_id: Annotated[str, Depends(current_user)]) -> dict[str, Any]: + return {"apps": repository.list_app_boxes(user_id)} + + +@app.get("/api/v1/me/apps/{app}") +def get_app_box(app: AppKey, user_id: Annotated[str, Depends(current_user)]) -> dict[str, Any]: + return repository.get_app_box(user_id, app) + + +@app.patch("/api/v1/me/apps/{app}") +def update_app_status( + app: AppKey, + payload: AppStatusUpdate, + user_id: Annotated[str, Depends(current_user)], +) -> dict[str, Any]: + return repository.set_app_status(user_id, app, payload.status) + + +@app.post("/api/v1/me/apps/{app}/authorize", status_code=201) +def authorize_app( + app: AppKey, + payload: AppAuthorizeRequest, + user_id: Annotated[str, Depends(current_user)], +) -> dict[str, Any]: + client = APP_CLIENTS[app] + if not payload.redirect.startswith(client["redirect_prefixes"]): + raise HTTPException(status.HTTP_400_BAD_REQUEST, "That redirect address is not registered for this app.") + code = new_verification_token() + repository.create_app_code(user_id, app, token_digest(code), payload.code_challenge) + separator = "&" if "?" in payload.redirect else "?" + return { + "redirect_url": f"{payload.redirect}{separator}code={quote(code)}&state={quote(payload.state)}", + "expires_in": settings.app_code_seconds, + "app": {"key": app, "name": client["name"]}, + } + + +@app.delete( + "/api/v1/me/apps/{app}/sessions", + status_code=status.HTTP_204_NO_CONTENT, + response_class=Response, +) +def revoke_app_access(app: AppKey, user_id: Annotated[str, Depends(current_user)]) -> Response: + repository.revoke_app_sessions(user_id, app) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@app.delete( + "/api/v1/me/apps/{app}/sessions/{session_id}", + status_code=status.HTTP_204_NO_CONTENT, + response_class=Response, +) +def revoke_one_app_session( + app: AppKey, + session_id: str, + user_id: Annotated[str, Depends(current_user)], +) -> Response: + repository.revoke_app_sessions(user_id, app, session_id) + return Response(status_code=status.HTTP_204_NO_CONTENT) + +@app.delete("/api/v1/me/apps/{app}/data") +def clear_app_box(app: AppKey, user_id: Annotated[str, Depends(current_user)]) -> dict[str, Any]: + return repository.clear_app_data(user_id, app) + + +@app.get("/api/v1/me/apps/{app}/export") +def export_app_box(app: AppKey, user_id: Annotated[str, Depends(current_user)]) -> dict[str, Any]: + return repository.export_app_box(user_id, app) + + +# --------------------------------------------------------------------------- +# App data — app surface (authenticated with an app-scoped token) +# +# The app key comes from the token itself, never from the path, so an app +# cannot even name another app's box. +# --------------------------------------------------------------------------- + + +def identity_block(state: dict[str, Any]) -> dict[str, Any]: + return { + "user_id": state.get("user_id"), + "indo_id": state.get("eyemail_id"), + "full_name": state.get("full_name"), + "nickname": state.get("nickname"), + "language": state.get("language"), + } + + +@app.post("/api/v1/app/session", status_code=201) +def exchange_app_code(payload: AppSessionExchange, request: Request) -> dict[str, Any]: + repository.enforce_public_request_limits( + "app_session", + payload.app, + request_client_ip(request), + now=int(time.time()), + window_seconds=settings.otp_rate_window_seconds, + subject_limit=settings.otp_target_window_limit * 4, + ip_limit=settings.otp_ip_window_limit * 2, + ) + record = repository.consume_app_code(payload.app, token_digest(payload.code)) + if not hmac.compare_digest(str(record.get("code_challenge", "")), pkce_challenge(payload.code_verifier)): + raise HTTPException(status.HTTP_400_BAD_REQUEST, "This sign-in request could not be verified.") + user_id = str(record["user_id"]) + issued = repository.issue_app_token(user_id, payload.app, payload.device) + state = repository.get_account_state(user_id) + return { + "token": issued["token"], + "expires_in": issued["expires_in"], + "session_id": issued["session_id"], + "app": {"key": payload.app, "name": APP_CLIENTS[payload.app]["name"]}, + "identity": identity_block(state), + } + + +@app.get("/api/v1/app/me") +def app_me( + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], +) -> dict[str, Any]: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=False) + return identity_block(repository.get_account_state(user_id)) + + +@app.get("/api/v1/app/state") +def app_state( + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], +) -> dict[str, Any]: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=False) + box = repository.get_app_box(user_id, app) + return { + "key": box["key"], + "name": box["name"], + "status": box["status"], + "connected": box["connected"], + "connected_at": box.get("connected_at"), + "last_used_at": box.get("last_used_at"), + "preferences": box.get("preferences", {}), + "counts": box["counts"], + } + + +@app.patch("/api/v1/app/preferences") +def app_preferences( + payload: AppPreferencesUpdate, + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], +) -> dict[str, Any]: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=True) + return repository.update_app_preferences(user_id, app, payload.preferences) + + +@app.get("/api/v1/app/saved") +def app_saved( + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], + limit: int = 50, + cursor: str | None = None, +) -> dict[str, Any]: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=False) + return repository.list_app_saved(user_id, app, limit=limit, cursor=cursor) + + +@app.post("/api/v1/app/saved", status_code=201) +def app_add_saved( + payload: AppSavedCreate, + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], +) -> dict[str, Any]: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=True) + return repository.add_app_saved(user_id, app, payload.title, payload.url) + + +@app.delete("/api/v1/app/saved/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_class=Response) +def app_delete_saved( + item_id: str, + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], +) -> Response: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=True) + repository.delete_app_saved(user_id, app, item_id) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@app.get("/api/v1/app/history") +def app_history( + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], + limit: int = 50, + cursor: str | None = None, +) -> dict[str, Any]: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=False) + return repository.list_app_history(user_id, app, limit=limit, cursor=cursor) + + +@app.post("/api/v1/app/history", status_code=202) +def app_add_history( + payload: AppHistoryBatch, + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], +) -> dict[str, Any]: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=True) + return repository.add_app_history(user_id, app, [entry.model_dump() for entry in payload.entries]) + + +@app.delete("/api/v1/app/history") +def app_clear_history( + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], +) -> dict[str, Any]: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=True) + return repository.clear_app_history(user_id, app) + + +@app.delete("/api/v1/app/data") +def app_clear_data( + request: Request, + session: Annotated[tuple[str, str, str], Depends(app_session)], +) -> dict[str, Any]: + user_id, app, _session_id = session + enforce_app_rate_limit(request, user_id, app, write=True) + return repository.clear_app_data(user_id, app) + + +@app.post("/api/v1/app/logout", status_code=status.HTTP_204_NO_CONTENT, response_class=Response) +def app_logout( + session: Annotated[tuple[str, str, str], Depends(app_session)], +) -> Response: + user_id, app, session_id = session + repository.revoke_app_sessions(user_id, app, session_id) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +handler = Mangum(app, lifespan="off") diff --git a/backend/app/repository.py b/backend/app/repository.py index 6314b6d..fa0bfd4 100644 --- a/backend/app/repository.py +++ b/backend/app/repository.py @@ -1,10 +1,13 @@ from __future__ import annotations +import copy +import json import logging import hmac import time from datetime import UTC, datetime from typing import Any +from urllib.parse import urlsplit, urlunsplit from uuid import uuid4 from .security import hash_password, new_session_token, new_verification_token, token_digest, verify_password @@ -53,6 +56,14 @@ def __init__(self, retry_after: int): self.retry_after = max(1, retry_after) +class PayloadTooLargeError(Exception): + pass + + +class AppPausedError(Exception): + pass + + class DynamoAccountRepository: """Single-table DynamoDB access for Indo Account. @@ -66,9 +77,9 @@ class DynamoAccountRepository: "phone": "phone", } APP_DEFAULTS = { - "SANKALPA": {"name": "Sankalp", "status": "Active", "connected": True, "plan": "Not connected", "quota": "No usage yet", "renewal": "—", "last_used": "Not yet used", "data": {"history": [], "saved": [], "memory": [], "preferences": {}}}, - "EYESEARCH": {"name": "Eyesearch Search Engine", "status": "Active", "connected": True, "plan": "Not connected", "quota": "No usage yet", "renewal": "—", "last_used": "Not yet used", "data": {"history": [], "saved": [], "preferences": {}}}, - "EYEBROWSE": {"name": "Eyebrowse Browser", "status": "Active", "connected": True, "plan": "Not connected", "quota": "No usage yet", "renewal": "—", "last_used": "Not yet used", "data": {"history": [], "saved": [], "preferences": {}}}, + "SANKALPA": {"name": "Sankalp", "status": "Active", "connected": False, "plan": "Not connected", "quota": "No usage yet", "renewal": "—", "last_used": "Not yet used", "data": {"history": [], "saved": [], "memory": [], "preferences": {}}}, + "EYESEARCH": {"name": "Eyesearch Search Engine", "status": "Active", "connected": False, "plan": "Not connected", "quota": "No usage yet", "renewal": "—", "last_used": "Not yet used", "data": {"history": [], "saved": [], "preferences": {}}}, + "EYEBROWSE": {"name": "Eyebrowse Browser", "status": "Active", "connected": False, "plan": "Not connected", "quota": "No usage yet", "renewal": "—", "last_used": "Not yet used", "data": {"history": [], "saved": [], "preferences": {}}}, } def __init__( @@ -80,6 +91,12 @@ def __init__( session_activity_update_seconds: int = 300, otp_max_attempts: int = 5, otp_verification_seconds: int = 900, + app_token_days: int = 30, + app_code_seconds: int = 60, + app_history_limit: int = 500, + app_saved_limit: int = 500, + app_box_max_bytes: int = 200 * 1024, + app_max_sessions: int = 5, ): self.table = table self.session_seconds = session_days * 86_400 @@ -87,6 +104,12 @@ def __init__( self.session_activity_update_seconds = max(60, session_activity_update_seconds) self.otp_max_attempts = otp_max_attempts self.otp_verification_seconds = otp_verification_seconds + self.app_token_seconds = max(300, app_token_days * 86_400) + self.app_code_seconds = max(30, app_code_seconds) + self.app_history_limit = max(1, app_history_limit) + self.app_saved_limit = max(1, app_saved_limit) + self.app_box_max_bytes = max(4096, app_box_max_bytes) + self.app_max_sessions = max(1, app_max_sessions) @staticmethod def _profile_key(user_id: str) -> dict[str, str]: @@ -1436,7 +1459,8 @@ def get_account_state(self, user_id: str, *, current_token: str | None = None) - ConsistentRead=True, ) items = response.get("Items", []) - apps = {key: {**value, "key": key} for key, value in self.APP_DEFAULTS.items()} + apps = {key: {**copy.deepcopy(value), "key": key} for key, value in self.APP_DEFAULTS.items()} + app_sessions: dict[str, list[dict[str, Any]]] = {} notifications = {"security": True, "signin": True, "account": True, "updates": True, "billing": True, "news": False} billing = {"company": "", "gstin": "", "address": "", "state": ""} sessions: list[dict[str, Any]] = [] @@ -1449,6 +1473,13 @@ def get_account_state(self, user_id: str, *, current_token: str | None = None) - key = sort_key.split("#")[1] if key in apps: apps[key] = {**apps[key], **item.get("state", {}), "key": key} + elif sort_key.startswith("APP#") and "#SESSION#" in sort_key: + if int(item.get("ttl", 0)) <= int(time.time()): + continue + app_key = sort_key.split("#")[1] + app_session = self._public(item) + app_session.pop("token_hash", None) + app_sessions.setdefault(app_key, []).append(app_session) elif sort_key == "SETTINGS#NOTIFICATIONS": notifications.update(item.get("state", {})) elif sort_key == "BILLING#PROFILE": @@ -1466,6 +1497,14 @@ def get_account_state(self, user_id: str, *, current_token: str | None = None) - invoices.append(self._public(item)) elif sort_key.startswith("EVENT#"): security_events.append(self._public(item)) + for key, box in apps.items(): + sessions_for_app = sorted(app_sessions.get(key, []), key=lambda item: str(item.get("created_at", ""))) + box["sessions"] = sessions_for_app + box["connected"] = bool(sessions_for_app) + box["counts"] = { + "history": len(box.get("data", {}).get("history", [])), + "saved": len(box.get("data", {}).get("saved", [])), + } security_events.sort(key=lambda item: str(item.get("created_at", "")), reverse=True) return { **profile, @@ -1831,3 +1870,415 @@ def delete_account( batch.delete_item(Key=key) + + # ------------------------------------------------------------------ + # App data — Sankalp, Eyesearch, Eyebrowse + # + # Each app owns exactly one item, APP##STATE, plus its own + # session items, APP##SESSION#. An app token can only reach + # its own key, and the panel can reach all three. + # ------------------------------------------------------------------ + + APP_STATUSES = {"Active", "Paused"} + APP_PREFERENCES = { + "SANKALPA": {"assistant_language", "memory_enabled"}, + "EYESEARCH": {"safe_search", "results_per_page", "region"}, + "EYEBROWSE": {"search_engine", "theme", "history_sync", "safe_browsing", "homepage"}, + } + + @staticmethod + def _app_state_key(user_id: str, app: str) -> dict[str, str]: + return {"PK": f"USER#{user_id}", "SK": f"APP#{app}#STATE"} + + @staticmethod + def _app_session_key(user_id: str, app: str, session_id: str) -> dict[str, str]: + return {"PK": f"USER#{user_id}", "SK": f"APP#{app}#SESSION#{session_id}"} + + @staticmethod + def _app_code_key(app: str, code_hash: str) -> dict[str, str]: + return {"PK": f"APPCODE#{app}#{code_hash}", "SK": "CODE"} + + @classmethod + def app_defaults(cls, app: str) -> dict[str, Any]: + if app not in cls.APP_DEFAULTS: + raise NotFoundError("This app is not registered with Indo Account.") + return copy.deepcopy(cls.APP_DEFAULTS[app]) + + @staticmethod + def strip_url(value: str, limit: int = 2000) -> str: + """Remove query string and fragment so a token cannot leak through a URL.""" + raw = (value or "").strip() + if not raw: + return "" + try: + parts = urlsplit(raw) + except ValueError: + return raw[:limit] + cleaned = urlunsplit((parts.scheme, parts.netloc, parts.path, "", "")) + return cleaned[:limit] + + @staticmethod + def clean_text(value: str, limit: int) -> str: + return " ".join(str(value or "").split())[:limit] + + def _app_box(self, user_id: str, app: str) -> dict[str, Any]: + box = self.app_defaults(app) + item = self.table.get_item(Key=self._app_state_key(user_id, app), ConsistentRead=True).get("Item") + if item: + stored = item.get("state", {}) + for field in ("name", "status", "connected", "connected_at", "last_used_at", "plan", "quota", "renewal", "preferences"): + if field in stored: + box[field] = stored[field] + if isinstance(stored.get("data"), dict): + box["data"].update(stored["data"]) + box["key"] = app + box.setdefault("preferences", box["data"].get("preferences", {})) + return box + + def _write_app_box(self, user_id: str, app: str, box: dict[str, Any]) -> None: + data: dict[str, Any] = { + "history": list(box.get("data", {}).get("history", []))[-self.app_history_limit:], + "saved": list(box.get("data", {}).get("saved", []))[-self.app_saved_limit:], + } + if "memory" in self.APP_DEFAULTS[app]["data"]: + data["memory"] = list(box.get("data", {}).get("memory", []))[-self.app_history_limit:] + state = { + "name": box.get("name", self.APP_DEFAULTS[app]["name"]), + "status": box.get("status", "Active"), + "connected": bool(box.get("connected", False)), + "connected_at": box.get("connected_at"), + "last_used_at": box.get("last_used_at"), + "plan": box.get("plan", "Not connected"), + "quota": box.get("quota", "No usage yet"), + "renewal": box.get("renewal", "—"), + "preferences": dict(box.get("preferences") or {}), + "data": data, + } + if len(json.dumps(state, separators=(",", ":")).encode()) > self.app_box_max_bytes: + raise PayloadTooLargeError("This app's data has reached its size limit. Clear some history and try again.") + self.table.put_item( + Item={ + **self._app_state_key(user_id, app), + "entity_type": "APP_STATE", + "state": state, + "updated_at": utc_now(), + } + ) + + def get_app_box(self, user_id: str, app: str) -> dict[str, Any]: + box = self._app_box(user_id, app) + sessions = self._app_sessions(user_id, app) + box["connected"] = bool(sessions) or bool(box.get("connected")) + box["sessions"] = sessions + box["counts"] = { + "history": len(box["data"].get("history", [])), + "saved": len(box["data"].get("saved", [])), + } + return box + + def list_app_boxes(self, user_id: str) -> list[dict[str, Any]]: + return [self.get_app_box(user_id, app) for app in self.APP_DEFAULTS] + + def _app_sessions(self, user_id: str, app: str) -> list[dict[str, Any]]: + now = int(time.time()) + response = self.table.query( + KeyConditionExpression="PK = :pk AND begins_with(SK, :session)", + ExpressionAttributeValues={":pk": f"USER#{user_id}", ":session": f"APP#{app}#SESSION#"}, + ConsistentRead=True, + ) + sessions = [] + for item in response.get("Items", []): + if int(item.get("ttl", 0)) <= now: + continue + session = self._public(item) + session.pop("token_hash", None) + sessions.append(session) + sessions.sort(key=lambda item: str(item.get("created_at", ""))) + return sessions + + def issue_app_token(self, user_id: str, app: str, device: str) -> dict[str, Any]: + self.app_defaults(app) + token = new_session_token() + session_id = f"aps_{uuid4().hex[:18]}" + now = int(time.time()) + active = self._app_sessions(user_id, app) + overflow = active[: max(0, len(active) - self.app_max_sessions + 1)] + for session in overflow: + self.table.delete_item(Key={"PK": session["PK"], "SK": session["SK"]}) + self.table.put_item( + Item={ + **self._app_session_key(user_id, app, session_id), + "entity_type": "APP_SESSION", + "session_id": session_id, + "app": app, + "token_hash": token_digest(token), + "device": self.clean_text(device, 120) or "Unknown device", + "created_at": utc_now(), + "last_used_at": utc_now(), + "last_used_epoch": now, + "ttl": now + self.app_token_seconds, + } + ) + box = self._app_box(user_id, app) + box["connected"] = True + if not box.get("connected_at"): + box["connected_at"] = utc_now() + box["last_used_at"] = utc_now() + self._write_app_box(user_id, app, box) + self.record_security_event( + user_id, + "app.connected", + f"{box['name']} connected", + f"{self.clean_text(device, 120) or 'A device'} was given access to {box['name']} data.", + ) + return { + "token": f"{app}.{user_id}.{token}", + "expires_in": self.app_token_seconds, + "session_id": session_id, + } + + def user_from_app_token(self, token: str) -> tuple[str, str, str]: + try: + app, user_id, opaque = token.split(".", 2) + except ValueError as error: + raise AuthenticationError("App session is invalid.") from error + if app not in self.APP_DEFAULTS: + raise AuthenticationError("App session is invalid.") + response = self.table.query( + KeyConditionExpression="PK = :pk AND begins_with(SK, :session)", + ExpressionAttributeValues={":pk": f"USER#{user_id}", ":session": f"APP#{app}#SESSION#"}, + ConsistentRead=True, + ) + digest = token_digest(opaque) + session = next((item for item in response.get("Items", []) if item.get("token_hash") == digest), None) + now = int(time.time()) + if not session or int(session.get("ttl", 0)) <= now: + raise AuthenticationError("App session has expired.") + if now - int(session.get("last_used_epoch", 0)) >= self.session_activity_update_seconds: + try: + self.table.update_item( + Key={"PK": session["PK"], "SK": session["SK"]}, + UpdateExpression="SET last_used_at = :stamp, last_used_epoch = :epoch", + ConditionExpression="token_hash = :digest AND #ttl > :now", + ExpressionAttributeNames={"#ttl": "ttl"}, + ExpressionAttributeValues={ + ":stamp": utc_now(), + ":epoch": now, + ":digest": digest, + ":now": now, + }, + ) + except self.table.meta.client.exceptions.ConditionalCheckFailedException as error: + raise AuthenticationError("App session has expired.") from error + return user_id, app, str(session.get("session_id") or session["SK"].rsplit("#", 1)[-1]) + + def revoke_app_sessions(self, user_id: str, app: str, session_id: str | None = None) -> int: + self.app_defaults(app) + sessions = self._app_sessions(user_id, app) + if session_id is None: + targets = sessions + else: + targets = [session for session in sessions if session.get("session_id") == session_id] + if not targets: + raise NotFoundError("This app session is no longer active.") + with self.table.batch_writer() as batch: + for session in targets: + batch.delete_item(Key=self._app_session_key(user_id, app, str(session["session_id"]))) + box = self._app_box(user_id, app) + box["connected"] = bool(self._app_sessions(user_id, app)) + self._write_app_box(user_id, app, box) + if targets: + self.record_security_event( + user_id, + "app.disconnected" if session_id is None else "app.session_revoked", + f"{box['name']} access revoked", + f"{len(targets)} session{'s were' if len(targets) != 1 else ' was'} removed from {box['name']}.", + ) + return len(targets) + + def set_app_status(self, user_id: str, app: str, status: str) -> dict[str, Any]: + if status not in self.APP_STATUSES: + raise ValueError("App status must be Active or Paused.") + box = self._app_box(user_id, app) + box["status"] = status + self._write_app_box(user_id, app, box) + self.record_security_event( + user_id, + "app.paused" if status == "Paused" else "app.resumed", + f"{box['name']} {'paused' if status == 'Paused' else 'resumed'}", + f"{box['name']} access was set to {status}.", + ) + return self.get_app_box(user_id, app) + + def clear_app_data(self, user_id: str, app: str) -> dict[str, Any]: + box = self._app_box(user_id, app) + box["data"] = {key: [] for key in self.APP_DEFAULTS[app]["data"] if isinstance(self.APP_DEFAULTS[app]["data"][key], list)} + box["data"]["preferences"] = {} + box["preferences"] = {} + self._write_app_box(user_id, app, box) + self.record_security_event( + user_id, + "app.data_cleared", + f"{box['name']} data cleared", + f"All {box['name']} history, saved items and preferences were deleted.", + ) + return self.get_app_box(user_id, app) + + def export_app_box(self, user_id: str, app: str) -> dict[str, Any]: + box = self.get_app_box(user_id, app) + return { + "export_version": "1.0", + "exported_at": utc_now(), + "app": app, + "name": box["name"], + "status": box["status"], + "connected": box["connected"], + "connected_at": box.get("connected_at"), + "preferences": box.get("preferences", {}), + "history": box["data"].get("history", []), + "saved": box["data"].get("saved", []), + "sessions": [ + {key: value for key, value in session.items() if key in {"session_id", "device", "created_at", "last_used_at"}} + for session in box["sessions"] + ], + } + + def update_app_preferences(self, user_id: str, app: str, changes: dict[str, Any]) -> dict[str, Any]: + allowed = self.APP_PREFERENCES.get(app, set()) + box = self._app_box(user_id, app) + preferences = dict(box.get("preferences") or {}) + for key, value in changes.items(): + if key not in allowed: + continue + if isinstance(value, bool): + preferences[key] = value + elif isinstance(value, (int, float)): + preferences[key] = value + else: + preferences[key] = self.clean_text(value, 200) + box["preferences"] = preferences + box["data"]["preferences"] = preferences + box["last_used_at"] = utc_now() + self._write_app_box(user_id, app, box) + return {"preferences": preferences} + + def _require_active(self, user_id: str, app: str) -> dict[str, Any]: + box = self._app_box(user_id, app) + if box.get("status") == "Paused": + raise AppPausedError(f"{box['name']} is paused. Resume it in Indo Account to sync again.") + return box + + def list_app_saved(self, user_id: str, app: str, limit: int = 50, cursor: str | None = None) -> dict[str, Any]: + box = self._app_box(user_id, app) + items = list(box["data"].get("saved", [])) + items.sort(key=lambda item: str(item.get("added_at", "")), reverse=True) + start = 0 + if cursor: + start = next((index + 1 for index, item in enumerate(items) if item.get("id") == cursor), 0) + page = items[start : start + max(1, min(limit, 100))] + next_cursor = page[-1]["id"] if len(items) > start + len(page) else None + return {"items": page, "next_cursor": next_cursor, "total": len(items)} + + def add_app_saved(self, user_id: str, app: str, title: str, url: str) -> dict[str, Any]: + box = self._require_active(user_id, app) + cleaned_url = self.strip_url(url) + if not cleaned_url: + raise ValueError("A saved item needs a URL.") + item = { + "id": f"sv_{uuid4().hex[:12]}", + "title": self.clean_text(title, 300) or cleaned_url, + "url": cleaned_url, + "added_at": utc_now(), + } + saved = list(box["data"].get("saved", [])) + saved = [entry for entry in saved if entry.get("url") != cleaned_url] + saved.append(item) + box["data"]["saved"] = saved[-self.app_saved_limit:] + box["last_used_at"] = utc_now() + self._write_app_box(user_id, app, box) + return item + + def delete_app_saved(self, user_id: str, app: str, item_id: str) -> None: + box = self._require_active(user_id, app) + saved = list(box["data"].get("saved", [])) + remaining = [entry for entry in saved if entry.get("id") != item_id] + if len(remaining) == len(saved): + raise NotFoundError("That saved item was not found.") + box["data"]["saved"] = remaining + self._write_app_box(user_id, app, box) + + def list_app_history(self, user_id: str, app: str, limit: int = 50, cursor: str | None = None) -> dict[str, Any]: + box = self._app_box(user_id, app) + items = list(box["data"].get("history", [])) + items.sort(key=lambda item: str(item.get("visited_at", "")), reverse=True) + start = 0 + if cursor: + start = next((index + 1 for index, item in enumerate(items) if item.get("id") == cursor), 0) + page = items[start : start + max(1, min(limit, 100))] + next_cursor = page[-1]["id"] if len(items) > start + len(page) else None + return {"items": page, "next_cursor": next_cursor, "total": len(items)} + + def add_app_history(self, user_id: str, app: str, entries: list[dict[str, Any]]) -> dict[str, Any]: + box = self._require_active(user_id, app) + if box.get("preferences", {}).get("history_sync") is False and app == "EYEBROWSE": + raise AppPausedError("History sync is turned off for this app.") + history = list(box["data"].get("history", [])) + added = 0 + for entry in entries[:100]: + url = self.strip_url(str(entry.get("url") or entry.get("origin") or "")) + if not url: + continue + parts = urlsplit(url) + history.append( + { + "id": f"hs_{uuid4().hex[:12]}", + "title": self.clean_text(entry.get("title", ""), 300) or url, + "origin": f"{parts.scheme}://{parts.netloc}" if parts.netloc else url, + "path": (parts.path or "/")[:500], + "visited_at": self.clean_text(entry.get("visited_at", ""), 40) or utc_now(), + "visits": max(1, min(int(entry.get("visits", 1) or 1), 1000)), + } + ) + added += 1 + box["data"]["history"] = history[-self.app_history_limit:] + box["last_used_at"] = utc_now() + self._write_app_box(user_id, app, box) + return {"added": added, "total": len(box["data"]["history"])} + + def clear_app_history(self, user_id: str, app: str) -> dict[str, Any]: + box = self._app_box(user_id, app) + box["data"]["history"] = [] + self._write_app_box(user_id, app, box) + return {"history": 0} + + def create_app_code(self, user_id: str, app: str, code_hash: str, code_challenge: str) -> None: + self.app_defaults(app) + now = int(time.time()) + self.table.put_item( + Item={ + **self._app_code_key(app, code_hash), + "entity_type": "APP_CODE", + "user_id": user_id, + "app": app, + "code_challenge": code_challenge, + "created_at": utc_now(), + "ttl": now + self.app_code_seconds, + } + ) + + def consume_app_code(self, app: str, code_hash: str) -> dict[str, Any]: + key = self._app_code_key(app, code_hash) + item = self.table.get_item(Key=key, ConsistentRead=True).get("Item") + now = int(time.time()) + if not item or int(item.get("ttl", 0)) <= now: + raise OtpError("This sign-in request has expired. Start again from the app.") + try: + self.table.delete_item( + Key=key, + ConditionExpression="attribute_exists(PK) AND #ttl > :now", + ExpressionAttributeNames={"#ttl": "ttl"}, + ExpressionAttributeValues={":now": now}, + ) + except self.table.meta.client.exceptions.ConditionalCheckFailedException as error: + raise OtpError("This sign-in request has expired. Start again from the app.") from error + return item diff --git a/backend/tests/app_data_smoke.py b/backend/tests/app_data_smoke.py new file mode 100644 index 0000000..8365c44 --- /dev/null +++ b/backend/tests/app_data_smoke.py @@ -0,0 +1,319 @@ +"""Offline smoke test for the app-data API. + +Runs the whole hand-off and isolation flow against an in-memory table, so it +needs no AWS credentials and never touches production: + + python3 backend/tests/app_data_smoke.py +""" + +from __future__ import annotations + +import base64 +import hashlib +import os +import sys + +os.environ.setdefault("AWS_DEFAULT_REGION", "ap-southeast-2") +os.environ.setdefault("AWS_ACCESS_KEY_ID", "test") +os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "test") +os.environ.setdefault("OTP_HASH_SECRET", "x" * 40) + +sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parents[1])) + +from fastapi.testclient import TestClient # noqa: E402 + +from app import main as api # noqa: E402 +from app.repository import DynamoAccountRepository # noqa: E402 + + +class ConditionalCheckFailed(Exception): + pass + + +class FakeClient: + class exceptions: + ConditionalCheckFailedException = ConditionalCheckFailed + TransactionCanceledException = type("TransactionCanceledException", (Exception,), {}) + TransactionConflictException = type("TransactionConflictException", (Exception,), {}) + ProvisionedThroughputExceededException = type("ProvisionedThroughputExceededException", (Exception,), {}) + + def describe_table(self, TableName): # noqa: N803 + return { + "TableName": TableName, + "TableStatus": "ACTIVE", + "BillingModeSummary": {"BillingMode": "PROVISIONED"}, + "ProvisionedThroughput": {"ReadCapacityUnits": 25, "WriteCapacityUnits": 25}, + } + + meta = type("Meta", (), {"region_name": "ap-southeast-2"})() + + def transact_write_items(self, TransactItems): # noqa: N803 + return {"ResponseMetadata": {"HTTPStatusCode": 200}} + + +class FakeTable: + name = "UnifiedAppTable" + + def __init__(self): + self.items = {} + self.meta = type("Meta", (), {"client": FakeClient()})() + + def _key(self, key): + return (key["PK"], key["SK"]) + + def get_item(self, Key, ConsistentRead=False): # noqa: N803 + item = self.items.get(self._key(Key)) + return {"Item": dict(item)} if item else {} + + def put_item(self, Item): + self.items[self._key(Item)] = dict(Item) + + def query(self, KeyConditionExpression, ExpressionAttributeValues, ConsistentRead=False): # noqa: N803 + pk = ExpressionAttributeValues[":pk"] + prefix = None + for name, value in ExpressionAttributeValues.items(): + if name == ":session": + prefix = value + rows = [dict(item) for (item_pk, sk), item in self.items.items() if item_pk == pk] + if prefix: + rows = [row for row in rows if str(row["SK"]).startswith(prefix)] + return {"Items": rows} + + def delete_item(self, Key, ConditionExpression=None, ExpressionAttributeValues=None, ExpressionAttributeNames=None): # noqa: N803 + existing = self.items.get(self._key(Key)) + if ConditionExpression and not existing: + raise ConditionalCheckFailed() + if ConditionExpression and ExpressionAttributeValues: + if ":session_id" in ExpressionAttributeValues: + if existing.get("session_id") != ExpressionAttributeValues[":session_id"]: + raise ConditionalCheckFailed() + if ":now" in ExpressionAttributeValues: + if int(existing.get("ttl", 0)) <= ExpressionAttributeValues[":now"]: + raise ConditionalCheckFailed() + self.items.pop(self._key(Key), None) + + def update_item(self, Key, UpdateExpression, ConditionExpression=None, ExpressionAttributeValues=None, ExpressionAttributeNames=None): # noqa: N803 + item = self.items.get(self._key(Key)) + if not item: + raise ConditionalCheckFailed() + if ConditionExpression and ExpressionAttributeValues and ":digest" in ExpressionAttributeValues: + if item.get("token_hash") != ExpressionAttributeValues[":digest"]: + raise ConditionalCheckFailed() + for name, value in (ExpressionAttributeValues or {}).items(): + if name in {":digest", ":now"}: + continue + field = name.lstrip(":") + item[{"stamp": "last_used_at", "active": "last_active"}.get(field, field)] = value + return {"Attributes": item} + + def batch_writer(self): + table = self + + class Writer: + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def delete_item(self, Key): # noqa: N803 + table.items.pop(table._key(Key), None) + + return Writer() + + +def build_repo(): + table = FakeTable() + return table, DynamoAccountRepository( + table, + session_days=30, + session_max_active=10, + session_activity_update_seconds=300, + otp_max_attempts=5, + otp_verification_seconds=900, + app_token_days=30, + app_code_seconds=60, + app_history_limit=5, + app_saved_limit=5, + app_box_max_bytes=200 * 1024, + app_max_sessions=2, + ) + + +def pkce(verifier: str) -> str: + return base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=") + + +failures = [] + + +def check(name, condition, extra=""): + if condition: + print(f" PASS {name}") + else: + print(f" FAIL {name} {extra}") + failures.append(name) + + +def main() -> int: + table, repo = build_repo() + api.repository = repo + client = TestClient(api.app) + + user_id = "usr_test0001" + table.put_item( + Item={ + "PK": f"USER#{user_id}", + "SK": "PROFILE", + "user_id": user_id, + "eyemail_id": "tester@eyemail.in", + "full_name": "Test User", + "nickname": "Tester", + "language": "kn", + "secondary_email": "tester@example.com", + } + ) + session_token = repo.create_bearer_session(user_id, "Chrome on Linux") + user_headers = {"Authorization": f"Bearer {session_token}"} + + print("panel surface") + r = client.get("/api/v1/me/apps", headers=user_headers) + check("list apps 200", r.status_code == 200, r.text) + apps = r.json()["apps"] + check("three app boxes", len(apps) == 3, str([a["key"] for a in apps])) + check("nothing connected yet", all(a["connected"] is False for a in apps)) + + print("handoff") + verifier = "a" * 50 + bad = client.post( + "/api/v1/me/apps/EYEBROWSE/authorize", + headers=user_headers, + json={"redirect": "https://evil.example/steal", "code_challenge": pkce(verifier), "state": "s"}, + ) + check("unregistered redirect refused", bad.status_code == 400, bad.text) + + good = client.post( + "/api/v1/me/apps/EYEBROWSE/authorize", + headers=user_headers, + json={"redirect": "indobrowse://auth", "code_challenge": pkce(verifier), "state": "state123"}, + ) + check("authorize 201", good.status_code == 201, good.text) + redirect_url = good.json()["redirect_url"] + check("redirect carries state", "state=state123" in redirect_url, redirect_url) + code = redirect_url.split("code=")[1].split("&")[0] + + wrong = client.post( + "/api/v1/app/session", + json={"app": "EYEBROWSE", "code": code, "code_verifier": "b" * 50, "device": "Pixel"}, + ) + check("wrong PKCE verifier refused", wrong.status_code == 400, wrong.text) + + check("code burned after a failed attempt", client.post( + "/api/v1/app/session", + json={"app": "EYEBROWSE", "code": code, "code_verifier": verifier, "device": "Pixel"}, + ).status_code == 400) + + fresh = client.post( + "/api/v1/me/apps/EYEBROWSE/authorize", + headers=user_headers, + json={"redirect": "indobrowse://auth", "code_challenge": pkce(verifier), "state": "state123"}, + ) + code = fresh.json()["redirect_url"].split("code=")[1].split("&")[0] + + exchanged = client.post( + "/api/v1/app/session", + json={"app": "EYEBROWSE", "code": code, "code_verifier": verifier, "device": "Pixel 7"}, + ) + check("exchange 201", exchanged.status_code == 201, exchanged.text) + app_token = exchanged.json()["token"] + check("token is app scoped", app_token.startswith("EYEBROWSE."), app_token[:20]) + identity = exchanged.json()["identity"] + check("identity has five fields", sorted(identity) == ["full_name", "indo_id", "language", "nickname", "user_id"], str(identity)) + check("no email leaked", "secondary_email" not in identity and "tester@example.com" not in str(identity)) + + replay = client.post( + "/api/v1/app/session", + json={"app": "EYEBROWSE", "code": code, "code_verifier": verifier, "device": "Pixel"}, + ) + check("code cannot be replayed", replay.status_code == 400, replay.text) + + app_headers = {"Authorization": f"Bearer {app_token}"} + + print("app surface") + check("app me 200", client.get("/api/v1/app/me", headers=app_headers).status_code == 200) + state = client.get("/api/v1/app/state", headers=app_headers).json() + check("app is connected", state["connected"] is True, str(state)) + + saved = client.post( + "/api/v1/app/saved", + headers=app_headers, + json={"title": "ISRO", "url": "https://www.isro.gov.in/missions?token=SECRET#frag"}, + ) + check("saved created", saved.status_code == 201, saved.text) + check("query string stripped", "SECRET" not in saved.json()["url"], saved.json()["url"]) + check("fragment stripped", "#" not in saved.json()["url"], saved.json()["url"]) + + history = client.post( + "/api/v1/app/history", + headers=app_headers, + json={"entries": [{"url": f"https://example.com/page{i}?q=secret", "title": f"Page {i}"} for i in range(8)]}, + ) + check("history accepted", history.status_code == 202, history.text) + check("history trimmed to limit", history.json()["total"] == 5, history.text) + listed = client.get("/api/v1/app/history", headers=app_headers).json() + check("history has no query strings", all("?" not in item["path"] for item in listed["items"]), str(listed["items"][:1])) + + print("isolation") + cross = client.get("/api/v1/app/saved", headers=app_headers, params={"app": "EYESEARCH"}) + check("naming another app in a query is ignored", cross.status_code == 200 and cross.json()["total"] == 1, cross.text) + cross_path = client.get("/api/v1/app/EYESEARCH/state", headers=app_headers) + check("no path exists that names another app", cross_path.status_code in {403, 404, 422}, cross_path.text) + eyesearch_box = client.get("/api/v1/me/apps/EYESEARCH", headers=user_headers).json() + check("Eyesearch box untouched by Eyebrowse", eyesearch_box["counts"]["saved"] == 0 and eyesearch_box["counts"]["history"] == 0, str(eyesearch_box["counts"])) + panel_with_app_token = client.get("/api/v1/me/apps", headers=app_headers) + check("app token rejected on panel door", panel_with_app_token.status_code in {401, 403}, panel_with_app_token.text) + app_door_with_user_token = client.get("/api/v1/app/me", headers=user_headers) + check("account session rejected on app door", app_door_with_user_token.status_code in {401, 403}, app_door_with_user_token.text) + + print("pause and clear") + paused = client.patch("/api/v1/me/apps/EYEBROWSE", headers=user_headers, json={"status": "Paused"}) + check("pause 200", paused.status_code == 200, paused.text) + blocked = client.post("/api/v1/app/saved", headers=app_headers, json={"title": "x", "url": "https://example.com/x"}) + check("paused app cannot write", blocked.status_code == 403, blocked.text) + check("paused app can still read", client.get("/api/v1/app/state", headers=app_headers).status_code == 200) + + box = client.get("/api/v1/me/apps/EYEBROWSE", headers=user_headers).json() + check("panel sees the session", len(box["sessions"]) == 1, str(box["sessions"])) + check("panel sees counts", box["counts"]["saved"] == 1 and box["counts"]["history"] == 5, str(box["counts"])) + + exported = client.get("/api/v1/me/apps/EYEBROWSE/export", headers=user_headers) + check("export 200", exported.status_code == 200, exported.text) + check("export has no token hashes", "token_hash" not in exported.text) + + cleared = client.delete("/api/v1/me/apps/EYEBROWSE/data", headers=user_headers) + check("clear 200", cleared.status_code == 200, cleared.text) + check("history emptied", cleared.json()["counts"]["history"] == 0, cleared.text) + check("saved emptied", cleared.json()["counts"]["saved"] == 0, cleared.text) + + revoked = client.delete("/api/v1/me/apps/EYEBROWSE/sessions", headers=user_headers) + check("revoke 204", revoked.status_code == 204, revoked.text) + after = client.get("/api/v1/app/state", headers=app_headers) + check("revoked token stops working", after.status_code == 401, after.text) + disconnected = client.get("/api/v1/me/apps/EYEBROWSE", headers=user_headers).json() + check("box shows disconnected", disconnected["connected"] is False, str(disconnected["connected"])) + + print("cascade") + repo.delete_account(user_id) + left = [key for key in table.items if key[0] == f"USER#{user_id}"] + check("account delete removes every app item", not left, str(left)) + + print() + if failures: + print(f"{len(failures)} FAILED: {failures}") + return 1 + print("all checks passed") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/app-data-contract.md b/docs/app-data-contract.md new file mode 100644 index 0000000..f49ffc6 --- /dev/null +++ b/docs/app-data-contract.md @@ -0,0 +1,288 @@ +# Indo Account — App Data Contract + +Status: draft for owner approval. Version 0.1. Date: 16 Nov 2026. + +This document is the handshake between the Indo Account backend, the management +panel, and each Indo app (Sankalp, Eyesearch, Eyebrowse). Nothing is implemented +against it yet. Once approved it is the checklist the work is judged against. + +--- + +## 1. Principles + +1. The account is the only source of truth. Apps never copy profile fields into + local storage; they read them live. +2. Each app owns exactly one data box. An app can never read or write another + app's box, and this is enforced on the server, never trusted from the client. +3. One identity, one password, one place to manage everything. Apps do not build + their own settings screens for account data. +4. Deleting the account deletes every app box with it. + +## 2. App registry + +Only these keys are accepted anywhere in the API. Anything else is a 404. + +| Key | Display name | Box contents | +| --- | --- | --- | +| `SANKALPA` | Sankalp | history, saved, memory, preferences | +| `EYESEARCH` | Eyesearch Search Engine | history, saved, preferences | +| `EYEBROWSE` | Eyebrowse Browser | history, saved, preferences | + +A key is never renamed, because it is part of the DynamoDB sort key +(`APP##STATE`) and of every issued token. + +## 3. Two API surfaces + +The panel and the apps get different surfaces. This is the core of the isolation. + +| Surface | Path prefix | Authenticated by | Can touch | +| --- | --- | --- | --- | +| Panel (user session) | `/api/v1/me/apps...` | the user's normal bearer session | all three boxes | +| App (scoped token) | `/api/v1/app...` | an app-scoped token | its own box only | + +An app-scoped token presented on `/api/v1/me/...` is rejected with `403`. A user +session presented on `/api/v1/app/...` is also rejected with `403`. There is no +path where an app token reaches another app's data. + +## 4. Sign-in hand-off (first-party) + +Eyebrowse is a first-party client, so there is no consent screen. + +1. The app opens the account sign-in page in a Custom Tab: + + ``` + https://indoworkspace.github.io/Indo-Account/Sign%20in/index.html + ?app=EYEBROWSE + &redirect=indobrowse%3A%2F%2Fauth + &state=<32 random bytes, base64url> + &code_challenge= + &code_challenge_method=S256 + ``` + +2. After a successful sign-in the account validates `app` against the registry + and `redirect` against the registered scheme for that app, then redirects to: + + ``` + indobrowse://auth?code=&state= + ``` + +3. While the user is signed in, the page asks the API for the code: + + ``` + POST /api/v1/me/apps/EYEBROWSE/authorize + { "redirect": "indobrowse://auth", + "code_challenge": "", + "state": "" } + ``` + + Response `201`: + + ```json + { "redirect_url": "indobrowse://auth?code=...&state=...", + "expires_in": 60, + "app": { "key": "EYEBROWSE", "name": "Eyebrowse Browser" } } + ``` + + A redirect that does not match the registered prefix for that app is refused + with `400`, so a stolen sign-in link cannot be pointed at another host. + +4. The app validates that `state` matches what it sent, then exchanges the code: + + ``` + POST /api/v1/app/session + { + "app": "EYEBROWSE", + "code": "", + "code_verifier": "" + } + ``` + + Response `201`: + + ```json + { + "token": "", + "expires_in": 2592000, + "app": { "key": "EYEBROWSE", "name": "Eyebrowse Browser" }, + "identity": { + "user_id": "usr_...", + "indo_id": "name@eyemail.in", + "full_name": "...", + "nickname": "...", + "language": "kn" + } + } + ``` + +Rules for the code: single use, 60-second lifetime, bound to the app key and to +the PKCE challenge, and hashed at rest. A replayed or expired code returns `400`. +The code is consumed by the first exchange attempt even when the PKCE verifier +is wrong, so a guessed verifier cannot be retried against a live code. + +Rules for the token: opaque, 32 random bytes, stored only as a SHA-256 digest, +30-day lifetime, bound to one app key, listed as its own session so the panel can +revoke it alone. + +`identity` carries exactly five fields and nothing else. No email, no mobile, no +date of birth, no address. + +## 5. App-facing endpoints + +All require `Authorization: Bearer `. All return `403` for a token +that does not match the app key in the path. + +The app key comes from the token, never from the path. There is no URL an app +can call that names another app, so a mix-up is impossible rather than merely +refused. + +| Method | Path | Purpose | +| --- | --- | --- | +| `GET` | `/api/v1/app/me` | current identity block (same five fields) | +| `GET` | `/api/v1/app/state` | this app's box: status, connected, counts, preferences | +| `PATCH` | `/api/v1/app/preferences` | merge preferences | +| `GET` | `/api/v1/app/saved?limit=50&cursor=...` | paginated saved items | +| `POST` | `/api/v1/app/saved` | add one saved item | +| `DELETE` | `/api/v1/app/saved/{id}` | remove one saved item | +| `GET` | `/api/v1/app/history?limit=50&cursor=...` | paginated history | +| `POST` | `/api/v1/app/history` | add up to 100 entries in one call | +| `DELETE` | `/api/v1/app/history` | clear history for this app only | +| `DELETE` | `/api/v1/app/data` | clear this app's whole box | +| `POST` | `/api/v1/app/logout` | revoke the presented token | + +A paused app (`status: "Paused"`) gets `403` on every write endpoint, but may +still read, so it can show the user why nothing is syncing. + +## 6. Panel-facing endpoints + +All require the user's normal bearer session. + +| Method | Path | Purpose | +| --- | --- | --- | +| `GET` | `/api/v1/me/apps` | all three boxes, summary only | +| `GET` | `/api/v1/me/apps/{app}` | one box in full, including sessions | +| `PATCH` | `/api/v1/me/apps/{app}` | `{"status": "Active" \| "Paused"}` | +| `DELETE` | `/api/v1/me/apps/{app}/sessions` | sign out this app only | +| `DELETE` | `/api/v1/me/apps/{app}/sessions/{session_id}` | sign out one device of this app | +| `DELETE` | `/api/v1/me/apps/{app}/data` | clear this app's whole box | +| `GET` | `/api/v1/me/apps/{app}/export` | JSON export of this box | + +Disconnecting is `DELETE /api/v1/me/apps/{app}/sessions` plus +`{"connected": false}` recorded on the box; there is no separate endpoint. + +## 7. Data shapes + +App box, as returned to the panel: + +```json +{ + "key": "EYEBROWSE", + "name": "Eyebrowse Browser", + "status": "Active", + "connected": true, + "connected_at": "2026-11-16T05:10:00Z", + "last_used_at": "2026-11-16T05:12:00Z", + "counts": { "history": 12, "saved": 3 }, + "preferences": { "search_engine": "duckduckgo", "theme": "system", "history_sync": false }, + "sessions": [ + { + "session_id": "aps_7f3e9b21", + "device": "Eyebrowse on Pixel 7", + "created_at": "2026-11-16T05:10:00Z", + "last_used_at": "2026-11-16T05:12:00Z" + } + ] +} +``` + +Saved item: + +```json +{ "id": "sv_9a1c", "title": "ISRO", "url": "https://www.isro.gov.in/", "added_at": "2026-11-16T05:11:00Z" } +``` + +History entry: + +```json +{ "id": "hs_4d2e", "title": "ISRO missions", "origin": "https://www.isro.gov.in", "path": "/missions", "visited_at": "2026-11-16T05:11:30Z", "visits": 1 } +``` + +`url`, `origin` and `path` never contain a query string or fragment. The server +strips both before storing, so a client that forgets cannot leak a token through +a URL. + +Preferences, per app, closed set: + +| App | Keys | +| --- | --- | +| `EYEBROWSE` | `search_engine`, `theme`, `history_sync`, `safe_browsing`, `homepage` | +| `EYESEARCH` | `safe_search`, `results_per_page`, `region` | +| `SANKALPA` | `assistant_language`, `memory_enabled` | + +Unknown preference keys are dropped silently, not rejected. + +## 8. Limits + +| Limit | Value | Reason | +| --- | --- | --- | +| History entries per app | 500, oldest dropped first | item size | +| Saved items per app | 500 | item size | +| `title` | 300 characters | item size | +| `url` | 2000 characters | item size | +| `path` | 500 characters | item size | +| History batch | 100 entries per request | request size | +| Total box size | 200 KB | DynamoDB's 400 KB item limit, with headroom | +| App token requests | 120 per minute per token | abuse | +| App token writes | 30 per minute per token | abuse | +| Code lifetime | 60 seconds, single use | replay | + +Over-limit writes return `413` with `{"detail": "..."}`. History beyond 500 is +trimmed rather than refused. + +## 9. Errors + +Existing conventions are kept: every error is `{"detail": "string"}`, and no +message ever reveals whether another account exists. + +| Status | When | +| --- | --- | +| `400` | expired or replayed code, bad PKCE verifier, malformed body | +| `401` | missing, invalid or revoked token | +| `403` | token used on the wrong surface, wrong app key, or app paused | +| `404` | unknown app key, unknown item id | +| `413` | body or box over the limits above | +| `429` | rate limit, with `retry_after` | + +## 10. Audit + +Every one of these writes a security event through the existing +`record_security_event` path, visible in the account's activity: + +- `app.connected` — an app obtained its first token +- `app.session_revoked` — one app signed out +- `app.disconnected` — all sessions of one app revoked +- `app.data_cleared` — a box was emptied +- `app.paused` / `app.resumed` + +## 11. Storage + +One item per app per user, as today: + +``` +PK = USER# +SK = APP##STATE +``` + +New attributes: `connected_at`, `last_used_at`, `counts`, and the sessions are +kept as their own items (`SK = APP##SESSION#`) so one app's session can +be revoked without touching another. + +Account deletion already removes the whole `USER#` partition, so every +app box and every app session goes with it. No new cascade code is needed. + +## 12. Non-goals for this phase + +- Third-party OAuth / OIDC and a consent screen. +- History or bookmark sync from Eyebrowse. Identity only, first. +- Any migration of existing localStorage data beyond what already syncs. +- Payments, GST, contacts — removed by the owner, not to be reintroduced. +- SMS OTP — deferred by the owner.