GitLab cannot restrict who reads or edits a single file in a repository. Access is granted per project. You can still stop secrets from reaching the repository and control who changes sensitive paths by combining push rules, secret detection, protected branches and CODEOWNERS approvals. This page corrects the examples below, adds working configuration for each control, and explains what to do when a secret has already been committed.
Security
GitLab does not provide true file-level access control (like โonly Alice can read secrets.ymlโ) โ but it does provide tools to restrict access and prevent exposure of sensitive files using:
โ What You Can Do in GitLab (SaaS and Self-managed)
1. โ Push Rules for Sensitive Files
- Prevent commits that contain secrets, keys, passwords, or specific file names.
- Configure under:
Settings โ Repository โ Push Rules
Example:
- Reject commits with
.envor*.pemfiles:
Forbidden file names: ^(.env|.*\.pem)$
- Reject commits with AWS keys using regex:
Secret detection regex: AKIA[0-9A-Z]{16}
2. โ Protected Branches
- Prevent unauthorized push/merge to sensitive branches like
main,release, etc. - Set under:
Settings โ Repository โ Protected Branches
3. โ Code Owners for Sensitive Files
- Define ownership for sensitive files using a
CODEOWNERSfile. - Prevent changes to specific paths unless approved by listed owners.
Example:
/secrets/* @devops-lead @security-team
Code language: PHP (php)
4. โ Secret Detection (SAST/Static Scanning)
- GitLab CI/CD automatically scans for hardcoded secrets and keys.
- Available in GitLab Ultimate and in some parts of Premium.
- Found under:
Security & Compliance โ Vulnerability Report
5. โ File Pattern Merge Request Rules (Paid)
- Use merge request approval rules for changes to specific file paths (e.g., secrets, configs).
Example:
Rule: If /infra/keys/* is changed โ require @security-team to approve
Code language: PHP (php)
โ What You Cannot Do Directly in GitLab
| Feature | GitLab Status |
|---|---|
| Per-file access control (ACL-style) | โ Not supported |
| Per-user permission to view/edit specific files | โ Not supported |
| Encryption-at-rest per file inside repo | โ Not native (requires external tools) |
๐ Recommended Best Practices
| Goal | GitLab Feature to Use |
|---|---|
| Prevent secrets in repo | Push rules + Secret detection + .gitignore |
| Limit merge to sensitive files | CODEOWNERS + Approval Rules |
| Block commits with unsafe patterns | Push Rules + Pre-commit Hooks (externally) |
| Enforce audits of sensitive changes | Merge request rules with approval |
Why GitLab has no per-file access control
Git copies the whole repository to every clone, so any user who can clone a project can read every file in it. In GitLab, permission to read code comes from project or group membership and the project's visibility setting. It is never set per file or per folder. If someone has read access, every path is visible to them, secrets/ included.
The controls in the example above cover different jobs. Push rules and secret detection stop sensitive content from entering the repository. Protected branches and CODEOWNERS control who can change sensitive paths. None of them hides a file from someone who already has read access.
Note: If some files really must be readable by fewer people, move them to a separate project or group with tighter membership. That project can be consumed as a Git submodule or as a pipeline dependency. See GitLab Hierarchy: Organization, Namespace, Group & Project for how membership is inherited.
Corrections to the examples above
| Original | Problem | Corrected |
|---|---|---|
Forbidden file names: ^(.env|.*\.pem)$ | The field is called Prohibited file names. The regex is matched against the full file path, so ^.env$ misses config/.env. The unescaped . also matches any character. | (^|/)\.env$|\.pem$ |
Secret detection regex: AKIA[0-9A-Z]{16} | Push rules have no content regex field. They check file names, branch names, commit messages and author emails, not what is inside a file. | Use secret push protection or pipeline secret detection, both of which already detect AWS access keys. |
/secrets/* @devops-lead @security-team | In CODEOWNERS, /secrets/* matches only files directly inside secrets/ and skips its subdirectories. | /secrets/ @devops-lead @security-team |
| Secret detection "automatically scans" and is Ultimate-only | Pipeline secret detection only runs after you enable it in .gitlab-ci.yml (or through Auto DevOps). The scan works on every tier. Ultimate adds the vulnerability report and the merge request widget. | Include the Jobs/Secret-Detection.gitlab-ci.yml template. |
Security & Compliance โ Vulnerability Report | Outdated menu path. | Secure > Vulnerability report |
| "File pattern merge request rules" | GitLab approval rules have no file-path condition. Path-based approval comes from CODEOWNERS combined with the protected branch setting Require approval from code owners. | Use a CODEOWNERS section, as shown below. |
Note: Push rules and CODEOWNERS approvals need GitLab Premium or Ultimate. On the Free tier, use pre-commit hooks and pipeline secret detection instead.
Configure push rules for sensitive file names
- Open the project and go to Settings > Repository > Push rules. To apply the same rules to every new project in a group, use the group-level push rules instead.
- Turn on Prevent pushing secret files. This built-in list rejects common credential file names, such as private SSH keys and
.pemfiles. - In Prohibited file names, enter a regex for anything the built-in list misses, for example
(^|/)\.env$|\.pem$|(^|/)secrets\.ya?ml$. - Select Save push rules, then test by pushing a commit that adds a
.envfile. The server should reject the push.
Push rules check only new commits as they are pushed. Files that are already in the repository are not affected, so search the existing history separately (see the section on committed secrets below).
Detect secrets inside file contents
GitLab offers two content scanners. Secret push protection (Ultimate) checks pushed changes for high-confidence secret patterns, such as cloud provider keys and tokens, and blocks the push before the secret lands. Enable it in Secure > Security configuration. On self-managed instances, an administrator must allow it for the instance first. Pipeline secret detection runs as a CI job after the commit has been pushed, and it works on every tier.
stages:
- test
include:
- template: Jobs/Secret-Detection.gitlab-ci.yml
secret_detection:
variables:
# Scan the full Git history once; remove after the first run
SECRET_DETECTION_HISTORIC_SCAN: "true"Code language: PHP (php)
The template adds a secret_detection job to the test stage, so that stage must exist. The job writes a gl-secret-detection-report.json artifact. On Ultimate, the findings also appear in the merge request and under Secure > Vulnerability report. Setting the historic scan variable once is a good way to find secrets that were committed before scanning was turned on.
To catch secrets before they leave a developer's machine, add a local hook such as gitleaks through the pre-commit framework:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: vX.Y.Z # replace with the current gitleaks release tag
hooks:
- id: gitleaks
# then run once per clone:
# pip install pre-commit && pre-commit installCode language: PHP (php)
Note: Local hooks are easy to bypass with git commit --no-verify. Use them for fast feedback only, and rely on the server-side controls for enforcement.
Require approval for sensitive paths with CODEOWNERS
Place a CODEOWNERS file in the repository root, in docs/ or in .gitlab/. Sections let you require more than one approval for a group of paths:
# .gitlab/CODEOWNERS
[Security][2] @security-team
/secrets/
/infra/keys/
*.tfvars
[Platform] @devops-lead
/.gitlab-ci.yml
/infra/Code language: PHP (php)
[Security][2] sets @security-team as the default owner for the paths listed under it and requires two approvals from that team. A trailing slash such as /infra/keys/ matches everything below that directory, at any depth.
- Commit the CODEOWNERS file to the default branch.
- Go to Settings > Repository > Protected branches and protect
main. Set Allowed to push and merge to No one, so every change has to go through a merge request. - Turn on Code owner approval for that branch.
- Open a test merge request that changes
/infra/keys/and confirm that the Security approval rule appears and blocks the merge.
Keep secrets out of the repository entirely
The controls above stop mistakes. The lasting fix is to keep credentials outside Git altogether:
- CI/CD variables (Settings > CI/CD > Variables): mark them Masked so values are redacted in job logs, and Protected so they are available only to pipelines on protected branches and tags.
- External secret managers: the
secrets:keyword (Premium) fetches values from HashiCorp Vault and other providers at job runtime, authenticating with short-livedid_tokens. - Encrypted files: if configuration must live in Git, encrypt it with a tool such as SOPS or git-crypt, and keep the decryption keys out of the repository.
.gitignore: list.env,*.pemand local credential files, so they are never staged by accident.
deploy:
id_tokens:
VAULT_ID_TOKEN:
aud: https://vault.example.com
secrets:
DATABASE_PASSWORD:
vault: production/db/password@ops # path/field@mount
token: $VAULT_ID_TOKEN
script:
- ./deploy.sh # DATABASE_PASSWORD is written to a temp file; the variable holds its pathCode language: PHP (php)
By default, a secret fetched this way is written to a file, and the variable holds that file's path. Add file: false under the secret if the script needs the value itself.
For more pipeline patterns, see What is GitLab CI/CD and use cases of GitLab CI/CD?.
If a secret was already committed
- Revoke and rotate the credential first. Assume it is compromised: clones, forks, CI logs and caches may already hold a copy.
- Remove the file from history in a fresh mirror clone, for example
git filter-repo --path config/.env --invert-paths. - Force-push the rewritten branches and tags. Protected branches must temporarily allow force push for this step.
- In GitLab, go to Settings > Repository > Repository cleanup and upload the
commit-mapfile that git-filter-repo generated, so GitLab removes the unreachable objects. - Ask everyone to re-clone, and add the file pattern to push rules so it cannot come back.
Note: Rewriting history without rotating the credential does not make it safe. Anyone who copied the secret before the rewrite can still use it.
Feature availability by tier
| Control | Free | Premium | Ultimate |
|---|---|---|---|
| Protected branches | Yes | Yes | Yes |
| Masked and protected CI/CD variables | Yes | Yes | Yes |
| Pipeline secret detection (job and report artifact) | Yes | Yes | Yes |
| Push rules, including prohibited file names | No | Yes | Yes |
| CODEOWNERS with required code owner approval | No | Yes | Yes |
secrets: keyword with external managers | No | Yes | Yes |
| Secret push protection, vulnerability report, MR security widget | No | No | Yes |
Tier packaging changes between releases, so check the current GitLab documentation for your edition before you plan a rollout.
Frequently asked questions
Can I restrict who can view a specific file in a GitLab repository?
No. Read access is granted per project, and anyone who can clone the repository can read every file in it. Move sensitive files to a separate project with restricted membership, or keep them out of Git and use CI/CD variables or a secret manager.
Are GitLab push rules available on the Free tier?
No. Push rules, including Prevent pushing secret files and Prohibited file names, require Premium or Ultimate. On Free, use pre-commit hooks and pipeline secret detection.
Does GitLab scan for secrets automatically?
Pipeline secret detection runs only after you include the Jobs/Secret-Detection.gitlab-ci.yml template or enable Auto DevOps. Secret push protection, which blocks secrets at push time, has to be switched on in Secure > Security configuration and requires Ultimate.
How do I make the security team approve changes to certain folders?
List the paths under a CODEOWNERS section owned by the security team, then turn on Code owner approval for the target protected branch. Merge requests that touch those paths cannot be merged until the required owners approve.
How do I remove a leaked secret from GitLab history?
Rotate the credential first. Then rewrite history with git filter-repo, force-push, and upload the generated commit-map in Settings > Repository > Repository cleanup so GitLab deletes the old objects.
Related tutorials
- GitLab for Practical Pipelines, Secure Delivery, and Faster Releases
- What is GitLab CI/CD and use cases of GitLab CI/CD?
- GitLab Hierarchy: Organization, Namespace, Group & Project
- More GitLab tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals