"""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, 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 customer.call('/account/register', {'customer': {'cnpj': CNPJ, 'zap': '16999990000', 'mail': address}, 'password': 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 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 ') 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'))] mail.send_pending(db.connect, ids=ids) assert len(sink.messages) == 2, 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 ' 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')} # The recovery's text is erased once sent; an alert keeps its own. assert sent['reset']['sent_at'] and sent['reset']['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) smtp_delivery(tag) order, quote = alerts(tag) print('PASS: password recovery by a one-time link, 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.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()