How can you block git commits from invalid users?

这一生的挚爱 提交于 2019-12-10 16:26:52

问题


I am running a gitlab git server.

Most of my users are running 1 of 3 versions of git.

git 1.7.1 (centos users)
git 1.7.9 (everyone else)
git 1.8.4 (mac users)

Some users have accidentally been committing and pushing code as the root user. I need to block commits from those users.

My pre-commit hook looks like this:

#!/bin/bash

if [[ $GIT_AUTHOR_NAME == 'root' ]]
then
    echo "If you commit as root, you're gonna have a bad time";
    echo "Set 'git config user.name' and try again";
    exit 1;
fi

This works as a pre-commit hook on 1.7.9 and 1.8.x but not 1.7.1

According to this blog, pre receive and post receive hooks do not have any of the environment variables that I am looking for ( GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, GIT_AUTHOR_DATE, GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL, GIT_COMMITTER_DATE, EMAIL ).

Is there any way to modify this pre-commit hook to block root users on older versions of git?

http://longair.net/blog/2011/04/09/missing-git-hooks-documentation/


回答1:


Why don't you put the check in a pre-receive hook i.e., do the authetication on the server side when the code is about to be committed to the central git repository/server.

#Extract commiter names here.
commiters=$(git log --pretty=format:"%cn" $revs) #This should work in all git versions

printf "$commiters\n" | while read name; do
     if [[ $name == "root" ]]; then
      echo "You are commiting as root user which I don't like. Reveal your identity!"
      exit 1
     fi
done



回答2:


Set up e.g. gitolite (there should be packages for your server's system), and configure it so that only approved users can push. If they switch to root the credentials won't match, and the push will be refused. It gives you detailed control over the branches each one has access to.




回答3:


You can encourage your users to use the pre-commit hook on their side as a mitigation, but ultimately your will have to reject the pushes on the server side to have the policy fully enforced.

One thing that you can do is to employ an update hook that will reject pushes of commits that have been made by the root author. Add this to your .git/hooks/update:

git log --format="%h %an" ${2}..${3} | while read COMMIT_HASH COMMIT_AUTHOR; do
    if [ "$COMMIT_AUTHOR" = "root" ]; then
        echo "Updating ${1} by root is not allowed, offending commit: $COMMIT_HASH"
        exit 1
    fi
done

The snippet will parse all the commits between the old revisions and the new revision being pushed and will reject the push if any of these commits has root as the author. Also, make sure that the hook is executable!



来源:https://stackoverflow.com/questions/22491942/how-can-you-block-git-commits-from-invalid-users

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!