Files
versitygw/s3err/invalid-argument.go
T
niksis02 9f786b3c2c feat: global error refactoring
Fixes #2123
Fixes #2120
Fixes #2116
Fixes #2111
Fixes #2108
Fixes #2086
Fixes #2085
Fixes #2083
Fixes #2081
Fixes #2080
Fixes #2073
Fixes #2072
Fixes #2071
Fixes #2069
Fixes #2044
Fixes #2043
Fixes #2042
Fixes #2041
Fixes #2040
Fixes #2039
Fixes #2036
Fixes #2035
Fixes #2034
Fixes #2028
Fixes #2020
Fixes #1842
Fixes #1810
Fixes #1780
Fixes #1775
Fixes #1736
Fixes #1705
Fixes #1663
Fixes #1645
Fixes #1583
Fixes #1526
Fixes #1514
Fixes #1493
Fixes #1487
Fixes #959
Fixes #779
Closes #823
Closes #85

Refactor global S3 error handling around structured error types and centralized XML response generation.

All S3 errors now share the common APIError base for the fields every error has: Code, HTTP status code, and Message. Non-traditional errors that need AWS-compatible XML fields now have dedicated typed errors in the s3err package. Each typed error implements the shared S3Error behavior so controllers and middleware can handle errors consistently while still emitting error-specific XML fields.

Add a dedicated InvalidArgumentError type because InvalidArgument is used widely across request validation, auth, copy source handling, object lock validation, multipart validation, and header parsing. The new InvalidArgument path uses explicit InvalidArgErrorCode constants with predefined descriptions and ArgumentName values, keeping call sites readable while preserving the correct InvalidArgument XML shape and optional ArgumentValue.

New structured errors added in s3err:
- `AccessForbiddenError`: Method, ResourceType
- `BadDigestError`: CalculatedDigest, ExpectedDigest
- `BucketError`: BucketName
- `ContentSHA256MismatchError`: ClientComputedContentSHA256, S3ComputedContentSHA256
- `EntityTooLargeError`: ProposedSize, MaxSizeAllowed
- `EntityTooSmallError`: ProposedSize, MinSizeAllowed
- `ExpiredPresignedURLError`: ServerTime, XAmzExpires, Expires
- `InvalidAccessKeyIdError`: AWSAccessKeyId
- `InvalidArgumentError`: Description, ArgumentName, ArgumentValue
- `InvalidChunkSizeError`: Chunk, BadChunkSize
- `InvalidDigestError`: ContentMD5
- `InvalidLocationConstraintError`: LocationConstraint
- `InvalidPartError`: UploadId, PartNumber, ETag
- `InvalidRangeError`: RangeRequested, ActualObjectSize
- `InvalidTagError`: TagKey, TagValue
- `KeyTooLongError`: Size, MaxSizeAllowed
- `MetadataTooLargeError`: Size, MaxSizeAllowed
- `MethodNotAllowedError`: Method, ResourceType, AllowedMethods
- `NoSuchUploadError`: UploadId
- `NoSuchVersionError`: Key, VersionId
- `NotImplementedError`: Header, AdditionalMessage
- `PreconditionFailedError`: Condition
- `RequestTimeTooSkewedError`: RequestTime, ServerTime, MaxAllowedSkewMilliseconds
- `SignatureDoesNotMatchError`: AWSAccessKeyId, StringToSign, SignatureProvided, StringToSignBytes, CanonicalRequest, CanonicalRequestBytes

Fix CompleteMultipartUpload validation in the Azure backend so missing or empty `ETag` values return the appropriate S3 error instead of allowing a gateway panic.

Fix presigned authentication expiration validation to compare server time in `UTC`, matching the `UTC` timestamp used by presigned URL signing.

Add request ID and host ID support across S3 requests. Each request now receives AWS S3-like identifiers, returned in response headers as `x-amz-request-id` and `x-amz-id-2` and included in all XML error responses as RequestId and HostId. The generated ID structure is designed to resemble AWS S3 request IDs and host IDs.

The request signature calculation/validation for streaming uploads was previously delayed until the request body was fully read, both for Authorization header authentication and presigned URLs.
Now, the signature is validated immediately in the authorization middlewares without reading the request body, since the signature calculation itself does not depend on the request body. Instead, only the `x-amz-content-sha256` SHA-256 hash calculation is delayed.
2026-05-21 23:49:34 +04:00

275 lines
8.8 KiB
Go

// Copyright 2026 Versity Software
// This file is licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package s3err
import (
"bytes"
"encoding/xml"
"fmt"
"net/http"
)
type InvalidArgErrorCode int
const (
InvalidArgMaxBuckets InvalidArgErrorCode = iota
InvalidArgNegativeMaxKeys
InvalidArgObjectAttributes
InvalidArgPartNumber
InvalidArgCompleteMpPartNumber
InvalidArgCopySourceRange
InvalidArgCopySourceBucket
InvalidArgCopySourceObject
InvalidArgCopySourceEncoding
InvalidArgURLEncodedTagging
InvalidArgAuthHeader
InvalidArgAuthorizationType
InvalidArgPOSTFileRequired
InvalidArgSHA256Payload
InvalidArgCopySource
InvalidArgRetainUntilDate
InvalidArgPastObjectLockRetainDate
InvalidArgObjectLockRetentionDays
InvalidArgObjectLockRetentionYears
InvalidArgMissingObjectLockRetainDate
InvalidArgMissingObjectLockMode
InvalidArgLegalHoldStatus
InvalidArgObjectLockMode
InvalidArgMetadataDirective
InvalidArgTaggingDirective
InvalidArgVersionId
InvalidArgChecksumPart
InvalidArgMissingUploadId
InvalidArgUploadIdMarker
InvalidArgCannedAcl
InvalidArgOnlyAws4HmacSha256
InvalidArgDateHeader
)
var invalidArgErrResponses = map[InvalidArgErrorCode]InvalidArgumentError{
InvalidArgMaxBuckets: {
Description: "Argument max-buckets must be an integer between 1 and 10000.",
ArgumentName: "max-buckets",
},
InvalidArgNegativeMaxKeys: {
Description: "max-keys cannot be negative",
ArgumentName: "maxKeys",
},
InvalidArgObjectAttributes: {
Description: "Invalid attribute name specified.",
ArgumentName: "x-amz-object-attributes",
},
InvalidArgPartNumber: {
Description: "Part number must be an integer between 1 and 10000, inclusive.",
ArgumentName: "partNumber",
},
InvalidArgCompleteMpPartNumber: {
Description: "PartNumber must be >= 1",
ArgumentName: "PartNumber",
},
InvalidArgCopySourceRange: {
Description: "The x-amz-copy-source-range value must be of the form bytes=first-last where first and last are the zero-based offsets of the first and last bytes to copy",
ArgumentName: "x-amz-copy-source-range",
},
InvalidArgCopySourceBucket: {
Description: "Invalid copy source bucket name",
ArgumentName: "x-amz-copy-source",
},
InvalidArgCopySourceObject: {
Description: "Invalid copy source object key",
ArgumentName: "x-amz-copy-source",
},
InvalidArgCopySourceEncoding: {
Description: "Invalid copy source encoding",
ArgumentName: "x-amz-copy-source",
},
InvalidArgURLEncodedTagging: {
Description: "The header 'x-amz-tagging' shall be encoded as UTF-8 then URLEncoded URL query parameters without tag name duplicates.",
ArgumentName: "x-amz-tagging",
},
InvalidArgAuthHeader: {
Description: "Authorization header is invalid -- one and only one ' ' (space) required.",
ArgumentName: "Authorization",
},
InvalidArgAuthorizationType: {
Description: "Unsupported Authorization Type",
ArgumentName: "Authorization",
},
InvalidArgPOSTFileRequired: {
Description: "POST requires exactly one file upload per request.",
ArgumentName: "file",
},
InvalidArgSHA256Payload: {
Description: "x-amz-content-sha256 must be UNSIGNED-PAYLOAD, STREAMING-UNSIGNED-PAYLOAD-TRAILER, STREAMING-AWS4-HMAC-SHA256-PAYLOAD, STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER, STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD, STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER or a valid sha256 value.",
ArgumentName: "x-amz-content-sha256",
},
InvalidArgCopySource: {
Description: "You can only specify a copy source header for copy requests.",
ArgumentName: "x-amz-copy-source",
},
InvalidArgRetainUntilDate: {
Description: "The retain until date must be provided in ISO 8601 format",
ArgumentName: "x-amz-object-lock-retain-until-date",
},
InvalidArgPastObjectLockRetainDate: {
Description: "The retain until date must be in the future!",
ArgumentName: "x-amz-object-lock-retain-until-date",
},
InvalidArgMissingObjectLockRetainDate: {
Description: "x-amz-object-lock-retain-until-date and x-amz-object-lock-mode must both be supplied.",
ArgumentName: "x-amz-object-lock-retain-until-date",
},
InvalidArgMissingObjectLockMode: {
Description: "x-amz-object-lock-retain-until-date and x-amz-object-lock-mode must both be supplied.",
ArgumentName: "x-amz-object-lock-mode",
},
InvalidArgObjectLockRetentionDays: {
Description: "Default retention period must be a positive integer value.",
ArgumentName: "Days",
},
InvalidArgObjectLockRetentionYears: {
Description: "Default retention period must be a positive integer value.",
ArgumentName: "Years",
},
InvalidArgLegalHoldStatus: {
Description: "Legal Hold must be either of 'ON' or 'OFF'",
ArgumentName: "x-amz-object-lock-legal-hold",
},
InvalidArgObjectLockMode: {
Description: "Unknown wormMode directive.",
ArgumentName: "x-amz-object-lock-mode",
},
InvalidArgMetadataDirective: {
Description: "Unknown metadata directive.",
ArgumentName: "x-amz-metadata-directive",
},
InvalidArgTaggingDirective: {
Description: "Unknown tagging directive.",
ArgumentName: "x-amz-tagging-directive",
},
InvalidArgVersionId: {
Description: "Invalid version id specified",
ArgumentName: "versionId",
},
InvalidArgChecksumPart: {
Description: "Invalid Base64 or multiple checksums present in request",
ArgumentName: "Checksum",
},
InvalidArgMissingUploadId: {
Description: "This operation does not accept partNumber without uploadId",
ArgumentName: "partNumber",
},
InvalidArgUploadIdMarker: {
Description: "Invalid uploadId marker",
ArgumentName: "upload-id-marker",
},
InvalidArgCannedAcl: {
Description: "",
ArgumentName: "x-amz-acl",
},
InvalidArgOnlyAws4HmacSha256: {
Description: "Only AWS4-HMAC-SHA256 is supported",
ArgumentName: "X-Amz-Algorithm",
},
InvalidArgDateHeader: {
Description: "X-Amz-Date must be formated via ISO8601 Long format",
ArgumentName: "X-Amz-Date",
},
}
// InvalidArgumentError is returned when a request argument is invalid.
// Produces <ArgumentName> and <ArgumentValue> fields in the XML response.
type InvalidArgumentError struct {
Description string
ArgumentName string
ArgumentValue string
}
func (e InvalidArgumentError) BaseError() APIError {
return APIError{
Code: "InvalidArgument",
Description: e.Description,
HTTPStatusCode: http.StatusBadRequest,
}
}
// InvalidArgumentError http status code is always 400
func (e InvalidArgumentError) StatusCode() int { return http.StatusBadRequest }
func (e InvalidArgumentError) Error() string {
var bytesBuffer bytes.Buffer
bytesBuffer.WriteString(xml.Header)
enc := xml.NewEncoder(&bytesBuffer)
_ = enc.Encode(e)
return bytesBuffer.String()
}
func (e InvalidArgumentError) XMLBody(requestID, hostID string) []byte {
return encodeResponse(struct {
XMLName xml.Name `xml:"Error"`
Code string
Message string
ArgumentName string `xml:"ArgumentName,omitempty"`
ArgumentValue string `xml:"ArgumentValue,omitempty"`
RequestId string `xml:"RequestId,omitempty"`
HostId string `xml:"HostId,omitempty"`
}{
Code: "InvalidArgument",
Message: e.Description,
ArgumentName: e.ArgumentName,
ArgumentValue: e.ArgumentValue,
RequestId: requestID,
HostId: hostID,
})
}
func GetInvalidArgumentErr(code InvalidArgErrorCode, value string) InvalidArgumentError {
err := invalidArgErrResponses[code]
err.ArgumentValue = value
return err
}
func GetInvalidArgMaxLimiter(name, value string) InvalidArgumentError {
return InvalidArgumentError{
ArgumentName: name,
ArgumentValue: value,
Description: fmt.Sprintf("Provided %s not an integer or within integer range", value),
}
}
func GetInvalidArgNegativeMaxLimiter(name, value string) InvalidArgumentError {
return InvalidArgumentError{
ArgumentName: name,
ArgumentValue: value,
Description: fmt.Sprintf("Argument %s must be an integer between 0 and 2147483647", value),
}
}
func GetInvalidArgExceedingRange(size int64) InvalidArgumentError {
return InvalidArgumentError{
ArgumentName: "x-amz-copy-source-range",
ArgumentValue: fmt.Sprint(size),
Description: fmt.Sprintf("Range specified is not valid for source object of size: %d", size),
}
}
func GetInvalidArgObjectOwnership(value string) InvalidArgumentError {
return InvalidArgumentError{
ArgumentName: "x-amz-object-ownership",
// no ArgumentValue is returned for this error
Description: fmt.Sprintf("Invalid x-amz-object-ownership header: %s", value),
}
}