Documentation
¶
Overview ¶
AWS Signature Version 4 implementation for HTTP request authentication.
This implementation is inspired by: - MinIO (https://github.com/minio/minio) - Apache 2.0 License - LabStore (https://github.com/IllumiKnowLabs/labstore) - Apache 2.0 License
AWS Signature Version 4 specification: https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html
Pre-signed URL Support Implementation (Phase 3.2 #3)
✅ IMPLEMENTED: Core pre-signed URL authentication (Feb 16, 2026)
Implemented features: 1. ✅ Query string authentication parsing (X-Amz-Algorithm, X-Amz-Credential, X-Amz-Date, X-Amz-Expires, X-Amz-SignedHeaders, X-Amz-Signature) 2. ✅ Signature verification for pre-signed requests (VerifyPresignedSignature) 3. ✅ Expiration validation (X-Amz-Expires, max 604800 seconds / 7 days) 4. ✅ Context tracking (IsPreSignedRequest, GetPreSignedExpiresAt) 5. ✅ Middleware integration (AuthMiddleware handles both header and query auth)
Testing commands (to verify implementation): - aws s3 presign s3://bucket/object.txt --expires-in 300 - boto3: generate_presigned_url() - mc share download alias/bucket/object.txt
TODO (Future enhancements): - [ ] X-Amz-Security-Token support for temporary credentials (STS) - [ ] URL generation helper for creating pre-signed URLs (for future CLI/SDK)
References: - https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html - MinIO: cmd/signature-v4.go (doesPresignedSignatureMatch)
Index ¶
- Variables
- func BuildCanonicalRequest(r *http.Request, signedHeaders []string, payloadHash string) string
- func BuildStringToSign(timestamp time.Time, region, canonicalRequest string) string
- func ComputeSignature(secretKey string, timestamp time.Time, region, stringToSign string) string
- func DebugVerifySignature(r *http.Request, secretKey string) error
- func GeneratePresignedGetURL(accessKey, secretKey, region, bucket, key, baseURL string, ...) (string, error)
- func GeneratePresignedURL(accessKey, secretKey, region, bucket, key, baseURL, method string, ...) (string, error)
- func GetAccessKey(r *http.Request) (string, error)
- func GetAccessKeyFromPresignedURL(r *http.Request) (string, error)
- func GetRequestUser(ctx context.Context) *metadata.User
- func IsChunkedEncoding(contentSHA256 string) bool
- func ValidatePostPolicyConditions(doc *PostPolicyDocument, bucket, key, contentType string, contentLength int64) error
- func ValidatePostPolicyExpiration(doc *PostPolicyDocument) error
- func VerifyPostPolicySignature(form *PostPolicyForm, secretKey string) error
- func VerifyPresignedSignature(r *http.Request, secretKey string) (time.Time, error)
- func VerifySignature(r *http.Request, secretKey string) error
- type Authenticator
- func (a *Authenticator) AltRootAccessKey() string
- func (a *Authenticator) AltRootUser() *metadata.User
- func (a *Authenticator) AuthMiddleware(next http.Handler) http.Handler
- func (a *Authenticator) AuthenticatePostPolicyRequest(r *http.Request) (*metadata.User, *PostPolicyForm, *PostPolicyDocument, error)
- func (a *Authenticator) AuthenticatePresignedRequest(r *http.Request) (*metadata.User, time.Time, error)
- func (a *Authenticator) AuthenticateRequest(r *http.Request) (*metadata.User, error)
- func (a *Authenticator) GetUserForAccessKey(ctx context.Context, accessKey string) (*metadata.User, error)
- func (a *Authenticator) IsServiceAccount(ctx context.Context, accessKey string) (*iam.ServiceAccount, bool)
- func (a *Authenticator) PrimaryRootAccessKey() string
- func (a *Authenticator) RootUser() *metadata.User
- func (a *Authenticator) UpdateAltCredentials(accessKey, secretKey string)
- func (a *Authenticator) UpdatePrimaryCredentials(accessKey, secretKey string)
- func (a *Authenticator) ValidateCredentials(ctx context.Context, accessKey, secretKey string) bool
- func (a *Authenticator) WithAlternativeRoot(accessKey, secretKey string) *Authenticator
- type ChunkSignatureVerifier
- type ChunkedReader
- type Credentials
- type PostPolicyDocument
- type PostPolicyForm
Constants ¶
This section is empty.
Variables ¶
var ( // ErrAuthenticationFailed is returned when authentication fails ErrAuthenticationFailed = errors.New("authentication failed") // ErrUserNotFound is returned when the user doesn't exist ErrUserNotFound = errors.New("user not found") // ErrUserInactive is returned when the user account is not active ErrUserInactive = errors.New("user account is not active") )
var ( // ErrInvalidChunkFormat is returned when chunk format is invalid ErrInvalidChunkFormat = errors.New("invalid chunk format") // ErrChunkSizeMismatch is returned when chunk size doesn't match data ErrChunkSizeMismatch = errors.New("chunk size mismatch") // ErrChunkSignatureMismatch is returned when chunk signature verification fails ErrChunkSignatureMismatch = errors.New("chunk signature mismatch") )
var ( // ErrMissingAuthHeader is returned when the Authorization header is missing ErrMissingAuthHeader = errors.New("missing Authorization header") // ErrInvalidAuthFormat is returned when the Authorization header format is invalid ErrInvalidAuthFormat = errors.New("invalid Authorization header format") // ErrMissingDateHeader is returned when the X-Amz-Date header is missing ErrMissingDateHeader = errors.New("missing X-Amz-Date header") // ErrInvalidDateFormat is returned when the date format is invalid ErrInvalidDateFormat = errors.New("invalid date format") // ErrSignatureMismatch is returned when the signature doesn't match ErrSignatureMismatch = errors.New("signature mismatch") // ErrMissingCredential is returned when credential is missing from auth header ErrMissingCredential = errors.New("missing credential in Authorization header") // ErrMissingSignature is returned when signature is missing from auth header ErrMissingSignature = errors.New("missing signature in Authorization header") // ErrMissingSignedHeaders is returned when SignedHeaders is missing from auth header ErrMissingSignedHeaders = errors.New("missing SignedHeaders in Authorization header") // ErrPresignedURLExpired is returned when a pre-signed URL has expired ErrPresignedURLExpired = errors.New("pre-signed URL has expired") // ErrInvalidExpiresValue is returned when X-Amz-Expires is invalid ErrInvalidExpiresValue = errors.New("invalid X-Amz-Expires value") // ErrMissingPresignedParams is returned when required pre-signed URL params are missing ErrMissingPresignedParams = errors.New("missing required pre-signed URL parameters") )
Functions ¶
func BuildCanonicalRequest ¶
BuildCanonicalRequest constructs the canonical request string Format: HTTPMethod + "\n" + CanonicalURI + "\n" + CanonicalQueryString + "\n" + CanonicalHeaders + "\n" + SignedHeaders + "\n" + HashedPayload
func BuildStringToSign ¶
BuildStringToSign constructs the string to sign Format: Algorithm + "\n" + RequestDateTime + "\n" + CredentialScope + "\n" + HashedCanonicalRequest
func ComputeSignature ¶
ComputeSignature computes the AWS Signature V4 signature
func DebugVerifySignature ¶
DebugVerifySignature is like VerifySignature but logs verbose debug information about each step of the signing process, at debug level, with credential and signature material redacted before logging. This keeps the output useful for diagnosing signature mismatches without leaking secrets into log aggregators that may be less tightly access-controlled than the server itself.
func GeneratePresignedGetURL ¶
func GeneratePresignedGetURL(accessKey, secretKey, region, bucket, key, baseURL string, expiry time.Duration) (string, error)
GeneratePresignedGetURL builds a pre-signed S3 GET URL for the given object using AWS Signature Version 4 query-string authentication.
expiry must be between 1 second and 7 days (604800 seconds); region should match the server's configured region (defaults to "us-east-1").
func GeneratePresignedURL ¶
func GeneratePresignedURL(accessKey, secretKey, region, bucket, key, baseURL, method string, expiry time.Duration) (string, error)
GeneratePresignedURL builds a pre-signed S3 URL for the given object and HTTP method using AWS Signature Version 4 query-string authentication.
expiry must be between 1 second and 7 days (604800 seconds).
func GetAccessKey ¶
GetAccessKey extracts the access key from the Authorization header without verifying the signature
func GetAccessKeyFromPresignedURL ¶
GetAccessKeyFromPresignedURL extracts the access key from pre-signed URL query parameters
func IsChunkedEncoding ¶
IsChunkedEncoding checks if the request uses AWS SigV4 chunked encoding
func ValidatePostPolicyConditions ¶
func ValidatePostPolicyConditions(doc *PostPolicyDocument, bucket, key, contentType string, contentLength int64) error
ValidatePostPolicyConditions enforces the conditions encoded in a POST policy document.
Supported condition forms:
- Object condition: {"bucket": "val"}, {"key": "val"}, {"content-type": "val"}
- Array eq: ["eq", "$field", "value"]
- Array starts-with: ["starts-with", "$field", "prefix"]
- Array length range: ["content-length-range", min, max]
Credential/algorithm/date conditions are skipped — they are already validated by the signature.
func ValidatePostPolicyExpiration ¶
func ValidatePostPolicyExpiration(doc *PostPolicyDocument) error
ValidatePostPolicyExpiration checks whether the policy has expired. Reuses ErrPresignedURLExpired to keep error mapping consistent.
func VerifyPostPolicySignature ¶
func VerifyPostPolicySignature(form *PostPolicyForm, secretKey string) error
VerifyPostPolicySignature verifies the HMAC-SHA256 signature of a POST policy upload.
Signing key derivation (same as standard SigV4 ComputeSignature):
signingKey = HMAC(HMAC(HMAC(HMAC("AWS4"+secretKey, date), region), "s3"), "aws4_request")
The signature is computed over the raw base64-encoded policy string (not the decoded JSON).
func VerifyPresignedSignature ¶
VerifyPresignedSignature verifies the AWS Signature V4 signature for a pre-signed URL request
Types ¶
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator handles authentication and authorization
func New ¶
func New(metadataManager *metadata.Manager, rootAccessKey, rootSecretKey string) *Authenticator
New creates a new authenticator with primary root credentials
func (*Authenticator) AltRootAccessKey ¶
func (a *Authenticator) AltRootAccessKey() string
AltRootAccessKey returns the current alternative root access key. Implements policy.AdminKeyChecker.
func (*Authenticator) AltRootUser ¶
func (a *Authenticator) AltRootUser() *metadata.User
func (*Authenticator) AuthMiddleware ¶
func (a *Authenticator) AuthMiddleware(next http.Handler) http.Handler
func (*Authenticator) AuthenticatePostPolicyRequest ¶
func (a *Authenticator) AuthenticatePostPolicyRequest(r *http.Request) (*metadata.User, *PostPolicyForm, *PostPolicyDocument, error)
AuthenticatePostPolicyRequest validates an HTTP request that uses S3 POST policy form-based upload.
Credentials are embedded in the multipart form body (not headers or query string). The method parses the form, decodes the policy, checks expiration, looks up the user, and verifies the HMAC-SHA256 signature over the base64-encoded policy string.
func (*Authenticator) AuthenticatePresignedRequest ¶
func (a *Authenticator) AuthenticatePresignedRequest(r *http.Request) (*metadata.User, time.Time, error)
AuthenticatePresignedRequest validates an HTTP request using AWS Signature V4 pre-signed URL authentication. This is used for temporary access via pre-signed URLs embedded in query parameters.
Returns the authenticated user and expiration time if successful, or an error: - ErrMissingPresignedParams: Required query parameters missing - ErrPresignedURLExpired: The pre-signed URL has expired - ErrUserNotFound: Access key doesn't exist - ErrUserInactive: User account is not active - ErrSignatureMismatch: Signature verification failed
func (*Authenticator) AuthenticateRequest ¶
AuthenticateRequest validates an HTTP request using AWS Signature V4 authentication. This is the main entry point for request authentication.
Returns the authenticated user if successful, or an error: - ErrAuthenticationFailed: Missing or invalid Authorization header - ErrUserNotFound: Access key doesn't exist - ErrUserInactive: User account is not active - ErrSignatureMismatch: Signature verification failed
func (*Authenticator) GetUserForAccessKey ¶
func (a *Authenticator) GetUserForAccessKey(ctx context.Context, accessKey string) (*metadata.User, error)
GetUserForAccessKey retrieves user information for an access key
func (*Authenticator) IsServiceAccount ¶
func (a *Authenticator) IsServiceAccount(ctx context.Context, accessKey string) (*iam.ServiceAccount, bool)
IsServiceAccount checks if the given access key belongs to a service account. Returns the ServiceAccount and true if found, nil and false otherwise.
func (*Authenticator) PrimaryRootAccessKey ¶
func (a *Authenticator) PrimaryRootAccessKey() string
PrimaryRootAccessKey returns the current primary root access key. Implements policy.AdminKeyChecker.
func (*Authenticator) RootUser ¶
func (a *Authenticator) RootUser() *metadata.User
func (*Authenticator) UpdateAltCredentials ¶
func (a *Authenticator) UpdateAltCredentials(accessKey, secretKey string)
UpdateAltCredentials atomically replaces the alternative root credentials. Call this in dual-admin mode where CLI creds are primary and data-config creds are the alternative.
func (*Authenticator) UpdatePrimaryCredentials ¶
func (a *Authenticator) UpdatePrimaryCredentials(accessKey, secretKey string)
UpdatePrimaryCredentials atomically replaces the primary root credentials. Call this when the data-config admin is the primary (no explicit CLI creds).
func (*Authenticator) ValidateCredentials ¶
func (a *Authenticator) ValidateCredentials(ctx context.Context, accessKey, secretKey string) bool
ValidateCredentials checks if access key and secret key are valid
func (*Authenticator) WithAlternativeRoot ¶
func (a *Authenticator) WithAlternativeRoot(accessKey, secretKey string) *Authenticator
WithAlternativeRoot adds alternative root credentials (e.g., from data config) This allows both CLI admin and data config admin to coexist
type ChunkSignatureVerifier ¶
type ChunkSignatureVerifier struct {
SecretKey string // Secret key for HMAC
Timestamp time.Time // Request timestamp from X-Amz-Date
Region string // AWS region from credential scope
PreviousSignature string // Signature of previous chunk (or request signature for first chunk)
}
ChunkSignatureVerifier holds parameters for verifying chunk signatures
type ChunkedReader ¶
type ChunkedReader struct {
// contains filtered or unexported fields
}
ChunkedReader decodes AWS SigV4 chunked transfer encoding
func NewChunkedReader ¶
func NewChunkedReader(r io.Reader) *ChunkedReader
NewChunkedReader creates a new chunked encoding decoder without signature verification
func (*ChunkedReader) Read ¶
func (cr *ChunkedReader) Read(p []byte) (int, error)
Read implements io.Reader, decoding chunked data
func (*ChunkedReader) WithSignatureVerification ¶
func (cr *ChunkedReader) WithSignatureVerification(verifier *ChunkSignatureVerifier) *ChunkedReader
WithSignatureVerification enables chunk signature verification
type Credentials ¶
type Credentials struct {
AccessKey string
Date string
Region string
Service string
SignedHeaders []string
Signature string
}
Credentials represents parsed AWS credentials from the Authorization header
func ParseAuthorizationHeader ¶
func ParseAuthorizationHeader(authHeader string) (*Credentials, error)
ParseAuthorizationHeader parses the AWS Signature V4 Authorization header Format: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, SignedHeaders=host;range;x-amz-date, Signature=fe5f80f77d5fa3beca038a248ff027d0445342fe2855ddc963176630326f1024
func ParsePresignedURLAuth ¶
ParsePresignedURLAuth parses AWS Signature V4 authentication from query parameters Used for pre-signed URLs with format: ?X-Amz-Algorithm=AWS4-HMAC-SHA256 &X-Amz-Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request &X-Amz-Date=20130524T000000Z &X-Amz-Expires=86400 &X-Amz-SignedHeaders=host &X-Amz-Signature=...
type PostPolicyDocument ¶
type PostPolicyDocument struct {
Expiration time.Time
Conditions []json.RawMessage
}
PostPolicyDocument is the decoded JSON policy document from a POST policy upload.
func ParsePostPolicyDocument ¶
func ParsePostPolicyDocument(policyBase64 string) (*PostPolicyDocument, error)
ParsePostPolicyDocument base64-decodes and JSON-parses the policy document.
func (*PostPolicyDocument) UnmarshalJSON ¶
func (p *PostPolicyDocument) UnmarshalJSON(data []byte) error
UnmarshalJSON customises JSON decoding to parse the Expiration string.
type PostPolicyForm ¶
type PostPolicyForm struct {
Algorithm string // x-amz-algorithm
Credential string // x-amz-credential (full: ACCESSKEY/DATE/REGION/s3/aws4_request)
Date string // x-amz-date (ISO 8601 timestamp)
Signature string // x-amz-signature
PolicyBase64 string // policy (base64-encoded policy document)
Key string // key (object key, may contain ${filename})
AccessKey string // extracted from Credential
DateShort string // extracted date (YYYYMMDD) from Credential
Region string // extracted from Credential
ContentType string // Content-Type
SuccessRedirect string // success_action_redirect
SuccessStatus string // success_action_status
}
PostPolicyForm holds parsed credential fields from a multipart/form-data POST policy upload.
func ParsePostPolicyForm ¶
func ParsePostPolicyForm(r *http.Request) (*PostPolicyForm, error)
ParsePostPolicyForm parses the multipart form fields from a POST policy upload request.