Some checks failed
The signups that marked an account as confirmed are deleted after a day, so an older account was left unconfirmed and brought nothing. The code e-mail sent before the account existed stays in the queue and now counts too. A password reset, whose link came by e-mail, also confirms the address and brings the orders. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
407 lines
21 KiB
Python
407 lines
21 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()
|
|
# 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)
|
|
# 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,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 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 = alerts(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, alerts to who asked for them, 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()
|