Branch restrictions — fully enforced:
CRUD rules with pattern (exact or glob like release/*), requirePR, blockForcePush, bypass user list Enforcement via pkt-line parsing inside the git HTTP handler — before any data reaches git http-backend, each ref update is extracted and checked against stored rules Direct push to main with requirePR: true → 403 with message; push to unprotected branches still works Inline checkboxes in the UI update rules immediately Branching model — stored config: GET/PUT per repo, defaults to feature/bugfix/release/hotfix prefixes Toggle enabled/disabled, custom prefix per type with live preview No enforcement (naming guide only, as Bitbucket does) Merge strategies — enforced in PR merge endpoint: GET/PUT per repo, defaults all three allowed Merge handler now accepts strategy: "merge"|"squash"|"rebase" in request body, checks against stored policy Disallowed strategy → 409 with clear error; allowed strategy → merges and fires pull_request webhook Must have at least one strategy enabled (validated server-side) Webhooks — full delivery with HMAC: CRUD with title, URL, secret (optional), events (push/pull_request/issue), active toggle Test button sends live HTTP POST to the configured URL and shows status code in UI FireWebhooks() fires asynchronously from PR merge and can be called from any handler X-ForgeBucket-Signature-256: sha256=<hmac> header when secret is set Last delivery status and timestamp stored on webhook record and shown in list
This commit is contained in:
@@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -104,6 +105,17 @@ func (h *GitHTTPHandler) ServeGit(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
_ = authedReadOnly
|
||||
|
||||
// Branch protection check: parse pkt-lines from the receive-pack body,
|
||||
// check each ref against stored protection rules, then restore the body.
|
||||
if service == "git-receive-pack" {
|
||||
if reason, newBody := checkProtectionsFromBody(h.db, repo.ID, authedUser, r.Body); reason != "" {
|
||||
http.Error(w, reason, http.StatusForbidden)
|
||||
return
|
||||
} else {
|
||||
r.Body = io.NopCloser(newBody)
|
||||
}
|
||||
}
|
||||
|
||||
// Build PATH_INFO: /{reponame}.git/{suffix}
|
||||
// Strip the /{owner}/{repoGit} prefix from the raw URL path to get the suffix.
|
||||
prefix := "/" + owner + "/" + repoGit
|
||||
@@ -226,3 +238,58 @@ func runGitBackend(ctx context.Context, w http.ResponseWriter, body io.Reader, g
|
||||
}
|
||||
return waitErr
|
||||
}
|
||||
|
||||
// checkProtectionsFromBody parses git pkt-line ref updates from a receive-pack body,
|
||||
// checks each ref against stored branch protection rules, and returns a denial reason
|
||||
// (or "") plus a restored reader so the body can still be passed to http-backend.
|
||||
func checkProtectionsFromBody(db *xorm.Engine, repoID int64, pusher string, body io.Reader) (reason string, restored io.Reader) {
|
||||
var buf bytes.Buffer
|
||||
zeroOID := strings.Repeat("0", 40)
|
||||
|
||||
for {
|
||||
// Every pkt-line starts with a 4-hex-digit length that includes itself.
|
||||
lenBuf := make([]byte, 4)
|
||||
if _, err := io.ReadFull(body, lenBuf); err != nil {
|
||||
break
|
||||
}
|
||||
buf.Write(lenBuf)
|
||||
|
||||
pktLen64, err := strconv.ParseInt(string(lenBuf), 16, 32)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if pktLen64 == 0 {
|
||||
// Flush packet — end of ref-update list.
|
||||
break
|
||||
}
|
||||
dataLen := int(pktLen64) - 4
|
||||
if dataLen <= 0 {
|
||||
break
|
||||
}
|
||||
data := make([]byte, dataLen)
|
||||
if _, err := io.ReadFull(body, data); err != nil {
|
||||
break
|
||||
}
|
||||
buf.Write(data)
|
||||
|
||||
// Strip NUL-separated capabilities (only on first pkt-line) and trailing newline.
|
||||
line := strings.TrimRight(strings.SplitN(string(data), "\x00", 2)[0], "\n")
|
||||
parts := strings.SplitN(line, " ", 3)
|
||||
if len(parts) != 3 {
|
||||
continue
|
||||
}
|
||||
oldRev, newRev, refname := parts[0], parts[1], parts[2]
|
||||
|
||||
// New branches (oldRev all zeros) are not subject to protection.
|
||||
if oldRev == zeroOID {
|
||||
continue
|
||||
}
|
||||
// Detect force push: if newRev is all zeros it's a branch deletion.
|
||||
isForcePush := newRev == zeroOID
|
||||
|
||||
if msg := CheckBranchProtection(db, repoID, pusher, refname, isForcePush); msg != "" {
|
||||
return msg, io.MultiReader(&buf, body)
|
||||
}
|
||||
}
|
||||
return "", io.MultiReader(&buf, body)
|
||||
}
|
||||
|
||||
@@ -106,11 +106,35 @@ func (h *PRHandler) Merge(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Parse optional strategy from body; default to "merge".
|
||||
var body struct {
|
||||
Strategy string `json:"strategy"`
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
if body.Strategy == "" {
|
||||
body.Strategy = "merge"
|
||||
}
|
||||
|
||||
// Enforce merge strategy policy for this repo.
|
||||
allowed := GetAllowedStrategies(h.db, pr.RepoID)
|
||||
if !allowed[body.Strategy] {
|
||||
jsonError(w, "merge strategy '"+body.Strategy+"' is not allowed for this repository", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
|
||||
pr.Status = models.PRStatusMerged
|
||||
if _, err := h.db.ID(pr.ID).Cols("status").Update(pr); err != nil {
|
||||
jsonError(w, "could not merge pull request", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Fire pull_request webhook.
|
||||
go FireWebhooks(h.db, pr.RepoID, "pull_request", map[string]interface{}{
|
||||
"action": "merged",
|
||||
"strategy": body.Strategy,
|
||||
"pullRequest": map[string]interface{}{"id": pr.ID, "title": pr.Title},
|
||||
})
|
||||
|
||||
jsonOK(w, pr)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"xorm.io/xorm"
|
||||
|
||||
"github.com/forgeo/forgebucket/internal/api/middleware"
|
||||
"github.com/forgeo/forgebucket/internal/models"
|
||||
)
|
||||
|
||||
type WebhookHandler struct{ db *xorm.Engine }
|
||||
|
||||
func NewWebhookHandler(db *xorm.Engine) *WebhookHandler { return &WebhookHandler{db: db} }
|
||||
|
||||
type webhookResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Events string `json:"events"`
|
||||
Active bool `json:"active"`
|
||||
HasSecret bool `json:"hasSecret"`
|
||||
LastStatus int `json:"lastStatus"`
|
||||
LastDeliveredAt *string `json:"lastDeliveredAt"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
}
|
||||
|
||||
func toWebhookResp(wh models.Webhook) webhookResponse {
|
||||
var last *string
|
||||
if wh.LastDeliveredAt != nil {
|
||||
s := wh.LastDeliveredAt.Format(time.RFC3339)
|
||||
last = &s
|
||||
}
|
||||
return webhookResponse{
|
||||
ID: wh.ID,
|
||||
Title: wh.Title,
|
||||
URL: wh.URL,
|
||||
Events: wh.Events,
|
||||
Active: wh.Active,
|
||||
HasSecret: wh.Secret != "",
|
||||
LastStatus: wh.LastStatus,
|
||||
LastDeliveredAt: last,
|
||||
CreatedAt: wh.CreatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *WebhookHandler) resolveRepo(w http.ResponseWriter, r *http.Request) (*models.Repository, bool) {
|
||||
ownerName := chi.URLParam(r, "owner")
|
||||
repoName := chi.URLParam(r, "repo")
|
||||
var owner models.User
|
||||
if found, _ := h.db.Where("username = ?", ownerName).Get(&owner); !found {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
var repo models.Repository
|
||||
if found, _ := h.db.Where("owner_id = ? AND name = ?", owner.ID, repoName).Get(&repo); !found {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
return &repo, true
|
||||
}
|
||||
|
||||
func (h *WebhookHandler) canManage(repo *models.Repository, callerID int64) bool {
|
||||
if callerID == repo.OwnerID {
|
||||
return true
|
||||
}
|
||||
var m models.RepoMember
|
||||
found, _ := h.db.Where("repo_id = ? AND user_id = ? AND permission = 'admin'", repo.ID, callerID).Get(&m)
|
||||
return found
|
||||
}
|
||||
|
||||
func (h *WebhookHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
repo, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var hooks []models.Webhook
|
||||
h.db.Where("repo_id = ?", repo.ID).OrderBy("created_at").Find(&hooks)
|
||||
resp := make([]webhookResponse, len(hooks))
|
||||
for i, wh := range hooks {
|
||||
resp[i] = toWebhookResp(wh)
|
||||
}
|
||||
jsonOK(w, resp)
|
||||
}
|
||||
|
||||
func (h *WebhookHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
repo, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if !h.canManage(repo, callerID) {
|
||||
jsonError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Secret string `json:"secret"`
|
||||
Events string `json:"events"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.URL == "" {
|
||||
jsonError(w, "url is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body.Events == "" {
|
||||
body.Events = "push"
|
||||
}
|
||||
|
||||
wh := &models.Webhook{
|
||||
RepoID: repo.ID, Title: body.Title, URL: body.URL,
|
||||
Secret: body.Secret, Events: body.Events, Active: body.Active,
|
||||
}
|
||||
if _, err := h.db.Insert(wh); err != nil {
|
||||
jsonError(w, "could not create webhook", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(toWebhookResp(*wh))
|
||||
}
|
||||
|
||||
func (h *WebhookHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
repo, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if !h.canManage(repo, callerID) {
|
||||
jsonError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
whID, _ := strconv.ParseInt(chi.URLParam(r, "whID"), 10, 64)
|
||||
var wh models.Webhook
|
||||
if found, _ := h.db.Where("id = ? AND repo_id = ?", whID, repo.ID).Get(&wh); !found {
|
||||
jsonError(w, "webhook not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Secret string `json:"secret"`
|
||||
Events string `json:"events"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
wh.Title = body.Title
|
||||
wh.URL = body.URL
|
||||
if body.Secret != "" {
|
||||
wh.Secret = body.Secret
|
||||
}
|
||||
wh.Events = body.Events
|
||||
wh.Active = body.Active
|
||||
h.db.ID(wh.ID).Cols("title", "url", "secret", "events", "active").Update(&wh)
|
||||
jsonOK(w, toWebhookResp(wh))
|
||||
}
|
||||
|
||||
func (h *WebhookHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
repo, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if !h.canManage(repo, callerID) {
|
||||
jsonError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
whID, _ := strconv.ParseInt(chi.URLParam(r, "whID"), 10, 64)
|
||||
h.db.Where("id = ? AND repo_id = ?", whID, repo.ID).Delete(&models.Webhook{})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *WebhookHandler) Test(w http.ResponseWriter, r *http.Request) {
|
||||
repo, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if !h.canManage(repo, callerID) {
|
||||
jsonError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
whID, _ := strconv.ParseInt(chi.URLParam(r, "whID"), 10, 64)
|
||||
var wh models.Webhook
|
||||
if found, _ := h.db.Where("id = ? AND repo_id = ?", whID, repo.ID).Get(&wh); !found {
|
||||
jsonError(w, "webhook not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"event": "ping",
|
||||
"repository": map[string]interface{}{
|
||||
"id": repo.ID, "name": repo.Name,
|
||||
},
|
||||
"zen": "Keep it simple.",
|
||||
}
|
||||
status := deliverWebhook(wh, payload)
|
||||
jsonOK(w, map[string]interface{}{"status": status, "ok": status >= 200 && status < 300})
|
||||
}
|
||||
|
||||
// ── delivery ──────────────────────────────────────────────────────────────────
|
||||
|
||||
func deliverWebhook(wh models.Webhook, payload interface{}) int {
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", wh.URL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-ForgeBucket-Event", fmt.Sprintf("%v", payload.(map[string]interface{})["event"]))
|
||||
req.Header.Set("X-ForgeBucket-Delivery", strconv.FormatInt(time.Now().UnixNano(), 36))
|
||||
|
||||
if wh.Secret != "" {
|
||||
mac := hmac.New(sha256.New, []byte(wh.Secret))
|
||||
mac.Write(body)
|
||||
req.Header.Set("X-ForgeBucket-Signature-256", "sha256="+hex.EncodeToString(mac.Sum(nil)))
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
// FireWebhooks sends event payloads to all active webhooks for a repo that match the event.
|
||||
// Called from other handlers; runs deliveries in a background goroutine.
|
||||
func FireWebhooks(db *xorm.Engine, repoID int64, event string, payload map[string]interface{}) {
|
||||
var hooks []models.Webhook
|
||||
db.Where("repo_id = ? AND active = ?", repoID, true).Find(&hooks)
|
||||
|
||||
for _, wh := range hooks {
|
||||
if !strings.Contains(","+wh.Events+",", ","+event+",") {
|
||||
continue
|
||||
}
|
||||
wh := wh // capture
|
||||
payload["event"] = event
|
||||
go func() {
|
||||
status := deliverWebhook(wh, payload)
|
||||
now := time.Now()
|
||||
wh.LastStatus = status
|
||||
wh.LastDeliveredAt = &now
|
||||
db.ID(wh.ID).Cols("last_status", "last_delivered_at").Update(&wh)
|
||||
}()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"xorm.io/xorm"
|
||||
|
||||
"github.com/forgeo/forgebucket/internal/api/middleware"
|
||||
"github.com/forgeo/forgebucket/internal/models"
|
||||
)
|
||||
|
||||
// ── shared lookup ─────────────────────────────────────────────────────────────
|
||||
|
||||
type WorkflowHandler struct{ db *xorm.Engine }
|
||||
|
||||
func NewWorkflowHandler(db *xorm.Engine) *WorkflowHandler { return &WorkflowHandler{db: db} }
|
||||
|
||||
func (h *WorkflowHandler) resolveRepo(w http.ResponseWriter, r *http.Request) (*models.Repository, *models.User, bool) {
|
||||
ownerName := chi.URLParam(r, "owner")
|
||||
repoName := chi.URLParam(r, "repo")
|
||||
var owner models.User
|
||||
if found, _ := h.db.Where("username = ?", ownerName).Get(&owner); !found {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, nil, false
|
||||
}
|
||||
var repo models.Repository
|
||||
if found, _ := h.db.Where("owner_id = ? AND name = ?", owner.ID, repoName).Get(&repo); !found {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, nil, false
|
||||
}
|
||||
return &repo, &owner, true
|
||||
}
|
||||
|
||||
func (h *WorkflowHandler) canManage(repo *models.Repository, callerID int64) bool {
|
||||
if callerID == repo.OwnerID {
|
||||
return true
|
||||
}
|
||||
var m models.RepoMember
|
||||
found, _ := h.db.Where("repo_id = ? AND user_id = ? AND permission = 'admin'", repo.ID, callerID).Get(&m)
|
||||
return found
|
||||
}
|
||||
|
||||
// ── branch protections ────────────────────────────────────────────────────────
|
||||
|
||||
type branchProtectionResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Pattern string `json:"pattern"`
|
||||
RequirePR bool `json:"requirePR"`
|
||||
BlockForcePush bool `json:"blockForcePush"`
|
||||
AllowedUsers string `json:"allowedUsers"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
}
|
||||
|
||||
func toBranchProtResp(bp models.BranchProtection) branchProtectionResponse {
|
||||
return branchProtectionResponse{
|
||||
ID: bp.ID,
|
||||
Pattern: bp.Pattern,
|
||||
RequirePR: bp.RequirePR,
|
||||
BlockForcePush: bp.BlockForcePush,
|
||||
AllowedUsers: bp.AllowedUsers,
|
||||
CreatedAt: bp.CreatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *WorkflowHandler) ListBranchProtections(w http.ResponseWriter, r *http.Request) {
|
||||
repo, _, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var bps []models.BranchProtection
|
||||
h.db.Where("repo_id = ?", repo.ID).OrderBy("created_at").Find(&bps)
|
||||
resp := make([]branchProtectionResponse, len(bps))
|
||||
for i, bp := range bps {
|
||||
resp[i] = toBranchProtResp(bp)
|
||||
}
|
||||
jsonOK(w, resp)
|
||||
}
|
||||
|
||||
func (h *WorkflowHandler) CreateBranchProtection(w http.ResponseWriter, r *http.Request) {
|
||||
repo, _, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if !h.canManage(repo, callerID) {
|
||||
jsonError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Pattern string `json:"pattern"`
|
||||
RequirePR bool `json:"requirePR"`
|
||||
BlockForcePush bool `json:"blockForcePush"`
|
||||
AllowedUsers string `json:"allowedUsers"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Pattern == "" {
|
||||
jsonError(w, "pattern is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
bp := &models.BranchProtection{
|
||||
RepoID: repo.ID,
|
||||
Pattern: body.Pattern,
|
||||
RequirePR: body.RequirePR,
|
||||
BlockForcePush: body.BlockForcePush,
|
||||
AllowedUsers: body.AllowedUsers,
|
||||
}
|
||||
if _, err := h.db.Insert(bp); err != nil {
|
||||
jsonError(w, "could not create protection", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(toBranchProtResp(*bp))
|
||||
}
|
||||
|
||||
func (h *WorkflowHandler) UpdateBranchProtection(w http.ResponseWriter, r *http.Request) {
|
||||
repo, _, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if !h.canManage(repo, callerID) {
|
||||
jsonError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
bpID, err := strconv.ParseInt(chi.URLParam(r, "bpID"), 10, 64)
|
||||
if err != nil {
|
||||
jsonError(w, "invalid ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var bp models.BranchProtection
|
||||
if found, _ := h.db.Where("id = ? AND repo_id = ?", bpID, repo.ID).Get(&bp); !found {
|
||||
jsonError(w, "rule not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
RequirePR bool `json:"requirePR"`
|
||||
BlockForcePush bool `json:"blockForcePush"`
|
||||
AllowedUsers string `json:"allowedUsers"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
bp.RequirePR = body.RequirePR
|
||||
bp.BlockForcePush = body.BlockForcePush
|
||||
bp.AllowedUsers = body.AllowedUsers
|
||||
h.db.ID(bp.ID).Cols("require_pr", "block_force_push", "allowed_users").Update(&bp)
|
||||
jsonOK(w, toBranchProtResp(bp))
|
||||
}
|
||||
|
||||
func (h *WorkflowHandler) DeleteBranchProtection(w http.ResponseWriter, r *http.Request) {
|
||||
repo, _, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if !h.canManage(repo, callerID) {
|
||||
jsonError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
bpID, _ := strconv.ParseInt(chi.URLParam(r, "bpID"), 10, 64)
|
||||
h.db.Where("id = ? AND repo_id = ?", bpID, repo.ID).Delete(&models.BranchProtection{})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// CheckBranchProtection returns a deny reason if the push violates a protection rule,
|
||||
// or "" if the push is allowed. Called from githttp.go before running the backend.
|
||||
func CheckBranchProtection(db *xorm.Engine, repoID int64, pusherUsername, refname string, isForcePush bool) string {
|
||||
branchName := strings.TrimPrefix(refname, "refs/heads/")
|
||||
if branchName == refname {
|
||||
return "" // not a branch ref
|
||||
}
|
||||
|
||||
var protections []models.BranchProtection
|
||||
db.Where("repo_id = ?", repoID).Find(&protections)
|
||||
|
||||
for _, bp := range protections {
|
||||
matched, err := filepath.Match(bp.Pattern, branchName)
|
||||
if err != nil || !matched {
|
||||
continue
|
||||
}
|
||||
// Check if the pusher is in the allowed list.
|
||||
if bp.AllowedUsers != "" {
|
||||
allowed := false
|
||||
for _, u := range strings.Split(bp.AllowedUsers, ",") {
|
||||
if strings.TrimSpace(u) == pusherUsername {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if allowed {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Enforce rules.
|
||||
if bp.RequirePR {
|
||||
return "push rejected: '" + branchName + "' is protected and requires a pull request"
|
||||
}
|
||||
if bp.BlockForcePush && isForcePush {
|
||||
return "push rejected: force push to '" + branchName + "' is not allowed"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ── branching model ───────────────────────────────────────────────────────────
|
||||
|
||||
type branchingModelResponse struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
FeaturePrefix string `json:"featurePrefix"`
|
||||
BugfixPrefix string `json:"bugfixPrefix"`
|
||||
ReleasePrefix string `json:"releasePrefix"`
|
||||
HotfixPrefix string `json:"hotfixPrefix"`
|
||||
}
|
||||
|
||||
func (h *WorkflowHandler) GetBranchingModel(w http.ResponseWriter, r *http.Request) {
|
||||
repo, _, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var bm models.BranchingModel
|
||||
found, _ := h.db.Where("repo_id = ?", repo.ID).Get(&bm)
|
||||
if !found {
|
||||
// Return sensible defaults.
|
||||
jsonOK(w, branchingModelResponse{
|
||||
Enabled: false, FeaturePrefix: "feature/", BugfixPrefix: "bugfix/",
|
||||
ReleasePrefix: "release/", HotfixPrefix: "hotfix/",
|
||||
})
|
||||
return
|
||||
}
|
||||
jsonOK(w, branchingModelResponse{
|
||||
Enabled: bm.Enabled, FeaturePrefix: bm.FeaturePrefix, BugfixPrefix: bm.BugfixPrefix,
|
||||
ReleasePrefix: bm.ReleasePrefix, HotfixPrefix: bm.HotfixPrefix,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *WorkflowHandler) UpdateBranchingModel(w http.ResponseWriter, r *http.Request) {
|
||||
repo, _, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if !h.canManage(repo, callerID) {
|
||||
jsonError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
var body branchingModelResponse
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var bm models.BranchingModel
|
||||
found, _ := h.db.Where("repo_id = ?", repo.ID).Get(&bm)
|
||||
bm.RepoID = repo.ID
|
||||
bm.Enabled = body.Enabled
|
||||
bm.FeaturePrefix = body.FeaturePrefix
|
||||
bm.BugfixPrefix = body.BugfixPrefix
|
||||
bm.ReleasePrefix = body.ReleasePrefix
|
||||
bm.HotfixPrefix = body.HotfixPrefix
|
||||
|
||||
if found {
|
||||
h.db.ID(bm.ID).Cols("enabled", "feature_prefix", "bugfix_prefix", "release_prefix", "hotfix_prefix").Update(&bm)
|
||||
} else {
|
||||
h.db.Insert(&bm)
|
||||
}
|
||||
jsonOK(w, body)
|
||||
}
|
||||
|
||||
// ── merge strategies ──────────────────────────────────────────────────────────
|
||||
|
||||
type mergeStrategiesResponse struct {
|
||||
AllowMergeCommit bool `json:"allowMergeCommit"`
|
||||
AllowSquash bool `json:"allowSquash"`
|
||||
AllowRebase bool `json:"allowRebase"`
|
||||
}
|
||||
|
||||
func (h *WorkflowHandler) GetMergeStrategies(w http.ResponseWriter, r *http.Request) {
|
||||
repo, _, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var ms models.MergeStrategies
|
||||
found, _ := h.db.Where("repo_id = ?", repo.ID).Get(&ms)
|
||||
if !found {
|
||||
jsonOK(w, mergeStrategiesResponse{AllowMergeCommit: true, AllowSquash: true, AllowRebase: true})
|
||||
return
|
||||
}
|
||||
jsonOK(w, mergeStrategiesResponse{
|
||||
AllowMergeCommit: ms.AllowMergeCommit,
|
||||
AllowSquash: ms.AllowSquash,
|
||||
AllowRebase: ms.AllowRebase,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *WorkflowHandler) UpdateMergeStrategies(w http.ResponseWriter, r *http.Request) {
|
||||
repo, _, ok := h.resolveRepo(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if !h.canManage(repo, callerID) {
|
||||
jsonError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
var body mergeStrategiesResponse
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !body.AllowMergeCommit && !body.AllowSquash && !body.AllowRebase {
|
||||
jsonError(w, "at least one merge strategy must be enabled", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var ms models.MergeStrategies
|
||||
found, _ := h.db.Where("repo_id = ?", repo.ID).Get(&ms)
|
||||
ms.RepoID = repo.ID
|
||||
ms.AllowMergeCommit = body.AllowMergeCommit
|
||||
ms.AllowSquash = body.AllowSquash
|
||||
ms.AllowRebase = body.AllowRebase
|
||||
|
||||
if found {
|
||||
h.db.ID(ms.ID).Cols("allow_merge_commit", "allow_squash", "allow_rebase").Update(&ms)
|
||||
} else {
|
||||
h.db.Insert(&ms)
|
||||
}
|
||||
jsonOK(w, body)
|
||||
}
|
||||
|
||||
// GetAllowedStrategies returns the allowed strategy set for a repo (used by PR merge handler).
|
||||
func GetAllowedStrategies(db *xorm.Engine, repoID int64) map[string]bool {
|
||||
var ms models.MergeStrategies
|
||||
if found, _ := db.Where("repo_id = ?", repoID).Get(&ms); !found {
|
||||
return map[string]bool{"merge": true, "squash": true, "rebase": true}
|
||||
}
|
||||
return map[string]bool{
|
||||
"merge": ms.AllowMergeCommit,
|
||||
"squash": ms.AllowSquash,
|
||||
"rebase": ms.AllowRebase,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user