Files
mockupAWS/README.md
Luca Sacchi Ricciardi a5f6e1a20c
Some checks failed
CI/CD - Build & Test / Backend Tests (push) Has been cancelled
CI/CD - Build & Test / Frontend Tests (push) Has been cancelled
CI/CD - Build & Test / Security Scans (push) Has been cancelled
CI/CD - Build & Test / Docker Build Test (push) Has been cancelled
CI/CD - Build & Test / Terraform Validate (push) Has been cancelled
Deploy to Production / Build & Test (push) Has been cancelled
Deploy to Production / Security Scan (push) Has been cancelled
Deploy to Production / Build Docker Images (push) Has been cancelled
Deploy to Production / Deploy to Staging (push) Has been cancelled
Deploy to Production / E2E Tests (push) Has been cancelled
Deploy to Production / Deploy to Production (push) Has been cancelled
docs: update documentation for v1.0.0 release and future milestones
Update todo.md:
- Mark v1.0.0 as completed (Production Ready)
- Add v1.1.0 and v2.0.0 roadmap sections
- Add maintenance and deployment sections
- Update version info

Update README.md:
- Add Production Ready section with v1.0.0 features
- Include HA, performance, caching, backups, monitoring, security

Documentation now reflects current v1.0.0 status and future development plans.
2026-04-07 21:51:59 +02:00

22 KiB

mockupAWS - Backend Profiler & Cost Estimator

Versione: 1.0.0 (Production Ready)
Stato: Authentication & API Keys

Panoramica

mockupAWS è una piattaforma di simulazione locale (homelab) progettata per profilare il traffico e calcolare i driver di costo dei servizi AWS (SQS, Lambda, Bedrock/LLM) prima del deploy in produzione.

A differenza dei semplici calcolatori di costo online, mockupAWS permette di:

  • Creare scenari di simulazione isolati e tracciabili
  • Inviare log reali tramite HTTP API (compatibile Logstash)
  • Storicizzare tutte le metriche in database PostgreSQL
  • Calcolare costi usando prezzi AWS reali aggiornabili
  • Generare report PDF/CSV professionali
  • Confrontare scenari per decisioni data-driven
  • Rilevare PII nei log prima dell'invio al cloud

Caratteristiche Principali

🎯 Gestione Scenari

  • Crea scenari di simulazione con nome, descrizione e tag
  • Isola completamente i dati tra scenari diversi
  • Stati dello scenario: draftrunningcompletedarchived
  • Confronta scenari side-by-side con indicatori di delta costi

💰 Calcolo Costi AWS Reale

  • Tabella prezzi AWS configurabile per regione
  • Calcolo accurato basato su:
    • SQS: $0.40 per milione richieste (blocchi 64KB)
    • Lambda: $0.20 per milione richieste + $0.0000166667 per GB-second
    • Bedrock: Prezzi per token input/output (variano per modello)
  • Supporto multi-regione (us-east-1, eu-west-1, ecc.)

📊 Interfaccia Web

  • Dashboard responsive con grafici in tempo reale
  • Form guidato per creazione scenari
  • Vista dettaglio con metriche, costi, logs e PII detection

🚀 Production Ready (v1.0.0)

  • High Availability: 99.9% uptime target con Multi-AZ deployment
  • Performance: <200ms response time (p95), 1000+ utenti concorrenti
  • Redis Caching: 3-tier caching strategy (query, reports, pricing)
  • Automated Backups: PITR (Point-in-Time Recovery), RTO<1h, RPO<5min
  • Monitoring: Prometheus + Grafana con 15+ alert rules
  • Security: Audit logging, 0 vulnerabilità critiche, compliance GDPR

🔐 Authentication & API Keys (v0.5.0)

  • JWT Authentication: Login/Register con token access (30min) e refresh (7giorni)
  • API Keys Management: Generazione e gestione chiavi API con scopes
  • Password Security: bcrypt hashing con cost=12
  • Token Rotation: Refresh token rotation per sicurezza

📈 Data Visualization & Reports (v0.4.0)

  • Report Generation: PDF/CSV professionali con template personalizzabili
  • Data Visualization: Grafici interattivi con Recharts (Pie, Area, Bar)
  • Scenario Comparison: Confronto side-by-side di 2-4 scenari con delta costi
  • Dark/Light Mode: Toggle tema con rilevamento preferenza sistema

🔒 Sicurezza

  • Rilevamento automatico email (PII) nei log
  • Hashing dei messaggi per privacy
  • Deduplicazione automatica per simulazione batching ottimizzato
  • Autenticazione JWT e API Keys
  • Rate limiting per endpoint

Architettura

┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐
│   Logstash      │     │   React Web UI   │     │   API Clients   │
│   (o Client)    │     │   (Dashboard)    │     │   (CI/CD)       │
└────────┬────────┘     └────────┬─────────┘     └────────┬────────┘
         │                       │                        │
         │ HTTP POST             │ HTTPS                  │ API Key
         │ /ingest               │ /api/v1/*              │ /api/v1/*
         ▼                       ▼                        ▼
┌────────────────────────────────────────────────────────────────────┐
│                    API LAYER (FastAPI + Uvicorn)                   │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌───────────┐ │
│  │ /scenarios  │  │ /ingest     │  │ /reports    │  │ /pricing  │ │
│  │ /metrics    │  │ (scenario)  │  │ generate    │  │ (admin)   │ │
│  └─────────────┘  └─────────────┘  └─────────────┘  └───────────┘ │
└────────────────────────────────────────────────────────────────────┘
         │
         ▼
┌────────────────────────────────────────────────────────────────────┐
│              DATABASE LAYER (PostgreSQL 15+)                       │
│  ┌──────────────┐ ┌──────────────┐ ┌──────────────┐               │
│  │  scenarios   │ │scenario_logs │ │ aws_pricing  │               │
│  │  scenario_   │ │  reports     │ │              │               │
│  │  metrics     │ │              │ │              │               │
│  └──────────────┘ └──────────────┘ └──────────────┘               │
└────────────────────────────────────────────────────────────────────┘

Screenshots

Nota: Gli screenshot saranno aggiunti nella release finale.

Dashboard

Dashboard Dashboard principale con lista scenari e metriche overview

Scenario Detail con Grafici

Scenario Detail Vista dettaglio scenario con cost breakdown chart e time series

Scenario Comparison

Comparison Confronto side-by-side di multipli scenari con indicatori delta

Dark Mode

Dark Mode Tema scuro applicato a tutta l'interfaccia

Report Generation

Reports Generazione e download report PDF/CSV

Stack Tecnologico

Backend

  • FastAPI (≥0.110) - Framework web async ad alte prestazioni
  • PostgreSQL (≥15) - Database relazionale con supporto JSON
  • SQLAlchemy (≥2.0) - ORM moderno con supporto async/await
  • Alembic - Migrazioni database versionate
  • Pydantic (≥2.7) - Validazione dati e serializzazione
  • tiktoken - Tokenizer ufficiale OpenAI per calcolo costi LLM
  • python-jose - JWT handling per autenticazione
  • bcrypt - Password hashing (cost=12)
  • slowapi - Rate limiting per endpoint
  • APScheduler - Job scheduling per report automatici
  • SendGrid/AWS SES - Email notifications

Frontend

  • React (≥18) - UI library con hooks e functional components
  • Vite (≥5.0) - Build tool ultra-veloce con HMR
  • TypeScript (≥5.0) - Type safety e developer experience
  • Tailwind CSS (≥3.4) - Utility-first CSS framework
  • shadcn/ui - Componenti UI accessibili e personalizzabili
  • TanStack Query (React Query) - Data fetching e caching
  • Axios - HTTP client con interceptors
  • React Router - Client-side routing
  • Lucide React - Icone moderne e consistenti

DevOps

  • Docker & Docker Compose - Containerizzazione
  • Nginx - Reverse proxy (pronto per produzione)
  • uv - Package manager Python veloce e moderno
  • Ruff - Linter e formatter Python
  • ESLint & Prettier - Code quality frontend

Requisiti

  • Docker & Docker Compose
  • Python 3.11+ (se sviluppo locale)
  • Node.js 20+ (se sviluppo frontend)
  • ~2GB RAM disponibili

Installazione e Avvio

Prerequisiti

  • Docker & Docker Compose
  • Python 3.11+ (per sviluppo locale)
  • Node.js 20+ (per sviluppo frontend)
  • PostgreSQL 15+ (se non usi Docker)

Metodo 1: Docker Compose (Consigliato)

# Clona il repository
git clone <repository-url>
cd mockupAWS

# Avvia tutti i servizi (API + Database + Frontend)
docker-compose up --build

# L'applicazione sarà disponibile su:
# - Web UI: http://localhost:5173  (Vite dev server)
# - API: http://localhost:8000
# - API Docs: http://localhost:8000/docs
# - Database: localhost:5432

Metodo 2: Sviluppo Locale

Step 1: Database

# Usa Docker solo per PostgreSQL
docker-compose up -d postgres
# oppure configura PostgreSQL localmente

Step 2: Backend

# Installa dipendenze Python
uv sync

# Esegui migrazioni database
uv run alembic upgrade head

# Avvia server API
uv run uvicorn src.main:app --reload --host 0.0.0.0 --port 8000

Step 3: Frontend (in un altro terminale)

cd frontend

# Installa dipendenze
npm install

# Avvia server sviluppo
npm run dev

# L'app sarà disponibile su http://localhost:5173

Configurazione Ambiente

Crea un file .env nella root del progetto copiando da .env.example:

cp .env.example .env

Variabili d'Ambiente Richieste

# =============================================================================
# Database (Richiesto)
# =============================================================================
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/mockupaws

# =============================================================================
# Applicazione (Richiesto)
# =============================================================================
APP_NAME=mockupAWS
DEBUG=true
API_V1_STR=/api/v1

# =============================================================================
# JWT Authentication (Richiesto per v0.5.0)
# =============================================================================
# Genera con: openssl rand -hex 32
JWT_SECRET_KEY=your-32-char-secret-here-minimum
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
REFRESH_TOKEN_EXPIRE_DAYS=7

# =============================================================================
# Sicurezza (Richiesto per v0.5.0)
# =============================================================================
BCRYPT_ROUNDS=12
API_KEY_PREFIX=mk_

# =============================================================================
# Email (Opzionale - per notifiche report)
# =============================================================================
EMAIL_PROVIDER=sendgrid
EMAIL_FROM=noreply@mockupaws.com
SENDGRID_API_KEY=sg_your_key_here

# =============================================================================
# Frontend (per CORS)
# =============================================================================
FRONTEND_URL=http://localhost:5173
ALLOWED_HOSTS=localhost,127.0.0.1

# =============================================================================
# Reports & Storage
# =============================================================================
REPORTS_STORAGE_PATH=./storage/reports
REPORTS_MAX_FILE_SIZE_MB=50
REPORTS_CLEANUP_DAYS=30
REPORTS_RATE_LIMIT_PER_MINUTE=10

# =============================================================================
# Scheduler (Cron Jobs)
# =============================================================================
SCHEDULER_ENABLED=true
SCHEDULER_INTERVAL_MINUTES=5

Generazione JWT Secret

# Genera un JWT secret sicuro (32+ caratteri)
openssl rand -hex 32

# Esempio output:
# a3f5c8e9d2b1f4a7c6e8d9b0a2c4e6f8a1b3d5c7e9f2a4b6c8d0e2f4a6b8c0d

Utilizzo

1. Creare uno Scenario

Via Web UI:

  1. Apri http://localhost:3000
  2. Clicca "Nuovo Scenario"
  3. Inserisci nome, descrizione, seleziona regione AWS
  4. Clicca "Crea e Avvia"

Via API:

curl -X POST http://localhost:8000/api/v1/scenarios \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Produzione Q2",
    "description": "Simulazione traffico produzione",
    "region": "us-east-1",
    "tags": ["production"]
  }'
# Response: { "id": "uuid-scenario-123", ... }

2. Inviare Log allo Scenario

# Usa lo scenario ID ricevuto
curl -X POST http://localhost:8000/ingest \
  -H "Content-Type: application/json" \
  -H "X-Scenario-ID: uuid-scenario-123" \
  -d '{"message": "Error: connection timeout", "source": "api"}'

Oppure configura Logstash:

output {
  http {
    url => "http://localhost:8000/ingest"
    headers => ["X-Scenario-ID", "uuid-scenario-123"]
    content_type => "application/json"
    format => "json"
  }
}

3. Monitorare in Tempo Reale

  • Apri la Web UI http://localhost:3000
  • Seleziona il tuo scenario
  • Osserva metriche in tempo reale:
    • Richieste totali
    • Costo stimato cumulativo
    • Blocchi SQS fatturabili
    • Token LLM contati
    • Violazioni PII rilevate

4. Generare Report

Via Web UI:

  1. Vai al tab "Report" dello scenario
  2. Seleziona formato (PDF o CSV)
  3. Clicca "Genera Report"
  4. Scarica il file

Via API:

curl -X POST http://localhost:8000/api/v1/scenarios/uuid-scenario-123/reports \
  -H "Content-Type: application/json" \
  -d '{"format": "pdf", "include_logs": false}'

5. Confrontare Scenari

Nella Web UI:

  1. Dalla lista scenari, seleziona 2+ scenari con i checkbox
  2. Clicca "Confronta Selezionati"
  3. Visualizza comparazione costi e metriche

Struttura del Progetto

mockupAWS/
├── src/                          # Backend FastAPI
│   ├── main.py                   # Entry point applicazione
│   ├── api/
│   │   ├── deps.py              # Dependencies (DB session, auth)
│   │   └── v1/                  # API v1 endpoints
│   │       ├── scenarios.py     # CRUD scenari
│   │       ├── ingest.py        # Ingestione log
│   │       └── metrics.py       # Metriche e costi
│   ├── core/
│   │   ├── config.py            # Configurazione app
│   │   ├── database.py          # SQLAlchemy setup
│   │   └── exceptions.py        # Gestione errori
│   ├── models/                  # SQLAlchemy models
│   │   ├── scenario.py
│   │   ├── scenario_log.py
│   │   ├── scenario_metric.py
│   │   ├── aws_pricing.py
│   │   └── report.py
│   ├── schemas/                 # Pydantic schemas
│   ├── repositories/            # Repository pattern
│   └── services/                # Business logic
│       ├── pii_detector.py
│       ├── cost_calculator.py
│       ├── ingest_service.py
│       └── report_service.py    # PDF/CSV generation (v0.4.0)
├── frontend/                     # Frontend React
│   ├── src/
│   │   ├── App.tsx              # Root component
│   │   ├── components/
│   │   │   ├── layout/          # Header, Sidebar, Layout
│   │   │   ├── ui/              # shadcn components
│   │   │   ├── charts/          # Recharts components (v0.4.0)
│   │   │   ├── comparison/      # Comparison components (v0.4.0)
│   │   │   └── reports/         # Report generation UI (v0.4.0)
│   │   ├── hooks/               # React Query hooks
│   │   ├── lib/
│   │   │   ├── api.ts           # Axios client
│   │   │   ├── utils.ts         # Utility functions
│   │   │   └── theme-provider.tsx # Dark mode (v0.4.0)
│   │   ├── pages/               # Page components
│   │   │   ├── Dashboard.tsx
│   │   │   ├── ScenarioDetail.tsx
│   │   │   ├── ScenarioEdit.tsx
│   │   │   ├── Compare.tsx      # Scenario comparison (v0.4.0)
│   │   │   └── Reports.tsx      # Reports page (v0.4.0)
│   │   └── types/
│   │       └── api.ts           # TypeScript types
│   ├── e2e/                     # E2E tests (v0.4.0)
│   ├── package.json
│   ├── playwright.config.ts     # Playwright config (v0.4.0)
│   └── vite.config.ts
├── alembic/                      # Database migrations
│   └── versions/                 # Migration files
├── export/                       # Documentazione progetto
│   ├── prd.md                   # Product Requirements
│   ├── architecture.md          # Architettura sistema
│   ├── kanban.md                # Task breakdown
│   └── progress.md              # Progress tracking
├── docker-compose.yml            # Docker orchestration
├── pyproject.toml               # Python dependencies
└── README.md                    # Questo file

Principi di Design

🔐 Safety First

Validazione rigorosa dei payload e rilevamento PII prima di qualsiasi elaborazione.

🔄 Little Often

Processamento a piccoli batch per simulare l'ottimizzazione Lambda e minimizzare costi.

✓ Double Check

Ogni calcolo (token count, billing blocks, costi) è verificato. Target: >95% accuratezza vs AWS reale.

Sviluppo

Flusso di Lavoro (TDD)

  1. Spec-Driven: Definisci input/output prima di implementare
  2. Test First: Scrivi test che falliscono (Red)
  3. Implementa: Codice minimo per far passare test (Green)
  4. Refactor: Migliora codice mantenendo test passanti

Convenzioni Git

  • Conventional Commits: feat:, fix:, test:, docs:, chore:
  • Commit atomici
  • Esempio: feat: add scenario cost calculation with AWS pricing

Comandi Utili

# Test
uv run pytest                    # Tutti i test
uv run pytest -v                 # Verbose
uv run pytest --cov=src          # Con coverage

# Database
uv run alembic revision --autogenerate -m "description"
uv run alembic upgrade head
uv run alembic downgrade -1

# Formattazione
uv run ruff check src/
uv run ruff format src/

# Frontend
cd frontend
npm run lint
npm run build

Configurazione Sicurezza (v0.5.0)

Setup Iniziale JWT

  1. Genera JWT Secret:

    openssl rand -hex 32
    
  2. Configura .env:

    JWT_SECRET_KEY=<generated-secret>
    JWT_ALGORITHM=HS256
    ACCESS_TOKEN_EXPIRE_MINUTES=30
    REFRESH_TOKEN_EXPIRE_DAYS=7
    BCRYPT_ROUNDS=12
    
  3. Verifica sicurezza:

    # Controlla che JWT_SECRET_KEY sia >= 32 caratteri
    echo $JWT_SECRET_KEY | wc -c
    # Deve mostrare 65+ (64 hex chars + newline)
    

Rate Limiting

I limiti sono configurati automaticamente:

Endpoint Limite Finestra
/auth/* 5 req 1 minuto
/api-keys/* 10 req 1 minuto
/reports/* 10 req 1 minuto
API generale 100 req 1 minuto
/ingest 1000 req 1 minuto

HTTPS in Produzione

Per produzione, configura HTTPS obbligatorio:

server {
    listen 443 ssl http2;
    server_name api.mockupaws.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    ssl_protocols TLSv1.3;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    location / {
        proxy_pass http://backend:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name api.mockupaws.com;
    return 301 https://$server_name$request_uri;
}

Documentazione Sicurezza

Roadmap

v0.2.0 Completata

  • API ingestion base
  • Calcolo metriche (SQS, Lambda, Bedrock)
  • Database PostgreSQL con SQLAlchemy 2.0 async
  • Tabelle scenari e persistenza
  • Tabella prezzi AWS (seed dati per us-east-1, eu-west-1)
  • Migrazioni Alembic (6 migrations)
  • Repository pattern + Services layer
  • PII detection e cost calculation

v0.3.0 Completata

  • Frontend React 18 con Vite
  • Dashboard responsive con Tailwind CSS
  • Form creazione/modifica scenari
  • Lista scenari con paginazione
  • Pagina dettaglio scenario
  • Integrazione API con Axios + React Query
  • Componenti UI shadcn/ui

v0.4.0 Completata (2026-04-07)

  • Generazione report PDF/CSV con ReportLab
  • Confronto scenari (2-4 scenari side-by-side)
  • Grafici interattivi con Recharts (Pie, Area, Bar)
  • Dark/Light mode toggle con rilevamento sistema
  • E2E Testing suite con 100 test cases (Playwright)

v0.5.0 Completata (2026-04-07)

  • Database migrations (users, api_keys, report_schedules)
  • JWT implementation (HS256, 30min access, 7days refresh)
  • bcrypt password hashing (cost=12)
  • Auth API endpoints (/auth/*)
  • API Keys service (generazione, validazione, hashing)
  • API Keys endpoints (/api-keys/*)
  • Protected route middleware
  • Report scheduling service (database pronto)
  • Email service (SendGrid/AWS SES configurazione)
  • Frontend auth integration
  • Security documentation

v1.0.0 Completata (2026-04-07)

  • Backup automatico database con PITR (RTO<1h)
  • Documentazione API completa (OpenAPI + examples)
  • Performance optimizations (Redis, bundle 308KB, p95<200ms)
  • Production deployment guide (Terraform, CI/CD, AWS)
  • Redis caching layer (3-tier strategy)
  • 99.9% uptime monitoring e alerting
  • Security audit completa (0 vulnerabilità critiche)
  • SLA definition e incident response
  • 153+ E2E tests (85% coverage)

Contributi

Contributi sono benvenuti! Per favore:

  1. Fork il repository
  2. Crea un branch feature (git checkout -b feature/amazing-feature)
  3. Commit le modifiche (git commit -m 'feat: add amazing feature')
  4. Push al branch (git push origin feature/amazing-feature)
  5. Apri una Pull Request

Licenza

Distribuito sotto licenza MIT. Vedi LICENSE per dettagli.


MockupAWS - Parte del progetto LogWhispererAI
Stima i costi AWS prima di spenderli davvero