Files
dtf-system/tests/mail_test.py
Cauê Faleiros c8857a5bf5
All checks were successful
Build and deploy / Validate source (push) Successful in 47s
Build and deploy / Integration suite on a real stack (push) Successful in 3m38s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m20s
feat: the team no longer gets alert e-mails; the Kanban user form drops the option
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 09:37:41 -03:00

409 lines
22 KiB
Python

"""E-mail: a customer's password recovery, signup codes and order confirmation.
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()
# An account never confirmed: the reset link, sent to the address, confirms it.
c.execute('UPDATE dtf_local.accounts SET email_verified=false WHERE email=%s', (address,))
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
with db.connect() as c:
assert c.execute('SELECT email_verified FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()['email_verified']
# 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)
html = queued(c, address, 'code')[-1]['html']
assert '&nbsp;'.join(first) in html and 'Confirme seu e-mail' in html, html[:200]
# 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 email_change(tag):
"""A new e-mail is the account's only once the code sent to it is entered,
and the old address is told."""
old, new, taken = (f'{n}-{tag}@example.test' for n in ('antigo', 'trocado', 'ocupado'))
owner = Client()
owner.call('/session')
register(owner, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': old}, PASSWORD)
register(Client(), {'cnpj': CNPJ, 'zap': '16999990000', 'mail': taken}, PASSWORD)
owner.call('/account/email', {'email': new, 'password': 'senha-errada-123'}, expected=401)
owner.call('/account/email', {'email': old, 'password': PASSWORD}, expected=422)
owner.call('/account/email', {'email': taken, 'password': PASSWORD}, expected=409)
started = owner.call('/account/email', {'email': new.upper(), 'password': PASSWORD})
assert started['email'] == new and started['verify'], started
assert owner.call('/account/me')['customer']['mail'] == old
with db.connect() as c:
code = code_of(c, new)
wrong = '000000' if code != '000000' else '111111'
assert 'Restam 4' in owner.call('/account/email/verify', {'change': started['verify'], 'code': wrong}, expected=400)['detail']
# Another signed-in customer cannot complete someone else's change.
stranger = Client()
stranger.call('/session')
register(stranger, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': f'outro-{tag}@example.test'}, PASSWORD)
stranger.call('/account/email/verify', {'change': started['verify'], 'code': code}, expected=410)
owner.call('/account/email/resend', {'change': started['verify']}, expected=429)
assert owner.call('/account/email/verify', {'change': started['verify'], 'code': code})['customer']['mail'] == new
assert owner.call('/account/me')['customer']['mail'] == new
owner.call('/account/email/verify', {'change': started['verify'], 'code': code}, expected=410)
Client().call('/account/login', {'email': new, 'password': PASSWORD})
Client().call('/account/login', {'email': old, 'password': PASSWORD}, expected=401)
with db.connect() as c:
[notice] = queued(c, old, 'notice')
assert new in notice['body'] and 'Se não foi você' in notice['body']
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,html,available_at)
VALUES(%s,%s,%s,%s,%s,now()+interval '1 hour') RETURNING id''',
(kind, to, subject, body, html)).fetchone()['id']
for kind, subject, body, html in (
('reset', 'Crie uma nova senha · DTF Dropstar', 'link secreto ção', None),
('test', 'Teste de e-mail', 'olá equipe', None),
('code', '123456 é o seu código', 'código 123456', '<p>código 123456</p>'))]
mail.send_pending(db.connect, ids=ids)
assert len(sink.messages) == 3, sink.messages
# A customer message goes as plain text and HTML, the client picks.
coded = sink.messages[2][1]
assert coded.get_content_type() == 'multipart/alternative', coded.get_content_type()
assert coded.get_body(('plain',)).get_content().strip() == 'código 123456'
assert '<p>código 123456</p>' in coded.get_body(('html',)).get_content()
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, 'test') + queued(c, to, 'code')}
# A recovery link or a signup code is erased once sent; other messages keep their text.
assert sent['reset']['sent_at'] and sent['reset']['body'] == ''
assert sent['code']['sent_at'] and sent['code']['body'] == '' and sent['code']['html'] is None
assert sent['test']['sent_at'] and sent['test']['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('test',%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 order_confirmation(tag):
"""A paid order sends the customer the confirmation, and the team nothing."""
su = Client()
su.call('/session')
customer = Client()
customer.call('/session')
uid = upload_bytes(customer, b'MAIL ORDER 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'pedido-{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:
# The customer gets the confirmation, with the order in the account.
[confirmed] = queued(c, f'pedido-{tag}@example.test', 'order')
assert confirmed['subject'] == f"Recebemos seu pedido #{order['number']} · DTF Dropstar"
assert f"/conta/pedidos?order={order['id']}" in confirmed['body'] and 'Retirada em Franca-SP' in confirmed['body']
assert f"Recebemos seu pedido #{order['number']}" in confirmed['html'] and 'Ver meu pedido' in confirmed['html']
assert not c.execute("SELECT 1 FROM dtf_local.mail_queue WHERE kind='alert' AND subject LIKE %s",
(f"%#{order['number']} %",)).fetchone()
# 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 guest_order(document, address, made):
"""An order bought without an account, in a browser of its own."""
browser = Client()
browser.call('/session')
uid = upload_bytes(browser, b'GUEST ORDER ARTWORK')
item = item_spec('file', '1.2', 0, uid)
quote = browser.call('/quotes', {'request_key': str(uuid4()), 'items': [item],
'customer': {'cnpj': document, 'zap': '16999990000', 'mail': address},
'freight': {'service': 'pickup'}})
approved_quote(browser, quote, [item])
order = browser.call('/orders/dev-paid', {'quote_id': quote['id']})
made.append((order['id'], quote['id']))
return order['id'], uid
def claimed_orders(tag, made):
"""A confirmed account brings the orders bought without it with its CPF or
CNPJ and e-mail, from any browser; a CPF alone or an unconfirmed e-mail
brings nothing."""
cpf, address = '52998224725', f'comprador-{tag}@example.test'
mine, art = guest_order('529.982.247-25', address.upper(), made)
other_mail, _ = guest_order(cpf, f'outro-{tag}@example.test', made)
other_document, _ = guest_order(CNPJ, address, made)
# Someone who knows the CPF, with an e-mail of their own: nothing.
stranger = Client()
stranger.call('/session')
register(stranger, {'cnpj': cpf, 'zap': '16999990000', 'mail': f'curioso-{tag}@example.test'}, PASSWORD)
assert stranger.call('/customer/orders?page=1&size=10')['items'] == []
# The customer, on another computer: the order comes with its cart and files.
customer = Client()
customer.call('/session')
register(customer, {'cnpj': cpf, 'zap': '16999990000', 'mail': address}, PASSWORD)
listed = lambda client: {e['id'] for e in client.call('/customer/orders?page=1&size=10')['items'] if e['kind'] == 'order'}
assert listed(customer) == {mine}, listed(customer)
customer.call('/customer/orders/' + mine)
with db.connect() as c:
account = c.execute('SELECT id,email_verified FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()
assert account['email_verified']
assert c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (art,)).fetchone()['owner'] == account['id']
owners = {r['id']: r['owner'] for r in c.execute('SELECT id,owner FROM dtf_local.orders WHERE id=ANY(%s)',
([other_mail, other_document],)).fetchall()}
assert account['id'] not in owners.values()
# Bought later without signing in, elsewhere: it comes at the next sign-in.
later, _ = guest_order(cpf, address, made)
Client().call('/account/login', {'email': address, 'password': PASSWORD})
assert listed(customer) == {mine, later}
# An account whose e-mail was never confirmed brings nothing.
with db.connect() as c:
c.execute('UPDATE dtf_local.accounts SET email_verified=false WHERE id=%s', (account['id'],))
unconfirmed, _ = guest_order(cpf, address, made)
Client().call('/account/login', {'email': address, 'password': PASSWORD})
assert unconfirmed not in listed(customer)
def run():
tag = secrets.token_hex(3)
order = quote = None
made = []
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)
email_change(tag)
smtp_delivery(tag)
order, quote = order_confirmation(tag)
made.append((order, quote))
claimed_orders(tag, made)
print('PASS: password recovery by a one-time link, signup and e-mail changes confirmed by an e-mailed code, '
'SMTP delivery and retry, order confirmation and no team alerts, guest orders brought by CPF/CNPJ and e-mail')
finally:
with db.connect() as c:
for order, quote in made:
for table in ('movements', 'print_files', 'order_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,))
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.email_changes WHERE new_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()