Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keep git auth as environment variable instead of evaluated value

Tags:

git

bash

security

I'm trying to create a bash script that initializes a server and clones a git repository as part of initialization.

The installing user will set a personal access token (PAT) as an environment variable $TOKEN to clone via script. I want each subsequent user that pulls or pushes code to this cloned repository to set their PAT via environment variable $TOKEN, instead of using the original PAT the installer used.

However, when the script clones the repository gitconfig stores the interpreted value of the $TOKEN instead of variable $TOKEN so any subsequent pull/push uses the original installer's PAT.

i.e. when I do:

git clone https://oauth2:[email protected]/repo.git

gitconfig says:

[remote "origin"]
        url = https://oauth2:[email protected]/repo.git
        fetch = +refs/heads/*:refs/remotes/origin/*

when I want it to say:

[remote "origin"]
        url = https://oauth2:[email protected]/repo.git
        fetch = +refs/heads/*:refs/remotes/origin/*

I can't figure out how to force each user to use their token each time in a simple way.

Any ideas? Thanks

like image 700
Jessvin Thomas Avatar asked Jul 19 '26 17:07

Jessvin Thomas


1 Answers

You should avoid placing the token into the URL at all, since this is exposed to other users and saved in the configuration file. Instead, you can have the user configure a special credential helper to read from the environment, as outlined in the Git FAQ (substituting author below):

$ git config credential.helper \
    '!f() { echo username=author; echo "password=$TOKEN"; };f'

If you want to do this as part of a clone operation, you can do that with the -c argument to clone:

$ git clone -c credential.helper= \
  -c credential.helper='!f() { echo username=author; echo "password=$TOKEN"; };f' \
  https://gitlab.com/repo.git

The additional empty value for credential.helper causes any existing credential helpers to be removed, preventing the addition of this token into the user's credential helper. If you'd like the user to be able to save it, then remove that directive.

like image 195
bk2204 Avatar answered Jul 21 '26 12:07

bk2204



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!