Repository navigation
fix: require explicit anonymous webhook access - #14890
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughWebhook routes are hardened: missing/empty webhook security now rejects requests, anonymous access requires explicit ChangesWebhook Security Hardening: Fail-Safe Default
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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/testis reachable anonymously — violates a stated PR objective.Both
/agents/<agent_id>/webhookand/agents/<agent_id>/webhook/testshare the same handler with no@login_required/ owner check. Theis_testbranch only changes trace logging; if the canvas owner configuresallow_anonymous: true(which the frontend now does wheneverauth_type=Noneis selected), the test endpoint is also publicly callable. Issue#14882explicitly 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 winDefaults for
max_body_sizeandrate_limitare not applied to anonymous-allowed webhooks.Issue
#14882calls out: "Ensure default rate limits andmax_body_sizestill apply for anonymous-allowed webhooks (currently bypassed whensecurity_cfgis empty)." Today an operator can publish a webhook withsecurity = {"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: returnThis 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 webhooksdef _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 webhooksAlso 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 valueTruthy-helper accepts strings but not numeric
1/0.Minor inconsistency:
_is_truthyrecognizes the string"1"but not the integer1. If a DSL is hand-edited or generated from a YAML pipeline,allow_anonymous: 1will 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 winAdd logging for the new security-denial flow.
Per coding guideline
**/*.py: Add logging for new flows, the newly added denial paths (emptysecurity_cfg, missingallow_anonymousforauth_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_REQUESTAs 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 winSilent opt-in undermines the "explicit anonymous" intent — pair this with a UI confirmation.
This transform unconditionally sets
allow_anonymous: truewhenever the user picksauth_type = None, which means the backend's new "explicit opt-in" guard is satisfied without the user ever seeing the word "anonymous." Issue#14882specifically 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
📒 Files selected for processing (4)
api/apps/restful_apis/agent_api.pytest/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.pyweb/src/pages/agent/form/begin-form/schema.tsweb/src/pages/agent/utils.ts
45598fa to
62571f8
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
api/apps/restful_apis/agent_api.py (2)
1202-1208: Heads-up: non-anonymous webhooks without explicitmax_body_size/rate_limitget no limit at all.With the new branching, an authenticated webhook (
auth_typeoftoken/basic/jwt) that omitsmax_body_sizeorrate_limitreturns 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-minutefloor 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 winPromote
_is_truthyand_allow_anonymous_webhookto module scope.These helpers are pure (no closure over
_webhook_implstate) 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_limitwithout 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 == 1branch treats integers other than1as falsy (e.g.,2,-1). Switching tovalue != 0matches 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
📒 Files selected for processing (6)
api/apps/restful_apis/agent_api.pytest/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.pyweb/src/locales/en.tsweb/src/pages/agent/form/begin-form/schema.tsweb/src/pages/agent/form/begin-form/webhook/auth.tsxweb/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
62571f8 to
b966565
Compare
✅ Actions performedFull review triggered. |
### 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]>
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
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
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
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
) 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.
…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).
…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]>
…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.
What problem does this PR solve?
Fixes #14882
Agent webhook execution currently fails open when the saved webhook
securityblock is missing/empty, or whenauth_typeis set tonone. This allows unauthenticated webhook invocation without an explicit operator opt-in.This PR makes anonymous webhook access explicit:
allow_anonymous: truewhenauth_typeisnone.allow_anonymous: truewhen the user selectsNoneauth.Type of change
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.pyuv run ruff check api/apps/restful_apis/agent_api.py test/testcases/test_web_api/test_agent_app/test_agents_webhook_unit.pynpm exec eslint src/pages/agent/utils.ts src/pages/agent/form/begin-form/schema.ts