@@ -0,0 +1,250 @@ |
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | + |
| 3 | +package repo |
| 4 | + |
| 5 | +import ( |
| 6 | + "errors" |
| 7 | + "net/http" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/go-chi/chi/v5" |
| 12 | + "github.com/jackc/pgx/v5/pgtype" |
| 13 | + |
| 14 | + "github.com/tenseleyFlow/shithub/internal/auth/audit" |
| 15 | + "github.com/tenseleyFlow/shithub/internal/auth/policy" |
| 16 | + repogit "github.com/tenseleyFlow/shithub/internal/repos/git" |
| 17 | + reposdb "github.com/tenseleyFlow/shithub/internal/repos/sqlc" |
| 18 | + usersdb "github.com/tenseleyFlow/shithub/internal/users/sqlc" |
| 19 | + "github.com/tenseleyFlow/shithub/internal/web/middleware" |
| 20 | +) |
| 21 | + |
| 22 | +// MountSettingsBranches registers the branch-protection + default- |
| 23 | +// branch settings routes. Caller wraps with RequireUser. |
| 24 | +func (h *Handlers) MountSettingsBranches(r chi.Router) { |
| 25 | + r.Get("/{owner}/{repo}/settings/branches", h.settingsBranches) |
| 26 | + r.Post("/{owner}/{repo}/settings/branches", h.settingsBranchesUpsert) |
| 27 | + r.Post("/{owner}/{repo}/settings/branches/{id}/delete", h.settingsBranchesDelete) |
| 28 | + r.Post("/{owner}/{repo}/settings/default-branch", h.settingsDefaultBranch) |
| 29 | +} |
| 30 | + |
| 31 | +// settingsBranches lists existing protection rules + a form to create |
| 32 | +// a new one. Gated by repo:settings:branches. |
| 33 | +func (h *Handlers) settingsBranches(w http.ResponseWriter, r *http.Request) { |
| 34 | + row, owner, ok := h.loadRepoAndAuthorize(w, r, policy.ActionRepoSettingsBranches) |
| 35 | + if !ok { |
| 36 | + return |
| 37 | + } |
| 38 | + rules, err := h.rq.ListBranchProtectionRules(r.Context(), h.d.Pool, row.ID) |
| 39 | + if err != nil { |
| 40 | + h.d.Render.HTTPError(w, r, http.StatusInternalServerError, "") |
| 41 | + return |
| 42 | + } |
| 43 | + gitDir, _ := h.d.RepoFS.RepoPath(owner.Username, row.Name) |
| 44 | + refs, _ := repogit.ListRefs(r.Context(), gitDir) |
| 45 | + |
| 46 | + h.d.Render.RenderPage(w, r, "repo/settings_branches", map[string]any{ |
| 47 | + "Title": "Branch protection · " + row.Name, |
| 48 | + "CSRFToken": middleware.CSRFTokenForRequest(r), |
| 49 | + "Owner": owner.Username, |
| 50 | + "Repo": row, |
| 51 | + "Rules": rules, |
| 52 | + "Branches": refs.Branches, |
| 53 | + }) |
| 54 | +} |
| 55 | + |
| 56 | +// settingsBranchesUpsert creates a new rule (no `id` param) or updates |
| 57 | +// an existing one (`id` param set). Form fields: pattern, |
| 58 | +// prevent_force_push, prevent_deletion, require_pr_for_push, |
| 59 | +// allowed_pusher_usernames (comma-separated). |
| 60 | +func (h *Handlers) settingsBranchesUpsert(w http.ResponseWriter, r *http.Request) { |
| 61 | + row, owner, ok := h.loadRepoAndAuthorize(w, r, policy.ActionRepoSettingsBranches) |
| 62 | + if !ok { |
| 63 | + return |
| 64 | + } |
| 65 | + if err := r.ParseForm(); err != nil { |
| 66 | + http.Error(w, "form parse", http.StatusBadRequest) |
| 67 | + return |
| 68 | + } |
| 69 | + pattern := strings.TrimSpace(r.PostFormValue("pattern")) |
| 70 | + if pattern == "" || len(pattern) > 200 { |
| 71 | + http.Error(w, "pattern length must be 1–200", http.StatusBadRequest) |
| 72 | + return |
| 73 | + } |
| 74 | + preventForcePush := r.PostFormValue("prevent_force_push") == "on" |
| 75 | + preventDeletion := r.PostFormValue("prevent_deletion") == "on" |
| 76 | + requirePR := r.PostFormValue("require_pr_for_push") == "on" |
| 77 | + |
| 78 | + allowed, err := resolveUsernameList(r, h, r.PostFormValue("allowed_pushers")) |
| 79 | + if err != nil { |
| 80 | + http.Error(w, err.Error(), http.StatusBadRequest) |
| 81 | + return |
| 82 | + } |
| 83 | + |
| 84 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 85 | + |
| 86 | + idStr := r.PostFormValue("id") |
| 87 | + if idStr == "" { |
| 88 | + // Create. |
| 89 | + newID, err := h.rq.UpsertBranchProtectionRule(r.Context(), h.d.Pool, reposdb.UpsertBranchProtectionRuleParams{ |
| 90 | + RepoID: row.ID, |
| 91 | + Pattern: pattern, |
| 92 | + PreventForcePush: preventForcePush, |
| 93 | + PreventDeletion: preventDeletion, |
| 94 | + RequirePrForPush: requirePR, |
| 95 | + AllowedPusherUserIds: allowed, |
| 96 | + CreatedByUserID: pgtype.Int8{Int64: viewer.ID, Valid: viewer.ID != 0}, |
| 97 | + }) |
| 98 | + if err != nil { |
| 99 | + h.d.Logger.WarnContext(r.Context(), "branch-protection: insert", "error", err) |
| 100 | + http.Error(w, "failed to create rule", http.StatusInternalServerError) |
| 101 | + return |
| 102 | + } |
| 103 | + _ = h.d.Audit.Record(r.Context(), h.d.Pool, viewer.ID, |
| 104 | + audit.ActionRepoCreated, audit.TargetRepo, row.ID, |
| 105 | + map[string]any{"branch_protection_rule_id": newID, "pattern": pattern, "action": "create"}) |
| 106 | + } else { |
| 107 | + // Update. |
| 108 | + id, err := strconv.ParseInt(idStr, 10, 64) |
| 109 | + if err != nil { |
| 110 | + http.Error(w, "bad id", http.StatusBadRequest) |
| 111 | + return |
| 112 | + } |
| 113 | + // Defense in depth: confirm the rule belongs to this repo. |
| 114 | + existing, err := h.rq.GetBranchProtectionRule(r.Context(), h.d.Pool, id) |
| 115 | + if err != nil || existing.RepoID != row.ID { |
| 116 | + http.Error(w, "rule not found", http.StatusNotFound) |
| 117 | + return |
| 118 | + } |
| 119 | + if err := h.rq.UpdateBranchProtectionRule(r.Context(), h.d.Pool, reposdb.UpdateBranchProtectionRuleParams{ |
| 120 | + ID: id, |
| 121 | + Pattern: pattern, |
| 122 | + PreventForcePush: preventForcePush, |
| 123 | + PreventDeletion: preventDeletion, |
| 124 | + RequirePrForPush: requirePR, |
| 125 | + AllowedPusherUserIds: allowed, |
| 126 | + }); err != nil { |
| 127 | + http.Error(w, "failed to update rule", http.StatusInternalServerError) |
| 128 | + return |
| 129 | + } |
| 130 | + _ = h.d.Audit.Record(r.Context(), h.d.Pool, viewer.ID, |
| 131 | + audit.ActionRepoCreated, audit.TargetRepo, row.ID, |
| 132 | + map[string]any{"branch_protection_rule_id": id, "pattern": pattern, "action": "update"}) |
| 133 | + } |
| 134 | + http.Redirect(w, r, "/"+owner.Username+"/"+row.Name+"/settings/branches?notice=saved", http.StatusSeeOther) |
| 135 | +} |
| 136 | + |
| 137 | +// settingsBranchesDelete removes a rule. |
| 138 | +func (h *Handlers) settingsBranchesDelete(w http.ResponseWriter, r *http.Request) { |
| 139 | + row, owner, ok := h.loadRepoAndAuthorize(w, r, policy.ActionRepoSettingsBranches) |
| 140 | + if !ok { |
| 141 | + return |
| 142 | + } |
| 143 | + idStr := chi.URLParam(r, "id") |
| 144 | + id, err := strconv.ParseInt(idStr, 10, 64) |
| 145 | + if err != nil { |
| 146 | + http.Error(w, "bad id", http.StatusBadRequest) |
| 147 | + return |
| 148 | + } |
| 149 | + existing, err := h.rq.GetBranchProtectionRule(r.Context(), h.d.Pool, id) |
| 150 | + if err != nil || existing.RepoID != row.ID { |
| 151 | + http.Error(w, "rule not found", http.StatusNotFound) |
| 152 | + return |
| 153 | + } |
| 154 | + if err := h.rq.DeleteBranchProtectionRule(r.Context(), h.d.Pool, id); err != nil { |
| 155 | + http.Error(w, "failed to delete rule", http.StatusInternalServerError) |
| 156 | + return |
| 157 | + } |
| 158 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 159 | + _ = h.d.Audit.Record(r.Context(), h.d.Pool, viewer.ID, |
| 160 | + audit.ActionRepoCreated, audit.TargetRepo, row.ID, |
| 161 | + map[string]any{"branch_protection_rule_id": id, "pattern": existing.Pattern, "action": "delete"}) |
| 162 | + |
| 163 | + http.Redirect(w, r, "/"+owner.Username+"/"+row.Name+"/settings/branches?notice=deleted", http.StatusSeeOther) |
| 164 | +} |
| 165 | + |
| 166 | +// settingsDefaultBranch swaps the repo's default branch. Validates |
| 167 | +// the target exists, updates the DB row, and updates HEAD on disk via |
| 168 | +// `git symbolic-ref`. |
| 169 | +func (h *Handlers) settingsDefaultBranch(w http.ResponseWriter, r *http.Request) { |
| 170 | + row, owner, ok := h.loadRepoAndAuthorize(w, r, policy.ActionRepoSettingsBranches) |
| 171 | + if !ok { |
| 172 | + return |
| 173 | + } |
| 174 | + if err := r.ParseForm(); err != nil { |
| 175 | + http.Error(w, "form parse", http.StatusBadRequest) |
| 176 | + return |
| 177 | + } |
| 178 | + newDefault := strings.TrimSpace(r.PostFormValue("default_branch")) |
| 179 | + if newDefault == "" { |
| 180 | + http.Error(w, "default_branch required", http.StatusBadRequest) |
| 181 | + return |
| 182 | + } |
| 183 | + gitDir, err := h.d.RepoFS.RepoPath(owner.Username, row.Name) |
| 184 | + if err != nil { |
| 185 | + h.d.Render.HTTPError(w, r, http.StatusInternalServerError, "") |
| 186 | + return |
| 187 | + } |
| 188 | + refs, err := repogit.ListRefs(r.Context(), gitDir) |
| 189 | + if err != nil { |
| 190 | + http.Error(w, "ref lookup failed", http.StatusInternalServerError) |
| 191 | + return |
| 192 | + } |
| 193 | + exists := false |
| 194 | + for _, b := range refs.Branches { |
| 195 | + if b.Name == newDefault { |
| 196 | + exists = true |
| 197 | + break |
| 198 | + } |
| 199 | + } |
| 200 | + if !exists { |
| 201 | + http.Error(w, "branch not found", http.StatusBadRequest) |
| 202 | + return |
| 203 | + } |
| 204 | + |
| 205 | + if err := h.rq.UpdateRepoDefaultBranch(r.Context(), h.d.Pool, reposdb.UpdateRepoDefaultBranchParams{ |
| 206 | + ID: row.ID, DefaultBranch: newDefault, |
| 207 | + }); err != nil { |
| 208 | + http.Error(w, "DB update failed", http.StatusInternalServerError) |
| 209 | + return |
| 210 | + } |
| 211 | + if err := repogit.SetSymbolicRef(r.Context(), gitDir, "HEAD", "refs/heads/"+newDefault); err != nil { |
| 212 | + // DB updated but symbolic-ref failed — log and surface, but don't roll back DB |
| 213 | + // since the user-visible truth is the DB row (their UI shows it; new clones |
| 214 | + // follow it). Operator can re-run by setting it again. |
| 215 | + h.d.Logger.WarnContext(r.Context(), "default-branch: symbolic-ref", "error", err) |
| 216 | + } |
| 217 | + |
| 218 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 219 | + _ = h.d.Audit.Record(r.Context(), h.d.Pool, viewer.ID, |
| 220 | + audit.ActionRepoCreated, audit.TargetRepo, row.ID, |
| 221 | + map[string]any{"action": "default_branch_changed", "from": row.DefaultBranch, "to": newDefault}) |
| 222 | + |
| 223 | + http.Redirect(w, r, "/"+owner.Username+"/"+row.Name+"/settings/branches?notice=default-changed", http.StatusSeeOther) |
| 224 | +} |
| 225 | + |
| 226 | +// resolveUsernameList parses a comma-separated username list and |
| 227 | +// resolves each to a user_id. Empty input returns an empty slice |
| 228 | +// (no allowed-pushers restriction). Unknown usernames produce an |
| 229 | +// error so the admin sees the typo before the rule lands. |
| 230 | +func resolveUsernameList(r *http.Request, h *Handlers, raw string) ([]int64, error) { |
| 231 | + raw = strings.TrimSpace(raw) |
| 232 | + if raw == "" { |
| 233 | + return []int64{}, nil |
| 234 | + } |
| 235 | + uq := usersdb.New() |
| 236 | + parts := strings.Split(raw, ",") |
| 237 | + out := make([]int64, 0, len(parts)) |
| 238 | + for _, p := range parts { |
| 239 | + name := strings.ToLower(strings.TrimSpace(p)) |
| 240 | + if name == "" { |
| 241 | + continue |
| 242 | + } |
| 243 | + u, err := uq.GetUserByUsername(r.Context(), h.d.Pool, name) |
| 244 | + if err != nil { |
| 245 | + return nil, errors.New("unknown username: " + name) |
| 246 | + } |
| 247 | + out = append(out, u.ID) |
| 248 | + } |
| 249 | + return out, nil |
| 250 | +} |