@@ -0,0 +1,179 @@ |
| | 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| | 2 | + |
| | 3 | +// Package protection enforces branch-protection rules on incoming |
| | 4 | +// pushes. The pre-receive hook (S14) calls into Enforce once per |
| | 5 | +// pushed ref; this package owns the matching, the per-rule checks, |
| | 6 | +// and the rejection messages. |
| | 7 | +// |
| | 8 | +// Rule scope is `refs/heads/*` only — tag refs are out of scope here |
| | 9 | +// (tag protection is its own thing in a future sprint). |
| | 10 | +package protection |
| | 11 | + |
| | 12 | +import ( |
| | 13 | + "context" |
| | 14 | + "errors" |
| | 15 | + "fmt" |
| | 16 | + "path/filepath" |
| | 17 | + "sort" |
| | 18 | + "strings" |
| | 19 | + |
| | 20 | + "github.com/jackc/pgx/v5/pgxpool" |
| | 21 | + |
| | 22 | + repogit "github.com/tenseleyFlow/shithub/internal/repos/git" |
| | 23 | + reposdb "github.com/tenseleyFlow/shithub/internal/repos/sqlc" |
| | 24 | +) |
| | 25 | + |
| | 26 | +// Decision is the result of evaluating a single ref update against |
| | 27 | +// the rule set. Allow=true means the push proceeds; Allow=false |
| | 28 | +// surfaces the reason+rule pattern back to the user via stderr. |
| | 29 | +type Decision struct { |
| | 30 | + Allow bool |
| | 31 | + Reason string |
| | 32 | + RuleID int64 |
| | 33 | + Pattern string |
| | 34 | +} |
| | 35 | + |
| | 36 | +// Update is one ref update from the pre-receive hook's stdin. |
| | 37 | +type Update struct { |
| | 38 | + OldSHA string |
| | 39 | + NewSHA string |
| | 40 | + Ref string // "refs/heads/<name>" — tag refs and other namespaces are skipped |
| | 41 | + Pusher int64 // user_id; 0 means anonymous which any rule that requires explicit pushers will reject |
| | 42 | +} |
| | 43 | + |
| | 44 | +// Enforce evaluates the rule set against `u`. Returns Allow=true |
| | 45 | +// when no rule rejects; otherwise Allow=false with a human-readable |
| | 46 | +// reason naming the pattern that matched. |
| | 47 | +// |
| | 48 | +// Rule precedence: longest-pattern-match wins (alphabetical tiebreak). |
| | 49 | +// Rules don't apply to tag pushes or non-heads namespaces. |
| | 50 | +func Enforce(ctx context.Context, pool *pgxpool.Pool, gitDir string, repoID int64, u Update) (Decision, error) { |
| | 51 | + if !strings.HasPrefix(u.Ref, "refs/heads/") { |
| | 52 | + return Decision{Allow: true, Reason: "non-branch ref"}, nil |
| | 53 | + } |
| | 54 | + branch := strings.TrimPrefix(u.Ref, "refs/heads/") |
| | 55 | + |
| | 56 | + rq := reposdb.New() |
| | 57 | + rules, err := rq.ListBranchProtectionRules(ctx, pool, repoID) |
| | 58 | + if err != nil { |
| | 59 | + return Decision{}, fmt.Errorf("load rules: %w", err) |
| | 60 | + } |
| | 61 | + rule, ok := matchRule(rules, branch) |
| | 62 | + if !ok { |
| | 63 | + return Decision{Allow: true, Reason: "no rule matched"}, nil |
| | 64 | + } |
| | 65 | + |
| | 66 | + isCreate := isAllZeros(u.OldSHA) |
| | 67 | + isDelete := isAllZeros(u.NewSHA) |
| | 68 | + |
| | 69 | + // 1. Deletion gate. |
| | 70 | + if isDelete && rule.PreventDeletion { |
| | 71 | + return deny(rule, "deletion of this branch is blocked by protection rule"), nil |
| | 72 | + } |
| | 73 | + |
| | 74 | + // 2. Force-push gate. Only meaningful when this is an update of an |
| | 75 | + // existing branch (both sides non-zero). Skipping allows the create |
| | 76 | + // case (oldSHA all-zero) and the delete case (handled above). |
| | 77 | + if !isCreate && !isDelete && rule.PreventForcePush { |
| | 78 | + ff, err := repogit.IsAncestor(ctx, gitDir, u.OldSHA, u.NewSHA) |
| | 79 | + if err != nil { |
| | 80 | + return Decision{}, fmt.Errorf("ancestor check: %w", err) |
| | 81 | + } |
| | 82 | + if !ff { |
| | 83 | + return deny(rule, "force-push to this branch is blocked by protection rule"), nil |
| | 84 | + } |
| | 85 | + } |
| | 86 | + |
| | 87 | + // 3. Allowed-pushers gate. |
| | 88 | + if len(rule.AllowedPusherUserIds) > 0 { |
| | 89 | + ok := false |
| | 90 | + for _, id := range rule.AllowedPusherUserIds { |
| | 91 | + if id == u.Pusher { |
| | 92 | + ok = true |
| | 93 | + break |
| | 94 | + } |
| | 95 | + } |
| | 96 | + if !ok { |
| | 97 | + return deny(rule, "pusher is not on the allowed list for this branch"), nil |
| | 98 | + } |
| | 99 | + } |
| | 100 | + |
| | 101 | + // 4. require_signed_commits, require_pr_for_push, status_checks_required |
| | 102 | + // are placeholder columns wired by S20's migration; their owning |
| | 103 | + // sprints flip them on. No-op here. |
| | 104 | + |
| | 105 | + return Decision{Allow: true, Reason: "passed all rules", RuleID: rule.ID, Pattern: rule.Pattern}, nil |
| | 106 | +} |
| | 107 | + |
| | 108 | +func deny(r reposdb.BranchProtectionRule, reason string) Decision { |
| | 109 | + return Decision{ |
| | 110 | + Allow: false, |
| | 111 | + Reason: reason, |
| | 112 | + RuleID: r.ID, |
| | 113 | + Pattern: r.Pattern, |
| | 114 | + } |
| | 115 | +} |
| | 116 | + |
| | 117 | +// matchRule returns the rule with the longest pattern matching branch |
| | 118 | +// (alphabetical tiebreaker). Returns ok=false when no rule matches. |
| | 119 | +// |
| | 120 | +// Patterns use filepath.Match semantics: |
| | 121 | +// - `*` matches any sequence of non-separator chars (NOT crossing `/`) |
| | 122 | +// - `?` matches a single non-separator char |
| | 123 | +// - `[abc]` matches one of a/b/c |
| | 124 | +// |
| | 125 | +// `release/*` matches `release/v1.0` but NOT `release/v1.0/sub`. |
| | 126 | +func matchRule(rules []reposdb.BranchProtectionRule, branch string) (reposdb.BranchProtectionRule, bool) { |
| | 127 | + type cand struct { |
| | 128 | + rule reposdb.BranchProtectionRule |
| | 129 | + } |
| | 130 | + var matches []cand |
| | 131 | + for _, r := range rules { |
| | 132 | + ok, err := filepath.Match(r.Pattern, branch) |
| | 133 | + if err != nil { |
| | 134 | + continue // bad pattern — admin should fix; treat as no-match |
| | 135 | + } |
| | 136 | + if ok { |
| | 137 | + matches = append(matches, cand{rule: r}) |
| | 138 | + } |
| | 139 | + } |
| | 140 | + if len(matches) == 0 { |
| | 141 | + return reposdb.BranchProtectionRule{}, false |
| | 142 | + } |
| | 143 | + sort.Slice(matches, func(i, j int) bool { |
| | 144 | + li, lj := len(matches[i].rule.Pattern), len(matches[j].rule.Pattern) |
| | 145 | + if li != lj { |
| | 146 | + return li > lj |
| | 147 | + } |
| | 148 | + return matches[i].rule.Pattern < matches[j].rule.Pattern |
| | 149 | + }) |
| | 150 | + return matches[0].rule, true |
| | 151 | +} |
| | 152 | + |
| | 153 | +// isAllZeros reports whether a SHA string is git's "this side is |
| | 154 | +// absent" sentinel (40 zeros). Both pre-receive lines use this. |
| | 155 | +func isAllZeros(sha string) bool { |
| | 156 | + if len(sha) != 40 { |
| | 157 | + return false |
| | 158 | + } |
| | 159 | + for _, c := range sha { |
| | 160 | + if c != '0' { |
| | 161 | + return false |
| | 162 | + } |
| | 163 | + } |
| | 164 | + return true |
| | 165 | +} |
| | 166 | + |
| | 167 | +// FriendlyMessage formats a deny Decision for the user's git client. |
| | 168 | +// The pre-receive hook writes this to stderr. |
| | 169 | +func FriendlyMessage(d Decision) string { |
| | 170 | + if d.Allow { |
| | 171 | + return "" |
| | 172 | + } |
| | 173 | + return fmt.Sprintf("shithub: %s (rule pattern %q).", d.Reason, d.Pattern) |
| | 174 | +} |
| | 175 | + |
| | 176 | +// ErrTransient is returned by Enforce when DB connectivity is the |
| | 177 | +// failure cause. Pre-receive maps this to "transient error; try |
| | 178 | +// again" and rejects the push (fail closed per S20 spec). |
| | 179 | +var ErrTransient = errors.New("protection: transient error") |