BlueGit

timfa bluegit

Merge branch 'stage' into 'master'

timfa

Authored 2026-10-26 · 3 weeks ago

Hash
01e1d904818a5f7277356acac0e5db5487a83df3
Pipeline
Passed
10 files changed +797 −1
internal/i18n/catalog_whcopy.go added +52 −0
@@ -0,0 +1,52 @@
1 package i18n
2
3 func init() {
4 addCatalog(en, map[string]string{
5 "wh.copy": "Copy to…",
6 "wh.copyTitle": "Copy webhook",
7 "wh.copyTarget": "Target project or group",
8 "wh.copyName": "Name of the copy",
9 "wh.copyTip": "Copies this webhook with its settings. Secrets it uses are copied encrypted on the server when the target cannot see them yet; their values are never shown.",
10 "wh.copyNameTip": "Leave empty to keep the current name.",
11 "wh.copyGroups": "Groups",
12 "wh.copyProjects": "Projects",
13 "wh.copyMissing": "These secrets were not found and still need to be added in the target: %s.",
14 "flash.webhookCopied": "Webhook copied to %s.",
15 })
16 addCatalog(nl, map[string]string{
17 "wh.copy": "Kopiëren naar…",
18 "wh.copyTitle": "Webhook kopiëren",
19 "wh.copyTarget": "Doelproject of -groep",
20 "wh.copyName": "Naam van de kopie",
21 "wh.copyTip": "Kopieert deze webhook met alle instellingen. Geheimen die hij gebruikt worden versleuteld op de server meegekopieerd als het doel ze nog niet ziet; de waarden worden nooit getoond.",
22 "wh.copyNameTip": "Leeg laten om de huidige naam te houden.",
23 "wh.copyGroups": "Groepen",
24 "wh.copyProjects": "Projecten",
25 "wh.copyMissing": "Deze geheimen zijn niet gevonden en moeten nog in het doel worden toegevoegd: %s.",
26 "flash.webhookCopied": "Webhook gekopieerd naar %s.",
27 })
28 addCatalog(de, map[string]string{
29 "wh.copy": "Kopieren nach…",
30 "wh.copyTitle": "Webhook kopieren",
31 "wh.copyTarget": "Zielprojekt oder -gruppe",
32 "wh.copyName": "Name der Kopie",
33 "wh.copyTip": "Kopiert diesen Webhook mit allen Einstellungen. Verwendete Geheimnisse werden verschlüsselt auf dem Server mitkopiert, wenn das Ziel sie noch nicht sieht; die Werte werden nie angezeigt.",
34 "wh.copyNameTip": "Leer lassen, um den aktuellen Namen zu behalten.",
35 "wh.copyGroups": "Gruppen",
36 "wh.copyProjects": "Projekte",
37 "wh.copyMissing": "Diese Geheimnisse wurden nicht gefunden und müssen im Ziel noch angelegt werden: %s.",
38 "flash.webhookCopied": "Webhook nach %s kopiert.",
39 })
40 addCatalog(fr, map[string]string{
41 "wh.copy": "Copier vers…",
42 "wh.copyTitle": "Copier le webhook",
43 "wh.copyTarget": "Projet ou groupe cible",
44 "wh.copyName": "Nom de la copie",
45 "wh.copyTip": "Copie ce webhook avec tous ses réglages. Les secrets qu'il utilise sont copiés chiffrés sur le serveur si la cible ne les voit pas encore ; leurs valeurs ne sont jamais affichées.",
46 "wh.copyNameTip": "Laisser vide pour garder le nom actuel.",
47 "wh.copyGroups": "Groupes",
48 "wh.copyProjects": "Projets",
49 "wh.copyMissing": "Ces secrets sont introuvables et doivent encore être ajoutés dans la cible : %s.",
50 "flash.webhookCopied": "Webhook copié vers %s.",
51 })
52 }
@@ -0,0 +1,52 @@
1package i18n
2
3func init() {
4 addCatalog(en, map[string]string{
5 "wh.copy": "Copy to…",
6 "wh.copyTitle": "Copy webhook",
7 "wh.copyTarget": "Target project or group",
8 "wh.copyName": "Name of the copy",
9 "wh.copyTip": "Copies this webhook with its settings. Secrets it uses are copied encrypted on the server when the target cannot see them yet; their values are never shown.",
10 "wh.copyNameTip": "Leave empty to keep the current name.",
11 "wh.copyGroups": "Groups",
12 "wh.copyProjects": "Projects",
13 "wh.copyMissing": "These secrets were not found and still need to be added in the target: %s.",
14 "flash.webhookCopied": "Webhook copied to %s.",
15 })
16 addCatalog(nl, map[string]string{
17 "wh.copy": "Kopiëren naar…",
18 "wh.copyTitle": "Webhook kopiëren",
19 "wh.copyTarget": "Doelproject of -groep",
20 "wh.copyName": "Naam van de kopie",
21 "wh.copyTip": "Kopieert deze webhook met alle instellingen. Geheimen die hij gebruikt worden versleuteld op de server meegekopieerd als het doel ze nog niet ziet; de waarden worden nooit getoond.",
22 "wh.copyNameTip": "Leeg laten om de huidige naam te houden.",
23 "wh.copyGroups": "Groepen",
24 "wh.copyProjects": "Projecten",
25 "wh.copyMissing": "Deze geheimen zijn niet gevonden en moeten nog in het doel worden toegevoegd: %s.",
26 "flash.webhookCopied": "Webhook gekopieerd naar %s.",
27 })
28 addCatalog(de, map[string]string{
29 "wh.copy": "Kopieren nach…",
30 "wh.copyTitle": "Webhook kopieren",
31 "wh.copyTarget": "Zielprojekt oder -gruppe",
32 "wh.copyName": "Name der Kopie",
33 "wh.copyTip": "Kopiert diesen Webhook mit allen Einstellungen. Verwendete Geheimnisse werden verschlüsselt auf dem Server mitkopiert, wenn das Ziel sie noch nicht sieht; die Werte werden nie angezeigt.",
34 "wh.copyNameTip": "Leer lassen, um den aktuellen Namen zu behalten.",
35 "wh.copyGroups": "Gruppen",
36 "wh.copyProjects": "Projekte",
37 "wh.copyMissing": "Diese Geheimnisse wurden nicht gefunden und müssen im Ziel noch angelegt werden: %s.",
38 "flash.webhookCopied": "Webhook nach %s kopiert.",
39 })
40 addCatalog(fr, map[string]string{
41 "wh.copy": "Copier vers…",
42 "wh.copyTitle": "Copier le webhook",
43 "wh.copyTarget": "Projet ou groupe cible",
44 "wh.copyName": "Nom de la copie",
45 "wh.copyTip": "Copie ce webhook avec tous ses réglages. Les secrets qu'il utilise sont copiés chiffrés sur le serveur si la cible ne les voit pas encore ; leurs valeurs ne sont jamais affichées.",
46 "wh.copyNameTip": "Laisser vide pour garder le nom actuel.",
47 "wh.copyGroups": "Groupes",
48 "wh.copyProjects": "Projets",
49 "wh.copyMissing": "Ces secrets sont introuvables et doivent encore être ajoutés dans la cible : %s.",
50 "flash.webhookCopied": "Webhook copié vers %s.",
51 })
52}
internal/server/api_openapi.go +48 −1
@@ -131,6 +131,12 @@ func apiBinds() []apiBind {
131 131 {path: "/groups/{path}/webhooks", method: "POST", code: "201", body: "WebhookCreate", resp: "Webhook"},
132 132 {path: "/projects/{owner}/{repo}/webhooks", method: "GET", code: "200", resp: "Webhook", array: true},
133 133 {path: "/projects/{owner}/{repo}/webhooks", method: "POST", code: "201", body: "WebhookCreate", resp: "Webhook"},
134 {path: "/groups/{path}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
135 {path: "/groups/{path}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
136 {path: "/groups/{path}/webhooks/{id}/copy", method: "POST", code: "201", body: "WebhookCopy", resp: "WebhookCopyResult"},
137 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
138 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
139 {path: "/projects/{owner}/{repo}/webhooks/{id}/copy", method: "POST", code: "201", body: "WebhookCopy", resp: "WebhookCopyResult"},
134 140 }
135 141 }
136 142
@@ -343,7 +349,7 @@ func apiSchemas() map[string]any {
343 349 "avatar": str("Avatar URL."),
344 350 "icon": str("Icon URL or emoji."),
345 351 "alias": str("Alias."),
346 "token": str("Token. Stored as a secret and not returned."),
352 "token": str("Name of the secret that holds the token. The value is never returned."),
347 353 "chat": str("Chat id."),
348 354 "server": str("Server URL."),
349 355 "topic": str("Topic."),
@@ -354,6 +360,47 @@ func apiSchemas() map[string]any {
354 360 "headers": str("Extra headers."),
355 361 "body": str("Body template."),
356 362 }),
363 "WebhookUpdate": obj("Change a webhook. Omitted fields keep the stored value. An empty or omitted token keeps the stored secret reference; secret values are never returned.", map[string]any{
364 "name": str("Display name."),
365 "preset": str("Preset name."),
366 "branch_filter": str("Branch filter."),
367 "events": strArr("Events, see the list on the webhook schema."),
368 "active": boolean("Enable or disable the hook."),
369 "url": str("URL template."),
370 "username": str("Username for the preset."),
371 "avatar": str("Avatar URL."),
372 "icon": str("Icon URL or emoji."),
373 "alias": str("Alias."),
374 "token": str("Name of the secret that holds the token. Empty keeps the current one."),
375 "chat": str("Chat id."),
376 "server": str("Server URL."),
377 "topic": str("Topic."),
378 "homeserver": str("Matrix homeserver."),
379 "room": str("Matrix room."),
380 "method": str("HTTP method."),
381 "content_type": str("Content type."),
382 "headers": str("Extra headers. Empty keeps the current headers."),
383 "body": str("Body template."),
384 }),
385 "WebhookCopy": obj("Copy a webhook to a project or group where you are maintainer. Secrets the hook references and the target cannot already see are copied encrypted on the server; their values never reach the client.", map[string]any{
386 "target_type": str("project or group."),
387 "target": str("Target path: owner/project or group path."),
388 "name": str("Optional new name. Default keeps the name."),
389 "events": strArr("Optional event filter. Default keeps the events."),
390 }),
391 "WebhookCopyResult": obj("The new webhook plus the names (never values) of copied secrets.", map[string]any{
392 "id": integer("New webhook id."),
393 "name": str("Display name."),
394 "preset": str("Preset name."),
395 "url": str("URL template."),
396 "method": str("HTTP method."),
397 "events": strArr("Events."),
398 "branch_filter": str("Branch filter."),
399 "active": boolean("Hook is enabled."),
400 "scope": str("repo or group."),
401 "copied_secrets": strArr("Names of secrets copied to the target."),
402 "missing_secrets": strArr("Referenced secret names found nowhere; add them in the target."),
403 }),
357 404 }
358 405 }
359 406
@@ -131,6 +131,12 @@ func apiBinds() []apiBind {
131 {path: "/groups/{path}/webhooks", method: "POST", code: "201", body: "WebhookCreate", resp: "Webhook"},
131 {path: "/groups/{path}/webhooks", method: "POST", code: "201", body: "WebhookCreate", resp: "Webhook"},
132 {path: "/projects/{owner}/{repo}/webhooks", method: "GET", code: "200", resp: "Webhook", array: true},
132 {path: "/projects/{owner}/{repo}/webhooks", method: "GET", code: "200", resp: "Webhook", array: true},
133 {path: "/projects/{owner}/{repo}/webhooks", method: "POST", code: "201", body: "WebhookCreate", resp: "Webhook"},
133 {path: "/projects/{owner}/{repo}/webhooks", method: "POST", code: "201", body: "WebhookCreate", resp: "Webhook"},
134 {path: "/groups/{path}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
135 {path: "/groups/{path}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
136 {path: "/groups/{path}/webhooks/{id}/copy", method: "POST", code: "201", body: "WebhookCopy", resp: "WebhookCopyResult"},
137 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
138 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
139 {path: "/projects/{owner}/{repo}/webhooks/{id}/copy", method: "POST", code: "201", body: "WebhookCopy", resp: "WebhookCopyResult"},
134 }
140 }
135}
141}
136
142
@@ -343,7 +349,7 @@ func apiSchemas() map[string]any {
343 "avatar": str("Avatar URL."),
349 "avatar": str("Avatar URL."),
344 "icon": str("Icon URL or emoji."),
350 "icon": str("Icon URL or emoji."),
345 "alias": str("Alias."),
351 "alias": str("Alias."),
346 "token": str("Token. Stored as a secret and not returned."),
352 "token": str("Name of the secret that holds the token. The value is never returned."),
347 "chat": str("Chat id."),
353 "chat": str("Chat id."),
348 "server": str("Server URL."),
354 "server": str("Server URL."),
349 "topic": str("Topic."),
355 "topic": str("Topic."),
@@ -354,6 +360,47 @@ func apiSchemas() map[string]any {
354 "headers": str("Extra headers."),
360 "headers": str("Extra headers."),
355 "body": str("Body template."),
361 "body": str("Body template."),
356 }),
362 }),
363 "WebhookUpdate": obj("Change a webhook. Omitted fields keep the stored value. An empty or omitted token keeps the stored secret reference; secret values are never returned.", map[string]any{
364 "name": str("Display name."),
365 "preset": str("Preset name."),
366 "branch_filter": str("Branch filter."),
367 "events": strArr("Events, see the list on the webhook schema."),
368 "active": boolean("Enable or disable the hook."),
369 "url": str("URL template."),
370 "username": str("Username for the preset."),
371 "avatar": str("Avatar URL."),
372 "icon": str("Icon URL or emoji."),
373 "alias": str("Alias."),
374 "token": str("Name of the secret that holds the token. Empty keeps the current one."),
375 "chat": str("Chat id."),
376 "server": str("Server URL."),
377 "topic": str("Topic."),
378 "homeserver": str("Matrix homeserver."),
379 "room": str("Matrix room."),
380 "method": str("HTTP method."),
381 "content_type": str("Content type."),
382 "headers": str("Extra headers. Empty keeps the current headers."),
383 "body": str("Body template."),
384 }),
385 "WebhookCopy": obj("Copy a webhook to a project or group where you are maintainer. Secrets the hook references and the target cannot already see are copied encrypted on the server; their values never reach the client.", map[string]any{
386 "target_type": str("project or group."),
387 "target": str("Target path: owner/project or group path."),
388 "name": str("Optional new name. Default keeps the name."),
389 "events": strArr("Optional event filter. Default keeps the events."),
390 }),
391 "WebhookCopyResult": obj("The new webhook plus the names (never values) of copied secrets.", map[string]any{
392 "id": integer("New webhook id."),
393 "name": str("Display name."),
394 "preset": str("Preset name."),
395 "url": str("URL template."),
396 "method": str("HTTP method."),
397 "events": strArr("Events."),
398 "branch_filter": str("Branch filter."),
399 "active": boolean("Hook is enabled."),
400 "scope": str("repo or group."),
401 "copied_secrets": strArr("Names of secrets copied to the target."),
402 "missing_secrets": strArr("Referenced secret names found nowhere; add them in the target."),
403 }),
357 }
404 }
358}
405}
359
406
internal/server/api_routes.go +4 −0
@@ -75,6 +75,8 @@ var apiCatalog = []apiRoute{
75 75 {http.MethodGet, "/api/v1/groups/{path}/webhooks", access.ScopeRead, authUser, "List group webhooks", (*Server).apiGroupHooks},
76 76 {http.MethodPost, "/api/v1/groups/{path}/webhooks", access.ScopeWrite, authUser, "Create group webhook", (*Server).apiGroupHooks},
77 77 {http.MethodDelete, "/api/v1/groups/{path}/webhooks/{id}", access.ScopeWrite, authUser, "Delete group webhook", (*Server).apiDeleteGroupHook},
78 {http.MethodPatch, "/api/v1/groups/{path}/webhooks/{id}", access.ScopeWrite, authUser, "Update group webhook. Omitted fields and an empty token keep the stored value.", (*Server).apiPatchGroupHook},
79 {http.MethodPost, "/api/v1/groups/{path}/webhooks/{id}/copy", access.ScopeWrite, authUser, "Copy group webhook to a project or group, secrets stay server-side", (*Server).apiCopyGroupHook},
78 80 {http.MethodGet, "/api/v1/groups/{path}/approvals", access.ScopeRead, authUser, "Get group approvals", (*Server).apiGroupApproval},
79 81 {http.MethodPut, "/api/v1/groups/{path}/approvals", access.ScopeWrite, authUser, "Save group approvals", (*Server).apiGroupApproval},
80 82 {http.MethodGet, "/api/v1/groups/{path}/logo", access.ScopeRead, authUser, "Group logo", (*Server).apiGroupLogo},
@@ -97,6 +99,8 @@ var apiCatalog = []apiRoute{
97 99 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/webhooks", access.ScopeRead, authUser, "List project webhooks", (*Server).apiProjectHooks},
98 100 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/webhooks", access.ScopeWrite, authUser, "Create project webhook", (*Server).apiProjectHooks},
99 101 {http.MethodDelete, "/api/v1/projects/{owner}/{repo}/webhooks/{id}", access.ScopeWrite, authUser, "Delete project webhook", (*Server).apiDeleteProjectHook},
102 {http.MethodPatch, "/api/v1/projects/{owner}/{repo}/webhooks/{id}", access.ScopeWrite, authUser, "Update project webhook. Omitted fields and an empty token keep the stored value.", (*Server).apiPatchProjectHook},
103 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/webhooks/{id}/copy", access.ScopeWrite, authUser, "Copy project webhook to a project or group, secrets stay server-side", (*Server).apiCopyProjectHook},
100 104 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/approvals", access.ScopeRead, authUser, "Get project approvals", (*Server).apiProjectApproval},
101 105 {http.MethodPut, "/api/v1/projects/{owner}/{repo}/approvals", access.ScopeWrite, authUser, "Save project approvals", (*Server).apiProjectApproval},
102 106 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeRead, authUser, "List protected branches", (*Server).apiProtectBranches},
@@ -75,6 +75,8 @@ var apiCatalog = []apiRoute{
75 {http.MethodGet, "/api/v1/groups/{path}/webhooks", access.ScopeRead, authUser, "List group webhooks", (*Server).apiGroupHooks},
75 {http.MethodGet, "/api/v1/groups/{path}/webhooks", access.ScopeRead, authUser, "List group webhooks", (*Server).apiGroupHooks},
76 {http.MethodPost, "/api/v1/groups/{path}/webhooks", access.ScopeWrite, authUser, "Create group webhook", (*Server).apiGroupHooks},
76 {http.MethodPost, "/api/v1/groups/{path}/webhooks", access.ScopeWrite, authUser, "Create group webhook", (*Server).apiGroupHooks},
77 {http.MethodDelete, "/api/v1/groups/{path}/webhooks/{id}", access.ScopeWrite, authUser, "Delete group webhook", (*Server).apiDeleteGroupHook},
77 {http.MethodDelete, "/api/v1/groups/{path}/webhooks/{id}", access.ScopeWrite, authUser, "Delete group webhook", (*Server).apiDeleteGroupHook},
78 {http.MethodPatch, "/api/v1/groups/{path}/webhooks/{id}", access.ScopeWrite, authUser, "Update group webhook. Omitted fields and an empty token keep the stored value.", (*Server).apiPatchGroupHook},
79 {http.MethodPost, "/api/v1/groups/{path}/webhooks/{id}/copy", access.ScopeWrite, authUser, "Copy group webhook to a project or group, secrets stay server-side", (*Server).apiCopyGroupHook},
78 {http.MethodGet, "/api/v1/groups/{path}/approvals", access.ScopeRead, authUser, "Get group approvals", (*Server).apiGroupApproval},
80 {http.MethodGet, "/api/v1/groups/{path}/approvals", access.ScopeRead, authUser, "Get group approvals", (*Server).apiGroupApproval},
79 {http.MethodPut, "/api/v1/groups/{path}/approvals", access.ScopeWrite, authUser, "Save group approvals", (*Server).apiGroupApproval},
81 {http.MethodPut, "/api/v1/groups/{path}/approvals", access.ScopeWrite, authUser, "Save group approvals", (*Server).apiGroupApproval},
80 {http.MethodGet, "/api/v1/groups/{path}/logo", access.ScopeRead, authUser, "Group logo", (*Server).apiGroupLogo},
82 {http.MethodGet, "/api/v1/groups/{path}/logo", access.ScopeRead, authUser, "Group logo", (*Server).apiGroupLogo},
@@ -97,6 +99,8 @@ var apiCatalog = []apiRoute{
97 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/webhooks", access.ScopeRead, authUser, "List project webhooks", (*Server).apiProjectHooks},
99 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/webhooks", access.ScopeRead, authUser, "List project webhooks", (*Server).apiProjectHooks},
98 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/webhooks", access.ScopeWrite, authUser, "Create project webhook", (*Server).apiProjectHooks},
100 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/webhooks", access.ScopeWrite, authUser, "Create project webhook", (*Server).apiProjectHooks},
99 {http.MethodDelete, "/api/v1/projects/{owner}/{repo}/webhooks/{id}", access.ScopeWrite, authUser, "Delete project webhook", (*Server).apiDeleteProjectHook},
101 {http.MethodDelete, "/api/v1/projects/{owner}/{repo}/webhooks/{id}", access.ScopeWrite, authUser, "Delete project webhook", (*Server).apiDeleteProjectHook},
102 {http.MethodPatch, "/api/v1/projects/{owner}/{repo}/webhooks/{id}", access.ScopeWrite, authUser, "Update project webhook. Omitted fields and an empty token keep the stored value.", (*Server).apiPatchProjectHook},
103 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/webhooks/{id}/copy", access.ScopeWrite, authUser, "Copy project webhook to a project or group, secrets stay server-side", (*Server).apiCopyProjectHook},
100 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/approvals", access.ScopeRead, authUser, "Get project approvals", (*Server).apiProjectApproval},
104 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/approvals", access.ScopeRead, authUser, "Get project approvals", (*Server).apiProjectApproval},
101 {http.MethodPut, "/api/v1/projects/{owner}/{repo}/approvals", access.ScopeWrite, authUser, "Save project approvals", (*Server).apiProjectApproval},
105 {http.MethodPut, "/api/v1/projects/{owner}/{repo}/approvals", access.ScopeWrite, authUser, "Save project approvals", (*Server).apiProjectApproval},
102 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeRead, authUser, "List protected branches", (*Server).apiProtectBranches},
106 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeRead, authUser, "List protected branches", (*Server).apiProtectBranches},
internal/server/server.go +3 −0
@@ -138,6 +138,7 @@ func (s *Server) Handler() http.Handler {
138 138 mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
139 139 mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
140 140 mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)
141 mux.HandleFunc("POST /groups/{path}/webhooks/copy", s.groupWebhookCopy)
141 142
142 143 mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
143 144 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
@@ -250,6 +251,7 @@ func (s *Server) Handler() http.Handler {
250 251 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
251 252 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
252 253 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
254 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/copy", s.repoWebhookCopy)
253 255 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
254 256
255 257 return s.realIP(s.withSession(s.secure(s.gate(mux))))
@@ -654,6 +656,7 @@ type View struct {
654 656 Secrets []store.SecretMeta
655 657 HookSecrets []SecretChoice
656 658 Hooks []HookView
659 HookTargets []HookTarget
657 660 HookEdit HookDraft
658 661 Patterns []string
659 662 TagPatterns []string
@@ -138,6 +138,7 @@ func (s *Server) Handler() http.Handler {
138 mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
138 mux.HandleFunc("POST /groups/{path}/secrets/delete", s.groupSecretDelete)
139 mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
139 mux.HandleFunc("POST /groups/{path}/webhooks", s.groupWebhook)
140 mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)
140 mux.HandleFunc("POST /groups/{path}/webhooks/delete", s.groupWebhookDelete)
141 mux.HandleFunc("POST /groups/{path}/webhooks/copy", s.groupWebhookCopy)
141
142
142 mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
143 mux.HandleFunc("GET /{owner}/{repo}/info/refs", s.gitHTTP)
143 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
144 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
@@ -250,6 +251,7 @@ func (s *Server) Handler() http.Handler {
250 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
251 mux.HandleFunc("POST /{owner}/{repo}/-/secrets/delete", s.repoSecretDelete)
251 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
252 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks", s.repoWebhook)
252 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
253 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/delete", s.repoWebhookDelete)
254 mux.HandleFunc("POST /{owner}/{repo}/-/webhooks/copy", s.repoWebhookCopy)
253 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
255 mux.HandleFunc("POST /{owner}/{repo}/-/delete", s.deleteRepo)
254
256
255 return s.realIP(s.withSession(s.secure(s.gate(mux))))
257 return s.realIP(s.withSession(s.secure(s.gate(mux))))
@@ -654,6 +656,7 @@ type View struct {
654 Secrets []store.SecretMeta
656 Secrets []store.SecretMeta
655 HookSecrets []SecretChoice
657 HookSecrets []SecretChoice
656 Hooks []HookView
658 Hooks []HookView
659 HookTargets []HookTarget
657 HookEdit HookDraft
660 HookEdit HookDraft
658 Patterns []string
661 Patterns []string
659 TagPatterns []string
662 TagPatterns []string
internal/server/settings_handlers.go +2 −0
@@ -37,6 +37,7 @@ func (s *Server) settings(w http.ResponseWriter, r *http.Request) {
37 37 v.Patterns, _ = s.Store.ProtectedPatterns(r.Context(), repo.ID)
38 38 v.TagPatterns, _ = s.Store.ProtectedTagPatterns(r.Context(), repo.ID)
39 39 v.Hooks = s.hookViews(r, "repo", repo.ID)
40 v.HookTargets = s.hookTargets(r)
40 41 s.fillHookEdit(r, &v, "repo", repo.ID)
41 42 s.fillApproval(r, &v, repo)
42 43 }
@@ -635,6 +636,7 @@ func (s *Server) groupPage(w http.ResponseWriter, r *http.Request) {
635 636 v.Secrets, _ = s.Store.ListSecrets(r.Context(), "group", g.ID)
636 637 v.HookSecrets = s.groupSecretChoices(r, g)
637 638 v.Hooks = s.hookViews(r, "group", g.ID)
639 v.HookTargets = s.hookTargets(r)
638 640 s.fillHookEdit(r, &v, "group", g.ID)
639 641 s.fillGroupApproval(r, &v, g)
640 642 s.fillGroupRunners(w, r, &v, g)
@@ -37,6 +37,7 @@ func (s *Server) settings(w http.ResponseWriter, r *http.Request) {
37 v.Patterns, _ = s.Store.ProtectedPatterns(r.Context(), repo.ID)
37 v.Patterns, _ = s.Store.ProtectedPatterns(r.Context(), repo.ID)
38 v.TagPatterns, _ = s.Store.ProtectedTagPatterns(r.Context(), repo.ID)
38 v.TagPatterns, _ = s.Store.ProtectedTagPatterns(r.Context(), repo.ID)
39 v.Hooks = s.hookViews(r, "repo", repo.ID)
39 v.Hooks = s.hookViews(r, "repo", repo.ID)
40 v.HookTargets = s.hookTargets(r)
40 s.fillHookEdit(r, &v, "repo", repo.ID)
41 s.fillHookEdit(r, &v, "repo", repo.ID)
41 s.fillApproval(r, &v, repo)
42 s.fillApproval(r, &v, repo)
42 }
43 }
@@ -635,6 +636,7 @@ func (s *Server) groupPage(w http.ResponseWriter, r *http.Request) {
635 v.Secrets, _ = s.Store.ListSecrets(r.Context(), "group", g.ID)
636 v.Secrets, _ = s.Store.ListSecrets(r.Context(), "group", g.ID)
636 v.HookSecrets = s.groupSecretChoices(r, g)
637 v.HookSecrets = s.groupSecretChoices(r, g)
637 v.Hooks = s.hookViews(r, "group", g.ID)
638 v.Hooks = s.hookViews(r, "group", g.ID)
639 v.HookTargets = s.hookTargets(r)
638 s.fillHookEdit(r, &v, "group", g.ID)
640 s.fillHookEdit(r, &v, "group", g.ID)
639 s.fillGroupApproval(r, &v, g)
641 s.fillGroupApproval(r, &v, g)
640 s.fillGroupRunners(w, r, &v, g)
642 s.fillGroupRunners(w, r, &v, g)
internal/server/static/hookcopy.js added +25 −0
@@ -0,0 +1,25 @@
1 // Kopieervenster voor webhooks (eigen modal, geen browser-popup).
2 (function () {
3 var dlg = document.querySelector("[data-hookcopy-dialog]");
4 if (!dlg) { return; }
5 var id = dlg.querySelector("[data-hookcopy-id]");
6 var name = dlg.querySelector("[data-hookcopy-name-input]");
7 document.querySelectorAll("[data-hookcopy-open]").forEach(function (b) {
8 b.addEventListener("click", function () {
9 id.value = b.getAttribute("data-hookcopy-open");
10 name.value = "";
11 name.placeholder = b.getAttribute("data-hookcopy-name") || "";
12 document.documentElement.classList.add("bgmodal-open");
13 if (dlg.showModal) { dlg.showModal(); } else { dlg.setAttribute("open", ""); }
14 var sel = dlg.querySelector("select");
15 if (sel) { sel.focus(); }
16 });
17 });
18 function close() {
19 document.documentElement.classList.remove("bgmodal-open");
20 if (dlg.open) { dlg.close(); }
21 }
22 dlg.querySelector("[data-hookcopy-cancel]").addEventListener("click", close);
23 dlg.addEventListener("close", function () { document.documentElement.classList.remove("bgmodal-open"); });
24 dlg.addEventListener("click", function (e) { if (e.target === dlg) { close(); } });
25 })();
@@ -0,0 +1,25 @@
1// Kopieervenster voor webhooks (eigen modal, geen browser-popup).
2(function () {
3 var dlg = document.querySelector("[data-hookcopy-dialog]");
4 if (!dlg) { return; }
5 var id = dlg.querySelector("[data-hookcopy-id]");
6 var name = dlg.querySelector("[data-hookcopy-name-input]");
7 document.querySelectorAll("[data-hookcopy-open]").forEach(function (b) {
8 b.addEventListener("click", function () {
9 id.value = b.getAttribute("data-hookcopy-open");
10 name.value = "";
11 name.placeholder = b.getAttribute("data-hookcopy-name") || "";
12 document.documentElement.classList.add("bgmodal-open");
13 if (dlg.showModal) { dlg.showModal(); } else { dlg.setAttribute("open", ""); }
14 var sel = dlg.querySelector("select");
15 if (sel) { sel.focus(); }
16 });
17 });
18 function close() {
19 document.documentElement.classList.remove("bgmodal-open");
20 if (dlg.open) { dlg.close(); }
21 }
22 dlg.querySelector("[data-hookcopy-cancel]").addEventListener("click", close);
23 dlg.addEventListener("close", function () { document.documentElement.classList.remove("bgmodal-open"); });
24 dlg.addEventListener("click", function (e) { if (e.target === dlg) { close(); } });
25})();
internal/server/templates/collab.html +22 −0
@@ -850,6 +850,7 @@
850 850 <input type="hidden" name="csrf" value="{{$.CSRF}}"><input type="hidden" name="id" value="{{.ID}}">
851 851 <button class="ghost tiny" type="submit">{{t "action.remove"}}</button>
852 852 </form>
853 {{if $.HookTargets}}<button type="button" class="ghost tiny" data-hookcopy-open="{{.ID}}" data-hookcopy-name="{{.Name}}" data-tip="{{t "wh.copyTip"}}">{{t "wh.copy"}}</button>{{end}}
853 854 </div>
854 855 </td>
855 856 </tr>
@@ -858,6 +859,27 @@
858 859 </tbody>
859 860 </table>
860 861 </div>
862 {{if .HookTargets}}
863 <dialog class="bgmodal" data-hookcopy-dialog aria-labelledby="hookcopy-title">
864 <form class="bgmodal-box" method="post" action="{{if .Repo}}/{{.Repo.FullPath}}/-/webhooks/copy{{else}}/groups/{{.Group.Path}}/webhooks/copy{{end}}">
865 <h2 id="hookcopy-title">{{t "wh.copyTitle"}}</h2>
866 <p class="muted">{{t "wh.copyTip"}}</p>
867 <input type="hidden" name="csrf" value="{{.CSRF}}"><input type="hidden" name="id" value="" data-hookcopy-id>
868 <label>{{t "wh.copyTarget"}}
869 <select name="target" required>
870 <optgroup label="{{t "wh.copyGroups"}}">{{range .HookTargets}}{{if .Group}}<option value="{{.Value}}">{{.Label}}</option>{{end}}{{end}}</optgroup>
871 <optgroup label="{{t "wh.copyProjects"}}">{{range .HookTargets}}{{if not .Group}}<option value="{{.Value}}">{{.Label}}</option>{{end}}{{end}}</optgroup>
872 </select>
873 </label>
874 <label data-tip="{{t "wh.copyNameTip"}}">{{t "wh.copyName"}} <input name="name" data-hookcopy-name-input></label>
875 <div class="bgmodal-acts">
876 <button type="button" class="ghost" data-hookcopy-cancel>{{t "action.cancel"}}</button>
877 <button type="submit">{{t "wh.copyTitle"}}</button>
878 </div>
879 </form>
880 </dialog>
881 <script src="/assets/hookcopy.js"></script>
882 {{end}}
861 883 {{end}}
862 884 </div>
863 885 {{end}}
@@ -850,6 +850,7 @@
850 <input type="hidden" name="csrf" value="{{$.CSRF}}"><input type="hidden" name="id" value="{{.ID}}">
850 <input type="hidden" name="csrf" value="{{$.CSRF}}"><input type="hidden" name="id" value="{{.ID}}">
851 <button class="ghost tiny" type="submit">{{t "action.remove"}}</button>
851 <button class="ghost tiny" type="submit">{{t "action.remove"}}</button>
852 </form>
852 </form>
853 {{if $.HookTargets}}<button type="button" class="ghost tiny" data-hookcopy-open="{{.ID}}" data-hookcopy-name="{{.Name}}" data-tip="{{t "wh.copyTip"}}">{{t "wh.copy"}}</button>{{end}}
853 </div>
854 </div>
854 </td>
855 </td>
855 </tr>
856 </tr>
@@ -858,6 +859,27 @@
858 </tbody>
859 </tbody>
859</table>
860</table>
860</div>
861</div>
862{{if .HookTargets}}
863<dialog class="bgmodal" data-hookcopy-dialog aria-labelledby="hookcopy-title">
864 <form class="bgmodal-box" method="post" action="{{if .Repo}}/{{.Repo.FullPath}}/-/webhooks/copy{{else}}/groups/{{.Group.Path}}/webhooks/copy{{end}}">
865 <h2 id="hookcopy-title">{{t "wh.copyTitle"}}</h2>
866 <p class="muted">{{t "wh.copyTip"}}</p>
867 <input type="hidden" name="csrf" value="{{.CSRF}}"><input type="hidden" name="id" value="" data-hookcopy-id>
868 <label>{{t "wh.copyTarget"}}
869 <select name="target" required>
870 <optgroup label="{{t "wh.copyGroups"}}">{{range .HookTargets}}{{if .Group}}<option value="{{.Value}}">{{.Label}}</option>{{end}}{{end}}</optgroup>
871 <optgroup label="{{t "wh.copyProjects"}}">{{range .HookTargets}}{{if not .Group}}<option value="{{.Value}}">{{.Label}}</option>{{end}}{{end}}</optgroup>
872 </select>
873 </label>
874 <label data-tip="{{t "wh.copyNameTip"}}">{{t "wh.copyName"}} <input name="name" data-hookcopy-name-input></label>
875 <div class="bgmodal-acts">
876 <button type="button" class="ghost" data-hookcopy-cancel>{{t "action.cancel"}}</button>
877 <button type="submit">{{t "wh.copyTitle"}}</button>
878 </div>
879 </form>
880</dialog>
881<script src="/assets/hookcopy.js"></script>
882{{end}}
861{{end}}
883{{end}}
862</div>
884</div>
863{{end}}
885{{end}}
internal/server/webhook_copy_test.go added +187 −0
@@ -0,0 +1,187 @@
1 package server
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "net/http"
8 "net/http/cookiejar"
9 "net/http/httptest"
10 "net/url"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "testing"
15 "time"
16
17 "gitlab.com/Timfa/bluegit/internal/auth"
18 "gitlab.com/Timfa/bluegit/internal/config"
19 "gitlab.com/Timfa/bluegit/internal/store"
20 )
21
22 func TestWebhookPatchCopyKeepsSecretsServerSide(t *testing.T) {
23 if _, err := exec.LookPath("git"); err != nil {
24 t.Skip("git ontbreekt")
25 }
26 storage := t.TempDir()
27 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
28 if err != nil {
29 t.Fatal(err)
30 }
31 t.Cleanup(func() { _ = st.Close() })
32 ctx := context.Background()
33 ada, err := st.UpsertUser(ctx, 1, "ada", "", false)
34 if err != nil {
35 t.Fatal(err)
36 }
37 dev, err := st.UpsertUser(ctx, 2, "dev", "", false)
38 if err != nil {
39 t.Fatal(err)
40 }
41 issue := func(u store.User) string {
42 plain, _, err := st.IssueToken(ctx, u.ID, store.TokenRequest{Name: u.Username, Scopes: "api", ExpiresAt: time.Time{}})
43 if err != nil {
44 t.Fatal(err)
45 }
46 return plain
47 }
48 adaTok, devTok := issue(ada), issue(dev)
49 cfg := config.Config{
50 BaseURL: "http://127.0.0.1:9", StoragePath: storage,
51 Auth: config.Auth{Mode: "dev", DevUser: "ada", DevAuthID: 1},
52 Git: config.Git{Binary: "git", DefaultBranch: "master"},
53 }
54 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "ada", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true", StateDir: t.TempDir()}
55 ts := httptest.NewServer(srv.Handler())
56 t.Cleanup(ts.Close)
57
58 const secretVal = "geheim-waarde-1234567890"
59 var all strings.Builder
60 call := func(method, path, token, body string) (int, string) {
61 t.Helper()
62 req, _ := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
63 if body != "" {
64 req.Header.Set("Content-Type", "application/json")
65 }
66 req.Header.Set("Authorization", "Bearer "+token)
67 res, err := http.DefaultClient.Do(req)
68 if err != nil {
69 t.Fatal(err)
70 }
71 out := read(t, res)
72 all.WriteString(out)
73 return res.StatusCode, out
74 }
75 want := func(code int, body string, label string, status int, contains string) {
76 t.Helper()
77 if code != status || (contains != "" && !strings.Contains(body, contains)) {
78 t.Fatalf("%s: status %d body %s", label, code, body)
79 }
80 }
81 for _, n := range []string{"Src", "Dst"} {
82 code, body := call(http.MethodPost, "/api/v1/projects", adaTok, `{"name":"`+n+`","visibility":"private"}`)
83 want(code, body, "project "+n, 201, "")
84 }
85 code, body := call(http.MethodPost, "/api/v1/groups", adaTok, `{"name":"Team"}`)
86 want(code, body, "groep", 201, `"path":"team"`)
87 src, _ := st.RepoByPath(ctx, "ada", "src")
88 dst, _ := st.RepoByPath(ctx, "ada", "dst")
89 team, _ := st.GroupByPath(ctx, "team")
90 if err := st.PutSecret(ctx, "repo", src.ID, "GROK_TOKEN", secretVal, false); err != nil {
91 t.Fatal(err)
92 }
93
94 code, body = call(http.MethodPost, "/api/v1/projects/ada/src/webhooks", adaTok,
95 `{"name":"Ada","preset":"custom","url":"https://example.test/hook","events":["push"],"headers":"Authorization: Bearer {{secret.GROK_TOKEN}}\nX-Missing: {{secret.NOPE}}"}`)
96 want(code, body, "maken", 201, `"id"`)
97 var made struct{ ID int64 }
98 _ = json.Unmarshal([]byte(body), &made)
99 base := fmt.Sprintf("/api/v1/projects/ada/src/webhooks/%d", made.ID)
100
101 code, body = call(http.MethodPatch, base, adaTok, `{"name":"Ada 2","token":"","events":["push","pipeline_success"]}`)
102 want(code, body, "patch", 200, `"name":"Ada 2"`)
103 h, err := st.Webhook(ctx, "repo", src.ID, made.ID)
104 if err != nil || !strings.Contains(h.Headers["Authorization"], "{{secret.GROK_TOKEN}}") || len(h.Events) != 2 {
105 t.Fatalf("patch verloor velden: %+v %v", h, err)
106 }
107 code, body = call(http.MethodPatch, base, adaTok, `{"active":false}`)
108 want(code, body, "uit", 200, `"active":false`)
109 code, body = call(http.MethodPatch, base, adaTok, `{"active":true}`)
110 want(code, body, "aan", 200, `"active":true`)
111 code, body = call(http.MethodPatch, base, devTok, `{"name":"x"}`)
112 if code != 403 && code != 404 {
113 t.Fatalf("dev mag niet patchen: %d %s", code, body)
114 }
115
116 code, body = call(http.MethodPost, base+"/copy", adaTok, `{"target_type":"project","target":"ada/dst","name":"Kopie"}`)
117 want(code, body, "kopie project", 201, `"copied_secrets":["GROK_TOKEN"]`)
118 want(code, body, "ontbrekend", 201, `"missing_secrets":["NOPE"]`)
119 vals, err := st.SecretValues(ctx, "repo", dst.ID, true)
120 if err != nil || vals["GROK_TOKEN"] != secretVal {
121 t.Fatalf("geheim niet server-side gekopieerd: %v", err)
122 }
123 used, err := srv.hookSecrets(ctx, "repo", dst.ID, true, dst)
124 if err != nil || used["GROK_TOKEN"] != secretVal {
125 t.Fatalf("kopie gebruikt het geheim niet: %v", err)
126 }
127 hooks, _ := st.ListWebhooks(ctx, "repo", dst.ID)
128 if len(hooks) != 1 || hooks[0].Name != "Kopie" || !strings.Contains(hooks[0].Headers["Authorization"], "{{secret.GROK_TOKEN}}") {
129 t.Fatalf("kopie klopt niet: %+v", hooks)
130 }
131 code, body = call(http.MethodPost, base+"/copy", adaTok, `{"target_type":"project","target":"ada/dst"}`)
132 want(code, body, "tweede kopie", 201, `"copied_secrets":[]`)
133 code, body = call(http.MethodPost, base+"/copy", adaTok, `{"target_type":"group","target":"team","events":["release_published"]}`)
134 want(code, body, "kopie groep", 201, `"scope":"group"`)
135 gv, _ := st.SecretValues(ctx, "group", team.ID, true)
136 if gv["GROK_TOKEN"] != secretVal {
137 t.Fatal("groepsgeheim ontbreekt")
138 }
139 code, body = call(http.MethodPost, base+"/copy", devTok, `{"target_type":"group","target":"team"}`)
140 if code != 403 && code != 404 {
141 t.Fatalf("dev mag niet kopiëren: %d %s", code, body)
142 }
143 code, body = call(http.MethodPost, base+"/copy", adaTok, `{"target_type":"project","target":"ada/bestaatniet"}`)
144 want(code, body, "onbekend doel", 404, "")
145 code, body = call(http.MethodGet, "/api/v1/projects/ada/dst/webhooks", adaTok, "")
146 want(code, body, "lijst", 200, "Kopie")
147 code, body = call(http.MethodDelete, fmt.Sprintf("/api/v1/projects/ada/dst/webhooks/%d", hooks[0].ID), adaTok, "")
148 want(code, body, "verwijderen", 204, "")
149 code, body = call(http.MethodGet, "/api/v1/openapi.json", "", "")
150 want(code, body, "openapi", 200, "/webhooks/{id}/copy")
151
152 jar, _ := cookiejar.New(nil)
153 client := &http.Client{Jar: jar}
154 res, err := client.Get(ts.URL + "/login")
155 if err != nil {
156 t.Fatal(err)
157 }
158 _ = read(t, res)
159 res, err = client.Get(ts.URL + "/ada/src/-/settings?tab=webhooks")
160 if err != nil {
161 t.Fatal(err)
162 }
163 page := read(t, res)
164 all.WriteString(page)
165 if !strings.Contains(page, "data-hookcopy-open") || !strings.Contains(page, `value="group:team"`) || !strings.Contains(page, `value="project:ada/dst"`) {
166 t.Fatalf("kopieerknop of doelen ontbreken")
167 }
168 res, err = client.PostForm(ts.URL+"/ada/src/-/webhooks/copy", url.Values{
169 "csrf": {csrfOf(t, page)}, "id": {fmt.Sprint(made.ID)}, "target": {"project:ada/dst"}, "name": {"Via UI"},
170 })
171 if err != nil {
172 t.Fatal(err)
173 }
174 all.WriteString(read(t, res))
175 hooks, _ = st.ListWebhooks(ctx, "repo", dst.ID)
176 found := false
177 for _, h := range hooks {
178 found = found || h.Name == "Via UI"
179 }
180 if !found {
181 t.Fatalf("UI-kopie ontbreekt: %+v", hooks)
182 }
183
184 if strings.Contains(all.String(), secretVal) {
185 t.Fatal("geheime waarde in een API-respons")
186 }
187 }
@@ -0,0 +1,187 @@
1package server
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "net/http"
8 "net/http/cookiejar"
9 "net/http/httptest"
10 "net/url"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "testing"
15 "time"
16
17 "gitlab.com/Timfa/bluegit/internal/auth"
18 "gitlab.com/Timfa/bluegit/internal/config"
19 "gitlab.com/Timfa/bluegit/internal/store"
20)
21
22func TestWebhookPatchCopyKeepsSecretsServerSide(t *testing.T) {
23 if _, err := exec.LookPath("git"); err != nil {
24 t.Skip("git ontbreekt")
25 }
26 storage := t.TempDir()
27 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
28 if err != nil {
29 t.Fatal(err)
30 }
31 t.Cleanup(func() { _ = st.Close() })
32 ctx := context.Background()
33 ada, err := st.UpsertUser(ctx, 1, "ada", "", false)
34 if err != nil {
35 t.Fatal(err)
36 }
37 dev, err := st.UpsertUser(ctx, 2, "dev", "", false)
38 if err != nil {
39 t.Fatal(err)
40 }
41 issue := func(u store.User) string {
42 plain, _, err := st.IssueToken(ctx, u.ID, store.TokenRequest{Name: u.Username, Scopes: "api", ExpiresAt: time.Time{}})
43 if err != nil {
44 t.Fatal(err)
45 }
46 return plain
47 }
48 adaTok, devTok := issue(ada), issue(dev)
49 cfg := config.Config{
50 BaseURL: "http://127.0.0.1:9", StoragePath: storage,
51 Auth: config.Auth{Mode: "dev", DevUser: "ada", DevAuthID: 1},
52 Git: config.Git{Binary: "git", DefaultBranch: "master"},
53 }
54 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "ada", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true", StateDir: t.TempDir()}
55 ts := httptest.NewServer(srv.Handler())
56 t.Cleanup(ts.Close)
57
58 const secretVal = "geheim-waarde-1234567890"
59 var all strings.Builder
60 call := func(method, path, token, body string) (int, string) {
61 t.Helper()
62 req, _ := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
63 if body != "" {
64 req.Header.Set("Content-Type", "application/json")
65 }
66 req.Header.Set("Authorization", "Bearer "+token)
67 res, err := http.DefaultClient.Do(req)
68 if err != nil {
69 t.Fatal(err)
70 }
71 out := read(t, res)
72 all.WriteString(out)
73 return res.StatusCode, out
74 }
75 want := func(code int, body string, label string, status int, contains string) {
76 t.Helper()
77 if code != status || (contains != "" && !strings.Contains(body, contains)) {
78 t.Fatalf("%s: status %d body %s", label, code, body)
79 }
80 }
81 for _, n := range []string{"Src", "Dst"} {
82 code, body := call(http.MethodPost, "/api/v1/projects", adaTok, `{"name":"`+n+`","visibility":"private"}`)
83 want(code, body, "project "+n, 201, "")
84 }
85 code, body := call(http.MethodPost, "/api/v1/groups", adaTok, `{"name":"Team"}`)
86 want(code, body, "groep", 201, `"path":"team"`)
87 src, _ := st.RepoByPath(ctx, "ada", "src")
88 dst, _ := st.RepoByPath(ctx, "ada", "dst")
89 team, _ := st.GroupByPath(ctx, "team")
90 if err := st.PutSecret(ctx, "repo", src.ID, "GROK_TOKEN", secretVal, false); err != nil {
91 t.Fatal(err)
92 }
93
94 code, body = call(http.MethodPost, "/api/v1/projects/ada/src/webhooks", adaTok,
95 `{"name":"Ada","preset":"custom","url":"https://example.test/hook","events":["push"],"headers":"Authorization: Bearer {{secret.GROK_TOKEN}}\nX-Missing: {{secret.NOPE}}"}`)
96 want(code, body, "maken", 201, `"id"`)
97 var made struct{ ID int64 }
98 _ = json.Unmarshal([]byte(body), &made)
99 base := fmt.Sprintf("/api/v1/projects/ada/src/webhooks/%d", made.ID)
100
101 code, body = call(http.MethodPatch, base, adaTok, `{"name":"Ada 2","token":"","events":["push","pipeline_success"]}`)
102 want(code, body, "patch", 200, `"name":"Ada 2"`)
103 h, err := st.Webhook(ctx, "repo", src.ID, made.ID)
104 if err != nil || !strings.Contains(h.Headers["Authorization"], "{{secret.GROK_TOKEN}}") || len(h.Events) != 2 {
105 t.Fatalf("patch verloor velden: %+v %v", h, err)
106 }
107 code, body = call(http.MethodPatch, base, adaTok, `{"active":false}`)
108 want(code, body, "uit", 200, `"active":false`)
109 code, body = call(http.MethodPatch, base, adaTok, `{"active":true}`)
110 want(code, body, "aan", 200, `"active":true`)
111 code, body = call(http.MethodPatch, base, devTok, `{"name":"x"}`)
112 if code != 403 && code != 404 {
113 t.Fatalf("dev mag niet patchen: %d %s", code, body)
114 }
115
116 code, body = call(http.MethodPost, base+"/copy", adaTok, `{"target_type":"project","target":"ada/dst","name":"Kopie"}`)
117 want(code, body, "kopie project", 201, `"copied_secrets":["GROK_TOKEN"]`)
118 want(code, body, "ontbrekend", 201, `"missing_secrets":["NOPE"]`)
119 vals, err := st.SecretValues(ctx, "repo", dst.ID, true)
120 if err != nil || vals["GROK_TOKEN"] != secretVal {
121 t.Fatalf("geheim niet server-side gekopieerd: %v", err)
122 }
123 used, err := srv.hookSecrets(ctx, "repo", dst.ID, true, dst)
124 if err != nil || used["GROK_TOKEN"] != secretVal {
125 t.Fatalf("kopie gebruikt het geheim niet: %v", err)
126 }
127 hooks, _ := st.ListWebhooks(ctx, "repo", dst.ID)
128 if len(hooks) != 1 || hooks[0].Name != "Kopie" || !strings.Contains(hooks[0].Headers["Authorization"], "{{secret.GROK_TOKEN}}") {
129 t.Fatalf("kopie klopt niet: %+v", hooks)
130 }
131 code, body = call(http.MethodPost, base+"/copy", adaTok, `{"target_type":"project","target":"ada/dst"}`)
132 want(code, body, "tweede kopie", 201, `"copied_secrets":[]`)
133 code, body = call(http.MethodPost, base+"/copy", adaTok, `{"target_type":"group","target":"team","events":["release_published"]}`)
134 want(code, body, "kopie groep", 201, `"scope":"group"`)
135 gv, _ := st.SecretValues(ctx, "group", team.ID, true)
136 if gv["GROK_TOKEN"] != secretVal {
137 t.Fatal("groepsgeheim ontbreekt")
138 }
139 code, body = call(http.MethodPost, base+"/copy", devTok, `{"target_type":"group","target":"team"}`)
140 if code != 403 && code != 404 {
141 t.Fatalf("dev mag niet kopiëren: %d %s", code, body)
142 }
143 code, body = call(http.MethodPost, base+"/copy", adaTok, `{"target_type":"project","target":"ada/bestaatniet"}`)
144 want(code, body, "onbekend doel", 404, "")
145 code, body = call(http.MethodGet, "/api/v1/projects/ada/dst/webhooks", adaTok, "")
146 want(code, body, "lijst", 200, "Kopie")
147 code, body = call(http.MethodDelete, fmt.Sprintf("/api/v1/projects/ada/dst/webhooks/%d", hooks[0].ID), adaTok, "")
148 want(code, body, "verwijderen", 204, "")
149 code, body = call(http.MethodGet, "/api/v1/openapi.json", "", "")
150 want(code, body, "openapi", 200, "/webhooks/{id}/copy")
151
152 jar, _ := cookiejar.New(nil)
153 client := &http.Client{Jar: jar}
154 res, err := client.Get(ts.URL + "/login")
155 if err != nil {
156 t.Fatal(err)
157 }
158 _ = read(t, res)
159 res, err = client.Get(ts.URL + "/ada/src/-/settings?tab=webhooks")
160 if err != nil {
161 t.Fatal(err)
162 }
163 page := read(t, res)
164 all.WriteString(page)
165 if !strings.Contains(page, "data-hookcopy-open") || !strings.Contains(page, `value="group:team"`) || !strings.Contains(page, `value="project:ada/dst"`) {
166 t.Fatalf("kopieerknop of doelen ontbreken")
167 }
168 res, err = client.PostForm(ts.URL+"/ada/src/-/webhooks/copy", url.Values{
169 "csrf": {csrfOf(t, page)}, "id": {fmt.Sprint(made.ID)}, "target": {"project:ada/dst"}, "name": {"Via UI"},
170 })
171 if err != nil {
172 t.Fatal(err)
173 }
174 all.WriteString(read(t, res))
175 hooks, _ = st.ListWebhooks(ctx, "repo", dst.ID)
176 found := false
177 for _, h := range hooks {
178 found = found || h.Name == "Via UI"
179 }
180 if !found {
181 t.Fatalf("UI-kopie ontbreekt: %+v", hooks)
182 }
183
184 if strings.Contains(all.String(), secretVal) {
185 t.Fatal("geheime waarde in een API-respons")
186 }
187}
internal/server/webhook_manage.go added +426 −0
@@ -0,0 +1,426 @@
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 }
@@ -0,0 +1,426 @@
1package server
2
3import (
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
22func 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.
31func 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.
43func (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
107var secretRefRe = regexp.MustCompile(`\{\{\s*secret\.([A-Za-z_][A-Za-z0-9_]*)\s*\}\}`)
108
109// hookSecretRefs geeft de geheimnamen die een webhook gebruikt.
110func 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
131type scopeRef struct {
132 Kind string
133 ID int64
134}
135
136// secretScopes geeft de scopes waaruit een webhook geheimen leest, eigen scope eerst.
137func (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
147func (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.
157type 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.
165type HookCopyResult struct {
166 Hook store.Webhook
167 CopiedSecrets []string
168 MissingSecrets []string
169}
170
171func (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.
196func (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
284func (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
301func (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
322func hookNames(in []string) []string {
323 if in == nil {
324 return []string{}
325 }
326 return in
327}
328
329func (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
337func (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
345func (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
353func (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.
364type HookTarget struct {
365 Value string
366 Label string
367 Group bool
368}
369
370// hookTargets geeft projecten en groepen die deze gebruiker beheert.
371func (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
400func (s *Server) repoWebhookCopy(w http.ResponseWriter, r *http.Request) { s.webhookCopy(w, r, "repo") }
401func (s *Server) groupWebhookCopy(w http.ResponseWriter, r *http.Request) {
402 s.webhookCopy(w, r, "group")
403}
404
405func (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}
internal/store/flow.go +28 −0
@@ -1605,3 +1605,31 @@ func ProtectedRunning(jobs []Job) []Job {
1605 1605 }
1606 1606 return out
1607 1607 }
1608
1609 // CopySecret kopieert een versleuteld geheim naar een ander scope zonder het
1610 // te ontcijferen. Een bestaande naam in het doel wordt niet overschreven.
1611 func (s *Store) CopySecret(ctx context.Context, fromKind string, fromID int64, name, toKind string, toID int64) error {
1612 if toKind != "repo" && toKind != "group" {
1613 return i18n.E("err.scope")
1614 }
1615 res, err := s.db.ExecContext(ctx, `INSERT INTO secrets (scope_kind, scope_id, name, ciphertext, nonce, protected, invisible, created_at)
1616 SELECT ?, ?, name, ciphertext, nonce, protected, invisible, ? FROM secrets WHERE scope_kind = ? AND scope_id = ? AND name = ?`,
1617 toKind, toID, now(), fromKind, fromID, name)
1618 if err != nil {
1619 if strings.Contains(err.Error(), "UNIQUE") {
1620 return i18n.E("err.secretExists", name)
1621 }
1622 return err
1623 }
1624 n, _ := res.RowsAffected()
1625 if n == 0 {
1626 return errNotFound
1627 }
1628 return nil
1629 }
1630
1631 // SetWebhookActive zet een webhook aan of uit.
1632 func (s *Store) SetWebhookActive(ctx context.Context, scopeKind string, scopeID, id int64, on bool) error {
1633 _, err := s.db.ExecContext(ctx, `UPDATE webhooks SET active = ? WHERE id = ? AND scope_kind = ? AND scope_id = ?`, boolInt(on), id, scopeKind, scopeID)
1634 return err
1635 }
@@ -1605,3 +1605,31 @@ func ProtectedRunning(jobs []Job) []Job {
1605 }
1605 }
1606 return out
1606 return out
1607}
1607}
1608
1609// CopySecret kopieert een versleuteld geheim naar een ander scope zonder het
1610// te ontcijferen. Een bestaande naam in het doel wordt niet overschreven.
1611func (s *Store) CopySecret(ctx context.Context, fromKind string, fromID int64, name, toKind string, toID int64) error {
1612 if toKind != "repo" && toKind != "group" {
1613 return i18n.E("err.scope")
1614 }
1615 res, err := s.db.ExecContext(ctx, `INSERT INTO secrets (scope_kind, scope_id, name, ciphertext, nonce, protected, invisible, created_at)
1616 SELECT ?, ?, name, ciphertext, nonce, protected, invisible, ? FROM secrets WHERE scope_kind = ? AND scope_id = ? AND name = ?`,
1617 toKind, toID, now(), fromKind, fromID, name)
1618 if err != nil {
1619 if strings.Contains(err.Error(), "UNIQUE") {
1620 return i18n.E("err.secretExists", name)
1621 }
1622 return err
1623 }
1624 n, _ := res.RowsAffected()
1625 if n == 0 {
1626 return errNotFound
1627 }
1628 return nil
1629}
1630
1631// SetWebhookActive zet een webhook aan of uit.
1632func (s *Store) SetWebhookActive(ctx context.Context, scopeKind string, scopeID, id int64, on bool) error {
1633 _, err := s.db.ExecContext(ctx, `UPDATE webhooks SET active = ? WHERE id = ? AND scope_kind = ? AND scope_id = ?`, boolInt(on), id, scopeKind, scopeID)
1634 return err
1635}