Skip to content

fix(files): validate client-supplied file references at workflow entr… - #8147

Merged
shaohuzhang1 merged 1 commit into
v2from
fix/GHSA-wmwc-4v38-3ccv
Nov 25, 2026
Merged

shaohuzhang1 merged 1 commit into
v2from
fix/GHSA-wmwc-4v38-3ccv

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

…y points (GHSA-wmwc-4v38-3ccv)

Workflow nodes such as Document Content Extraction loaded File rows by the client-supplied file_id without any ownership check, letting a chat visitor read protected files (e.g. knowledge source files) through a published app.

Validate every file_id in the request at the entry points instead:

  • ChatSerializers.chat: own CHAT/temporary uploads (meta.user_id == chat_user_id), or APPLICATION files of this application and chat. Internal callers (sub-application node, trigger, MCP) opt out via check_file_access=False.
  • Knowledge workflow action/upload_document: own uploads, or KNOWLEDGE/DOCUMENT files of this knowledge base.
  • Tool workflow debug: own uploads, or TOOL files of this tool.

What this PR does / why we need it?

Summary of your change

Please indicate you've done the following:

  • Made sure tests are passing and test coverage is added if needed.
  • Made sure commit message follow the rule of Conventional Commits specification.
  • Considered the docs impact and opened a new docs issue or PR with docs changes if needed.

…y points (GHSA-wmwc-4v38-3ccv)

Workflow nodes such as Document Content Extraction loaded File rows by the
client-supplied file_id without any ownership check, letting a chat visitor
read protected files (e.g. knowledge source files) through a published app.

Validate every file_id in the request at the entry points instead:
- ChatSerializers.chat: own CHAT/temporary uploads (meta.user_id ==
  chat_user_id), or APPLICATION files of this application and chat.
  Internal callers (sub-application node, trigger, MCP) opt out via
  check_file_access=False.
- Knowledge workflow action/upload_document: own uploads, or
  KNOWLEDGE/DOCUMENT files of this knowledge base.
- Tool workflow debug: own uploads, or TOOL files of this tool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@shaohuzhang1
shaohuzhang1 merged commit d3eedda into v2 Nov 25, 2026
3 of 4 checks passed
@shaohuzhang1
shaohuzhang1 deleted the fix/GHSA-wmwc-4v38-3ccv branch November 25, 2026 05:40


def validate_owned_upload(file, user_id):
if (file is None or not user_id or file.source_type not in TEMPORARY_FILE_TYPES

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Here's my review of the patch:

Security / Correctness Issues

  1. validate_knowledge_file_references uses the wrong argument shape. It calls validate_file_references(instance, is_allowed), but every other caller passes a structured value (list/dict) that _iter_file_ids can walk via instance.get(...) or iteration. Passing a raw model instance means:

    • If instance is a dict/list, it works coincidentally.
    • If it's a model/object, _iter_file_ids will silently yield nothing (not iterable as expected), so all knowledge-file checks are skipped. This is a fail-open bug — the authorization check becomes a no-op. Use [instance.get(k) for k in ...] like the chat variant, or explicitly iterate over the intended fields.
  2. _iter_file_ids recurses into all dict values, including the file_id value itself. After yielding a file_id, it also recurses into value['file_id'] (a string → ignored) — harmless, but it will also descend into arbitrary/unrelated nested structures. If any user-controlled dict contains a key named file_id with attacker-chosen content, it's treated as a file reference; that's probably intended, but be aware it broadens scope. Also risks infinite recursion on self-referential structures (unlikely from JSON input, but worth a guard if value comes from trusted Python objects).

  3. is_valid_uuid failure returns 403 rather than 400. An invalid UUID is a malformed request, not an authorization failure. Returning AppUnauthorizedFailed(403) for bad input obscures the real cause and may break client retry logic. Consider a 400.

  4. N+1 / empty-queryset behavior in validate_knowledge_file_references. The DOCUMENT branch runs a .exists() query per file, inside the all(is_allowed(...)) loop. For many files this is O(n) queries. Batch-collect document source_ids and do a single filtered query, then compare counts.

  5. all(is_allowed(file) for file in files) short-circuits, which is fine for security, but combined with the per-file .exists() above the number of queries depends on ordering. Normalize to a set-based check.

  6. len(files) != len(file_ids) assumes one row per id and no duplicates. file_ids is already a set, so duplicate ids are collapsed — good. But if id is not unique (or soft-deleted rows are excluded by a default manager), a valid referenced file could be reported as "missing" → false 403. Verify the default manager doesn't filter out referenced files.

  7. file.meta.get('user_id') comparison via str() on both sides is okay, but if meta is None this raises AttributeError. Guard (file.meta or {}).

  8. file.meta.get('chat_id') in (None, str(chat_id)) allows chat_id to be None on the file side — meaning an application file with no chat_id at all is accepted for any chat. Depending on intent this may be too permissive; if these files should be chat-scoped, require an explicit match.

Code Quality / Consistency

  1. Inconsistent ownership rule. is_owned_upload includes FileSourceType.CHAT plus temporary types, while the pre-existing validate_owned_upload (shown truncated) only checks TEMPORARY_FILE_TYPES. Two functions with similar names but different semantics is a maintenance hazard — rename or unify (is_owned_upload vs validate_owned_upload).

  2. CHAT_FILE_FIELDS is hardcoded; adding a new field to the model silently skips validation. Derive from model fields where possible, or add a comment/test asserting coverage.

  3. bool(user_id) check in is_owned_upload — if user_id is falsy, all owned-upload checks fail closed (good), but the caller should ideally reject unauthenticated calls earlier.

  4. Duplicated 'No permission to access' strings — extract a constant to avoid drift.

  5. list(QuerySet(File).filter(...)) materializes full rows just to count and inspect source_type/source_id/meta. Use .only('id', 'source_type', 'source_id', 'meta') (or values) to reduce memory/IO.

Optimization Summary

  • Use .only() / values_list instead of full-object fetch.
  • Collapse the DOCUMENT existence check into one query.
  • Short-circuit UUID validation before the DB query (already done) — good.
  • Early-return when file_ids empty — good.

Biggest Risk

The validate_knowledge_file_references(instance, ...) call passing the raw instance is the most serious: it likely makes the knowledge-file authorization silently ineffective. Fix that first, then address the N+1 document check and the 403-vs-400 distinction.

chat_info.chat_id)
if chat_info.application.type == ApplicationTypeChoices.SIMPLE:
self.is_valid_application_simple(raise_exception=True, chat_info=chat_info)
return self.chat_simple(chat_info, instance, base_to_response)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No irregularities found. A few observations:

  1. Signature change is backward compatible — check_file_access is added as a keyword arg with default True, so existing callers are unaffected.

  2. Import path consistency — common.utils.file_reference follows the same common.utils.* convention as common.utils.common. Fine.

  3. Missing early validation ordering — validate_chat_file_references is called after is_valid_chat_user(). If file-reference validation is independent of user auth, you may want it earlier to fail fast; otherwise the current order is acceptable since authorization should typically short-circuit first.

  4. Defensive default for chat_user_id — self.data.get('chat_user_id') may return None. Confirm that validate_chat_file_references handles a None user id gracefully (e.g., debug mode). Otherwise, guard:

    if check_file_access and not instance.get('debug'):
        ...

    or ensure the validator itself treats None safely.

  5. chat_info attributes accessed eagerly — chat_info.chat_id is read just before branching on application.type == SIMPLE. If chat_simple() does not need chat_id, this reads a value unnecessarily and may raise AttributeError where previously it did not. Consider fetching chat_id inside/after the branch, or confirm chat_id is always present.

  6. Consistent boolean naming — check_file_access pairs well with existing check_chat_record. Good.

  7. Error surface — validate_chat_file_references presumably raises its own exception type. Make sure it is caught/normalized into ChatException at the caller level so API responses stay consistent.

  8. Minor optimization — If instance rarely contains file references, add a fast-path check inside validate_chat_file_references (e.g., if not instance.get('file_references'): return) to avoid unnecessary DB queries per chat message.

Overall, the change is small and low-risk; the main thing to verify is None-safety of chat_user_id and that chat_info.chat_id is reliably available at that point.

validate_knowledge_file_references(instance, self.data.get("knowledge_id"), user.id)
bind_knowledge_uploads(file_ids, self.data.get("knowledge_id"), user.id)
knowledge_action_id = uuid.uuid7()
meta = {"user_id": str(user.id), "user_name": user.username}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Here's my review of the diff:

Potential Issues

  1. knowledge_workflow / knowledge_workflow_version may be None
    Both blocks call .work_flow on a .first() result without a null check. If no matching record exists, this raises AttributeError. This is pre-existing but is now adjacent to your new code — worth adding a guard:

    if knowledge_workflow is None:
        raise ParseException("Knowledge workflow not found")
  2. Validating before binding in upload_document
    The order is: validate_knowledge_file_references(...) → bind_knowledge_uploads(file_ids, ...). Confirm that validation is intended to run against unbound files. If validate_knowledge_file_references expects references already linked via bind_knowledge_uploads, the sequence should be swapped. This is the most likely functional bug.

  3. Inconsistent argument types for knowledge_id

    • action: self.data.get("knowledge_id") — unclear type (str? UUID?)
    • New calls pass user.id as raw value while validate_resource_references wraps str(user.id).
      Verify validate_knowledge_file_references signature expectations; mixing UUID and str can cause silent equality mismatches against DB columns.
  4. No explicit file_ids pass-through
    In upload_document, instance is passed to the validator, but file_ids (the actual uploads) is bound separately. If validation is meant to cover those specific uploads, consider passing file_ids explicitly so the validator scope matches what gets bound.

  5. Duplicate lookup cost
    validate_knowledge_file_references likely re-queries Knowledge/Document by knowledge_id. Since knowledge_id was just used above, consider caching or accepting an already-fetched object to avoid an extra query per request.

Optimization Suggestions

  1. Move import grouping — bind_knowledge_uploads, validate_knowledge_file_references is fine, but keep alphabetized order consistent with the surrounding imports.

  2. Fail-fast ordering in action — validate_knowledge_file_references runs after validate_resource_references. If file-reference errors are cheaper/cheaper to detect, run them first to avoid the workflow fetch cost on invalid requests.

  3. Add a unit/integration test for the case where instance references a file from a different knowledge_id — this is the security-relevant path the new validator presumably guards.

Minor

  1. No transaction wrapping — in upload_document, validation + bind + action creation aren't atomic. If KnowledgeAction(...) fails after bind_knowledge_uploads, you get partially-bound uploads. Consider transaction.atomic() around the block.

  2. Trailing comma style — line lengths look consistent; no issue there.

Priority: #2 (ordering) and #1 (null check) first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant