Skip to content

05 Branch Protection Rules

Umutcan Γ–NER edited this page Jun 24, 2025 · 2 revisions

πŸ”’ Branch Protection Rules

Security Reviews Checks Deployments

Your safety net for code quality - Learn how branch protection rules keep our main branches secure, enforce quality standards, and automate deployments while maintaining a smooth development workflow.

πŸ“‹ Table of Contents


🎯 Overview

Branch protection rules are automated safeguards that ensure code quality and security:

🎯 Purpose

  • Prevent direct pushes
  • Enforce code review
  • Require passing tests
  • Maintain code quality

πŸ›‘οΈ Protection

  • No force pushes
  • No branch deletion
  • Required CI checks
  • Security scanning

πŸ‘₯ Reviews

  • Peer review required
  • Team assignments
  • CODEOWNERS
  • Dismissal rules

πŸš€ Automation

  • Auto-deployments
  • Version tagging
  • Release creation
  • Changelog updates

πŸ›‘οΈ Protection Strategy

See how different branches have different protection levels
flowchart TD
    subgraph "Protection Levels"
        Main[πŸš€ main<br/>Maximum Protection]
        Staging[πŸ§ͺ staging<br/>High Protection]
        Develop[πŸ”§ develop<br/>Standard Protection]
        Feature[🌟 feature/*<br/>No Protection]
    end
    
    subgraph "Requirements"
        Reviews2[2 Reviews<br/>Core Team]
        Reviews1[1 Review<br/>Any Maintainer]
        Checks[All CI Checks<br/>Must Pass]
        Security[Security Scans<br/>No Critical Issues]
        UpToDate[Up-to-date<br/>With Base]
    end
    
    Main --> Reviews2 & Checks & Security & UpToDate
    Staging --> Reviews1 & Checks & Security
    Develop --> Reviews1 & Checks & Security
    Feature --> NoReq[No Requirements]
    
    style Main fill:#FF6B6B,stroke:#333,stroke-width:3px,color:#fff
    style Staging fill:#FFD93D,stroke:#333,stroke-width:2px
    style Develop fill:#6BCF7F,stroke:#333,stroke-width:2px
    style Feature fill:#4ECDC4,stroke:#333,stroke-width:1px
Loading

πŸ“Š Protection Matrix

Complete overview of all protection rules
Branch Reviews Reviewers Dismiss Stale Enforce Admins Restrictions Delete Protection
πŸš€ main 2+ @core team βœ… βœ… Admins only βœ…
πŸ§ͺ staging 1+ Any maintainer βœ… ❌ None βœ…
πŸ”§ develop 1+ Any maintainer βœ… ❌ None βœ…
🌟 feature/* 0 - - - None ❌

πŸ”‘ Key Settings Explained

Setting Purpose Impact
Dismiss Stale Reviews Outdated approvals removed when new commits pushed Ensures reviews are for latest code
Enforce for Admins Rules apply even to repository admins No bypassing for anyone
Restrict Push Access Limit who can push even with approval Extra security layer
Require Up-to-date Must merge latest changes before merging Prevents conflicts

πŸ” Required Status Checks

All checks that must pass before merging

πŸ—οΈ For main Branch

flowchart LR
    PR[Pull Request] --> Validation{Validation Layer}
    
    Validation --> Format[βœ… PR Format<br/>Semantic title<br/>Size limits]
    Validation --> Branch[βœ… Branch Name<br/>Correct pattern]
    Validation --> Breaking[βœ… Breaking Changes<br/>Documentation]
    
    Format & Branch & Breaking --> Quality{Quality Layer}
    
    Quality --> Build[βœ… Build Check<br/>Compilation]
    Quality --> Lint[βœ… Biome Lint<br/>Code style]
    Quality --> Test[βœ… Vitest Tests<br/>All passing]
    Quality --> Type[βœ… TypeScript<br/>No errors]
    
    Build & Lint & Test & Type --> Security{Security Layer}
    
    Security --> CodeQL[βœ… CodeQL<br/>SAST analysis]
    Security --> Deps[βœ… Dependencies<br/>No vulnerabilities]
    Security --> Secrets[βœ… Secrets<br/>None exposed]
    
    CodeQL & Deps & Secrets --> Ready[Ready to Merge]
    
    style Ready fill:#6BCF7F
Loading

πŸ“Š Status Check Details

Check Type Workflow Required for Blocking Criteria
PR Validation pr-validation.yml All PRs Invalid format/size
Build build.yml PRs to main Build failure
CI Pipeline ci.yml develop/staging Any test failure
Security Suite security.yml All branches Critical vulnerabilities (Details)
Bundle Analysis build.yml PRs to main Size regression >10%

βš™οΈ Check Configuration

# Example of required status checks for main branch
required_status_checks:
  strict: true  # Require branches to be up-to-date
  contexts:
    # Format checks
    - "PR Validation / validate"
    
    # Quality checks
    - "Build / build"
    - "CI / lint"
    - "CI / test"
    - "CI / typecheck"
    
    # Security checks
    - "Security / security-scan"
    - "CodeQL / Analyze (javascript)"

πŸ‘₯ Review Requirements

Who needs to review your code

πŸ” Review Rules by Branch

flowchart TD
    subgraph "Pull Request Review Flow"
        Create[PR Created] --> AssignAuthor[Auto-assign Author]
        AssignAuthor --> CheckFiles{Check Changed Files}
        
        CheckFiles -->|Critical Path| CoreTeam[Assign @core Team]
        CheckFiles -->|Regular Files| AnyMaintainer[Any Maintainer]
        
        CoreTeam --> RequireReview{Target Branch?}
        AnyMaintainer --> RequireReview
        
        RequireReview -->|main| TwoReviews[2 Reviews Required]
        RequireReview -->|staging| OneReview[1 Review Required]
        RequireReview -->|develop| OneReview
        
        TwoReviews --> Approved[PR Approved]
        OneReview --> Approved
    end
Loading

πŸ‘€ CODEOWNERS Enforcement

Critical paths requiring @zopiolabs/core team review:

Path Pattern Why Critical Review Requirement
/packages/core/ Framework foundation 2 from core team
/packages/auth* Security critical 2 from core team
/packages/database/ Data integrity 2 from core team
/.github/ CI/CD pipeline 1 from core team
**/.env* Secrets management 2 from core team
**/package.json Dependencies 1 from core team

πŸ”„ Review Dismissal Rules

Scenario Action Applies To
New commits pushed Previous approvals dismissed All branches
Review marked stale Must re-review All branches
Admin override Not allowed main branch
Emergency hotfix 1 review minimum main branch

πŸ”€ Merge Strategies

How code gets merged into protected branches

πŸ“Š Merge Method by Branch

Branch Merge Method Commit History Use When
πŸš€ main Squash & Merge Clean, linear Production releases
πŸ§ͺ staging Squash & Merge Clean, linear Pre-prod testing
πŸ”§ develop Squash & Merge Clean, linear Feature integration
🌟 feature/* Any method Preserves all Developer preference

🎯 Merge Requirements

stateDiagram-v2
    [*] --> PRCreated: Open PR
    PRCreated --> ChecksRunning: Automated checks start
    
    state ChecksRunning {
        [*] --> Validation: PR Validation
        Validation --> CI: CI Pipeline
        CI --> Security: Security Scans
        Security --> [*]: All Pass
    }
    
    ChecksRunning --> ReviewRequired: Request reviews
    
    state ReviewRequired {
        [*] --> Reviewing: Reviewers assigned
        Reviewing --> ChangesRequested: Issues found
        ChangesRequested --> Reviewing: Address feedback
        Reviewing --> Approved: LGTM
    }
    
    ReviewRequired --> ReadyToMerge: All requirements met
    
    state ReadyToMerge {
        [*] --> UpToDate: Check if current
        UpToDate --> Outdated: New commits on base
        Outdated --> UpdateBranch: Merge/rebase base
        UpdateBranch --> UpToDate: Re-run checks
        UpToDate --> Mergeable: Can merge
    }
    
    ReadyToMerge --> Merged: Squash & merge
    Merged --> [*]: PR closed
Loading

⚑ Auto-merge Capabilities

  • Not enabled for any branches (security best practice)
  • All merges require manual approval
  • Consider enabling for dependabot updates only

πŸš€ Auto-Deployment Rules

How deployments are triggered by branch protection

🌐 Deployment Flow

flowchart LR
    subgraph "Branch Deployments"
        Main[πŸš€ main] -->|Auto-deploy| Prod[Production<br/>app.zopio.dev]
        Staging[πŸ§ͺ staging] -->|Auto-deploy| Stage[Staging<br/>staging.zopio.dev]
        Develop[πŸ”§ develop] -->|Auto-deploy| Dev[Development<br/>dev.zopio.dev]
    end
    
    subgraph "Deployment Protection"
        Prod -->|Required| ProdChecks[βœ… All checks<br/>βœ… 2 reviews<br/>βœ… No vulnerabilities]
        Stage -->|Required| StageChecks[βœ… CI passing<br/>βœ… 1 review]
        Dev -->|Required| DevChecks[βœ… Build success]
    end
    
    subgraph "Vercel Integration"
        ProdChecks --> VercelProd[Vercel Production]
        StageChecks --> VercelPreview[Vercel Preview]
        DevChecks --> VercelDev[Vercel Development]
    end
Loading

πŸ” Environment Protection Rules

Environment Branch URL Additional Protection
Production main app.zopio.dev β€’ Deployment approvals
β€’ Rollback capability
Staging staging staging.zopio.dev β€’ E2E tests required
β€’ QA sign-off
Development develop dev.zopio.dev β€’ Automatic deployment
β€’ Latest features

πŸ” Additional Protections

Extra security measures for protected branches

πŸ›‘οΈ Security Policies

Protection Enabled On Purpose Implementation
Force Push Protection All protected Preserve history GitHub setting
Deletion Protection All protected Prevent accidents GitHub setting
Signed Commits Recommended Verify authorship Git GPG/SSH
Linear History main, staging Clean history Squash merge
Tag Protection v*.. Release integrity Pattern rule

πŸ” Advanced Security Features

flowchart TD
    subgraph "Security Layers"
        Secret[Secret Scanning<br/>Real-time detection]
        Depend[Dependency Scanning<br/>Daily + PR triggered]
        Code[Code Scanning<br/>CodeQL analysis]
        Container[Container Scanning<br/>Docker images]
    end
    
    subgraph "Actions on Detection"
        Secret --> Block1[Block push<br/>Alert security team]
        Depend --> Block2[Block if critical<br/>Create issue]
        Code --> Block3[Create alert<br/>Suggest fix]
        Container --> Block4[Fail build<br/>Report in PR]
    end
    
    subgraph "Resolution"
        Block1 --> Fix[Developer fixes]
        Block2 --> Fix
        Block3 --> Fix
        Block4 --> Fix
        Fix --> Rescan[Re-run security checks]
        Rescan --> Pass[All clear βœ…]
    end
Loading

πŸ“ Audit Trail

All protected branch activities are logged:

  • Who merged what and when
  • Review approvals and dismissals
  • Override attempts (if any)
  • Failed merge attempts
  • Protection rule changes

⚑ Quick Reference

Common scenarios and solutions

πŸš€ Quick Commands

# Check if your PR can be merged
gh pr checks

# View required status checks
gh pr view --json statusCheckRollup

# Update branch with base
git fetch origin
git rebase origin/develop  # or staging/main

# Check review status
gh pr view --json reviews

❓ Common Questions

Question Answer
Why can't I push to main? Direct pushes disabled - use PR
Why was my review dismissed? New commits pushed after approval
How many reviews do I need? main: 2, staging/develop: 1
Can admins bypass rules? No for main, yes for others
Why is merge blocked? Check failed status checks

🎯 Best Practices

  1. Before Creating PR:

    • Run all checks locally
    • Ensure branch is up-to-date
    • Use semantic PR title
  2. During Review:

    • Respond to all comments
    • Don't push until ready
    • Request specific reviewers
  3. Before Merging:

    • Verify all checks green
    • Ensure reviews approved
    • Check deployment preview

πŸ”§ Troubleshooting

Solutions for common protection issues

❌ Merge Blocked Issues

Issue Cause Solution
"Branch out-of-date" Base branch has new commits Merge or rebase latest changes
"Required check failed" CI/Security check not passing Fix the failing check
"Needs approval" Missing required reviews Request reviews from team
"Changes requested" Reviewer requested changes Address feedback and re-request

πŸ”„ Updating Your Branch

# Option 1: Merge (preserves commits)
git fetch origin
git merge origin/develop

# Option 2: Rebase (cleaner history)
git fetch origin
git rebase origin/develop

# If conflicts occur
git status  # See conflicted files
# Fix conflicts in your editor
git add .
git rebase --continue

🚨 Emergency Procedures

For critical hotfixes when normal process is too slow:

  1. Create hotfix branch from main
  2. Get expedited review from senior team member
  3. Ensure critical checks pass (security, build)
  4. Document in PR why expedited process used
  5. Follow up with full review post-merge

πŸšͺ Next Steps

Now that you understand branch protection, explore these areas:

πŸ“š Learn More

πŸš€ Take Action

πŸ”— External Resources


Clone this wiki locally