# Prompt: Kickoff v0.5.0 - Authentication, API Keys & Advanced Features > **Progetto:** mockupAWS - Backend Profiler & Cost Estimator > **Versione Target:** v0.5.0 > **Fase:** Implementazione > **Data Inizio:** 2026-04-07 > **Deadline Stimata:** 2-3 settimane > **PrioritΓ :** P1 (High) --- ## 🎯 OBIETTIVI v0.5.0 ### Goals Principali 1. **Autenticazione JWT Completa** - Login/Register con JWT tokens 2. **API Keys Management** - Generazione e gestione chiavi API per accesso programmatico 3. **Report Scheduling** - Cron jobs per generazione automatica report 4. **Email Notifications** - Notifiche email per eventi (report pronti, errori, etc.) 5. **Advanced Filters** - Filtri avanzati nella lista scenari 6. **Export Comparison PDF** - Esportazione confronto scenari come PDF ### Metriche di Successo - [ ] Login/Register funzionanti con JWT - [ ] API Keys generabili e utilizzabili - [ ] Report scheduling configurabile (daily/weekly/monthly) - [ ] Email inviate correttamente (SendGrid/AWS SES) - [ ] Filtri scenari: per data, costo, regione, stato - [ ] Comparison esportabile come PDF - [ ] Test coverage >80% - [ ] Documentazione API aggiornata --- ## πŸ‘₯ ASSEGNAZIONE TASK ### @db-engineer - Database Schema (3 task) - PRIORITΓ€ MASSIMA **DA COMPLETARE PRIMA di @backend-dev e @frontend-dev** #### DB-USER-001: Users Table Migration **File:** `alembic/versions/xxx_create_users_table.py` - [ ] Creare tabella `users`: ```sql id: UUID PRIMARY KEY email: VARCHAR(255) UNIQUE NOT NULL password_hash: VARCHAR(255) NOT NULL full_name: VARCHAR(255) is_active: BOOLEAN DEFAULT true is_superuser: BOOLEAN DEFAULT false created_at: TIMESTAMP updated_at: TIMESTAMP last_login: TIMESTAMP ``` - [ ] Indici: email (unique), created_at - [ ] Downgrade migration #### DB-APIKEY-002: API Keys Table Migration **File:** `alembic/versions/xxx_create_api_keys_table.py` - [ ] Creare tabella `api_keys`: ```sql id: UUID PRIMARY KEY user_id: UUID FOREIGN KEY β†’ users.id key_hash: VARCHAR(255) UNIQUE NOT NULL key_prefix: VARCHAR(8) NOT NULL -- prime 8 chars per identificazione name: VARCHAR(255) -- nome descrittivo scopes: JSONB -- ["read:scenarios", "write:scenarios", ...] last_used_at: TIMESTAMP expires_at: TIMESTAMP NULL is_active: BOOLEAN DEFAULT true created_at: TIMESTAMP ``` - [ ] Indici: key_hash (unique), user_id - [ ] Relazione: api_keys.user_id β†’ users.id (ON DELETE CASCADE) #### DB-SCHEDULE-003: Report Schedules Table Migration **File:** `alembic/versions/xxx_create_report_schedules_table.py` - [ ] Creare tabella `report_schedules`: ```sql id: UUID PRIMARY KEY user_id: UUID FOREIGN KEY β†’ users.id scenario_id: UUID FOREIGN KEY β†’ scenarios.id name: VARCHAR(255) frequency: ENUM('daily', 'weekly', 'monthly') day_of_week: INTEGER NULL -- 0-6 per weekly day_of_month: INTEGER NULL -- 1-31 per monthly hour: INTEGER -- 0-23 minute: INTEGER -- 0-59 format: ENUM('pdf', 'csv') include_logs: BOOLEAN sections: JSONB email_to: VARCHAR(255)[] -- array di email is_active: BOOLEAN DEFAULT true last_run_at: TIMESTAMP next_run_at: TIMESTAMP created_at: TIMESTAMP ``` - [ ] Indici: user_id, scenario_id, next_run_at **Output atteso:** - 3 file migration in `alembic/versions/` - Eseguire: `uv run alembic upgrade head` - Verificare tabelle create in PostgreSQL --- ### @backend-dev - Backend Implementation (8 task) - PRIORITΓ€ ALTA **DA INIZIARE DOPO che @db-engineer completa le migrations** #### BE-AUTH-001: Authentication Service **File:** `src/services/auth_service.py` (creare) - [ ] `register_user(email, password, full_name) -> User` - Validazione email (formato corretto) - Hash password con bcrypt (cost=12) - Creare user in DB - Return user (senza password_hash) - [ ] `authenticate_user(email, password) -> User | None` - Trovare user by email - Verificare password con bcrypt.checkpw - Aggiornare last_login - Return user o None - [ ] `change_password(user_id, old_password, new_password) -> bool` - [ ] `reset_password_request(email) -> str` (genera token) - [ ] `reset_password(token, new_password) -> bool` #### BE-AUTH-002: JWT Implementation **File:** `src/core/security.py` (estendere) - [ ] `create_access_token(data: dict, expires_delta: timedelta) -> str` - Algoritmo: HS256 - Secret: da env var `JWT_SECRET_KEY` - Expire: default 30 minuti - [ ] `create_refresh_token(data: dict) -> str` - Expire: 7 giorni - [ ] `verify_token(token: str) -> dict | None` - Verifica signature - Verifica expiration - Return payload o None - [ ] `get_current_user(token: str) -> User` - Usato come dependency nelle API #### BE-AUTH-003: Authentication API **File:** `src/api/v1/auth.py` (creare) - [ ] `POST /api/v1/auth/register` - Body: `{email, password, full_name}` - Response: `{user, access_token, refresh_token}` - Errori: 400 (email esiste), 422 (validazione) - [ ] `POST /api/v1/auth/login` - Body: `{email, password}` - Response: `{access_token, refresh_token, token_type: "bearer"}` - Errori: 401 (credenziali invalide) - [ ] `POST /api/v1/auth/refresh` - Body: `{refresh_token}` - Response: nuovi access_token e refresh_token - [ ] `POST /api/v1/auth/logout` (opzionale: blacklist token) - [ ] `POST /api/v1/auth/reset-password-request` - [ ] `POST /api/v1/auth/reset-password` - [ ] `GET /api/v1/auth/me` - Current user info #### BE-APIKEY-004: API Keys Service **File:** `src/services/apikey_service.py` (creare) - [ ] `generate_api_key() -> tuple[str, str]` - Genera key: `mk_` + 32 chars random (base64) - Ritorna: (full_key, key_hash) - Prefix: prime 8 chars della key - [ ] `create_api_key(user_id, name, scopes, expires_days) -> APIKey` - Salva key_hash (non full_key!) - Scopes: array di stringhe (es. ["read:scenarios", "write:reports"]) - [ ] `validate_api_key(key: str) -> User | None` - Estrai prefix - Trova APIKey by prefix e key_hash - Verifica is_active, not expired - Return user - [ ] `revoke_api_key(api_key_id) -> bool` - [ ] `list_api_keys(user_id) -> list[APIKey]` (senza key_hash) #### BE-APIKEY-005: API Keys Endpoints **File:** `src/api/v1/apikeys.py` (creare) - [ ] `POST /api/v1/api-keys` - Create new key - Auth: JWT required - Body: `{name, scopes, expires_days}` - Response: `{id, name, key: "mk_..." (solo questa volta!), prefix, scopes, created_at}` - ⚠️ ATTENZIONE: La key completa si vede SOLO alla creazione! - [ ] `GET /api/v1/api-keys` - List user's keys - Response: lista senza key_hash - [ ] `DELETE /api/v1/api-keys/{id}` - Revoke key - [ ] `POST /api/v1/api-keys/{id}/rotate` - Genera nuova key #### BE-SCHEDULE-006: Report Scheduling Service **File:** `src/services/scheduler_service.py` (creare) - [ ] `create_schedule(user_id, scenario_id, config) -> ReportSchedule` - Calcola next_run_at basato su frequency - [ ] `update_schedule(schedule_id, config) -> ReportSchedule` - [ ] `delete_schedule(schedule_id) -> bool` - [ ] `list_schedules(user_id) -> list[ReportSchedule]` - [ ] `calculate_next_run(frequency, day_of_week, day_of_month, hour, minute) -> datetime` - Logica per calcolare prossima esecuzione #### BE-SCHEDULE-007: Cron Job Runner **File:** `src/jobs/report_scheduler.py` (creare) - [ ] Funzione `run_scheduled_reports()` - Query: trova schedules dove `next_run_at <= now()` AND `is_active = true` - Per ogni schedule: - Genera report (usa report_service) - Invia email (usa email_service) - Aggiorna `last_run_at` e `next_run_at` - [ ] Configurazione cron: - File: `src/main.py` o script separato - Usare: `APScheduler` o `celery beat` - Frequenza: ogni 5 minuti #### BE-EMAIL-008: Email Service **File:** `src/services/email_service.py` (creare) - [ ] `send_email(to: list[str], subject: str, body: str, attachments: list) -> bool` - Provider: SendGrid o AWS SES (configurabile) - Template HTML per email - [ ] `send_report_ready_email(user_email, report_id, download_url)` - [ ] `send_schedule_report_email(emails, report_file, scenario_name)` - [ ] `send_welcome_email(user_email, user_name)` - [ ] Configurazione in `src/core/config.py`: ```python email_provider: str = "sendgrid" # o "ses" sendgrid_api_key: str = "" aws_access_key_id: str = "" aws_secret_access_key: str = "" email_from: str = "noreply@mockupaws.com" ``` **Output atteso:** - 8 file service/API creati - Test con curl per ogni endpoint - Verifica JWT funzionante - Verifica API Key generazione e validazione --- ### @frontend-dev - Frontend Implementation (7 task) - PRIORITΓ€ ALTA #### FE-AUTH-009: Authentication UI **File:** `src/pages/Login.tsx`, `src/pages/Register.tsx` (creare) - [ ] **Login Page:** - Form: email, password - Link: "Forgot password?" - Link: "Create account" - Submit β†’ chiama `/api/v1/auth/login` - Salva token in localStorage - Redirect a Dashboard - [ ] **Register Page:** - Form: email, password, confirm password, full_name - Validazione: password match, email valido - Submit β†’ chiama `/api/v1/auth/register` - Auto-login dopo registrazione - [ ] **Auth Context:** - `src/contexts/AuthContext.tsx` - Stato: user, isAuthenticated, login, logout, register - Persistenza: localStorage per token - Axios interceptor per aggiungere Authorization header #### FE-AUTH-010: Protected Routes **File:** `src/components/auth/ProtectedRoute.tsx` (creare) - [ ] Componente che verifica auth - Se non autenticato β†’ redirect a /login - Se autenticato β†’ render children - [ ] Modifica `App.tsx`: - Wrappare route private con ProtectedRoute - Route /login e /register pubbliche #### FE-APIKEY-011: API Keys UI **File:** `src/pages/ApiKeys.tsx` (creare) - [ ] Route: `/settings/api-keys` - [ ] Lista API Keys: - Tabella: Nome, Prefix, Scopes, Created, Last Used, Actions - Azioni: Revoke, Rotate - [ ] Form creazione nuova key: - Input: name - Select: scopes (multi-select) - Select: expiration (7, 30, 90, 365 days, never) - Submit β†’ POST /api/v1/api-keys - **Modale successo:** Mostra la key completa (SOLO UNA VOLTA!) - Messaggio: "Copia ora, non potrai vederla di nuovo!" - [ ] Copia negli appunti (clipboard API) #### FE-FILTER-012: Advanced Filters **File:** Modificare `src/pages/ScenariosPage.tsx` - [ ] **Filter Bar:** - Date range picker: Created from/to - Select: Region (tutte le regioni AWS) - Select: Status (active, paused, completed) - Slider/Input: Min/Max cost - Input: Search by name (debounced) - Button: "Apply Filters" - Button: "Clear Filters" - [ ] **URL Sync:** - I filtri devono essere sincronizzati con URL query params - Esempio: `/scenarios?region=us-east-1&status=active&min_cost=100` - [ ] **Backend Integration:** - Modificare `useScenarios` hook per supportare filtri - Aggiornare chiamata API con query params #### FE-SCHEDULE-013: Report Scheduling UI **File:** `src/pages/ScenarioDetail.tsx` (aggiungere tab) - [ ] **Nuovo tab: "Schedule"** (accanto a Reports) - [ ] Lista schedules esistenti: - Tabella: Name, Frequency, Next Run, Status, Actions - Azioni: Edit, Delete, Toggle Active/Inactive - [ ] Form creazione schedule: - Input: name - Select: frequency (daily, weekly, monthly) - Condizionale: - Weekly: select day of week - Monthly: select day of month - Time picker: hour, minute - Select: format (PDF/CSV) - Checkbox: include_logs - Multi-select: sections - Input: email addresses (comma-separated) - Submit β†’ POST /api/v1/schedules #### FE-EXPORT-014: Export Comparison PDF **File:** Modificare `src/pages/Compare.tsx` - [ ] **Button "Export as PDF"** in alto a destra - [ ] Chiamata API: `POST /api/v1/comparison/export` (da creare in BE) - [ ] Body: `{scenario_ids: [id1, id2, ...], format: "pdf"}` - [ ] Download file (come per i report) - [ ] Toast notification: "Export started..." / "Export ready" #### FE-UI-015: User Profile & Settings **File:** `src/pages/Profile.tsx`, `src/pages/Settings.tsx` (creare) - [ ] **Profile:** - Mostra: email, full_name, created_at - Form cambio password - Lista sessioni attive (opzionale) - [ ] **Settings:** - Preferenze tema (giΓ  fatto in v0.4.0) - Link a API Keys management - Notificazioni email (toggle on/off) - [ ] **Header:** - Dropdown utente (click su nome) - Opzioni: Profile, Settings, API Keys, Logout **Output atteso:** - 7+ pagine/componenti creati - Auth flow funzionante (login β†’ dashboard) - API Keys visibili e gestibili - Filtri applicabili - Routes protette --- ### @devops-engineer - Infrastructure & Configuration (3 task) #### DEV-EMAIL-016: Email Provider Configuration **File:** Documentazione e config - [ ] Setup SendGrid: - Creare account SendGrid (free tier: 100 email/giorno) - Generare API Key - Verificare sender domain - [ ] OPPURE setup AWS SES: - Configurare SES in AWS Console - Verificare email sender - Ottenere AWS credentials - [ ] Aggiornare `.env.example`: ``` EMAIL_PROVIDER=sendgrid SENDGRID_API_KEY=sg_xxx # o EMAIL_PROVIDER=ses AWS_ACCESS_KEY_ID=AKIA... AWS_SECRET_ACCESS_KEY=... EMAIL_FROM=noreply@mockupaws.com ``` #### DEV-CRON-017: Cron Job Deployment **File:** `docker-compose.yml`, `Dockerfile.worker` - [ ] Aggiungere service `scheduler` a `docker-compose.yml`: ```yaml scheduler: build: . command: python -m src.jobs.report_scheduler depends_on: - postgres - redis # opzionale, per queue environment: - DATABASE_URL=postgresql+asyncpg://... ``` - [ ] OPPURE usare APScheduler in-process nel backend - [ ] Documentare come eseguire scheduler in produzione #### DEV-SECRETS-018: Secrets Management **File:** `.env.example`, documentazione - [ ] Aggiungere a `.env.example`: ``` # JWT JWT_SECRET_KEY=super-secret-change-in-production JWT_ALGORITHM=HS256 ACCESS_TOKEN_EXPIRE_MINUTES=30 REFRESH_TOKEN_EXPIRE_DAYS=7 # Security BCRYPT_ROUNDS=12 ``` - [ ] Creare `.env.production.example` con best practices - [ ] Documentare setup iniziale (generare JWT secret) **Output atteso:** - Email provider configurato e testato - Cron job deployabile - Secrets documentati --- ### @qa-engineer - Testing (4 task) - DA ESEGUIRE VERSO FINE #### QA-AUTH-019: Authentication Tests **File:** `frontend/e2e/auth.spec.ts` (creare) - [ ] Test registrazione: - Compila form β†’ submit β†’ verifica redirect - Test email duplicato β†’ errore - Test password mismatch β†’ errore - [ ] Test login: - Credenziali corrette β†’ dashboard - Credenziali errate β†’ errore - [ ] Test protected routes: - Accesso diretto a /scenarios senza auth β†’ redirect a login - Accesso con auth β†’ pagina visibile - [ ] Test logout: - Click logout β†’ redirect login β†’ token rimosso #### QA-APIKEY-020: API Keys Tests **File:** `frontend/e2e/apikeys.spec.ts` (creare) - [ ] Test creazione API Key: - Vai a settings/api-keys - Crea nuova key β†’ verifica modale con key completa - Verifica key appare in lista - [ ] Test revoke: - Revoca key β†’ non piΓΉ in lista - [ ] Test API access con key: - Chiamata API con header `X-API-Key: mk_...` - Verifica accesso consentito - Chiamata con key revocata β†’ 401 #### QA-FILTER-021: Filters Tests **File:** Aggiornare `frontend/e2e/scenarios.spec.ts` - [ ] Test filtri: - Applica filtro region β†’ lista aggiornata - Applica filtro costo β†’ lista aggiornata - Combinazione filtri β†’ URL aggiornato - Clear filters β†’ lista completa #### QA-E2E-022: E2E Regression **File:** Tutti i test esistenti - [ ] Aggiornare test esistenti per supportare auth: - Aggiungere login prima di ogni test - Usare API per creare dati di test autenticati - [ ] Verificare tutti i test v0.4.0 ancora passano - [ ] Target: >80% pass rate **Output atteso:** - 4+ file test E2E - Test passanti su Chromium - Documentazione test strategy --- ### @spec-architect - Architecture & Review (2 task) - CONTINUO #### SPEC-ARCH-023: Security Review - [ ] Review authentication flow: - JWT secret strength - Token expiration times - Refresh token rotation - Password hashing (bcrypt cost) - [ ] Review API Keys security: - Storage (hash, not plaintext) - Transmission (HTTPS only) - Scopes validation - [ ] Review CORS configuration - [ ] Review rate limiting: - Auth endpoints: 5 req/min - API Key endpoints: 10 req/min - General: 100 req/min - [ ] Documentare security considerations in `SECURITY.md` #### SPEC-DOC-024: API Documentation - [ ] Aggiornare OpenAPI/Swagger docs: - Tutti i nuovi endpoints /auth/* - Tutti i nuovi endpoints /api-keys/* - Endpoints /schedules/* - Schema utente, api_key, schedule - [ ] Aggiornare `export/architecture.md`: - Sezione Authentication - Sezione API Keys - Sezione Report Scheduling - Security Architecture - [ ] Aggiornare `README.md`: - Feature v0.5.0 - Setup instructions (env vars) **Output atteso:** - Security review document - Architecture docs aggiornati - API docs complete --- ## πŸ“… TIMELINE SUGGERITA (3 settimane) ### Week 1: Foundation (Database + Auth Core) - **Giorno 1-2:** @db-engineer - Migrations (3 task) - **Giorno 2-4:** @backend-dev - BE-AUTH-001, 002, 003 (Auth service + JWT + API) - **Giorno 3-5:** @frontend-dev - FE-AUTH-009, 010 (Login UI + Protected Routes) - **Giorno 5:** @devops-engineer - DEV-EMAIL-016 (Email config) - **Weekend:** Testing auth flow, bugfixing ### Week 2: API Keys & Scheduling - **Giorno 6-8:** @backend-dev - BE-APIKEY-004, 005, BE-SCHEDULE-006 (API Keys + Schedules) - **Giorno 8-10:** @frontend-dev - FE-APIKEY-011, FE-SCHEDULE-013, FE-FILTER-012 - **Giorno 10-12:** @backend-dev - BE-EMAIL-008, BE-SCHEDULE-007 (Email + Cron) - **Giorno 12:** @devops-engineer - DEV-CRON-017 (Cron deployment) - **Weekend:** Integration testing ### Week 3: Polish, Export & Testing - **Giorno 13-14:** @frontend-dev - FE-EXPORT-014, FE-UI-015 (Export + Profile) - **Giorno 14-16:** @qa-engineer - QA-AUTH-019, 020, 021, 022 (All tests) - **Giorno 16-17:** @backend-dev - Bugfixing - **Giorno 17-18:** @frontend-dev - Bugfixing - **Giorno 18:** @spec-architect - SPEC-ARCH-023, SPEC-DOC-024 (Review + Docs) - **Giorno 19-21:** Buffer per imprevisti, final review --- ## πŸ”§ DIPENDENZE CRITICHE ``` @db-engineer (DB-USER-001, 002, 003) ↓ (blocca) @backend-dev (tutti i BE-*) ↓ (blocca) @frontend-dev (FE-AUTH-009+, FE-APIKEY-011+) @backend-dev (BE-AUTH-003) ↓ (blocca) @qa-engineer (QA-AUTH-019) @devops-engineer (DEV-EMAIL-016) ↓ (blocca) @backend-dev (BE-EMAIL-008) ``` --- ## βœ… DEFINITION OF DONE ### Per ogni task: - [ ] Codice scritto e funzionante - [ ] TypeScript: nessun errore - [ ] Testati (manualmente o automaticamente) - [ ] Nessun errore console/browser - [ ] Documentato (se necessario) ### Per v0.5.0: - [ ] Tutte le migrations eseguite - [ ] Auth flow completo (register β†’ login β†’ access protected) - [ ] API Keys generabili e funzionanti - [ ] Report scheduling configurabile - [ ] Email inviate correttamente - [ ] Filtri avanzati funzionanti - [ ] Export comparison PDF funzionante - [ ] Test E2E >80% passanti - [ ] Documentazione aggiornata - [ ] Security review passata - [ ] Tag v0.5.0 creato --- ## 🚨 CRITERI DI BLOCCO **NON procedere se:** - ❌ Database migrations non eseguite - ❌ JWT secret non configurato - ❌ Auth flow non funziona - ❌ Password in plaintext (deve essere hash!) - ❌ API Keys in plaintext (deve essere hash!) --- ## 🎯 COMANDO DI AVVIO ```bash # @db-engineer cd /home/google/Sources/LucaSacchiNet/mockupAWS # Creare migrations e eseguire: uv run alembic upgrade head # @backend-dev cd /home/google/Sources/LucaSacchiNet/mockupAWS # Iniziare da BE-AUTH-001 dopo migrations # @frontend-dev cd /home/google/Sources/LucaSacchiNet/mockupAWS/frontend # Iniziare da FE-AUTH-009 quando BE-AUTH-003 Γ¨ pronto # @qa-engineer cd /home/google/Sources/LucaSacchiNet/mockupAWS/frontend # Iniziare quando FE-AUTH-010 Γ¨ pronto ``` --- **Buon lavoro team! Portiamo mockupAWS alla v0.5.0 con autenticazione e feature avanzate! πŸ”πŸš€** *Prompt v0.5.0 generato il 2026-04-07* *Inizio implementazione: appena il team Γ¨ ready*