Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

feat: bind agent webhooks to user credentials (#21421)

buua436a921941796f3
diff --git a/internal/dao/agent_webhook_credential.go b/internal/dao/agent_webhook_credential.go
new file mode 100644
index 0000000000..65ffd6b21b
--- /dev/null
+++ b/internal/dao/agent_webhook_credential.go
@@ -0,0 +1,71 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package dao
+
+import (
+ "context"
+ "time"
+
+ "ragflow/internal/entity"
+
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+// SaveAgentWebhookCredential creates or rotates the credential for one
+// (canvas, user, tenant) identity. Reissuing replaces the old hash atomically.
+func SaveAgentWebhookCredential(ctx context.Context, db *gorm.DB, credential *entity.AgentWebhookCredential) error {
+ now := time.Now().Local()
+ createTime := now.UnixMilli()
+ createDate := now.Truncate(time.Second)
+ updateTime := createTime
+ updateDate := createDate
+ credential.CreateTime = &createTime
+ credential.CreateDate = &createDate
+ credential.UpdateTime = &updateTime
+ credential.UpdateDate = &updateDate
+
+ return db.WithContext(ctx).Clauses(clause.OnConflict{
+ Columns: []clause.Column{{Name: "canvas_id"}, {Name: "user_id"}, {Name: "tenant_id"}},
+ DoUpdates: clause.AssignmentColumns([]string{"token_hash", "revoked_at", "update_time", "update_date"}),
+ }).Create(credential).Error
+}
+
+// GetActiveAgentWebhookCredential resolves a stored hash for the requested
+// canvas. Explicit predicates keep the lookup scoped to both the URL canvas
+// and the unguessable credential.
+func GetActiveAgentWebhookCredential(ctx context.Context, db *gorm.DB, canvasID, tokenHash string) (*entity.AgentWebhookCredential, error) {
+ var credential entity.AgentWebhookCredential
+ err := db.WithContext(ctx).
+ Where("canvas_id = ? AND token_hash = ? AND revoked_at IS NULL", canvasID, tokenHash).
+ Take(&credential).Error
+ if err != nil {
+ return nil, err
+ }
+ return &credential, nil
+}
+
+// RevokeAgentWebhookCredential revokes only the specified user's credential
+// for a canvas. It is safe to call repeatedly.
+func RevokeAgentWebhookCredential(ctx context.Context, db *gorm.DB, canvasID, userID string) error {
+ now := time.Now().Local()
+ updateTime := now.UnixMilli()
+ updateDate := now.Truncate(time.Second)
+ return db.WithContext(ctx).Model(&entity.AgentWebhookCredential{}).
+ Where("canvas_id = ? AND user_id = ? AND revoked_at IS NULL", canvasID, userID).
+ Updates(map[string]any{"revoked_at": now, "update_time": updateTime, "update_date": updateDate}).Error
+}
diff --git a/internal/dao/agent_webhook_credential_test.go b/internal/dao/agent_webhook_credential_test.go
new file mode 100644
index 0000000000..4d30bb152a
--- /dev/null
+++ b/internal/dao/agent_webhook_credential_test.go
@@ -0,0 +1,57 @@
+package dao
+
+import (
+ "errors"
+ "testing"
+
+ "github.com/glebarez/sqlite"
+ "gorm.io/gorm"
+
+ "ragflow/internal/entity"
+)
+
+func TestAgentWebhookCredentialRotationAndRevocation(t *testing.T) {
+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{TranslateError: true})
+ if err != nil {
+ t.Fatalf("open sqlite: %v", err)
+ }
+ if err := db.AutoMigrate(&entity.AgentWebhookCredential{}); err != nil {
+ t.Fatalf("migrate webhook credentials: %v", err)
+ }
+
+ identity := struct{ canvasID, userID, tenantID string }{"canvas-1", "user-1", "tenant-1"}
+ first := &entity.AgentWebhookCredential{
+ ID: "credential-1", CanvasID: identity.canvasID, UserID: identity.userID,
+ TenantID: identity.tenantID, TokenHash: "first-hash",
+ }
+ if err := SaveAgentWebhookCredential(t.Context(), db, first); err != nil {
+ t.Fatalf("save initial credential: %v", err)
+ }
+ if _, err := GetActiveAgentWebhookCredential(t.Context(), db, identity.canvasID, "first-hash"); err != nil {
+ t.Fatalf("load initial credential: %v", err)
+ }
+
+ rotated := &entity.AgentWebhookCredential{
+ ID: "credential-2", CanvasID: identity.canvasID, UserID: identity.userID,
+ TenantID: identity.tenantID, TokenHash: "second-hash",
+ }
+ if err := SaveAgentWebhookCredential(t.Context(), db, rotated); err != nil {
+ t.Fatalf("rotate credential: %v", err)
+ }
+ if _, err := GetActiveAgentWebhookCredential(t.Context(), db, identity.canvasID, "first-hash"); !errors.Is(err, gorm.ErrRecordNotFound) {
+ t.Fatalf("old credential lookup error = %v, want record not found", err)
+ }
+ if got, err := GetActiveAgentWebhookCredential(t.Context(), db, identity.canvasID, "second-hash"); err != nil || got.UserID != identity.userID || got.TenantID != identity.tenantID {
+ t.Fatalf("load rotated credential = (%+v, %v), want bound identity", got, err)
+ }
+
+ if err := RevokeAgentWebhookCredential(t.Context(), db, identity.canvasID, identity.userID); err != nil {
+ t.Fatalf("revoke credential: %v", err)
+ }
+ if _, err := GetActiveAgentWebhookCredential(t.Context(), db, identity.canvasID, "second-hash"); !errors.Is(err, gorm.ErrRecordNotFound) {
+ t.Fatalf("revoked credential lookup error = %v, want record not found", err)
+ }
+ if err := RevokeAgentWebhookCredential(t.Context(), db, identity.canvasID, identity.userID); err != nil {
+ t.Fatalf("repeat revoke: %v", err)
+ }
+}
diff --git a/internal/dao/database.go b/internal/dao/database.go
index 965405763e..da94c7ea15 100644
--- a/internal/dao/database.go
+++ b/internal/dao/database.go
@@ -177,6 +177,7 @@ func InitDB(ctx context.Context, migrateDB bool) error {
&entity.InvitationCode{},
&entity.Document{},
&entity.UserCanvas{},
+ &entity.AgentWebhookCredential{},
&entity.CanvasTemplate{},
&entity.UserCanvasVersion{},
&entity.LLMFactories{},
diff --git a/internal/entity/agent_webhook_credential.go b/internal/entity/agent_webhook_credential.go
new file mode 100644
index 0000000000..44915598af
--- /dev/null
+++ b/internal/entity/agent_webhook_credential.go
@@ -0,0 +1,37 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package entity
+
+import "time"
+
+// AgentWebhookCredential binds an external webhook capability to the user and
+// tenant whose permissions and model connections must be used for execution.
+// Only a one-way hash of the credential is persisted.
+type AgentWebhookCredential struct {
+ ID string `gorm:"column:id;primaryKey;size:32" json:"id"`
+ CanvasID string `gorm:"column:canvas_id;size:32;not null;uniqueIndex:idx_agent_webhook_credential_identity,priority:1" json:"canvas_id"`
+ UserID string `gorm:"column:user_id;size:32;not null;uniqueIndex:idx_agent_webhook_credential_identity,priority:2" json:"user_id"`
+ TenantID string `gorm:"column:tenant_id;size:32;not null;uniqueIndex:idx_agent_webhook_credential_identity,priority:3" json:"tenant_id"`
+ TokenHash string `gorm:"column:token_hash;size:64;not null;uniqueIndex:idx_agent_webhook_credential_hash" json:"-"`
+ RevokedAt *time.Time `gorm:"column:revoked_at" json:"revoked_at,omitempty"`
+ BaseModel
+}
+
+// TableName returns the persistence table for AgentWebhookCredential.
+func (AgentWebhookCredential) TableName() string {
+ return "agent_webhook_credential"
+}
diff --git a/internal/handler/agent.go b/internal/handler/agent.go
index 094c6c9115..c104fde170 100644
--- a/internal/handler/agent.go
+++ b/internal/handler/agent.go
@@ -74,10 +74,11 @@ type chatAgentService interface {
// AgentHandler agent handler
type AgentHandler struct {
- agentService *service.AgentService
- chatRunner chatAgentService
- fileService agentFileService
- loader canvasLoader
+ agentService *service.AgentService
+ chatRunner chatAgentService
+ fileService agentFileService
+ loader canvasLoader
+ webhookCredentials agentWebhookCredentialManager
// redisGet fetches a raw string from Redis. Defaults to the global
// client (kvrocks.Get) so production behaviour is unchanged; tests inject
// a miniredis-backed getter to exercise Agent log endpoints without a
diff --git a/internal/handler/agent_webhook.go b/internal/handler/agent_webhook.go
index 3871842e6e..552ad4b5a7 100644
--- a/internal/handler/agent_webhook.go
+++ b/internal/handler/agent_webhook.go
@@ -66,7 +66,9 @@ import (
"io"
"math"
"net/http"
+ "net/url"
"ragflow/internal/agent/canvas"
+ dslpkg "ragflow/internal/agent/dsl"
"ragflow/internal/common"
kvrocks "ragflow/internal/engine/kvrocks"
"ragflow/internal/service"
@@ -80,6 +82,7 @@ import (
"ragflow/internal/dao"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
)
// canvasLoader is the subset of service.AgentService the webhook handler
@@ -96,27 +99,57 @@ type canvasLoader interface {
RunAgentWithWebhook(ctx context.Context, userID, canvasID string, payload map[string]any) (<-chan canvas.RunEvent, error)
}
-// Webhook is the handler method mounted at:
+type agentWebhookCredentialManager interface {
+ Issue(ctx context.Context, subject permission.Subject, canvas *entity.UserCanvas) (string, error)
+ Resolve(ctx context.Context, canvasID, token string) (*entity.AgentWebhookCredential, error)
+ Revoke(ctx context.Context, canvasID, userID string) error
+}
+
+// Webhook handles the public credential-authenticated trigger and the
+// authenticated test trigger mounted at:
//
-// /api/v1/agents/:canvas_id/webhook (production trigger)
+// /api/v1/agents/:canvas_id/webhook (production trigger, webhook credential required)
// /api/v1/agents/:canvas_id/webhook/test (test trigger, with trace)
//
// The Python decorator stack at agent_api.py:1563 binds six methods to
// a single path. Gin has no Match() — the router registers each verb
// individually via registerAnyMethod (see internal/router/agent_routes.go).
func (h *AgentHandler) Webhook(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.ResponseWithCodeData(c, code, nil, msg)
- return
- }
-
canvasID := c.Param("canvas_id")
if h.loader == nil {
jsonInternalError(c, errors.New("agent webhook: loader not configured"))
return
}
isTest := strings.HasSuffix(c.Request.URL.Path, "/webhook/test")
+ ctx := c.Request.Context()
+ userID := ""
+ if isTest {
+ user, code, msg := GetUser(c)
+ if code != common.CodeSuccess {
+ common.ResponseWithHttpCodeData(c, http.StatusUnauthorized, code, nil, msg)
+ return
+ }
+ userID = user.ID
+ } else {
+ // Production webhooks are mounted outside AuthMiddleware. External
+ // callers authenticate with a per-user capability in the URL; RAGFlow
+ // API keys and user JWTs are not accepted on this route.
+ credential, err := h.webhookCredentialManager().Resolve(ctx, canvasID, c.Query("credential"))
+ if err != nil {
+ if errors.Is(err, service.ErrInvalidAgentWebhookCredential) {
+ common.ResponseWithHttpCodeData(c, http.StatusUnauthorized, common.CodeUnauthorized, nil, "Invalid or revoked webhook credential.")
+ } else {
+ jsonInternalError(c, err)
+ }
+ return
+ }
+ userID = credential.UserID
+ ctx = permission.WithSubject(ctx, permission.Subject{UserID: credential.UserID, TenantID: credential.TenantID})
+ // The URL credential is transport authentication, not Agent input.
+ query := c.Request.URL.Query()
+ query.Del("credential")
+ c.Request.URL.RawQuery = query.Encode()
+ }
startTs := time.Now()
// 1. Load canvas. Webhook collapses missing-vs-foreign into a
@@ -124,7 +157,7 @@ func (h *AgentHandler) Webhook(c *gin.Context) {
// api/apps/restful_apis/agent_api.py:1572 and the existing
// GetAgentWebhookLogs envelope), so we DO NOT route through
// handler.mapAgentError here.
- cv, err := h.loader.LoadCanvasByID(c.Request.Context(), user.ID, canvasID)
+ cv, err := h.loader.LoadCanvasByID(ctx, userID, canvasID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) || errors.Is(err, dao.ErrUserCanvasVersionNotFound) {
common.ResponseWithCodeData(c, common.CodeDataError, nil, "Canvas not found.")
@@ -150,6 +183,7 @@ func (h *AgentHandler) Webhook(c *gin.Context) {
for k, v := range cv.DSL {
dsl[k] = v
}
+ dsl = dslpkg.NormalizeForCanvas(dsl)
// 4. Find Begin component with mode=="Webhook".
webhookCfg := findWebhookBegin(dsl)
@@ -230,15 +264,74 @@ func (h *AgentHandler) Webhook(c *gin.Context) {
}
// Detached background run — does NOT inherit c.Request.Context()
// so a client disconnect does not cancel the canvas run.
- go h.runWebhookDetached(c.Request.Context(), cv, clean, isTest, startTs)
+ go h.runWebhookDetached(ctx, userID, cv, clean, isTest, startTs)
c.Data(status, contentType, payload)
return
}
// Streaming / blocking mode.
- out := h.runWebhookSync(c.Request.Context(), cv, clean, isTest, startTs)
+ out := h.runWebhookSync(ctx, userID, cv, clean, isTest, startTs)
c.JSON(out.status, out.body)
}
+// CreateWebhookCredential issues or rotates the authenticated user's
+// capability for this Agent and returns the URL once.
+func (h *AgentHandler) CreateWebhookCredential(c *gin.Context) {
+ user, code, msg := GetUser(c)
+ if code != common.CodeSuccess {
+ common.ResponseWithCodeData(c, code, nil, msg)
+ return
+ }
+ if h.loader == nil {
+ jsonInternalError(c, errors.New("agent webhook: loader not configured"))
+ return
+ }
+ canvasID := c.Param("canvas_id")
+ ctx := c.Request.Context()
+ canvas, err := h.loader.LoadCanvasByID(ctx, user.ID, canvasID)
+ if err != nil {
+ responseCode, responseMessage := mapAgentError(err)
+ common.ResponseWithCodeData(c, responseCode, nil, responseMessage)
+ return
+ }
+ credential, err := h.webhookCredentialManager().Issue(ctx, permission.Subject{UserID: user.ID}, canvas)
+ if err != nil {
+ if errors.Is(err, permission.ErrPermissionDenied) || errors.Is(err, permission.ErrMembershipNotFound) || errors.Is(err, permission.ErrInvalidSubject) {
+ common.ResponseWithHttpCodeData(c, http.StatusForbidden, common.CodeForbidden, nil, "You do not have permission to create a webhook credential for this agent.")
+ return
+ }
+ jsonInternalError(c, err)
+ return
+ }
+ query := url.Values{"credential": []string{credential}}
+ webhookPath := fmt.Sprintf("/api/v1/agents/%s/webhook?%s", url.PathEscape(canvasID), query.Encode())
+ common.ResponseWithCodeData(c, common.CodeSuccess, gin.H{
+ "credential": credential,
+ "webhook_url": webhookPath,
+ }, "success")
+}
+
+// RevokeWebhookCredential revokes only the authenticated user's capability
+// for this Agent.
+func (h *AgentHandler) RevokeWebhookCredential(c *gin.Context) {
+ user, code, msg := GetUser(c)
+ if code != common.CodeSuccess {
+ common.ResponseWithCodeData(c, code, nil, msg)
+ return
+ }
+ if err := h.webhookCredentialManager().Revoke(c.Request.Context(), c.Param("canvas_id"), user.ID); err != nil {
+ jsonInternalError(c, err)
+ return
+ }
+ common.ResponseWithCodeData(c, common.CodeSuccess, true, "success")
+}
+
+func (h *AgentHandler) webhookCredentialManager() agentWebhookCredentialManager {
+ if h.webhookCredentials != nil {
+ return h.webhookCredentials
+ }
+ return service.NewAgentWebhookCredentialService(dao.DB)
+}
+
// findWebhookBegin scans the DSL components map for a Begin component
// whose params.mode equals "Webhook". Returns the params map (the
// webhook_cfg) on success; nil otherwise. Mirrors agent_api.py:1584-1592.
@@ -255,15 +348,11 @@ func findWebhookBegin(dsl map[string]any) map[string]any {
if entry == nil {
continue
}
- obj, _ := entry["obj"].(map[string]any)
- if obj == nil {
- continue
- }
- name, _ := obj["component_name"].(string)
+ name, _ := entry["name"].(string)
if !strings.EqualFold(name, "begin") {
continue
}
- params, _ := obj["params"].(map[string]any)
+ params, _ := entry["params"].(map[string]any)
if params == nil {
continue
}
@@ -483,20 +572,20 @@ func renderImmediatelyResponse(cfg map[string]any) (int, string, []byte, error)
// Mirrors python: agent_api.py:2123-2175 (the asyncio.create_task body
// inside the Immediately branch).
func (h *AgentHandler) runWebhookDetached(
- parent context.Context, cv *entity.UserCanvas, payload map[string]any, isTest bool, startTs time.Time,
+ parent context.Context, userID string, cv *entity.UserCanvas, payload map[string]any, isTest bool, startTs time.Time,
) {
sessionID := common.GenerateToken()
parent = service.WithAgentSessionID(parent, sessionID)
ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), 5*time.Minute)
defer cancel()
- h.runWebhookDetachedWithContext(ctx, cv, payload, isTest, startTs, sessionID)
+ h.runWebhookDetachedWithContext(ctx, userID, cv, payload, isTest, startTs, sessionID)
}
func (h *AgentHandler) runWebhookDetachedWithContext(
- ctx context.Context, cv *entity.UserCanvas, payload map[string]any,
+ ctx context.Context, userID string, cv *entity.UserCanvas, payload map[string]any,
isTest bool, startTs time.Time, sessionID string,
) {
- events, err := h.loader.RunAgentWithWebhook(ctx, cv.UserID, cv.ID, payload)
+ events, err := h.loader.RunAgentWithWebhook(ctx, userID, cv.ID, payload)
if err != nil {
common.Warn("webhook detached run start failed",
zap.String("canvas", cv.ID),
@@ -557,13 +646,13 @@ type webhookSyncResult struct {
}
func (h *AgentHandler) runWebhookSync(
- ctx context.Context, cv *entity.UserCanvas, payload map[string]any,
+ ctx context.Context, userID string, cv *entity.UserCanvas, payload map[string]any,
isTest bool, startTs time.Time,
) webhookSyncResult {
status := 200
sessionID := common.GenerateToken()
ctx = service.WithAgentSessionID(ctx, sessionID)
- events, err := h.loader.RunAgentWithWebhook(ctx, cv.UserID, cv.ID, payload)
+ events, err := h.loader.RunAgentWithWebhook(ctx, userID, cv.ID, payload)
if err != nil {
if ctxErr := ctx.Err(); ctxErr != nil {
event := webhookContextTerminalEvent(ctxErr, sessionID)
diff --git a/internal/handler/agent_webhook_test.go b/internal/handler/agent_webhook_test.go
index 4dc21a747f..27ea1f645a 100644
--- a/internal/handler/agent_webhook_test.go
+++ b/internal/handler/agent_webhook_test.go
@@ -33,9 +33,11 @@ import (
"github.com/gin-gonic/gin"
"ragflow/internal/agent/canvas"
+ dslpkg "ragflow/internal/agent/dsl"
"ragflow/internal/common"
"ragflow/internal/dao"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
"ragflow/internal/service"
)
@@ -49,18 +51,65 @@ type fakeCanvasLoader struct {
runErr error
events []canvas.RunEvent
waitForCancellation bool
+ loadUserID string
+ runUserID string
+ runCanvasID string
+ runContext context.Context
+ runPayload map[string]any
+ runStarted chan string
runCalls atomic.Int32
}
-func (f *fakeCanvasLoader) LoadCanvasByID(_ context.Context, _, _ string) (*entity.UserCanvas, error) {
+type fakeAgentWebhookCredentialManager struct {
+ credential entity.AgentWebhookCredential
+ token string
+ resolveErr error
+ issueToken string
+ issueErr error
+ resolveID string
+ resolveToken string
+ revokedID string
+ revokedUser string
+}
+
+func (f *fakeAgentWebhookCredentialManager) Issue(_ context.Context, _ permission.Subject, _ *entity.UserCanvas) (string, error) {
+ return f.issueToken, f.issueErr
+}
+
+func (f *fakeAgentWebhookCredentialManager) Resolve(_ context.Context, canvasID, token string) (*entity.AgentWebhookCredential, error) {
+ f.resolveID = canvasID
+ f.resolveToken = token
+ if f.resolveErr != nil || token != f.token {
+ return nil, service.ErrInvalidAgentWebhookCredential
+ }
+ credential := f.credential
+ credential.CanvasID = canvasID
+ return &credential, nil
+}
+
+func (f *fakeAgentWebhookCredentialManager) Revoke(_ context.Context, canvasID, userID string) error {
+ f.revokedID = canvasID
+ f.revokedUser = userID
+ return nil
+}
+
+func (f *fakeCanvasLoader) LoadCanvasByID(_ context.Context, userID, _ string) (*entity.UserCanvas, error) {
+ f.loadUserID = userID
if f.err != nil {
return nil, f.err
}
return f.canvas, nil
}
-func (f *fakeCanvasLoader) RunAgentWithWebhook(ctx context.Context, _, _ string, _ map[string]any) (<-chan canvas.RunEvent, error) {
+func (f *fakeCanvasLoader) RunAgentWithWebhook(ctx context.Context, userID, canvasID string, payload map[string]any) (<-chan canvas.RunEvent, error) {
f.runCalls.Add(1)
+ f.runUserID = userID
+ f.runCanvasID = canvasID
+ f.runContext = ctx
+ f.runPayload = payload
+ if f.runStarted != nil {
+ f.runStarted <- userID
+ }
if f.runErr != nil {
return nil, f.runErr
}
@@ -122,8 +171,8 @@ func makeWebhookCanvas(id, userID, mode string, params map[string]any) *entity.U
}
}
-// webhookCtx builds a gin test context with the supplied method/path/body
-// and a pre-set "user" so GetUser() returns success.
+// webhookCtx builds a request carrying a test webhook credential and a user
+// for the authenticated /webhook/test route.
func webhookCtx(method, path, body, contentType string) (*gin.Context, *httptest.ResponseRecorder) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
@@ -135,6 +184,16 @@ func webhookCtx(method, path, body, contentType string) (*gin.Context, *httptest
reader = strings.NewReader(body)
}
c.Request = httptest.NewRequest(method, path, reader)
+ query := c.Request.URL.Query()
+ query.Set("credential", "test-capability")
+ c.Request.URL.RawQuery = query.Encode()
+ pathParts := strings.Split(strings.Trim(path, "/"), "/")
+ for i, part := range pathParts {
+ if part == "agents" && i+1 < len(pathParts) {
+ c.Params = gin.Params{{Key: "canvas_id", Value: pathParts[i+1]}}
+ break
+ }
+ }
if contentType != "" {
c.Request.Header.Set("Content-Type", contentType)
}
@@ -142,6 +201,124 @@ func webhookCtx(method, path, body, contentType string) (*gin.Context, *httptest
return c, w
}
+func newWebhookTestAgentHandler(loader canvasLoader) *AgentHandler {
+ return &AgentHandler{
+ loader: loader,
+ webhookCredentials: &fakeAgentWebhookCredentialManager{
+ credential: entity.AgentWebhookCredential{UserID: "u-1", TenantID: "u-1"},
+ token: "test-capability",
+ },
+ }
+}
+
+func TestPublicWebhookRunsAsCredentialIdentityWithoutUserToken(t *testing.T) {
+ tenantID := "tenant-1"
+ canvas := makeWebhookCanvas("c1", "canvas-owner", "Webhook", map[string]any{
+ "execution_mode": "Streaming",
+ "schema": map[string]any{"query": map[string]any{
+ "properties": map[string]any{"value": map[string]any{"type": "string"}},
+ }},
+ })
+ canvas.TenantID = &tenantID
+ loader := &fakeCanvasLoader{canvas: canvas, runStarted: make(chan string, 1)}
+ credentials := &fakeAgentWebhookCredentialManager{
+ credential: entity.AgentWebhookCredential{UserID: "webhook-caller", TenantID: tenantID},
+ token: "external-capability",
+ }
+ h := &AgentHandler{loader: loader, webhookCredentials: credentials}
+ c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
+ c.Delete("user")
+ c.Request.URL.RawQuery = "credential=external-capability&value=visible"
+
+ h.Webhook(c)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, body=%s; want 200", w.Code, w.Body.String())
+ }
+ if credentials.resolveID != "c1" || credentials.resolveToken != "external-capability" {
+ t.Fatalf("credential lookup = (%q, %q), want path canvas and URL credential", credentials.resolveID, credentials.resolveToken)
+ }
+ if loader.loadUserID != "webhook-caller" {
+ t.Fatalf("canvas loaded as %q, want bound webhook caller", loader.loadUserID)
+ }
+ select {
+ case userID := <-loader.runStarted:
+ if userID != "webhook-caller" {
+ t.Fatalf("agent ran as %q, want bound webhook caller", userID)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("webhook did not start the agent")
+ }
+ if subject, ok := permission.SubjectFromContext(loader.runContext); !ok || subject.TenantID != tenantID {
+ t.Fatalf("run tenant = %q, want %q", subject.TenantID, tenantID)
+ }
+ input := loader.runPayload["input"].(map[string]any)
+ query := input["query"].(map[string]any)
+ if _, leaked := query["credential"]; leaked {
+ t.Fatalf("webhook credential leaked into Agent query input: %#v", query)
+ }
+ if query["value"] != "visible" {
+ t.Fatalf("webhook query input = %#v, want the non-auth query field", query)
+ }
+}
+
+func TestPublicWebhookRejectsMissingOrInvalidCredential(t *testing.T) {
+ for _, token := range []string{"", "wrong-capability"} {
+ t.Run("token="+token, func(t *testing.T) {
+ loader := &fakeCanvasLoader{canvas: makeWebhookCanvas("c1", "canvas-owner", "Webhook", nil)}
+ credentials := &fakeAgentWebhookCredentialManager{token: "valid-capability"}
+ h := &AgentHandler{loader: loader, webhookCredentials: credentials}
+ c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
+ c.Delete("user")
+ c.Request.Header.Set("Authorization", "Bearer user-api-key")
+ if token != "" {
+ c.Request.URL.RawQuery = "credential=" + token
+ }
+
+ h.Webhook(c)
+
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want 401; body=%s", w.Code, w.Body.String())
+ }
+ if loader.runCalls.Load() != 0 || loader.loadUserID != "" {
+ t.Fatalf("invalid credential reached canvas load/run: user=%q runs=%d", loader.loadUserID, loader.runCalls.Load())
+ }
+ })
+ }
+}
+
+func TestWebhookCredentialManagementReturnsOneTimeURLAndRevokesCurrentUser(t *testing.T) {
+ manager := &fakeAgentWebhookCredentialManager{issueToken: "issued-capability"}
+ h := &AgentHandler{
+ loader: &fakeCanvasLoader{canvas: makeWebhookCanvas("c1", "u-1", "Webhook", nil)},
+ webhookCredentials: manager,
+ }
+ c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook/credentials", "", "")
+ h.CreateWebhookCredential(c)
+ var response struct {
+ Code common.ErrorCode `json:"code"`
+ Data struct {
+ Credential string `json:"credential"`
+ WebhookURL string `json:"webhook_url"`
+ } `json:"data"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode credential response: %v; body=%s", err, w.Body.String())
+ }
+ if w.Code != http.StatusOK || response.Code != common.CodeSuccess {
+ t.Fatalf("create status=%d code=%d body=%s", w.Code, response.Code, w.Body.String())
+ }
+ if response.Data.Credential != manager.issueToken || !strings.Contains(response.Data.WebhookURL, "credential=issued-capability") {
+ t.Fatalf("credential response = %+v, want one-time credential URL", response.Data)
+ }
+
+ c, w = webhookCtx("DELETE", "/api/v1/agents/c1/webhook/credentials", "", "")
+ h.RevokeWebhookCredential(c)
+ if w.Code != http.StatusOK || manager.revokedID != "c1" || manager.revokedUser != "u-1" {
+ t.Fatalf("revoke status=%d identity=(%q,%q), body=%s", w.Code, manager.revokedID, manager.revokedUser, w.Body.String())
+ }
+}
+
// errBody extracts {code, message} from a 102 envelope response.
func errBody(t *testing.T, body []byte) (int, string) {
t.Helper()
@@ -169,7 +346,7 @@ func TestWebhookHeaderSchemaAcceptsMixedCase(t *testing.T) {
}},
})
loader := &fakeCanvasLoader{canvas: cv}
- h := &AgentHandler{loader: loader}
+ h := newWebhookTestAgentHandler(loader)
h.webhookTraceAppender = func(context.Context, string, time.Time, canvas.RunEvent) {}
c, w := webhookCtx("POST", path, `{}`, "application/json")
c.Request.Header.Set("X-Request-ID", "request-123")
@@ -181,11 +358,49 @@ func TestWebhookHeaderSchemaAcceptsMixedCase(t *testing.T) {
}
}
+func TestWebhookRunsAsCredentialCaller(t *testing.T) {
+ for _, executionMode := range []string{"Streaming", "Immediately"} {
+ t.Run(executionMode, func(t *testing.T) {
+ cv := makeWebhookCanvas("c1", "canvas-owner", "Webhook", map[string]any{
+ "execution_mode": executionMode,
+ })
+ loader := &fakeCanvasLoader{canvas: cv, runStarted: make(chan string, 1)}
+ h := newWebhookTestAgentHandler(loader)
+ h.webhookCredentials = &fakeAgentWebhookCredentialManager{
+ credential: entity.AgentWebhookCredential{UserID: "webhook-caller", TenantID: "canvas-owner"},
+ token: "test-capability",
+ }
+ c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
+ c.Delete("user")
+
+ h.Webhook(c)
+
+ if loader.loadUserID != "webhook-caller" {
+ t.Fatalf("canvas loaded as %q, want credential-bound caller", loader.loadUserID)
+ }
+ select {
+ case runUserID := <-loader.runStarted:
+ if runUserID != "webhook-caller" {
+ t.Fatalf("agent ran as %q, want credential-bound caller", runUserID)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("webhook did not start the agent")
+ }
+ if loader.runCanvasID != cv.ID {
+ t.Fatalf("agent ran canvas %q, want %q", loader.runCanvasID, cv.ID)
+ }
+ if executionMode == "Streaming" && w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
+
// TestWebhook_RejectsUnknownCanvas pins the 102 "Canvas not found."
// envelope when LoadCanvasByID returns ErrUserCanvasNotFound. This is
// the deliberate divergence from mapAgentError (which would surface 103).
func TestWebhook_RejectsUnknownCanvas(t *testing.T) {
- h := &AgentHandler{loader: &fakeCanvasLoader{err: dao.ErrUserCanvasNotFound}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{err: dao.ErrUserCanvasNotFound})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
h.Webhook(c)
@@ -207,7 +422,7 @@ func TestWebhook_RejectsUnknownCanvas(t *testing.T) {
func TestWebhook_DataFlowRejected(t *testing.T) {
cv := makeWebhookCanvas("c1", "u-1", "Webhook", nil)
cv.CanvasCategory = "dataflow_canvas"
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
h.Webhook(c)
@@ -225,7 +440,7 @@ func TestWebhook_DataFlowRejected(t *testing.T) {
// mode="Webhook".
func TestWebhook_RejectsMissingWebhookConfig(t *testing.T) {
cv := makeWebhookCanvas("c1", "u-1", "Manual", nil) // wrong mode
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
h.Webhook(c)
@@ -247,7 +462,7 @@ func TestWebhook_RejectsDisallowedMethod(t *testing.T) {
cv := makeWebhookCanvas("c1", "u-1", "Webhook", map[string]any{
"methods": []any{"POST"},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("GET", "/api/v1/agents/c1/webhook", ``, "")
h.Webhook(c)
@@ -280,7 +495,7 @@ func TestWebhook_TokenAuthPasses(t *testing.T) {
},
})
loader := &fakeCanvasLoader{canvas: cv}
- h := &AgentHandler{loader: loader}
+ h := newWebhookTestAgentHandler(loader)
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
c.Request.Header.Set("X-Webhook-Token", "s3cret")
@@ -302,7 +517,7 @@ func TestWebhook_TokenAuthFails(t *testing.T) {
},
},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
c.Request.Header.Set("X-Webhook-Token", "wrong")
@@ -324,7 +539,7 @@ func TestWebhook_BodySizeLimit(t *testing.T) {
"max_body_size": "1kb",
},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook",
strings.Repeat("a", 2048), "text/plain")
@@ -343,7 +558,7 @@ func TestWebhook_BodySizeLimitTooLarge(t *testing.T) {
"max_body_size": "11mb",
},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
h.Webhook(c)
@@ -371,7 +586,7 @@ func TestWebhook_BasicAuthPasses(t *testing.T) {
"execution_mode": "Immediately",
"response": map[string]any{"status": 200},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
c.Request.SetBasicAuth("alice", "wonderland")
@@ -392,7 +607,7 @@ func TestWebhook_BasicAuthFails(t *testing.T) {
},
},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
c.Request.SetBasicAuth("alice", "wrong")
@@ -420,7 +635,7 @@ func TestWebhook_SchemaExtractionRequired(t *testing.T) {
"execution_mode": "Immediately",
"response": map[string]any{"status": 200},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook?other=v", ``, "")
h.Webhook(c)
@@ -448,7 +663,7 @@ func TestWebhook_SchemaExtractionTypeMismatch(t *testing.T) {
"execution_mode": "Immediately",
"response": map[string]any{"status": 200},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{"n":"abc"}`, "application/json")
h.Webhook(c)
@@ -482,7 +697,7 @@ func TestWebhook_ImmediatelyReturnsConfiguredStatus(t *testing.T) {
{Type: "done", Data: ""},
},
}
- h := &AgentHandler{loader: loader}
+ h := newWebhookTestAgentHandler(loader)
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
h.Webhook(c)
@@ -510,7 +725,7 @@ func TestWebhook_DefaultModeAggregatesContent(t *testing.T) {
{Type: "done", Data: ""},
},
}
- h := &AgentHandler{loader: loader}
+ h := newWebhookTestAgentHandler(loader)
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
h.Webhook(c)
@@ -573,7 +788,7 @@ func TestWebhook_DefaultModePropagatesTerminalEvents(t *testing.T) {
cv := makeWebhookCanvas("c1", "u-1", "Webhook", map[string]any{
"execution_mode": "Streaming",
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv, events: []canvas.RunEvent{tt.event}}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv, events: []canvas.RunEvent{tt.event}})
var trace []canvas.RunEvent
h.webhookTraceAppender = func(_ context.Context, _ string, _ time.Time, ev canvas.RunEvent) {
trace = append(trace, ev)
@@ -622,7 +837,7 @@ func TestWebhook_DefaultModeRedactsStartError(t *testing.T) {
"execution_mode": "Streaming",
})
startErr := errors.Join(errors.New("dial mysql password=secret"), service.ErrAgentStorageError)
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv, runErr: startErr}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv, runErr: startErr})
var trace []canvas.RunEvent
h.webhookTraceAppender = func(_ context.Context, _ string, _ time.Time, ev canvas.RunEvent) {
trace = append(trace, ev)
@@ -678,13 +893,13 @@ func TestRunWebhookDetachedAppendsFinishedTrace(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cv := makeWebhookCanvas("c1", "u-1", "Webhook", nil)
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv, events: tt.events, runErr: tt.runErr}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv, events: tt.events, runErr: tt.runErr})
var trace []canvas.RunEvent
h.webhookTraceAppender = func(_ context.Context, _ string, _ time.Time, ev canvas.RunEvent) {
trace = append(trace, ev)
}
- h.runWebhookDetached(t.Context(), cv, map[string]any{}, true, time.Now())
+ h.runWebhookDetached(t.Context(), "u-1", cv, map[string]any{}, true, time.Now())
assertWebhookFinishedTrace(t, trace, tt.wantSuccess)
if tt.forbidden != "" {
@@ -710,7 +925,7 @@ func TestRunWebhookDetachedRecordsTimeoutTrace(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
cv := makeWebhookCanvas("c1", "u-1", "Webhook", nil)
tt.loader.canvas = cv
- h := &AgentHandler{loader: tt.loader}
+ h := newWebhookTestAgentHandler(tt.loader)
var trace []canvas.RunEvent
h.webhookTraceAppender = func(ctx context.Context, _ string, _ time.Time, ev canvas.RunEvent) {
if err := ctx.Err(); err != nil {
@@ -725,7 +940,7 @@ func TestRunWebhookDetachedRecordsTimeoutTrace(t *testing.T) {
)
defer cancel()
<-ctx.Done()
- h.runWebhookDetachedWithContext(ctx, cv, map[string]any{}, true, time.Now(), "session-1")
+ h.runWebhookDetachedWithContext(ctx, "u-1", cv, map[string]any{}, true, time.Now(), "session-1")
if len(trace) < 2 || trace[0].Type != "error" || !strings.Contains(trace[0].Data, "timed out") {
t.Fatalf("timeout trace = %+v, want error followed by failed finished event", trace)
@@ -737,7 +952,7 @@ func TestRunWebhookDetachedRecordsTimeoutTrace(t *testing.T) {
func TestRunWebhookSyncRecordsCancelledTrace(t *testing.T) {
cv := makeWebhookCanvas("c1", "u-1", "Webhook", nil)
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv, waitForCancellation: true}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv, waitForCancellation: true})
var trace []canvas.RunEvent
h.webhookTraceAppender = func(ctx context.Context, _ string, _ time.Time, ev canvas.RunEvent) {
if err := ctx.Err(); err != nil {
@@ -748,7 +963,7 @@ func TestRunWebhookSyncRecordsCancelledTrace(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
cancel()
- result := h.runWebhookSync(ctx, cv, map[string]any{}, true, time.Now())
+ result := h.runWebhookSync(ctx, "u-1", cv, map[string]any{}, true, time.Now())
if result.status != http.StatusConflict {
t.Errorf("status = %d, want %d", result.status, http.StatusConflict)
@@ -767,13 +982,13 @@ func TestWebhookBufferedTerminalEventAfterCancellationUsesCleanupContext(t *test
{
name: "detached",
run: func(_ *testing.T, h *AgentHandler, ctx context.Context, cv *entity.UserCanvas) {
- h.runWebhookDetachedWithContext(ctx, cv, map[string]any{}, true, time.Now(), "session-1")
+ h.runWebhookDetachedWithContext(ctx, "u-1", cv, map[string]any{}, true, time.Now(), "session-1")
},
},
{
name: "sync",
run: func(t *testing.T, h *AgentHandler, ctx context.Context, cv *entity.UserCanvas) {
- result := h.runWebhookSync(ctx, cv, map[string]any{}, true, time.Now())
+ result := h.runWebhookSync(ctx, "u-1", cv, map[string]any{}, true, time.Now())
if result.status != http.StatusConflict {
t.Errorf("status = %d, want %d", result.status, http.StatusConflict)
}
@@ -791,7 +1006,7 @@ func TestWebhookBufferedTerminalEventAfterCancellationUsesCleanupContext(t *test
Data: `{"message":"Agent run was cancelled."}`,
}},
}
- h := &AgentHandler{loader: loader}
+ h := newWebhookTestAgentHandler(loader)
var trace []canvas.RunEvent
h.webhookTraceAppender = func(ctx context.Context, _ string, _ time.Time, ev canvas.RunEvent) {
if err := ctx.Err(); err != nil {
@@ -844,7 +1059,7 @@ func TestWebhook_InvalidResponseStatusRange(t *testing.T) {
"execution_mode": "Immediately",
"response": map[string]any{"status": 500},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{}`, "application/json")
h.Webhook(c)
@@ -872,6 +1087,15 @@ func TestWebhook_FindWebhookBegin_NoComponents(t *testing.T) {
}
}
+func TestWebhook_FindWebhookBegin_NormalizedCanvas(t *testing.T) {
+ canvas := makeWebhookCanvas("c1", "u-1", "Webhook", nil)
+ normalized := dslpkg.NormalizeForCanvas(canvas.DSL)
+ params := findWebhookBegin(normalized)
+ if params == nil || params["mode"] != "Webhook" {
+ t.Fatalf("findWebhookBegin(normalized canvas) = %v, want Webhook params", params)
+ }
+}
+
// ---------- Regression tests for issues raised in code review ----------
type webhookReadErrorCase struct {
@@ -918,7 +1142,7 @@ func assertWebhookRejectsBodyReadError(t *testing.T, request webhookReadErrorCas
},
})
loader := &fakeCanvasLoader{canvas: cv}
- h := &AgentHandler{loader: loader}
+ h := newWebhookTestAgentHandler(loader)
c, w := webhookCtx("POST", path, "", request.contentType)
// Exercise the stream limit, not the Content-Length pre-check.
c.Request.ContentLength = -1
@@ -1028,7 +1252,7 @@ func TestWebhook_MultipartReturns501(t *testing.T) {
"execution_mode": "Immediately",
"response": map[string]any{"status": 200},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook",
"--boundary\r\nContent-Disposition: form-data; name=\"k\"\r\n\r\nv\r\n--boundary--\r\n",
"multipart/form-data; boundary=boundary")
@@ -1055,7 +1279,7 @@ func TestWebhook_ContentTypeMismatchReturns102(t *testing.T) {
"execution_mode": "Immediately",
"response": map[string]any{"status": 200},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
// text/plain where the config demands application/json.
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", "raw body", "text/plain")
@@ -1084,7 +1308,7 @@ func TestWebhook_ContentTypesEmptyAllowsAnything(t *testing.T) {
"response": map[string]any{"status": 200},
})
loader := &fakeCanvasLoader{canvas: cv}
- h := &AgentHandler{loader: loader}
+ h := newWebhookTestAgentHandler(loader)
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{"k":"v"}`, "text/plain")
h.Webhook(c)
@@ -1107,7 +1331,7 @@ func TestWebhook_ContentTypeMissingHeaderRejected(t *testing.T) {
"execution_mode": "Immediately",
"response": map[string]any{"status": 200},
})
- h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
+ h := newWebhookTestAgentHandler(&fakeCanvasLoader{canvas: cv})
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook", `{"k":"v"}`, "")
// ↑ "" content-type means the header is absent. gin will not
// produce a default Content-Type on a POST so this is a clean
diff --git a/internal/handler/agent_webhook_workflow_test.go b/internal/handler/agent_webhook_workflow_test.go
index 37ecb13c98..545ce991e7 100644
--- a/internal/handler/agent_webhook_workflow_test.go
+++ b/internal/handler/agent_webhook_workflow_test.go
@@ -76,7 +76,7 @@ func TestWebhookHeaderReachesDownstreamMessage(t *testing.T) {
"obj": map[string]any{"component_name": "Message", "params": map[string]any{"content": "{{begin@headers." + field + "}}"}},
"upstream": []string{"begin"},
}
- h := &AgentHandler{loader: &webhookWorkflowLoader{&fakeCanvasLoader{canvas: cv}}}
+ h := newWebhookTestAgentHandler(&webhookWorkflowLoader{&fakeCanvasLoader{canvas: cv}})
h.webhookTraceAppender = func(context.Context, string, time.Time, canvas.RunEvent) {}
c, w := webhookCtx("POST", "/api/v1/agents/c1/webhook/test", `{}`, "application/json")
c.Request.Header.Set(field, "request-123")
diff --git a/internal/router/agent_routes.go b/internal/router/agent_routes.go
index e9bf5c4c03..02d06becbf 100644
--- a/internal/router/agent_routes.go
+++ b/internal/router/agent_routes.go
@@ -79,14 +79,11 @@ func RegisterAgentRoutes(g *gin.RouterGroup, h *handler.AgentHandler) {
// Logs and webhook.
g.GET("/:canvas_id/logs/:message_id", h.GetAgentLogs)
g.GET("/:canvas_id/webhook/logs", h.GetAgentWebhookLogs)
- // Webhook trigger endpoints. The Python agent API
- // (api/apps/restful_apis/agent_api.py:1563-1564) registers six
- // HTTP methods on a single path. Gin has no Match() helper, so we
- // register each verb explicitly via registerAnyMethod. The handler
- // is identical for all six; semantics differ only by
- // c.Request.Method.
- registerAnyMethod(g, "/:canvas_id/webhook", h.Webhook)
+ // The test trigger remains authenticated. Production triggers live on the
+ // public API group and use per-user webhook credentials.
registerAnyMethod(g, "/:canvas_id/webhook/test", h.Webhook)
+ g.POST("/:canvas_id/webhook/credentials", h.CreateWebhookCredential)
+ g.DELETE("/:canvas_id/webhook/credentials", h.RevokeWebhookCredential)
// Top-level actions (no canvas id in path).
// NOTE: `/chat/completion` (singular) is intentionally NOT registered.
@@ -98,6 +95,16 @@ func RegisterAgentRoutes(g *gin.RouterGroup, h *handler.AgentHandler) {
g.POST("/test_db_connection", h.TestDBConnection)
}
+// RegisterPublicAgentWebhookRoutes registers external webhook triggers on
+// the public API group. Each request is authenticated by its per-user
+// credential and rechecked against current membership and run permission.
+func RegisterPublicAgentWebhookRoutes(g *gin.RouterGroup, h *handler.AgentHandler) {
+ if g == nil || h == nil {
+ return
+ }
+ registerAnyMethod(g, "/:canvas_id/webhook", h.Webhook)
+}
+
// RegisterAgentCancelRoutes registers ordinary Agent session cancellation on
// the existing /api/v1/tasks URI. The path is retained for clients, while the
// parameter and all runtime semantics are session-scoped.
diff --git a/internal/router/agent_routes_test.go b/internal/router/agent_routes_test.go
index ed6e56ab66..acbeec1c67 100644
--- a/internal/router/agent_routes_test.go
+++ b/internal/router/agent_routes_test.go
@@ -57,9 +57,11 @@ func TestAgentRoutesRegistered(t *testing.T) {
{http.MethodDelete, "/api/v1/agents/abc/versions/v1"},
{http.MethodPost, "/api/v1/agents/abc/versions/v1/apply"},
{http.MethodPost, "/api/v1/agents/abc/reset"},
+ {http.MethodPost, "/api/v1/agents/abc/webhook/credentials"},
+ {http.MethodDelete, "/api/v1/agents/abc/webhook/credentials"},
}
- if len(cases) != 12 {
- t.Fatalf("expected 12 routes, listed %d", len(cases))
+ if len(cases) != 14 {
+ t.Fatalf("expected 14 routes, listed %d", len(cases))
}
for _, c := range cases {
w := httptest.NewRecorder()
@@ -73,6 +75,21 @@ func TestAgentRoutesRegistered(t *testing.T) {
}
}
+func TestPublicAgentWebhookRouteRegistered(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ RegisterPublicAgentWebhookRoutes(engine.Group("/api/v1/agents"), &handler.AgentHandler{})
+
+ for _, method := range []string{http.MethodPost, http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead} {
+ response := httptest.NewRecorder()
+ request := httptest.NewRequest(method, "/api/v1/agents/agent-1/webhook", nil)
+ engine.ServeHTTP(response, request)
+ if response.Code == http.StatusNotFound {
+ t.Errorf("%s production webhook route was not registered", method)
+ }
+ }
+}
+
// TestAgentRoutes_NilSafety makes sure the helper tolerates the "no
// handler yet" wiring case. A nil group or nil handler is a no-op so
// upstream config bugs surface as missing routes, not nil-deref panics.
diff --git a/internal/router/router.go b/internal/router/router.go
index 697a4b7c31..de9a1f1af2 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -191,6 +191,8 @@ func (r *Router) Setup(engine *gin.Engine) {
apiNoAuth.GET("/dify/retrieval/health", r.difyRetrievalHandler.HealthCheck)
+ RegisterPublicAgentWebhookRoutes(apiNoAuth.Group("/agents"), r.agentHandler)
+
RegisterEENoAuthRouter(apiNoAuth, r)
}
diff --git a/internal/service/agent_webhook_credential.go b/internal/service/agent_webhook_credential.go
new file mode 100644
index 0000000000..457299157d
--- /dev/null
+++ b/internal/service/agent_webhook_credential.go
@@ -0,0 +1,157 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package service
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "strings"
+
+ "gorm.io/gorm"
+
+ "ragflow/internal/common"
+ "ragflow/internal/dao"
+ "ragflow/internal/entity"
+ "ragflow/internal/permission"
+)
+
+var ErrInvalidAgentWebhookCredential = errors.New("invalid agent webhook credential")
+
+// AgentWebhookCredentialService issues and resolves bearer capabilities for
+// external Agent webhook callers.
+type AgentWebhookCredentialService struct {
+ db *gorm.DB
+}
+
+func NewAgentWebhookCredentialService(db *gorm.DB) *AgentWebhookCredentialService {
+ return &AgentWebhookCredentialService{db: db}
+}
+
+// Issue creates or rotates the credential for the authenticated user and the
+// canvas tenant. The raw token is returned once; only its SHA-256 hash is saved.
+func (s *AgentWebhookCredentialService) Issue(ctx context.Context, subject permission.Subject, canvas *entity.UserCanvas) (string, error) {
+ if s == nil || s.db == nil || canvas == nil {
+ return "", gorm.ErrInvalidDB
+ }
+ userID := strings.TrimSpace(subject.UserID)
+ tenantID := canvas.EffectiveTenantID()
+ if userID == "" || tenantID == "" || strings.TrimSpace(canvas.ID) == "" {
+ return "", permission.ErrInvalidSubject
+ }
+ subject.TenantID = tenantID
+ checker := permission.NewDatabaseChecker(s.db)
+ if err := checker.CheckTenant(ctx, subject, tenantID, permission.TenantMember); err != nil {
+ return "", err
+ }
+ if err := checker.CheckResource(ctx, subject, permission.ResourceRef{
+ Kind: permission.ResourceKindCanvas,
+ ID: canvas.ID,
+ }, permission.OperationRun); err != nil {
+ return "", err
+ }
+
+ raw := make([]byte, 32)
+ if _, err := rand.Read(raw); err != nil {
+ return "", err
+ }
+ token := base64.RawURLEncoding.EncodeToString(raw)
+ tokenHash := hashAgentWebhookCredential(token)
+ credential := &entity.AgentWebhookCredential{
+ ID: common.GenerateToken(),
+ CanvasID: canvas.ID,
+ UserID: userID,
+ TenantID: tenantID,
+ TokenHash: tokenHash,
+ }
+ if err := dao.SaveAgentWebhookCredential(ctx, s.db, credential); err != nil {
+ return "", err
+ }
+ return token, nil
+}
+
+// Resolve validates a raw webhook capability, confirms its canvas tenant has
+// not changed, and rechecks the bound user's membership and run permission.
+func (s *AgentWebhookCredentialService) Resolve(ctx context.Context, canvasID, token string) (*entity.AgentWebhookCredential, error) {
+ if s == nil || s.db == nil || strings.TrimSpace(canvasID) == "" {
+ return nil, ErrInvalidAgentWebhookCredential
+ }
+ if len(token) != 43 {
+ return nil, ErrInvalidAgentWebhookCredential
+ }
+ decoded, err := base64.RawURLEncoding.DecodeString(token)
+ if err != nil || len(decoded) != 32 || base64.RawURLEncoding.EncodeToString(decoded) != token {
+ return nil, ErrInvalidAgentWebhookCredential
+ }
+ credential, err := dao.GetActiveAgentWebhookCredential(ctx, s.db, canvasID, hashAgentWebhookCredential(token))
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, ErrInvalidAgentWebhookCredential
+ }
+ return nil, fmt.Errorf("load agent webhook credential: %w", err)
+ }
+
+ var canvas entity.UserCanvas
+ if err := s.db.WithContext(ctx).Where("id = ?", canvasID).Take(&canvas).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, ErrInvalidAgentWebhookCredential
+ }
+ return nil, fmt.Errorf("load webhook canvas: %w", err)
+ }
+ if canvas.EffectiveTenantID() != credential.TenantID {
+ return nil, ErrInvalidAgentWebhookCredential
+ }
+ subject := permission.Subject{UserID: credential.UserID, TenantID: credential.TenantID}
+ checker := permission.NewDatabaseChecker(s.db)
+ if err := checker.CheckTenant(ctx, subject, credential.TenantID, permission.TenantMember); err != nil {
+ if errors.Is(err, permission.ErrMembershipNotFound) || errors.Is(err, permission.ErrPermissionDenied) || errors.Is(err, permission.ErrInvalidSubject) {
+ return nil, ErrInvalidAgentWebhookCredential
+ }
+ return nil, fmt.Errorf("check webhook tenant membership: %w", err)
+ }
+ if err := checker.CheckResource(ctx, subject, permission.ResourceRef{
+ Kind: permission.ResourceKindCanvas,
+ ID: canvasID,
+ }, permission.OperationRun); err != nil {
+ if errors.Is(err, permission.ErrMembershipNotFound) || errors.Is(err, permission.ErrPermissionDenied) || errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrInvalidSubject) {
+ return nil, ErrInvalidAgentWebhookCredential
+ }
+ return nil, fmt.Errorf("check webhook run permission: %w", err)
+ }
+ return credential, nil
+}
+
+// Revoke removes the authenticated user's ability to trigger this canvas with
+// their webhook credential. The operation is idempotent.
+func (s *AgentWebhookCredentialService) Revoke(ctx context.Context, canvasID, userID string) error {
+ if s == nil || s.db == nil {
+ return gorm.ErrInvalidDB
+ }
+ if strings.TrimSpace(canvasID) == "" || strings.TrimSpace(userID) == "" {
+ return permission.ErrInvalidSubject
+ }
+ return dao.RevokeAgentWebhookCredential(ctx, s.db, canvasID, userID)
+}
+
+func hashAgentWebhookCredential(token string) string {
+ hash := sha256.Sum256([]byte(token))
+ return hex.EncodeToString(hash[:])
+}
diff --git a/internal/service/agent_webhook_credential_test.go b/internal/service/agent_webhook_credential_test.go
new file mode 100644
index 0000000000..3426fd1108
--- /dev/null
+++ b/internal/service/agent_webhook_credential_test.go
@@ -0,0 +1,106 @@
+package service
+
+import (
+ "errors"
+ "testing"
+
+ "github.com/glebarez/sqlite"
+ "gorm.io/gorm"
+
+ "ragflow/internal/entity"
+ "ragflow/internal/permission"
+)
+
+func TestAgentWebhookCredentialUsesBoundPrincipalAndCanBeRotated(t *testing.T) {
+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{TranslateError: true})
+ if err != nil {
+ t.Fatalf("open sqlite: %v", err)
+ }
+ if err := db.AutoMigrate(&entity.UserTenant{}, &entity.UserCanvas{}, &entity.AgentWebhookCredential{}); err != nil {
+ t.Fatalf("migrate webhook credential tables: %v", err)
+ }
+
+ joined := entity.TenantMembershipStatusJoined
+ tenantID := "tenant-1"
+ if err := db.Create(&entity.UserTenant{
+ ID: "membership-1", UserID: "caller-1", TenantID: tenantID, Role: "normal", Status: &joined,
+ }).Error; err != nil {
+ t.Fatalf("seed tenant membership: %v", err)
+ }
+ canvas := &entity.UserCanvas{
+ ID: "canvas-1", UserID: "owner-1", TenantID: &tenantID,
+ Permission: string(entity.TenantPermissionTeam), CanvasCategory: "agent_canvas",
+ }
+ if err := db.Create(canvas).Error; err != nil {
+ t.Fatalf("seed canvas: %v", err)
+ }
+
+ svc := NewAgentWebhookCredentialService(db)
+ firstToken, err := svc.Issue(t.Context(), permission.Subject{UserID: "caller-1"}, canvas)
+ if err != nil {
+ t.Fatalf("issue credential: %v", err)
+ }
+ if len(firstToken) != 43 {
+ t.Fatalf("credential length = %d, want 43-character base64url token", len(firstToken))
+ }
+ var stored entity.AgentWebhookCredential
+ if err := db.Where("canvas_id = ? AND user_id = ?", canvas.ID, "caller-1").Take(&stored).Error; err != nil {
+ t.Fatalf("load stored credential: %v", err)
+ }
+ if stored.TokenHash == firstToken || len(stored.TokenHash) != 64 {
+ t.Fatalf("stored hash = %q, raw token must not be stored", stored.TokenHash)
+ }
+
+ resolved, err := svc.Resolve(t.Context(), canvas.ID, firstToken)
+ if err != nil {
+ t.Fatalf("resolve credential: %v", err)
+ }
+ if resolved.UserID != "caller-1" || resolved.TenantID != tenantID {
+ t.Fatalf("resolved principal = (%q, %q), want (caller-1, %q)", resolved.UserID, resolved.TenantID, tenantID)
+ }
+
+ secondToken, err := svc.Issue(t.Context(), permission.Subject{UserID: "caller-1"}, canvas)
+ if err != nil {
+ t.Fatalf("rotate credential: %v", err)
+ }
+ if secondToken == firstToken {
+ t.Fatal("rotating a credential returned the same token")
+ }
+ if _, err := svc.Resolve(t.Context(), canvas.ID, firstToken); !errors.Is(err, ErrInvalidAgentWebhookCredential) {
+ t.Fatalf("old token resolution error = %v, want invalid credential", err)
+ }
+ if _, err := svc.Resolve(t.Context(), canvas.ID, secondToken); err != nil {
+ t.Fatalf("resolve rotated token: %v", err)
+ }
+ if _, err := svc.Resolve(t.Context(), "different-canvas", secondToken); !errors.Is(err, ErrInvalidAgentWebhookCredential) {
+ t.Fatalf("credential used for another canvas error = %v, want invalid credential", err)
+ }
+ if err := db.Model(&entity.UserCanvas{}).Where("id = ?", canvas.ID).
+ Update("permission", string(entity.TenantPermissionMe)).Error; err != nil {
+ t.Fatalf("make canvas private: %v", err)
+ }
+ if _, err := svc.Resolve(t.Context(), canvas.ID, secondToken); !errors.Is(err, ErrInvalidAgentWebhookCredential) {
+ t.Fatalf("revoked run permission error = %v, want invalid credential", err)
+ }
+ if err := db.Model(&entity.UserCanvas{}).Where("id = ?", canvas.ID).
+ Update("permission", string(entity.TenantPermissionTeam)).Error; err != nil {
+ t.Fatalf("restore tenant sharing: %v", err)
+ }
+
+ removed := entity.TenantMembershipStatusRemoved
+ if err := db.Model(&entity.UserTenant{}).Where("user_id = ? AND tenant_id = ?", "caller-1", tenantID).Update("status", removed).Error; err != nil {
+ t.Fatalf("remove caller membership: %v", err)
+ }
+ if _, err := svc.Resolve(t.Context(), canvas.ID, secondToken); !errors.Is(err, ErrInvalidAgentWebhookCredential) {
+ t.Fatalf("removed member token resolution error = %v, want invalid credential", err)
+ }
+ if err := svc.Revoke(t.Context(), canvas.ID, "caller-1"); err != nil {
+ t.Fatalf("revoke credential: %v", err)
+ }
+ if err := svc.Revoke(t.Context(), canvas.ID, "caller-1"); err != nil {
+ t.Fatalf("repeat revoke: %v", err)
+ }
+ if _, err := svc.Resolve(t.Context(), canvas.ID, secondToken); !errors.Is(err, ErrInvalidAgentWebhookCredential) {
+ t.Fatalf("revoked token resolution error = %v, want invalid credential", err)
+ }
+}
diff --git a/web/src/hooks/use-agent-request.ts b/web/src/hooks/use-agent-request.ts
index b68961fc0f..282d196530 100644
--- a/web/src/hooks/use-agent-request.ts
+++ b/web/src/hooks/use-agent-request.ts
@@ -28,6 +28,7 @@ import {
IBuiltinPipelineListResponse,
IFlow,
IFlowTemplate,
+ IAgentWebhookCredential,
IPipeLineListRequest,
ITraceData,
IWebhookTrace,
@@ -48,6 +49,8 @@ import agentService, {
fetchSharedTrace,
fetchTrace,
fetchWebhookTrace,
+ issueAgentWebhookCredential,
+ revokeAgentWebhookCredential,
updateAgent,
updateAgentTags,
uploadAgentFile,
@@ -89,6 +92,8 @@ export const enum AgentApiAction {
CancelDataflow = 'cancelDataflow',
CancelCanvas = 'cancelCanvas',
FetchWebhookTrace = 'fetchWebhookTrace',
+ CreateWebhookCredential = 'createWebhookCredential',
+ RevokeWebhookCredential = 'revokeWebhookCredential',
FetchSessionsByCanvasId = 'fetchSessionsByCanvasId',
FetchSessionById = 'fetchSessionById',
CreateAgentSession = 'createAgentSession',
@@ -1195,6 +1200,42 @@ export const useFetchWebhookTrace = (autoStart: boolean = true) => {
};
};
+export function useCreateAgentWebhookCredential() {
+ const { id } = useParams();
+ const { mutateAsync, isPending: loading } = useMutation({
+ mutationKey: [AgentApiAction.CreateWebhookCredential],
+ mutationFn: async () => {
+ if (!id) throw new Error('Agent ID is required');
+
+ const { data } = await issueAgentWebhookCredential(id);
+ if (data?.code !== 0 || !data?.data?.webhook_url) {
+ throw new Error(data?.message || 'Failed to create webhook URL');
+ }
+
+ return data.data as IAgentWebhookCredential;
+ },
+ });
+
+ return { createWebhookCredential: mutateAsync, loading };
+}
+
+export function useRevokeAgentWebhookCredential() {
+ const { id } = useParams();
+ const { mutateAsync, isPending: loading } = useMutation({
+ mutationKey: [AgentApiAction.RevokeWebhookCredential],
+ mutationFn: async () => {
+ if (!id) throw new Error('Agent ID is required');
+
+ const { data } = await revokeAgentWebhookCredential(id);
+ if (data?.code !== 0) {
+ throw new Error(data?.message || 'Failed to revoke webhook URL');
+ }
+ },
+ });
+
+ return { revokeWebhookCredential: mutateAsync, loading };
+}
+
export function useCreateAgentSession() {
const queryClient = useQueryClient();
diff --git a/web/src/interfaces/database/agent.ts b/web/src/interfaces/database/agent.ts
index 8012af63c6..facf4a5cc9 100644
--- a/web/src/interfaces/database/agent.ts
+++ b/web/src/interfaces/database/agent.ts
@@ -354,3 +354,8 @@ export interface IWebhookTrace {
next_since_ts: number;
finished: boolean;
}
+
+export interface IAgentWebhookCredential {
+ credential: string;
+ webhook_url: string;
+}
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index 1ebc2d8465..745f2ac750 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -3811,6 +3811,20 @@ Important structured information may include: names, dates, locations, events, k
variableAssignerParameterMissing: 'Parameter is required',
webhook: {
name: 'Webhook',
+ endpoint: 'Endpoint',
+ testEndpoint: 'Test endpoint',
+ personalUrl: 'Personal webhook URL',
+ credentialDescription:
+ 'Anyone with this URL can run the agent as you. Keep it secret; creating a new URL invalidates the old one.',
+ createCredential: 'Create or rotate URL',
+ revokeCredential: 'Revoke my URL',
+ credentialCreated:
+ 'Webhook URL created. Copy and store it now; it will not be shown again after you leave this page.',
+ credentialRevoked: 'Webhook URL revoked.',
+ credentialRequestFailed: 'Unable to update the webhook URL.',
+ revokeCredentialTitle: 'Revoke your webhook URL?',
+ revokeCredentialDescription:
+ 'Requests using this URL will stop working. You can create a new URL at any time.',
methods: 'Methods',
contentTypes: 'Content types',
security: 'Security',
diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.ts
index 8ca3903b1b..ccde9fbb3d 100644
--- a/web/src/locales/zh.ts
+++ b/web/src/locales/zh.ts
@@ -3302,6 +3302,20 @@ Tokenizer 会根据所选方式将内容存储为对应的数据结构。`,
variableAssignerParameterMissing: '请填写参数',
webhook: {
name: '网络钩子',
+ endpoint: '接口地址',
+ testEndpoint: '测试接口地址',
+ personalUrl: '个人 Webhook URL',
+ credentialDescription:
+ '持有此链接即可按你的权限运行 Agent,请妥善保管;重新生成会使旧链接失效。',
+ createCredential: '生成或轮换 URL',
+ revokeCredential: '撤销我的 URL',
+ credentialCreated:
+ 'Webhook URL 已生成,请立即复制保存;离开页面后将无法再次查看。',
+ credentialRevoked: 'Webhook URL 已撤销。',
+ credentialRequestFailed: '更新 Webhook URL 失败。',
+ revokeCredentialTitle: '撤销 Webhook URL?',
+ revokeCredentialDescription:
+ '使用此 URL 的请求将立即失效。你可以随时重新生成 URL。',
methods: '方法',
contentTypes: '内容类型',
security: '安全配置',
diff --git a/web/src/pages/agent/canvas/node/begin-node.tsx b/web/src/pages/agent/canvas/node/begin-node.tsx
index b469f78c8a..e3ba736de3 100644
--- a/web/src/pages/agent/canvas/node/begin-node.tsx
+++ b/web/src/pages/agent/canvas/node/begin-node.tsx
@@ -61,7 +61,7 @@ function InnerBeginNode({
)}
{isWebhookMode ? (
<LabelCard className="mt-2 flex gap-1 items-center">
- <span className="font-bold">URL</span>
+ <span className="font-bold">{t('flow.webhook.endpoint')}</span>
<span className="flex-1 truncate">{url}</span>
</LabelCard>
) : (
diff --git a/web/src/pages/agent/form/begin-form/webhook/index.tsx b/web/src/pages/agent/form/begin-form/webhook/index.tsx
index b852922c94..af52cf41c6 100644
--- a/web/src/pages/agent/form/begin-form/webhook/index.tsx
+++ b/web/src/pages/agent/form/begin-form/webhook/index.tsx
@@ -4,13 +4,19 @@ import NumberInput from '@/components/originui/number-input';
import { SelectWithSearch } from '@/components/originui/select-with-search';
import { RAGFlowFormItem } from '@/components/ragflow-form';
import { Label } from '@/components/ui/label';
+import { Modal } from '@/components/ui/modal/modal';
import { MultiSelect } from '@/components/ui/multi-select';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
-import { useBuildWebhookUrl } from '@/pages/agent/hooks/use-build-webhook-url';
+import { Button } from '@/components/ui/button';
+import message from '@/components/ui/message';
+import {
+ useCreateAgentWebhookCredential,
+ useRevokeAgentWebhookCredential,
+} from '@/hooks/use-agent-request';
import { buildOptions } from '@/utils/form';
import { upperFirst } from 'lodash';
-import { useCallback } from 'react';
+import { useCallback, useState } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import {
@@ -40,6 +46,11 @@ const RequestLimitMap = {
export function WebHook() {
const { t } = useTranslation();
const form = useFormContext();
+ const [personalWebhookUrl, setPersonalWebhookUrl] = useState('');
+ const { createWebhookCredential, loading: creatingCredential } =
+ useCreateAgentWebhookCredential();
+ const { revokeWebhookCredential, loading: revokingCredential } =
+ useRevokeAgentWebhookCredential();
const rateLimitPer = useWatch({
name: 'security.rate_limit.per',
@@ -50,11 +61,71 @@ export function WebHook() {
return RequestLimitMap[rateLimitPer as keyof typeof RequestLimitMap] ?? 100;
}, []);
- const text = useBuildWebhookUrl();
+ const handleCreateCredential = useCallback(async () => {
+ try {
+ const credential = await createWebhookCredential();
+ setPersonalWebhookUrl(
+ new URL(credential.webhook_url, window.location.origin).toString(),
+ );
+ message.success(t('flow.webhook.credentialCreated'));
+ } catch {
+ message.error(t('flow.webhook.credentialRequestFailed'));
+ }
+ }, [createWebhookCredential, t]);
+
+ const revokeCredential = useCallback(async () => {
+ try {
+ await revokeWebhookCredential();
+ setPersonalWebhookUrl('');
+ message.success(t('flow.webhook.credentialRevoked'));
+ } catch {
+ message.error(t('flow.webhook.credentialRequestFailed'));
+ }
+ }, [revokeWebhookCredential, t]);
+
+ const handleRevokeCredential = useCallback(() => {
+ Modal.confirm({
+ title: t('flow.webhook.revokeCredentialTitle'),
+ content: t('flow.webhook.revokeCredentialDescription'),
+ okText: t('common.confirm'),
+ cancelText: t('common.cancel'),
+ okButtonClassName: 'bg-state-error hover:bg-state-error/90',
+ onOk: revokeCredential,
+ });
+ }, [revokeCredential, t]);
return (
<>
- <CopyToClipboardWithText text={text}></CopyToClipboardWithText>
+ <section className="space-y-3 rounded-md border border-border-button bg-bg-card p-3">
+ <div>
+ <Label>{t('flow.webhook.personalUrl')}</Label>
+ <p className="mt-1 text-xs text-text-secondary">
+ {t('flow.webhook.credentialDescription')}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ type="button"
+ size="sm"
+ loading={creatingCredential}
+ onClick={handleCreateCredential}
+ >
+ {t('flow.webhook.createCredential')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ loading={revokingCredential}
+ onClick={handleRevokeCredential}
+ >
+ {t('flow.webhook.revokeCredential')}
+ </Button>
+ </div>
+ {personalWebhookUrl && (
+ <CopyToClipboardWithText text={personalWebhookUrl} />
+ )}
+ </section>
<RAGFlowFormItem name="methods" label={t('flow.webhook.methods')}>
{(field) => (
<MultiSelect
diff --git a/web/src/pages/agent/webhook-sheet/index.tsx b/web/src/pages/agent/webhook-sheet/index.tsx
index 42966655c3..7ab9d788e2 100644
--- a/web/src/pages/agent/webhook-sheet/index.tsx
+++ b/web/src/pages/agent/webhook-sheet/index.tsx
@@ -56,7 +56,9 @@ const WebhookSheet = ({ hideModal }: RunSheetProps) => {
</SheetHeader>
<div className="space-y-2">
- <div className="text-sm font-medium">Webhook URL:</div>
+ <div className="text-sm font-medium">
+ {t('flow.webhook.testEndpoint')}:
+ </div>
<CopyToClipboardWithText text={text}></CopyToClipboardWithText>
</div>
diff --git a/web/src/services/agent-service.ts b/web/src/services/agent-service.ts
index ad10f0caea..4a129dfee6 100644
--- a/web/src/services/agent-service.ts
+++ b/web/src/services/agent-service.ts
@@ -235,6 +235,12 @@ export const fetchWebhookTrace = (
return request.get(api.fetchWebhookTrace(id), { params: params });
};
+export const issueAgentWebhookCredential = (id: string) =>
+ request.post(api.issueAgentWebhookCredential(id), { data: {} });
+
+export const revokeAgentWebhookCredential = (id: string) =>
+ request.delete(api.revokeAgentWebhookCredential(id));
+
export function createAgentSession({ id, name }: { id: string; name: string }) {
return request.post(api.createAgentSession(id), { data: { name } });
}
diff --git a/web/src/utils/api.ts b/web/src/utils/api.ts
index 312fa1e7e9..6c41060c56 100644
--- a/web/src/utils/api.ts
+++ b/web/src/utils/api.ts
@@ -401,6 +401,10 @@ export default {
},
downloadFile: `${restAPIv1}/agents/download`,
testWebhook: (id: string) => `${restAPIv1}/agents/${id}/webhook/test`,
+ issueAgentWebhookCredential: (id: string) =>
+ `${restAPIv1}/agents/${id}/webhook/credentials`,
+ revokeAgentWebhookCredential: (id: string) =>
+ `${restAPIv1}/agents/${id}/webhook/credentials`,
fetchWebhookTrace: (id: string) => `${restAPIv1}/agents/${id}/webhook/logs`,
// explore