MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Gitlab FAQ

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 .env or *.pem files:
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 CODEOWNERS file.
  • 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

FeatureGitLab 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

GoalGitLab Feature to Use
Prevent secrets in repoPush rules + Secret detection + .gitignore
Limit merge to sensitive filesCODEOWNERS + Approval Rules
Block commits with unsafe patternsPush Rules + Pre-commit Hooks (externally)
Enforce audits of sensitive changesMerge 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

OriginalProblemCorrected
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-teamIn CODEOWNERS, /secrets/* matches only files directly inside secrets/ and skips its subdirectories./secrets/ @devops-lead @security-team
Secret detection "automatically scans" and is Ultimate-onlyPipeline 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 ReportOutdated 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

  1. 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.
  2. Turn on Prevent pushing secret files. This built-in list rejects common credential file names, such as private SSH keys and .pem files.
  3. In Prohibited file names, enter a regex for anything the built-in list misses, for example (^|/)\.env$|\.pem$|(^|/)secrets\.ya?ml$.
  4. Select Save push rules, then test by pushing a commit that adds a .env file. 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.

  1. Commit the CODEOWNERS file to the default branch.
  2. 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.
  3. Turn on Code owner approval for that branch.
  4. 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-lived id_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, *.pem and 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

  1. Revoke and rotate the credential first. Assume it is compromised: clones, forks, CI logs and caches may already hold a copy.
  2. Remove the file from history in a fresh mirror clone, for example git filter-repo --path config/.env --invert-paths.
  3. Force-push the rewritten branches and tags. Protected branches must temporarily allow force push for this step.
  4. In GitLab, go to Settings > Repository > Repository cleanup and upload the commit-map file that git-filter-repo generated, so GitLab removes the unreachable objects.
  5. 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

ControlFreePremiumUltimate
Protected branchesYesYesYes
Masked and protected CI/CD variablesYesYesYes
Pipeline secret detection (job and report artifact)YesYesYes
Push rules, including prohibited file namesNoYesYes
CODEOWNERS with required code owner approvalNoYesYes
secrets: keyword with external managersNoYesYes
Secret push protection, vulnerability report, MR security widgetNoNoYes

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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Packer Tutorials: Amazon Secrets Manager Data Source – amazon-secretsmanager

The amazon-secretsmanager data source lets a Packer HCL2 template read a secret from AWS Secrets Manager during a build, so passwords and tokens stay out of your…

Read More

DevOps in Banking: What Engineers Should Know Before Joining a Compliance Team

DevOps in banking follows a rule most tech companies can bend: every change to a production system needs an approval and a record someone can check later. …

Read More

How to Add an AI Model API to a DevOps Pipeline Safely

Adding an AI/ML service to a DevOps pipeline involves more than placing an API key in an environment variable. The team must decide which pipeline stages can…

Read More

Building an AI Video Pipeline: A DevOps Guide for Ad Teams

An AI video pipeline for advertising treats video generation like any other cloud workload: requests are submitted asynchronously, jobs are tracked and polled, outputs are validated automatically,…

Read More

Dark Web Explained for DevOps: What It Is, What It Isnโ€™t, and How to Reduce Risk

The dark web is a small, intentionally hidden part of the internet, often confused with the deep web. This guide explains the differences and gives DevOps teams practical steps to detect leaks, rotate secrets, and harden delivery pipelines.

Read More

Using AI assistants in DevOps without leaking your secrets

AI assistants have quietly become part of the everyday DevOps toolkit. Engineers use them to draft pipeline configurations, explain cryptic error messages, write shell scripts, summarise incident…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x