"""Passwordless-user onboarding — one-time set-password links sent by webhook. An admin creates a user with just a name/email/role (see ``user_service.create_user_without_password``). To let that user in, the admin clicks "Send Email": this service issues a one-time token and POSTs a payload carrying it to an admin-configured webhook URL (intended for a Power Automate flow that actually sends the email — the exact webhook contract is still being finalized, hence the configurable URL rather than a hardcoded integration). The same mechanism, and the same button, is reused for password resets on existing users. """ from __future__ import annotations import logging import secrets from datetime import datetime, timedelta import requests from sqlalchemy.orm import Session from app.config import settings from app.domain.errors import BusinessRuleViolation, EntityNotFoundError from app.models.password_setup_token import PasswordSetupToken from app.models.user import User logger = logging.getLogger(__name__) _WEBHOOK_URL_CONFIG_KEY = "password_setup.webhook_url" _WEBHOOK_API_KEY_CONFIG_KEY = "password_setup.webhook_api_key" _TOKEN_TTL = timedelta(hours=24) # Standard footer appended to every Power-Automate-delivered notification # email, matching the platform's established template. _EMAIL_SIGNATURE = ( "\n\nRegards,\n" "AEGIS Security Platform\n" "Purple Team Engineering\n" "Owned and operated by Enterprise Corp.\n\n" "Assume breach. Validate controls. Improve continuously.\n\n" "This is an automated notification. Please do not reply." ) def _build_email_body(full_name: str | None, message: str) -> str: """Wrap *message* in the standard greeting + signature template.""" greeting = full_name or "there" return f"HI {greeting}\n\n{message}{_EMAIL_SIGNATURE}" def _read_system_config(db: Session, key: str) -> str | None: from app.models.system_config import SystemConfig # avoid circular at import time row = db.query(SystemConfig).filter(SystemConfig.key == key).first() return row.value if row else None def _write_system_config(db: Session, key: str, value: str) -> None: from app.models.system_config import SystemConfig row = db.query(SystemConfig).filter(SystemConfig.key == key).first() if row: row.value = value else: db.add(SystemConfig(key=key, value=value)) def get_password_webhook_url(db: Session) -> str | None: """Return the configured Power-Automate-style webhook URL, or None.""" return _read_system_config(db, _WEBHOOK_URL_CONFIG_KEY) or None def set_password_webhook_url(db: Session, url: str) -> None: """Persist the webhook URL. Does not commit; caller commits.""" _write_system_config(db, _WEBHOOK_URL_CONFIG_KEY, url) def get_password_webhook_api_key(db: Session) -> str | None: """Return the configured webhook API key, or None.""" return _read_system_config(db, _WEBHOOK_API_KEY_CONFIG_KEY) or None def set_password_webhook_api_key(db: Session, api_key: str) -> None: """Persist the webhook API key. Does not commit; caller commits.""" _write_system_config(db, _WEBHOOK_API_KEY_CONFIG_KEY, api_key) def create_setup_token(db: Session, user: User) -> PasswordSetupToken: """Issue a fresh one-time token for *user*, invalidating any unused ones. Does not commit; caller commits. """ db.query(PasswordSetupToken).filter( PasswordSetupToken.user_id == user.id, PasswordSetupToken.used_at.is_(None), ).delete() token = PasswordSetupToken( user_id=user.id, token=secrets.token_urlsafe(32), expires_at=datetime.utcnow() + _TOKEN_TTL, ) db.add(token) db.flush() return token def send_password_setup_email(db: Session, user: User) -> None: """Issue a token and POST it to the configured webhook. Raises BusinessRuleViolation if no webhook URL is configured yet. Does not commit; caller commits (the token must be persisted even if the webhook call itself fails, so a fresh "Send Email" retry works). """ webhook_url = get_password_webhook_url(db) if not webhook_url: raise BusinessRuleViolation( "No password-setup webhook is configured yet — set one in Settings first." ) token = create_setup_token(db, user) set_password_url = f"{settings.PLATFORM_URL}/set-password?token={token.token}" is_reset = not user.must_change_password subject = "Reset Your Password" if is_reset else "Set Your Password" message = ( f'Click the link below to {"reset" if is_reset else "set"} your Aegis password:\n\n' f"{set_password_url}\n\n" "This link expires in 24 hours and can only be used once." ) api_key = get_password_webhook_api_key(db) headers = {"x-api-key": api_key} if api_key else {} try: requests.post( webhook_url, json={ "to": user.email, "subject": subject, "body": _build_email_body(user.full_name, message), }, headers=headers, timeout=10, ) except requests.RequestException: # Best-effort: the token still exists, so the admin can retry # "Send Email" once the webhook endpoint is reachable again. logger.warning("Password-setup webhook call failed for user %s", user.id, exc_info=True) def _get_valid_token_or_raise(db: Session, token: str) -> PasswordSetupToken: row = db.query(PasswordSetupToken).filter(PasswordSetupToken.token == token).first() if row is None: raise EntityNotFoundError("Password setup token", token) if row.used_at is not None: raise BusinessRuleViolation("This link has already been used") if row.expires_at < datetime.utcnow(): raise BusinessRuleViolation("This link has expired — ask an admin to send a new one") return row def validate_token(db: Session, token: str) -> User: """Return the token's owning user if the token is valid, else raise.""" row = _get_valid_token_or_raise(db, token) return row.user def consume_token_and_set_password(db: Session, token: str, new_password: str) -> User: """Set *new_password* for the token's user and mark the token used. Does not commit; caller commits. """ from app.auth import hash_password row = _get_valid_token_or_raise(db, token) user = row.user user.hashed_password = hash_password(new_password) user.must_change_password = False row.used_at = datetime.utcnow() db.flush() return user