-
Notifications
You must be signed in to change notification settings - Fork 61
feat(api): outbound workspace webhooks with signed delivery and logs #306
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "net/http" | ||
|
|
||
| "github.com/Devlaner/devlane/api/internal/middleware" | ||
| "github.com/Devlaner/devlane/api/internal/service" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/google/uuid" | ||
| ) | ||
|
|
||
| // WebhookHandler serves outbound workspace webhook management + delivery logs. | ||
| type WebhookHandler struct { | ||
| Webhooks *service.WebhookService | ||
| } | ||
|
|
||
| type webhookBody struct { | ||
| URL string `json:"url"` | ||
| IsActive *bool `json:"is_active"` | ||
| Project *bool `json:"project"` | ||
| Issue *bool `json:"issue"` | ||
| Module *bool `json:"module"` | ||
| Cycle *bool `json:"cycle"` | ||
| IssueComment *bool `json:"issue_comment"` | ||
| } | ||
|
|
||
| func (b webhookBody) toInput() service.WebhookInput { | ||
| return service.WebhookInput{ | ||
| URL: b.URL, | ||
| IsActive: b.IsActive, | ||
| Project: b.Project, | ||
| Issue: b.Issue, | ||
| Module: b.Module, | ||
| Cycle: b.Cycle, | ||
| IssueComment: b.IssueComment, | ||
| } | ||
| } | ||
|
|
||
| // List returns the workspace's webhooks. | ||
| // GET /api/workspaces/:slug/webhooks/ | ||
| func (h *WebhookHandler) List(c *gin.Context) { | ||
| user := middleware.GetUser(c) | ||
| if user == nil { | ||
| c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"}) | ||
| return | ||
| } | ||
| list, err := h.Webhooks.List(c.Request.Context(), c.Param("slug"), user.ID) | ||
| if err != nil { | ||
| h.webhookError(c, err) | ||
| return | ||
| } | ||
| c.JSON(http.StatusOK, list) | ||
| } | ||
|
|
||
| // Create adds a webhook. | ||
| // POST /api/workspaces/:slug/webhooks/ | ||
| func (h *WebhookHandler) Create(c *gin.Context) { | ||
| user := middleware.GetUser(c) | ||
| if user == nil { | ||
| c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"}) | ||
| return | ||
| } | ||
| var body webhookBody | ||
| if err := c.ShouldBindJSON(&body); err != nil { | ||
| c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request", "detail": err.Error()}) | ||
| return | ||
| } | ||
| w, err := h.Webhooks.Create(c.Request.Context(), c.Param("slug"), user.ID, body.toInput()) | ||
| if err != nil { | ||
| h.webhookError(c, err) | ||
| return | ||
| } | ||
| // The signing secret is returned exactly once, here at creation. Every other | ||
| // response omits it (model.Webhook.SecretKey is json:"-"), so it never leaks | ||
| // on subsequent list/update fetches. | ||
| c.JSON(http.StatusCreated, gin.H{ | ||
| "id": w.ID, | ||
| "url": w.URL, | ||
| "secret_key": w.SecretKey, | ||
| "is_active": w.IsActive, | ||
| "project": w.Project, | ||
| "issue": w.Issue, | ||
| "module": w.Module, | ||
| "cycle": w.Cycle, | ||
| "issue_comment": w.IssueComment, | ||
| "version": w.Version, | ||
| "workspace_id": w.WorkspaceID, | ||
| "created_at": w.CreatedAt, | ||
| "updated_at": w.UpdatedAt, | ||
| }) | ||
| } | ||
|
|
||
| // Update edits a webhook. | ||
| // PATCH /api/workspaces/:slug/webhooks/:webhookId/ | ||
| func (h *WebhookHandler) Update(c *gin.Context) { | ||
| user := middleware.GetUser(c) | ||
| if user == nil { | ||
| c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"}) | ||
| return | ||
| } | ||
| id, err := uuid.Parse(c.Param("webhookId")) | ||
| if err != nil { | ||
| c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid webhook ID"}) | ||
| return | ||
| } | ||
| var body webhookBody | ||
| if err := c.ShouldBindJSON(&body); err != nil { | ||
| c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request", "detail": err.Error()}) | ||
| return | ||
| } | ||
| w, err := h.Webhooks.Update(c.Request.Context(), c.Param("slug"), user.ID, id, body.toInput()) | ||
| if err != nil { | ||
| h.webhookError(c, err) | ||
| return | ||
| } | ||
| c.JSON(http.StatusOK, w) | ||
| } | ||
|
|
||
| // Delete removes a webhook. | ||
| // DELETE /api/workspaces/:slug/webhooks/:webhookId/ | ||
| func (h *WebhookHandler) Delete(c *gin.Context) { | ||
| user := middleware.GetUser(c) | ||
| if user == nil { | ||
| c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"}) | ||
| return | ||
| } | ||
| id, err := uuid.Parse(c.Param("webhookId")) | ||
| if err != nil { | ||
| c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid webhook ID"}) | ||
| return | ||
| } | ||
| if err := h.Webhooks.Delete(c.Request.Context(), c.Param("slug"), user.ID, id); err != nil { | ||
| h.webhookError(c, err) | ||
| return | ||
| } | ||
| c.Status(http.StatusNoContent) | ||
| } | ||
|
|
||
| // ListLogs returns a webhook's recent delivery logs. | ||
| // GET /api/workspaces/:slug/webhooks/:webhookId/logs/ | ||
| func (h *WebhookHandler) ListLogs(c *gin.Context) { | ||
| user := middleware.GetUser(c) | ||
| if user == nil { | ||
| c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication required"}) | ||
| return | ||
| } | ||
| id, err := uuid.Parse(c.Param("webhookId")) | ||
| if err != nil { | ||
| c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid webhook ID"}) | ||
| return | ||
| } | ||
| logs, err := h.Webhooks.ListLogs(c.Request.Context(), c.Param("slug"), user.ID, id) | ||
| if err != nil { | ||
| h.webhookError(c, err) | ||
| return | ||
| } | ||
| c.JSON(http.StatusOK, logs) | ||
| } | ||
|
|
||
| func (h *WebhookHandler) webhookError(c *gin.Context, err error) { | ||
| switch err { | ||
| case service.ErrWebhookForbidden: | ||
| c.JSON(http.StatusForbidden, gin.H{"error": err.Error()}) | ||
| case service.ErrWebhookWorkspace, service.ErrWebhookNotFound: | ||
| c.JSON(http.StatusNotFound, gin.H{"error": "Not found"}) | ||
| case service.ErrWebhookBadURL: | ||
| c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | ||
| default: | ||
| c.JSON(http.StatusInternalServerError, gin.H{"error": "Webhook request failed"}) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,127 +1,68 @@ | ||
| package handler_test | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/hmac" | ||
| "crypto/sha256" | ||
| "encoding/hex" | ||
| "encoding/json" | ||
| "net/http" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| devcrypto "github.com/Devlaner/devlane/api/internal/crypto" | ||
| "github.com/Devlaner/devlane/api/internal/model" | ||
| "github.com/Devlaner/devlane/api/internal/store" | ||
| "github.com/Devlaner/devlane/api/internal/testutil" | ||
| "github.com/stretchr/testify/require" | ||
| "gorm.io/gorm" | ||
| ) | ||
|
|
||
| func signGitHubPayload(secret string, body []byte) string { | ||
| mac := hmac.New(sha256.New, []byte(secret)) | ||
| mac.Write(body) | ||
| return "sha256=" + hex.EncodeToString(mac.Sum(nil)) | ||
| } | ||
|
|
||
| // seedGitHubWebhookSecret stores an encrypted webhook secret in instance_settings | ||
| // the way handler/instance.go would when an admin saves the github_app section. | ||
| func seedGitHubWebhookSecret(t *testing.T, db *gorm.DB, secret string) { | ||
| t.Helper() | ||
| settings := store.NewInstanceSettingStore(db) | ||
| require.NoError(t, settings.Upsert(context.Background(), "github_app", model.JSONMap{ | ||
| "app_id": "12345", | ||
| "app_name": "test-app", | ||
| "client_id": "Iv1.testclient", | ||
| "webhook_secret": devcrypto.EncryptOrPlain(secret), | ||
| "webhook_secret_set": true, | ||
| })) | ||
| } | ||
|
|
||
| func TestWebhook_GitHub_MissingSignature(t *testing.T) { | ||
| ts := testutil.NewTestServer(t) | ||
| seedGitHubWebhookSecret(t, ts.DB, "test-webhook-secret") | ||
|
|
||
| body := []byte(`{"action":"opened"}`) | ||
| rr := ts.DoWithHeaders(http.MethodPost, "/webhooks/github", body, http.Header{ | ||
| "X-GitHub-Event": []string{"pull_request"}, | ||
| "X-GitHub-Delivery": []string{"deadbeef-1234"}, | ||
| }) | ||
| require.Equal(t, http.StatusUnauthorized, rr.Code, "body=%s", rr.Body.String()) | ||
| } | ||
|
|
||
| func TestWebhook_GitHub_BadSignature(t *testing.T) { | ||
| ts := testutil.NewTestServer(t) | ||
| seedGitHubWebhookSecret(t, ts.DB, "test-webhook-secret") | ||
|
|
||
| body := []byte(`{"action":"opened"}`) | ||
| rr := ts.DoWithHeaders(http.MethodPost, "/webhooks/github", body, http.Header{ | ||
| "X-GitHub-Event": []string{"pull_request"}, | ||
| "X-GitHub-Delivery": []string{"deadbeef-1234"}, | ||
| "X-Hub-Signature-256": []string{"sha256=" + strings.Repeat("0", 64)}, | ||
| "Content-Type": []string{"application/json"}, | ||
| }) | ||
| require.Equal(t, http.StatusUnauthorized, rr.Code, "body=%s", rr.Body.String()) | ||
| } | ||
|
|
||
| func TestWebhook_GitHub_ValidSignature_NoTrailingSlash(t *testing.T) { | ||
| // Webhook CRUD for a workspace admin: create (secret generated), list, toggle, | ||
| // delete. Covers #195. | ||
| func TestWebhook_CRUD(t *testing.T) { | ||
| ts := testutil.NewTestServer(t) | ||
| const secret = "test-webhook-secret" | ||
| seedGitHubWebhookSecret(t, ts.DB, secret) | ||
|
|
||
| body := []byte(`{"action":"opened","number":1}`) | ||
| sig := signGitHubPayload(secret, body) | ||
|
|
||
| rr := ts.DoWithHeaders(http.MethodPost, "/webhooks/github", body, http.Header{ | ||
| "X-GitHub-Event": []string{"pull_request"}, | ||
| "X-GitHub-Delivery": []string{"deadbeef-1234"}, | ||
| "X-Hub-Signature-256": []string{sig}, | ||
| "Content-Type": []string{"application/json"}, | ||
| }) | ||
| require.Equal(t, http.StatusOK, rr.Code, "body=%s", rr.Body.String()) | ||
| w := testutil.SeedWorld(t, ts.DB) // seeded user owns the workspace | ||
| base := "/api/workspaces/" + w.Workspace.Slug + "/webhooks/" | ||
|
|
||
| rr := ts.POST(base, map[string]any{"url": "https://example.com/hook", "issue": true}, w.Session) | ||
| require.Equal(t, http.StatusCreated, rr.Code, "body=%s", rr.Body.String()) | ||
| var created map[string]any | ||
| require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &created)) | ||
| id, _ := created["id"].(string) | ||
| require.NotEmpty(t, id) | ||
| require.NotEmpty(t, created["secret_key"], "a secret should be generated") | ||
| require.Equal(t, true, created["issue"]) | ||
|
|
||
| // List includes the webhook but never the secret: it is returned only once, | ||
| // at creation. | ||
| lr := ts.GET(base, w.Session) | ||
| require.Equal(t, http.StatusOK, lr.Code) | ||
| var list []map[string]any | ||
| require.NoError(t, json.Unmarshal(lr.Body.Bytes(), &list)) | ||
| require.Len(t, list, 1) | ||
| require.NotContains(t, list[0], "secret_key", "the secret must not leak on list") | ||
|
|
||
| // Toggle it off. | ||
| ur := ts.PATCH(base+id+"/", map[string]any{"is_active": false}, w.Session) | ||
| require.Equal(t, http.StatusOK, ur.Code, "body=%s", ur.Body.String()) | ||
| var updated map[string]any | ||
| require.NoError(t, json.Unmarshal(ur.Body.Bytes(), &updated)) | ||
| require.Equal(t, false, updated["is_active"]) | ||
|
|
||
| // Delete it. | ||
| require.Equal(t, http.StatusNoContent, ts.DELETE(base+id+"/", w.Session).Code) | ||
| lr2 := ts.GET(base, w.Session) | ||
| var list2 []map[string]any | ||
| require.NoError(t, json.Unmarshal(lr2.Body.Bytes(), &list2)) | ||
| require.Len(t, list2, 0) | ||
| } | ||
|
|
||
| func TestWebhook_GitHub_ValidSignature_TrailingSlash(t *testing.T) { | ||
| // A non-http URL is rejected. | ||
| func TestWebhook_RejectsBadURL(t *testing.T) { | ||
| ts := testutil.NewTestServer(t) | ||
| const secret = "test-webhook-secret" | ||
| seedGitHubWebhookSecret(t, ts.DB, secret) | ||
|
|
||
| body := []byte(`{"action":"opened","number":2}`) | ||
| sig := signGitHubPayload(secret, body) | ||
|
|
||
| rr := ts.DoWithHeaders(http.MethodPost, "/webhooks/github/", body, http.Header{ | ||
| "X-GitHub-Event": []string{"pull_request"}, | ||
| "X-GitHub-Delivery": []string{"deadbeef-5678"}, | ||
| "X-Hub-Signature-256": []string{sig}, | ||
| "Content-Type": []string{"application/json"}, | ||
| }) | ||
| require.Equal(t, http.StatusOK, rr.Code, "body=%s", rr.Body.String()) | ||
| w := testutil.SeedWorld(t, ts.DB) | ||
| rr := ts.POST("/api/workspaces/"+w.Workspace.Slug+"/webhooks/", map[string]any{"url": "ftp://example.com"}, w.Session) | ||
| require.Equal(t, http.StatusBadRequest, rr.Code) | ||
| } | ||
|
|
||
| func TestWebhook_GitHub_NoSecretConfigured(t *testing.T) { | ||
| // With no github_app settings, webhook secret is empty → VerifySignature | ||
| // returns "secret is not configured" → 401. | ||
| // A non-admin (non-member) cannot manage webhooks. | ||
| func TestWebhook_NonAdminForbidden(t *testing.T) { | ||
| ts := testutil.NewTestServer(t) | ||
|
|
||
| body := []byte(`{"action":"opened"}`) | ||
| rr := ts.DoWithHeaders(http.MethodPost, "/webhooks/github", body, http.Header{ | ||
| "X-GitHub-Event": []string{"pull_request"}, | ||
| "X-GitHub-Delivery": []string{"any"}, | ||
| "X-Hub-Signature-256": []string{"sha256=" + strings.Repeat("0", 64)}, | ||
| }) | ||
| require.Equal(t, http.StatusUnauthorized, rr.Code) | ||
| } | ||
|
|
||
| func TestWebhook_GitHub_MissingHeaders(t *testing.T) { | ||
| ts := testutil.NewTestServer(t) | ||
| const secret = "test-webhook-secret" | ||
| seedGitHubWebhookSecret(t, ts.DB, secret) | ||
|
|
||
| body := []byte(`{"action":"opened"}`) | ||
| sig := signGitHubPayload(secret, body) | ||
|
|
||
| // Valid signature but no event/delivery headers → 400. | ||
| rr := ts.DoWithHeaders(http.MethodPost, "/webhooks/github", body, http.Header{ | ||
| "X-Hub-Signature-256": []string{sig}, | ||
| }) | ||
| require.Equal(t, http.StatusBadRequest, rr.Code, "body=%s", rr.Body.String()) | ||
| w := testutil.SeedWorld(t, ts.DB) | ||
| stranger := testutil.CreateUser(t, ts.DB) | ||
| session := testutil.LoginAs(t, ts.DB, stranger) | ||
| rr := ts.GET("/api/workspaces/"+w.Workspace.Slug+"/webhooks/", session) | ||
| require.Equal(t, http.StatusForbidden, rr.Code) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.