Learn GitHub
$ gh ghautomation.ghsecurity

Security and Best Practices

6 learning objectives · 12 key terms · 7 commands · 3 diagrams · 5 quiz questions

$objectives

Security and Best Practices

Automation & Security

Module 4 of 5 · lesson 14 in this module

What you'll be able to do

  • Keep credentials, tokens and keys out of git history entirely
  • Store configuration secrets safely and use them from workflows
  • Turn on secret scanning, Dependabot and code scanning
  • Protect important branches with rules, reviews and required checks
  • Choose between SSH keys and personal access tokens, and scope them tightly
  • Recognise the destructive commands that cause irreversible damage
$concept

The idea, in plain language

A repository is a public, permanently archived, easily searchable record — which makes it a terrible place for a password. The failure mode is well known and still constant: a .env file or a hard-coded API key is committed, pushed, and scraped by bots within minutes, and even a private repository has a lifetime beyond the moment you delete the file. Rotating the leaked credential is the only real fix; deleting it from the repository is damage control.

So the design goal is that secrets never enter the working directory in the first place. Configuration that is not secret goes in the repository. Secrets live in the platform's secret store — GitHub repository, environment or organisation secrets — and are injected at run time. Local development uses a .env file that is listed in .gitignore from the very first commit, with a committed .env.example documenting the variable names without the values. When a leak does happen anyway, the response is: revoke or rotate the credential immediately, then clean the repository and, if needed, rewrite history.

Around that core sit the automated defences. Secret scanning watches pushes for known credential patterns and partner tokens. Dependabot opens pull requests when a dependency has a known vulnerability, and alerts when one is found in what you already use. Code scanning runs static analysis to catch injection, path traversal and similar classes of bug before review. Branch protection rules turn all of it into a gate: no direct pushes to main, at least one approval, required status checks green, and signed commits if your team needs provenance. Enable those, and the answer to "can someone ship a broken or malicious change by accident?" becomes no.

$key terms

Key terms

.gitignore for secrets
The first line of defence: .env and credential files are never tracked.
GitHub Secrets
Encrypted values stored per repository, environment or organisation and injected at run time.
Secret scanning
GitHub scanning pushes for known credential patterns and alerting the provider.
Push protection
A block that stops a push containing a detected secret before it lands.
Dependabot
Automated dependency updates and vulnerability alerts.
Code scanning
Static analysis (for example CodeQL) that finds vulnerable code patterns.
Branch protection
Rules on a branch: required reviews, required checks, no force-push, no deletion.
Signed commit
A commit cryptographically signed (GPG or SSH), proving who authored it.
Two-factor authentication
A second factor on your account; required for contributing to many organisations.
Least privilege
Giving a token or collaborator only the permissions the task actually needs.
Personal access token
A scoped alternative to a password for HTTPS API and Git access.
Deploy key
An SSH key scoped to a single repository, usually read-only for CI.
$steps

How it works, step by step

  1. 1
    Build the .gitignore before the first commit

    Secret files must never exist as tracked files even once. Add the patterns now, commit the .gitignore itself, and provide a .env.example with placeholder values.

    .gitignorebash
    .env
    .env.*
    !.env.example
    *.pem
    *.key
    secrets/
    credentials.json
  2. 2
    Store real secrets in the platform, not the repository

    Add values in Settings → Secrets and variables → Actions. Reference them through the secrets context at run time, and scope them to an environment when they should only be available to a production job.

    environment-scoped secretyaml
    jobs:
      deploy:
        runs-on: ubuntu-latest
        environment: production
        steps:
          - run: ./deploy.sh
            env:
              DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
  3. 3
    If a secret was committed, rotate it first

    Order matters: revoke or rotate the credential, then remove the file. Anything pushed should be assumed compromised, even in a private repository, because clones and forks keep copies.

    contain the leakbash
    git rm --cached .env
    git commit -m "Stop tracking .env"
    # then rotate the credential in the provider dashboard
  4. 4
    Turn on the automated scanners

    Enable secret scanning (with push protection where available), Dependabot alerts and security updates, and code scanning with the default CodeQL setup. These run without anyone remembering to run them.

    check what is enabledbash
    gh api repos/:owner/:repo --jq '{secret_scanning: .security_and_analysis.secret_scanning.status, dependabot: .security_and_analysis.dependabot_security_updates.status}'
  5. 5
    Protect the branches that matter

    On main: require a pull request with at least one approval, require status checks to pass, require conversation resolution, disallow force-pushes and deletions, and require review from code owners for sensitive paths.

    branch protectionbash
    gh api --method PUT repos/:owner/:repo/branches/main/protection \
      -f required_status_checks[strict]=true \
      -f enforce_admins=true \
      -F required_pull_request_reviews[required_approving_review_count]=1
  6. 6
    Authenticate with scoped credentials

    Prefer SSH keys or a fine-grained personal access token over a password, give each token the minimum scopes and an expiry date, and use separate tokens per machine so one can be revoked alone.

    credentialsbash
    ssh-keygen -t ed25519 -C "ada@example.com"
    # add the public key in GitHub → Settings → SSH and GPG keys
    gh auth login --scopes "repo,read:org"
  7. 7
    Require two-factor authentication and least privilege

    Turn on 2FA on your own account, and in an organisation require it for members. Give collaborators and tokens the lowest role that gets the job done: read, triage or write as needed, not admin by default.

$commands

Commands worth memorising

Every block below is copy-ready — use the Copy button, then paste it into your terminal. Expected output is shown underneath so you know what “working” looks like.

stop tracking a leaked filebash
git rm --cached .env
Output
rm '.env'

Removes the file from the index while leaving it on disk, so your local setup keeps working.

confirm nothing sensitive is trackedbash
git ls-files | grep -E "\.env$|\.pem$|\.key
quot;
Output
(no output — good)

Anything listed here is in history and must be rotated, not just deleted.

search history for a leaked valuebash
git log -S "AKIA" --oneline

Finds commits that added or removed that string. If it returns commits, treat the value as compromised.

enable Dependabot alertsbash
gh api --method PUT repos/:owner/:repo/vulnerability-alerts

Also enable Dependabot security updates so vulnerable dependencies get pull requests automatically.

list secret scanning alertsbash
gh api repos/:owner/:repo/secret-scanning/alerts --jq '.[] | "\(.state): \(.secret_type)"'
Output
open: github_personal_access_token

Every open alert should end in a rotated credential, not just a closed alert.

check branch protectionbash
gh api repos/:owner/:repo/branches/main/protection
Output
{"required_pull_request_reviews":{"required_approving_review_count":1},"required_status_checks":{"strict":true}}

If this 404s, main is unprotected — anyone with write access can push straight to it.

log in with scoped credentialsbash
gh auth login --scopes "repo,read:org"

Ask for the scopes you need and no more; use --web for the browser flow or paste a token with -t.

$diagrams

Workflow diagrams

Diagram 1A change passing through the security gates

Each gate is automatic, so protection does not depend on anyone remembering the rules.

Reading the diagram
  1. A push is scanned before it lands; a detected credential is blocked and the developer rotates it.
  2. Automated checks run tests, static analysis and dependency review against the change.
  3. A human review is still required — automated scanners find classes of problem, not intent.
  4. Only a change that passed every gate can reach the protected main branch.
Diagram 2Commands that can lose work or leak data

Every entry here is safe in a throwaway clone and dangerous on shared or production history. Understand before you type.

Reading the diagram
  1. Force-push is the most common self-inflicted team outage: someone loses commits they had not pushed anywhere else.
  2. A history rewrite is not a local operation — every clone, fork and open pull request must be re-synced by hand.
  3. Changing repository visibility is effectively permanent: assume everything becomes public immediately.
Diagram 3Choosing how you authenticate

All three are legitimate; the difference is how tightly the credential can be scoped and revoked.

Reading the diagram
  1. Use SSH keys or a fine-grained token with an expiry for anything automated.
  2. Use deploy keys or GitHub Apps for per-repository and per-organisation automation.
  3. Never share credentials between people or machines — revocation depends on that separation.
$example

Worked example

A leak, caught and handled in the right order. The rotation is the part people skip and the part that matters.

handling a committed credentialbash
# 1. find out what leaked and where
git log -S "sk_live" --oneline
# 8c1d2ab Add payment integration
# 3f9a1c2 Initial commit

# 2. rotate the credential FIRST, in the provider dashboard
#    (a Stripe restricted key in this case) — the old one is now dead

# 3. stop tracking it locally
git rm --cached .env
printf '.env\n.env.*\n!.env.example\n' >> .gitignore
git add .gitignore
git commit -m "Stop tracking .env and ignore env files"

# 4. give the team a template with no values
printf 'STRIPE_KEY=\nAPI_BASE_URL=\n' > .env.example
git add .env.example
git commit -m "Add .env.example documenting required variables"

# 5. store the new value as a repository secret and use it from CI
gh secret set STRIPE_KEY
gh secret list
# STRIPE_KEY  updated  a few seconds ago

# 6. verify nothing sensitive is still tracked
git ls-files | grep -E "\.env
quot;
# (no output)
Output
The credential is dead, the repository no longer tracks secret files, and CI reads the replacement from GitHub Secrets.
1git log -S searches history for a string, which is how you find out how long a value has been exposed and whether it predates the current file.
2Rotation comes first. Cleaning the repository while the credential still works anywhere just reduces detection without reducing risk.
3git rm --cached untracks the file but keeps it on disk, so local development is not interrupted. .gitignore prevents it being re-added by a routine git add .
4.env.example is the safe half of the pair: it documents which variables exist without containing their values, so a new contributor knows what to configure.
5The new value goes into repository secrets, where workflows read it as an environment variable and CI logs mask it.
6A final check confirms nothing matching the secret patterns is tracked. History still contains the old value, which is acceptable precisely because it was rotated.
$use cases

Where you'll use it

▸Onboarding a new contributor without handing them production credentials.
▸Running a deployment workflow that needs a token, without the token existing in the repository.
▸Getting automatic pull requests when a dependency you use is found vulnerable.
▸Preventing an accidental direct push to main, including by administrators.
▸Passing a security review that asks how secrets are managed and who can deploy.
▸Proving which key signed a release commit when provenance matters.
$mistakes

Common mistakes

  • Committing a .env file "just for now" and pushing it.
  • Believing a private repository makes secrets safe — clones, forks and future visibility changes say otherwise.
  • Deleting a leaked key from the latest commit but not rotating it: the value is still live in history.
  • Rewriting history to purge a secret without coordinating, leaving every teammate’s clone inconsistent.
  • Scoping a personal access token to everything with no expiry because it was quicker.
  • Leaving main unprotected, so a single compromised account can push straight to production.
  • Disabling a flaky required check instead of fixing it — the gate that gets disabled is the one that mattered.
$best practices

Best practices

  • Assume any credential that was ever committed is compromised and rotate it immediately.
  • Keep .env out of tracking, commit .env.example, and document the required variables.
  • Store secrets in GitHub repository or environment secrets, never in the workflow file.
  • Enable secret scanning with push protection, Dependabot and code scanning on every repository.
  • Protect main: pull requests required, at least one approval, status checks green, no force-push, no deletion.
  • Use least-privilege, expiring, per-machine credentials, and require two-factor authentication.
  • Run dangerous commands like git clean -fdx with the preview flag first.
$exercise

Hands-on exercise

Harden one repository end to end

Audit, protect and automate in a single pass.

  1. In a practice repository, create a .env containing a fake key, commit it, and push it.
  2. Run git log -S "<your fake key>" --oneline and record how many commits contain it — this is the audit you would run for a real leak.
  3. Write the remediation: remove it from tracking with git rm --cached, add .env to .gitignore, add a .env.example, and note in a file called SECURITY-NOTES.md that the credential would be rotated first.
  4. Add the same fake value as a repository secret with gh secret set, and reference it from a workflow step.
  5. Enable branch protection on main requiring one approval and a passing status check, then try to push directly to main and confirm it is refused.
  6. Enable secret scanning push protection if available and attempt to push a file containing a token-shaped string, noting the block.

💡 Hint: To test a push block without a real credential, use a clearly fake but correctly shaped token, or simply confirm the setting is on under Settings → Code security.

Done when: No secret files are tracked, a secret is used from CI, and a direct push to main is rejected by branch protection.

$quiz

Checkpoint quiz

0 of 5 answered · 0 correct

  1. Multiple choiceQ1

    You accidentally committed and pushed a live API key. What is the first thing to do?

  2. TroubleshootingQ2

    A required status check keeps failing intermittently. A teammate suggests removing it from branch protection. What is the better response?

  3. Command outputQ3

    What would this command output in a healthy repository?

    git ls-files | grep -E "\.env
    quot;
  4. True or falseQ4

    True or false: making a repository private removes secrets that were previously committed.

  5. Multiple choiceQ5

    Which practice best limits the damage if a token is compromised?

$summary

Module summary

  • Never commit secrets: .gitignore plus .env.example from the first commit.
  • GitHub Secrets (repository or environment) is where values live, injected at run time and masked in logs.
  • If a secret was committed, rotate it first, then clean up.
  • Enable secret scanning with push protection, Dependabot and code scanning.
  • Protect main with required reviews, required checks, no force-push and no deletion.
  • Use least-privilege, expiring credentials and require two-factor authentication.
  • Treat force-push, reset --hard, clean -fdx, history rewrites and going public as dangerous operations.

Next up: Security constrains what automation may touch. Module 12 shows what it may produce: versioned releases, published packages, container images and GitHub Pages deployments.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Put the GitHub course to work: open one of the company-wise repositories and follow the workflow you just learned, branch to release.