DIE Community
Ask

How do I keep my GitHub token safe when scripts push code for me?

DIEAbdulHadiFounderAsked 0 views
0

The question says it all.

1 answer

  1. 0

    Chosen as the best answer

    Use a fine-grained token that only covers the repos your script needs and has an expiry date. Keep it in a .env file that git ignores, send it as a header instead of putting it in the URL, check every push for secrets, and if you think it leaked, revoke it right away.

    Scripts that push for you are where tokens leak, because nobody is watching when they run. This is the setup we use.

    Give it the least power possible

    On GitHub, create a fine-grained personal access token, not a classic one. Give it access only to the repos it pushes to, with Contents set to read and write. Set an expiry date, even a long one, and note it down. If it ever leaks, the damage stays small and ends on a known day.

    Keep it out of your code

    Put it in a .env file next to your scripts, and add .env to .gitignore before you create the file. Load it only when needed:

    set -a; . ./.env; set +a
    

    Don't paste it into a script, a README, an issue, or any chat that does not need it.

    Don't put it in the remote URL

    https://TOKEN@github.com/you/repo.git is handy, but that URL ends up in .git/config, shell history and error messages. Send it as a header for the one push instead:

    AUTH=$(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0)
    git -c http.extraHeader="Authorization: Basic $AUTH" push https://github.com/you/repo.git main
    

    The token only lives in memory for that command.

    Check before every push

    Have the script stop if the files contain anything that looks like a secret: .env files, keystores, private keys, or token-shaped text (GitHub tokens start with ghp or github_pat). Also turn on GitHub's secret scanning and push protection for your repos.

    If it might have leaked

    Don't wait to be sure. Revoke it on GitHub, make a new one, update your .env, and look through the repo's recent activity. Rewriting git history does not help much: treat anything that reached a public place as already copied.

    Link

Your answer

↑ ↓ to moveEnter to open