TL;DR
Learn essential security best practices for GitLab, including access controls, secret management, security scanning, and compliance configurations.
GitLab Security Best Practices: A Complete Guide
Executive Summary
Securing GitLab means securing the system that holds your source code, your build pipeline, and often the credentials your pipeline uses to deploy. A compromise here is not one application breach; it is the means to produce trusted malicious code. This guide covers the controls that carry the most weight: least-privilege access with two-factor authentication, protected branches and approval rules that make the default branch hard to change quietly, secret management that keeps credentials out of the repository and masked in logs, the scanning suite wired into merge requests, and audit and compliance features that make the whole thing reviewable. You will finish able to prioritise these controls by risk rather than by checklist order.
Why This Matters
Source control and CI concentrate trust. Developers push code that a pipeline builds and a deployment credential promotes to production, often with little human contact in between. Attackers understand this: a leaked CI variable, an over-privileged personal access token, or a merge request approved without review can each become a production compromise that arrives through your own legitimate process and is signed by your own infrastructure. The controls in this guide are therefore not hygiene theatre. Branch protection and approvals defend the integrity of what gets built. Secret management defends the credentials the build uses. Scanning defends against known-bad code and dependencies entering the flow. Audit events are how you find out any of it failed.
Core Concepts
Identity and Access: Least Privilege, Enforced
Start with accounts. Enforce two-factor authentication at the instance or group level, integrate single sign-on where your tier and identity provider support it, and review membership on a cadence, because group membership accumulates and departed contractors rarely remove themselves.
# config/gitlab.rb gitlab_rails['two_factor_authentication_required'] = true
Assign the lowest role that does the job. Reporter for read-only visibility, Developer for contributing work, Maintainer for configuration and merging, Owner only for those who administer the group. Watch for the quiet escalations: personal access tokens with broad scopes and no expiry, deploy keys with write access, and project access tokens created for one job that become permanent infrastructure. Tokens are accounts; inventory and expire them like accounts.
Protected Branches and Merge Controls
The default branch and any release branch should be protected: no direct pushes, no force pushes, merges only through merge requests, and stale approvals dismissed when new commits are pushed.
# .gitlab/branch-protection.yml
main:
allowed_to_push:
- maintainers
allowed_to_merge:
- maintainers
code_owner_approval_required: trueIn practice these settings live in project settings or the API; the file form is a useful reviewable record. Layer approval rules on top: a minimum number of approvals, approvals from code owners for the paths they own, and separate approval for security-sensitive areas such as pipeline configuration and infrastructure code.
# .gitlab/merge_request_approvals.yml
rules:
- name: security-review
approvers:
- security-team
applies_to:
- security/*
minimum_approvals: 2Protect the pipeline definition itself. A merge request that can edit .gitlab-ci.yml and immediately run with protected variables can bypass every other control, so require the pipeline to pass, prevent approvals from the author, and consider requiring review specifically for CI configuration changes.
Secret Management
The rule is absolute: secrets do not go in the repository, in any commit, at any point, because history is effectively permanent. Secrets live in CI/CD variables, masked so they do not print in logs, protected so they are only exposed to pipelines on protected branches, and scoped to the environment that needs them.
# .gitlab-ci.yml
variables:
DB_PASSWORD:
value: $DB_PASSWORD
masked: true
protected: trueMasking has limits: a value that is too short or contains characters outside the maskable set cannot be masked, and a job can transform a secret so the masked form never appears. Treat logs as readable by anyone with project access and design accordingly. For production credentials, prefer an external secrets manager and short-lived credentials fetched at job time over long-lived stored variables.
include:
- template: Vault/Access.gitlab-ci.yml
variables:
VAULT_SERVER_URL: 'https://vault.example.com'
job:
script:
- vault read secret/my-app/configaws_secrets:
script:
- aws secretsmanager get-secret-value
--secret-id production/api/keys
--query SecretString
--output textRotate on a schedule and immediately on suspicion, and use secret detection scanning on pushes and pipelines so a committed credential is caught in minutes, with the response being revocation first and history cleanup second.
Security Scanning in the Merge Request
GitLab's scanners shift findings to where they are cheapest: the merge request, before merge. Static analysis examines code for vulnerability patterns.
# .gitlab-ci.yml include: - template: Security/SAST.gitlab-ci.yml variables: SAST_EXCLUDED_PATHS: "spec, test, tests, tmp"
Dependency scanning evaluates lockfiles against vulnerability databases, and container scanning does the same for built images.
include:
- template: Security/Container-Scanning.gitlab-ci.yml
container_scanning:
variables:
CS_SEVERITY_THRESHOLD: "Critical"include:
- template: Security/Dependency-Scanning.gitlab-ci.yml
dependency_scanning:
variables:
DS_EXCLUDED_PATHS: "test/, spec/"Add infrastructure-as-code scanning for Terraform and Kubernetes manifests, secret detection as described above, and dynamic analysis against review apps for web applications where your tier supports it. Scanner availability and depth vary significantly by tier, so verify what your plan actually runs before writing policy that assumes it. Whatever runs, the operating model matters more than the tool list: findings land in the vulnerability report, are triaged to confirmed or dismissed with a reason, and a defined severity blocks merge. A scanner whose findings nobody triages is a cost centre producing ignored PDFs.
Vulnerability Management and Security Policy
The vulnerability report is the system of record: each finding has a state, an owner path, and the option to create an issue for scheduled remediation. For organisations that need enforcement independent of individual projects, security policies, managed centrally, can require scans to run, require approvals based on findings, and block merges that violate them. Central policy is powerful and must be rolled out carefully: a policy that blocks every merge on day one will be disabled by Friday, while one introduced in report-only mode and tightened severity by severity becomes durable.
Audit, Logging, and Compliance
Audit events record who changed what: membership, settings, approvals, and configuration. On self-managed instances, ensure audit logging is enabled and streamed to a system the GitLab administrators cannot alter, since the people you most need to audit are sometimes the administrators themselves.
# config/gitlab.rb gitlab_rails['audit_events_enabled'] = true gitlab_rails['audit_events_target'] = 'file'
Compliance frameworks label projects with the regime they fall under so reporting and policy can be scoped, and compliance pipelines can enforce a defined pipeline configuration for those projects. Treat compliance configuration as code: reviewed, versioned, and tested like the pipelines it governs.
Runner and Pipeline Security
Runners execute arbitrary code by design, so they are part of the security boundary. Unprivileged runners for untrusted work, protected runners for protected branches only, no privileged Docker on shared fleets, and no production network access from general CI. A job that can reach the production database does not need a vulnerability to be an incident; it only needs a malicious or mistaken script. Deployment credentials should be environment-scoped, short-lived where the platform supports it, and never available to pipelines from forks.
Application and Instance Hardening
For self-managed instances, the platform itself needs care: timely patching, because GitLab publishes security releases on a regular cadence and they are actively exploited when delayed; restricted sign-up and external access; rate limiting on authentication endpoints; and backups that are tested by restoration. The hardening guidance in your web server layer, TLS configuration, and security headers protects the web interface your administrators use daily.
# nginx configuration add_header X-Frame-Options "DENY" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always;
Decision Framework
| Situation | Recommendation |
|---|---|
| New project, no controls yet | Protect the default branch, require approvals and a passing pipeline, enforce 2FA at group level |
| Secrets currently in CI variables for production | Move production credentials to an external manager with short-lived access; rotate what was stored |
| A secret is committed | Revoke and rotate it first, then purge history and add secret detection to prevent recurrence |
| Scanners produce hundreds of findings | Triage by severity and reachability, set a merge-blocking threshold, and burn down in the open |
| Many projects need the same enforcement | Central security policies, introduced in report-only mode and tightened gradually |
| Forks contribute to the project | Ensure fork pipelines get no protected variables and run on unprivileged runners |
| Self-managed instance behind on patches | Treat patching as the highest-priority control; no other setting compensates |
Implementation Checklist
Trade-offs
Every control here costs velocity somewhere. Approval requirements slow trivial changes unless trivial paths are scoped out deliberately. Strict scanning gates produce false positives that consume triage time, and loosening them re-admits real risk. Short-lived credentials are safer and operationally harder than a stored variable that simply works. Central policies guarantee consistency and can become a bottleneck and a political problem when one team's exception is another team's outage. The task is not to maximise controls; it is to place friction where the risk is, production paths, secrets, pipeline definitions, and to keep the everyday path fast enough that nobody builds a workaround.
When Not to Use
Do not rely on GitLab's built-in scanners as your entire security programme if your risk profile demands more: organisations with heavy regulatory exposure, complex runtime threats, or large dependency estates often need dedicated application security tooling, runtime protection, and a software composition programme that goes beyond pipeline scanning. Do not store secrets in GitLab variables when a regulator or your own architecture already mandates a central vault with its own audit trail; integrate with it instead. Do not enforce organisation-wide merge-blocking policies before the findings backlog is understood; you will teach the organisation to route around security. And do not treat the checklist as a substitute for patching a self-managed instance, which remains the single highest-value activity on this page.
Conclusion
GitLab security is won at the boundaries: who can change the default branch, what credentials a pipeline can reach, and whether findings block or merely accumulate. Enforce identity, protect branches and pipeline configuration, keep secrets out and short-lived, scan in the merge request, and audit everything. Those controls, maintained, are what make the rest of the platform safe to trust.
References
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.