如何通过git pre-receive hook验证用户

时间:2016-06-24 13:58:27

标签: python git authentication githooks

我希望用Python编写一个pre-receive githook。我的理解是,没有参数传递给pre-receive脚本,而是使用标准输入在不同的行上传递每个引用。我已经能够通过以下方式阅读参考更改:

!/usr/bin/env python

import sys
import fileinput

for line in fileinput.input():
    print "pre-receive: Trying to push ref: %s" % line

但是,对于这个钩子,我主要关心的是确保用户推送代码具有正确的权限,以推送到他们正在尝试的分支。通过我的研究,我一直无法找到寻找提交者用户凭据的方法。我的目标是将他们的信用与白名单进行比较,以便授予访问权限。

如何更改我的pre-receive代码以对提交用户进行身份验证并验证它们是否已列入白名单以推送到其尝试的分支?如果有的话,我必须在git存储库上进行哪些更改才能使代码生效?

2 个答案:

答案 0 :(得分:3)

从标准输入,我们可以获得<old-value> SP <new-value> SP <ref-name> LF。在钩子中使用git cat-file -p $new-valuegit cat-file -p $ref-name,我们可以获得这样的信息

tree d06734b17feff2faf22bcd7c0fac1587876e601d
parent 524bd5e2fa72e6358a22f28582e094de936c3768
author Xyz <mm@nn.com> 1466782764 +0800
committer Abc <ss@tt.com> 1466782764 +0800

或者以更简单的方式,我们可以使用git log -1 --pretty=%an $ref-name来获取作者,并使用git log -1 --pretty=%cn $ref-name来获取提交者。

因此bash中钩子的一部分可能是:

#!/bin/bash

read old new ref
author=$(git log -1 $ref --pretty=%an)
committer=$(git log -1 $ref --pretty=%cn)
echo author:$author
echo committer:$committer

左边部分是检查作者或提交者是否有权做某事。

我在python中实现你的钩子的版本是

#!/usr/bin/env python

import sys
import fileinput
import commands

for line in fileinput.input():
    print "pre-receive: Trying to push ref: %s" % line
    values = line.split()
    old = values[0]
    new = values[1]
    ref = values[2]
    author = ''
    committer = ''
    status,output = commands.getstatusoutput('git log -1 --pretty=%an {0}'.format(ref))
    if status == 0:
        author = output
    status,output = commands.getstatusoutput('git log -1 --pretty=%cn {0}'.format(ref))
    if status == 0:
        committer = output

答案 1 :(得分:1)

如果你在ssh(或本地文件系统中的git)上使用git,那么提交用户可以在环境变量USER中使用钩子,所以在python中你可以检查os.environ['USER']

可以设置一个环境(使用git-daemon;还有其他方法),你的git服务器收到一个包,并且没有任何连接的身份验证信息;在那种情况下,你运气不好。