Repository navigation
fix: add bucket prefix to Azure Blob SPN and SAS storage operations - #14347
Conversation
- 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.
📝 WalkthroughWalkthroughTwo Azure storage connection utilities are updated to prepend bucket prefixes to file paths across all file operations, resolving filename collision issues between datasets. The Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes 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.
🧹 Nitpick comments (3)
rag/utils/azure_sas_conn.py (2)
50-85: LGTM on prefixing;getexplicit-None return is a welcome consistency fix.Minor optional nit:
put(lines 54-61) still falls off the loop without an explicitreturn Noneon retry exhaustion, which is inconsistent with the explicit returns now used ingetandget_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:expiresparameter is ignored; URL inherits container-wide SAS permissions instead of blob-scoped read-only.This method accepts an
expiresparameter but never uses it. Becauseself.connis aContainerClientcreated from a container SAS URL, the childBlobClient.urlincludes the container's SAS query string—but with the container's full permission set (potentially write/delete), not a read-only, blob-scoped grant asencrypted_storage.get_presigned_url()and peer implementations likeminio_conn.pyprovide.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_existresolves to{bucket}/{fnm}. Any blobs already written by the previous (flat) implementation under justfnmwill 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
📒 Files selected for processing (2)
rag/utils/azure_sas_conn.pyrag/utils/azure_spn_conn.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
Can you provide screen shots to proof your modification valid ? |
| def get_presigned_url(self, bucket, fnm, expires): | ||
| for _ in range(10): | ||
| try: | ||
| return self.conn.get_presigned_url("GET", bucket, fnm, expires) |
There was a problem hiding this comment.
Why change it to self.conn.get_file_client?
| def get_presigned_url(self, bucket, fnm, expires): | ||
| for _ in range(10): | ||
| try: | ||
| return self.conn.get_presigned_url("GET", bucket, fnm, expires) |
There was a problem hiding this comment.
Why change it to self.conn.get_blob_client(f"{bucket}/{fnm}").url?
…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]>
…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]>
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
Testing
Manual verification: files from different datasets now stored under distinct bucket/ prefixes, preventing collisions.
Fixes #14159