Repository navigation
fix(files): validate client-supplied file references at workflow entr… - #8147
Conversation
…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>
|
|
||
|
|
||
| def validate_owned_upload(file, user_id): | ||
| if (file is None or not user_id or file.source_type not in TEMPORARY_FILE_TYPES |
There was a problem hiding this comment.
Here's my review of the patch:
Security / Correctness Issues
-
validate_knowledge_file_referencesuses the wrong argument shape. It callsvalidate_file_references(instance, is_allowed), but every other caller passes a structured value (list/dict) that_iter_file_idscan walk viainstance.get(...)or iteration. Passing a raw model instance means:- If
instanceis a dict/list, it works coincidentally. - If it's a model/object,
_iter_file_idswill 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.
- If
-
_iter_file_idsrecurses into all dict values, including thefile_idvalue itself. After yielding afile_id, it also recurses intovalue['file_id'](a string → ignored) — harmless, but it will also descend into arbitrary/unrelated nested structures. If any user-controlled dict contains a key namedfile_idwith 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 ifvaluecomes from trusted Python objects). -
is_valid_uuidfailure returns 403 rather than 400. An invalid UUID is a malformed request, not an authorization failure. ReturningAppUnauthorizedFailed(403)for bad input obscures the real cause and may break client retry logic. Consider a 400. -
N+1 / empty-queryset behavior in
validate_knowledge_file_references. TheDOCUMENTbranch runs a.exists()query per file, inside theall(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. -
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. -
len(files) != len(file_ids)assumes one row per id and no duplicates.file_idsis already aset, so duplicate ids are collapsed — good. But ifidis 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. -
file.meta.get('user_id')comparison viastr()on both sides is okay, but ifmetaisNonethis raisesAttributeError. Guard(file.meta or {}). -
file.meta.get('chat_id') in (None, str(chat_id))allowschat_idto beNoneon 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
-
Inconsistent ownership rule.
is_owned_uploadincludesFileSourceType.CHATplus temporary types, while the pre-existingvalidate_owned_upload(shown truncated) only checksTEMPORARY_FILE_TYPES. Two functions with similar names but different semantics is a maintenance hazard — rename or unify (is_owned_uploadvsvalidate_owned_upload). -
CHAT_FILE_FIELDSis hardcoded; adding a new field to the model silently skips validation. Derive from model fields where possible, or add a comment/test asserting coverage. -
bool(user_id)check inis_owned_upload— ifuser_idis falsy, all owned-upload checks fail closed (good), but the caller should ideally reject unauthenticated calls earlier. -
Duplicated
'No permission to access'strings — extract a constant to avoid drift. -
list(QuerySet(File).filter(...))materializes full rows just to count and inspectsource_type/source_id/meta. Use.only('id', 'source_type', 'source_id', 'meta')(orvalues) to reduce memory/IO.
Optimization Summary
- Use
.only()/values_listinstead of full-object fetch. - Collapse the
DOCUMENTexistence check into one query. - Short-circuit UUID validation before the DB query (already done) — good.
- Early-return when
file_idsempty — 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) |
There was a problem hiding this comment.
No irregularities found. A few observations:
-
Signature change is backward compatible —
check_file_accessis added as a keyword arg with defaultTrue, so existing callers are unaffected. -
Import path consistency —
common.utils.file_referencefollows the samecommon.utils.*convention ascommon.utils.common. Fine. -
Missing early validation ordering —
validate_chat_file_referencesis called afteris_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. -
Defensive default for
chat_user_id—self.data.get('chat_user_id')may returnNone. Confirm thatvalidate_chat_file_referenceshandles aNoneuser id gracefully (e.g., debug mode). Otherwise, guard:if check_file_access and not instance.get('debug'): ...
or ensure the validator itself treats
Nonesafely. -
chat_infoattributes accessed eagerly —chat_info.chat_idis read just before branching onapplication.type == SIMPLE. Ifchat_simple()does not needchat_id, this reads a value unnecessarily and may raiseAttributeErrorwhere previously it did not. Consider fetchingchat_idinside/after the branch, or confirmchat_idis always present. -
Consistent boolean naming —
check_file_accesspairs well with existingcheck_chat_record. Good. -
Error surface —
validate_chat_file_referencespresumably raises its own exception type. Make sure it is caught/normalized intoChatExceptionat the caller level so API responses stay consistent. -
Minor optimization — If
instancerarely contains file references, add a fast-path check insidevalidate_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} |
There was a problem hiding this comment.
Here's my review of the diff:
Potential Issues
-
knowledge_workflow/knowledge_workflow_versionmay beNone
Both blocks call.work_flowon a.first()result without a null check. If no matching record exists, this raisesAttributeError. 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")
-
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. Ifvalidate_knowledge_file_referencesexpects references already linked viabind_knowledge_uploads, the sequence should be swapped. This is the most likely functional bug. -
Inconsistent argument types for
knowledge_idaction:self.data.get("knowledge_id")— unclear type (str? UUID?)- New calls pass
user.idas raw value whilevalidate_resource_referenceswrapsstr(user.id).
Verifyvalidate_knowledge_file_referencessignature expectations; mixingUUIDandstrcan cause silent equality mismatches against DB columns.
-
No explicit
file_idspass-through
Inupload_document,instanceis passed to the validator, butfile_ids(the actual uploads) is bound separately. If validation is meant to cover those specific uploads, consider passingfile_idsexplicitly so the validator scope matches what gets bound. -
Duplicate lookup cost
validate_knowledge_file_referenceslikely re-queriesKnowledge/Documentbyknowledge_id. Sinceknowledge_idwas just used above, consider caching or accepting an already-fetched object to avoid an extra query per request.
Optimization Suggestions
-
Move import grouping —
bind_knowledge_uploads, validate_knowledge_file_referencesis fine, but keep alphabetized order consistent with the surrounding imports. -
Fail-fast ordering in
action—validate_knowledge_file_referencesruns aftervalidate_resource_references. If file-reference errors are cheaper/cheaper to detect, run them first to avoid the workflow fetch cost on invalid requests. -
Add a unit/integration test for the case where
instancereferences a file from a differentknowledge_id— this is the security-relevant path the new validator presumably guards.
Minor
-
No transaction wrapping — in
upload_document, validation + bind + action creation aren't atomic. IfKnowledgeAction(...)fails afterbind_knowledge_uploads, you get partially-bound uploads. Considertransaction.atomic()around the block. -
Trailing comma style — line lengths look consistent; no issue there.
…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:
What this PR does / why we need it?
Summary of your change
Please indicate you've done the following: