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 {
// 1. Run all heavy lifting (builds) on the dedicated Agent
// 1. Run heavy lifting (Build/Push) on the Agent
agent { label 'jenkins-agent' }
environment {
// --- REGISTRY & REPOSITORY FIXES ---
// CRITICAL FIX: Use the Registry Name we verified via 'doctl'
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}"
FRONTEND_TAG = "frontend-${env.BRANCH_NAME}-${env.BUILD_NUMBER}"
// --- DEPLOYMENT TARGET ---
// Deployment Target (The Gitea Server)
DEPLOY_HOST = 'gitea.kongseng.in'
DEPLOY_USER = 'root'
}
@@ -23,8 +25,9 @@ pipeline {
stage('Install Dependencies') {
steps {
echo "Installing dependencies for ${env.BRANCH_NAME} branch..."
// Assuming Node is installed on the agent
echo "Installing dependencies for ${env.BRANCH_NAME}..."
// Ensure folders exist to avoid errors
sh 'ls -la'
dir('backend') { sh 'npm install' }
dir('frontend') { sh 'npm install' }
}
@@ -33,7 +36,7 @@ pipeline {
stage('Build Docker Images') {
steps {
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}:${FRONTEND_TAG} ./frontend"
}
@@ -42,78 +45,66 @@ pipeline {
stage('Push to Registry') {
steps {
// We MUST inject the token here, or the push will fail with "Unauthorized"
withCredentials([string(credentialsId: 'do-registry-token', variable: 'DO_TOKEN')]) {
script {
echo "Logging into DigitalOcean Registry..."
// Clean login for robustness
echo "Logging into Registry..."
// 1. Clean previous state
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'
echo "Pushing images..."
sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}"
sh "docker push ${REGISTRY_URL}/${REPO_NAME}:${FRONTEND_TAG}"
// 3. Logout
sh 'docker logout registry.digitalocean.com'
}
}
}
}
stage('Remote Deploy') {
// --- REMOTE DEPLOYMENT (AGENT -> GITEA SERVER) ---
stage('Deploy') {
steps {
script {
echo "--- REMOTE DEPLOYMENT STARTED ---"
// 1. Define Dynamic Ports and Names
def backPort = "3000"
def frontPort = "4000"
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"; }
// Define Ports based on Branch
def appPort = "3000"
if (env.BRANCH_NAME == 'Dev') { appPort = "3001" }
else if (env.BRANCH_NAME == 'Release') { appPort = "3002" }
else if (env.BRANCH_NAME == 'main') { appPort = "3003" }
def backName = "backend-${env.BRANCH_NAME}"
def frontName = "frontend-${env.BRANCH_NAME}"
def containerName = "backend-${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}"
// 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')]) {
// Remote Login (Gitea Server needs to pull)
// 1. Remote Login
sh "${remote} 'echo ${DO_TOKEN} | docker login registry.digitalocean.com -u token --password-stdin'"
// --- BACKEND DEPLOYMENT (Primary Service) ---
echo "Deploying Backend to Port ${backPort}..."
// 2. Remote Pull
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 """
${remote} 'docker run -d \
--name ${backName} \
--name ${containerName} \
--restart always \
-p ${backPort}:3001 \
-p ${appPort}:3000 \
${REGISTRY_URL}/${REPO_NAME}:${BACKEND_TAG}'
"""
// --- FRONTEND DEPLOYMENT (Secondary Service) ---
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}"
echo "SUCCESS: App is live at http://${DEPLOY_HOST}:${appPort}"
}
}
}
@@ -122,9 +113,7 @@ pipeline {
post {
always {
// Cleanup: Delete source code and clean Docker cache on the Agent
echo 'Cleaning Agent workspace...'
deleteDir()
// Save disk space on the Agent
sh 'docker system prune -f'
}
}

View File

@@ -14,8 +14,8 @@ COPY package*.json ./
# Install dependencies
RUN npm ci --only=production && npm cache clean --force
# Copy all application files
COPY . ./
# Copy application files
COPY server.js ./
# Create logs directory and set permissions
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 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3001/health || exit 1
# Expose port 3001 for backend
# Expose port
EXPOSE 3001
# Start the application

View File

@@ -2,20 +2,21 @@ const express = require('express');
const cors = require('cors');
require('dotenv').config();
// Load secrets from environment variables (never hardcode secrets!)
const AWS_ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID;
const AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY;
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
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;
// TESTING: Dummy secrets for TruffleHog detection - SHOULD TRIGGER SECURITY SCAN!
const AWS_ACCESS_KEY_ID = 'AKIAIOSFODNN7EXAMPLE';
const AWS_SECRET_ACCESS_KEY = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';
const GITHUB_TOKEN = 'ghp_1234567890abcdef1234567890abcdef12345678';
// No-op variable used only to trigger CI/CD pipelines on small pushes
const TRIGGER_PIPELINE_VAR = 'trigger-20251130';
// Additional test secrets for comprehensive detection
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 PORT = process.env.PORT || 3001;
@@ -183,7 +184,7 @@ app.use((err, req, res, next) => {
});
// Start server
app.listen(PORT, '0.0.0.0', () => {
app.listen(PORT, () => {
console.log(`🚀 Backend server running on port ${PORT}`);
console.log(`📊 Health check: http://localhost:${PORT}/health`);
console.log(`📝 API endpoints: http://localhost:${PORT}/api/todos`);
@@ -191,3 +192,4 @@ app.listen(PORT, '0.0.0.0', () => {
});
module.exports = app;
const API_KEY = 'sk-1234567890abcdef1234567890abcdef12345678';

View File

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

View File

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