Security and Best Practices
6 learning objectives · 12 key terms · 7 commands · 3 diagrams · 5 quiz questions
Security and Best Practices
Automation & SecurityWhat 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
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
- .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.
How it works, step by step
- 1Build 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
- 2Store 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 secretyamljobs: deploy: runs-on: ubuntu-latest environment: production steps: - run: ./deploy.sh env: DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
- 3If 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 leakbashgit rm --cached .env git commit -m "Stop tracking .env" # then rotate the credential in the provider dashboard
- 4Turn 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 enabledbashgh api repos/:owner/:repo --jq '{secret_scanning: .security_and_analysis.secret_scanning.status, dependabot: .security_and_analysis.dependabot_security_updates.status}'
- 5Protect 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 protectionbashgh 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
- 6Authenticate 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.
credentialsbashssh-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"
- 7Require 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 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.
git rm --cached .envrm '.env'
Removes the file from the index while leaving it on disk, so your local setup keeps working.
git ls-files | grep -E "\.env$|\.pem$|\.keyquot;
(no output — good)
Anything listed here is in history and must be rotated, not just deleted.
git log -S "AKIA" --oneline
Finds commits that added or removed that string. If it returns commits, treat the value as compromised.
gh api --method PUT repos/:owner/:repo/vulnerability-alerts
Also enable Dependabot security updates so vulnerable dependencies get pull requests automatically.
gh api repos/:owner/:repo/secret-scanning/alerts --jq '.[] | "\(.state): \(.secret_type)"'
open: github_personal_access_token
Every open alert should end in a rotated credential, not just a closed alert.
gh api repos/:owner/:repo/branches/main/protection
{"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.
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.
Workflow diagrams
Each gate is automatic, so protection does not depend on anyone remembering the rules.
- A push is scanned before it lands; a detected credential is blocked and the developer rotates it.
- Automated checks run tests, static analysis and dependency review against the change.
- A human review is still required — automated scanners find classes of problem, not intent.
- Only a change that passed every gate can reach the protected main branch.
| Command | What it can destroy | Safer habit |
|---|---|---|
| git push --force | Commits other people have based work on | Use --force-with-lease, and never on a shared branch |
| git reset --hard | Uncommitted work in the affected paths | Check git status first; use git restore for single files |
| git clean -fdx | All untracked files and ignored directories, permanently | Run git clean -n first to preview, and never in a folder with uncommitted work |
| Committing .env | Live credentials, in history forever | List it in .gitignore before the first commit |
| git filter-repo / history rewrite | Every commit hash after the change; breaks all clones | Only as a coordinated team decision, after rotating secrets |
| Making a repository public | Any secret currently in it, plus every future one | Treat visibility as irreversible; audit before changing it |
Every entry here is safe in a throwaway clone and dangerous on shared or production history. Understand before you type.
- Force-push is the most common self-inflicted team outage: someone loses commits they had not pushed anywhere else.
- A history rewrite is not a local operation — every clone, fork and open pull request must be re-synced by hand.
- Changing repository visibility is effectively permanent: assume everything becomes public immediately.
| Method | Good for | Watch out for |
|---|---|---|
| HTTPS + personal access token | Scripts, CI, quick setup | Tokens are passwords: scope them, expire them, never commit them |
| SSH key | Your own machine, long-lived convenience | One key per machine, passphrase-protected, rotaatable via Settings |
| SSH deploy key | A single repository, usually read-only CI | Scoped to one repo — never reuse a personal key for this |
| GitHub App | Automations with granular, revocable permissions | Slightly more setup than a token, far better blast radius |
| Password | Nothing — it is not accepted for Git operations | Retired by GitHub for Git over HTTPS |
All three are legitimate; the difference is how tightly the credential can be scoped and revoked.
- Use SSH keys or a fine-grained token with an expiry for anything automated.
- Use deploy keys or GitHub Apps for per-repository and per-organisation automation.
- Never share credentials between people or machines — revocation depends on that separation.
Worked example
A leak, caught and handled in the right order. The rotation is the part people skip and the part that matters.
# 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 "\.envquot; # (no output)
The credential is dead, the repository no longer tracks secret files, and CI reads the replacement from GitHub Secrets.
Where you'll use it
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
- 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.
Hands-on exercise
Harden one repository end to end
Audit, protect and automate in a single pass.
- In a practice repository, create a .env containing a fake key, commit it, and push it.
- 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.
- 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.
- Add the same fake value as a repository secret with gh secret set, and reference it from a workflow step.
- 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.
- 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.
Checkpoint quiz
0 of 5 answered · 0 correct
- Multiple choiceQ1
You accidentally committed and pushed a live API key. What is the first thing to do?
- TroubleshootingQ2
A required status check keeps failing intermittently. A teammate suggests removing it from branch protection. What is the better response?
- Command outputQ3
What would this command output in a healthy repository?
git ls-files | grep -E "\.envquot;
- True or falseQ4
True or false: making a repository private removes secrets that were previously committed.
- Multiple choiceQ5
Which practice best limits the damage if a token is compromised?
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.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
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.