Files
dtf-system/tests/mail_test.py
Cauê Faleiros 95be624cca
All checks were successful
Build and deploy / Validate source (push) Successful in 17s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m22s
feat: a new account is confirmed with a code sent to its e-mail
Anyone could open an account on someone else's e-mail. Now "Criar conta"
e-mails a 6-digit code, and the account exists only once it is entered: one
big field that takes a paste or the phone's autofill and confirms by itself,
"Reenviar código" after 60 s, "Trocar e-mail", and the sign-in box hidden
meanwhile.

Security: 15 minutes per code, 5 wrong attempts, at most 5 codes, limits per
address and per source; the password is hashed at the first step and the code
stored only as a hash, its e-mail erased once sent. An address that already
has an account gets the same answer on screen and a "você já tem conta"
e-mail instead of a code, so the form does not reveal who is registered.
Without e-mail (MAIL_ADAPTER=off) the account is created at once, as before.

The browser test reads the code from a local-only endpoint that exists only
where e-mail stays in the log. Tested: mail_test (wrong, locked, resent,
expired codes, existing address, erasure after SMTP), the full suite and the
browser test in a CI-style stack, and the screens in Brave on desktop and phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:18:37 -03:00

311 lines
16 KiB
Python

"""E-mail: a customer's password recovery, and the team's alerts.
Run inside the API container: python -m tests.mail_test
The local stack keeps e-mail in the database (MAIL_ADAPTER=log); the SMTP
path is checked against a small SMTP server this test runs itself.
"""
import email
import hashlib
import os
import re
import secrets
import socketserver
import threading
from email import policy
from uuid import uuid4
from app import mail
from app.core import db
from tests.smoke_test import Client, approved_quote, item_spec, register, upload_bytes
CNPJ = '11222333000181'
PASSWORD = 'senha-antiga-12345'
NEW_PASSWORD = 'senha-nova-678901'
class Sink(socketserver.ThreadingTCPServer):
"""Just enough SMTP to receive what smtplib sends, kept in `messages`."""
allow_reuse_address = True
daemon_threads = True
def __init__(self):
self.messages = []
super().__init__(('127.0.0.1', 0), SinkHandler)
class SinkHandler(socketserver.StreamRequestHandler):
def reply(self, line):
self.wfile.write(line.encode() + b'\r\n')
def handle(self):
self.reply('220 sink')
rcpt = []
while line := self.rfile.readline():
verb = line.decode().strip().split(' ')[0].upper()
if verb == 'EHLO':
self.wfile.write(b'250-sink\r\n250 8BITMIME\r\n')
elif verb == 'RCPT':
rcpt.append(line.decode().strip())
self.reply('250 ok')
elif verb == 'DATA':
self.reply('354 go')
data = b''
while (chunk := self.rfile.readline()) != b'.\r\n':
data += chunk[1:] if chunk.startswith(b'..') else chunk
self.server.messages.append((rcpt, email.message_from_bytes(data, policy=policy.default)))
self.reply('250 queued')
elif verb == 'QUIT':
self.reply('221 bye')
return
else:
self.reply('250 ok')
def queued(c, to, kind):
return c.execute('SELECT * FROM dtf_local.mail_queue WHERE to_addr=%s AND kind=%s ORDER BY id',
(to, kind)).fetchall()
def recovery(tag):
address = f'cliente-{tag}@example.test'
customer = Client()
assert customer.call('/session')['password_recovery'] is True
register(customer, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': address}, PASSWORD)
# Signed in elsewhere with the old password: the reset signs that out.
elsewhere = Client()
elsewhere.call('/session')
elsewhere.call('/account/login', {'email': address, 'password': PASSWORD})
# The same answer whether or not the e-mail has an account.
stranger = Client()
stranger.call('/session')
unknown = stranger.call('/account/forgot', {'email': f'ninguem-{tag}@example.test'})
known = stranger.call('/account/forgot', {'email': address.upper()})
assert unknown == known and 'Se houver uma conta' in known['message']
with db.connect() as c:
assert not queued(c, f'ninguem-{tag}@example.test', 'reset')
[message] = queued(c, address, 'reset')
link = re.search(r'(\S+)/conta/redefinir#([A-Za-z0-9_-]+)', message['body'])
assert link and '1 hora' in message['body'], message['body']
token = link.group(2)
with db.connect() as c:
# Only the token's hash is kept.
assert not c.execute('SELECT 1 FROM dtf_local.password_resets WHERE token_hash=%s', (token,)).fetchone()
stranger.call('/account/reset', {'token': 'x' * 43, 'password': NEW_PASSWORD}, expected=400)
stranger.call('/account/reset', {'token': token, 'password': 'curta'}, expected=422)
assert stranger.call('/account/reset', {'token': token, 'password': NEW_PASSWORD})['customer']['mail'] == address
assert stranger.call('/account/me')['customer']['mail'] == address
# Works once; the old password and the old sessions are gone.
stranger.call('/account/reset', {'token': token, 'password': NEW_PASSWORD}, expected=400)
elsewhere.call('/account/me', expected=401)
Client().call('/account/login', {'email': address, 'password': PASSWORD}, expected=401)
Client().call('/account/login', {'email': address, 'password': NEW_PASSWORD})
# An expired link does nothing.
expired = secrets.token_urlsafe(32)
with db.connect() as c:
account = c.execute('SELECT id FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()['id']
c.execute('''INSERT INTO dtf_local.password_resets(token_hash,account_id,expires_at)
VALUES(%s,%s,now()-interval '1 minute')''', (hashlib.sha256(expired.encode()).hexdigest(), account))
stranger.call('/account/reset', {'token': expired, 'password': NEW_PASSWORD}, expected=400)
# A few links an hour per address, so nobody fills someone's inbox.
other = f'muitos-{tag}@example.test'
for _ in range(3):
stranger.call('/account/forgot', {'email': other})
stranger.call('/account/forgot', {'email': other}, expected=429)
return address
def code_of(c, address):
body = c.execute("SELECT body FROM dtf_local.mail_queue WHERE kind='code' AND to_addr=%s ORDER BY id DESC LIMIT 1",
(address,)).fetchone()['body']
return re.search(r'\b(\d{6})\b', body).group(1)
def signup(tag):
"""The account exists only once the code sent to the address is entered."""
address = f'novo-{tag}@example.test'
customer = {'cnpj': CNPJ, 'zap': '16999990000', 'mail': address}
browser = Client()
browser.call('/session')
started = browser.call('/account/register', {'customer': customer, 'password': PASSWORD})
assert started['email'] == address and started['minutes'] == 15 and started['verify'], started
assert browser.call('/account/me')['customer'] is None
with db.connect() as c:
assert not c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()
first = code_of(c, address)
# The password is stored hashed from the first step.
assert c.execute('SELECT password_hash FROM dtf_local.account_signups WHERE id=%s',
(started['verify'],)).fetchone()['password_hash'].startswith('scrypt-v2$')
wrong = '000000' if first != '000000' else '111111'
attempt = lambda code, expected: browser.call('/account/register/verify', {'signup': started['verify'], 'code': code},
expected=expected)
assert 'Restam 4' in attempt(wrong, 400)['detail']
attempt('12a456', 422)
# Another code only after a minute; the old one stops working.
browser.call('/account/register/resend', {'signup': started['verify']}, expected=429)
with db.connect() as c:
c.execute("UPDATE dtf_local.account_signups SET sent_at=now()-interval '2 minutes' WHERE id=%s", (started['verify'],))
browser.call('/account/register/resend', {'signup': started['verify']})
with db.connect() as c:
second = code_of(c, address)
if second != first:
attempt(first, 400)
# Five wrong codes lock it until a new code is asked for.
with db.connect() as c:
c.execute('UPDATE dtf_local.account_signups SET attempts=5 WHERE id=%s', (started['verify'],))
attempt(second, 429)
with db.connect() as c:
c.execute('UPDATE dtf_local.account_signups SET attempts=0 WHERE id=%s', (started['verify'],))
assert attempt(second, 200)['customer']['mail'] == address
assert browser.call('/account/me')['customer']['mail'] == address
attempt(second, 410)
Client().call('/account/login', {'email': address, 'password': PASSWORD})
# An address that already has an account: the same answer, a notice instead
# of a code, and no code opens anything.
again = Client()
again.call('/session')
other = again.call('/account/register', {'customer': customer, 'password': NEW_PASSWORD})
assert set(other) == set(started) and other['email'] == address
with db.connect() as c:
notices = c.execute("SELECT subject FROM dtf_local.mail_queue WHERE kind='account' AND to_addr=%s",
(address,)).fetchall()
assert len(notices) == 1 and 'já tem conta' in notices[0]['subject']
assert code_of(c, address) == second
again.call('/account/register/verify', {'signup': other['verify'], 'code': second}, expected=400)
Client().call('/account/login', {'email': address, 'password': NEW_PASSWORD}, expected=401)
# An expired code.
late = Client()
late.call('/session')
expiring = late.call('/account/register', {'customer': {**customer, 'mail': f'tarde-{tag}@example.test'},
'password': PASSWORD})
with db.connect() as c:
code = code_of(c, f'tarde-{tag}@example.test')
c.execute("UPDATE dtf_local.account_signups SET expires_at=now()-interval '1 second' WHERE id=%s",
(expiring['verify'],))
late.call('/account/register/verify', {'signup': expiring['verify'], 'code': code}, expected=410)
def smtp_delivery(tag):
"""The worker's SMTP path, against a server of our own."""
sink = Sink()
threading.Thread(target=sink.serve_forever, daemon=True).start()
saved = mail.ADAPTER, {k: os.environ.get(k) for k in ('SMTP_HOST', 'SMTP_PORT', 'SMTP_SECURITY', 'MAIL_FROM')}
to = f'smtp-{tag}@example.test'
try:
mail.ADAPTER = 'smtp'
os.environ.update(SMTP_HOST='127.0.0.1', SMTP_PORT=str(sink.server_address[1]), SMTP_SECURITY='none',
MAIL_FROM='DTF Dropstar <nao-responda@dropstar.test>')
with db.connect() as c:
# Not due yet, so the stack's own worker leaves them to this test.
ids = [c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,available_at)
VALUES(%s,%s,%s,%s,now()+interval '1 hour') RETURNING id''',
(kind, to, subject, body)).fetchone()['id']
for kind, subject, body in (('reset', 'Crie uma nova senha · DTF Dropstar', 'link secreto ção'),
('alert', 'Pedido pago', 'olá equipe'),
('code', '123456 é o seu código', 'código 123456'))]
mail.send_pending(db.connect, ids=ids)
assert len(sink.messages) == 3, sink.messages
rcpt, first = sink.messages[0]
assert to in rcpt[0] and first['Subject'] == 'Crie uma nova senha · DTF Dropstar'
assert first['From'] == 'DTF Dropstar <nao-responda@dropstar.test>'
assert first.get_content().strip() == 'link secreto ção'
with db.connect() as c:
sent = {r['kind']: r for r in queued(c, to, 'reset') + queued(c, to, 'alert') + queued(c, to, 'code')}
# A recovery link or a signup code is erased once sent; an alert keeps its text.
assert sent['reset']['sent_at'] and sent['reset']['body'] == ''
assert sent['code']['sent_at'] and sent['code']['body'] == ''
assert sent['alert']['sent_at'] and sent['alert']['body'] == 'olá equipe'
# A server that does not answer: retried later, with the error kept.
os.environ['SMTP_PORT'] = '1'
with db.connect() as c:
failing = c.execute('''INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body,available_at)
VALUES('alert',%s,'x','y',now()+interval '1 hour') RETURNING id''', (to,)).fetchone()['id']
mail.send_pending(db.connect, ids=[failing])
with db.connect() as c:
row = c.execute('SELECT * FROM dtf_local.mail_queue WHERE id=%s', (failing,)).fetchone()
assert row['attempts'] == 1 and row['last_error'] and not row['sent_at'] and not row['failed_at']
assert mail.status(c)['error']['to'] == to
c.execute('DELETE FROM dtf_local.mail_queue WHERE id=%s', (failing,))
finally:
mail.ADAPTER = saved[0]
for key, value in saved[1].items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
sink.shutdown()
def alerts(tag):
"""Who gets the team's alerts, and that a paid order sends one."""
su = Client()
su.call('/session')
wants, quiet, away = (f'{n}-{tag}@example.test' for n in ('alertas', 'quieto', 'fora'))
for address, on, active in ((wants, True, True), (quiet, False, True), (away, True, False)):
su.call('/operator/users', {'name': address, 'email': address, 'role': 'gestao', 'password': PASSWORD,
'alerts': on, 'active': active}, operator=True)
users = {u['email']: u for u in su.call('/operator/users', operator=True)['users']}
assert users[wants]['alerts'] is True and users[quiet]['alerts'] is False
board = su.call('/operator/board', operator=True)
assert board['providers']['mail']['adapter'] == 'log' and board['providers']['mail']['alerts'] >= 1
customer = Client()
customer.call('/session')
uid = upload_bytes(customer, b'MAIL ALERT ARTWORK')
item = item_spec('file', '1.2', 0, uid)
quote = customer.call('/quotes', {'request_key': str(uuid4()), 'items': [item],
'customer': {'cnpj': CNPJ, 'zap': '16999990000', 'mail': f'alerta-{tag}@example.test'},
'freight': {'service': 'pickup'}})
approved_quote(customer, quote, [item])
order = customer.call('/orders/dev-paid', {'quote_id': quote['id']})
with db.connect() as c:
[alert] = [r for r in queued(c, wants, 'alert') if f"#{order['number']}" in r['subject']]
assert 'pago' in alert['subject'] and '11.222.333/0001-81' in alert['body'] and '1,2 m' in alert['body']
assert 'Abrir no Kanban: http' in alert['body']
assert not queued(c, quiet, 'alert') and not queued(c, away, 'alert')
# The test message goes to whoever asked for it.
sent = su.call('/operator/mail/test', {}, operator=True)
with db.connect() as c:
assert queued(c, sent['to'], 'test')
return order['id'], quote['id']
def run():
tag = secrets.token_hex(3)
order = quote = None
with db.connect() as c:
# The recovery's per-source limit would make a second run within 15 minutes fail.
c.execute('DELETE FROM dtf_local.login_attempts')
try:
recovery(tag)
signup(tag)
smtp_delivery(tag)
order, quote = alerts(tag)
print('PASS: password recovery by a one-time link, signup confirmed by an e-mailed code, '
'SMTP delivery and retry, alerts to who asked for them')
finally:
with db.connect() as c:
if order:
for table in ('movements', 'print_files'):
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (order,))
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{order}:%',))
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
if quote:
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (quote,))
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
c.execute("DELETE FROM dtf_local.mail_queue WHERE to_addr LIKE %s OR kind='test'", (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.account_signups WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.accounts WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
c.execute('DELETE FROM dtf_local.login_attempts')
if __name__ == '__main__':
run()