Compare commits
No commits in common. "38a2e08062f8ee6044ce22c27bba296d028feaa5" and "99e01f97fc3471e7e42d56fe3e22939d48c79f6b" have entirely different histories.
38a2e08062
...
99e01f97fc
@ -1,2 +1,3 @@
|
||||
# All jobs use the existing ubuntu-latest runner label.
|
||||
{}
|
||||
self-hosted-runner:
|
||||
labels:
|
||||
- xpeditis-deploy
|
||||
|
||||
@ -231,11 +231,8 @@ jobs:
|
||||
PLATFORM: linux/${{ matrix.arch }}
|
||||
run: |
|
||||
trivy image --platform "$PLATFORM" --scanners vuln --severity HIGH,CRITICAL \
|
||||
--ignore-unfixed=false --exit-code 1 --timeout 15m --no-progress --format json \
|
||||
--ignore-unfixed=false --exit-code 1 --timeout 15m --format json \
|
||||
--output "$RUNNER_TEMP/image-security.json" "$IMAGE"
|
||||
- name: Show image scan results
|
||||
if: always()
|
||||
run: python3 scripts/ci/summarize-image-security.py
|
||||
- name: Save image report
|
||||
if: always()
|
||||
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
|
||||
@ -248,8 +245,9 @@ jobs:
|
||||
# ═══ 4. Déploiement ══════════════════════════════════════════════════════
|
||||
deploy:
|
||||
name: Déployer en production
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: xpeditis-deploy
|
||||
needs: [verify-image, build-frontend, image-security]
|
||||
# Gitea 1.22 ignores environments: serialize on the dedicated deployment runner.
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
|
||||
@ -9,10 +9,9 @@ name: CD Preprod
|
||||
# NEXT_PUBLIC_APP_URL — https://preprod.xpeditis.com
|
||||
# PORTAINER_WEBHOOK_BACKEND — Portainer webhook (preprod backend)
|
||||
# PORTAINER_WEBHOOK_FRONTEND— Portainer webhook (preprod frontend)
|
||||
# PREPROD_BACKEND_URL — https://api.preprod.xpeditis.com
|
||||
# PREPROD_FRONTEND_URL — https://preprod.xpeditis.com
|
||||
# DISCORD_WEBHOOK_URL
|
||||
# Optional health URL overrides (secrets, then repository variables):
|
||||
# PREPROD_BACKEND_URL — defaults to https://api.preprod.xpeditis.com
|
||||
# PREPROD_FRONTEND_URL — defaults to https://app.preprod.xpeditis.com
|
||||
|
||||
on:
|
||||
push:
|
||||
@ -313,11 +312,8 @@ jobs:
|
||||
PLATFORM: linux/${{ matrix.arch }}
|
||||
run: |
|
||||
trivy image --platform "$PLATFORM" --scanners vuln --severity HIGH,CRITICAL \
|
||||
--ignore-unfixed=false --exit-code 1 --timeout 15m --no-progress --format json \
|
||||
--ignore-unfixed=false --exit-code 1 --timeout 15m --format json \
|
||||
--output "$RUNNER_TEMP/image-security.json" "$IMAGE"
|
||||
- name: Show image scan results
|
||||
if: always()
|
||||
run: python3 scripts/ci/summarize-image-security.py
|
||||
- name: Save image report
|
||||
if: always()
|
||||
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
|
||||
@ -330,7 +326,7 @@ jobs:
|
||||
# ── 5. Deploy via Portainer ──────────────────────────────────────────
|
||||
deploy:
|
||||
name: Deploy to Preprod
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: xpeditis-deploy
|
||||
needs: [build-backend, build-frontend, build-log-exporter, image-security]
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
@ -381,12 +377,12 @@ jobs:
|
||||
|
||||
- name: Verify backend health
|
||||
env:
|
||||
BASE_URL: ${{ secrets.PREPROD_BACKEND_URL || vars.PREPROD_BACKEND_URL || 'https://api.preprod.xpeditis.com' }}
|
||||
run: bash scripts/ci/health-check.sh "${BASE_URL%/}/api/v1/health"
|
||||
BASE_URL: ${{ secrets.PREPROD_BACKEND_URL }}
|
||||
run: bash scripts/ci/health-check.sh "${BASE_URL:?Missing PREPROD_BACKEND_URL}/api/v1/health"
|
||||
- name: Verify frontend health
|
||||
env:
|
||||
BASE_URL: ${{ secrets.PREPROD_FRONTEND_URL || vars.PREPROD_FRONTEND_URL || 'https://app.preprod.xpeditis.com' }}
|
||||
run: bash scripts/ci/health-check.sh "${BASE_URL%/}/api/health"
|
||||
BASE_URL: ${{ secrets.PREPROD_FRONTEND_URL }}
|
||||
run: bash scripts/ci/health-check.sh "${BASE_URL:?Missing PREPROD_FRONTEND_URL}"
|
||||
|
||||
- name: Mark successfully deployed preprod images
|
||||
env:
|
||||
|
||||
@ -40,10 +40,6 @@ RUN npm prune --production --legacy-peer-deps
|
||||
# ===============================================
|
||||
FROM node:22-alpine AS production
|
||||
|
||||
# Runtime starts with node; remove the base image package manager and its dependencies.
|
||||
# npm remains available in the dependency and build stages.
|
||||
RUN npm uninstall --global npm
|
||||
|
||||
# Install dumb-init for proper signal handling
|
||||
RUN apk add --no-cache dumb-init
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import * as request from 'supertest';
|
||||
import { AppModule } from '../src/app.module';
|
||||
|
||||
describe('AppController (e2e)', () => {
|
||||
|
||||
@ -1,45 +0,0 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { RedisCacheAdapter } from '../../src/infrastructure/cache/redis-cache.adapter';
|
||||
|
||||
describe('Redis cache integration', () => {
|
||||
let cache: RedisCacheAdapter;
|
||||
const prefix = `integration:${randomUUID()}:`;
|
||||
const keys = ['value', 'expires'].map(key => `${prefix}${key}`);
|
||||
|
||||
beforeAll(async () => {
|
||||
cache = new RedisCacheAdapter(
|
||||
new ConfigService({
|
||||
REDIS_HOST: process.env.REDIS_HOST,
|
||||
REDIS_PORT: Number(process.env.REDIS_PORT),
|
||||
REDIS_PASSWORD: process.env.REDIS_PASSWORD || undefined,
|
||||
REDIS_DB: Number(process.env.REDIS_DB),
|
||||
})
|
||||
);
|
||||
await cache.onModuleInit();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
// Delete only this suite's keys; never flush a shared database.
|
||||
await cache.deleteMany(keys);
|
||||
} finally {
|
||||
await cache.onModuleDestroy();
|
||||
}
|
||||
});
|
||||
|
||||
it('round-trips cached application data and invalidates it', async () => {
|
||||
const value = { amount: 125.5, currency: 'EUR', ports: ['FRLEH', 'USNYC'] };
|
||||
await cache.set(keys[0], value, 60);
|
||||
expect(await cache.get(keys[0])).toEqual(value);
|
||||
await cache.delete(keys[0]);
|
||||
expect(await cache.get(keys[0])).toBeNull();
|
||||
});
|
||||
|
||||
it('expires cached data using the server TTL', async () => {
|
||||
await cache.set(keys[1], { valid: true }, 1);
|
||||
expect(await cache.exists(keys[1])).toBe(true);
|
||||
await new Promise(resolve => setTimeout(resolve, 1200));
|
||||
expect(await cache.exists(keys[1])).toBe(false);
|
||||
});
|
||||
});
|
||||
@ -1,10 +1,7 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": "../",
|
||||
"testMatch": [
|
||||
"<rootDir>/test/integration/**/*.spec.ts",
|
||||
"<rootDir>/src/infrastructure/persistence/typeorm/repositories/typeorm-trade-quota.repository.spec.ts"
|
||||
],
|
||||
"testMatch": ["**/test/integration/**/*.spec.ts"],
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": [
|
||||
"ts-jest",
|
||||
@ -22,7 +19,7 @@
|
||||
"testEnvironment": "node",
|
||||
"moduleNameMapper": {
|
||||
"^@domain/(.*)$": "<rootDir>/src/domain/$1",
|
||||
"^@application/(.*)$": "<rootDir>/src/application/$1",
|
||||
"@application/(.*)$": "<rootDir>/src/application/$1",
|
||||
"^@infrastructure/(.*)$": "<rootDir>/src/infrastructure/$1"
|
||||
},
|
||||
"transformIgnorePatterns": ["node_modules/(?!(@faker-js)/)"],
|
||||
|
||||
@ -11,18 +11,6 @@ process.env.TEST_DB_USER = process.env.TEST_DB_USER || 'postgres';
|
||||
process.env.TEST_DB_PASSWORD = process.env.TEST_DB_PASSWORD || 'postgres';
|
||||
process.env.TEST_DB_NAME = process.env.TEST_DB_NAME || 'xpeditis_test';
|
||||
|
||||
// Enable the repository integration suite using the disposable CI service.
|
||||
// Never fall back to DATABASE_* (the application's deployment connection).
|
||||
if (!process.env.TRADE_TEST_DATABASE_URL) {
|
||||
const database = new URL('postgresql://localhost');
|
||||
database.hostname = process.env.TEST_DB_HOST;
|
||||
database.port = process.env.TEST_DB_PORT;
|
||||
database.username = process.env.TEST_DB_USER;
|
||||
database.password = process.env.TEST_DB_PASSWORD;
|
||||
database.pathname = `/${process.env.TEST_DB_NAME}`;
|
||||
process.env.TRADE_TEST_DATABASE_URL = database.toString();
|
||||
}
|
||||
|
||||
// Redis test configuration
|
||||
process.env.REDIS_HOST = process.env.REDIS_HOST || 'localhost';
|
||||
process.env.REDIS_PORT = process.env.REDIS_PORT || '6379';
|
||||
|
||||
@ -50,10 +50,6 @@ RUN npm run build
|
||||
# ===============================================
|
||||
FROM node:22-alpine AS production
|
||||
|
||||
# Runtime starts with node; remove the base image package manager and its dependencies.
|
||||
# npm remains available in the dependency and build stages.
|
||||
RUN npm uninstall --global npm
|
||||
|
||||
# Install dumb-init for proper signal handling
|
||||
RUN apk add --no-cache dumb-init curl
|
||||
|
||||
|
||||
@ -5,9 +5,6 @@ WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
# Only Node and application dependencies are needed at runtime.
|
||||
RUN npm uninstall --global npm
|
||||
|
||||
COPY src/ ./src/
|
||||
|
||||
EXPOSE 3200
|
||||
|
||||
@ -80,31 +80,21 @@ comme des protections effectives dans les workflows adaptés.
|
||||
Docker. Les builds multiarchitecture ont besoin du support QEMU/binfmt.
|
||||
Les services d'intégration sont joints via `postgres` et `redis`, sans ports
|
||||
hôte fixes ; un runner en mode host n'est pas la cible de ces workflows.
|
||||
2. Les déploiements préprod et production utilisent le runner existant avec le
|
||||
label **`ubuntu-latest`**, comme les builds et les audits. Aucun runner dédié
|
||||
`xpeditis-deploy` n'est nécessaire. Ce runner doit aussi disposer de SSH et
|
||||
rsync pour le déploiement de production. Gitea 1.22 ne prenant pas en charge
|
||||
`concurrency`, les workflows ne garantissent pas la sérialisation des
|
||||
déploiements si les runners autorisent plusieurs jobs simultanés.
|
||||
Pour éviter les chevauchements, attendre la fin d'un déploiement avant de
|
||||
déclencher le suivant sur le même environnement.
|
||||
2. Enregistrer **un seul runner** avec le label **`xpeditis-deploy`**, une capacité
|
||||
**1**, et une limite d'exécution adaptée (par exemple 1 h). Les deux jobs de
|
||||
déploiement utilisent ce label : publication des alias, déploiement, santé et
|
||||
fermeture du firewall restent dans le même job. Ne pas donner ce label à
|
||||
plusieurs runners. Le runner doit être isolé des jobs de PR et disposer de
|
||||
Docker, Git, curl, SSH et rsync. Sans ce runner, les déploiements restent en attente.
|
||||
3. Protéger `dev`, `preprod`, `main` dans les réglages de branches Gitea : interdire
|
||||
les push directs/force-push et exiger **Security gate**, les deux contrôles
|
||||
qualité et les deux tests unitaires ; ajouter l'intégration pour preprod/main.
|
||||
Choisir les noms exacts proposés après la première exécution. Les approbations
|
||||
humaines doivent être imposées sur les PR, pas via `environment`.
|
||||
4. Renseigner les secrets/variables dans **Settings → Actions** du dépôt Gitea :
|
||||
registre, webhooks Portainer, URLs de build et identifiants
|
||||
registre, webhooks Portainer, URLs préprod, URLs de build et identifiants
|
||||
SSH/Hetzner déjà référencés. Les secrets ne sont pas des secrets d'environnement
|
||||
GitHub. Les clés SSH temporaires sont écrites dans le répertoire du job.
|
||||
Les contrôles de santé préprod utilisent par défaut
|
||||
`https://api.preprod.xpeditis.com/api/v1/health` et
|
||||
`https://app.preprod.xpeditis.com/api/health`, conformément aux routes Traefik
|
||||
de la stack. Le contrôle frontend cible son endpoint de santé pour éviter
|
||||
la redirection HTTP 307 de la page d’accueil.
|
||||
`PREPROD_BACKEND_URL` et `PREPROD_FRONTEND_URL` sont des surcharges facultatives
|
||||
(URL de base sans chemin API), lues dans les secrets puis les variables du dépôt.
|
||||
Une réponse HTTP 200 reste obligatoire pour valider le déploiement.
|
||||
5. Les fonctions manuelles `workflow_dispatch` ne sont pas disponibles sur 1.22.
|
||||
L'ancien workflow de rollback est conservé hors du dossier actif dans
|
||||
`.gitea/manual/rollback.reference.yml` comme référence, sans prétendre qu'il est
|
||||
@ -244,34 +234,3 @@ exécution Gitea n'est effectué par cette correction locale.
|
||||
Sources : [migration Next 15](https://nextjs.org/docs/app/guides/upgrading/version-15),
|
||||
[distribution SheetJS](https://docs.sheetjs.com/docs/getting-started/installation/nodejs/),
|
||||
[exceptions Trivy](https://trivy.dev/docs/dev/configuration/filtering/).
|
||||
|
||||
## Images de déploiement : npm global (25 septembre 2026)
|
||||
|
||||
Les rapports du run Gitea 150 attribuent huit alertes HIGH identiques, sur AMD64
|
||||
et ARM64, aux dépendances du npm global livré dans `node:22-alpine` :
|
||||
`usr/local/lib/node_modules/npm/node_modules/...`. Les audits npm du projet ne
|
||||
couvrent pas ce gestionnaire global ; un audit applicatif vert ne suffit donc
|
||||
pas à valider l'image finale.
|
||||
|
||||
Les trois Dockerfiles désinstallent le npm global avec `npm uninstall --global
|
||||
npm` uniquement après les installations nécessaires, dans l'image d'exécution.
|
||||
Le backend et le frontend gardent npm dans leurs étages de construction.
|
||||
Les services démarrent avec Node, et les migrations backend utilisent directement
|
||||
TypeORM via `startup.js`. La procédure manuelle Portainer utilise également Node.
|
||||
Aucune CVE n'est ignorée et les scans par digest restent bloquants en préprod/prod.
|
||||
|
||||
Chaque job de scan affiche maintenant un résumé indiquant CVE, paquet, version,
|
||||
correctif disponible et chemin, même après échec. Le rapport JSON complet reste
|
||||
joint en artefact. Les barres de progression sont désactivées pour éviter les
|
||||
journaux illisibles. L'avertissement de Trivy 0.74 sur la liste EOL d'Alpine 3.24
|
||||
n'est pas la cause du code de sortie 1 observé : il est aussi présent sur les
|
||||
scans corrigés qui retournent 0.
|
||||
|
||||
Validation du correctif : reconstruction des trois images ARM64 et du log-exporter
|
||||
AMD64 ; scans Trivy au seuil HIGH/CRITICAL sans exclusions ; HTTP 200 sur les
|
||||
routes de santé frontend et log-exporter ; chargement du démarrage backend et de
|
||||
la CLI TypeORM sans npm/npx ; validation des workflows et 30 tests de scripts.
|
||||
Les images backend/frontend AMD64 et le déploiement restent à confirmer par la
|
||||
prochaine exécution Gitea après publication du correctif. Relancer uniquement les
|
||||
anciens jobs de scan réanalyse les anciens digests vulnérables : il faut rebâtir
|
||||
les images à partir du commit corrigé.
|
||||
|
||||
@ -144,12 +144,12 @@ NEXT_PUBLIC_API_URL=https://api.xpeditis.com
|
||||
|
||||
## Migrations automatiques
|
||||
|
||||
Le backend exécute les migrations automatiquement via `startup.js`, qui attend PostgreSQL,
|
||||
appelle directement TypeORM puis lance le serveur Node. npm n’est pas présent dans l’image finale :
|
||||
Le backend exécute les migrations automatiquement au démarrage via le script `docker-entrypoint.sh` :
|
||||
|
||||
```bash
|
||||
# Commande de démarrage de l’image
|
||||
node startup.js
|
||||
# apps/backend/docker-entrypoint.sh attend PostgreSQL puis :
|
||||
npm run migration:run
|
||||
node dist/main.js
|
||||
```
|
||||
|
||||
Les logs Portainer affichent :
|
||||
@ -199,7 +199,8 @@ traefik.http.services.frontend.loadbalancer.server.port=3000
|
||||
### Migrations échouent
|
||||
|
||||
```bash
|
||||
docker exec -it xpeditis-backend node -e 'require("./startup").runMigrations().catch(() => process.exit(1))'
|
||||
docker exec -it xpeditis-backend sh
|
||||
cd /app && npm run migration:run
|
||||
```
|
||||
|
||||
Si blocage : vérifier que PostgreSQL est accessible (`DATABASE_HOST` = nom du service Docker).
|
||||
|
||||
@ -1,32 +0,0 @@
|
||||
"""Show actionable image findings even when the blocking Trivy step failed."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def summarize(path):
|
||||
try:
|
||||
report = json.loads(path.read_text())
|
||||
if not isinstance(report, dict) or not isinstance(report.get('Results'), list):
|
||||
raise ValueError('Missing scan results')
|
||||
except (OSError, ValueError):
|
||||
print('Image report missing or invalid: inspect the Trivy step; scan not verified.')
|
||||
return 1
|
||||
|
||||
count = 0
|
||||
for result in report['Results']:
|
||||
for finding in result.get('Vulnerabilities') or []:
|
||||
if finding.get('Severity') not in ('HIGH', 'CRITICAL'):
|
||||
continue
|
||||
count += 1
|
||||
print(f'{finding["Severity"]} {finding.get("VulnerabilityID", "unknown")}: '
|
||||
f'{finding.get("PkgName", "unknown")} '
|
||||
f'{finding.get("InstalledVersion", "unknown")} -> '
|
||||
f'{finding.get("FixedVersion") or "no fixed version published"}')
|
||||
print(f' Path: {finding.get("PkgPath") or result.get("Target", "unknown")}')
|
||||
print(f'{count} HIGH/CRITICAL image findings. Full details: image-security artifact.')
|
||||
return int(count > 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(summarize(Path(os.environ['RUNNER_TEMP']) / 'image-security.json'))
|
||||
@ -1,40 +0,0 @@
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
'image_summary', Path(__file__).with_name('summarize-image-security.py'))
|
||||
summary = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(summary)
|
||||
|
||||
|
||||
class ImageSummary(unittest.TestCase):
|
||||
def test_reports_global_npm_path_and_preserves_failure(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'image-security.json'
|
||||
path.write_text(json.dumps({'Results': [{'Vulnerabilities': [{
|
||||
'Severity': 'HIGH', 'VulnerabilityID': 'CVE-example',
|
||||
'PkgName': 'pacote', 'InstalledVersion': '19.0.2',
|
||||
'FixedVersion': '21.5.1',
|
||||
'PkgPath': 'usr/local/lib/node_modules/npm/node_modules/pacote/package.json',
|
||||
}]}]}))
|
||||
output = io.StringIO()
|
||||
with contextlib.redirect_stdout(output):
|
||||
self.assertEqual(summary.summarize(path), 1)
|
||||
self.assertIn('19.0.2 -> 21.5.1', output.getvalue())
|
||||
self.assertIn('usr/local/lib/node_modules/npm/', output.getvalue())
|
||||
|
||||
def test_missing_invalid_and_clean_reports(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'image-security.json'
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(summary.summarize(path), 1)
|
||||
for content in ('broken', '{}', '{"Results": null}'):
|
||||
path.write_text(content)
|
||||
self.assertEqual(summary.summarize(path), 1)
|
||||
path.write_text('{"Results": []}')
|
||||
self.assertEqual(summary.summarize(path), 0)
|
||||
Loading…
Reference in New Issue
Block a user