Files
FabledSteward/tests/integration/test_invites.py
T
bvandeusenandClaude Opus 5.5 9a3e7ddba2
CI / lint (push) Successful in 2s
CI / integration (push) Failing after 1m11s
CI / unit (push) Successful in 1m26s
CI / publish (push) Skipped
feat(email): the report, invites, resets and test sends go through the outbox; only it talks SMTP (#5508)
#5508 "Every other email through the outbox: weekly report, invites,
password resets, and the test buttons" (milestone 501).

- outbox.send_each queues one email per reader (claimed, so the sender
  doesn't take it too) and tries them at once, for a page that answers
  with what happened; outbox.said words the result. attempt takes a cfg
  for a test of the form's unsaved settings and returns the settled rows.
- Weekly report (scheduled and Send now) and invites: queued, tried at
  once; one the server couldn't take yet is retried for an hour. An invite
  that didn't go shows its link with the reason, as before.
- Password reset: queued in the reset link's own transaction; the sender
  delivers it on its next tick.
- Settings -> Notifications test email and a rule's Send test: queued and
  recorded with retry=False, tried once (System 156 ruling).
- Removed mail.send, notifications._send_email and _smtp_send_sync;
  dispatch_notifications is webhook only. A guard asserts only the outbox
  (and smtp_open itself) opens an SMTP connection, with a self-test.

Also fixes run 8941 (#5507's integration test): its Also-send-to
addresses were "@test", which is_real_address rightly drops; they are
example.com now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:05:01 -04:00

213 lines
10 KiB
Python

"""Integration: invite a user by email (milestone 496), from the Users page
to the invitee's own account. The routes run for real against Postgres;
only mail delivery is replaced."""
from __future__ import annotations
import asyncio
import json
import os
import re
import time
import uuid
import pytest
pytestmark = pytest.mark.integration
CSRF = {"X-CSRF-Token": "test-token"}
_KEY = re.compile(r"/invite/([A-Za-z0-9_-]{20,})")
@pytest.fixture
def app():
if not os.environ.get("STEWARD_DATABASE_URL"):
pytest.skip("needs Postgres")
from steward.app import create_app
from steward.auth.throttle import login_throttle
login_throttle._failures.clear() # bad keys below count against this address
app = create_app(testing=False)
yield app
login_throttle._failures.clear()
async def _admin(app, role="admin"):
from steward.models.users import User, UserRole
uid = str(uuid.uuid4())
name = f"inv-{uid[:8]}"
async with app.db_sessionmaker() as s:
async with s.begin():
s.add(User(id=uid, username=name, email=f"{uid[:8]}-{name}@example.com", password_hash="x",
role=UserRole(role), is_active=True, time_zone="America/New_York"))
client = app.test_client()
async with client.session_transaction() as sess:
sess.update(user_id=uid, user_role=role, username=name, _csrf="test-token", login_at=time.time())
return client, uid, name
async def _stranger(app):
"""A browser with no session, holding only the link."""
client = app.test_client()
await client.get("/login") # a session with a CSRF token, as a real visit has
async with client.session_transaction() as sess:
sess["_csrf"] = "test-token"
return client
async def _audits(app, uid):
from sqlalchemy import select
from steward.models.audit import AuditEvent
async with app.db_sessionmaker() as s:
rows = (await s.execute(select(AuditEvent).where(AuditEvent.user_id == uid)
.order_by(AuditEvent.timestamp))).scalars().all()
return [(r.action, json.loads(r.detail_json or "{}")) for r in rows]
def _mail(app, monkeypatch, answer=None):
from tests.integration._mail import capture
return capture(app, monkeypatch, answer)
def test_an_invite_is_emailed_and_the_invitee_makes_their_own_account_once(app, monkeypatch):
sent = _mail(app, monkeypatch)
async def _go():
from steward.models.users import User
admin, aid, aname = await _admin(app)
page = await (await admin.get("/settings/users/")).get_data(as_text=True)
assert 'href="/settings/users/invite"' in page # findable from the list
to = f"new-{aid[:8]}@example.com"
resp = await admin.post("/settings/users/invite", headers=CSRF,
form={"email": to, "role": "operator", "days": "1"})
assert resp.status_code == 302 and resp.headers["Location"].endswith("?done=invited")
assert len(sent) == 1 and sent[0]["To"] == to
text = sent[0].get_body(("plain",)).get_content()
assert f"{aname} invited you to Steward" in text and "EDT" in text and "UTC" in text
key = _KEY.search(text).group(1)
page = await (await admin.get(resp.headers["Location"])).get_data(as_text=True)
assert "Invites not yet used" in page and to in page and "Invite sent." in page
assert [a for a, _ in await _audits(app, aid)] == ["user.invited"]
guest = await _stranger(app)
page = await (await guest.get(f"/invite/{key}")).get_data(as_text=True)
assert "Join Steward" in page and f"{aname} invited you as an operator" in page
assert f'value="{to}"' in page # prefilled, and theirs to change
mine = f"me-{aid[:8]}@example.com"
form = {"username": f"joined-{aid[:8]}", "email": mine, "password": "longenough", "confirm": "nope"}
resp = await guest.post(f"/invite/{key}", headers=CSRF, form=form)
assert resp.status_code == 400 and "passwords don" in await resp.get_data(as_text=True)
resp = await guest.post(f"/invite/{key}", headers=CSRF, form=form | {"username": aname, "confirm": "longenough"})
assert resp.status_code == 400 and f"username {aname} is taken" in await resp.get_data(as_text=True)
resp = await guest.post(f"/invite/{key}", headers=CSRF, form=form | {"confirm": "longenough"})
assert resp.status_code == 302
async with guest.session_transaction() as sess:
new_id = sess["user_id"]
async with app.db_sessionmaker() as s:
user = await s.get(User, new_id)
assert (user.username, user.email, user.role.value, user.auth_source) == (
f"joined-{aid[:8]}", mine, "operator", "local")
assert [a for a, _ in await _audits(app, new_id)] == ["user.joined"]
# The key made one account; it opens nothing now.
again = await _stranger(app)
resp = await again.get(f"/invite/{key}")
assert resp.status_code == 404 and "expired, been used or been withdrawn" in await resp.get_data(as_text=True)
resp = await again.post(f"/invite/{key}", headers=CSRF,
form=form | {"username": "second", "email": "second@example.com", "confirm": "longenough"})
assert resp.status_code == 404
page = await (await admin.get("/settings/users/")).get_data(as_text=True)
assert to not in page # a used invite leaves the list
asyncio.run(_go())
def test_without_mail_the_admin_gets_the_link_once(app):
async def _go():
app.config["SMTP"] = {}
admin, aid, _ = await _admin(app)
page = await (await admin.get("/settings/users/invite")).get_data(as_text=True)
assert "No mail server is set" in page and "Make invite link" in page
resp = await admin.post("/settings/users/invite", headers=CSRF,
form={"email": f"nomail-{aid[:8]}@example.com", "role": "viewer", "days": "7"})
page = await resp.get_data(as_text=True)
assert resp.status_code == 200 and "It can't be shown again" in page
key = _KEY.search(page).group(1)
assert (await (await _stranger(app)).get(f"/invite/{key}")).status_code == 200
asyncio.run(_go())
def test_resend_replaces_the_link_and_withdraw_ends_it(app, monkeypatch):
sent = _mail(app, monkeypatch)
async def _go():
from sqlalchemy import select
from steward.models.invites import UserInvite
admin, aid, _ = await _admin(app)
to = f"again-{aid[:8]}@example.com"
await admin.post("/settings/users/invite", headers=CSRF, form={"email": to, "role": "viewer", "days": "7"})
first = _KEY.search(sent[-1].get_body(("plain",)).get_content()).group(1)
async with app.db_sessionmaker() as s:
invite_id = (await s.execute(select(UserInvite.id).where(UserInvite.email == to))).scalar_one()
resp = await admin.post(f"/settings/users/invites/{invite_id}/resend", headers=CSRF)
assert resp.status_code == 302 and len(sent) == 2
second = _KEY.search(sent[-1].get_body(("plain",)).get_content()).group(1)
guest = await _stranger(app)
assert (await guest.get(f"/invite/{first}")).status_code == 404
assert (await guest.get(f"/invite/{second}")).status_code == 200
resp = await admin.post(f"/settings/users/invites/{invite_id}/revoke", headers=CSRF)
assert resp.status_code == 302
assert (await guest.get(f"/invite/{second}")).status_code == 404
assert (await admin.post(f"/settings/users/invites/{invite_id}/resend", headers=CSRF)).status_code == 404
assert [a for a, _ in await _audits(app, aid)] == ["user.invited", "user.invite_resent", "user.invite_revoked"]
asyncio.run(_go())
def test_an_address_with_an_account_is_not_invited_and_only_an_admin_invites(app, monkeypatch):
_mail(app, monkeypatch)
async def _go():
admin, aid, _ = await _admin(app)
resp = await admin.post("/settings/users/invite", headers=CSRF,
form={"email": f"{aid[:8]}-inv-{aid[:8]}@example.com", "role": "viewer", "days": "7"})
assert resp.status_code == 400 and "already has an account" in await resp.get_data(as_text=True)
resp = await admin.post("/settings/users/invite", headers=CSRF,
form={"email": "x@example.com", "role": "viewer", "days": "3"})
assert resp.status_code == 400
operator, _, _ = await _admin(app, role="operator")
assert (await operator.get("/settings/users/invite")).status_code == 403
assert (await operator.post("/settings/users/invite", headers=CSRF,
form={"email": "y@example.com"})).status_code == 403
asyncio.run(_go())
def test_an_invite_the_server_refuses_or_defers_shows_the_link_and_why(app, monkeypatch):
# Sent through the queue (#5508) and tried at once: a refusal says so; a
# "try later" says Steward keeps trying; either way the link is shown.
import smtplib
answers = {}
_mail(app, monkeypatch, lambda m: answers.get(m["To"]))
async def _go():
admin, aid, _ = await _admin(app)
refused, later = f"no-{aid[:8]}@example.com", f"later-{aid[:8]}@example.com"
answers[refused] = smtplib.SMTPRecipientsRefused({refused: (550, b"no such user")})
answers[later] = smtplib.SMTPDataError(451, b"greylisted")
resp = await admin.post("/settings/users/invite", headers=CSRF,
form={"email": refused, "role": "viewer", "days": "7"})
page = await resp.get_data(as_text=True)
assert f"Sending to {refused} failed (550 no such user)." in page and "/invite/" in page
resp = await admin.post("/settings/users/invite", headers=CSRF,
form={"email": later, "role": "viewer", "days": "7"})
page = await resp.get_data(as_text=True)
assert "451 greylisted" in page and "keep trying for up to an hour" in page
asyncio.run(_go())