Lock down a public GitHub repository
Squash-only merges, rulesets, secret scanning, CodeQL, Dependabot, read-only Actions and an approved production environment for a public repo you own alone.
The settings I put on a public repository that I own alone, on GitHub Free. Every step can be done two ways: a gh api call (the gh CLI tab) or the same setting in the browser (the GitHub UI tab). You need admin rights on the repository. For the CLI, set R=<owner>/<repo> once and the commands below reuse it.
- Pull requestWorkflows from an outside contributor wait for your approval before they run.
- CI and CodeQLActions start with read access only, and every action is pinned to a full commit SHA.
- Default branch rulesetNo merge until the checks pass on an up-to-date branch, conversations are resolved and CodeQL finds no high or critical alert.
- mainSquash merges only. Nobody force pushes or deletes it, you included.
- Production environmentThe deploy job waits for your approval before it gets secrets or a cloud token.
- Your cloudIt trusts only the production subject, so a pull request run gets nothing.
1. Allow squash merges only
R=<owner>/<repo>
gh api -X PATCH repos/$R \
-F allow_squash_merge=true -F allow_merge_commit=false -F allow_rebase_merge=false \
-F delete_branch_on_merge=true -F allow_update_branch=true \
-F allow_auto_merge=false -F has_wiki=false \
-f squash_merge_commit_title=PR_TITLE -f squash_merge_commit_message=PR_BODY-F sends true and false as booleans, -f sends text.
Settings → General:
- Pull Requests: keep only Allow squash merging. Select Always suggest updating pull request branches and Automatically delete head branches. Clear Allow auto-merge.
- Features: clear Wikis.
2. Protect the default branch
An empty bypass list means the rules apply to me too. Zero approvals still forces a pull request; it just doesn't wait for a second person. Leave require_code_owner_review off: it needs a code owner's approval, and in my setup I can't approve my own pull request. Blocking force pushes also stops admins from renaming the default branch unless they're on the bypass list.
Save as branch-ruleset.json:
{
"name": "default-branch",
"target": "branch",
"enforcement": "active",
"bypass_actors": [],
"conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
"rules": [
{ "type": "deletion" },
{ "type": "non_fast_forward" },
{ "type": "required_linear_history" },
{
"type": "pull_request",
"parameters": {
"required_approving_review_count": 0,
"dismiss_stale_reviews_on_push": false,
"require_code_owner_review": false,
"require_last_push_approval": false,
"required_review_thread_resolution": true,
"allowed_merge_methods": ["squash"]
}
},
{
"type": "required_status_checks",
"parameters": {
"strict_required_status_checks_policy": true,
"required_status_checks": [{ "context": "<ci-job-name>" }]
}
},
{
"type": "code_scanning",
"parameters": {
"code_scanning_tools": [
{
"tool": "CodeQL",
"security_alerts_threshold": "high_or_higher",
"alerts_threshold": "errors"
}
]
}
}
]
}gh api -X POST repos/$R/rulesets --input branch-ruleset.jsoncontext is the check's name exactly as it shows on a pull request. strict_required_status_checks_policy is the up-to-date option.
Settings → Rules → Rulesets → New ruleset → New branch ruleset:
- Ruleset name:
default-branch. Enforcement status: Active. Leave Bypass list empty. - Target branches → Add a target → Include default branch.
- Branch protections: keep Restrict deletions and Block force pushes, and select Require linear history.
- Require a pull request before merging: Required approvals
0, select Require conversation resolution before merging, and allow only Squash as the merge method. Leave Require review from Code Owners clear. - Require status checks to pass: select Require branches to be up to date before merging, then add your CI check by name with +.
- Require code scanning results: tool CodeQL, Alerts Errors, Security alerts High or higher.
Click Create. A ruleset saved as JSON can also come in with New ruleset → Import a ruleset.
The CodeQL rule blocks a merge while CodeQL is still running, isn't set up, or finds a high or critical alert.
3. Protect release tags
gh api -X POST repos/$R/rulesets --input - <<'EOF'
{
"name": "release-tags", "target": "tag", "enforcement": "active", "bypass_actors": [],
"conditions": { "ref_name": { "include": ["refs/tags/v*"], "exclude": [] } },
"rules": [
{ "type": "deletion" },
{ "type": "non_fast_forward" },
{ "type": "update", "parameters": { "update_allows_fetch_and_merge": false } }
]
}
EOF
gh api -X PUT repos/$R/immutable-releases- Settings → Rules → Rulesets → New ruleset → New tag ruleset. Set the enforcement status to Active. Under Target tags, Add a target with the pattern
v*. Under Tag protections, select Restrict updates, Restrict deletions and Block force pushes. - Settings → General → Releases: select Enable release immutability.
New v* tags can still be created, but nobody can move or delete them. Immutable releases also lock a published release's tag and files, for releases made after you turn it on.
4. Turn on the security features
Secret scanning already runs for free on public repositories and covers the whole Git history on every branch. Push protection, Dependabot and private reporting you turn on yourself.
gh api -X PUT repos/$R/vulnerability-alerts # Dependabot alerts + dependency graph
gh api -X PUT repos/$R/automated-security-fixes # Dependabot security updates
gh api -X PUT repos/$R/private-vulnerability-reporting
gh api -X PATCH repos/$R --input - <<'EOF'
{ "security_and_analysis": {
"secret_scanning_push_protection": { "status": "enabled" } } }
EOFSettings → Advanced Security, and click Enable next to Dependency graph, Dependabot alerts, Dependabot security updates, Private vulnerability reporting and Push protection.
Validity checks and generic patterns aren't in the list for a personal repository: they need GitHub Secret Protection on an organization's repository. If scanning finds a secret, rotate it right away. Removing it from the Git history alone doesn't make it safe again.
5. Scan the code with CodeQL
Default setup reads the repository's languages, including actions for workflow files, and runs the larger extended suite without a workflow to maintain.
gh api -X PATCH repos/$R/code-scanning/default-setup -f state=configured -f query_suite=extendedSettings → Advanced Security → CodeQL analysis → Set up → Default. In the dialog, click Edit, choose the extended query suite under Query suites, then Enable CodeQL.
Pick one setup. If you write your own CodeQL workflow instead (advanced setup), keep default setup off: while it's on, it blocks CodeQL uploads from workflows.
6. Add the repository files
Three files, in one pull request:
SECURITY.md: report privately with Report a vulnerability on the Security and quality tab, never in a public issue..github/CODEOWNERS:* @<username>. With one owner it's a record, not a gate..github/dependabot.yml: one entry per ecosystem, plusgithub-actionsfor the workflows.
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule: { interval: weekly }
- package-ecosystem: npm
directory: /
schedule: { interval: weekly }
ignore:
- dependency-name: '@types/node' # stay on the Node LTS
update-types: ['version-update:semver-major']git switch -c repo-security
# add SECURITY.md, .github/CODEOWNERS and .github/dependabot.yml
git add SECURITY.md .github/CODEOWNERS .github/dependabot.yml
git commit -m "Add security policy, code owners and Dependabot config"
git push -u origin repo-security
gh pr create --fill- Security and quality tab → Security policy → Start setup, write the policy, Commit changes..., commit to a new branch and open a pull request.
- On that branch, Add file → Create new file for
.github/CODEOWNERSand.github/dependabot.yml, then merge the pull request.
ignore applies to security updates too, so an ignored major gets no security pull request either. Add a LICENSE only if you want others to reuse the code.
7. Lock down GitHub Actions
gh api -X PUT repos/$R/actions/permissions/workflow \
-f default_workflow_permissions=read -F can_approve_pull_request_reviews=false
gh api -X PUT repos/$R/actions/permissions/fork-pr-contributor-approval \
-f approval_policy=all_external_contributors
gh api -X PUT repos/$R/actions/permissions \
-F enabled=true -f allowed_actions=all -F sha_pinning_required=trueThe last call replaces the whole Actions policy, so keep allowed_actions at what you use now.
Settings → Actions → General:
- Actions permissions: select Require actions to be pinned to a full-length commit SHA.
- Approval for running fork pull request workflows from contributors: Require approval for all external contributors.
- Workflow permissions: read access for contents and packages, and clear Allow GitHub Actions to create and approve pull requests.
In each workflow, set permissions: contents: read at the top and grant more per job only where needed. Pin every action to a full commit SHA with a # vN comment, as in the OIDC note. Use persist-credentials: false on actions/checkout unless a later step runs git push. Avoid pull_request_target: it runs in the base branch's context and skips the fork approval.
8. Gate deploys with a production environment
ID=$(gh api users/<username> --jq .id)
gh api -X PUT repos/$R/environments/production --input - <<EOF
{ "prevent_self_review": false,
"reviewers": [{ "type": "User", "id": $ID }],
"deployment_branch_policy": { "protected_branches": false, "custom_branch_policies": true } }
EOF
gh api -X POST repos/$R/environments/production/deployment-branch-policies -f name=main -f type=branchSettings → Environments → New environment → production:
- Required reviewers: add yourself. Leave Prevent self-review clear, or you can't approve runs you started.
- Clear Allow administrators to bypass configured protection rules.
- Deployment branches: Selected branches and tags → Add deployment branch or tag rule →
main.
One approval is enough to start the job, and its environment secrets only reach it after that. Admins can skip the approval by default; that switch is only in the UI, so clear it there. On GitHub Free, required reviewers work only in public repositories.
9. Deploy without stored cloud keys
Sign in with OIDC, as in the OIDC note. Make the federated credential trust only the production environment's subject, and give id-token: write only to the deploy job. A pull request run then can't get a cloud token at all.
10. Read everything back
gh api repos/$R --jq '{allow_squash_merge, allow_merge_commit, allow_rebase_merge,
delete_branch_on_merge, allow_update_branch, allow_auto_merge, has_wiki, security_and_analysis}'
gh api repos/$R/rulesets --jq '.[] | {name, target, enforcement}'
gh api repos/$R/vulnerability-alerts --silent && echo 'alerts on' # 404 when off
gh api repos/$R/automated-security-fixes --jq .enabled
gh api repos/$R/private-vulnerability-reporting --jq .enabled
gh api repos/$R/immutable-releases --jq .enabled
gh api repos/$R/code-scanning/default-setup --jq '{state, query_suite, languages}'
gh api repos/$R/actions/permissions
gh api repos/$R/actions/permissions/workflow
gh api repos/$R/actions/permissions/fork-pr-contributor-approval
gh api repos/$R/environments/production --jq '{protection_rules, deployment_branch_policy}'
gh api repos/$R/environments/production/deployment-branch-policies --jq '.branch_policies[].name'The admin bypass switch on the environment isn't in these answers, so check it on the page.
- Settings → General: the merge options and Wikis from step 1.
- Settings → Rules → Rulesets: both rulesets show Active.
- Settings → Advanced Security: everything from steps 4 and 5 shows Disable (it's on).
- Settings → Actions → General: the three settings from step 7.
- Settings → Environments →
production: reviewer, admin bypass cleared, branchmain.
Sources
- Available rules for rulesets (GitHub Docs)
- REST API endpoints for repositories (GitHub Docs)
- Secret scanning (GitHub Docs)
- Configuring default setup for code scanning (GitHub Docs)
- Dependabot options reference (GitHub Docs)
- Managing GitHub Actions settings for a repository (GitHub Docs)
- Managing environments for deployment (GitHub Docs)
- actions/checkout README (GitHub)