You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "fallintoplace (via GitHub)" <gi...@apache.org> on 2026/06/22 23:12:15 UTC

[PR] fix(io): validate cloud object URI buckets [iceberg-go]

fallintoplace opened a new pull request, #1259:
URL: https://github.com/apache/iceberg-go/pull/1259

   Summary
   - validate S3/GCS/OSS URI authorities before turning locations into object keys
   - reject wrong-bucket and empty-key object paths instead of treating the bucket name as part of the key
   - run WalkDir roots through the same extractor so list operations reject the same bad authorities
   - add S3 and GCS regression coverage for extractor, write, and walk paths
   
   Why
   The old extractor removed the scheme and then tried to trim the configured bucket prefix. If the prefix did not match, a path like s3://other-bucket/data/file.parquet became the key other-bucket/data/file.parquet in the opened bucket. That makes reads, writes, and deletes land under a surprising key instead of failing early.
   
   Testing
   - go test ./io/gocloud -run 'TestDefaultKeyExtractor|TestBlobFileIORejectsWrongBucketObjectPaths|TestBlobFileIOWalkDir' -count=1
   - go test ./io/gocloud -count=1
   - go test ./io -count=1
   - go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.8.0 run --timeout=10m ./io/gocloud
   - git diff --check
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "fallintoplace (via GitHub)" <gi...@apache.org>.
fallintoplace commented on code in PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#discussion_r3478007877


##########
io/gocloud/blob.go:
##########
@@ -188,25 +284,52 @@ func (bfs *blobFileIO) NewWriter(ctx context.Context, path string, overwrite boo
 		nil
 }
 
-func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor) icebergio.IO {
-	return &blobFileIO{Bucket: bucket, keyExtractor: keyExtractor, ctx: ctx}
+func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor, extractObject ...objectLocationExtractor) icebergio.IO {

Review Comment:
   Thank you for your attention, I will have a look tomorrow evening.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#issuecomment-4840618724

   Sound good to me


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#discussion_r3521437089


##########
io/gocloud/blob_test.go:
##########
@@ -57,42 +86,142 @@ func TestDefaultKeyExtractor(t *testing.T) {
 			input:       "gs://my-bucket/path/to/file.parquet",
 			expectedKey: "path/to/file.parquet",
 		},
+		{
+			name:        "azure URI with path",
+			bucketName:  "container@account.dfs.core.windows.net",
+			input:       "abfs://container@account.dfs.core.windows.net/path/to/file.parquet",
+			expectedKey: "path/to/file.parquet",
+		},
+		{

Review Comment:
   [MINOR] The tests exercise different-bucket rejection here, but they still do not cover the wrong-scheme/same-authority bypass. Please add cases for an s3 FileIO receiving `gs://same-bucket/...` and a gs FileIO receiving `s3://same-bucket/...`.



##########
io/gocloud/blob.go:
##########
@@ -69,33 +68,102 @@ func (f *blobOpenFile) Sys() any                   { return f.b }
 func (f *blobOpenFile) IsDir() bool                { return false }
 func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 
-// KeyExtractor extracts the object key from an input path
+// KeyExtractor extracts the object key from an input path.
 type KeyExtractor func(path string) (string, error)
 
-// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
-// e.g., s3://bucket/path/file -> path/file
-func defaultKeyExtractor(bucketName string) KeyExtractor {
+var errEmptyObjectKey = errors.New("object key is empty")

Review Comment:
   [MINOR] `errEmptyObjectKey` is now surfaced through public IO errors (including `WalkDir` handling around `io/gocloud/blob.go:301-304`) but remains unexported, so consumers cannot use `errors.Is` against it. Export it or document that callers should not depend on this sentinel.



##########
io/gocloud/blob.go:
##########
@@ -69,33 +68,102 @@ func (f *blobOpenFile) Sys() any                   { return f.b }
 func (f *blobOpenFile) IsDir() bool                { return false }
 func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 
-// KeyExtractor extracts the object key from an input path
+// KeyExtractor extracts the object key from an input path.
 type KeyExtractor func(path string) (string, error)
 
-// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
-// e.g., s3://bucket/path/file -> path/file
-func defaultKeyExtractor(bucketName string) KeyExtractor {
+var errEmptyObjectKey = errors.New("object key is empty")
+
+type objectLocation struct {
+	authority    string
+	key          string
+	uriPrefix    string
+	hasAuthority bool
+}
+
+func splitObjectLocation(location string) (objectLocation, error) {
+	scheme, rest, ok := strings.Cut(location, "://")
+	if !ok {
+		return objectLocation{key: location}, nil
+	}
+
+	authorityEnd := strings.IndexAny(rest, "/?#")
+	if authorityEnd == -1 {
+		authorityEnd = len(rest)
+	}
+
+	authority := rest[:authorityEnd]
+	if authority == "" {
+		return objectLocation{}, fmt.Errorf("URI authority is empty: %s", location)
+	}
+
+	key := ""
+	if authorityEnd < len(rest) {
+		if rest[authorityEnd] != '/' {
+			return objectLocation{}, fmt.Errorf("URI authority %q must be followed by an object path: %s",
+				authority, location)
+		}
+
+		// Keep object keys raw. Cloud object names are opaque strings, so this
+		// intentionally does not URL-unescape literal %, spaces, ? or #.
+		key = strings.TrimPrefix(rest[authorityEnd:], "/")
+	}
+
+	return objectLocation{
+		authority:    authority,
+		key:          key,
+		uriPrefix:    scheme + "://" + authority + "/",
+		hasAuthority: true,
+	}, nil
+}
+
+type objectLocationExtractor func(location string) (objectLocation, error)
+
+func keyExtractorFromObjectLocation(extract objectLocationExtractor) KeyExtractor {
 	return func(location string) (string, error) {
-		_, after, found := strings.Cut(location, "://")
-		if found {
-			location = after
+		parsed, err := extract(location)
+		if err != nil {
+			return "", err
+		}
+
+		return parsed.key, nil
+	}
+}
+
+func defaultObjectLocationExtractor(bucketName string) objectLocationExtractor {
+	return func(location string) (objectLocation, error) {
+		parsed, err := splitObjectLocation(location)
+		if err != nil {
+			return objectLocation{}, err
 		}
 
-		key := strings.TrimPrefix(location, bucketName+"/")
+		if parsed.hasAuthority {

Review Comment:
   [MAJOR] `splitObjectLocation` records only authority-derived state while `defaultObjectLocationExtractor` validates only `authority == bucketName`, so an S3-backed FileIO can accept `gs://same-bucket/path` (and the reverse) as long as the authority matches. Carry the URI scheme in `objectLocation`, validate it against the backend's allowed schemes from registration, and add s3+gs wrong-scheme/same-authority tests.



##########
io/gocloud/azure.go:
##########
@@ -201,21 +201,48 @@ func createAzureBucket(ctx context.Context, parsed *url.URL, props map[string]st
 	return azureblob.OpenBucket(ctx, client, nil)
 }
 
-// adlsKeyExtractor creates a key extractor for Azure schemes using the adlsURIPattern pattern
-func adlsKeyExtractor() KeyExtractor {
-	return func(location string) (string, error) {
+func adlsAuthority(parsed *url.URL) string {
+	if parsed.User == nil {
+		return parsed.Hostname()
+	}
+
+	return parsed.User.Username() + "@" + parsed.Hostname()
+}
+
+func adlsObjectLocationExtractor(parsedURL *url.URL) objectLocationExtractor {
+	expectedAuthority := adlsAuthority(parsedURL)
+
+	return func(location string) (objectLocation, error) {
 		matches := adlsURIPattern.FindStringSubmatch(location)
 		if len(matches) < 4 {
-			return "", fmt.Errorf("invalid ADLS location: %s", location)
+			return objectLocation{}, fmt.Errorf("invalid ADLS location: %s", location)
+		}
+
+		authority := matches[2]
+		if authority != expectedAuthority {

Review Comment:
   [MAJOR] This hard authority check also applies to the generic blob path at `io/gocloud/blob.go:139-143`, so read/write/delete/walk reject object URIs whose bucket/container differs from the opened root. Iceberg tables may legally reference data in another bucket/container. Please make an explicit design choice: route per authority, return a documented unsupported-mode error, or narrow the rejection to write/delete only.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#discussion_r3493439697


##########
io/gocloud/blob.go:
##########
@@ -69,33 +68,138 @@ func (f *blobOpenFile) Sys() any                   { return f.b }
 func (f *blobOpenFile) IsDir() bool                { return false }
 func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 
-// KeyExtractor extracts the object key from an input path
+// KeyExtractor extracts the object key from an input path.
 type KeyExtractor func(path string) (string, error)
 
-// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
-// e.g., s3://bucket/path/file -> path/file
-func defaultKeyExtractor(bucketName string) KeyExtractor {
+var errEmptyObjectKey = errors.New("object key is empty")
+
+type objectLocation struct {
+	authority    string
+	key          string
+	uriKey       string
+	uriPrefix    string
+	hasAuthority bool
+}
+
+func splitObjectLocation(location string) (objectLocation, error) {
+	scheme, rest, ok := strings.Cut(location, "://")
+	if !ok {
+		return objectLocation{key: location, uriKey: location}, nil
+	}
+
+	authorityEnd := strings.IndexAny(rest, "/?#")
+	if authorityEnd == -1 {
+		authorityEnd = len(rest)
+	}
+
+	authority := rest[:authorityEnd]
+	if authority == "" {
+		return objectLocation{}, fmt.Errorf("URI authority is empty: %s", location)
+	}
+
+	key := ""
+	if authorityEnd < len(rest) {
+		if rest[authorityEnd] != '/' {
+			return objectLocation{}, fmt.Errorf("URI authority %q must be followed by an object path: %s",
+				authority, location)
+		}
+
+		key = strings.TrimPrefix(rest[authorityEnd:], "/")
+	}
+
+	return objectLocation{
+		authority:    authority,
+		key:          key,
+		uriKey:       key,
+		uriPrefix:    scheme + "://" + authority + "/",
+		hasAuthority: true,
+	}, nil
+}
+
+type keyExtractorConfig struct {
+	strictAuthorityValidation bool
+}
+
+type keyExtractorOption func(*keyExtractorConfig)
+
+func withStrictAuthorityValidation() keyExtractorOption {
+	return func(cfg *keyExtractorConfig) {
+		cfg.strictAuthorityValidation = true
+	}
+}
+
+type objectLocationExtractor func(location string) (objectLocation, error)
+
+func keyExtractorFromObjectLocation(extract objectLocationExtractor) KeyExtractor {
 	return func(location string) (string, error) {
-		_, after, found := strings.Cut(location, "://")
-		if found {
-			location = after
+		parsed, err := extract(location)
+		if err != nil {
+			return "", err
+		}
+
+		return parsed.key, nil
+	}
+}
+
+// Non-strict cross-authority paths still fold into a storage key so existing
+// manifests keep loading until the FileIO can open per-authority buckets.
+func legacyAuthorityKey(parsed objectLocation) string {
+	if parsed.key == "" {
+		return parsed.authority + "/"
+	}
+
+	return parsed.authority + "/" + parsed.key
+}
+
+func defaultObjectLocationExtractor(bucketName string, opts ...keyExtractorOption) objectLocationExtractor {
+	var cfg keyExtractorConfig
+	for _, opt := range opts {
+		opt(&cfg)
+	}
+
+	return func(location string) (objectLocation, error) {
+		parsed, err := splitObjectLocation(location)
+		if err != nil {
+			return objectLocation{}, err
 		}
 
-		key := strings.TrimPrefix(location, bucketName+"/")
+		if parsed.hasAuthority {
+			if parsed.authority != bucketName {
+				if cfg.strictAuthorityValidation {
+					return objectLocation{}, fmt.Errorf("URI authority %q does not match configured authority %q",
+						parsed.authority, bucketName)
+				}
+
+				// Preserve the legacy fold-by-authority behavior on the default
+				// path so existing cross-authority manifests keep loading until
+				// the FileIO can open per-authority buckets.
+				parsed.key = legacyAuthorityKey(parsed)
+			}
+		} else {
+			parsed.key = strings.TrimPrefix(location, bucketName+"/")
+			parsed.uriKey = parsed.key
+		}
 
-		if key == "" {
-			return "", fmt.Errorf("URI path is empty: %s", location)
+		if parsed.key == "" {
+			return parsed, fmt.Errorf("%w: %s", errEmptyObjectKey, location)
 		}
 
-		return key, nil
+		return parsed, nil
 	}
 }
 
+// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI.
+// e.g., s3://bucket/path/file -> path/file.
+func defaultKeyExtractor(bucketName string, opts ...keyExtractorOption) KeyExtractor {
+	return keyExtractorFromObjectLocation(defaultObjectLocationExtractor(bucketName, opts...))
+}
+
 type blobFileIO struct {
 	*blob.Bucket
 
-	keyExtractor KeyExtractor
-	ctx          context.Context
+	keyExtractor  KeyExtractor

Review Comment:
   `blobFileIO` stores both `keyExtractor` and `extractObject`, but `keyExtractor` is always derived from `extractObject` via `keyExtractorFromObjectLocation` in every path. Storing both invites drift — consider keeping only `extractObject` and deriving the extractor where needed (and dropping it from the `createBlobFS` signature).



##########
io/gocloud/register.go:
##########
@@ -30,6 +31,14 @@ func init() {
 	registerAzureSchemes()
 }
 
+func keyExtractorOptions(props map[string]string) []keyExtractorOption {
+	if enabled, err := strconv.ParseBool(props[icebergio.ObjectStoreStrictAuthorityValidation]); err == nil && enabled {

Review Comment:
   Strict-mode opt-in silently swallows `ParseBool` errors — a typo like `"ture"`/`"yes"` disables validation invisibly. Since the prop only accepts the two bool spellings, consider returning the parse error to the factory instead of ignoring it.



##########
io/gocloud/blob.go:
##########
@@ -198,25 +302,64 @@ func (bfs *blobFileIO) NewWriter(ctx context.Context, path string, overwrite boo
 		nil
 }
 
-func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor) icebergio.IO {
-	return &blobFileIO{Bucket: bucket, keyExtractor: keyExtractor, ctx: ctx}
+func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor, extractObject objectLocationExtractor) icebergio.IO {
+	return &blobFileIO{Bucket: bucket, keyExtractor: keyExtractor, extractObject: extractObject, ctx: ctx}
+}
+
+func (bfs *blobFileIO) objectLocation(root string) (objectLocation, error) {
+	if bfs.extractObject == nil {
+		return objectLocation{}, errors.New("blob file IO missing object location extractor")
+	}
+
+	return bfs.extractObject(root)
+}
+
+func walkedURIPath(location objectLocation, walked string) string {
+	if walked == "." {
+		return location.uriPrefix
+	}
+
+	uriKey := walked
+	if location.key != location.uriKey {
+		storageRoot := strings.TrimSuffix(location.key, "/")
+		if walked == location.key || walked == storageRoot {
+			uriKey = location.uriKey
+		} else {
+			prefix := storageRoot + "/"
+			if suffix, ok := strings.CutPrefix(walked, prefix); ok {

Review Comment:
   If `walked` matches none of `location.key` / `storageRoot` / `storageRoot+"/"`, this `ok=false` path leaves `uriKey = walked`, producing `uriPrefix + walked` with the bucket doubled (e.g. `s3://other-bucket/other-bucket/foo`). Unreachable today since `WalkDir` only emits descendants, but a silent fallback — consider an explicit error or an invariant comment.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#discussion_r3461715826


##########
io/gocloud/blob.go:
##########
@@ -72,25 +72,61 @@ func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 // KeyExtractor extracts the object key from an input path
 type KeyExtractor func(path string) (string, error)
 
+var errEmptyObjectKey = errors.New("object key is empty")
+
 // defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
 // e.g., s3://bucket/path/file -> path/file
 func defaultKeyExtractor(bucketName string) KeyExtractor {
 	return func(location string) (string, error) {
-		_, after, found := strings.Cut(location, "://")
-		if found {
-			location = after
+		parsed, err := url.Parse(location)
+		if err != nil {
+			return "", fmt.Errorf("invalid URI %q: %w", location, err)
 		}
 
-		key := strings.TrimPrefix(location, bucketName+"/")
+		var key string
+		if validatesURIAuthority(parsed.Scheme) && (parsed.Scheme != "" || parsed.Host != "") {
+			if parsed.Host == "" {
+				return "", fmt.Errorf("URI bucket is empty: %s", location)
+			}
+			if parsed.Host != bucketName {
+				return "", fmt.Errorf("URI bucket %q does not match configured bucket %q", parsed.Host, bucketName)
+			}
+
+			key = strings.TrimPrefix(parsed.EscapedPath(), "/")
+			if key != "" {
+				if parsed.RawQuery != "" {
+					key += "?" + parsed.RawQuery
+				}
+				if parsed.Fragment != "" {
+					key += "#" + parsed.EscapedFragment()
+				}
+			}
+		} else {
+			_, after, found := strings.Cut(location, "://")
+			if found {
+				location = after
+			}
+
+			key = strings.TrimPrefix(location, bucketName+"/")
+		}
 
 		if key == "" {
-			return "", fmt.Errorf("URI path is empty: %s", location)
+			return "", fmt.Errorf("%w: %s", errEmptyObjectKey, location)
 		}
 
 		return key, nil
 	}
 }
 
+func validatesURIAuthority(scheme string) bool {
+	switch scheme {
+	case "", "s3", "s3a", "s3n", "oss", "gs":

Review Comment:
   isn't this missing azure authorities and others?



##########
io/gocloud/blob.go:
##########
@@ -72,25 +72,61 @@ func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 // KeyExtractor extracts the object key from an input path
 type KeyExtractor func(path string) (string, error)
 
+var errEmptyObjectKey = errors.New("object key is empty")

Review Comment:
   should this be public so that consumers can use `errors.Is`?



##########
io/gocloud/blob.go:
##########
@@ -72,25 +72,61 @@ func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 // KeyExtractor extracts the object key from an input path
 type KeyExtractor func(path string) (string, error)
 
+var errEmptyObjectKey = errors.New("object key is empty")
+
 // defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
 // e.g., s3://bucket/path/file -> path/file
 func defaultKeyExtractor(bucketName string) KeyExtractor {
 	return func(location string) (string, error) {
-		_, after, found := strings.Cut(location, "://")
-		if found {
-			location = after
+		parsed, err := url.Parse(location)
+		if err != nil {
+			return "", fmt.Errorf("invalid URI %q: %w", location, err)
 		}
 
-		key := strings.TrimPrefix(location, bucketName+"/")
+		var key string
+		if validatesURIAuthority(parsed.Scheme) && (parsed.Scheme != "" || parsed.Host != "") {
+			if parsed.Host == "" {
+				return "", fmt.Errorf("URI bucket is empty: %s", location)
+			}
+			if parsed.Host != bucketName {
+				return "", fmt.Errorf("URI bucket %q does not match configured bucket %q", parsed.Host, bucketName)
+			}
+
+			key = strings.TrimPrefix(parsed.EscapedPath(), "/")
+			if key != "" {
+				if parsed.RawQuery != "" {
+					key += "?" + parsed.RawQuery
+				}
+				if parsed.Fragment != "" {
+					key += "#" + parsed.EscapedFragment()
+				}
+			}
+		} else {
+			_, after, found := strings.Cut(location, "://")
+			if found {
+				location = after
+			}
+
+			key = strings.TrimPrefix(location, bucketName+"/")
+		}

Review Comment:
   what's the case where the `url.Parse` succeeds but the condition at line 87 fails? can't we still just use `parsed` to figure this out instead of needing to do `strings.Cut`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#discussion_r3474015374


##########
io/gocloud/blob.go:
##########
@@ -188,25 +284,52 @@ func (bfs *blobFileIO) NewWriter(ctx context.Context, path string, overwrite boo
 		nil
 }
 
-func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor) icebergio.IO {
-	return &blobFileIO{Bucket: bucket, keyExtractor: keyExtractor, ctx: ctx}
+func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor, extractObject ...objectLocationExtractor) icebergio.IO {

Review Comment:
   I'd make `extractObject` a required parameter rather than variadic.
   
   The variadic reads as composable but isn't — only `[0]` is ever used, a second arg is silently dropped, and `createBlobFS(ctx, bucket, ext, nil)` is legal and quietly installs a nil extractor that sends every call down the fallback path below. The only callers relying on the optionality are a few old 3-arg test helpers; I'd rather update those four call sites than keep a fallback that papers over a real semantic difference.



##########
io/config.go:
##########
@@ -17,6 +17,14 @@
 
 package io
 
+// Constants for generic object store configuration options.
+const (
+	// ObjectStoreStrictAuthorityValidation rejects fully-qualified object paths
+	// whose URI authority differs from the bucket or container used to create
+	// the FileIO.
+	ObjectStoreStrictAuthorityValidation = "object-store.strict-authority-validation"

Review Comment:
   This sits at the top level next to `s3.*`/`gcs.*`/`adls.*`, all of which are mirrored in Java and PyIceberg — but `object-store.strict-authority-validation` is Go-only. Java's `S3FileIO`/`ADLSFileIO` and PyIceberg's fsspec create per-authority FileIO instances and have no cross-authority knob, so a user who sets this in table properties expecting portable behavior gets it honored only by the gocloud backend and silently ignored elsewhere.
   
   I'd either move it into the gocloud package unexported and wire it through the functional option you already have, or, if it stays exported, add a doc comment that it's honored only by the gocloud FileIO and ignored by Java/PyIceberg/Rust. wdyt?



##########
io/gocloud/blob.go:
##########
@@ -69,33 +68,130 @@ func (f *blobOpenFile) Sys() any                   { return f.b }
 func (f *blobOpenFile) IsDir() bool                { return false }
 func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 
-// KeyExtractor extracts the object key from an input path
+// KeyExtractor extracts the object key from an input path.
 type KeyExtractor func(path string) (string, error)
 
-// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
-// e.g., s3://bucket/path/file -> path/file
-func defaultKeyExtractor(bucketName string) KeyExtractor {
+var errEmptyObjectKey = errors.New("object key is empty")
+
+type objectLocation struct {
+	authority    string
+	key          string
+	uriPrefix    string
+	hasAuthority bool
+}
+
+func splitObjectLocation(location string) (objectLocation, error) {
+	scheme, rest, ok := strings.Cut(location, "://")
+	if !ok {
+		return objectLocation{key: location}, nil
+	}
+
+	authorityEnd := strings.IndexAny(rest, "/?#")
+	if authorityEnd == -1 {
+		authorityEnd = len(rest)
+	}
+
+	authority := rest[:authorityEnd]
+	if authority == "" {
+		return objectLocation{}, fmt.Errorf("URI authority is empty: %s", location)
+	}
+
+	key := ""
+	if authorityEnd < len(rest) {
+		if rest[authorityEnd] != '/' {
+			return objectLocation{}, fmt.Errorf("URI authority %q must be followed by an object path: %s",
+				authority, location)
+		}
+
+		key = strings.TrimPrefix(rest[authorityEnd:], "/")
+	}
+
+	return objectLocation{
+		authority:    authority,
+		key:          key,
+		uriPrefix:    scheme + "://" + authority + "/",
+		hasAuthority: true,
+	}, nil
+}
+
+type keyExtractorConfig struct {
+	strictAuthorityValidation bool
+}
+
+type keyExtractorOption func(*keyExtractorConfig)
+
+func withStrictAuthorityValidation() keyExtractorOption {
+	return func(cfg *keyExtractorConfig) {
+		cfg.strictAuthorityValidation = true
+	}
+}
+
+type objectLocationExtractor func(location string) (objectLocation, error)
+
+func keyExtractorFromObjectLocation(extract objectLocationExtractor) KeyExtractor {
 	return func(location string) (string, error) {
-		_, after, found := strings.Cut(location, "://")
-		if found {
-			location = after
+		parsed, err := extract(location)
+		if err != nil {
+			return "", err
+		}
+
+		return parsed.key, nil
+	}
+}
+
+func legacyAuthorityKey(parsed objectLocation) string {
+	if parsed.key == "" {
+		return parsed.authority + "/"
+	}
+
+	return parsed.authority + "/" + parsed.key
+}
+
+func defaultObjectLocationExtractor(bucketName string, opts ...keyExtractorOption) objectLocationExtractor {
+	var cfg keyExtractorConfig
+	for _, opt := range opts {
+		opt(&cfg)
+	}
+
+	return func(location string) (objectLocation, error) {
+		parsed, err := splitObjectLocation(location)
+		if err != nil {
+			return objectLocation{}, err
 		}
 
-		key := strings.TrimPrefix(location, bucketName+"/")
+		if parsed.hasAuthority {
+			if parsed.authority != bucketName {
+				if cfg.strictAuthorityValidation {
+					return objectLocation{}, fmt.Errorf("URI authority %q does not match configured authority %q",
+						parsed.authority, bucketName)
+				}
 
-		if key == "" {
-			return "", fmt.Errorf("URI path is empty: %s", location)
+				parsed.key = legacyAuthorityKey(parsed)

Review Comment:
   In non-strict mode a cross-authority URI silently becomes a key inside the configured bucket, which I think is riskier than the old behavior.
   
   `s3://data-bucket/snap-1.avro` against a FileIO bound to `meta-bucket` writes an object at key `data-bucket/snap-1.avro` inside `meta-bucket` and reports success, where the SDK previously returned a clear not-found. I'd either make strict the default with an explicit `object-store.allow-cross-authority` opt-out, or at minimum emit a structured warning here so a misconfigured FileIO leaves a trace instead of silently misplacing data. Which way would you prefer — strict-by-default, or keep the legacy fold but make it loud?



##########
io/gocloud/blob.go:
##########
@@ -188,25 +284,52 @@ func (bfs *blobFileIO) NewWriter(ctx context.Context, path string, overwrite boo
 		nil
 }
 
-func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor) icebergio.IO {
-	return &blobFileIO{Bucket: bucket, keyExtractor: keyExtractor, ctx: ctx}
+func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor, extractObject ...objectLocationExtractor) icebergio.IO {
+	var extractor objectLocationExtractor
+	if len(extractObject) > 0 {
+		extractor = extractObject[0]
+	}
+
+	return &blobFileIO{Bucket: bucket, keyExtractor: keyExtractor, extractObject: extractor, ctx: ctx}
+}
+
+func (bfs *blobFileIO) objectLocation(root string) (objectLocation, error) {
+	if bfs.extractObject != nil {
+		return bfs.extractObject(root)
+	}
+
+	location, err := splitObjectLocation(root)
+	if err != nil {
+		return objectLocation{}, err
+	}
+
+	key, err := bfs.preprocess(root)
+	location.key = key
+
+	return location, err
 }
 
 func (bfs *blobFileIO) WalkDir(root string, fn fs.WalkDirFunc) error {
-	parsed, err := url.Parse(root)
+	location, err := bfs.objectLocation(root)
+	walkPath := location.key
 	if err != nil {
-		return fmt.Errorf("invalid URL %s: %w", root, err)
-	}
+		if !errors.Is(err, errEmptyObjectKey) {
+			return &fs.PathError{Op: "walk dir", Path: root, Err: err}
+		}
 
-	walkPath := strings.TrimPrefix(parsed.Path, "/")
-	if walkPath == "" {
 		walkPath = "."
 	}
 
-	parsed.Path = ""
-
 	return fs.WalkDir(bfs.Bucket, walkPath, func(path string, d fs.DirEntry, err error) error {
-		return fn(parsed.JoinPath(path).String(), d, err)
+		if location.hasAuthority {
+			if path == "." {
+				path = location.uriPrefix
+			} else {
+				path = location.uriPrefix + path

Review Comment:
   The same doubled-authority bug surfaces here on the non-strict path even with `extractObject` set: `defaultObjectLocationExtractor` folds the authority into `parsed.key` via `legacyAuthorityKey` but leaves `uriPrefix` as the original `s3://other-bucket/`, so `walkPath = "other-bucket/data"`, the walk yields `other-bucket/data/file.parquet`, and this line prepends `s3://other-bucket/` to give `s3://other-bucket/other-bucket/data/file.parquet`.
   
   A table case would lock this down: write a file at `other-bucket/data/file.parquet`, walk `s3://other-bucket/data` non-strict against a FileIO bound to `my-bucket`, and assert no returned path contains a duplicated authority. Every current WalkDir test uses a matching authority or strict mode, so this path is unguarded.



##########
io/gocloud/blob.go:
##########
@@ -188,25 +284,52 @@ func (bfs *blobFileIO) NewWriter(ctx context.Context, path string, overwrite boo
 		nil
 }
 
-func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor) icebergio.IO {
-	return &blobFileIO{Bucket: bucket, keyExtractor: keyExtractor, ctx: ctx}
+func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtractor, extractObject ...objectLocationExtractor) icebergio.IO {
+	var extractor objectLocationExtractor
+	if len(extractObject) > 0 {
+		extractor = extractObject[0]
+	}
+
+	return &blobFileIO{Bucket: bucket, keyExtractor: keyExtractor, extractObject: extractor, ctx: ctx}
+}
+
+func (bfs *blobFileIO) objectLocation(root string) (objectLocation, error) {
+	if bfs.extractObject != nil {
+		return bfs.extractObject(root)
+	}
+
+	location, err := splitObjectLocation(root)
+	if err != nil {
+		return objectLocation{}, err
+	}
+
+	key, err := bfs.preprocess(root)

Review Comment:
   This fallback computes the key two incompatible ways and they disagree on cross-authority input.
   
   For `s3://other-bucket/path`, `splitObjectLocation` leaves `location.uriPrefix = "s3://other-bucket/"` with `key = "path"`, but `bfs.preprocess(root)` (non-strict `defaultKeyExtractor`) then overwrites `location.key` with `legacyAuthorityKey` = `"other-bucket/path"` while `uriPrefix` still points at `other-bucket`. WalkDir reconstructs `s3://other-bucket/other-bucket/path` — authority doubled. If we make `extractObject` required (see the `createBlobFS` comment) this branch goes away entirely; if it stays, the key needs to come from `splitObjectLocation` too so prefix and key agree.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#discussion_r3482957498


##########
io/gocloud/azure.go:
##########
@@ -201,21 +201,53 @@ func createAzureBucket(ctx context.Context, parsed *url.URL, props map[string]st
 	return azureblob.OpenBucket(ctx, client, nil)
 }
 
-// adlsKeyExtractor creates a key extractor for Azure schemes using the adlsURIPattern pattern
-func adlsKeyExtractor() KeyExtractor {
-	return func(location string) (string, error) {
+func adlsAuthority(parsed *url.URL) string {
+	if parsed.User == nil {
+		return parsed.Host
+	}
+
+	return parsed.User.String() + "@" + parsed.Host
+}
+
+func adlsObjectLocationExtractor(parsedURL *url.URL, opts ...keyExtractorOption) objectLocationExtractor {
+	var cfg keyExtractorConfig
+	for _, opt := range opts {
+		opt(&cfg)
+	}
+
+	expectedAuthority := adlsAuthority(parsedURL)
+
+	return func(location string) (objectLocation, error) {
 		matches := adlsURIPattern.FindStringSubmatch(location)
 		if len(matches) < 4 {
-			return "", fmt.Errorf("invalid ADLS location: %s", location)
+			return objectLocation{}, fmt.Errorf("invalid ADLS location: %s", location)
+		}
+
+		authority := matches[2]
+		if cfg.strictAuthorityValidation && authority != expectedAuthority {
+			return objectLocation{}, fmt.Errorf("URI authority %q does not match configured authority %q",
+				authority, expectedAuthority)
 		}
 
 		uriPath := matches[3]
 		key := strings.TrimPrefix(uriPath, "/")

Review Comment:
   `adlsURIPattern` is `^(abfss?|wasbs?)://([^/?#]+)(.*)?$`, so group 3 captures everything after the authority *including* a leading `?` or `#`. For `abfs://container@account.dfs.core.windows.net?prefix=data`, `uriPath` is `?prefix=data` and `key` becomes `?prefix=data` - non-empty, so it's accepted as the object key. `splitObjectLocation` now explicitly rejects this shape for s3/gs (`must be followed by an object path`), and since `objectLocation()` also feeds `WalkDir`, the two paths disagree on the same malformed input. Suggest rejecting a non-empty `uriPath` that doesn't begin with `/` here too, to keep ADLS consistent with the generic parser (a matching `abfs://...?prefix=data` test would lock it in).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "fallintoplace (via GitHub)" <gi...@apache.org>.
fallintoplace commented on code in PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#discussion_r3468872269


##########
io/gocloud/blob.go:
##########
@@ -69,22 +68,70 @@ func (f *blobOpenFile) Sys() any                   { return f.b }
 func (f *blobOpenFile) IsDir() bool                { return false }
 func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 
-// KeyExtractor extracts the object key from an input path
+// KeyExtractor extracts the object key from an input path.
 type KeyExtractor func(path string) (string, error)
 
-// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
-// e.g., s3://bucket/path/file -> path/file
+// ErrEmptyObjectKey is returned when a location names a bucket or authority
+// without an object key.
+var ErrEmptyObjectKey = errors.New("object key is empty")

Review Comment:
   @laskoviymishka Can you please check again when you have time? Thank you for your attention.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#discussion_r3466850027


##########
io/gocloud/blob.go:
##########
@@ -69,22 +68,70 @@ func (f *blobOpenFile) Sys() any                   { return f.b }
 func (f *blobOpenFile) IsDir() bool                { return false }
 func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 
-// KeyExtractor extracts the object key from an input path
+// KeyExtractor extracts the object key from an input path.
 type KeyExtractor func(path string) (string, error)
 
-// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
-// e.g., s3://bucket/path/file -> path/file
+// ErrEmptyObjectKey is returned when a location names a bucket or authority
+// without an object key.
+var ErrEmptyObjectKey = errors.New("object key is empty")
+
+type objectLocation struct {
+	authority    string
+	key          string
+	uriPrefix    string
+	hasAuthority bool
+}
+
+func splitObjectLocation(location string) (objectLocation, error) {
+	scheme, rest, ok := strings.Cut(location, "://")
+	if !ok {
+		return objectLocation{key: location}, nil
+	}
+
+	authorityEnd := strings.IndexAny(rest, "/?#")
+	if authorityEnd == -1 {
+		authorityEnd = len(rest)
+	}
+
+	authority := rest[:authorityEnd]
+	if authority == "" {
+		return objectLocation{}, fmt.Errorf("URI authority is empty: %s", location)
+	}
+
+	key := ""
+	if authorityEnd < len(rest) && rest[authorityEnd] == '/' {
+		key = strings.TrimPrefix(rest[authorityEnd:], "/")
+	}
+
+	return objectLocation{
+		authority:    authority,
+		key:          key,
+		uriPrefix:    scheme + "://" + authority + "/",
+		hasAuthority: true,
+	}, nil
+}
+
+// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI.
+// e.g., s3://bucket/path/file -> path/file.
 func defaultKeyExtractor(bucketName string) KeyExtractor {
 	return func(location string) (string, error) {
-		_, after, found := strings.Cut(location, "://")
-		if found {
-			location = after
+		parsed, err := splitObjectLocation(location)
+		if err != nil {
+			return "", err
 		}
 
-		key := strings.TrimPrefix(location, bucketName+"/")
+		key := parsed.key
+		if parsed.hasAuthority {
+			if parsed.authority != bucketName {

Review Comment:
   My one real hesitation about merging this: the hard authority check runs on the default read path, and I think it breaks a supported Iceberg layout.
   
   A table can set `write.data.path = s3://data-bucket/` while its location and metadata live in `s3://metadata-bucket/...`. Manifests then carry full URIs like `s3://data-bucket/data/00000.parquet`. As I read it, the scan opens those through the single table IO keyed to the metadata bucket — so `parsed.authority` is `data-bucket`, `bucketName` is `metadata-bucket`, and we now reject a file that Java `S3FileIO` and PyIceberg read without complaint (neither restricts which bucket a path resolves to).
   
   I'd keep the validation but make it not the default on reads — either construct a per-authority IO when a data-file URI's authority differs from the table's, or gate strict equality behind an opt-in property. Before I lean too hard on this though: can you confirm the scan path really does reuse one IO across differing data-path authorities? If it already loads an FS per data path, this concern mostly evaporates and I'd drop it to a nit. wdyt?



##########
io/gocloud/blob.go:
##########
@@ -193,20 +240,30 @@ func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtr
 }
 
 func (bfs *blobFileIO) WalkDir(root string, fn fs.WalkDirFunc) error {
-	parsed, err := url.Parse(root)
+	walkPath, err := bfs.preprocess(root)
 	if err != nil {
-		return fmt.Errorf("invalid URL %s: %w", root, err)
-	}
+		if !errors.Is(err, ErrEmptyObjectKey) {
+			return &fs.PathError{Op: "walkdir", Path: root, Err: err}
+		}
 
-	walkPath := strings.TrimPrefix(parsed.Path, "/")
-	if walkPath == "" {
 		walkPath = "."
 	}
 
-	parsed.Path = ""
+	location, err := splitObjectLocation(root)

Review Comment:
   We parse `root` twice here — once via `preprocess` (which runs `keyExtractor`) and again directly through `splitObjectLocation` — then use the second parse's `uriPrefix` to reconstruct the callback paths.
   
   That's fine for `defaultKeyExtractor`, but for any extractor whose authority boundary differs from the naive up-to-`/?#` cut — `adlsKeyExtractor` today, or any custom one — the prefix used for reconstruction can diverge from what the extractor actually accepted. The two parsers disagreeing is exactly the kind of bug that stays invisible until someone plugs in a non-default extractor.
   
   I'd parse once and share the `objectLocation` for both the key extraction and the prefix reconstruction, so there's a single source of truth for the authority boundary.



##########
io/gocloud/blob_test.go:
##########
@@ -229,13 +333,67 @@ func TestBlobFileIOWalkDir(t *testing.T) {
 	require.NoError(t, err)
 
 	expected := []string{
+		"s3://test-bucket/data/100%off/file.parquet",
+		"s3://test-bucket/data/city=New York/file.parquet",
 		"s3://test-bucket/data/file1.parquet",
 		"s3://test-bucket/data/file2.parquet",
 		"s3://test-bucket/metadata/snap-123.avro",
 	}
 	assert.ElementsMatch(t, expected, walked)
 }
 
+func TestBlobFileIOWalkDirRejectsWrongBucket(t *testing.T) {
+	ctx := context.Background()
+
+	bucket := memblob.OpenBucket(nil)
+	defer bucket.Close()
+
+	require.NoError(t, bucket.WriteAll(ctx, "data/file1.parquet", []byte("content"), nil))
+
+	bfs := &blobFileIO{
+		Bucket:       bucket,
+		keyExtractor: defaultKeyExtractor("test-bucket"),
+		ctx:          ctx,
+	}
+
+	for _, tt := range []struct {
+		name string
+		root string
+	}{
+		{name: "s3", root: "s3://other-bucket/"},
+		{name: "gcs", root: "gs://other-bucket/data"},
+	} {
+		t.Run(tt.name, func(t *testing.T) {
+			err := bfs.WalkDir(tt.root, func(string, fs.DirEntry, error) error {
+				t.Fatal("WalkDir callback should not be called")
+
+				return nil
+			})
+			require.ErrorContains(t, err, "does not match configured authority")
+		})
+	}
+}
+
+func TestBlobFileIOWalkDirRejectsWrongAzureAuthority(t *testing.T) {
+	ctx := context.Background()
+
+	bucket := memblob.OpenBucket(nil)
+	defer bucket.Close()
+
+	bfs := &blobFileIO{
+		Bucket:       bucket,
+		keyExtractor: defaultKeyExtractor("container@account.dfs.core.windows.net"),

Review Comment:
   This test doesn't actually exercise the Azure path. Production Azure/ADLS schemes are registered with `adlsKeyExtractor` (register.go), which extracts the path but never compares the authority — so `WriteFile("abfs://other-container@account.../data/file.parquet")` still silently lands in the opened container with the old bug intact.
   
   The test only rejects because it wires up `defaultKeyExtractor` here, so it's proving the S3 extractor's behavior under an Azure-looking string rather than the real Azure code path. As written it implies a cross-container protection that doesn't exist.
   
   I'd either add a configured authority + mismatch check to `adlsKeyExtractor` and point this test at it, or drop the test and note in the PR that ADLS authority validation is out of scope for now.



##########
io/gocloud/blob.go:
##########
@@ -69,22 +68,70 @@ func (f *blobOpenFile) Sys() any                   { return f.b }
 func (f *blobOpenFile) IsDir() bool                { return false }
 func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 
-// KeyExtractor extracts the object key from an input path
+// KeyExtractor extracts the object key from an input path.
 type KeyExtractor func(path string) (string, error)
 
-// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
-// e.g., s3://bucket/path/file -> path/file
+// ErrEmptyObjectKey is returned when a location names a bucket or authority
+// without an object key.
+var ErrEmptyObjectKey = errors.New("object key is empty")
+
+type objectLocation struct {
+	authority    string
+	key          string
+	uriPrefix    string
+	hasAuthority bool
+}
+
+func splitObjectLocation(location string) (objectLocation, error) {
+	scheme, rest, ok := strings.Cut(location, "://")
+	if !ok {
+		return objectLocation{key: location}, nil
+	}
+
+	authorityEnd := strings.IndexAny(rest, "/?#")
+	if authorityEnd == -1 {
+		authorityEnd = len(rest)
+	}
+
+	authority := rest[:authorityEnd]
+	if authority == "" {
+		return objectLocation{}, fmt.Errorf("URI authority is empty: %s", location)
+	}
+
+	key := ""

Review Comment:
   A malformed authority-only URI quietly degrades into a full bucket walk, which surprised me. For `s3://my-bucket?foo/bar`, `IndexAny` stops at `?`, the authority is `my-bucket`, and since `rest[authorityEnd]` is `?` not `/`, `key` stays empty. That bubbles up as `ErrEmptyObjectKey`, which `WalkDir` then treats as a bucket root and promotes to `walkPath = "."` — walking the entire bucket from a malformed input.
   
   Iceberg locations shouldn't carry a query or fragment, so this is an edge, but silently turning a bad URI into a full walk feels risky. I'd either reject a non-`/` continuation after the authority explicitly, or at least keep that case from reaching the walk-everything fallback.



##########
io/gocloud/blob.go:
##########
@@ -193,20 +240,30 @@ func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtr
 }
 
 func (bfs *blobFileIO) WalkDir(root string, fn fs.WalkDirFunc) error {
-	parsed, err := url.Parse(root)
+	walkPath, err := bfs.preprocess(root)
 	if err != nil {
-		return fmt.Errorf("invalid URL %s: %w", root, err)
-	}
+		if !errors.Is(err, ErrEmptyObjectKey) {
+			return &fs.PathError{Op: "walkdir", Path: root, Err: err}
+		}
 
-	walkPath := strings.TrimPrefix(parsed.Path, "/")
-	if walkPath == "" {
 		walkPath = "."
 	}
 
-	parsed.Path = ""
+	location, err := splitObjectLocation(root)
+	if err != nil {
+		return &fs.PathError{Op: "walkdir", Path: root, Err: err}
+	}
 
 	return fs.WalkDir(bfs.Bucket, walkPath, func(path string, d fs.DirEntry, err error) error {
-		return fn(parsed.JoinPath(path).String(), d, err)
+		if location.hasAuthority {
+			if path == "." {
+				path = strings.TrimSuffix(location.uriPrefix, "/")

Review Comment:
   The root-entry path changed shape here. The old code returned `parsed.JoinPath(".")` → `s3://bucket/` for the root entry; this returns `strings.TrimSuffix(uriPrefix, "/")` → `s3://bucket` (no trailing slash), while every child is `uriPrefix + path` → `s3://bucket/...`. So the root entry no longer matches the form callers passed in as the walk root.
   
   Current callers all filter with `!d.IsDir()`, so the root `"."` entry is skipped and nothing breaks today — but it's a silent behavior change waiting for the first caller that compares a walked entry against the stored root. I'd use `uriPrefix` consistently for the `"."` case so the root keeps its trailing slash.



##########
io/gocloud/blob_test.go:
##########
@@ -57,25 +85,60 @@ func TestDefaultKeyExtractor(t *testing.T) {
 			input:       "gs://my-bucket/path/to/file.parquet",
 			expectedKey: "path/to/file.parquet",
 		},
+		{
+			name:        "azure URI with path",
+			bucketName:  "container@account.dfs.core.windows.net",
+			input:       "abfs://container@account.dfs.core.windows.net/path/to/file.parquet",
+			expectedKey: "path/to/file.parquet",
+		},
+		{
+			name:            "s3 URI with different bucket",
+			input:           "s3://other-bucket/path/to/file.parquet",
+			wantErrContains: "does not match configured authority",
+		},
+		{
+			name:            "gs URI with different bucket",
+			input:           "gs://other-bucket/path/to/file.parquet",
+			wantErrContains: "does not match configured authority",
+		},
+		{
+			name:            "azure URI with different container",
+			bucketName:      "container@account.dfs.core.windows.net",
+			input:           "abfs://other@account.dfs.core.windows.net/path/to/file.parquet",
+			wantErrContains: "does not match configured authority",
+		},
 		{
 			name:        "URI with query and fragment",
 			input:       "s3://my-bucket/path/to/file.parquet?param=value#fragment",
 			expectedKey: "path/to/file.parquet?param=value#fragment",
 		},
 		{
-			name:        "URI with empty path",
-			input:       "s3://my-bucket/",
-			shouldError: true,
+			name:            "URI with empty path",
+			input:           "s3://my-bucket/",
+			wantErrContains: "object key is empty",
+			wantErrIs:       ErrEmptyObjectKey,
+		},
+		{
+			name:            "URI with empty authority",
+			input:           "s3:///path/to/file.parquet",
+			wantErrContains: "URI authority is empty",
 		},
 	}
 
-	extractor := defaultKeyExtractor("my-bucket")
 	for _, test := range tests {
 		t.Run(test.name, func(t *testing.T) {
+			bucketName := test.bucketName
+			if bucketName == "" {
+				bucketName = "my-bucket"
+			}
+			extractor := defaultKeyExtractor(bucketName)
 			key, err := extractor(test.input)
 
-			if test.shouldError {
-				assert.Error(t, err, "Expected error for input: %s", test.input)
+			if test.wantErrContains != "" {
+				assert.ErrorContains(t, err, test.wantErrContains, "Expected error for input: %s", test.input)
+				if test.wantErrIs != nil {
+					assert.True(t, errors.Is(err, test.wantErrIs), "expected errors.Is(%v)", test.wantErrIs)

Review Comment:
   `assert.ErrorIs(t, err, test.wantErrIs)` reads better here and prints the actual error chain on failure, versus `assert.True` over a bare bool.
   
   Separately, the gating assertions in this table are `assert`, not `require` — on a nil-when-error-expected case the `ErrorContains` fails but execution continues into this `errors.Is` check (and on the success path `NoError` continues into `Equal`), so one root cause produces two failures. I'd make the gate a `require`.



##########
io/gocloud/blob.go:
##########
@@ -69,22 +68,70 @@ func (f *blobOpenFile) Sys() any                   { return f.b }
 func (f *blobOpenFile) IsDir() bool                { return false }
 func (f *blobOpenFile) Stat() (fs.FileInfo, error) { return f, nil }
 
-// KeyExtractor extracts the object key from an input path
+// KeyExtractor extracts the object key from an input path.
 type KeyExtractor func(path string) (string, error)
 
-// defaultKeyExtractor extracts the object key by removing the scheme and bucket name from the URI
-// e.g., s3://bucket/path/file -> path/file
+// ErrEmptyObjectKey is returned when a location names a bucket or authority
+// without an object key.
+var ErrEmptyObjectKey = errors.New("object key is empty")

Review Comment:
   `ErrEmptyObjectKey` is exported, but its only consumer is the internal `errors.Is` in `WalkDir` — bucket-root handling is otherwise transparent to callers. Exporting it is a permanent API commitment, so I'd either unexport it to `errEmptyObjectKey`, or document it explicitly as part of the `KeyExtractor` author contract ("custom extractors must wrap this for bucket-root inputs") — which also ties into the `adlsKeyExtractor` gap.



##########
io/gocloud/blob.go:
##########
@@ -193,20 +240,30 @@ func createBlobFS(ctx context.Context, bucket *blob.Bucket, keyExtractor KeyExtr
 }
 
 func (bfs *blobFileIO) WalkDir(root string, fn fs.WalkDirFunc) error {
-	parsed, err := url.Parse(root)
+	walkPath, err := bfs.preprocess(root)
 	if err != nil {
-		return fmt.Errorf("invalid URL %s: %w", root, err)
-	}
+		if !errors.Is(err, ErrEmptyObjectKey) {
+			return &fs.PathError{Op: "walkdir", Path: root, Err: err}

Review Comment:
   Small one: the rest of this file uses space-separated op names (`"write file"`, `"new writer"`), so I'd make this `"walk dir"` to match.
   
   While we're here — the authority-mismatch error is a plain `fmt.Errorf` with no sentinel, so callers can't `errors.Is` it the way they can `ErrEmptyObjectKey`. If we expect anyone to branch on it, an exported `ErrWrongAuthority` wrapped with `%w` would be more consistent. Not blocking.



##########
io/gocloud/blob_test.go:
##########
@@ -84,6 +147,45 @@ func TestDefaultKeyExtractor(t *testing.T) {
 	}
 }
 
+func TestBlobFileIORejectsWrongBucketObjectPaths(t *testing.T) {
+	ctx := context.Background()
+
+	bucket := memblob.OpenBucket(nil)
+	defer bucket.Close()
+
+	bfs := &blobFileIO{
+		Bucket:       bucket,
+		keyExtractor: defaultKeyExtractor("test-bucket"),
+		ctx:          ctx,
+	}
+
+	for _, tt := range []struct {
+		name   string
+		path   string
+		oldKey string
+	}{
+		{
+			name:   "s3",
+			path:   "s3://other-bucket/data/file.parquet",
+			oldKey: "other-bucket/data/file.parquet",
+		},
+		{
+			name:   "gcs",
+			path:   "gs://other-bucket/data/file.parquet",
+			oldKey: "other-bucket/data/file.parquet",
+		},
+	} {
+		t.Run(tt.name, func(t *testing.T) {
+			err := bfs.WriteFile(tt.path, []byte("content"))
+			require.ErrorContains(t, err, "does not match configured authority")
+
+			exists, err := bucket.Exists(ctx, tt.oldKey)

Review Comment:
   This `oldKey` existence check is vacuously true — nothing ever seeds `oldKey`, so `Exists` returns false even if the write had been misrouted somewhere else, and the `require.ErrorContains` above already guarantees no write happened.
   
   If we want this to actually prove "not misrouted to the old key", seed `oldKey` with a known sentinel first and assert it's unchanged after the failed write. Otherwise I'd just drop the `Exists` block — the `ErrorContains` carries the assertion on its own.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka merged PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


Re: [PR] fix(io): validate cloud object URI buckets [iceberg-go]

Posted by "fallintoplace (via GitHub)" <gi...@apache.org>.
fallintoplace commented on PR #1259:
URL: https://github.com/apache/iceberg-go/pull/1259#issuecomment-4845997822

   @laskoviymishka Can you please check again this PR?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org