feat: implement tenant validation for file access and enhance related tests

This commit introduces a new validation mechanism to ensure that file access paths include the correct tenant segment, preventing cross-tenant access. The `ValidateStoragePathTenant` function has been added to enforce this rule, and the `serveFiles` function has been updated to return a forbidden status for invalid paths. Additionally, new tests have been added to verify the behavior of the file service under various tenant scenarios, ensuring robust handling of file access permissions.
This commit is contained in:
wizardchen
2026-05-29 13:44:20 +08:00
committed by lyingbug
parent 48381fbaf5
commit bb202a203a
4 changed files with 74 additions and 2 deletions
+14
View File
@@ -95,6 +95,20 @@ func VerifyFileURLSig(filePath string, tenantID uint64, expiresStr, sig string)
return hmac.Equal([]byte(expected), []byte(sig))
}
// ValidateStoragePathTenant ensures the tenant segment embedded in a provider://
// storage path matches the authenticated caller's tenant. Cross-tenant access
// must use /api/v1/files/presigned with an HMAC bound to the resource owner.
func ValidateStoragePathTenant(filePath string, tenantID uint64) error {
pathTenant := ParseTenantIDFromStoragePath(filePath)
if pathTenant == 0 {
return fmt.Errorf("storage path has no tenant segment")
}
if pathTenant != tenantID {
return fmt.Errorf("storage path tenant mismatch")
}
return nil
}
// ParseTenantIDFromStoragePath extracts the tenant ID from a provider:// storage path.
// Storage paths follow the convention: {scheme}://.../{tenantID}/...
// Returns 0 if the path does not contain a valid tenant ID.
+6
View File
@@ -86,6 +86,12 @@ func TestVerifyFileURLSig_NoKey(t *testing.T) {
assert.False(t, VerifyFileURLSig("local://1/img.png", 1, "99999999999", "abc"))
}
func TestValidateStoragePathTenant(t *testing.T) {
assert.NoError(t, ValidateStoragePathTenant("local://42/knowledge/file.pdf", 42))
assert.Error(t, ValidateStoragePathTenant("local://7/knowledge/file.pdf", 42))
assert.Error(t, ValidateStoragePathTenant("local://docs/example.txt", 42))
}
func TestParseTenantIDFromStoragePath(t *testing.T) {
tests := []struct {
path string