| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "net/http" |
| 7 | "regexp" |
| 8 | "sort" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | |
| 12 | "gitlab.com/Timfa/bluegit/internal/access" |
| 13 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 14 | "gitlab.com/Timfa/bluegit/internal/store" |
| 15 | "gitlab.com/Timfa/bluegit/internal/webhook" |
| 16 | ) |
| 17 | |
| 18 | // Webhooks aanpassen en kopiëren. Geheimen blijven server-side: het |
| 19 | // token-veld is de naam van een geheim, en bij kopiëren gaan ontbrekende |
| 20 | // geheimen versleuteld mee naar het doel. Waarden komen nooit in een respons. |
| 21 | |
| 22 | func hookID(r *http.Request) (int64, error) { |
| 23 | id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) |
| 24 | if err != nil || id <= 0 { |
| 25 | return 0, fail(404, i18n.E("err.notFound")) |
| 26 | } |
| 27 | return id, nil |
| 28 | } |
| 29 | |
| 30 | // inputOf geeft de opgeslagen invoer van een webhook terug. |
| 31 | func inputOf(h store.Webhook) webhook.Input { |
| 32 | d := draftFrom(h) |
| 33 | return webhook.Input{ |
| 34 | URL: d.URL, Username: d.Username, Avatar: d.Avatar, Icon: d.Icon, Alias: d.Alias, |
| 35 | Token: d.Token, Chat: d.Chat, Server: d.Server, Topic: d.Topic, |
| 36 | Homeserver: d.Home, Room: d.Room, Method: d.Method, ContentType: d.CType, |
| 37 | Headers: d.Headers, Body: d.Body, |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | // opPatchWebhook werkt alleen de meegestuurde velden bij. Een leeg of |
| 42 | // weggelaten token houdt het bestaande geheim. |
| 43 | func (s *Server) opPatchWebhook(ctx context.Context, user store.User, kind string, scopeID, id int64, raw map[string]json.RawMessage) (store.Webhook, error) { |
| 44 | if err := s.manageScope(ctx, user, kind, scopeID); err != nil { |
| 45 | return store.Webhook{}, err |
| 46 | } |
| 47 | h, err := s.Store.Webhook(ctx, kind, scopeID, id) |
| 48 | if err != nil { |
| 49 | return store.Webhook{}, fail(404, i18n.E("err.notFound")) |
| 50 | } |
| 51 | in := inputOf(h) |
| 52 | name, preset, filter, events := h.Name, h.Preset, h.BranchFilter, h.Events |
| 53 | str := func(key string, dst *string, keepEmpty bool) error { |
| 54 | v, ok := raw[key] |
| 55 | if !ok { |
| 56 | return nil |
| 57 | } |
| 58 | var sv string |
| 59 | if err := json.Unmarshal(v, &sv); err != nil { |
| 60 | return fail(400, i18n.E("err.json")) |
| 61 | } |
| 62 | if keepEmpty && strings.TrimSpace(sv) == "" { |
| 63 | return nil |
| 64 | } |
| 65 | *dst = sv |
| 66 | return nil |
| 67 | } |
| 68 | fields := []struct { |
| 69 | key string |
| 70 | dst *string |
| 71 | keep bool |
| 72 | }{ |
| 73 | {"name", &name, true}, {"preset", &preset, true}, {"branch_filter", &filter, false}, |
| 74 | {"url", &in.URL, true}, {"username", &in.Username, false}, {"avatar", &in.Avatar, false}, |
| 75 | {"icon", &in.Icon, false}, {"alias", &in.Alias, false}, {"token", &in.Token, true}, |
| 76 | {"chat", &in.Chat, false}, {"server", &in.Server, false}, {"topic", &in.Topic, false}, |
| 77 | {"homeserver", &in.Homeserver, false}, {"room", &in.Room, false}, {"method", &in.Method, true}, |
| 78 | {"content_type", &in.ContentType, false}, {"headers", &in.Headers, true}, {"body", &in.Body, false}, |
| 79 | } |
| 80 | for _, f := range fields { |
| 81 | if err := str(f.key, f.dst, f.keep); err != nil { |
| 82 | return store.Webhook{}, err |
| 83 | } |
| 84 | } |
| 85 | if v, ok := raw["events"]; ok { |
| 86 | var ev []string |
| 87 | if err := json.Unmarshal(v, &ev); err != nil { |
| 88 | return store.Webhook{}, fail(400, i18n.E("err.json")) |
| 89 | } |
| 90 | events = ev |
| 91 | } |
| 92 | if _, err := s.saveWebhookRecord(ctx, kind, scopeID, id, strings.TrimSpace(name), preset, filter, events, in); err != nil { |
| 93 | if store.Missing(err) { |
| 94 | return store.Webhook{}, fail(404, i18n.E("err.notFound")) |
| 95 | } |
| 96 | return store.Webhook{}, fail(400, err) |
| 97 | } |
| 98 | if v, ok := raw["active"]; ok { |
| 99 | var on bool |
| 100 | if json.Unmarshal(v, &on) == nil { |
| 101 | _ = s.Store.SetWebhookActive(ctx, kind, scopeID, id, on) |
| 102 | } |
| 103 | } |
| 104 | return s.Store.Webhook(ctx, kind, scopeID, id) |
| 105 | } |
| 106 | |
| 107 | var secretRefRe = regexp.MustCompile(`\{\{\s*secret\.([A-Za-z_][A-Za-z0-9_]*)\s*\}\}`) |
| 108 | |
| 109 | // hookSecretRefs geeft de geheimnamen die een webhook gebruikt. |
| 110 | func hookSecretRefs(h store.Webhook) []string { |
| 111 | seen := map[string]bool{} |
| 112 | add := func(s string) { |
| 113 | for _, m := range secretRefRe.FindAllStringSubmatch(s, -1) { |
| 114 | seen[m[1]] = true |
| 115 | } |
| 116 | } |
| 117 | add(h.URLTemplate) |
| 118 | add(h.BodyTemplate) |
| 119 | for k, v := range h.Headers { |
| 120 | add(k) |
| 121 | add(v) |
| 122 | } |
| 123 | out := make([]string, 0, len(seen)) |
| 124 | for k := range seen { |
| 125 | out = append(out, k) |
| 126 | } |
| 127 | sort.Strings(out) |
| 128 | return out |
| 129 | } |
| 130 | |
| 131 | type scopeRef struct { |
| 132 | Kind string |
| 133 | ID int64 |
| 134 | } |
| 135 | |
| 136 | // secretScopes geeft de scopes waaruit een webhook geheimen leest, eigen scope eerst. |
| 137 | func (s *Server) secretScopes(ctx context.Context, kind string, id int64) []scopeRef { |
| 138 | out := []scopeRef{{kind, id}} |
| 139 | if kind == "repo" { |
| 140 | if repo, err := s.Store.RepoByID(ctx, id); err == nil && repo.OwnerKind == "group" { |
| 141 | out = append(out, scopeRef{"group", repo.OwnerID}) |
| 142 | } |
| 143 | } |
| 144 | return out |
| 145 | } |
| 146 | |
| 147 | func (s *Server) secretNames(ctx context.Context, sc scopeRef) map[string]bool { |
| 148 | out := map[string]bool{} |
| 149 | list, _ := s.Store.ListSecrets(ctx, sc.Kind, sc.ID) |
| 150 | for _, m := range list { |
| 151 | out[m.Name] = true |
| 152 | } |
| 153 | return out |
| 154 | } |
| 155 | |
| 156 | // CopyTarget is het doel van een kopie. |
| 157 | type CopyTarget struct { |
| 158 | Type string `json:"target_type"` // project of group |
| 159 | Target string `json:"target"` // eigenaar/project of groepspad |
| 160 | Name string `json:"name"` |
| 161 | Events []string `json:"events"` |
| 162 | } |
| 163 | |
| 164 | // HookCopyResult vertelt wat er gekopieerd is, zonder waarden. |
| 165 | type HookCopyResult struct { |
| 166 | Hook store.Webhook |
| 167 | CopiedSecrets []string |
| 168 | MissingSecrets []string |
| 169 | } |
| 170 | |
| 171 | func (s *Server) resolveTarget(ctx context.Context, t CopyTarget) (string, int64, error) { |
| 172 | path := strings.Trim(strings.TrimSpace(t.Target), "/") |
| 173 | switch strings.ToLower(strings.TrimSpace(t.Type)) { |
| 174 | case "project", "repo": |
| 175 | i := strings.LastIndex(path, "/") |
| 176 | if i <= 0 { |
| 177 | return "", 0, fail(404, i18n.E("err.notFound")) |
| 178 | } |
| 179 | repo, err := s.Store.RepoByPath(ctx, path[:i], path[i+1:]) |
| 180 | if err != nil { |
| 181 | return "", 0, fail(404, i18n.E("err.notFound")) |
| 182 | } |
| 183 | return "repo", repo.ID, nil |
| 184 | case "group": |
| 185 | g, err := s.Store.GroupByPath(ctx, path) |
| 186 | if err != nil { |
| 187 | return "", 0, fail(404, i18n.E("err.notFound")) |
| 188 | } |
| 189 | return "group", g.ID, nil |
| 190 | } |
| 191 | return "", 0, fail(400, i18n.E("err.scope")) |
| 192 | } |
| 193 | |
| 194 | // opCopyWebhook kopieert een webhook met geheimen naar een ander project of |
| 195 | // een andere groep. Beide scopes vragen beheerrechten. |
| 196 | func (s *Server) opCopyWebhook(ctx context.Context, user store.User, kind string, scopeID, id int64, t CopyTarget) (HookCopyResult, error) { |
| 197 | if err := s.manageScope(ctx, user, kind, scopeID); err != nil { |
| 198 | return HookCopyResult{}, err |
| 199 | } |
| 200 | h, err := s.Store.Webhook(ctx, kind, scopeID, id) |
| 201 | if err != nil { |
| 202 | return HookCopyResult{}, fail(404, i18n.E("err.notFound")) |
| 203 | } |
| 204 | tKind, tID, err := s.resolveTarget(ctx, t) |
| 205 | if err != nil { |
| 206 | return HookCopyResult{}, err |
| 207 | } |
| 208 | if err := s.manageScope(ctx, user, tKind, tID); err != nil { |
| 209 | if oe, ok := err.(*opError); ok && oe.status == 403 { |
| 210 | return HookCopyResult{}, fail(404, i18n.E("err.notFound")) |
| 211 | } |
| 212 | return HookCopyResult{}, err |
| 213 | } |
| 214 | if tKind == kind && tID == scopeID && strings.TrimSpace(t.Name) == "" { |
| 215 | t.Name = h.Name + " (2)" |
| 216 | } |
| 217 | nh := h |
| 218 | nh.ID, nh.ScopeKind, nh.ScopeID = 0, tKind, tID |
| 219 | if n := strings.TrimSpace(t.Name); n != "" { |
| 220 | nh.Name = n |
| 221 | } |
| 222 | if t.Events != nil { |
| 223 | if len(t.Events) == 0 { |
| 224 | return HookCopyResult{}, fail(400, i18n.E("err.pickEvent")) |
| 225 | } |
| 226 | nh.Events = t.Events |
| 227 | } |
| 228 | var res HookCopyResult |
| 229 | src := s.secretScopes(ctx, kind, scopeID) |
| 230 | dst := s.secretScopes(ctx, tKind, tID) |
| 231 | srcNames := make([]map[string]bool, len(src)) |
| 232 | for i, sc := range src { |
| 233 | srcNames[i] = s.secretNames(ctx, sc) |
| 234 | } |
| 235 | dstNames := map[string]bool{} |
| 236 | for _, sc := range dst { |
| 237 | for k := range s.secretNames(ctx, sc) { |
| 238 | dstNames[k] = true |
| 239 | } |
| 240 | } |
| 241 | type plan struct { |
| 242 | from scopeRef |
| 243 | name string |
| 244 | } |
| 245 | var todo []plan |
| 246 | for _, name := range hookSecretRefs(h) { |
| 247 | if dstNames[name] { |
| 248 | continue |
| 249 | } |
| 250 | found := false |
| 251 | for i, sc := range src { |
| 252 | if srcNames[i][name] { |
| 253 | todo = append(todo, plan{sc, name}) |
| 254 | found = true |
| 255 | break |
| 256 | } |
| 257 | } |
| 258 | if !found { |
| 259 | res.MissingSecrets = append(res.MissingSecrets, name) |
| 260 | } |
| 261 | } |
| 262 | for _, p := range todo { |
| 263 | if err := s.Store.CopySecret(ctx, p.from.Kind, p.from.ID, p.name, tKind, tID); err != nil { |
| 264 | return HookCopyResult{}, fail(400, err) |
| 265 | } |
| 266 | res.CopiedSecrets = append(res.CopiedSecrets, p.name) |
| 267 | } |
| 268 | nid, err := s.Store.CreateWebhook(ctx, nh) |
| 269 | if err != nil { |
| 270 | return HookCopyResult{}, fail(400, err) |
| 271 | } |
| 272 | if !h.Active { |
| 273 | _ = s.Store.SetWebhookActive(ctx, tKind, tID, nid, false) |
| 274 | } |
| 275 | res.Hook, err = s.Store.Webhook(ctx, tKind, tID, nid) |
| 276 | if err != nil { |
| 277 | return HookCopyResult{}, fail(500, err) |
| 278 | } |
| 279 | return res, nil |
| 280 | } |
| 281 | |
| 282 | // --- API --- |
| 283 | |
| 284 | func (s *Server) apiPatchHook(w http.ResponseWriter, r *http.Request, kind string, scopeID int64) { |
| 285 | id, err := hookID(r) |
| 286 | if !s.apiOK(w, r, err) { |
| 287 | return |
| 288 | } |
| 289 | raw := map[string]json.RawMessage{} |
| 290 | if err := readJSON(r, &raw); err != nil { |
| 291 | s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) |
| 292 | return |
| 293 | } |
| 294 | h, err := s.opPatchWebhook(r.Context(), apiUser(r), kind, scopeID, id, raw) |
| 295 | if !s.apiOK(w, r, err) { |
| 296 | return |
| 297 | } |
| 298 | writeJSON(w, http.StatusOK, hookJSON(h)) |
| 299 | } |
| 300 | |
| 301 | func (s *Server) apiCopyHook(w http.ResponseWriter, r *http.Request, kind string, scopeID int64) { |
| 302 | id, err := hookID(r) |
| 303 | if !s.apiOK(w, r, err) { |
| 304 | return |
| 305 | } |
| 306 | var t CopyTarget |
| 307 | if err := readJSON(r, &t); err != nil { |
| 308 | s.writeAPIErr(w, r, fail(400, i18n.E("err.json"))) |
| 309 | return |
| 310 | } |
| 311 | res, err := s.opCopyWebhook(r.Context(), apiUser(r), kind, scopeID, id, t) |
| 312 | if !s.apiOK(w, r, err) { |
| 313 | return |
| 314 | } |
| 315 | out := hookJSON(res.Hook) |
| 316 | out["scope"] = res.Hook.ScopeKind |
| 317 | out["copied_secrets"] = hookNames(res.CopiedSecrets) |
| 318 | out["missing_secrets"] = hookNames(res.MissingSecrets) |
| 319 | writeJSON(w, http.StatusCreated, out) |
| 320 | } |
| 321 | |
| 322 | func hookNames(in []string) []string { |
| 323 | if in == nil { |
| 324 | return []string{} |
| 325 | } |
| 326 | return in |
| 327 | } |
| 328 | |
| 329 | func (s *Server) apiPatchGroupHook(w http.ResponseWriter, r *http.Request) { |
| 330 | g, ok := s.apiGroup(w, r, access.RoleMaintainer) |
| 331 | if !ok { |
| 332 | return |
| 333 | } |
| 334 | s.apiPatchHook(w, r, "group", g.ID) |
| 335 | } |
| 336 | |
| 337 | func (s *Server) apiPatchProjectHook(w http.ResponseWriter, r *http.Request) { |
| 338 | repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer) |
| 339 | if !ok { |
| 340 | return |
| 341 | } |
| 342 | s.apiPatchHook(w, r, "repo", repo.ID) |
| 343 | } |
| 344 | |
| 345 | func (s *Server) apiCopyGroupHook(w http.ResponseWriter, r *http.Request) { |
| 346 | g, ok := s.apiGroup(w, r, access.RoleMaintainer) |
| 347 | if !ok { |
| 348 | return |
| 349 | } |
| 350 | s.apiCopyHook(w, r, "group", g.ID) |
| 351 | } |
| 352 | |
| 353 | func (s *Server) apiCopyProjectHook(w http.ResponseWriter, r *http.Request) { |
| 354 | repo, _, ok := s.apiRepo(w, r, access.RoleMaintainer) |
| 355 | if !ok { |
| 356 | return |
| 357 | } |
| 358 | s.apiCopyHook(w, r, "repo", repo.ID) |
| 359 | } |
| 360 | |
| 361 | // --- UI --- |
| 362 | |
| 363 | // HookTarget is een keuze in het kopieervenster. |
| 364 | type HookTarget struct { |
| 365 | Value string |
| 366 | Label string |
| 367 | Group bool |
| 368 | } |
| 369 | |
| 370 | // hookTargets geeft projecten en groepen die deze gebruiker beheert. |
| 371 | func (s *Server) hookTargets(r *http.Request) []HookTarget { |
| 372 | p := s.who(r) |
| 373 | if !p.OK { |
| 374 | return nil |
| 375 | } |
| 376 | ctx := r.Context() |
| 377 | var out []HookTarget |
| 378 | groups, _ := s.Store.ListGroups(ctx, p.User.ID) |
| 379 | for _, g := range groups { |
| 380 | if s.manageScope(ctx, p.User, "group", g.ID) == nil { |
| 381 | out = append(out, HookTarget{Value: "group:" + g.Path, Label: g.Path, Group: true}) |
| 382 | } |
| 383 | } |
| 384 | ids, _ := s.Store.ListRepoIDs(ctx, p.User.ID) |
| 385 | var repos []HookTarget |
| 386 | for _, id := range ids { |
| 387 | if s.manageScope(ctx, p.User, "repo", id) != nil { |
| 388 | continue |
| 389 | } |
| 390 | repo, err := s.Store.RepoByID(ctx, id) |
| 391 | if err != nil { |
| 392 | continue |
| 393 | } |
| 394 | repos = append(repos, HookTarget{Value: "project:" + repo.FullPath(), Label: repo.FullPath()}) |
| 395 | } |
| 396 | sort.Slice(repos, func(i, j int) bool { return repos[i].Label < repos[j].Label }) |
| 397 | return append(out, repos...) |
| 398 | } |
| 399 | |
| 400 | func (s *Server) repoWebhookCopy(w http.ResponseWriter, r *http.Request) { s.webhookCopy(w, r, "repo") } |
| 401 | func (s *Server) groupWebhookCopy(w http.ResponseWriter, r *http.Request) { |
| 402 | s.webhookCopy(w, r, "group") |
| 403 | } |
| 404 | |
| 405 | func (s *Server) webhookCopy(w http.ResponseWriter, r *http.Request, kind string) { |
| 406 | scopeID, back, ok := s.adminScope(w, r, kind) |
| 407 | if !ok || !s.csrfOK(w, r) { |
| 408 | return |
| 409 | } |
| 410 | back = strings.Split(back, "?")[0] + scopeTab(kind, "webhooks") |
| 411 | if kind == "group" { |
| 412 | back += "#webhooks" |
| 413 | } |
| 414 | id, _ := strconv.ParseInt(r.FormValue("id"), 10, 64) |
| 415 | typ, target, _ := strings.Cut(r.FormValue("target"), ":") |
| 416 | res, err := s.opCopyWebhook(r.Context(), s.who(r).User, kind, scopeID, id, CopyTarget{Type: typ, Target: target, Name: r.FormValue("name")}) |
| 417 | if err != nil { |
| 418 | s.redirect(w, r, back, "", s.trErr(r, err)) |
| 419 | return |
| 420 | } |
| 421 | msg := s.tr(r, "flash.webhookCopied", target) |
| 422 | if len(res.MissingSecrets) > 0 { |
| 423 | msg += " " + s.tr(r, "wh.copyMissing", strings.Join(res.MissingSecrets, ", ")) |
| 424 | } |
| 425 | s.redirect(w, r, back, msg, "") |
| 426 | } |