59 Commits

Author SHA1 Message Date
pm 87a6c63ac8 Merge pull request 'owasp zap config v6' (#12) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Failing after 52s
Reviewed-on: #12
2026-06-12 23:57:30 +00:00
pm 0fdd3c1558 owasp zap config v6
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 43s
2026-06-13 00:55:31 +01:00
pm 0a92b7f4a0 Merge pull request 'owasp zap config v3' (#11) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Failing after 43s
Reviewed-on: #11
2026-06-12 23:52:59 +00:00
pm 430c418062 owasp zap config v5
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 42s
2026-06-13 00:50:04 +01:00
pm aba23ad583 owasp zap config v4 2026-06-13 00:48:45 +01:00
pm c23ad4f6d3 owasp zap config v3 2026-06-13 00:44:33 +01:00
pm a1aadf130d Merge pull request 'owasp zap config v2' (#9) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Failing after 42s
Reviewed-on: #9
2026-06-12 23:42:12 +00:00
pm 47db928d3c owasp zap config v2
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 43s
2026-06-13 00:40:00 +01:00
pm dd94920955 Merge pull request 'owasp zap config' (#8) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Failing after 53s
Reviewed-on: #8
2026-06-12 23:36:56 +00:00
pm 745c8b4e71 owasp zap config
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 45s
2026-06-13 00:34:35 +01:00
pm 54a52d9ebe Merge pull request 'feat: adiciona nova funcionalidade (com erro oculto)' (#7) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Successful in 1m30s
Reviewed-on: #7
2026-06-12 23:26:14 +00:00
pm 432d3d8840 sonar v2
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 56s
2026-06-13 00:04:18 +01:00
pm 500972ea6f sonar
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 45s
2026-06-13 00:00:44 +01:00
pm aa726dbd77 teste: introduz lodash para forcar bloqueio do trivy
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 30s
2026-06-12 23:58:15 +01:00
pm 3da598485b trivy nodemailer v2
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 45s
2026-06-12 23:52:38 +01:00
pm 22940982e7 trivy nodemailer
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 46s
2026-06-12 23:49:01 +01:00
pm 62aaba7cae gitleak v7
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 6s
2026-06-12 23:43:38 +01:00
pm d30db1d4cc gitleak v6
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 56s
2026-06-12 23:41:13 +01:00
pm cc8c34868c gitleak v5
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 18s
2026-06-12 23:35:47 +01:00
pm eb1aec157d gitleak v3
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 17s
2026-06-12 23:30:22 +01:00
pm 2760503bfa gitleak v2
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 9s
2026-06-12 23:28:27 +01:00
pm 9ade6ec23f gitleak
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 17s
2026-06-12 23:26:06 +01:00
pm b7ba597b0a fix deploy
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 17s
2026-06-12 23:24:14 +01:00
pm a75556acd2 fix deploy
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 37s
2026-06-12 23:21:01 +01:00
pm 34eb81849b trivy v4
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 9s
2026-06-12 23:17:52 +01:00
pm 6adf9ea8b9 trivy v3
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 9s
2026-06-12 23:15:38 +01:00
pm 03b75c1da6 trivy v2
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 13s
2026-06-12 23:14:19 +01:00
pm 29816c44bb trivy
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 14s
2026-06-12 23:11:55 +01:00
pm 734e128696 gitleak bloqueio
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 9s
2026-06-12 23:07:19 +01:00
pm deb2605e08 Merge branch 'teste-bloqueio' of https://gitea.each-cs.com/pm/website-secure into teste-bloqueio
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 36s
2026-06-12 23:01:49 +01:00
pm 0ba2cb3a1b sonar v8 2026-06-12 23:00:27 +01:00
pm b8ae8e0a5b sonar v6
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 31s
2026-06-12 09:07:09 +01:00
pm 11399103e4 sonar v5
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 37s
2026-06-12 08:48:57 +01:00
pm 1b70908cad sonar v3
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 36s
2026-06-12 01:08:00 +01:00
pm a53b8e23e7 sonar v2
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 38s
2026-06-12 01:03:28 +01:00
pm 0689c0bc17 sonar v1
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 35s
2026-06-12 00:54:56 +01:00
pm 3a2685d5b6 ut v3
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 36s
2026-06-12 00:50:08 +01:00
pm f9e6fd47a4 ut v2
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 9s
2026-06-12 00:47:30 +01:00
pm cd5785c497 ut v1
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 8s
2026-06-12 00:45:12 +01:00
pm 3967393895 docker v3
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 9s
2026-06-12 00:41:21 +01:00
pm dbf0d7445c docker v2
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 8s
2026-06-12 00:39:12 +01:00
pm 20d454d5c6 docker
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 7s
2026-06-12 00:37:06 +01:00
pm 18ded6b7fc alterações deploy
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 5s
2026-06-12 00:35:09 +01:00
pm bba5d7c581 deploy en-us e unit tests melhorado
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 7s
2026-06-12 00:28:08 +01:00
pm 70321152a7 teste error
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 7s
2026-06-12 00:17:00 +01:00
pm 25849c273c chore: adiciona condicoes de execucao e exclusoes do sonar
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 34s
2026-06-12 00:13:49 +01:00
pm 740b6386ef deploy
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 1m20s
2026-06-12 00:06:46 +01:00
pm 980005151f fix: recria package.json do backend para remover BOM fantasma
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 37s
2026-06-12 00:00:20 +01:00
pm c234771d28 deploy atualizado; test correto
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 8s
2026-06-11 23:54:58 +01:00
pm b71d73afe0 feat: adiciona nova funcionalidade (com erro oculto)
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 1m17s
2026-06-11 23:41:19 +01:00
pm 002f696161 Merge pull request 'docs: altera readme para testar fluxo de CI/CD' (#6) from teste-fluxo-limpo into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Successful in 1m16s
Reviewed-on: #6
2026-06-11 22:37:12 +00:00
pm 1f8953ab41 docs: altera readme para testar fluxo de CI/CD
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 1m16s
2026-06-11 23:18:55 +01:00
pm 9d8aaeb8f2 Merge pull request 'feat: integra aplicacao portal corporativo real com backend e frontend' (#5) from base-aplicacao into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Successful in 1m19s
Reviewed-on: #5
2026-06-11 22:06:36 +00:00
pm 7ec0a5136d Trigger pipeline rebuild
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 1m17s
2026-06-10 23:42:36 +01:00
pm 73f91a1261 fix: altera teste de integridade para executar internamente com wget
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Successful in 1m16s
2026-06-10 22:48:04 +01:00
pm aacc679600 fix: resolve problema de rede entre contentores no Gitea runner
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 3m36s
2026-06-10 22:40:43 +01:00
pm 2a62d54f81 fix: adiciona sleep e corrige tag da imagem docker
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 1m21s
2026-06-10 22:33:50 +01:00
pm eb99f05016 feat: integra aplicacao portal corporativo real com backend e frontend
DevSecOps Enterprise Pipeline / security-gate-and-deploy (pull_request) Failing after 1m13s
2026-06-10 22:26:52 +01:00
pm 6fc1b22f7f ci: adiciona trigger de pull request para ativar a pipeline
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Failing after 1m16s
2026-06-10 21:24:50 +01:00
11 changed files with 5790 additions and 137 deletions
+4 -3
View File
@@ -1,5 +1,6 @@
.git
.env
node_modules
npm-debug.log
.env
.git
.gitea
*.md
.vscode
+47 -95
View File
@@ -1,8 +1,4 @@
name: "DevSecOps Enterprise Pipeline"
# ==========================================
# PONTO 4: TRIGGERS (Push vs PR)
# ==========================================
on:
push:
branches: [ main ]
@@ -13,128 +9,84 @@ jobs:
security-gate-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
- name: 0. Checkout Code
uses: actions/checkout@v3
with:
fetch-depth: 0
# ==========================================
# STAGE 1: STATIC SECURITY TESTING (SAST, SCA)
# ==========================================
- name: 1. Build Application Image
run: docker build -f backend/Dockerfile -t apex-solutions:latest .
- name: Gitleaks Scan
- name: 1.5. Execute Unit Tests
run: |
npm install
npm test
- name: 2. Secret Scanning (Gitleaks)
run: |
curl -sL https://github.com/gitleaks/gitleaks/releases/download/v8.18.2/gitleaks_8.18.2_linux_x64.tar.gz | tar -xz -C /tmp
/tmp/gitleaks detect --source . --verbose --redact --log-opts="-1" --exit-code 1
/tmp/gitleaks detect --source . --no-git --verbose --redact --exit-code 1
# PONTO 3: Artefactos do Trivy adicionados
- name: Scan Docker Image Vulnerabilities (Trivy)
- name: 3. Software Composition Analysis (Trivy)
run: |
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
# 1. Guarda o output para um ficheiro de texto para o Artefato
trivy image --severity HIGH,CRITICAL --format table --output trivy-report.txt nginx:alpine
# 2. Corre novamente no terminal para forçar a quebra da pipeline se encontrar falhas (Exit-Code 1)
trivy image --severity HIGH,CRITICAL --exit-code 1 nginx:alpine
trivy image --exit-code 1 --severity HIGH,CRITICAL apex-solutions:latest
- name: Archive Trivy Report
if: always()
uses: actions/upload-artifact@v3
with:
name: trivy-sca-report
path: trivy-report.txt
- name: SonarQube Analysis
- name: 4. Static Application Security Testing (SonarQube)
run: |
curl -sL https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-5.0.1.3006-linux.zip -o sonar-scanner.zip
unzip -q sonar-scanner.zip
./sonar-scanner-5.0.1.3006-linux/bin/sonar-scanner \
-Dsonar.projectKey=website-test \
-Dsonar.projectKey=website-apex \
-Dsonar.sources=. \
-Dsonar.exclusions=**/node_modules/** \
-Dsonar.host.url=https://sonar.each-cs.com \
-Dsonar.token=${{ secrets.SONAR_TOKEN }} \
-Dsonar.qualitygate.wait=true
-Dsonar.qualitygate.wait=true \
-Dsonar.javascript.lcov.reportPaths=coverage/lcov.info
# ==========================================
# STAGE 2 & 3: DYNAMIC TESTING (ZAP)
# ==========================================
- name: Provision Ephemeral Sandbox
- name: 5. Dynamic Security Scan (OWASP ZAP)
if: github.event_name == 'push'
run: |
docker rm -f website-test-sandbox || true
docker run -d --name website-test-sandbox nginx:alpine
docker cp index.html website-test-sandbox:/usr/share/nginx/html/index.html
sleep 5
echo ">>> Limpando ambiente anterior (Contentores e Rede)..."
docker rm -f apex-sandbox zap-scanner || true
docker network rm zap-net || true
- name: OWASP ZAP Baseline Scan
run: |
echo ">>> Criando rede isolada..."
docker network create zap-net
echo ">>> Iniciando sandbox..."
docker run -d --name apex-sandbox --network zap-net apex-solutions:latest
sleep 10
echo ">>> Iniciando OWASP ZAP Baseline Scan..."
mkdir -p qatests
docker rm -f zap-scanner || true
docker volume rm zap-reports || true
docker volume create zap-reports
docker run --user root --name zap-scanner \
--link website-test-sandbox:website-test-sandbox \
-v zap-reports:/zap/wrk/:rw \
--network zap-net \
-v ${{ github.workspace }}:/zap/wrk/:rw \
-t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py \
-t http://website-test-sandbox \
-t http://apex-sandbox:3000 \
-r report.html \
-I
-I -c zap-baseline.conf
docker cp zap-scanner:/zap/wrk/report.html qatests/report.html
docker rm -f zap-scanner || true
docker volume rm zap-reports || true
docker cp zap-scanner:/zap/wrk/report.html qatests/report.html || true
- name: Teardown Ephemeral Sandbox
if: always()
echo ">>> Limpeza final..."
docker rm -f zap-scanner apex-sandbox || true
docker network rm zap-net || true
- name: 6. Production Deployment
if: github.event_name == 'push'
run: |
docker rm -f website-test-sandbox || true
docker rm -f portal-corporativo || true
docker run -d -p 3000:3000 --name portal-corporativo apex-solutions:latest
sleep 5
docker cp qatests/report.html portal-corporativo:/usr/src/app/frontend/zap-report.html || true
# ==========================================
# STAGE 4: PRODUCTION DEPLOYMENT (SSH)
# ==========================================
# PONTO 6: Deploy Seguro Condicional
# Só executa se for um Push (não PR) e se for na branch main
- name: Hardened Production Deployment via SSH
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
uses: appleboy/ssh-action@v1.0.0
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
echo ">>> A iniciar Deploy Seguro no Servidor de Produção..."
# 1. Navegar para a pasta do projeto (Ajusta o caminho para o teu servidor real)
cd /opt/website-test
# 2. Puxar as últimas alterações do repositório
git pull origin main
# 3. Tratamento do ficheiro .ENV dinâmico (Frente 2)
# Isto injeta os Secrets do Gitea num ficheiro .env temporário no servidor
echo "PORT=80" > .env
echo "API_SECRET=${{ secrets.API_SECRET_PROD }}" >> .env
# 4. Construir e iniciar o contentor de Produção
docker build -t website-test-backend:latest .
docker rm -f website-test-backend || true
docker run -d -p 80:80 --env-file .env --name website-test-backend website-test-backend:latest
echo ">>> Deploy em Produção concluído com sucesso!"
# ==========================================
# STAGE 5: ARTIFACT MANAGEMENT & REPORTING
# ==========================================
- name: Archive ZAP Report (Raw HTML)
if: always()
- name: 7. Archive ZAP Report
if: always() && github.event_name == 'push'
uses: actions/upload-artifact@v3
with:
name: owasp-zap-report
path: qatests/report.html
- name: Pipeline Status Notification
if: always()
run: |
echo "Pipeline finished with status: ${{ job.status }}"
+27 -4
View File
@@ -1,9 +1,32 @@
FROM node:18-alpine
WORKDIR /usr/src/app/backend
COPY backend/package*.json ./
RUN npm install --omit=dev
FROM node:22-alpine
# ==========================================
# DEVSECOPS: HARDENING DA IMAGEM BASE
# ==========================================
# Agrupamos os comandos RUN num só para otimizar as camadas da imagem (Regra do SonarQube)
RUN apk update && apk upgrade --no-cache && \
npm install -g npm@latest && \
addgroup -S appgroup && adduser -S appuser -G appgroup
# Define o diretório de trabalho
WORKDIR /usr/src/app
# Ajusta as permissões da pasta para o novo utilizador
RUN chown -R appuser:appgroup /usr/src/app
# Copia os ficheiros e instala dependências
COPY package*.json ./
RUN npm install --omit=dev
# Copia o código fonte
COPY backend/ ./backend/
COPY frontend/ ./frontend/
# Altera a propriedade dos ficheiros copiados para o utilizador
RUN chown -R appuser:appgroup /usr/src/app
# Muda para o utilizador sem privilégios
USER appuser
EXPOSE 3000
CMD ["node", "backend/server.js"]
-14
View File
@@ -1,14 +0,0 @@
{
"name": "corporate-portal",
"version": "2.0.0",
"description": "Multi-page Corporate Portal for DevSecOps PoC",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"nodemailer": "^6.9.3"
}
}
+37 -9
View File
@@ -1,9 +1,13 @@
const express = require('express');
const cors = require('cors');
const path = require('path');
const path = require('node:path');
const nodemailer = require('nodemailer');
const app = express();
app.disable('x-powered-by');
const PORT = process.env.PORT || 3000;
app.use(cors());
@@ -19,8 +23,29 @@ app.get('/about', (req, res) => res.sendFile(path.join(__dirname, '../frontend/a
app.get('/careers', (req, res) => res.sendFile(path.join(__dirname, '../frontend/careers.html')));
app.get('/contact', (req, res) => res.sendFile(path.join(__dirname, '../frontend/contact.html')));
// Rota de Pesquisa Vulnerável a Reflected XSS (Armadilha para o OWASP ZAP)
app.get('/api/search', (req, res) => {
const termoPesquisa = req.query.q || '';
// A vulnerabilidade: devolver o input diretamente para o navegador como HTML
res.send(`
<html>
<body>
<h2>Resultados da pesquisa para: ${termoPesquisa}</h2>
<p>Nenhum resultado encontrado.</p>
</body>
</html>
`);
});
// Configuração do transporte de E-mail
const transporter = nodemailer.createTransport({
let transporter;
if (process.env.NODE_ENV === 'test') {
// Em teste, criamos um mock vazio para evitar erros
transporter = { sendMail: jest.fn().mockResolvedValue({ messageId: 'test-id' }) };
} else {
// Em produção, usamos o transporter real
transporter = nodemailer.createTransport({
host: 'mail.limpezascleanandcare.com',
port: 465,
secure: true,
@@ -28,10 +53,10 @@ const transporter = nodemailer.createTransport({
user: 'teste@limpezascleanandcare.com',
pass: 'HTC?D=}5&cHoTrH='
},
tls: {
rejectUnauthorized: false // Ignora avisos de certificado no servidor SMTP
}
});
tls: { rejectUnauthorized: false }
});
}
// Endpoint do Formulário de Contacto (Com Recetor Dinâmico)
app.post('/api/contact', async (req, res) => {
@@ -84,7 +109,10 @@ app.post('/api/contact', async (req, res) => {
res.status(500).json({ error: 'Internal server error. Could not send confirmation email.' });
}
});
app.listen(PORT, () => {
module.exports = { app, transporter };
// Export the app for testing, but only listen if run directly
if (require.main === module) {
app.listen(PORT, () => {
console.log(`[Apex Server] Running on port ${PORT}`);
});
});
}
+1 -1
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home | Apex Solutions</title>
<title>Home | Apex Solutions branch sec</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
html { scroll-behavior: smooth; } /* Animação suave ao clicar no link de serviços */
+1 -1
View File
@@ -79,7 +79,7 @@ body {
/* Efeito ao passar o rato (Hover) */
.navbar a:hover {
color: white;
background-color: rgba(255, 255, 255, 0.1); /* Fundo branco muito subtil */
background-color: rgba(255, 255, 255, 0.); /* Fundo branco muito subtil */
}
/* Estado da página atual (Active) */
+5558
View File
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "website-secure",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --coverage --coverageReporters=lcovonly"
},
"repository": {
"type": "git",
"url": "https://gitea.each-cs.com/pm/website-secure.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"nodemailer": "^8.0.11"
},
"devDependencies": {
"jest": "^30.4.2",
"supertest": "^7.2.2"
}
}
+77
View File
@@ -0,0 +1,77 @@
const request = require('supertest');
process.env.NODE_ENV = 'test';
const { app, transporter } = require('../backend/server');
const nodemailer = require('nodemailer');
// ==========================================
// MOCK EXTERNAL SERVICES
// ==========================================
jest.mock('nodemailer');
describe('Enterprise Application Flow & API Validation', () => {
beforeAll(() => {
// Configure the mock to simulate a successful SMTP response
nodemailer.createTransport.mockReturnValue({
sendMail: jest.fn().mockResolvedValue({ messageId: 'mock-id-enterprise-1234' })
});
});
afterEach(() => {
jest.clearAllMocks(); // Clear tracking between tests
});
// ==========================================
// 1. STATIC ROUTING TESTS
// ==========================================
describe('1. Static Web Routing', () => {
it('Should return 200 OK and text/html for the Home Page (/)', async () => {
const response = await request(app).get('/');
expect(response.status).toBe(200);
expect(response.headers['content-type']).toMatch(/text\/html/);
});
it('Should return 404 Not Found for an unknown endpoint', async () => {
const response = await request(app).get('/invalid-admin-route');
expect(response.status).toBe(404);
});
});
// ==========================================
// 2. API BUSINESS LOGIC & VALIDATION TESTS
// ==========================================
describe('2. Contact API Endpoint (/api/contact)', () => {
it('Should reject requests and return 400 Bad Request if email is missing', async () => {
const invalidPayload = {
firstName: 'John',
message: 'I need a security audit.'
// Missing 'email' deliberately
};
const response = await request(app).post('/api/contact').send(invalidPayload);
expect(response.status).toBe(400);
expect(response.body).toHaveProperty('error', 'Email and message are required.');
});
it('Should process request, return 200 OK, and invoke SMTP transporter with valid data', async () => {
const validPayload = {
firstName: 'Jane',
lastName: 'Doe',
email: 'jane.doe@example.com',
company: 'Apex Corporation',
message: 'Please send me the DevSecOps proposal.'
};
const response = await request(app).post('/api/contact').send(validPayload);
// Validate HTTP Response
expect(response.status).toBe(200);
// Validate Business Logic: Verifica o objeto 'transporter' que veio do server.js
// Como este objeto é o que injetámos no server, ele já é o mock!
expect(transporter.sendMail).toHaveBeenCalledTimes(1);
});
});
});
+2
View File
@@ -0,0 +1,2 @@
# Bloqueia a pipeline se encontrar algo grave
FAIL_ON_SEVERITY: HIGH