Skip to content

fix: require explicit anonymous webhook access - #14890

Merged
yuzhichang merged 6 commits into
infiniflow:mainfrom
ai-mountain:fix/agent-webhook-security
Jun 28, 2026
Merged

yuzhichang merged 6 commits into
infiniflow:mainfrom
ai-mountain:fix/agent-webhook-security

Conversation

@ai-mountain

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes #14882

Agent webhook execution currently fails open when the saved webhook security block is missing/empty, or when auth_type is set to none. This allows unauthenticated webhook invocation without an explicit operator opt-in.

This PR makes anonymous webhook access explicit:

  • Rejects missing or empty webhook security config.
  • Requires allow_anonymous: true when auth_type is none.
  • Preserves explicit anonymous webhooks by having the frontend serialize allow_anonymous: true when the user selects None auth.
  • Updates webhook unit tests to cover both denied implicit-anonymous configs and allowed explicit-anonymous configs.

Type of change

  • Bug Fix
  • Security hardening
  • Test

Tests

  • ZHIPU_AI_API_KEY=dummy uv run python -m pytest --confcutdir=test/testcases/test_web_api/test_agent_app test/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.py
  • uv run ruff check api/apps/restful_apis/agent_api.py test/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.py
  • npm exec eslint src/pages/agent/utils.ts src/pages/agent/form/begin-form/schema.ts

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label May 13, 2026
@coderabbitai

coderabbitai Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Webhook routes are hardened: missing/empty webhook security now rejects requests, anonymous access requires explicit allow_anonymous, /webhook/test requires login + ownership, defaults for max body size and rate limit are applied, and frontend + tests updated accordingly.

Changes

Webhook Security Hardening: Fail-Safe Default

Layer / File(s) Summary
Route split and shared implementation
api/apps/restful_apis/agent_api.py
Introduce _webhook_impl(agent_id, is_test); /agents/<agent_id>/webhook delegates with is_test=False; /agents/<agent_id>/webhook/test requires login and ownership, delegates with is_test=True.
Security validation and helpers
api/apps/restful_apis/agent_api.py
Add _is_truthy and _allow_anonymous_webhook; validate_webhook_security raises when security_cfg is missing/empty or not a dict; auth_type=="none" requires explicit allow_anonymous.
Body-size and rate-limit handling
api/apps/restful_apis/agent_api.py
When max_body_size or rate_limit are absent, _validate_max_body_size and _validate_rate_limit now set defaults ("10MB" and {limit:60, per:"minute"}) instead of returning early.
Test helper and webhook test updates
test/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.py
Add _anonymous_security(**overrides) and refactor many webhook unit tests to use it; update deferred/SSE/background tests to call webhook_test where appropriate.
Frontend schema, transform, i18n, and UI
web/src/pages/agent/form/begin-form/schema.ts, web/src/pages/agent/utils.ts, web/src/pages/agent/form/begin-form/webhook/auth.tsx, web/src/locales/en.ts
Add optional security.allow_anonymous to BeginFormSchema; transformBeginParams preserves allow_anonymous for auth_type: none; UI renders a Switch for allow_anonymous; add i18n keys for label and tooltip.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#14330: Prior changes to webhook handlers that modified /agents/<agent_id>/webhook and related logic.

Suggested labels

🌈 python, 🧰 typescript, 🐖api, size:XS

Poem

🐰 I found a webhook wide and bright,
No door or guard to block the night.
A tiny switch now keeps the key,
The rabbit hops, "That's safe for me." 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.34% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: require explicit anonymous webhook access' accurately and concisely describes the main change: enforcing explicit opt-in for anonymous webhook access through the allow_anonymous flag.
Description check ✅ Passed The PR description comprehensively covers the problem (issue #14882), the solution approach, change types (Bug Fix, Security hardening, Test), and lists executed tests and linters.
Linked Issues check ✅ Passed All key requirements from #14882 are addressed: deny missing/empty security config, require allow_anonymous:true for auth_type=none, add explicit allow_anonymous field to schema, update tests for both denied and allowed cases, apply default rate limits/max_body_size, require authentication for /webhook/test.
Out of Scope Changes check ✅ Passed All changes directly support the security hardening objectives: schema updates add allow_anonymous field, frontend logic conditionally sets it for None auth type, backend validation enforces the requirement, tests cover both implicit and explicit scenarios.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
api/apps/restful_apis/agent_api.py (2)

1104-1106: ⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy lift

/webhook/test is reachable anonymously — violates a stated PR objective.

Both /agents/<agent_id>/webhook and /agents/<agent_id>/webhook/test share the same handler with no @login_required / owner check. The is_test branch only changes trace logging; if the canvas owner configures allow_anonymous: true (which the frontend now does whenever auth_type=None is selected), the test endpoint is also publicly callable. Issue #14882 explicitly requires the test endpoint to be authenticated and bound to the canvas owner/tenant because it is a development-time surface.

Suggested approach: split the test route into its own login-required, owner-scoped handler that delegates to the shared implementation. Example:

🔒 Proposed fix — separate authenticated handler for the test endpoint
-@manager.route("/agents/<agent_id>/webhook", methods=["POST", "GET", "PUT", "PATCH", "DELETE", "HEAD"])  # noqa: F821
-@manager.route("/agents/<agent_id>/webhook/test",methods=["POST", "GET", "PUT", "PATCH", "DELETE", "HEAD"],)  # noqa: F821
-async def webhook(agent_id: str):
-    is_test = request.path.startswith(f"/api/v1/agents/{agent_id}/webhook/test")
+@manager.route("/agents/<agent_id>/webhook", methods=["POST", "GET", "PUT", "PATCH", "DELETE", "HEAD"])  # noqa: F821
+async def webhook(agent_id: str):
+    return await _webhook_impl(agent_id, is_test=False)
+
+@manager.route("/agents/<agent_id>/webhook/test", methods=["POST", "GET", "PUT", "PATCH", "DELETE", "HEAD"])  # noqa: F821
+@login_required
+@add_tenant_id_to_kwargs
+@_require_canvas_owner_sync
+async def webhook_test(agent_id: str, tenant_id: str):
+    return await _webhook_impl(agent_id, is_test=True)
+
+async def _webhook_impl(agent_id: str, is_test: bool):
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/agent_api.py` around lines 1104 - 1106, The
/agents/<agent_id>/webhook/test endpoint is currently routed to the same async
webhook(agent_id: str) handler and can be invoked anonymously when
canvas.allow_anonymous is true; split the test route into a separate handler
that enforces authentication and owner/tenant scoping and then delegates to the
shared implementation. Concretely: keep the existing webhook(agent_id)
implementation (with its is_test branch) but add a new function (e.g.,
webhook_test(agent_id)) decorated with
manager.route("/agents/<agent_id>/webhook/test", methods=[...]) plus
`@login_required` (or the project’s auth decorator) and an explicit owner/tenant
check (verify_owner_or_tenant or the existing owner-scoping helper) that sets
is_test=True before calling the shared webhook logic; ensure the new handler
does not rely on canvas.allow_anonymous and returns the same responses by
delegating to the original webhook implementation.

1189-1211: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Defaults for max_body_size and rate_limit are not applied to anonymous-allowed webhooks.

Issue #14882 calls out: "Ensure default rate limits and max_body_size still apply for anonymous-allowed webhooks (currently bypassed when security_cfg is empty)." Today an operator can publish a webhook with security = {"auth_type": "none", "allow_anonymous": true} and no body-size or rate-limit settings, and both validators short-circuit on the first line:

  • Line 1192: if not max_size: return
  • Line 1237: if not rl: return

This means the explicit-opt-in path the PR introduces still has zero size/rate guardrails on a publicly reachable endpoint — exactly the abuse vector the linked issue wants to close. Apply server-enforced defaults (and the existing 10MB hard cap) whenever _allow_anonymous_webhook(security_cfg) is true.

🛡️ Proposed fix — fall back to defaults for anonymous webhooks
 async def _validate_max_body_size(security_cfg):
     """Check request size does not exceed max_body_size."""
-    max_size = security_cfg.get("max_body_size")
-    if not max_size:
-        return
+    max_size = security_cfg.get("max_body_size")
+    if not max_size:
+        if not _allow_anonymous_webhook(security_cfg):
+            return
+        max_size = "10MB"  # default cap for anonymous webhooks
 def _validate_rate_limit(security_cfg):
     """Simple in-memory rate limiting."""
-    rl = security_cfg.get("rate_limit")
-    if not rl:
-        return
+    rl = security_cfg.get("rate_limit")
+    if not rl:
+        if not _allow_anonymous_webhook(security_cfg):
+            return
+        rl = {"limit": 60, "per": "minute"}  # default for anonymous webhooks

Also applies to: 1234-1238

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/agent_api.py` around lines 1189 - 1211, The validators
currently return early when security_cfg lacks max_body_size or rate_limit,
which skips server defaults for anonymous-allowed webhooks; update
_validate_max_body_size and the rate-limit validator (the function that checks
"rate_limit") to detect when _allow_anonymous_webhook(security_cfg) is true and,
instead of returning, substitute the server-enforced defaults (e.g.,
DEFAULT_MAX_BODY_SIZE and DEFAULT_RATE_LIMIT) into security_cfg or local vars so
parsing and the 10MB hard cap (MAX_LIMIT) still run; keep the existing parsing
logic for units and the content_length check (request.content_length) and ensure
the same pattern is applied for the rate_limit path so anonymous webhooks
receive default guards even when fields are missing.
🧹 Nitpick comments (3)
api/apps/restful_apis/agent_api.py (2)

1144-1149: 💤 Low value

Truthy-helper accepts strings but not numeric 1/0.

Minor inconsistency: _is_truthy recognizes the string "1" but not the integer 1. If a DSL is hand-edited or generated from a YAML pipeline, allow_anonymous: 1 will be silently rejected even though the operator likely intended to enable it. Consider extending the check to cover ints, or document the constraint clearly.

 def _is_truthy(value):
     if isinstance(value, bool):
         return value
+    if isinstance(value, int):
+        return value == 1
     if isinstance(value, str):
         return value.strip().lower() in {"1", "true", "yes", "on"}
     return False
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/agent_api.py` around lines 1144 - 1149, The helper
function _is_truthy currently accepts bool and string values but rejects numeric
types, causing ints like 1/0 to be ignored; update _is_truthy to also handle
integer (and optionally other numeric) inputs by returning True for 1 and False
for 0 (and treat other numeric values as False or raise/ignore per existing
behavior), while keeping the existing bool and str branches intact so
hand-edited/generated YAML values like allow_anonymous: 1 are recognized.

1154-1188: ⚡ Quick win

Add logging for the new security-denial flow.

Per coding guideline **/*.py: Add logging for new flows, the newly added denial paths (empty security_cfg, missing allow_anonymous for auth_type=none, etc.) silently return a 400 with the exception text. Audit-friendly logging on rejection is important for a security-hardening change because operators will want to detect mis-configurations and probe traffic.

📝 Proposed fix — log denial at the route boundary
     try:
         security_config=webhook_cfg.get("security", {})
         await validate_webhook_security(security_config)
     except Exception as e:
+        logging.warning(
+            "Webhook security validation denied request: agent_id=%s path=%s remote=%s reason=%s",
+            agent_id, request.path, request.remote_addr, str(e),
+        )
         return get_data_error_result(code=RetCode.BAD_REQUEST,message=str(e)),RetCode.BAD_REQUEST

As per coding guidelines: **/*.py: Add logging for new flows.

Also applies to: 1362-1366

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/agent_api.py` around lines 1154 - 1188, The
validate_webhook_security function currently raises exceptions on denial paths
without logging; update validate_webhook_security to log audit-friendly
warnings/errors before each rejection (e.g., when security_cfg is
missing/invalid, when auth_type == "none" but
_allow_anonymous_webhook(security_cfg) is false, and when auth_type is
unsupported) using the module logger (obtain via logging.getLogger(__name__) or
the project’s standard logger) and include context details (auth_type, client
IP/header info if available, and a short reason) so operators can detect
misconfigurations and rejected webhook attempts; ensure logs are written
immediately before each raise call in validate_webhook_security and in any
helper validations it delegates to.
web/src/pages/agent/utils.ts (1)

442-444: ⚡ Quick win

Silent opt-in undermines the "explicit anonymous" intent — pair this with a UI confirmation.

This transform unconditionally sets allow_anonymous: true whenever the user picks auth_type = None, which means the backend's new "explicit opt-in" guard is satisfied without the user ever seeing the word "anonymous." Issue #14882 specifically asks the webhook UI to surface a warning (and ideally block save) when no auth/IP rule is set, so the opt-in is genuinely explicit. The transform itself is fine, but the corresponding warning/confirmation should live in the begin-form component before this serialization runs; otherwise the security model only reads as fail-safe at the wire level, not for the operator.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/agent/utils.ts` around lines 442 - 444, The transform
unconditionally sets nextSecurity.allow_anonymous when
params.security?.auth_type === WebhookSecurityAuthType.None which silently opts
users into "anonymous" — instead, add an explicit UI confirmation in the form
component that serializes these params (the begin-form / webhook begin-form
component) so the user must acknowledge a clear "allow anonymous access" warning
before the serializer runs; only set nextSecurity.allow_anonymous = true when
the form explicitly includes that confirmation flag (e.g., a checked "confirm
allow anonymous" field on the form model) and otherwise leave it false, and
ensure the serializer reads that explicit confirmation field from params
(alongside params.security and WebhookSecurityAuthType.None) before toggling
nextSecurity.allow_anonymous.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1104-1106: The /agents/<agent_id>/webhook/test endpoint is
currently routed to the same async webhook(agent_id: str) handler and can be
invoked anonymously when canvas.allow_anonymous is true; split the test route
into a separate handler that enforces authentication and owner/tenant scoping
and then delegates to the shared implementation. Concretely: keep the existing
webhook(agent_id) implementation (with its is_test branch) but add a new
function (e.g., webhook_test(agent_id)) decorated with
manager.route("/agents/<agent_id>/webhook/test", methods=[...]) plus
`@login_required` (or the project’s auth decorator) and an explicit owner/tenant
check (verify_owner_or_tenant or the existing owner-scoping helper) that sets
is_test=True before calling the shared webhook logic; ensure the new handler
does not rely on canvas.allow_anonymous and returns the same responses by
delegating to the original webhook implementation.
- Around line 1189-1211: The validators currently return early when security_cfg
lacks max_body_size or rate_limit, which skips server defaults for
anonymous-allowed webhooks; update _validate_max_body_size and the rate-limit
validator (the function that checks "rate_limit") to detect when
_allow_anonymous_webhook(security_cfg) is true and, instead of returning,
substitute the server-enforced defaults (e.g., DEFAULT_MAX_BODY_SIZE and
DEFAULT_RATE_LIMIT) into security_cfg or local vars so parsing and the 10MB hard
cap (MAX_LIMIT) still run; keep the existing parsing logic for units and the
content_length check (request.content_length) and ensure the same pattern is
applied for the rate_limit path so anonymous webhooks receive default guards
even when fields are missing.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1144-1149: The helper function _is_truthy currently accepts bool
and string values but rejects numeric types, causing ints like 1/0 to be
ignored; update _is_truthy to also handle integer (and optionally other numeric)
inputs by returning True for 1 and False for 0 (and treat other numeric values
as False or raise/ignore per existing behavior), while keeping the existing bool
and str branches intact so hand-edited/generated YAML values like
allow_anonymous: 1 are recognized.
- Around line 1154-1188: The validate_webhook_security function currently raises
exceptions on denial paths without logging; update validate_webhook_security to
log audit-friendly warnings/errors before each rejection (e.g., when
security_cfg is missing/invalid, when auth_type == "none" but
_allow_anonymous_webhook(security_cfg) is false, and when auth_type is
unsupported) using the module logger (obtain via logging.getLogger(__name__) or
the project’s standard logger) and include context details (auth_type, client
IP/header info if available, and a short reason) so operators can detect
misconfigurations and rejected webhook attempts; ensure logs are written
immediately before each raise call in validate_webhook_security and in any
helper validations it delegates to.

In `@web/src/pages/agent/utils.ts`:
- Around line 442-444: The transform unconditionally sets
nextSecurity.allow_anonymous when params.security?.auth_type ===
WebhookSecurityAuthType.None which silently opts users into "anonymous" —
instead, add an explicit UI confirmation in the form component that serializes
these params (the begin-form / webhook begin-form component) so the user must
acknowledge a clear "allow anonymous access" warning before the serializer runs;
only set nextSecurity.allow_anonymous = true when the form explicitly includes
that confirmation flag (e.g., a checked "confirm allow anonymous" field on the
form model) and otherwise leave it false, and ensure the serializer reads that
explicit confirmation field from params (alongside params.security and
WebhookSecurityAuthType.None) before toggling nextSecurity.allow_anonymous.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3282f6f9-1c5d-40d0-9fd1-910f87f392f0

📥 Commits

Reviewing files that changed from the base of the PR and between ff685d3 and 45598fa.

📒 Files selected for processing (4)
  • api/apps/restful_apis/agent_api.py
  • test/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.py
  • web/src/pages/agent/form/begin-form/schema.ts
  • web/src/pages/agent/utils.ts

@ai-mountain
ai-mountain force-pushed the fix/agent-webhook-security branch from 45598fa to 62571f8 Compare May 13, 2026 11:24
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels May 13, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
api/apps/restful_apis/agent_api.py (2)

1202-1208: Heads-up: non-anonymous webhooks without explicit max_body_size / rate_limit get no limit at all.

With the new branching, an authenticated webhook (auth_type of token/basic/jwt) that omits max_body_size or rate_limit returns early from the corresponding validators — so neither cap nor throttle is applied. That's a deliberate change in this PR (defaults only fire for anonymous-allowed configs), but in practice it means authenticated webhooks rely entirely on operators remembering to set both fields, with no server-side floor against an oversized body or runaway client.

If the intent is "authenticated callers are trusted," fine — but consider either:

  • documenting this contract clearly in the schema/UI (so operators know they must set both), or
  • applying the same 10MB / 60-per-minute floor unconditionally and only widening when explicitly configured.

Also applies to: 1249-1255

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/agent_api.py` around lines 1202 - 1208, The validators
currently return early for authenticated webhooks causing no default limits to
be applied; update _validate_max_body_size to set the floor ("10MB") when
security_cfg.get("max_body_size") is missing regardless of
_allow_anonymous_webhook(), and do the analogous change in the rate-limit
validator (the block around lines referencing rate_limit) to apply the floor
(e.g., "60-per-minute") when rate_limit is absent; keep the existing widening
behavior for anonymous-webhook configs but do not return early for authenticated
configs so that an explicit minimum cap/throttle is always enforced.

1155-1166: ⚡ Quick win

Promote _is_truthy and _allow_anonymous_webhook to module scope.

These helpers are pure (no closure over _webhook_impl state) and are redefined on every webhook request as nested functions. Lifting them to module level avoids the per-request rebinding, makes them unit-testable in isolation, and lets you reuse them from _validate_max_body_size / _validate_rate_limit without relying on closure lookup. Worth doing while the surface is small.

♻️ Suggested move

Outside _webhook_impl (e.g., near the other module-level helpers around _require_canvas_owner_sync):

def _is_truthy(value):
    if isinstance(value, bool):
        return value
    if isinstance(value, int):
        return value != 0
    if isinstance(value, str):
        return value.strip().lower() in {"1", "true", "yes", "on"}
    return False


def _allow_anonymous_webhook(security_cfg: dict) -> bool:
    if not isinstance(security_cfg, dict):
        return False
    return _is_truthy(security_cfg.get("allow_anonymous"))

Then drop the nested definitions inside _webhook_impl.

Side note: the current isinstance(value, int): return value == 1 branch treats integers other than 1 as falsy (e.g., 2, -1). Switching to value != 0 matches the usual truthy semantics callers will expect from a helper named _is_truthy.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/restful_apis/agent_api.py` around lines 1155 - 1166, Lift the nested
helpers _is_truthy and _allow_anonymous_webhook out of _webhook_impl to module
scope (place them alongside other top-level helpers such as
_require_canvas_owner_sync), remove their nested definitions inside
_webhook_impl, and update any internal references to call the module-level
functions; change the integer handling in _is_truthy from equality to non-zero
(use value != 0) to match normal truthiness, and make _allow_anonymous_webhook
robust by verifying security_cfg is a dict before calling _is_truthy on
security_cfg.get("allow_anonymous").
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1113-1114: Add warning logs at each security short-circuit: when
the owner check using UserCanvasService.query(user_id=tenant_id, id=agent_id)
fails, when security_cfg is missing/empty, and when the implicit-anonymous
rejection triggers; for each place emit logging.warning including agent_id,
request.method, and a concise rejection reason (do not log headers or other
secrets), then continue returning the existing get_json_result as before so the
behavior is unchanged.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1202-1208: The validators currently return early for authenticated
webhooks causing no default limits to be applied; update _validate_max_body_size
to set the floor ("10MB") when security_cfg.get("max_body_size") is missing
regardless of _allow_anonymous_webhook(), and do the analogous change in the
rate-limit validator (the block around lines referencing rate_limit) to apply
the floor (e.g., "60-per-minute") when rate_limit is absent; keep the existing
widening behavior for anonymous-webhook configs but do not return early for
authenticated configs so that an explicit minimum cap/throttle is always
enforced.
- Around line 1155-1166: Lift the nested helpers _is_truthy and
_allow_anonymous_webhook out of _webhook_impl to module scope (place them
alongside other top-level helpers such as _require_canvas_owner_sync), remove
their nested definitions inside _webhook_impl, and update any internal
references to call the module-level functions; change the integer handling in
_is_truthy from equality to non-zero (use value != 0) to match normal
truthiness, and make _allow_anonymous_webhook robust by verifying security_cfg
is a dict before calling _is_truthy on security_cfg.get("allow_anonymous").
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d724f1eb-9073-4d78-91ea-ca0288879a6e

📥 Commits

Reviewing files that changed from the base of the PR and between 45598fa and 62571f8.

📒 Files selected for processing (6)
  • api/apps/restful_apis/agent_api.py
  • test/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.py
  • web/src/locales/en.ts
  • web/src/pages/agent/form/begin-form/schema.ts
  • web/src/pages/agent/form/begin-form/webhook/auth.tsx
  • web/src/pages/agent/utils.ts
✅ Files skipped from review due to trivial changes (1)
  • web/src/locales/en.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • web/src/pages/agent/form/begin-form/schema.ts
  • web/src/pages/agent/utils.ts
  • test/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.py

Comment thread api/apps/restful_apis/agent_api.py Resolved
@ai-mountain
ai-mountain force-pushed the fix/agent-webhook-security branch from 62571f8 to b966565 Compare May 13, 2026 11:49
@coderabbitai

coderabbitai Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@yuzhichang
yuzhichang self-requested a review June 28, 2026 00:49
@yuzhichang
yuzhichang merged commit 6c87225 into infiniflow:main Jun 28, 2026
3 checks passed
@ai-mountain
ai-mountain deleted the fix/agent-webhook-security branch June 28, 2026 11:47
yuzhichang added a commit that referenced this pull request Jun 29, 2026
### What problem does this PR solve?

Fixes #14882

Agent webhook execution currently fails open when the saved webhook
`security` block is missing/empty, or when `auth_type` is set to `none`.
This allows unauthenticated webhook invocation without an explicit
operator opt-in.

This PR makes anonymous webhook access explicit:
- Rejects missing or empty webhook security config.
- Requires `allow_anonymous: true` when `auth_type` is `none`.
- Preserves explicit anonymous webhooks by having the frontend serialize
`allow_anonymous: true` when the user selects `None` auth.
- Updates webhook unit tests to cover both denied implicit-anonymous
configs and allowed explicit-anonymous configs.

### Type of change

- [x] Bug Fix
- [x] Security hardening
- [x] Test

### Tests

- [x] `ZHIPU_AI_API_KEY=dummy uv run python -m pytest
--confcutdir=test/testcases/test_web_api/test_agent_app
test/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.py`
- [x] `uv run ruff check api/apps/restful_apis/agent_api.py
test/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.py`
- [x] `npm exec eslint src/pages/agent/utils.ts
src/pages/agent/form/begin-form/schema.ts`

---------

Co-authored-by: Zhichang Yu <[email protected]>
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 L/M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 2 - SSRF + cross-cutting
- infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates
  the target URL and (optionally) the proxy URL BEFORE any HTTP
  request. utility.PinnedHTTPClient dials the validated public
  IP for the direct path (defeats DNS rebinding). No-redirects
  policy closes the 30x-bypass window. ALLOW_ANY_HOST env var
  added to utility.AssertURLSafe for test bypass (production:
  never set; tests: t.Setenv). 4 new tests cover loopback,
  metadata IP, loopback proxy, no-follow-redirect.

Group 4 - API auth + interactive events
- infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/
  <message_id> sibling. BetaAuthMiddleware now also looks up
  the APIToken directly and stashes DialogID in the gin
  context as agent_id, so the handler can build the Redis key
  without trusting the URL segment. New UserService.GetAPITokenByBeta
  + userTokenResolver interface method + stub update. 2 new
  tests cover agent_id-in-context and message_id-required paths.
- infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an
  Event field (json:event,omitempty); WriteChatbotFrame includes
  it in the inner data envelope so the front-end can distinguish
  user_inputs / workflow_finished events from plain messages
  and render the UserFillUp form vs the assistant text. 3 new
  tests cover the user_inputs, workflow_finished, and message
  event types.
- infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now
  rejects empty/nil security config (was fail-open); validateAuth
  rejects auth_type=none without allow_anonymous=true. New
  isTruthyAllowAnonymous helper mirrors python _is_truthy.
  Existing tests updated to use the explicit-opt-in default via
  makeWebhookCanvas. 3 new tests cover empty/nil config,
  auth_type=none without opt-in, and the various truthy forms
  of allow_anonymous.

Total: 12 new tests across 3 modified test files. All touched
package tests pass (1709 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 L/M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 2 - SSRF + cross-cutting
- infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates
  the target URL and (optionally) the proxy URL BEFORE any HTTP
  request. utility.PinnedHTTPClient dials the validated public
  IP for the direct path (defeats DNS rebinding). No-redirects
  policy closes the 30x-bypass window. ALLOW_ANY_HOST env var
  added to utility.AssertURLSafe for test bypass (production:
  never set; tests: t.Setenv). 4 new tests cover loopback,
  metadata IP, loopback proxy, no-follow-redirect.

Group 4 - API auth + interactive events
- infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/
  <message_id> sibling. BetaAuthMiddleware now also looks up
  the APIToken directly and stashes DialogID in the gin
  context as agent_id, so the handler can build the Redis key
  without trusting the URL segment. New UserService.GetAPITokenByBeta
  + userTokenResolver interface method + stub update. 2 new
  tests cover agent_id-in-context and message_id-required paths.
- infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an
  Event field (json:event,omitempty); WriteChatbotFrame includes
  it in the inner data envelope so the front-end can distinguish
  user_inputs / workflow_finished events from plain messages
  and render the UserFillUp form vs the assistant text. 3 new
  tests cover the user_inputs, workflow_finished, and message
  event types.
- infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now
  rejects empty/nil security config (was fail-open); validateAuth
  rejects auth_type=none without allow_anonymous=true. New
  isTruthyAllowAnonymous helper mirrors python _is_truthy.
  Existing tests updated to use the explicit-opt-in default via
  makeWebhookCanvas. 3 new tests cover empty/nil config,
  auth_type=none without opt-in, and the various truthy forms
  of allow_anonymous.

Total: 12 new tests across 3 modified test files. All touched
package tests pass (1709 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 L/M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 2 - SSRF + cross-cutting
- infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates
  the target URL and (optionally) the proxy URL BEFORE any HTTP
  request. utility.PinnedHTTPClient dials the validated public
  IP for the direct path (defeats DNS rebinding). No-redirects
  policy closes the 30x-bypass window. ALLOW_ANY_HOST env var
  added to utility.AssertURLSafe for test bypass (production:
  never set; tests: t.Setenv). 4 new tests cover loopback,
  metadata IP, loopback proxy, no-follow-redirect.

Group 4 - API auth + interactive events
- infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/
  <message_id> sibling. BetaAuthMiddleware now also looks up
  the APIToken directly and stashes DialogID in the gin
  context as agent_id, so the handler can build the Redis key
  without trusting the URL segment. New UserService.GetAPITokenByBeta
  + userTokenResolver interface method + stub update. 2 new
  tests cover agent_id-in-context and message_id-required paths.
- infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an
  Event field (json:event,omitempty); WriteChatbotFrame includes
  it in the inner data envelope so the front-end can distinguish
  user_inputs / workflow_finished events from plain messages
  and render the UserFillUp form vs the assistant text. 3 new
  tests cover the user_inputs, workflow_finished, and message
  event types.
- infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now
  rejects empty/nil security config (was fail-open); validateAuth
  rejects auth_type=none without allow_anonymous=true. New
  isTruthyAllowAnonymous helper mirrors python _is_truthy.
  Existing tests updated to use the explicit-opt-in default via
  makeWebhookCanvas. 3 new tests cover empty/nil config,
  auth_type=none without opt-in, and the various truthy forms
  of allow_anonymous.

Total: 12 new tests across 3 modified test files. All touched
package tests pass (1709 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 L/M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 2 - SSRF + cross-cutting
- infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates
  the target URL and (optionally) the proxy URL BEFORE any HTTP
  request. utility.PinnedHTTPClient dials the validated public
  IP for the direct path (defeats DNS rebinding). No-redirects
  policy closes the 30x-bypass window. ALLOW_ANY_HOST env var
  added to utility.AssertURLSafe for test bypass (production:
  never set; tests: t.Setenv). 4 new tests cover loopback,
  metadata IP, loopback proxy, no-follow-redirect.

Group 4 - API auth + interactive events
- infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/
  <message_id> sibling. BetaAuthMiddleware now also looks up
  the APIToken directly and stashes DialogID in the gin
  context as agent_id, so the handler can build the Redis key
  without trusting the URL segment. New UserService.GetAPITokenByBeta
  + userTokenResolver interface method + stub update. 2 new
  tests cover agent_id-in-context and message_id-required paths.
- infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an
  Event field (json:event,omitempty); WriteChatbotFrame includes
  it in the inner data envelope so the front-end can distinguish
  user_inputs / workflow_finished events from plain messages
  and render the UserFillUp form vs the assistant text. 3 new
  tests cover the user_inputs, workflow_finished, and message
  event types.
- infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now
  rejects empty/nil security config (was fail-open); validateAuth
  rejects auth_type=none without allow_anonymous=true. New
  isTruthyAllowAnonymous helper mirrors python _is_truthy.
  Existing tests updated to use the explicit-opt-in default via
  makeWebhookCanvas. 3 new tests cover empty/nil config,
  auth_type=none without opt-in, and the various truthy forms
  of allow_anonymous.

Total: 12 new tests across 3 modified test files. All touched
package tests pass (1709 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
yuzhichang added a commit that referenced this pull request Jun 30, 2026
)

Mirrors 14 merged upstream PRs into the Go agent port.

PRs ported:
  - #15609 ExeSQL SSRF guard + DNS pin
  - #15436 HTTP timeout on external API tools
  - #16363 be_output restore + DeepL error path
  - #15644 switch no longer matches empty condition
  - #15374 session_id bind to path agent_id (DAO idor guard)
  - #16169 sandbox artifact ownership gate
  - #15457 tenant ownership on agentbots
  - #15145 rerun agent document access check
- #15446 thinking switch (component portion; provider policy lives in
internal/llm)
  - #15426 Invoke URL/proxy SSRF + DNS pin + no-redirects
  - #15238 agentbot thinking-logs beta endpoint
  - #14589 UserFillUp SSE event propagation
  - #14890 anonymous webhook opt-in
- #15068 PipelineChunker new component (text/file_ref/parser_id
dispatch; file-format extraction is a follow-up)

40 files, +2355 / -58 lines. 33 new tests, all targeted package suites
pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.
yuzhichang added a commit to ondery/ragflow that referenced this pull request Jul 1, 2026
…sion/user + input/output to Langfuse for agent runs

Rebuilt on current upstream/main after force-push; cherry-pick of the 7
PR-original commits collapsed into a single net diff to avoid conflicts
with intervening commits pulled in by repeated merges of upstream/main.

Original PR work (commits dropped during rebuild because their content
already lives on upstream/main or was a merge of upstream/main):
  c7339ae Enhance LLMService with token usage reporting
  0266cf0 Implement token usage tracking and Langfuse integration
  ab2b267 Include session_id in run_kwargs
  8bf937c Implement token usage tracking in chat model
  c955988 Enhance token tracking with context variables and functions
  3e88ed5 fix(agent): address CodeRabbit review on token usage tracking
  74b8c8c fix(agent): address CodeRabbit follow-up review

Forced-upstream duplicates dropped (already merged to main):
  70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405),
  730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410),
  c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436),
  ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609),
  2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985),
  bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426),
  4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145)

Plus 18 'Merge branch main into main' commits dropped (polluted topology).
yuzhichang added a commit to ondery/ragflow that referenced this pull request Jul 1, 2026
…sion/user + input/output to Langfuse for agent runs

Rebuilt on current upstream/main after force-push; cherry-pick of the 7
PR-original commits collapsed into a single net diff to avoid conflicts
with intervening commits pulled in by repeated merges of upstream/main.

Original PR work (commits dropped during rebuild because their content
already lives on upstream/main or was a merge of upstream/main):
  c7339ae Enhance LLMService with token usage reporting
  0266cf0 Implement token usage tracking and Langfuse integration
  ab2b267 Include session_id in run_kwargs
  8bf937c Implement token usage tracking in chat model
  c955988 Enhance token tracking with context variables and functions
  3e88ed5 fix(agent): address CodeRabbit review on token usage tracking
  74b8c8c fix(agent): address CodeRabbit follow-up review

Forced-upstream duplicates dropped (already merged to main):
  70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405),
  730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410),
  c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436),
  ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609),
  2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985),
  bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426),
  4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145)

Plus 18 'Merge branch main into main' commits dropped (polluted topology).

Co-authored-by: yzc <[email protected]>
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 1, 2026
…iniflow#16455)

Mirrors 14 merged upstream PRs into the Go agent port.

PRs ported:
  - infiniflow#15609 ExeSQL SSRF guard + DNS pin
  - infiniflow#15436 HTTP timeout on external API tools
  - infiniflow#16363 be_output restore + DeepL error path
  - infiniflow#15644 switch no longer matches empty condition
  - infiniflow#15374 session_id bind to path agent_id (DAO idor guard)
  - infiniflow#16169 sandbox artifact ownership gate
  - infiniflow#15457 tenant ownership on agentbots
  - infiniflow#15145 rerun agent document access check
- infiniflow#15446 thinking switch (component portion; provider policy lives in
internal/llm)
  - infiniflow#15426 Invoke URL/proxy SSRF + DNS pin + no-redirects
  - infiniflow#15238 agentbot thinking-logs beta endpoint
  - infiniflow#14589 UserFillUp SSE event propagation
  - infiniflow#14890 anonymous webhook opt-in
- infiniflow#15068 PipelineChunker new component (text/file_ref/parser_id
dispatch; file-format extraction is a follow-up)

40 files, +2355 / -58 lines. 33 new tests, all targeted package suites
pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Agent webhook trigger is insecure-by-default — unauthenticated invocation when security_cfg is empty

2 participants