Skip to content

fix: add bucket prefix to Azure Blob SPN and SAS storage operations - #14347

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
D2758695161:fix/azure-blob-bucket-prefix
May 8, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
D2758695161:fix/azure-blob-bucket-prefix

Conversation

@D2758695161

@D2758695161 D2758695161 commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes file collision between different datasets when using Azure Blob storage (SPN or SAS authentication).

Bug

azure_spn_conn.py and �zure_sas_conn.py ignored the �ucket parameter entirely, storing all files flat with just the filename. This caused files with the same name from different datasets (knowledge bases) to overwrite each other.

Fix

Prepend bucket/ as a path prefix in all methods (put,
m, get, obj_exist, get_presigned_url, health) to match the behavior of MinIO and S3 implementations.

Changes

  • rag/utils/azure_spn_conn.py: Added {bucket}/ prefix to file paths in all operations
  • rag/utils/azure_sas_conn.py: Same fix applied for consistency (also noted in the original issue)

Testing

Manual verification: files from different datasets now stored under distinct bucket/ prefixes, preventing collisions.

Fixes #14159

- azure_spn_conn.py: prepend bucket as path prefix in put(), rm(), get(),
  obj_exist(), get_presigned_url(), and health() to prevent files from
  different datasets overwriting each other (fixes infiniflow#14159)
- azure_sas_conn.py: apply same bucket prefix fix for consistency

Before this change the Azure implementations stored files flat (filename only),
while MinIO and S3 correctly prefixed paths with the bucket/knowledge base ID.
This caused filename collisions when different datasets had files with the
same name.
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Apr 24, 2026
@coderabbitai

coderabbitai Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Two Azure storage connection utilities are updated to prepend bucket prefixes to file paths across all file operations, resolving filename collision issues between datasets. The get_presigned_url method is refactored to directly return the blob/file client's URL instead of calling a connection-level method. Explicit None returns replace bare returns in failure paths.

Changes

Cohort / File(s) Summary
Azure Storage Path Prefix Fixes
rag/utils/azure_sas_conn.py, rag/utils/azure_spn_conn.py
Path construction modified across health, put, rm, get, and obj_exist to use bucket-qualified paths ("{bucket}/{fnm}") instead of flat filenames. get_presigned_url refactored to return client URL directly rather than calling connection-level method. Explicit None returns added in failure cases.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Buckets now prefix each file with care,
No more collisions floating in the air!
Azure paths grow logical and neat,
Datasets dance without collision heat. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 accurately summarizes the main change: adding bucket prefixes to Azure Blob storage operations for both SPN and SAS implementations.
Linked Issues check ✅ Passed The PR implements all required changes from issue #14159: bucket prefixes added to all methods (put, rm, get, obj_exist, get_presigned_url, health) in both azure_spn_conn.py and azure_sas_conn.py.
Out of Scope Changes check ✅ Passed All changes are directly related to the linked issue; both files modified are explicitly mentioned in the issue, with changes limited to adding bucket prefixes as specified.
Description check ✅ Passed The PR description clearly identifies the bug (ignored bucket parameter), explains the fix (prepend bucket/ prefix), lists affected files, and references the issue.

✏️ 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 and usage tips.

@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.

🧹 Nitpick comments (3)
rag/utils/azure_sas_conn.py (2)

50-85: LGTM on prefixing; get explicit-None return is a welcome consistency fix.

Minor optional nit: put (lines 54-61) still falls off the loop without an explicit return None on retry exhaustion, which is inconsistent with the explicit returns now used in get and get_presigned_url. Not a bug, but worth normalizing.

♻️ Optional normalization
     def put(self, bucket, fnm, binary, tenant_id=None):
         for _ in range(3):
             try:
                 return self.conn.upload_blob(name=f"{bucket}/{fnm}", data=BytesIO(binary), length=len(binary))
             except Exception:
                 logging.exception(f"Fail put {bucket}/{fnm}")
                 self.__open__()
                 time.sleep(1)
+        return None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/utils/azure_sas_conn.py` around lines 50 - 85, The put method retries up
to 3 times but does not explicitly return a value when all retries fail (unlike
get which returns None); update put (method put in rag/utils/azure_sas_conn.py)
to return None after the retry loop completes (optionally logging the final
failure) so callers get a consistent explicit None on exhaustion, and ensure
this change complements the existing exception handling and self.__open__ retry
behavior.

87-95: Pre-existing design issue: expires parameter is ignored; URL inherits container-wide SAS permissions instead of blob-scoped read-only.

This method accepts an expires parameter but never uses it. Because self.conn is a ContainerClient created from a container SAS URL, the child BlobClient.url includes the container's SAS query string—but with the container's full permission set (potentially write/delete), not a read-only, blob-scoped grant as encrypted_storage.get_presigned_url() and peer implementations like minio_conn.py provide.

Per tracked follow-ups, consider replacing with blob-scoped SAS generation using generate_blob_sas(..., permission=BlobSasPermissions(read=True), expiry=..., ) with the container SAS's account key, so the public contract (TTL + least-privilege) is honored. This is a pre-existing design limitation and separate from the bucket-prefix fix.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/utils/azure_sas_conn.py` around lines 87 - 95, get_presigned_url
currently ignores the expires parameter and returns the container SAS URL
(inheriting broad container permissions) via self.conn.get_blob_client(...).url;
update get_presigned_url to generate a blob-scoped, read-only SAS that honors
the expires TTL instead of returning the container SAS. Use the Azure SDK helper
generate_blob_sas with permission=BlobSasPermissions(read=True) and expiry set
from the expires arg, deriving the needed credentials from the existing
container client / connection (self.conn) or the account key, then return the
blob-specific URL (BlobClient.url + generated SAS token) so callers get a
least-privilege, time-limited URL.
rag/utils/azure_spn_conn.py (1)

65-108: Backward compatibility: existing flat-layout blobs become unreachable.

After this change, every get/rm/obj_exist resolves to {bucket}/{fnm}. Any blobs already written by the previous (flat) implementation under just fnm will no longer be found, so upgrading deployments risk silently "losing" their existing datasets. Consider adding a fallback read path (try {bucket}/{fnm} then {fnm}), a one-shot migration utility, or at minimum documenting this as a breaking change in the release notes.

Please confirm whether production/staging Azure SPN containers currently hold blobs written without the bucket prefix, and whether a migration step is planned alongside this PR.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/utils/azure_spn_conn.py` around lines 65 - 108, The change causes keys to
be looked up as "{bucket}/{fnm}", making previously stored flat keys ("{fnm}")
unreachable; update the storage accessors get, rm, and obj_exist in
rag/utils/azure_spn_conn.py to attempt the new names first (f"{bucket}/{fnm}")
and if not found/fails, fall back to the legacy flat key (f"{fnm}"); ensure get
tries the second path before returning None, rm attempts to delete both paths,
and obj_exist returns True if either path exists; optionally mention put
behavior (leave writing to new path only or write both) in a comment or add a
migration helper if desired.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@rag/utils/azure_sas_conn.py`:
- Around line 50-85: The put method retries up to 3 times but does not
explicitly return a value when all retries fail (unlike get which returns None);
update put (method put in rag/utils/azure_sas_conn.py) to return None after the
retry loop completes (optionally logging the final failure) so callers get a
consistent explicit None on exhaustion, and ensure this change complements the
existing exception handling and self.__open__ retry behavior.
- Around line 87-95: get_presigned_url currently ignores the expires parameter
and returns the container SAS URL (inheriting broad container permissions) via
self.conn.get_blob_client(...).url; update get_presigned_url to generate a
blob-scoped, read-only SAS that honors the expires TTL instead of returning the
container SAS. Use the Azure SDK helper generate_blob_sas with
permission=BlobSasPermissions(read=True) and expiry set from the expires arg,
deriving the needed credentials from the existing container client / connection
(self.conn) or the account key, then return the blob-specific URL
(BlobClient.url + generated SAS token) so callers get a least-privilege,
time-limited URL.

In `@rag/utils/azure_spn_conn.py`:
- Around line 65-108: The change causes keys to be looked up as
"{bucket}/{fnm}", making previously stored flat keys ("{fnm}") unreachable;
update the storage accessors get, rm, and obj_exist in
rag/utils/azure_spn_conn.py to attempt the new names first (f"{bucket}/{fnm}")
and if not found/fails, fall back to the legacy flat key (f"{fnm}"); ensure get
tries the second path before returning None, rm attempts to delete both paths,
and obj_exist returns True if either path exists; optionally mention put
behavior (leave writing to new path only or write both) in a comment or add a
migration helper if desired.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2c9f9304-be3e-43fb-a97b-2dd2e6607c8f

📥 Commits

Reviewing files that changed from the base of the PR and between 199fbce and eadcd48.

📒 Files selected for processing (2)
  • rag/utils/azure_sas_conn.py
  • rag/utils/azure_spn_conn.py

@wangq8
wangq8 requested a review from Magicbook1108 April 24, 2026 09:46
@wangq8 wangq8 added the ci Continue Integration label Apr 24, 2026
@wangq8
wangq8 marked this pull request as draft April 24, 2026 09:47
@wangq8
wangq8 marked this pull request as ready for review April 24, 2026 09:47
@codecov

codecov Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (bb10b83) to head (f6aaef2).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14347   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Magicbook1108

Copy link
Copy Markdown
Contributor

Can you provide screen shots to proof your modification valid ?

Comment thread rag/utils/azure_spn_conn.py Outdated
def get_presigned_url(self, bucket, fnm, expires):
for _ in range(10):
try:
return self.conn.get_presigned_url("GET", bucket, fnm, expires)

@JinHai-CN JinHai-CN Apr 27, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why change it to self.conn.get_file_client?

Comment thread rag/utils/azure_sas_conn.py Outdated
def get_presigned_url(self, bucket, fnm, expires):
for _ in range(10):
try:
return self.conn.get_presigned_url("GET", bucket, fnm, expires)

@JinHai-CN JinHai-CN Apr 27, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why change it to self.conn.get_blob_client(f"{bucket}/{fnm}").url?

@Magicbook1108 Magicbook1108 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.

LGTM

@JinHai-CN
JinHai-CN merged commit f063e03 into infiniflow:main May 8, 2026
1 check passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
…nfiniflow#14347)

## Summary

Fixes file collision between different datasets when using Azure Blob
storage (SPN or SAS authentication).

## Bug

azure_spn_conn.py and �zure_sas_conn.py ignored the �ucket parameter
entirely, storing all files flat with just the filename. This caused
files with the same name from different datasets (knowledge bases) to
overwrite each other.

## Fix

Prepend bucket/ as a path prefix in all methods (put, 
m, get, obj_exist, get_presigned_url, health) to match the behavior of
MinIO and S3 implementations.

## Changes

- **rag/utils/azure_spn_conn.py**: Added {bucket}/ prefix to file paths
in all operations
- **rag/utils/azure_sas_conn.py**: Same fix applied for consistency
(also noted in the original issue)

## Testing

Manual verification: files from different datasets now stored under
distinct bucket/ prefixes, preventing collisions.

Fixes infiniflow#14159

Co-authored-by: Hunter <[email protected]>
Co-authored-by: Jin Hai <[email protected]>
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…nfiniflow#14347)

## Summary

Fixes file collision between different datasets when using Azure Blob
storage (SPN or SAS authentication).

## Bug

azure_spn_conn.py and �zure_sas_conn.py ignored the �ucket parameter
entirely, storing all files flat with just the filename. This caused
files with the same name from different datasets (knowledge bases) to
overwrite each other.

## Fix

Prepend bucket/ as a path prefix in all methods (put, 
m, get, obj_exist, get_presigned_url, health) to match the behavior of
MinIO and S3 implementations.

## Changes

- **rag/utils/azure_spn_conn.py**: Added {bucket}/ prefix to file paths
in all operations
- **rag/utils/azure_sas_conn.py**: Same fix applied for consistency
(also noted in the original issue)

## Testing

Manual verification: files from different datasets now stored under
distinct bucket/ prefixes, preventing collisions.

Fixes infiniflow#14159

Co-authored-by: Hunter <[email protected]>
Co-authored-by: Jin Hai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Azure Blob SPN storage: files from different datasets can overwrite each other due to missing bucket prefix

4 participants