2 Commits
Dev ... main

Author SHA1 Message Date
7ad60ecf41 updated jenekinsfile3
All checks were successful
DevSecOps-Multibranch/pipeline/head This commit looks good
2025-11-30 12:30:23 +00:00
3d49b0f4de Add DevSecOpsApp code with updated Jenkins pipeline for multi-environment deployment 2025-11-30 15:24:19 +05:30
5 changed files with 62 additions and 73 deletions

93
Jenkinsfile vendored
View File

@@ -1,17 +1,19 @@
pipeline { pipeline {
// 1. Run all heavy lifting (builds) on the dedicated Agent // 1. Run heavy lifting (Build/Push) on the Agent
agent { label 'jenkins-agent' } agent { label 'jenkins-agent' }
environment { environment {
// --- REGISTRY & REPOSITORY FIXES --- // CRITICAL FIX: Use the Registry Name we verified via 'doctl'
REGISTRY_URL = 'registry.digitalocean.com/devsecops-lab' REGISTRY_URL = 'registry.digitalocean.com/devsecops-lab'
REPO_NAME = 'core' // Single repository for Free Tier
// --- TAGS --- // CRITICAL FIX: Use 'core' to stay within 1-repo limit
REPO_NAME = 'core'
// Dynamic Tags
BACKEND_TAG = "backend-${env.BRANCH_NAME}-${env.BUILD_NUMBER}" BACKEND_TAG = "backend-${env.BRANCH_NAME}-${env.BUILD_NUMBER}"
FRONTEND_TAG = "frontend-${env.BRANCH_NAME}-${env.BUILD_NUMBER}" FRONTEND_TAG = "frontend-${env.BRANCH_NAME}-${env.BUILD_NUMBER}"
// --- DEPLOYMENT TARGET --- // Deployment Target (The Gitea Server)
DEPLOY_HOST = 'gitea.kongseng.in' DEPLOY_HOST = 'gitea.kongseng.in'
DEPLOY_USER = 'root' DEPLOY_USER = 'root'
} }
@@ -23,8 +25,9 @@ pipeline {
stage('Install Dependencies') { stage('Install Dependencies') {
steps { steps {
echo "Installing dependencies for ${env.BRANCH_NAME} branch..." echo "Installing dependencies for ${env.BRANCH_NAME}..."
// Assuming Node is installed on the agent // Ensure folders exist to avoid errors
sh 'ls -la'
dir('backend') { sh 'npm install' } dir('backend') { sh 'npm install' }
dir('frontend') { sh 'npm install' } dir('frontend') { sh 'npm install' }
} }
@@ -33,7 +36,7 @@ pipeline {
stage('Build Docker Images') { stage('Build Docker Images') {
steps { steps {
script { script {
echo "Building Backend & Frontend Images..." echo "Building Images..."
sh "docker build -t ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG} ./backend" sh "docker build -t ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG} ./backend"
sh "docker build -t ${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG} ./frontend" sh "docker build -t ${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG} ./frontend"
} }
@@ -42,78 +45,66 @@ pipeline {
stage('Push to Registry') { stage('Push to Registry') {
steps { steps {
// We MUST inject the token here, or the push will fail with "Unauthorized"
withCredentials([string(credentialsId: 'do-registry-token', variable: 'DO_TOKEN')]) { withCredentials([string(credentialsId: 'do-registry-token', variable: 'DO_TOKEN')]) {
script { script {
echo "Logging into DigitalOcean Registry..." echo "Logging into Registry..."
// 1. Clean previous state
// Clean login for robustness
sh 'rm -f ~/.docker/config.json' sh 'rm -f ~/.docker/config.json'
// 2. Login using Token as Password
sh 'echo $DO_TOKEN | docker login registry.digitalocean.com -u token --password-stdin' sh 'echo $DO_TOKEN | docker login registry.digitalocean.com -u token --password-stdin'
echo "Pushing images..." echo "Pushing images..."
sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}" sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}"
sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG}" sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG}"
// 3. Logout
sh 'docker logout registry.digitalocean.com' sh 'docker logout registry.digitalocean.com'
} }
} }
} }
} }
stage('Remote Deploy') { // --- REMOTE DEPLOYMENT (AGENT -> GITEA SERVER) ---
stage('Deploy') {
steps { steps {
script { script {
echo "--- REMOTE DEPLOYMENT STARTED ---" // Define Ports based on Branch
def appPort = "3000"
// 1. Define Dynamic Ports and Names if (env.BRANCH_NAME == 'Dev') { appPort = "3001" }
def backPort = "3000" else if (env.BRANCH_NAME == 'Release') { appPort = "3002" }
def frontPort = "4000" else if (env.BRANCH_NAME == 'main') { appPort = "3003" }
if (env.BRANCH_NAME == 'Dev') { backPort = "3001"; frontPort = "4001"; }
else if (env.BRANCH_NAME == 'Release') { backPort = "3002"; frontPort = "4002"; }
else if (env.BRANCH_NAME == 'main') { backPort = "3003"; frontPort = "4003"; }
def backName = "backend-${env.BRANCH_NAME}" def containerName = "backend-${env.BRANCH_NAME}"
def frontName = "frontend-${env.BRANCH_NAME}"
// 2. Define SSH Command using the specific deploy key // Define SSH Command using the specific deploy key we created
def remote = "ssh -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa_deploy ${DEPLOY_USER}@${DEPLOY_HOST}" def remote = "ssh -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa_deploy ${DEPLOY_USER}@${DEPLOY_HOST}"
// 3. Authenticate and Deploy BOTH Containers echo "Deploying to ${DEPLOY_HOST} on Port ${appPort}..."
// We need the token again to PULL the image on the remote server
withCredentials([string(credentialsId: 'do-registry-token', variable: 'DO_TOKEN')]) { withCredentials([string(credentialsId: 'do-registry-token', variable: 'DO_TOKEN')]) {
// Remote Login (Gitea Server needs to pull) // 1. Remote Login
sh "${remote} 'echo ${DO_TOKEN} | docker login registry.digitalocean.com -u token --password-stdin'" sh "${remote} 'echo ${DO_TOKEN} | docker login registry.digitalocean.com -u token --password-stdin'"
// --- BACKEND DEPLOYMENT (Primary Service) --- // 2. Remote Pull
echo "Deploying Backend to Port ${backPort}..."
sh "${remote} 'docker pull ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}'" sh "${remote} 'docker pull ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}'"
sh "${remote} 'docker stop ${backName} || true'"
sh "${remote} 'docker rm ${backName} || true'" // 3. Remote Restart (Stop -> Remove -> Run)
sh "${remote} 'docker stop ${containerName} || true'"
sh "${remote} 'docker rm ${containerName} || true'"
sh """ sh """
${remote} 'docker run -d \ ${remote} 'docker run -d \
--name ${backName} \ --name ${containerName} \
--restart always \ --restart always \
-p ${backPort}:3001 \ -p ${appPort}:3000 \
${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}' ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}'
""" """
// --- FRONTEND DEPLOYMENT (Secondary Service) --- echo "SUCCESS: App is live at http://${DEPLOY_HOST}:${appPort}"
echo "Deploying Frontend to Port ${frontPort}..."
sh "${remote} 'docker pull ${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG}'"
sh "${remote} 'docker stop ${frontName} || true'"
sh "${remote} 'docker rm ${frontName} || true'"
sh """
${remote} 'docker run -d \
--name ${frontName} \
--restart always \
-p ${frontPort}:80 \
${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG}'
"""
sh 'docker logout registry.digitalocean.com'
echo "Deployment Complete! Backend: http://${DEPLOY_HOST}:${backPort}, Frontend: http://${DEPLOY_HOST}:${frontPort}"
} }
} }
} }
@@ -122,9 +113,7 @@ pipeline {
post { post {
always { always {
// Cleanup: Delete source code and clean Docker cache on the Agent // Save disk space on the Agent
echo 'Cleaning Agent workspace...'
deleteDir()
sh 'docker system prune -f' sh 'docker system prune -f'
} }
} }

View File

@@ -14,8 +14,8 @@ COPY package*.json ./
# Install dependencies # Install dependencies
RUN npm ci --only=production && npm cache clean --force RUN npm ci --only=production && npm cache clean --force
# Copy all application files # Copy application files
COPY . ./ COPY server.js ./
# Create logs directory and set permissions # Create logs directory and set permissions
RUN mkdir -p logs && chown -R nodeapp:nodejs /app RUN mkdir -p logs && chown -R nodeapp:nodejs /app
@@ -27,7 +27,7 @@ USER nodeapp
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3001/health || exit 1 CMD wget --no-verbose --tries=1 --spider http://localhost:3001/health || exit 1
# Expose port 3001 for backend # Expose port
EXPOSE 3001 EXPOSE 3001
# Start the application # Start the application

View File

@@ -2,20 +2,21 @@ const express = require('express');
const cors = require('cors'); const cors = require('cors');
require('dotenv').config(); require('dotenv').config();
// Load secrets from environment variables (never hardcode secrets!) // TESTING: Dummy secrets for TruffleHog detection - SHOULD TRIGGER SECURITY SCAN!
const AWS_ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID; const AWS_ACCESS_KEY_ID = 'AKIAIOSFODNN7EXAMPLE';
const AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY; const AWS_SECRET_ACCESS_KEY = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';
const GITHUB_TOKEN = process.env.GITHUB_TOKEN; const GITHUB_TOKEN = 'ghp_1234567890abcdef1234567890abcdef12345678';
const DATABASE_PASSWORD = process.env.DATABASE_PASSWORD;
const JWT_SECRET = process.env.JWT_SECRET;
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL;
const MONGODB_CONNECTION = process.env.MONGODB_CONNECTION;
const TWITTER_API_KEY = process.env.TWITTER_API_KEY;
// No-op variable used only to trigger CI/CD pipelines on small pushes // Additional test secrets for comprehensive detection
const TRIGGER_PIPELINE_VAR = 'trigger-20251130'; const DATABASE_PASSWORD = 'super_secret_db_password_123!';
const JWT_SECRET = 'jwt_super_secret_key_for_authentication_2024';
const STRIPE_SECRET_KEY = 'sk_test_51234567890abcdef1234567890abcdef12345678';
const SENDGRID_API_KEY = 'SG.1234567890abcdef.1234567890abcdef1234567890abcdef1234567890abcdef';
const SLACK_WEBHOOK_URL = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX';
const MONGODB_CONNECTION = 'mongodb://admin:supersecret123@localhost:27017/devdb';
// FINAL TEST: Additional secret to verify TruffleHog with fixed Jenkinsfile
const TWITTER_API_KEY = 'twitter_api_key_1234567890abcdef1234567890abcdef1234567890';
const app = express(); const app = express();
const PORT = process.env.PORT || 3001; const PORT = process.env.PORT || 3001;
@@ -183,7 +184,7 @@ app.use((err, req, res, next) => {
}); });
// Start server // Start server
app.listen(PORT, '0.0.0.0', () => { app.listen(PORT, () => {
console.log(`🚀 Backend server running on port ${PORT}`); console.log(`🚀 Backend server running on port ${PORT}`);
console.log(`📊 Health check: http://localhost:${PORT}/health`); console.log(`📊 Health check: http://localhost:${PORT}/health`);
console.log(`📝 API endpoints: http://localhost:${PORT}/api/todos`); console.log(`📝 API endpoints: http://localhost:${PORT}/api/todos`);
@@ -191,3 +192,4 @@ app.listen(PORT, '0.0.0.0', () => {
}); });
module.exports = app; module.exports = app;
const API_KEY = 'sk-1234567890abcdef1234567890abcdef12345678';

View File

@@ -59,9 +59,7 @@ http {
# Proxy API calls to backend # Proxy API calls to backend
location /api { location /api {
# Use Docker bridge gateway so container can reach host's backend proxy_pass http://backend:3001;
# 172.17.0.1 is the common Docker bridge gateway; adjust if different
proxy_pass http://172.17.0.1:3001;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade'; proxy_set_header Connection 'upgrade';

View File

@@ -46,5 +46,5 @@
"last 1 safari version" "last 1 safari version"
] ]
}, },
"proxy": "http://backend:3001" "proxy": "http://localhost:3001"
} }