diff --git a/control-plane/api/cmd/api/main.go b/control-plane/api/cmd/api/main.go index 25bef60..e70d731 100644 --- a/control-plane/api/cmd/api/main.go +++ b/control-plane/api/cmd/api/main.go @@ -20,6 +20,7 @@ import ( "github.com/omnex/control-plane/api/internal/config" "github.com/omnex/control-plane/api/internal/db" "github.com/omnex/control-plane/api/internal/demos" + "github.com/omnex/control-plane/api/internal/downloads" "github.com/omnex/control-plane/api/internal/k8s" "github.com/omnex/control-plane/api/internal/profile" "github.com/omnex/control-plane/api/internal/router" @@ -184,13 +185,14 @@ func main() { } deps := router.Deps{ - Cfg: cfg, - Issuer: iss, - Sessions: sessions, - AuthH: auth.NewHandler(userStore, sessions, iss, cfg.Secure()), - DemosH: demos.NewHandler(demoSvc, helmProv), - SubH: sub.NewHandler(codeStore, demoSvc), - ProfileH: profile.NewHandler(profileStore), + Cfg: cfg, + Issuer: iss, + Sessions: sessions, + AuthH: auth.NewHandler(userStore, sessions, iss, cfg.Secure()), + DemosH: demos.NewHandler(demoSvc, helmProv), + SubH: sub.NewHandler(codeStore, demoSvc), + ProfileH: profile.NewHandler(profileStore), + DownloadsH: downloads.NewHandler(cfg.AppDownloadsDir, userStore, demoSvc), } r := router.New(deps) diff --git a/control-plane/api/internal/config/config.go b/control-plane/api/internal/config/config.go index bbbd034..935c5c3 100644 --- a/control-plane/api/internal/config/config.go +++ b/control-plane/api/internal/config/config.go @@ -21,6 +21,7 @@ type Config struct { FrontendImage string BackendImage string LBTelegramImage string + AppDownloadsDir string // OMNEX_APP_DOWNLOADS_DIR : répertoire des .apk téléchargeables (voir internal/downloads) } // Load lit la config. Fail-secure : secret JWT obligatoire ; en prod base + Redis aussi. @@ -45,6 +46,7 @@ func Load() (Config, error) { FrontendImage: os.Getenv("FRONTEND_IMAGE_APP"), BackendImage: os.Getenv("BACKEND_IMAGE_APP"), LBTelegramImage: os.Getenv("LBTELEGRAM_IMAGE_APP"), + AppDownloadsDir: getenv("OMNEX_APP_DOWNLOADS_DIR", "/app-downloads"), } if cfg.Env == "prod" { diff --git a/control-plane/api/internal/downloads/handler.go b/control-plane/api/internal/downloads/handler.go new file mode 100644 index 0000000..5b835a4 --- /dev/null +++ b/control-plane/api/internal/downloads/handler.go @@ -0,0 +1,135 @@ +// Package downloads expose les applications mobiles (.apk) téléchargeables +// par un client ayant une démo active ou un abonnement premium en cours. +// Les fichiers sont déposés manuellement (pas de build automatisé) dans le +// répertoire configuré (voir config.AppDownloadsDir) : le contenu du +// répertoire est listé dynamiquement, aucun nom de fichier n'est en dur. +package downloads + +import ( + "net/http" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "github.com/omnex/control-plane/api/internal/auth" + "github.com/omnex/control-plane/api/internal/demos" +) + +type App struct { + Name string `json:"name"` + SizeBytes int64 `json:"size_bytes"` +} + +type Handler struct { + dir string + users auth.UserStore + demos *demos.Service // optionnel : nil => éligibilité basée uniquement sur l'abonnement +} + +func NewHandler(dir string, users auth.UserStore, demoSvc *demos.Service) *Handler { + return &Handler{dir: dir, users: users, demos: demoSvc} +} + +// eligible : démo active OU abonnement premium non expiré. +func (h *Handler) eligible(username string) (bool, error) { + if user, found := h.users.ByUsername(username); found { + if user.TypeAbo == "premium" && time.Now().UTC().Before(user.ExpiredAt) { + return true, nil + } + } + if h.demos == nil { + return false, nil + } + list, err := h.demos.ListForUser(username) + if err != nil { + return false, err + } + for _, d := range list { + if d.Status.Active() { + return true, nil + } + } + return false, nil +} + +// List renvoie les apps disponibles et si le client courant a le droit de +// les télécharger — la liste reste visible même si non éligible, pour +// afficher un message explicite côté front plutôt qu'une page vide. +func (h *Handler) List(c *gin.Context) { + p := auth.PrincipalFrom(c) + if p == nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"}) + return + } + ok, err := h.eligible(p.Username) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "erreur serveur"}) + return + } + apps, err := h.listFiles() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "erreur serveur"}) + return + } + c.JSON(http.StatusOK, gin.H{"eligible": ok, "items": apps}) +} + +// Download sert un fichier .apk du répertoire — revérifie l'éligibilité +// côté serveur (le flag "eligible" de List n'est qu'un affichage). +func (h *Handler) Download(c *gin.Context) { + p := auth.PrincipalFrom(c) + if p == nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "non authentifié"}) + return + } + ok, err := h.eligible(p.Username) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "erreur serveur"}) + return + } + if !ok { + c.JSON(http.StatusForbidden, gin.H{"error": "démo ou abonnement actif requis"}) + return + } + + name := c.Param("name") + // Un seul segment de chemin, extension .apk uniquement : exclut toute + // tentative de traversée de répertoire (pas de "/" ni "\\" autorisés). + if name == "" || strings.ContainsAny(name, "/\\") || filepath.Ext(name) != ".apk" { + c.JSON(http.StatusBadRequest, gin.H{"error": "nom de fichier invalide"}) + return + } + full := filepath.Join(h.dir, name) + if _, err := os.Stat(full); err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "fichier introuvable"}) + return + } + c.FileAttachment(full, name) +} + +func (h *Handler) listFiles() ([]App, error) { + entries, err := os.ReadDir(h.dir) + if err != nil { + if os.IsNotExist(err) { + return []App{}, nil + } + return nil, err + } + out := make([]App, 0, len(entries)) + for _, e := range entries { + if e.IsDir() || filepath.Ext(e.Name()) != ".apk" { + continue + } + info, err := e.Info() + if err != nil { + continue + } + out = append(out, App{Name: e.Name(), SizeBytes: info.Size()}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} diff --git a/control-plane/api/internal/router/router.go b/control-plane/api/internal/router/router.go index 9fa833b..309c348 100644 --- a/control-plane/api/internal/router/router.go +++ b/control-plane/api/internal/router/router.go @@ -9,6 +9,7 @@ import ( "github.com/omnex/control-plane/api/internal/auth" "github.com/omnex/control-plane/api/internal/config" "github.com/omnex/control-plane/api/internal/demos" + "github.com/omnex/control-plane/api/internal/downloads" "github.com/omnex/control-plane/api/internal/httpx" "github.com/omnex/control-plane/api/internal/profile" "github.com/omnex/control-plane/api/internal/session" @@ -17,13 +18,14 @@ import ( // Deps : dépendances injectées (facilite les tests). type Deps struct { - Cfg config.Config - Issuer *auth.Issuer - Sessions session.Manager - AuthH *auth.Handler - DemosH *demos.Handler - SubH *sub.Handler - ProfileH *profile.Handler + Cfg config.Config + Issuer *auth.Issuer + Sessions session.Manager + AuthH *auth.Handler + DemosH *demos.Handler + SubH *sub.Handler + ProfileH *profile.Handler + DownloadsH *downloads.Handler } // New construit l'engine Gin avec toute la chaîne de sécurité. @@ -61,6 +63,10 @@ func New(d Deps) *gin.Engine { if d.DemosH != nil { client.GET("/demos/mine", d.DemosH.ListMine) } + if d.DownloadsH != nil { + client.GET("/apps", d.DownloadsH.List) + client.GET("/apps/:name", d.DownloadsH.Download) + } } // Espace admin : provisioning des démos (admin uniquement). admin := authed.Group("") diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index e5b41c7..4429c79 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -13,7 +13,6 @@ services: interval: 5s timeout: 3s retries: 10 - # Pas de port exposé : accès interne uniquement (défense en profondeur). redis: image: redis:7-alpine @@ -33,8 +32,26 @@ services: depends_on: api: condition: service_healthy + + waf: + image: xor1234/omnex-waf:latest + restart: unless-stopped + environment: + - DISABLE_MODSEC_ENV_SUBST=true + - PARANOIA=2 + - ANOMALY_INBOUND=5 + - ANOMALY_OUTBOUND=4 + - MODSEC_AUDIT_LOG=/var/log/modsec/modsec_audit.log + volumes: + - ./nginx/certs:/etc/nginx/certs:ro + - /var/log/waf/nginx:/var/log/nginx + - /var/log/waf/modsec:/var/log/modsec ports: - - "3000:80" + - "80:80" + - "443:443" + depends_on: + - web + - api api: image: xor1234/omnex-api:latest @@ -59,22 +76,20 @@ services: BACKEND_IMAGE_APP: ${BACKEND_IMAGE_APP:-xor1234/backend-mln:helm} LBTELEGRAM_IMAGE_APP: ${LBTELEGRAM_IMAGE_APP:-xor1234/lbtelegram:helm} KUBECONFIG: /kubeconfig/config + OMNEX_APP_DOWNLOADS_DIR: /app-downloads volumes: - ../deploy/chart-gestion:/charts:ro - - /home/xor_fakers/.kube/config:/kubeconfig/config:ro + - ${KUBECONFIG_HOST_PATH:-/home/xor_fakers/.kube/config}:/kubeconfig/config:ro + # Dossier où déposer manuellement les .apk (Admin Panel / Client) à + # rendre téléchargeables aux clients ayant une démo ou un abonnement + # actif — voir control-plane/api/internal/downloads. + - ../app:/app-downloads:ro healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/healthz"] interval: 5s timeout: 3s retries: 10 - # Le temps que le fix "EnsureSharedInfra en arrière-plan" soit déployé - # (voir control-plane/api/cmd/api/main.go) : laisse la marge pour que - # le "helm upgrade --install --wait --timeout 5m" bloquant échoue tout - # seul si le cluster est injoignable, plutôt que de faire échouer - # `docker compose up` avant même que le serveur HTTP démarre. start_period: 330s - ports: - - "8080:8080" volumes: pgdata: diff --git a/docker/waf/Dockerfile b/docker/waf/Dockerfile new file mode 100644 index 0000000..aa8e521 --- /dev/null +++ b/docker/waf/Dockerfile @@ -0,0 +1,18 @@ +# WAF (Nginx + ModSecurity/OWASP CRS) — même pattern que +# projet_gestion_commande/docker-prod/backend/Dockerfile (stage "waf") : +# seul point de terminaison TLS + reverse-proxy devant web/api. +FROM owasp/modsecurity-crs:nginx-alpine + +USER root + +RUN mkdir -p /var/log/modsec /etc/nginx/certs && \ + chown -R nginx:nginx /var/log/modsec /etc/nginx/certs /usr/share/nginx/html + +COPY nginx.conf /etc/nginx/conf.d/app.conf +COPY custom-rules.conf /etc/nginx/modsec/custom-rules.conf +RUN echo "Include /etc/nginx/modsec/custom-rules.conf" > /etc/nginx/modsec/custom-includes.conf && \ + rm -f /etc/nginx/templates/conf.d/default.conf.template || true + +USER nginx +EXPOSE 80 443 +CMD ["nginx", "-g", "daemon off;"] diff --git a/docker/waf/custom-rules.conf b/docker/waf/custom-rules.conf new file mode 100644 index 0000000..186d3a9 --- /dev/null +++ b/docker/waf/custom-rules.conf @@ -0,0 +1,48 @@ +# Exclure le corps des requêtes/réponses de l'audit log pour garder des +# lignes de taille raisonnable. +SecAuditLogParts ABIFHZ + +SecRule IP:BANNED "@eq 1" \ + "id:100000,phase:1,deny,status:403,log,\ + msg:'IP is banned'" + +SecRule IP:REPUTATION_SCORE "@ge 100" \ + "id:100099,phase:1,deny,status:403,log,\ + msg:'Critical reputation score',\ + setvar:'ip.blocked=1',expirevar:'ip.blocked=86400'" + +SecRule TX:SQL_INJECTION_SCORE "@ge 5" \ + "id:100001,phase:2,deny,status:403,log,\ + msg:'SQL Injection detected',\ + setvar:'ip.banned=1',expirevar:'ip.banned=172800'" + +SecRule TX:XSS_SCORE "@ge 5" \ + "id:100010,phase:2,deny,status:403,log,\ + msg:'XSS detected',\ + setvar:'ip.banned=1',expirevar:'ip.banned=172800'" + +SecRule TX:RCE_SCORE "@ge 5" \ + "id:100020,phase:2,deny,status:403,log,\ + msg:'RCE detected',\ + setvar:'ip.banned=1',expirevar:'ip.banned=259200'" + +SecRule TX:LFI_SCORE "@ge 5" \ + "id:100030,phase:2,deny,status:403,log,\ + msg:'LFI detected',\ + setvar:'ip.banned=1',expirevar:'ip.banned=172800'" + +SecRule TX:INBOUND_ANOMALY_SCORE "@ge 20" \ + "id:100060,phase:2,deny,status:403,log,\ + msg:'Critical anomaly score',\ + setvar:'ip.banned=1',expirevar:'ip.banned=172800'" + +# Rate limit basique par IP (indépendant du RateLimit Go déjà en place sur +# /auth/login côté control-plane — celui-ci protège tout le reste). +SecAction \ + "id:400161,phase:1,nolog,pass,\ + setvar:'ip.request_window_1sec=+1',\ + expirevar:'ip.request_window_1sec=1'" + +SecRule IP:REQUEST_WINDOW_1SEC "@gt 20" \ + "id:400160,phase:1,deny,status:429,log,\ + msg:'Too many requests'" diff --git a/docker/waf/nginx.conf b/docker/waf/nginx.conf new file mode 100644 index 0000000..1007dae --- /dev/null +++ b/docker/waf/nginx.conf @@ -0,0 +1,138 @@ +# Request ID correlation +map $http_x_request_id $req_id { + default $http_x_request_id; + "" $request_id; +} + +# HTTP → HTTPS +server { + listen 80; + listen [::]:80; + server_name _; + + return 301 https://$host$request_uri; +} + +# HTTPS — Hardened + ModSecurity +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name _; + + server_tokens off; + + # --------------------------------------------------- + # TLS (certs copiés par ansible/playbook-certbot.yml, voir + # docker-compose.yml service waf) + # --------------------------------------------------- + ssl_certificate /etc/nginx/certs/fullchain.pem; + ssl_certificate_key /etc/nginx/certs/privkey.pem; + + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256; + ssl_prefer_server_ciphers off; + + ssl_session_cache shared:SSL:10m; + ssl_session_timeout 1d; + ssl_session_tickets off; + + resolver 127.0.0.11 valid=10s ipv6=off; + resolver_timeout 5s; + + # --------------------------------------------------- + # En-têtes de sécurité + # --------------------------------------------------- + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; + add_header X-Frame-Options "DENY" always; + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "no-referrer" always; + add_header Content-Security-Policy "default-src 'none'; frame-ancestors 'none'" always; + + # --------------------------------------------------- + # Limites et timeouts + # --------------------------------------------------- + client_max_body_size 10M; + client_body_buffer_size 128k; + client_header_buffer_size 1k; + large_client_header_buffers 4 8k; + + client_body_timeout 30s; + client_header_timeout 30s; + send_timeout 30s; + keepalive_timeout 65s; + + # --------------------------------------------------- + # ModSecurity WAF + # --------------------------------------------------- + modsecurity on; + modsecurity_rules_file /etc/nginx/modsec/custom-rules.conf; + + # --------------------------------------------------- + # API control-plane Go (voir control-plane/api/internal/router) + # --------------------------------------------------- + location /api/ { + limit_except GET POST PATCH DELETE OPTIONS { deny all; } + + set $upstream_api http://api:8080; + proxy_pass $upstream_api; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Request-ID $req_id; + proxy_hide_header X-Powered-By; + + proxy_connect_timeout 60s; + proxy_send_timeout 300s; + proxy_read_timeout 300s; + } + + location = /healthz { + set $upstream_api http://api:8080; + proxy_pass $upstream_api; + } + + # --------------------------------------------------- + # Frontend React SPA + # --------------------------------------------------- + location / { + set $upstream_web http://web:80; + proxy_pass $upstream_web; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # --------------------------------------------------- + # Blocage fichiers sensibles / scans courants + # --------------------------------------------------- + location ~ /\. { + deny all; + access_log off; + log_not_found off; + } + + location ~* \.(env|git|sql|bak|log|conf|ini|sh)$ { + deny all; + access_log off; + log_not_found off; + } + + location ~* (package\.json|package-lock\.json|yarn\.lock|Dockerfile|docker-compose)$ { + deny all; + access_log off; + log_not_found off; + } + + location ~* (wp-admin|wp-login|wp-content|xmlrpc|\.php)$ { + deny all; + access_log off; + log_not_found off; + } +} diff --git a/web/src/App.tsx b/web/src/App.tsx index 6f8de39..a3f96a9 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -10,6 +10,7 @@ import { Demos } from './pages/backoffice/Demos' import { PremiumDemos } from './pages/backoffice/PremiumDemos' import { Codes } from './pages/backoffice/Codes' import { Subscription } from './pages/backoffice/Subscription' +import { AppDownloads } from './pages/backoffice/AppDownloads' import { Profile } from './pages/backoffice/Profile' import { PublicLayout } from './components/PublicLayout' import { BackofficeLayout } from './components/BackofficeLayout' @@ -103,6 +104,7 @@ export function App() { } /> } /> + } /> } /> diff --git a/web/src/components/BackofficeLayout.tsx b/web/src/components/BackofficeLayout.tsx index 7e69da9..8cc2f86 100644 --- a/web/src/components/BackofficeLayout.tsx +++ b/web/src/components/BackofficeLayout.tsx @@ -55,6 +55,7 @@ export function BackofficeLayout() { {isClient && Abonnement} + {isClient && Applications} {(isAdmin || isClient) && Profile} {isAdmin && Démos} {isAdmin && Premium} @@ -99,6 +100,11 @@ export function BackofficeLayout() { Abonnement )} + {isClient && ( + + Applications + + )} {isAdmin && ( Démos diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 9de214c..688d8a4 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -147,6 +147,16 @@ export interface AlertSettings { telegram_chat_id: string } +export interface AppDownload { + name: string + size_bytes: number +} + +export interface AppDownloadsResponse { + eligible: boolean + items: AppDownload[] +} + // --- Endpoints --- export const api = { @@ -221,4 +231,13 @@ export const api = { getAlertSettings: () => request('GET', '/profile/alerts'), setAlertSettings: (settings: AlertSettings) => request('POST', '/profile/alerts', settings), + + listAppDownloads: () => request('GET', '/apps'), +} + +// URL de téléchargement direct d'une app — le cookie de session httpOnly +// suffit à authentifier la navigation (voir auth.tokenFromRequest côté API), +// pas besoin de fetch + blob. +export function appDownloadUrl(name: string): string { + return `${BASE}/api/v1/apps/${encodeURIComponent(name)}` } diff --git a/web/src/lib/format.ts b/web/src/lib/format.ts index 39b2d2b..47f3633 100644 --- a/web/src/lib/format.ts +++ b/web/src/lib/format.ts @@ -72,6 +72,19 @@ export function timeRemaining(expiresAt: string, now: number = Date.now()): stri return `${hours} h ${mins} min` } +// Taille de fichier lisible (ex. "42.3 Mo"). +export function formatFileSize(bytes: number): string { + if (bytes < 1024) return `${bytes} o` + const units = ['Ko', 'Mo', 'Go'] + let value = bytes / 1024 + let unitIndex = 0 + while (value >= 1024 && unitIndex < units.length - 1) { + value /= 1024 + unitIndex += 1 + } + return `${value.toFixed(1)} ${units[unitIndex]}` +} + export function formatDate(iso: string): string { return new Date(iso).toLocaleDateString('fr-FR', { day: '2-digit', diff --git a/web/src/pages/backoffice/AppDownloads.tsx b/web/src/pages/backoffice/AppDownloads.tsx new file mode 100644 index 0000000..92d2862 --- /dev/null +++ b/web/src/pages/backoffice/AppDownloads.tsx @@ -0,0 +1,92 @@ +import { useCallback, useEffect, useState } from 'react' +import { + Box, + Button, + Flex, + HStack, + Heading, + Spacer, + Spinner, + Stack, + Text, + VStack, + useToast, +} from '@chakra-ui/react' +import { useNavigate } from 'react-router-dom' +import { api, ApiError, appDownloadUrl, type AppDownload } from '../../lib/api' +import { formatFileSize } from '../../lib/format' + +const DownloadIcon = () => ( + + + +) + +export function AppDownloads() { + const toast = useToast() + const navigate = useNavigate() + const [items, setItems] = useState([]) + const [eligible, setEligible] = useState(false) + const [loading, setLoading] = useState(true) + + const load = useCallback(async () => { + try { + const res = await api.listAppDownloads() + setItems(res.items ?? []) + setEligible(res.eligible) + } catch (err) { + if (err instanceof ApiError && err.status === 401) navigate('/login') + else toast({ status: 'error', title: 'Chargement des applications impossible' }) + } finally { + setLoading(false) + } + }, [navigate, toast]) + + useEffect(() => { + void load() + }, [load]) + + return ( + <> + + Applications + + + + + {loading ? ( + + ) : !eligible ? ( + + Le téléchargement des applications nécessite une démo ou un abonnement actif. + + ) : items.length === 0 ? ( + Aucune application disponible pour le moment. + ) : ( + + {items.map((item) => ( + + + {item.name} + + {formatFileSize(item.size_bytes)} + + + + + ))} + + )} + + + ) +}