Petru Constantin rulează Kubernetes, Terraform și GitLab CI/CD în producție din 2022, întâi ca Senior DevOps engineer, iar acum ca IT project manager și specialist AI care lucrează în continuare direct pe infrastructură. Exemplele de cod sunt scrise pe documentația Kubernetes 1.37, GitHub Actions (actions/checkout v7, codeql-action v4, trivy-action v0.36.0), template-urile de securitate GitLab CI/CD actuale și OPA 1.x (Rego v1).
Securitatea Pipeline-ului DevSecOps: Integrarea Securității în CI/CD
DevSecOps reprezintă o schimbare fundamentală în modul în care organizațiile abordează securitatea - trecerea de la un control final înainte de deployment la o practică integrată pe tot parcursul ciclului de viață al dezvoltării software. Pipeline-ul CI/CD este locul unde această integrare prinde forma concretă.
Acest ghid oferă abordări practice pentru construirea pipeline-urilor securizate.
Arhitectură Pipeline-ului Securizat
┌─────────────────────────────────────────────────────────────────────────────┐
│ Secure CI/CD Pipeline │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Code │ → │ Build │ → │ Test │ → │ Deploy │ → │ Monitor │ │
│ │ Commit │ │ │ │ │ │ │ │ │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │ │ │
│ ▼ ▼ ▼ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Pre- │ │ SAST │ │ DAST │ │ Config │ │ Runtime │ │
│ │ commit │ │ SCA │ │ Security │ │ Audit │ │ Security │ │
│ │ Hooks │ │ Secrets │ │ Tests │ │ CSPM │ │ RASP │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Etapa 1: Securitate Pre-Commit
Configurare Git Hooks
# .pre-commit-config.yaml
repos:
# Secrets detection (create the baseline once: detect-secrets scan > .secrets.baseline)
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
args: ['--baseline', '.secrets.baseline']
# Python security linting (pre-commit passes the staged .py files)
- repo: https://github.com/PyCQA/bandit
rev: 1.9.4
hooks:
- id: bandit
args: ['-ll']
# Dockerfile linting
- repo: https://github.com/hadolint/hadolint
rev: v2.15.1
hooks:
- id: hadolint-docker
args: ['--ignore', 'DL3008']
# Terraform security (needs trivy and checkov installed locally)
- repo: https://github.com/antonbabenko/pre-commit-terraform
rev: v1.109.5
hooks:
- id: terraform_trivy
- id: terraform_checkov
# YAML linting (for K8s manifests)
- repo: https://github.com/adrienverge/yamllint
rev: v1.38.0
hooks:
- id: yamllint
args: ['-c', '.yamllint.yml']Hook-uri Custom de Securitate
#!/usr/bin/env bash
# .git/hooks/pre-commit
set -euo pipefail
echo "Running security checks..."
# Scan only the lines added in this commit (staged content, not the working tree)
ADDED_LINES="$(git diff --cached --unified=0 --no-color --diff-filter=ACM | grep -E '^\+[^+]' || true)"
SECRET_PATTERNS=(
'(password|passwd|secret|api[_-]?key)[[:space:]]*[:=][[:space:]]*["'\''][^"'\'']{8,}'
'AKIA[0-9A-Z]{16}'
'-----BEGIN ([A-Z]+ )?PRIVATE KEY-----'
)
for pattern in "${SECRET_PATTERNS[@]}"; do
# Here-string instead of a pipe: grep -q with pipefail can report a false "no match"
if grep -qiE -e "$pattern" <<< "$ADDED_LINES"; then
echo "ERROR: staged change matches secret pattern: $pattern" >&2
echo "Remove the secret before committing; if it was ever pushed, rotate it" >&2
exit 1
fi
done
# Block sensitive file types
SENSITIVE_REGEX='\.(pem|key|p12|pfx)$|(^|/)\.env(\.[^/]*)?$'
if git diff --cached --name-only --diff-filter=ACM | grep -E "$SENSITIVE_REGEX"; then
echo "ERROR: sensitive file type staged; use a secrets manager instead" >&2
exit 1
fi
echo "Pre-commit security checks passed"Etapa 2: Securitatea Build-ului
Pipeline Securizat GitHub Actions
# .github/workflows/secure-pipeline.yml
name: Secure CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
# Least privilege by default; jobs ask for more only where they need it.
permissions:
contents: read
# Version tags are shown for readability. Pin every action to a full commit SHA
# in production (GitHub secure-use guide); trivy-action is pinned that way below.
jobs:
sast:
runs-on: ubuntu-latest
# returntocorp/semgrep-action is deprecated; run the Semgrep CLI image instead
container:
image: semgrep/semgrep
permissions:
contents: read
security-events: write # upload SARIF to code scanning
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Run SAST (Semgrep)
run: semgrep scan --config auto --sarif --output semgrep.sarif
- name: Upload SAST results
if: always()
uses: github/codeql-action/upload-sarif@v4.39.3
with:
sarif_file: semgrep.sarif
category: semgrep
security-scan:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
steps:
- name: Checkout code
uses: actions/checkout@v7.0.1
with:
fetch-depth: 0 # full history for secret scanning
persist-credentials: false
# SCA - dependencies and lockfiles
- name: Run SCA (Trivy)
# trivy-action tags were force-pushed in March 2026 (GHSA-69fq-xp46-6x23): pin by SHA
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
scan-type: 'fs'
scan-ref: '.'
format: 'sarif'
output: 'trivy-sca.sarif'
severity: 'CRITICAL,HIGH'
- name: Upload SCA results
uses: github/codeql-action/upload-sarif@v4.39.3
with:
sarif_file: trivy-sca.sarif
category: trivy-fs
# Secret scanning over the git history
- name: Scan for secrets
uses: trufflesecurity/trufflehog@v3.99.9
with:
extra_args: --results=verified,unknown
# IaC scanning before anything is deployed
- name: Scan infrastructure config
uses: bridgecrewio/checkov-action@v12
with:
directory: ./terraform
framework: terraform
output_format: sarif
output_file_path: checkov.sarif
- name: Upload infrastructure scan
if: always()
uses: github/codeql-action/upload-sarif@v4.39.3
with:
sarif_file: checkov.sarif
category: checkov
build-and-scan:
needs: [sast, security-scan]
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4.4.1
- name: Build container image
uses: docker/build-push-action@v7.4.0
with:
context: .
push: false
load: true
tags: app:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
# Container image scanning
- name: Scan container image
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: 'app:${{ github.sha }}'
format: 'sarif'
output: 'trivy-container.sarif'
severity: 'CRITICAL,HIGH'
exit-code: '1'
- name: Upload container scan results
if: always()
uses: github/codeql-action/upload-sarif@v4.39.3
with:
sarif_file: trivy-container.sarif
category: trivy-image
# SBOM generation (the action uploads it as a workflow artifact by default)
- name: Generate SBOM
uses: anchore/sbom-action@v0.24.3
with:
image: app:${{ github.sha }}
format: spdx-json
output-file: sbom.spdx.json
# DAST against the image built in this job (images are not shared between jobs)
- name: Start the application
run: |
set -euo pipefail
docker run -d --name app -p 8080:8080 "app:${GITHUB_SHA}"
curl --fail --silent --show-error --retry 10 --retry-connrefused --retry-delay 3 \
http://localhost:8080/ > /dev/null
- name: Run DAST (OWASP ZAP baseline)
uses: zaproxy/action-baseline@v0.15.0
with:
target: 'http://localhost:8080'
rules_file_name: '.zap/rules.tsv'
cmd_options: '-a'
allow_issue_writing: false # no issues: write permission needed
artifact_name: zap-baseline
deploy-staging:
needs: build-and-scan
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: staging
permissions:
contents: read
id-token: write # OIDC token for AWS, no static access keys
steps:
- name: Configure AWS credentials (OIDC)
uses: aws-actions/configure-aws-credentials@v6.3.0
with:
role-to-assume: ${{ vars.AWS_STAGING_ROLE_ARN }}
aws-region: eu-central-1
- name: Deploy to staging
run: |
aws sts get-caller-identity
# your deployment command goes here (helm upgrade, terraform apply, ...)Pipeline Securizat GitLab CI
# .gitlab-ci.yml
stages:
- build
- test # GitLab security templates run in the test stage
- dast
variables:
SAST_EXCLUDED_PATHS: "spec, test, tests, tmp, vendor"
CS_IMAGE: "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" # image scanned by container_scanning
# Security scanning templates.
# License-Scanning.gitlab-ci.yml was removed in GitLab 17.0; license data comes from dependency scanning.
include:
- template: Jobs/SAST.gitlab-ci.yml
- template: Jobs/Secret-Detection.gitlab-ci.yml
- template: Jobs/Dependency-Scanning.v2.gitlab-ci.yml
- template: Jobs/Container-Scanning.gitlab-ci.yml
# Build and push with Buildah (no Docker-in-Docker daemon)
build:
stage: build
image: quay.io/buildah/stable
variables:
STORAGE_DRIVER: vfs
BUILDAH_FORMAT: docker
before_script:
- echo "$CI_REGISTRY_PASSWORD" | buildah login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
script:
- buildah build
--label "org.opencontainers.image.revision=$CI_COMMIT_SHA"
-t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" .
- buildah push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA"
# Custom dependency audit
security-audit:
stage: test
image: node:24-alpine
script:
- npm ci --ignore-scripts
- npm audit --audit-level=high
allow_failure: false
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
# Infrastructure scanning
infra-security:
stage: test
image:
name: bridgecrew/checkov:latest
entrypoint: [""]
script:
- checkov -d ./terraform --framework terraform --output cli --output junitxml --output-file-path ./checkov-results
artifacts:
when: always
reports:
junit: checkov-results/results_junitxml.xml
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
- "terraform/**/*"
# DAST baseline against staging (STAGING_URL is a CI/CD variable)
dast-baseline:
stage: dast
image: ghcr.io/zaproxy/zaproxy:stable
script:
- mkdir -p /zap/wrk
- zap-baseline.py -t "$STAGING_URL" -r zap-report.html || ZAP_EXIT=$?
- cp /zap/wrk/zap-report.html .
- exit "${ZAP_EXIT:-0}"
artifacts:
when: always
paths:
- zap-report.html
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCHEtapa 3: Integrarea Testării de Securitate
Configurare SAST (Semgrep)
# .semgrep.yml
rules:
- id: hardcoded-secret
pattern-regex: (?i)(password|secret|api_key|token)\s*=\s*['"][^'"]{8,}['"]
message: Hardcoded secret detected
languages: [python, javascript, typescript, java]
severity: ERROR
- id: sql-injection
# pattern-either = logical OR; a list under "patterns" would require all of them at once
pattern-either:
- pattern: $CURSOR.execute("..." + $INPUT, ...)
- pattern: $CURSOR.execute("..." % $INPUT, ...)
- pattern: $CURSOR.execute(f"...", ...)
message: Potential SQL injection, use parameterized queries
languages: [python]
severity: ERROR
- id: unsafe-deserialization
pattern-either:
- pattern: pickle.loads($X)
- pattern: pickle.load($X)
message: Unsafe deserialization with pickle
languages: [python]
severity: ERROR
- id: command-injection
pattern-either:
- pattern: subprocess.$FUNC($CMD, ..., shell=True, ...)
- pattern: os.system($CMD)
message: Potential command injection
languages: [python]
severity: ERRORConfigurare SCA (Dependabot + Renovate)
# .github/dependabot.yml
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "daily"
open-pull-requests-limit: 10
labels:
- "dependencies"
- "security"
groups:
security-patches:
applies-to: security-updates
patterns:
- "*"
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
groups:
security-patches:
applies-to: security-updates
patterns:
- "*"
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "terraform"
directory: "/terraform"
schedule:
interval: "weekly"{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:recommended",
":semanticCommits"
],
"vulnerabilityAlerts": {
"enabled": true,
"labels": ["security"]
},
"osvVulnerabilityAlerts": true,
"packageRules": [
{
"matchUpdateTypes": ["patch", "minor"],
"matchCurrentVersion": "!/^0/",
"automerge": true,
"automergeType": "pr",
"automergeStrategy": "squash"
},
{
"matchDepTypes": ["devDependencies"],
"automerge": true
},
{
"matchUpdateTypes": ["major"],
"labels": ["major-update"]
}
]
}Etapa 4: Securitatea Containerelor
Dockerfile Securizat
# Dockerfile with security best practices
# Pin a version, not latest (Node.js 24 is an LTS line; pin the full tag or the digest)
FROM node:24-alpine AS builder
WORKDIR /app
# Copy only package files first for better caching
COPY package*.json ./
# Full install: the build step needs devDependencies
RUN npm ci
COPY . .
# Build, drop devDependencies, then audit what ships
RUN npm run build && \
npm prune --omit=dev && \
npm audit --omit=dev --audit-level=high
# Production stage
FROM node:24-alpine AS production
# Security updates
RUN apk upgrade --no-cache && \
apk add --no-cache dumb-init
# Create non-root user (UID 1001 matches runAsUser in the Kubernetes manifest)
RUN addgroup -g 1001 -S appgroup && \
adduser -u 1001 -S appuser -G appgroup
WORKDIR /app
# Copy built application
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /app/package.json ./
ENV NODE_ENV=production
ENV NPM_CONFIG_LOGLEVEL=warn
# Numeric UID so Kubernetes can verify runAsNonRoot
USER 1001:1001
# healthcheck.js must be part of the build output in dist/
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD ["node", "dist/healthcheck.js"]
# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "dist/server.js"]
# Labels
LABEL org.opencontainers.image.source="https://github.com/org/repo"
LABEL org.opencontainers.image.description="Application description"
LABEL org.opencontainers.image.licenses="MIT"Politici de Securitate Kubernetes
# k8s/security-policies.yaml
# Pod Security Admission: enforce the "restricted" Pod Security Standard on the namespace
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: v1.37
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/audit: restricted
---
# A Deployment that passes the restricted profile
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
namespace: production
spec:
replicas: 2
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 1001
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: registry.example.com/myapp:1.0.0
ports:
- containerPort: 8080
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true # hardening, not required by the restricted profile
capabilities:
drop: ["ALL"]
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}
---
# Network Policy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: app-network-policy
namespace: production
spec:
podSelector:
matchLabels:
app: myapp
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: api-gateway
ports:
- protocol: TCP
port: 8080
egress:
- to:
- podSelector:
matchLabels:
app: database
ports:
- protocol: TCP
port: 5432
- to:
- namespaceSelector: {}
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
---
# Resource Quotas
apiVersion: v1
kind: ResourceQuota
metadata:
name: security-quota
namespace: production
spec:
hard:
pods: "20"
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40GiEtapa 5: Conformitate ca și Cod
Policy as Code (OPA/Rego)
# policies/kubernetes.rego (Rego v1 syntax: "contains" and "if" in rule heads)
package kubernetes.admission
# Deny containers that may run as root (neither container nor pod sets runAsNonRoot)
deny contains msg if {
input.request.kind.kind == "Pod"
some container in input.request.object.spec.containers
not container.securityContext.runAsNonRoot
not input.request.object.spec.securityContext.runAsNonRoot
msg := sprintf("Container %v must run as non-root", [container.name])
}
# Require resource limits
deny contains msg if {
input.request.kind.kind == "Pod"
some container in input.request.object.spec.containers
not container.resources.limits
msg := sprintf("Container %v must have resource limits", [container.name])
}
# Deny privileged containers
deny contains msg if {
input.request.kind.kind == "Pod"
some container in input.request.object.spec.containers
container.securityContext.privileged
msg := sprintf("Container %v must not be privileged", [container.name])
}
# Require approved registries
deny contains msg if {
input.request.kind.kind == "Pod"
some container in input.request.object.spec.containers
not startswith(container.image, "gcr.io/my-project/")
not startswith(container.image, "docker.io/library/")
msg := sprintf("Container %v uses unapproved registry", [container.name])
}
# Require security scanning label
deny contains msg if {
input.request.kind.kind == "Deployment"
not input.request.object.metadata.labels["security-scanned"]
msg := "Deployment must have security-scanned label"
}Monitorizare și Alerte
# prometheus-alerts.yml
# The metric names below are examples: Prometheus has no such metrics by default.
# Your scanners or CI jobs must export them (for example through a Pushgateway).
groups:
- name: security-alerts
rules:
- alert: SecurityScanFailed
expr: security_scan_status{result="failed"} > 0
for: 5m
labels:
severity: critical
annotations:
summary: Security scan failed
description: "Security scan failed for {{ $labels.project }}"
- alert: HighVulnerabilityDetected
expr: security_vulnerabilities{severity="critical"} > 0
for: 1m
labels:
severity: critical
annotations:
summary: Critical vulnerability detected
description: "Critical vulnerability in {{ $labels.image }}"
- alert: UnauthorizedDeployment
expr: deployment_without_approval > 0
for: 1m
labels:
severity: warning
annotations:
summary: Deployment without security approval
- alert: SecretExposed
expr: secret_scan_detections > 0
for: 1m
labels:
severity: critical
annotations:
summary: Secret exposed in codeConcluzie
Fiecare etapă de mai sus adaugă o verificare, dar o verificare te protejează doar dacă rulează la fiecare schimbare și dacă eșecul ei oprește merge-ul sau deployment-ul. Ține verificările rapide (secrete, lintere) în pre-commit și repetă-le în CI, pentru că un hook local poate fi sărit cu git commit --no-verify.
Concluzii principale:
- Shift left - Prinde problemele cât mai devreme posibil
- Automatizează totul - Verificările manuale de securitate nu scalează
- Eșuează rapid - Blochează codul nesigur să avanseze în pipeline
- Măsoară și îmbunătățește - Urmărește metricile de securitate în timp
- Echilibrează securitatea și viteza - Securitatea nu ar trebui să fie un bottleneck
Resurse Conexe
- ML CI/CD: Continuous Integration and Deployment for Machine Learning: Aplică securitatea CI/CD pe pipeline-uri ML
- MLOps Security: Securing Your ML Pipeline: Securitate specifică pipeline-urilor ML
- MLOps Best Practices: Building Production-Ready ML Pipelines: Arhitectură pipeline-urilor de producție
- Common MLOps Mistakes and How to Avoid Them: Inclusiv capcanele deployment-ului manual
- What is MLOps?: Prezentare completă MLOps
Din producție
JARVIS, sistemul multi-agent pe Claude Code care operează DeviDevs, aplică aceeași idee pe propriul repository. Scanarea de secrete rulează pe conținut la commit, iar motivul e scris în cod: un secret ajuns în istoricul git nu se mai retrage, cheia trebuie rotită. Între 7 septembrie și 15 noiembrie 2026, verificarea a produs 45 de blocări reale. O regulă de shell blochează curl | bash, process substitution și $(curl ...) dat unui interpretor, fail-closed: 299 de blocări reale în aceeași perioadă. O lecție se aplică oricărui pipeline: testele care există, dar nu rulează, nu protejează nimic. Până în septembrie 2026 testele hook-urilor nu le rula nimeni, nici CI, nici pre-commit; apoi au primit un runner.
Surse oficiale
- Pod Security Admission | Kubernetes
- Pod Security Standards | Kubernetes
- GHSA-69fq-xp46-6x23 - aquasecurity/trivy security advisory
- semgrep-action (GitHub)
- License scanning of CycloneDX files | GitLab Docs
- Secure use reference - GitHub Docs
Pe același subiect: Securitate containere Kubernetes: ghid DevSecOps, Automatizarea Testelor de Securitate API: Acoperirea OWASP API Top 10, Securitatea aplicatiilor in SDLC: Mutarea securitatii la stanga. Mai multe articole în categoria DevSecOps, iar munca de inginerie din spatele lor e pe pagina de servicii.
Ai nevoie de un sistem AI construit și pus în producție, cu obiectivele stabilite în scris și garanția de livrare? Vezi prețul și garanția unui Sprint DeviDevs →