dify icon indicating copy to clipboard operation
dify copied to clipboard

[Bug]: unpadded base64url file references are parsed as raw record ids

Open indexGin opened this issue 2 weeks ago • 4 comments

Prerequisites

  • [x] I have searched the existing issues and discussions, and this is not a duplicate.
  • [x] This is a bug, not a usage question.

Background / Description

parse_file_reference in api/core/workflow/file_reference.py decodes the payload of a dify-file-ref:<base64url-json> reference with base64.urlsafe_b64decode(encoded_payload.encode()). RFC 4648 explicitly allows base64/base64url encoders to omit the trailing = padding, and many commonly do: JWT-style helpers, JavaScript btoa with padding stripped, and values that pass through URL handling where = is often removed.

urlsafe_b64decode raises binascii.Error ("Incorrect padding") for such a payload. The surrounding except ValueError (which covers binascii.Error) silently falls back to treating the whole reference string as a raw record id. As a result a perfectly valid canonical reference stops resolving: file attachments cannot be looked up, and is_canonical_file_reference returns False for canonical-only contracts.

The failure is silent - no exception reaches the caller - so it surfaces as a missing file rather than an obvious decode error.

Steps to Reproduce

import base64, json
from core.workflow.file_reference import (
    parse_file_reference, is_canonical_file_reference, build_file_reference,
)

padded = build_file_reference(record_id="abc-123")
ref = padded.rstrip("=")          # what a padding-stripping encoder produces

print(ref)
print(parse_file_reference(ref))
# Actual:   FileReference(record_id='dify-file-ref:eyJyZWNvcmRfaWQiOiJhYmMtMTIzIn0')
# Expected: FileReference(record_id='abc-123')
print(is_canonical_file_reference(ref))
# Actual: False   Expected: True

parse_file_reference(padded) works, so the same logical reference resolves or fails purely depending on whether the producer kept the padding.

Expected Behavior

A canonical reference is decoded identically whether or not the producer emitted trailing padding. Truly malformed payloads (invalid base64 or invalid JSON) must keep the existing lenient fallback to the raw record id.

Environment

  • Dify: current main (733454ea)
  • Python: 3.12

Additional context (added 2026-11-20, per the maintainer's request)

Dify version / source commit: Not a released build. Verified against the main source tree at commit 733454eae330f8e5c6478874a540951a42a9a14b — the merge base of PR #46650 when it was opened on 2026-11-18.

Cloud or Self Hosted: Self Hosted (Source), i.e. a local source checkout using the repository's own pytest suite. This is a source-only reproduction: it was not observed on a deployed Cloud or Docker instance. The affected code is a pure/shared parsing or serialization helper used by every deployment mode, so the behaviour does not depend on the deployment type. In a running deployment the same helper is reached through normal product paths, but no claim of an observed production incident is made here.

Steps to reproduce:

  1. Check out main at commit 733454eae330 and enter api/.
  2. Run pytest tests/unit_tests/core/workflow/test_file_reference_unpadded.py -q (regression test added by PR #46650).
  3. Or call api/core/workflow/file_reference.parse_file_reference with a canonical dify-file-ref:<base64url-json> whose payload has its trailing = padding removed (as produced by JWT-style encoders, btoa with padding stripped, or URL handling that drops =).

✔️ Expected Behavior: RFC 4648 allows unpadded base64url, so the payload is decoded and the canonical file reference is resolved normally.

❌ Actual Behavior: base64.urlsafe_b64decode() raises binascii.Error: Incorrect padding; the surrounding except ValueError (which covers binascii.Error) silently falls back to treating the entire reference string as a raw record id, so a valid reference is misrouted.

Complete reproduction: PR #46650 adds api/tests/unit_tests/core/workflow/test_file_reference_unpadded.py plus the fix; running that test file against 733454eae330f8e5c6478874a540951a42a9a14b fails before the fix and passes after it. The exact minimal snippet is also in the issue/PR description.

indexGin avatar Nov 18 '26 04:11 indexGin

One additional affected entry point is RequestDownloadFileMapping: for non-remote files, it calls is_canonical_file_reference() and raises ValueError("reference must be a canonical Dify file reference") when validation fails. So this can surface as a download-request validation failure, not just a missing file. [1]

Storage-key hydration has another failure path: load_storage_keys() passes the parsed record_id directly into uuid.UUID(). If parsing falls back to the whole unpadded reference, that conversion fails before any database lookup. [2]

For regression coverage, api/tests/unit_tests/core/workflow/test_file_reference.py already checks the three-helper contract (parse_file_reference, resolve_file_record_id, and is_canonical_file_reference) for malformed payloads. Extending that coverage with padded/unpadded pairs would check both successful resolution and preservation of the existing malformed-input fallback. I haven’t run the tests here. [3]

To reply, just mention @dosu.


Docs are dead. Just use Dosu.

Leave Feedback Ask Dosu about dify

dosubot[bot] avatar Nov 18 '26 04:11 dosubot[bot]

Good catch on binascii.Error getting swallowed by the ValueError catch block.

The standard fix here is to restore missing base64 padding before decoding in api/core/workflow/file_reference.py:

Patch Preview (First 3 lines of verified fix):

def _restore_b64_padding(payload: str) -> str:
    remainder = len(payload) % 4
    return payload + "=" * (4 - remainder) if remainder else payload
# ... [TRUNCATED — Full production patch & verification steps locked below]

grinem avatar Nov 18 '26 04:11 grinem

Hi @indexGin, thanks for opening this issue.

Why this is being closed

The report gives a source commit, Python version, and a useful minimal reproduction, but does not identify the deployment type or explain whether the affected reference occurs in a running Dify workflow. That context helps establish the conditions in which the behavior can be verified. The bug report template asks for version, deployment and reproduction details. We are closing this while that context is gathered; this is not a judgment that the underlying observation is incorrect.

Next steps

Please update the report with the missing details, the precise steps and observed versus expected results, and any relevant sanitized logs or test output. If this is a source-only reproduction, please say so explicitly and include the exact commit and how to run it. Then request reopening so the report and linked work can be reviewed.

crazywoola avatar Nov 20 '26 03:11 crazywoola

The missing bug-report context is now in the issue body: the exact source commit (733454eae330f8e5c6478874a540951a42a9a14b), the deployment type, an explicit source-only declaration, step-by-step reproduction commands, and observed versus expected results. I kept the original report intact and only added the details requested in the closing comment.

Requesting that this report be reopened, as suggested. Once it is ready for review, PR #46650 (the fix plus its regression test) can be reassessed. Thank you for the clear checklist — happy to supply anything else that would help.

indexGin avatar Nov 20 '26 07:11 indexGin