簡體   English   中英

在為 Google Source Repository 調用 git clone over HTTPS 時,有沒有辦法傳遞訪問令牌

[英]Is there a way to pass access tokens when calling git clone over HTTPS for Google Source Repository

我一直在嘗試使用 Google Cloud Functions (python 3.7) 來基本上克隆 Google Source Repository。 我正在使用GitPython庫,並且 Cloud Functions 的服務帳戶對我要克隆的存儲庫具有Source Repository Reader訪問權限。

最初,我嘗試將gcloud.sh credential.helper傳遞給 git 配置,但似乎 Cloud SDK 未安裝在 Cloud Functions 環境中(至少在 Python 3.7 環境中)。 這是我的代碼的要點:

from git import Repo
import tempfile

def git_clone():
    
    local_repo = tempfile.gettempdir()+'/localrepo'
    repo = Repo.init(local_repo)
    origin = repo.create_remote('origin', 'https://source.developers.google.com/p/PROJECT/r/REPO')

    repo.config_writer().set_value("user", "name", "gsr-to-gcs-backup-function").release()
    repo.config_writer().set_value("user", "email", "gsr-to-gcs-backup-function@PROJECT.iam.gserviceaccount.com").release()
    repo.config_writer().set_value("credential \"https://source.developers.google.com\"", "helper", "gcloud.sh").release()

    assert origin.exists()
    assert origin == repo.remotes.origin == repo.remotes['origin']
    
    origin.fetch()

如果在 Cloud Functions 上運行,function 將拋出以下錯誤,因為默認情況下,如果沒有憑證助手, https方法將詢問用戶名和密碼

git.exc.GitCommandError: Cmd('git') 失敗,原因是:退出代碼 (128) cmdline: git fetch -v origin stderr: 'fatal: could not read Username for 'https://source.developers.google.com ':輸入/輸出錯誤'

我只能找到以下答案來傳遞令牌以及git 克隆命令,但它沒有回答如何傳遞令牌:

在沒有 gcloud 的情況下克隆 Google Source Repository

如果我從雲 shell 啟動該命令,它將被掛起:

gcloud auth git-helper store --account=YOUR_ACCOUNT --ignore-unknown $@

這是我計划使用上述方法實現的類似內容(不是正確的代碼):

Repo.clone_from("https://source.developers.google.com/p/PROJECT/r/REPO",tempfile.gettempdir(), multi_options=['--config credential.helper={}'.format(MYTOKEN)], branch='master')

我不想將 SSH 密鑰作為一種克隆方法,因為我想稍后將其部署到生產環境中,而旋轉密鑰會很麻煩。

詢問的用戶名不過是服務帳戶地址和憑據,可以是臨時生成的 OAuth 2.0 訪問令牌。 所以,我最終做的是:

from git import Repo
import tempfile
import urllib.parse
import google.auth
import google.auth.transport.requests

def get_token():
    creds, project = google.auth.default()
    # creds.valid is False, and creds.token is None
    # # Need to refresh credentials to populate those
    auth_req = google.auth.transport.requests.Request()
    creds.refresh(auth_req)
    # Now you can use creds.token
    return creds.token

def url_parse():
    query = 'gsr-to-gcs-backup-function@PROJECT.iam.gserviceaccount.com'
    return urllib.parse.quote(query)

def git_clone():
    encoded_url = url_parse()
    credentials = get_token()
    
    local_repo = tempfile.gettempdir()+'/localrepo' 
    Repo.clone_from(f"https://{encoded_url}:{credentials}@source.developers.google.com/p/PROJECT/r/REPO",local_repo, branch='master')

def main(*args):
    git_clone()

注意:這只是我的代碼的一部分。 我想要的是將其復制到 GCS 存儲桶中。 但這超出了這個問題的范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM