Files
dtf-system/app/core/auth.py
Cauê Faleiros 445d686f43 fix: a redeploy's short database outage no longer takes the API down
Sentry DTF-API-2..7 (redeploy of 5a7fc0f, 13/11): the name db did not
resolve for about 12 s; the new API exited at startup and the worker and
audit() logged the error every second. The API now waits up to 90 s with
a backoff, the worker reports an outage once and backs off to 15 s, the
audit persistence error is logged at most once a minute, and api, site
and kanban update start-first so the old container serves meanwhile.

Built by Bobina.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 15:25:29 -03:00

275 lines
14 KiB
Python

"""Local customer passwords and revocable database sessions. No email service."""
import hashlib
import os
import secrets
import logging
import json
import time
from uuid import UUID, uuid4
from fastapi import HTTPException, Request
from ..core.db import connect
COOKIE_SECURE = os.environ.get('COOKIE_SECURE', 'false').lower() == 'true'
def client_ip(request: Request):
"""The requester's address, for rate-limit buckets and security events.
The API is only reachable through the web gateway, which replaces
X-Forwarded-For with the peer address it observed, so the header carries
exactly one value the client could not choose. Without this every request
looks like the gateway, which collapses per-source limits into one global
bucket and strips the address from the audit trail.
"""
forwarded = request.headers.get('x-forwarded-for', '').split(',')[0].strip()
if forwarded:
return forwarded[:64]
return request.client.host if request.client else 'unknown'
def password_hash(password, salt=None):
salt = salt or secrets.token_hex(16)
digest = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=16384, r=8, p=5).hex()
return f'scrypt-v2${salt}${digest}'
def password_matches(password, stored):
try:
version, salt, digest = stored.split('$')
if version not in ('scrypt', 'scrypt-v2'): return False
actual = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=16384, r=8,
p=1 if version == 'scrypt' else 5).hex()
return secrets.compare_digest(actual, digest)
except (ValueError, TypeError):
return False
DUMMY_PASSWORD_HASH = password_hash('invalid-account-password', '00'*16)
def session_row(request):
try:
sid = UUID(request.cookies.get('dtf_session', ''))
except ValueError:
raise HTTPException(401, 'Sessão não iniciada. Recarregue a página.')
with connect() as c:
row = c.execute('SELECT * FROM dtf_local.sessions WHERE id=%s AND expires_at>now()', (sid,)).fetchone()
if not row:
raise HTTPException(401, 'Session expired; sign in or start a new session')
return row
def owner(request: Request):
return session_row(request)['owner']
def new_session(c, response, identity=None):
sid = uuid4()
identity = identity or uuid4()
c.execute('INSERT INTO dtf_local.sessions(id,owner) VALUES(%s,%s)', (sid,identity))
response.set_cookie('dtf_session', str(sid), httponly=True, secure=COOKIE_SECURE,
samesite='strict', max_age=86400*7)
return identity
def transfer_guest(c, previous, identity):
# Successful authentication can claim only the current guest browser's records.
if c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
return
for table in ('uploads','quotes','orders'):
c.execute(f'UPDATE dtf_local.{table} SET owner=%s WHERE owner=%s', (identity,previous['owner']))
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (previous['owner'],))
_persistence_error_at = None
def audit(event, c=None, **fields):
"""Record a security event. `c` is the caller's open connection, when there
is one, so the event commits with that transaction instead of opening a
second connection."""
global _persistence_error_at
# Only explicit metadata: never cookies, passwords, signed URLs or request bodies.
logging.getLogger('dtf.security').warning(json.dumps({'event':event, **fields}, sort_keys=True))
try:
from psycopg.types.json import Jsonb
if c is not None:
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
else:
with connect() as c:
c.execute('INSERT INTO dtf_local.security_events(event,details) VALUES(%s,%s)',(event,Jsonb(fields)))
except Exception:
# Logging must still work during a DB outage without recursively auditing
# itself; the error is reported once per minute, not on every event.
now = time.monotonic()
if _persistence_error_at is None or now-_persistence_error_at >= 60:
_persistence_error_at = now
logging.getLogger('dtf.security').error('Security event persistence unavailable')
def rate_limit(scope, identity, limit, seconds=900):
key = hashlib.sha256((scope+'|'+identity).encode()).hexdigest()
with connect() as c:
row = c.execute("""INSERT INTO dtf_local.login_attempts(key,attempts) VALUES(%s,1)
ON CONFLICT(key) DO UPDATE SET
attempts=CASE WHEN dtf_local.login_attempts.started_at < now()-%s*interval '1 second' THEN 1 ELSE LEAST(dtf_local.login_attempts.attempts+1,1000000) END,
started_at=CASE WHEN dtf_local.login_attempts.started_at < now()-%s*interval '1 second' THEN now() ELSE dtf_local.login_attempts.started_at END
RETURNING attempts""", (key,seconds,seconds)).fetchone()
if row['attempts'] > limit:
audit('rate_limit', scope=scope)
raise HTTPException(429, 'Muitas tentativas. Tente de novo mais tarde.', headers={'Retry-After':str(seconds)})
ACCOUNT_FAILURES = 10
def throttle(email, request):
# Independent account and source buckets prevent bypass by rotating emails.
# Every attempt counts against the source. Only failures count against the
# account: guessing a password is what the account bucket stops, and
# counting successful sign-ins too let ordinary use lock an operator out.
rate_limit('auth-source', client_ip(request), 60)
key = hashlib.sha256(('auth-account|'+email).encode()).hexdigest()
with connect() as c:
row = c.execute("""SELECT attempts FROM dtf_local.login_attempts
WHERE key=%s AND started_at >= now()-interval '900 seconds'""", (key,)).fetchone()
if row and row['attempts'] >= ACCOUNT_FAILURES:
audit('rate_limit', scope='auth-account')
raise HTTPException(429, 'Muitas tentativas. Tente de novo mais tarde.', headers={'Retry-After': '900'})
def login_failed(email):
"""Count a failed sign-in (or registration attempt) against the account."""
rate_limit('auth-account', email, 1_000_000)
# What each Kanban profile may do. "view" is reading; "produce" handles the
# artwork: approving the final files, the contraction, "Tratar a arte", the
# contact wait. "The designer approves every file" (Dropstar's rule D-16), so
# the operator does not: they pull and print. "print" is the print room's side
# of it (the machine, the
# queue's order, its files and folder); "manage" covers quotes, cancellations
# and payments; "users" is the Usuários page; "integrations" is everything in
# Integrações but the print room's folder (connecting Tiny, the checks, the
# backup, the Tiny log): the others see there only what is on and off.
# The designer approves and refuses artwork and asks for corrections, on every
# order whatever its machine. Which cards each profile moves is MOVES.
ROLES = ('superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor', 'vendedor', 'financeiro', 'expedicao')
CAPABILITIES = {
'view': set(ROLES),
'produce': {'superadmin', 'admin', 'gestao', 'designer'},
'print': {'superadmin', 'admin', 'gestao', 'operador'},
'manage': {'superadmin', 'admin', 'gestao'},
# Registering an order paid outside the system, from its Site quote (D-35).
# Not the seller: Vendedor only views the board (D-30).
'enter': {'superadmin', 'admin', 'gestao'},
# Rework (D-02): coordination opens it with its cause, an Administrador
# (Thales or Alexandre) authorizes it.
'rework': {'superadmin', 'gestao'},
'authorize': {'superadmin', 'admin'},
'users': {'superadmin', 'admin'},
'integrations': {'superadmin'},
# Financeiro (Dropstar, 2026-10-30): sees the board, Pagamentos, Números and
# Cotações, and cancels an order with its reason; moves no card, touches no
# file. Resolving a payment stays with "manage".
'payments': {'superadmin', 'admin', 'gestao', 'financeiro'},
'cancel': {'superadmin', 'admin', 'gestao', 'financeiro'},
# Prova OK or reprovada, on the proof card only (Dropstar, 2026-11-03): the
# seller, who otherwise only views, Gestão and the administrators.
'proof': {'superadmin', 'admin', 'gestao', 'vendedor'},
# "Retirado" at the counter (Dropstar's third round, item 14): everyone
# but the seller, who only views (D-30). It includes everyone who produces,
# and the operator, so an operator upload (artwork.py) takes it for its parts.
'deliver': {'superadmin', 'admin', 'gestao', 'designer', 'operador', 'revisor'},
# The photo or video of the printed sheet in Revisão (Fase 2, front 2): who
# releases to Finalizado, and Gestão, which may stand in for them.
'inspect': {'superadmin', 'admin', 'gestao', 'revisor'},
# Montar folha (Fase 2, front 7): the new Expedição profile and the seller,
# who gets this one action although otherwise view-only (D-30).
'assemble': {'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'},
# The 10x15 thermal label at Finalizado (Marcus, 2026-11-10, front 10): the
# Revisor who releases the card, the Expedição profile that ships it, and
# Gestão, which may stand in for either.
'label': {'superadmin', 'admin', 'gestao', 'revisor', 'expedicao'},
}
# Who moves which card (Dropstar's flow, 2026-10-23, and their rules of
# 2026-10-26): the designer the artwork, the operator the printing, and the
# Revisor to Finalizado, so nobody in the room releases their own print (D-29);
# Admin, Dropstar's own login, may release too (the user, 2026-10-28), and we,
# the superadmin, for support. Gestão, the coordination, pulls back and
# never forward, always with a reason (D-20): a step back, or Correção. Admin,
# Dropstar's own login, makes every other move. A step back undoes a mistaken
# move: open to whoever may make the move it undoes.
MOVES = {
'designer': {('rec', 'tra'), ('rec', 'cor'), ('tra', 'cor'), ('cor', 'rec'), ('cor', 'tra')},
'operador': {('tra', 'imp'), ('imp', 'rev')},
'revisor': {('rev', 'fin')},
}
ADMINS = ('superadmin', 'admin')
COORDINATION = ('gestao',)
MANAGERS = ADMINS + COORDINATION
RELEASERS = ('revisor', 'admin', 'superadmin')
# Who is asked "Em qual máquina você está?" after signing in (Dropstar, 2026-10-30):
# the operator must answer; Gestão and the administrators may say they are on
# none. The other profiles are never asked.
MACHINE_QUESTION = {'operador': 'required', 'gestao': 'optional', 'admin': 'optional'}
MOVERS = MANAGERS + tuple(MOVES)
def may_move(role, from_state, to_state, back=False):
"""Whether this profile may move a card; `back` is the step back that
undoes the move to_state -> from_state."""
if back:
return role in MANAGERS or (to_state, from_state) in MOVES.get(role, ())
if to_state == 'fin':
return role in RELEASERS
if to_state == 'cor' and role in COORDINATION:
return True
return role in ADMINS or (from_state, to_state) in MOVES.get(role, ())
def may_reorder(role, state):
"""Changing a card's place in its column, the order it is worked in: for
whoever takes cards forward out of it."""
return role in MANAGERS or any(a == state and b != 'cor' for a, b in MOVES.get(role, ()))
def signed_in(request: Request):
"""The operator behind this session, active, with the profile read now: a
role changed or an account disabled takes effect on the next request."""
token = request.cookies.get('dtf_operator', '')
if not token or len(token)>128:
raise HTTPException(401, 'Entre no Kanban.')
digest = hashlib.sha256(token.encode()).hexdigest()
with connect() as c:
row = c.execute('''SELECT o.id,o.email,o.name,o.role,s.machine_answered,m.id AS machine_id,m.name AS machine_name
FROM dtf_local.operator_sessions s
JOIN dtf_local.operators o ON o.email=s.username AND o.active
LEFT JOIN dtf_local.machines m ON m.id=s.machine_id
WHERE s.token_hash=%s AND s.expires_at>now()''', (digest,)).fetchone()
if row:
# When the session was last used, for "Ativo agora" in Usuários:
# written at most once a minute, not on every request.
c.execute('''UPDATE dtf_local.operator_sessions SET seen_at=now()
WHERE token_hash=%s AND (seen_at IS NULL OR seen_at<now()-interval '1 minute')''', (digest,))
if not row:
raise HTTPException(401, 'Sua sessão expirou. Entre de novo.')
# The machine this session works on (item 12), or None.
machine_id, machine_name = row.pop('machine_id'), row.pop('machine_name')
row['machine'] = {'id': str(machine_id), 'name': machine_name} if machine_id else None
row['session'] = digest
request.state.operator = row
return row
def can(capability):
"""A dependency that lets through the profiles allowed to do this, and
returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
if account['role'] not in CAPABILITIES[capability]:
raise HTTPException(403, 'Seu perfil não permite esta ação.')
return account['email']
return check
def can_any(*capabilities):
"""A dependency that lets through a profile with any of these capabilities,
and returns the operator's e-mail, as the routes record it."""
def check(request: Request):
account = signed_in(request)
if not any(account['role'] in CAPABILITIES[capability] for capability in capabilities):
raise HTTPException(403, 'Seu perfil não permite esta ação.')
return account['email']
return check
operator = can('view')