diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 8014b8f..a887514 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -86,7 +86,7 @@ jobs: # one a developer exercises on localhost. - name: API and workflow regressions run: | - for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do + for suite in smoke_test workflow_test security_test upload_limits_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test label_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test coupons_test stamps_test grade_rules_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ diff --git a/app/api/uploads.py b/app/api/uploads.py index c73b57f..95a9652 100644 --- a/app/api/uploads.py +++ b/app/api/uploads.py @@ -12,7 +12,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request from starlette.concurrency import run_in_threadpool from ..core import db -from ..core.auth import audit, owner, rate_limit +from ..core.auth import audit, client_ip, owner, rate_limit from ..core.limits import upload_limit_bytes from ..core.models import UploadStart from ..payments import UNPAID_HOLD @@ -20,13 +20,25 @@ from ..runtime import PART_BYTES, storage, upload_row router = APIRouter() +# A cart of many files: 66 in Marcus's case (2026-11-11), and adding more or +# retrying must fit. The per-source bucket bounds abuse, not a real order. +UPLOAD_START_LIMIT = 1000 +UPLOAD_START_IP_LIMIT = 3000 + + +def upload_ip_limit(request: Request): + """The public upload route's per-source bucket. The operator upload routes + reuse begin_upload directly and stay bound by their own session bucket.""" + rate_limit('upload-start-ip', client_ip(request), UPLOAD_START_IP_LIMIT, 900) + + @router.post('/api/uploads') -def begin_upload(body: UploadStart, session_id=Depends(owner)): +def begin_upload(body: UploadStart, session_id=Depends(owner), _source=Depends(upload_ip_limit)): if body.size > upload_limit_bytes(): raise HTTPException(413, 'O arquivo passa do tamanho máximo aceito. Escolha um arquivo menor.') uid = uuid4() key = f'originals/{uid}' - rate_limit('upload-start', str(session_id), 60, 900) + rate_limit('upload-start', str(session_id), UPLOAD_START_LIMIT, 900) with db.connect() as c: # Serialize reservations across API processes, including changing guest IDs. c.execute('SELECT pg_advisory_xact_lock(804208)') diff --git a/tests/upload_limits_test.py b/tests/upload_limits_test.py new file mode 100644 index 0000000..b5285ee --- /dev/null +++ b/tests/upload_limits_test.py @@ -0,0 +1,40 @@ +"""The upload start limit: a large cart fits, and the per-source bucket +still refuses above its own limit (Marcus's bugs of 2026-11-11, B1). + +Run against the local stack: python -m tests.upload_limits_test +""" +import secrets + +from fastapi import HTTPException + +from app.api.uploads import UPLOAD_START_IP_LIMIT, UPLOAD_START_LIMIT +from app.core.auth import rate_limit +from tests.smoke_test import Client + + +def run(): + assert (UPLOAD_START_LIMIT, UPLOAD_START_IP_LIMIT) == (1000, 3000) + client = Client() + client.call('/session') + # A 66-file cart, with retries, fits in one session. Each reservation is + # cancelled so the pending-upload quota (unchanged) does not stop the test. + for index in range(70): + uid = client.call('/uploads', {'name': f'LIMIT-{index}.png', 'size': 1})['id'] + client.call(f'/uploads/{uid}', expected=200, method='DELETE') + # The per-source bucket, exercised directly with a small limit: 3000 real + # starts would only slow CI. A unique key keeps other suites out of it. + key = 'upload-start-ip-test-' + secrets.token_hex(8) + for _ in range(3): + rate_limit('upload-start-ip', key, 3, 900) + try: + rate_limit('upload-start-ip', key, 3, 900) + except HTTPException as error: + assert error.status_code == 429, error + assert error.headers.get('Retry-After') == '900', error.headers + else: + raise AssertionError('the per-source upload bucket accepted above its limit') + print('PASS: 70 upload starts in one session; the per-source bucket refuses above its limit') + + +if __name__ == '__main__': + run() diff --git a/web/checkout.js b/web/checkout.js index 982634b..89b3014 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -46,7 +46,17 @@ let data; try { data = text ? JSON.parse(text) : {}; } catch (_) { throw new Error(response.ok ? 'Resposta inválida do serviço.' : 'O serviço está indisponível. Tente novamente em instantes.'); } - if (!response.ok) { const error=new Error(problem(data.detail));error.status=response.status;throw error; } + if (!response.ok) { + const text=problem(data.detail); + // A validation the customer cannot read still needs to reach us (Sentry + // picks up console.error later); the customer keeps the generic sentence. + if (response.status===422 && text==='Não foi possível concluir. Confira os dados e tente de novo.') + console.error('Detalhe da validação recusada:',data.detail); + const error=new Error(text);error.status=response.status; + const retry=response.headers.get('Retry-After'); + if(retry!=null)error.retryAfter=retry; + throw error; + } return data; }; // A refusal as one sentence: the server's own, or the first field a form @@ -262,10 +272,35 @@ pintaEnvio(); } const arquivosDoCarrinho=()=>[...pedido.filter(it=>it.marcado!==false),...(busy&&itemAtual?[itemAtual]:[])].flatMap(it=>it.localFiles||[]); + // Every file of the paying cart must be sent (and none failed) before the + // quote and before the payment button (bugs B2 and B4, Marcus 2026-11-11). + function faltaEnvio(){ + const files=arquivosDoCarrinho(); + let pending=0,failed=0; + for(const f of files){ + const k=chaveArquivo(f); + if(falhas.has(k)){failed++;continue;} + const e=envios.get(k); + if(!e||!e.done)pending++; + } + return {total:files.length,pending,failed,falta:pending+failed}; + } + window.dtfFaltaEnvio=faltaEnvio; + function faltaEnvioMensagem(){ + const missing=[]; + for(const f of arquivosDoCarrinho()){ + const k=chaveArquivo(f),e=envios.get(k); + if(falhas.has(k)||!e||!e.done)missing.push(f); + } + if(!missing.length) return ''; + return 'Falta enviar '+missing[0].name+ + (missing.length>1?' (e mais '+(missing.length-1)+')':''); + } const gb=n=>(n/1073741824).toLocaleString('pt-BR',{maximumFractionDigits:1})+' GB'; const mb=n=>n>=1073741824 ? gb(n) : Math.round(n/1048576)+' MB'; // Where the uploads stand, and roughly how long is left from the recent speed. const amostras=[]; + let ultimaFalta=null; function estadoEnvio() { const files=arquivosDoCarrinho(); if(!files.length) return null; let total=0, sent=0, pendentes=0; @@ -292,6 +327,13 @@ return 'Enviando seus arquivos · '+restante(e); } function pintaEnvio() { + // The cart button carries the uploads too (B2): repaint it only when the + // number of missing files changes, not on every progress tick. + const falta=faltaEnvio().falta; + if(falta!==ultimaFalta){ + ultimaFalta=falta; + if(typeof pintaPedido==='function')pintaPedido(); + } window.dispatchEvent(new Event('dtf-envio')); const e=estadoEnvio(), texto=textoEnvio(e); const el=document.getElementById('envioArq'); @@ -391,6 +433,8 @@ if (!clienteOk() || !entrega.cotado) return; if (!enderecoOk()) return message('Preencha o endereço de entrega.','error'); if (!cartPodeEnviar()) return message('Revise a qualidade e confirme a ressalva de cada item antes de enviar o pedido.','error'); + const semArquivo=faltaEnvioMensagem(); + if (semArquivo) return message(semArquivo+'.','error'); const cart = itensAPagar(); if (!cart.length) return message('Adicione um item ao pedido.','error'); const initialCart=cartSnapshot(); diff --git a/web/site-cart.js b/web/site-cart.js index 8dfd527..3133c71 100644 --- a/web/site-cart.js +++ b/web/site-cart.js @@ -114,13 +114,18 @@ function pintaPedido(){ '