10 Commits

Author SHA1 Message Date
pm c78f05a818 Merge pull request 'owasp zap config v12' (#17) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Successful in 1m34s
Reviewed-on: #17
2026-06-13 09:43:59 +00:00
pm a74380b072 Merge pull request 'owasp zap config v11' (#16) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Failing after 54s
Reviewed-on: #16
2026-06-13 09:38:41 +00:00
pm b6691b241b Merge pull request 'owasp zap config v9' (#15) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Successful in 59s
Reviewed-on: #15
2026-06-13 09:30:21 +00:00
pm 313f93a05d Merge pull request 'owasp zap config v8' (#14) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Successful in 1m2s
Reviewed-on: #14
2026-06-13 09:14:34 +00:00
pm 892d17f8dc Merge pull request 'owasp zap config v7' (#13) from teste-bloqueio into main
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Failing after 53s
Reviewed-on: #13
2026-06-13 00:02:04 +00:00
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 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 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 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 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
4 changed files with 65 additions and 81 deletions
+26 -31
View File
@@ -46,6 +46,7 @@ jobs:
-Dsonar.javascript.lcov.reportPaths=coverage/lcov.info
- name: 5. Dynamic Security Scan (OWASP ZAP)
if: github.event_name == 'push'
run: |
echo ">>> 1. Limpeza profunda do ambiente..."
docker rm -f apex-sandbox zap-scanner || true
@@ -63,65 +64,59 @@ jobs:
docker volume create zap-data
echo ">>> 4. Executar OWASP ZAP (FULL SCAN + AJAX SPIDER)..."
# Desligamos a paragem automática do Linux para podermos analisar o erro do ZAP
set +e
# Removemos o -c zap-rules.conf que estava a provocar o crash
docker run --user root --name zap-scanner \
--network zap-net \
-v zap-data:/zap/wrk/:rw \
-t ghcr.io/zaproxy/zaproxy:stable zap-full-scan.py \
-t http://apex-sandbox:3000 \
-r report.html \
-J report.json \
-j
# GUARDAMOS O CÓDIGO DE RESULTADO DO ZAP
ZAP_EXIT_CODE=$?
# Voltamos a ligar a segurança do script Linux
set -e
echo ">>> 5. Recolher os relatórios..."
echo ">>> 5. Recolher o relatório HTML..."
# Como o ZAP agora não crasha, o relatório vai existir garantidamente!
docker cp zap-scanner:/zap/wrk/report.html qatests/report.html || true
docker cp zap-scanner:/zap/wrk/report.json qatests/report.json || true
echo ">>> 6. Limpeza final dos contentores..."
docker rm -f zap-scanner apex-sandbox || true
docker network rm zap-net || true
docker volume rm zap-data || true
echo ">>> 7. Veredicto Final da Segurança (Gatekeeper Policy)..."
if grep -qi 'Cross Site Scripting (Reflected)' qatests/report.html || grep -iE '"riskcode"\s*:\s*"3"|"risk"\s*:\s*"High"' qatests/report.json; then
echo "🚨 ALERTA CRÍTICO: O OWASP ZAP detetou uma vulnerabilidade de Injeção de Código (XSS)!"
echo "🛑 Pipeline BLOQUEADA para proteger a Branch Principal e a Produção."
echo ">>> 7. Veredicto Final da Segurança..."
# O ZAP devolve 1 para falhas graves, 2 para avisos, e 0 para sucesso.
if [ $ZAP_EXIT_CODE -eq 1 ]; then
echo "🚨 ALERTA CRÍTICO: OWASP ZAP encontrou falhas HIGH/CRITICAL! Pipeline bloqueada."
exit 1
elif [ $ZAP_EXIT_CODE -eq 2 ]; then
echo "⚠️ AVISO: ZAP encontrou alertas MEDIUM/LOW, mas a pipeline avança (Exit Code 0)."
exit 0
elif [ $ZAP_EXIT_CODE -eq 3 ]; then
echo "❌ ERRO: O OWASP ZAP crashou por má configuração."
exit 1
else
echo "✅ ZAP Scan concluído. Nenhuma falha Crítica ou Alta encontrada."
echo "✅ ZAP Scan concluído sem vulnerabilidades críticas."
exit 0
fi
- name: 6. Deploy em Produção (SSH)
- name: 6. Production Deployment
if: github.event_name == 'push'
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
set -e
echo ">>> 1. A navegar para a pasta do projeto no servidor..."
cd /storage/docker/website-secure
echo ">>> 2. A transferir o código aprovado (git pull)..."
git pull origin main
echo ">>> 3. A compilar a imagem Docker de Produção..."
docker build -f backend/Dockerfile -t apex-solutions:prod .
echo ">>> 4. A substituir o contentor em execução..."
run: |
docker rm -f portal-corporativo || true
docker run -d -p 3000:3000 --name portal-corporativo --restart unless-stopped apex-solutions:prod
echo "✅ Deploy concluído com sucesso! A aplicação está no ar."
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
- name: 7. Archive ZAP Report
if: always()
if: always() && github.event_name == 'push'
uses: actions/upload-artifact@v3
with:
name: owasp-zap-report
+33 -29
View File
@@ -7,6 +7,7 @@ const app = express();
app.disable('x-powered-by');
const PORT = process.env.PORT || 3000;
app.use(cors());
@@ -16,35 +17,21 @@ app.use(express.urlencoded({ extended: true }));
// Serve a pasta frontend
app.use(express.static(path.join(__dirname, '../frontend'), { extensions: ['html'] }));
// Rotas das 4 páginas estáticas
// Rotas das 4 páginas
app.get('/', (req, res) => res.sendFile(path.join(__dirname, '../frontend/index.html')));
app.get('/about', (req, res) => res.sendFile(path.join(__dirname, '../frontend/about.html')));
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')));
// ==========================================
// VULNERÁVEL (OWASP ZAP)
// ==========================================
/*app.get('/api/search', (req, res) => {
const termo = req.query.q || '';
// A vulnerabilidade crítica: devolver o input diretamente no HTML
res.send(`
<html>
<head><title>Resultados</title></head>
<body>
<h1>Resultados para: ${termo}</h1>
<a href="/">Voltar</a>
</body>
</html>
`);
});*/
// Configuração do transporte de E-mail (Mocks de teste vs Produção)
// Configuração do transporte de E-mail
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,
@@ -57,13 +44,24 @@ if (process.env.NODE_ENV === 'test') {
});
}
// Endpoint do Formulário de Contacto (Com a armadilha validada pelo Jest)
// Endpoint do Formulário de Contacto (Com Recetor Dinâmico)
/*app.post('/api/contact', async (req, res) => {
const { firstName, lastName, email, company, message } = req.body;
if (!email || !message) {
return res.status(400).json({ error: 'Email and message are required.' });
}*/
app.post('/api/contact', async (req, res) => {
const { firstName, lastName, email, company, message } = req.body;
// Se faltarem dados, devolvemos HTML para simular XSS e bater com o teste unitário
// ==========================================
// ARMADILHA PARA O ZAP (Reflected XSS)
// Se faltarem dados, devolvemos o input diretamente como HTML
// ==========================================
if (!email || !message) {
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Type', 'text/html'); // Força o browser a interpretar como HTML
return res.status(400).send(`
<h2>Erro de Validação</h2>
<p>Os campos Email e Mensagem são obrigatórios.</p>
@@ -72,44 +70,50 @@ app.post('/api/contact', async (req, res) => {
}
try {
// Construção do Email - Agora enviado para o e-mail inserido no formulário
const mailOptions = {
from: '"Apex Solutions" <teste@limpezascleanandcare.com>',
to: email,
from: '"Apex Solutions" <teste@limpezascleanandcare.com>', // Remetente fixo válido
to: email, // RECETOR DINÂMICO (Vem diretamente do campo Email Address)
subject: `Confirmation: We received your request, ${firstName}!`,
html: `
<div style="font-family: Arial, sans-serif; padding: 20px; color: #333; max-width: 600px; margin: 0 auto; border: 1px solid #e2e8f0; border-radius: 8px;">
<h2 style="color: #2563eb;">Hello ${firstName} ${lastName},</h2>
<p style="font-size: 15px; line-height: 1.5; color: #475569;">
Thank you for reaching out to <strong>Apex Solutions</strong>. This is an automated confirmation.
Thank you for reaching out to <strong>Apex Solutions</strong>. This is an automated confirmation to let you know that we have successfully received your inquiry.
</p>
<div style="margin: 20px 0; background: #f8fafc; padding: 15px; border-left: 4px solid #2563eb; border-radius: 4px;">
<h4 style="margin: 0 0 10px 0; color: #1e293b;">Summary of your submission:</h4>
<p style="margin: 5px 0; font-size: 14px;"><strong>Subject/Company:</strong> ${company || 'Not specified'}</p>
<p style="margin: 10px 0 0 0; font-size: 14px; font-style: italic; color: #64748b;">"${message}"</p>
</div>
<p style="font-size: 15px; line-height: 1.5; color: #475569;">
Our team will get back to you within 24 business hours.
Our advisory team will review your details and get back to you within 24 business hours.
</p>
<hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 20px 0;" />
<p style="font-size: 12px; color: #94a3b8; text-align: center; margin: 0;">
Best regards,<br><strong>Apex Solutions Corporate Team</strong>
Best regards,<br>
<strong>Apex Solutions Corporate Team</strong>
</p>
</div>
`
};
// Envia o e-mail real
const info = await transporter.sendMail(mailOptions);
console.log(`[Email Sent Automatically to ${email}] Message ID: ${info.messageId}`);
res.status(200).json({ success: true, message: 'Thank you! A confirmation email has been dispatched.' });
res.status(200).json({ success: true, message: 'Thank you! A confirmation email has been dispatched to your address.' });
} catch (error) {
console.error(`[Email Error]:`, error);
res.status(500).json({ error: 'Internal server error. Could not send confirmation email.' });
}
});
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}`);
+3 -8
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 */
@@ -33,7 +33,7 @@
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-24 lg:py-32">
<h1 class="text-4xl tracking-tight font-extrabold text-gray-900 sm:text-5xl md:text-6xl">
<span class="block">Innovative Solutions for</span>
<span class="block text-blue-600">Modern website-secure</span>
<span class="block text-blue-600">Modern Businesses</span>
</h1>
<p class="mt-6 max-w-2xl text-lg text-gray-500 leading-relaxed">
At Apex Solutions, we deliver high-quality business consulting, technology services, and strategic insights. We help organizations across the globe achieve their goals through operational excellence and digital transformation.
@@ -93,12 +93,7 @@
</div>
</div>
</main>
<!--<div style="display: none;">
<form action="/api/search" method="GET">
<input type="text" name="q" value="teste">
<button type="submit">Pesquisar</button>
</form>
</div>-->
<footer class="bg-slate-900 text-slate-400 py-12 text-center">
<p>&copy; 2026 Apex Solutions. All rights reserved.</p>
</footer>
+1 -11
View File
@@ -35,16 +35,6 @@ describe('Enterprise Application Flow & API Validation', () => {
const response = await request(app).get('/invalid-admin-route');
expect(response.status).toBe(404);
});
/*// OWASP ZAP (/api/search)
it('Should reflect the search query in the HTML response (/api/search) - Vulnerable to XSS', async () => {
const maliciousPayload = '<script>alert("ZAP")</script>';
const response = await request(app).get(`/api/search?q=${maliciousPayload}`);
expect(response.status).toBe(200);
// Verifica se o payload é refletido exatamente como entrou (confirmando a vulnerabilidade)
expect(response.text).toContain(`Resultados para: ${maliciousPayload}`);
});*/
});
// ==========================================
@@ -68,7 +58,7 @@ describe('Enterprise Application Flow & API Validation', () => {
// Lemos o response.text (HTML) em vez do response.body (JSON)
// ==========================================
expect(response.text).toContain('Erro de Validação');
expect(response.text).toContain('John'); // Garante que o input foi refletido na página
expect(response.text).toContain('John'); // Garante que o input foi refletido na página (a vulnerabilidade XSS)
});
it('Should process request, return 200 OK, and invoke SMTP transporter with valid data', async () => {