Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block push to master branch on remote

Tags:

git

linux

Is there any way to block code push directly to master? I tried adding a script in .git/hooks/update:

#!/bin/sh
if [ $USER != "git-repo-admin" ];
then
  if [ "$1" == refs/heads/master ];
  then
    echo "Manual pushing to this repo is restricted"
    exit 1
  fi
fi

But this doesn't work - Everybody can still push. I want to allow only specific users to push to master and block others.

like image 637
Mitul Avatar asked Sep 26 '13 07:09

Mitul


People also ask

How do I stop push to GitHub?

The trick to prevent accidentally pushing in-development changes to the wrong environment is to use the git command for changing remote's URL. By adding the --push flag to the command, only the push URL is manipulated.


2 Answers

The original script was perfect, I just needed to rename it from .git/hooks/update.sample to .git/hooks/update on the remote server and make sure it's executable.

#!/bin/sh
if [ $USER != "git-repo-admin" ];
then
  if [ "$1" == refs/heads/master ];
  then
    echo "Manual pushing to this repo is restricted"
    exit 1
  fi
fi
like image 83
Mitul Avatar answered Oct 19 '22 20:10

Mitul


Using git hooks to control access might be useful as a once-off hack but can be a slippery slope leading to a hard-to-maintain git server configuration.

Thus, I would recommend setting up gitolite, which is precisely done for this kind of access control.
It manages bare repos (which are good for pushing).

You can find an example of preventing a push in a branch in "Gitolite permissions on branches":

repo @project
    RW+        = @git-repo-admin
    R   master = @developers
    -   master = @developers
    RW+        = @developers

Gitolite can rely on ssh for the authentication part, and automate the public key registration process.

But without Gitolite, you still can protect read/write access to a Git repo using ssh only, as described in "Git on the Server - Setting Up the Server" of the Pro Git Book (as mentioned by Anthony Geoghegan in the comments)

As an extra precaution, you can easily restrict the 'git' user to only doing Git activities with a limited shell tool called git-shell that comes with Git.
If you set this as your 'git' user’s login shell, then the 'git' user can’t have normal shell access to your server. To use this, specify git-shell instead of bash or csh for your user’s login shell. To do so, you’ll likely have to edit your /etc/passwd file.

like image 35
VonC Avatar answered Oct 19 '22 18:10

VonC