"""Store tenant Login envelopes and return authorized metadata only.""" import datetime as dt import secrets from core import keychain, login_envelope, login_origins KEY = "logins" MAX_ENTRIES = 40 MAX_SECRET_LENGTH = 4096 CONSENT_VERSION = "logins-read-only-v1" SECOND_FACTORS = frozenset({"none", "totp", "text", "sms", "email", "push", "manual", "code", "ask_user"}) META_FIELDS = ("id", "label", "origin", "username", "second_factor", "scope", "owner", "status", "preview", "created", "consent_version", "consent_at") ACTIVITY_FIELDS = ("id", "entry_id", "username", "status", "started_at", "allowed_actions", "action", "outcome") LoginLocked = login_envelope.LoginLocked class LoginStoreUnavailable(RuntimeError): """A strict tenant store operation failed.""" class LoginAccessDenied(PermissionError): """The requested Login is unavailable to this user.""" class LoginBusinessDenied(LoginAccessDenied): """Only an Administrator may change a business Login.""" def read_bucket(rt, name): """Read through the bound strict store seam instead of a display fallback.""" try: value = rt._store()._read_strict(rt.store_key(name)) if not isinstance(value, dict): raise ValueError() return value except Exception: raise LoginStoreUnavailable("The Login store is unavailable.") from None def _rows(rt): bucket = read_bucket(rt, KEY) entries = bucket.get("entries", {}) if not isinstance(entries, dict): raise LoginStoreUnavailable("The Login store is unavailable.") return entries def _visible(row, uname): return (isinstance(row, dict) and bool(uname) and (row.get("scope") == "business" or (row.get("scope") == "personal" and row.get("owner") == uname))) def may_touch(row, uname, is_admin=False): """A personal owner or business Administrator may change a Login.""" return (_visible(row, uname) and (row.get("scope") == "personal" or is_admin is True)) def _authorized(row, entry_id, uname, is_admin=False, *, touch=False): if not _visible(row, uname) or row.get("id") != entry_id: raise LoginAccessDenied("This Login is unavailable.") if touch and not may_touch(row, uname, is_admin): raise LoginBusinessDenied("Only an Administrator may change a business Login.") return row def _meta(row): metadata = {field: row.get(field, "") for field in META_FIELDS} metadata["preview"] = "\u2026\u2026" if any(not isinstance(value, str) for value in metadata.values()): raise LoginStoreUnavailable("The Login metadata is unavailable.") return metadata def list_meta(rt, uname, is_admin): """List business Logins and this user's personal Logins without decrypting.""" return [_meta(row) for _, row in sorted(_rows(rt).items()) if _visible(row, uname)] def odoo_origins(rt): """Resolve every configured Odoo host or refuse an uncertain connection.""" message = "The tenant's Odoo websites could not be checked." try: tenant = rt.tenant cfg = getattr(tenant, "config", {}) or {} if not isinstance(cfg, dict): raise ValueError() found = [] def collect(value): if isinstance(value, str): found.append(login_origins.configured_host(value)) elif isinstance(value, (tuple, list)): for item in value: collect(item) elif isinstance(value, dict): direct = [value[name] for name in ("url", "origin", "host", "odoo_url") if value.get(name)] if direct: for item in direct: collect(item) else: if not value or any(name in value for name in ("url", "origin", "host", "odoo_url", "db", "user", "api_key", "password")): raise ValueError() if "creds" in value: collect(value["creds"]) return for item in value.values(): collect(item) else: raise ValueError() for name in ("odoo_url", "odoo_host", "odoo_origin", "odoo_origins", "odoo", "odoo_connections"): if name in cfg and cfg[name] is not None: collect(cfg[name]) connectors = cfg.get("connectors", {}) if isinstance(connectors, dict) and "odoo" in connectors: collect(connectors["odoo"]) # Check the strict bucket first so list_entries cannot mask a read failure. bucket = read_bucket(rt, keychain.KEY) entries = bucket.get("entries", {}) if not isinstance(entries, dict): raise ValueError() for eid, row in entries.items(): if not isinstance(row, dict): raise ValueError() if row.get("type") == "odoo": fields = keychain.read_fields(rt, eid) if not isinstance(fields, dict) or not fields.get("url"): raise ValueError() collect(fields["url"]) sources = getattr(tenant, "sources", {}) or {} if not isinstance(sources, dict): raise ValueError() if "odoo" in sources: source = sources["odoo"] creds = getattr(source, "_creds", None) or getattr(source, "creds", None) source_url = getattr(source, "url", None) or getattr(source, "origin", None) if isinstance(source, dict): collect(source) elif creds: if not isinstance(creds, dict) or not creds.get("url"): raise ValueError() collect(creds["url"]) elif source_url: collect(source_url) elif not found and rt.key != "royal-imports": raise ValueError() if rt.key == "royal-imports": import os env_url = os.environ.get("ODOO_URL", "") if env_url: collect(env_url) elif "odoo" in sources and not found: raise ValueError() return tuple(sorted(set(found))) except Exception: raise login_origins.LoginOriginError(message) from None def check_origin(rt, origin): return login_origins.check(origin, odoo_origins=odoo_origins(rt)) def add(rt, label, origin, username, password, totp_seed, second_factor, scope, owner, *, is_admin=False, consent=False): """Seal and synchronously store a Login after scope and origin checks.""" if scope not in ("personal", "business") or not isinstance(owner, str) or not owner.strip(): raise ValueError("Choose a Login scope and an owner.") if scope == "business" and is_admin is not True: raise LoginBusinessDenied("Only an Administrator can add a business Login.") if consent is not True: raise ValueError("Consent is required to save a Login.") if (not isinstance(label, str) or not label.strip() or len(label) > 80 or not isinstance(username, str) or not username.strip() or len(username) > 320 or len(owner) > 320 or owner != owner.strip() or not isinstance(second_factor, str) or second_factor not in SECOND_FACTORS): raise ValueError("Enter a Login label, username and second factor.") if (not isinstance(password, str) or not 5 <= len(password) <= MAX_SECRET_LENGTH or not isinstance(totp_seed, str) or len(totp_seed) > 256): raise ValueError("Enter valid Login credentials.") original_seed = totp_seed if second_factor == "totp": import base64 try: normalized_seed = totp_seed.replace(" ", "").upper().rstrip("=") decoded = base64.b32decode(normalized_seed + "=" * (-len(normalized_seed) % 8)) if len(decoded) < 10: raise ValueError() totp_seed = normalized_seed except Exception: raise ValueError("Enter a valid authenticator seed.") from None elif totp_seed: raise ValueError("An authenticator seed requires the TOTP second factor.") clean_origin = check_origin(rt, origin) for secret in (password, totp_seed, original_seed): if secret and any(secret in value for value in (label, clean_origin, username, owner)): raise ValueError("Keep Login credentials out of its metadata.") eid = "login_" + secrets.token_hex(12) ctx = login_envelope.context(rt.key, eid, clean_origin) created = dt.datetime.now(dt.timezone.utc).isoformat() row = {"id": eid, "label": label.strip(), "origin": clean_origin, "username": username, "second_factor": second_factor, "scope": scope, "owner": owner, "status": "active", "preview": "\u2026\u2026", "created": created, "consent_at": created, "consent_version": CONSENT_VERSION, "context": ctx, **login_envelope.seal({"password": password, "totp_seed": totp_seed}, ctx)} def store(cur): if not isinstance(cur, dict) or not isinstance(cur.get("entries", {}), dict): raise LoginStoreUnavailable("The Login store is unavailable.") entries = cur.setdefault("entries", {}) if eid in entries: if entries[eid] == row: return cur raise LoginStoreUnavailable("The Login could not be saved.") if len(entries) >= MAX_ENTRIES: raise ValueError("The Login vault has reached its 40 Login limit.") entries[eid] = row return cur try: saved = rt.update(KEY, store, flush="sync") if not isinstance(saved, dict) or saved.get("entries", {}).get(eid) != row: raise LoginStoreUnavailable("The Login could not be saved.") except ValueError: raise ValueError("The Login could not be saved. Check the vault limit.") from None except Exception: raise LoginStoreUnavailable("The Login could not be saved.") from None return _meta(row) def entry_for_run(rt, entry_id, uname, is_admin=False): """Recheck visibility, status, origin and context before a worker starts.""" return _entry_for_run(rt, _rows(rt).get(entry_id), entry_id, uname, is_admin) def _entry_for_run(rt, row, entry_id, uname, is_admin=False): _authorized(row, entry_id, uname, is_admin) if row.get("status") != "active": raise LoginAccessDenied("This Login is unavailable.") origin = check_origin(rt, row.get("origin")) expected = login_envelope.context(rt.key, entry_id, origin) if origin != row.get("origin") or row.get("context") != expected: raise LoginAccessDenied("This Login is unavailable.") return row def _update(rt, fn): try: saved = rt.update(KEY, fn, flush="sync") if not isinstance(saved, dict) or not isinstance(saved.get("entries"), dict): raise LoginStoreUnavailable("The Login could not be saved.") return saved except (LoginAccessDenied, LoginLocked, login_origins.LoginOriginError): raise except Exception: raise LoginStoreUnavailable("The Login could not be saved.") from None def _mutable_entries(cur): if not isinstance(cur, dict) or not isinstance(cur.get("entries", {}), dict): raise LoginStoreUnavailable("The Login store is unavailable.") return cur.get("entries", {}) def revoke(rt, entry_id, uname, is_admin=False): """Persist revocation with the same authority check inside the store update.""" _authorized(_rows(rt).get(entry_id), entry_id, uname, is_admin, touch=True) def change(cur): row = _authorized(_mutable_entries(cur).get(entry_id), entry_id, uname, is_admin, touch=True) row["status"] = "revoked" return cur row = _update(rt, change).get("entries", {}).get(entry_id) _authorized(row, entry_id, uname, is_admin, touch=True) if row.get("status") != "revoked": raise LoginStoreUnavailable("The Login could not be revoked.") return _meta(row) def delete(rt, entry_id, uname, is_admin=False): """Remove the Login, its use log and its run records synchronously.""" _authorized(_rows(rt).get(entry_id), entry_id, uname, is_admin, touch=True) def change(cur): entries = _mutable_entries(cur) _authorized(entries.get(entry_id), entry_id, uname, is_admin, touch=True) for name in ("activity", "runs"): if not isinstance(cur.get(name, {}), dict): raise LoginStoreUnavailable("The Login store is unavailable.") del entries[entry_id] cur.get("activity", {}).pop(entry_id, None) runs = cur.get("runs", {}) for run_id, run in list(runs.items()): if not isinstance(run, dict): raise LoginStoreUnavailable("The Login store is unavailable.") if run.get("entry_id") == entry_id: del runs[run_id] return cur saved = _update(rt, change) if entry_id in _mutable_entries(saved): raise LoginStoreUnavailable("The Login could not be deleted.") return True def begin_run(rt, entry_id, uname, is_admin=False, *, reserve_usd=0.50, action="Read website"): """Admit a run and record safe metadata without decrypting the Login.""" from core import login_budget if action not in ("Read website", "Read purchase orders"): raise LoginStoreUnavailable("run_failed") if not 0 < login_budget._decimal(reserve_usd) <= login_budget._decimal(0.50): raise login_budget.LoginBudgetUnavailable("budget_unavailable") entry_for_run(rt, entry_id, uname, is_admin) run = {"id": "login_run_" + secrets.token_hex(12), "entry_id": entry_id, "username": uname, "status": "running", "started_at": dt.datetime.now(dt.timezone.utc).isoformat(), "allowed_actions": "read only", "action": action, "outcome": "running"} def change(cur): _entry_for_run(rt, _mutable_entries(cur).get(entry_id), entry_id, uname, is_admin) for name in ("activity", "runs"): if not isinstance(cur.get(name, {}), dict): raise LoginStoreUnavailable("The Login store is unavailable.") uses = cur.setdefault("activity", {}).setdefault(entry_id, []) if not isinstance(uses, list): raise LoginStoreUnavailable("The Login store is unavailable.") runs = cur.setdefault("runs", {}) if run["id"] in runs: if runs[run["id"]] == run and run in uses: return cur raise LoginStoreUnavailable("The Login run could not be saved.") runs[run["id"]] = dict(run) uses.append(dict(run)) return cur try: login_budget.reserve(rt, run["id"], reserve_usd) saved = _update(rt, change) if saved.get("runs", {}).get(run["id"]) != run: raise LoginStoreUnavailable("The Login run could not be saved.") except Exception: login_budget.release(rt, run["id"]) raise return dict(run) RUN_OUTCOMES = frozenset({"completed", "blocked_origin", "breaker_open", "sign_in_failed", "backend_unavailable", "model_failed", "read_only", "run_failed", "budget_unavailable", "budget_exceeded", "needs_code", "login_unavailable", "needs_human"}) RUN_WAIT_STATES = frozenset({"running", "waiting_for_code", "waiting_for_approval"}) CAPTCHA_MESSAGE = "This site asked for a puzzle. Open the site yourself and finish it." def run_for_owner(rt, run_id, uname): """Return fixed run fields only to its initiating tenant user, including Administrators.""" bucket = read_bucket(rt, KEY) runs = bucket.get("runs", {}) row = runs.get(run_id) if isinstance(runs, dict) else None if not isinstance(row, dict) or row.get("id") != run_id or row.get("username") != uname or not uname: raise LoginAccessDenied("This Login run is unavailable.") _authorized(_mutable_entries(bucket).get(row.get("entry_id")), row.get("entry_id"), uname) status = row.get("status") if status not in RUN_OUTCOMES | RUN_WAIT_STATES: raise LoginStoreUnavailable("run_failed") result = {field: row.get(field, "") for field in ("id", "entry_id", "status", "started_at", "ended_at", "allowed_actions", "action")} if any(not isinstance(value, str) for value in result.values()): raise LoginStoreUnavailable("run_failed") spend = row.get("spentUsd") if spend is not None: from core import login_budget if type(spend) not in (int, float): raise LoginStoreUnavailable("run_failed") spend = float(login_budget._decimal(spend)) result["spentUsd"] = spend result["message"] = { "needs_human": CAPTCHA_MESSAGE, "waiting_for_code": "Enter the sign-in code sent to you in Logins, or reply with the code.", "waiting_for_approval": "Approve the sign-in on your device. This run will wait for you.", }.get(status, "") return result def set_wait_state(rt, run_id, uname, status): """Update a live owned run and its single use row without any human code.""" if status not in RUN_WAIT_STATES: raise LoginStoreUnavailable("run_failed") run_for_owner(rt, run_id, uname) def change(cur): run = cur.get("runs", {}).get(run_id) if (not isinstance(run, dict) or run.get("username") != uname or run.get("status") not in RUN_WAIT_STATES or run.get("ended_at")): raise LoginAccessDenied("This Login run is unavailable.") _entry_for_run(rt, _mutable_entries(cur).get(run["entry_id"]), run["entry_id"], uname) run.update(status=status, outcome=status) for use in cur.get("activity", {}).get(run["entry_id"], []): if use.get("id") == run_id: use.update(status=status, outcome=status) return cur _update(rt, change) def finish_run(rt, run_id, status, *, steps=0, spent_usd=0, cost_known=True): """Persist only fixed outcomes and measured counters in the run and activity.""" from core import login_budget if (status not in RUN_OUTCOMES or type(steps) is not int or not 0 <= steps <= 25 or type(cost_known) is not bool): raise LoginStoreUnavailable("run_failed") spent = float(login_budget._decimal(spent_usd)) ended = dt.datetime.now(dt.timezone.utc).isoformat() def change(cur): entries = _mutable_entries(cur) run = cur.get("runs", {}).get(run_id) if not isinstance(run, dict): raise LoginStoreUnavailable("run_failed") run.update(status=status, outcome=status, ended_at=ended, steps=steps, spentUsd=spent if cost_known else None, measuredUsd=spent, costKnown=cost_known) for use in cur.get("activity", {}).get(run["entry_id"], []): if use.get("id") == run_id: use.update(status=status, outcome=status) row = entries.get(run["entry_id"]) if status == "sign_in_failed" and row and row.get("status") == "active": row["status"] = "Needs sign-in" return cur saved = _update(rt, change) return dict(saved["runs"][run_id]) def activity(rt, entry_id, uname, is_admin=False): """Return this visible Login's use log without arbitrary worker text.""" bucket = read_bucket(rt, KEY) _authorized(_mutable_entries(bucket).get(entry_id), entry_id, uname, is_admin) logs = bucket.get("activity", {}) if not isinstance(logs, dict) or not isinstance(logs.get(entry_id, []), list): raise LoginStoreUnavailable("The Login activity is unavailable.") rows = [] for use in logs.get(entry_id, []): if not isinstance(use, dict) or use.get("entry_id") != entry_id: raise LoginStoreUnavailable("The Login activity is unavailable.") row = {field: use.get(field, "") for field in ACTIVITY_FIELDS} if any(not isinstance(value, str) for value in row.values()): raise LoginStoreUnavailable("The Login activity is unavailable.") rows.append(row) return rows