Documentation
¶
Index ¶
- Constants
- Variables
- func BuildAuthorizationHeader(accessKeyID, credentialScope, signedHeaders, signature string) string
- func BuildCredentialScope(date, region, service string) string
- func CanonicalizeHeaders(headers http.Header, signedHeaderNames []string) (canonical string, signedHeaders string)
- func ComputePayloadHash(payload io.Reader) (string, error)
- func ComputePayloadHashFromBytes(payload []byte) string
- func ComputeSignature(signingKey []byte, stringToSign string) string
- func ComputeStringHash(data string) string
- func DeriveSigningKey(secret, date, region, service string) []byte
- func EncodeQueryValue(value string) string
- func EncodeQueryValues(values url.Values) string
- func EncodeURI(path string, encodeSlash bool) string
- func ExtractSignedHeaders(headers http.Header, additionalHeaders []string) []string
- func FormatSigningDate(t time.Time) string
- func FormatSigningTime(t time.Time) string
- func GetHeaderValue(headers http.Header, name string) string
- func NormalizePath(path string) string
- func ParseAuthorizationHeader(authHeader string) (credential, signedHeaders, signature string, err error)
- func ParseCredential(credential string) (accessKeyID, scope string, err error)
- func ParseCredentialScope(scope string) (date, region, service string, err error)
- func ParseSigningTime(timestamp string) (time.Time, error)
- func SetHeaderValue(headers http.Header, name, value string)
- func VerifySignature(expected, actual string) bool
- type CanonicalRequest
- type CanonicalRequestOptions
- type CredentialStore
- type Credentials
- type CredentialsProvider
- type InMemoryCredentialStore
- type SignedRequest
- type Signer
- type SignerOption
- type SignerOptions
- type SigningError
- type StaticCredentialsProvider
- type StringToSign
- type ValidationError
- type VerificationError
- type VerificationResult
- type Verifier
- type VerifierOption
- type VerifierOptions
Constants ¶
const ( // Algorithm is the AWS Signature Version 4 algorithm identifier Algorithm = "AWS4-HMAC-SHA256" // TimeFormat is the ISO8601 basic format used for timestamps TimeFormat = "20060102T150405Z" // DateFormat is the date format used for credential scope DateFormat = "20060102" // AWS4Request is the termination string for the credential scope AWS4Request = "aws4_request" // UnsignedPayload is used when the payload is not signed UnsignedPayload = "UNSIGNED-PAYLOAD" )
const ( // HeaderHost is the Host header name HeaderHost = "host" // HeaderAuthorization is the Authorization header name HeaderAuthorization = "Authorization" // HeaderXAmzDate is the X-Amz-Date header name for the request timestamp HeaderXAmzDate = "X-Amz-Date" // HeaderXAmzContentSHA256 is the X-Amz-Content-Sha256 header for payload hash HeaderXAmzContentSHA256 = "X-Amz-Content-Sha256" // HeaderXAmzSecurityToken is the X-Amz-Security-Token header for session tokens HeaderXAmzSecurityToken = "X-Amz-Security-Token" // HeaderContentType is the Content-Type header HeaderContentType = "Content-Type" )
Variables ¶
var ( // ErrInvalidCredentials indicates that the credentials are invalid or missing required fields ErrInvalidCredentials = errors.New("invalid credentials") // ErrMissingAuthorizationHeader indicates that the Authorization header is missing from the request ErrMissingAuthorizationHeader = errors.New("missing authorization header") // ErrInvalidAuthorizationHeader indicates that the Authorization header format is invalid ErrInvalidAuthorizationHeader = errors.New("invalid authorization header format") // ErrInvalidSignature indicates that the signature does not match the computed signature ErrInvalidSignature = errors.New("invalid signature") // ErrTimestampOutOfRange indicates that the request timestamp is outside the acceptable range ErrTimestampOutOfRange = errors.New("timestamp out of acceptable range") // ErrMissingRequiredHeader indicates that a required header is missing from the request ErrMissingRequiredHeader = errors.New("missing required header") // ErrCredentialNotFound indicates that the credential was not found in the credential store ErrCredentialNotFound = errors.New("credential not found") // ErrInvalidTimestamp indicates that the timestamp format is invalid ErrInvalidTimestamp = errors.New("invalid timestamp format") // ErrEmptyPayload indicates that the payload is empty when it should not be ErrEmptyPayload = errors.New("empty payload") )
Sentinel errors
Functions ¶
func BuildAuthorizationHeader ¶
BuildAuthorizationHeader builds the Authorization header value Format: AWS4-HMAC-SHA256 Credential=ACCESS_KEY/SCOPE, SignedHeaders=HEADERS, Signature=SIGNATURE
func BuildCredentialScope ¶
BuildCredentialScope builds the credential scope string Format: YYYYMMDD/region/service/aws4_request
func CanonicalizeHeaders ¶
func CanonicalizeHeaders(headers http.Header, signedHeaderNames []string) (canonical string, signedHeaders string)
CanonicalizeHeaders creates the canonical headers string for AWS Signature Version 4 It takes the HTTP headers and a list of header names to include in the signature Returns the canonical headers string and the signed headers list
Rules: 1. Convert header names to lowercase 2. Trim leading and trailing whitespace from values 3. Convert sequential spaces in values to a single space 4. Sort headers by name (case-insensitive) 5. Format as "name:value\n" for each header 6. The signed headers list is semicolon-separated lowercase header names
func ComputePayloadHash ¶
ComputePayloadHash computes the SHA256 hash of the request payload and returns it as a lowercase hex string
func ComputePayloadHashFromBytes ¶
ComputePayloadHashFromBytes computes the SHA256 hash of the request payload bytes and returns it as a lowercase hex string
func ComputeSignature ¶
ComputeSignature computes the signature for the given string to sign using the provided signing key. Returns the signature as a lowercase hex string.
func ComputeStringHash ¶
ComputeStringHash computes the SHA256 hash of a string and returns it as a lowercase hex string
func DeriveSigningKey ¶
DeriveSigningKey derives the signing key using the AWS Signature Version 4 algorithm This performs a 4-step HMAC-SHA256 chain: 1. kDate = HMAC-SHA256("AWS4" + secret, date) 2. kRegion = HMAC-SHA256(kDate, region) 3. kService = HMAC-SHA256(kRegion, service) 4. kSigning = HMAC-SHA256(kService, "aws4_request")
func EncodeQueryValue ¶
EncodeQueryValue encodes a single query parameter value according to RFC 3986 This is used for canonical query string construction
func EncodeQueryValues ¶
EncodeQueryValues encodes URL query parameters into a canonical query string The query string is sorted by parameter name, then by value if there are multiple values Each parameter is encoded as name=value with proper RFC 3986 encoding Multiple parameters are joined with &
func EncodeURI ¶
EncodeURI encodes a URI path according to RFC 3986 for AWS Signature Version 4 If encodeSlash is true, forward slashes (/) are also encoded All characters except unreserved characters (A-Z a-z 0-9 - _ . ~) are percent-encoded
func ExtractSignedHeaders ¶
ExtractSignedHeaders determines which headers should be included in the signature By default, includes: - host (always required) - All x-amz-* headers - content-type (if present)
Additional headers can be specified via options
func FormatSigningDate ¶
FormatSigningDate formats a time value into the date format used in the credential scope: YYYYMMDD
func FormatSigningTime ¶
FormatSigningTime formats a time value into the ISO8601 basic format used in AWS Signature Version 4: YYYYMMDDTHHMMSSZ
func GetHeaderValue ¶
GetHeaderValue retrieves a header value in a case-insensitive manner
func NormalizePath ¶
NormalizePath normalizes a URI path for canonical request construction It removes redundant slashes and applies RFC 3986 encoding
func ParseAuthorizationHeader ¶
func ParseAuthorizationHeader(authHeader string) (credential, signedHeaders, signature string, err error)
ParseAuthorizationHeader parses the Authorization header Returns credential (access key ID + scope), signed headers list, and signature
func ParseCredential ¶
ParseCredential parses the credential string from the Authorization header Format: ACCESS_KEY_ID/DATE/REGION/SERVICE/aws4_request Returns access key ID and credential scope
func ParseCredentialScope ¶
ParseCredentialScope parses a credential scope string into its components Returns date, region, service, and an error if parsing fails
func ParseSigningTime ¶
ParseSigningTime parses a timestamp in ISO8601 basic format
func SetHeaderValue ¶
SetHeaderValue sets a header value, replacing any existing values
func VerifySignature ¶
VerifySignature performs constant-time comparison of two signatures to prevent timing attacks
Types ¶
type CanonicalRequest ¶
type CanonicalRequest struct {
// Method is the HTTP method (GET, POST, etc.)
Method string
// CanonicalURI is the RFC 3986 encoded URI path
CanonicalURI string
// CanonicalQueryString is the sorted, encoded query parameters
CanonicalQueryString string
// CanonicalHeaders is the formatted canonical headers string
CanonicalHeaders string
// SignedHeaders is the semicolon-separated list of signed header names
SignedHeaders string
// PayloadHash is the SHA256 hash of the payload or "UNSIGNED-PAYLOAD"
PayloadHash string
}
CanonicalRequest represents a canonical HTTP request for AWS Signature Version 4
func BuildCanonicalRequest ¶
func BuildCanonicalRequest(req *http.Request, payloadHash string, opts *CanonicalRequestOptions) (*CanonicalRequest, error)
BuildCanonicalRequest builds a canonical request from an HTTP request
func (*CanonicalRequest) String ¶
func (cr *CanonicalRequest) String() string
String returns the canonical request as a string in the AWS SigV4 format: HTTPMethod + "\n" + CanonicalURI + "\n" + CanonicalQueryString + "\n" + CanonicalHeaders + "\n" + SignedHeaders + "\n" + HashedPayload
type CanonicalRequestOptions ¶
type CanonicalRequestOptions struct {
// DisableURIPathEscaping disables URI path encoding (for S3)
DisableURIPathEscaping bool
// AdditionalSignedHeaders specifies additional headers to include in the signature
AdditionalSignedHeaders []string
// UnsignedPayload indicates the payload should not be signed
UnsignedPayload bool
}
CanonicalRequestOptions provides options for building canonical requests
type CredentialStore ¶
type CredentialStore interface {
// GetCredentials retrieves credentials for the given access key ID
GetCredentials(ctx context.Context, accessKeyID string) (*Credentials, error)
}
CredentialStore is an interface for looking up credentials by access key ID This is used on the server side for signature verification
type Credentials ¶
type Credentials struct {
// AccessKeyID is the access key identifier
AccessKeyID string
// SecretAccessKey is the secret key used for signing
SecretAccessKey string
// SessionToken is an optional session token for temporary credentials
SessionToken string
}
Credentials represents AWS-style credentials used for signing requests
func (*Credentials) Validate ¶
func (c *Credentials) Validate() error
Validate checks if the credentials are valid
type CredentialsProvider ¶
type CredentialsProvider interface {
// Retrieve retrieves credentials from the provider
Retrieve(ctx context.Context) (*Credentials, error)
}
CredentialsProvider is an interface for retrieving credentials This allows for different credential sources (static, environment, files, etc.)
type InMemoryCredentialStore ¶
type InMemoryCredentialStore struct {
// contains filtered or unexported fields
}
InMemoryCredentialStore is a simple in-memory implementation of CredentialStore This is primarily for testing and simple use cases
func NewInMemoryCredentialStore ¶
func NewInMemoryCredentialStore() *InMemoryCredentialStore
NewInMemoryCredentialStore creates a new in-memory credential store
func (*InMemoryCredentialStore) AddCredentials ¶
func (s *InMemoryCredentialStore) AddCredentials(creds *Credentials) error
AddCredentials adds credentials to the store
func (*InMemoryCredentialStore) GetCredentials ¶
func (s *InMemoryCredentialStore) GetCredentials(ctx context.Context, accessKeyID string) (*Credentials, error)
GetCredentials retrieves credentials for the given access key ID
func (*InMemoryCredentialStore) RemoveCredentials ¶
func (s *InMemoryCredentialStore) RemoveCredentials(accessKeyID string)
RemoveCredentials removes credentials from the store
type SignedRequest ¶
type SignedRequest struct {
// Request is the signed HTTP request
Request *http.Request
// Signature is the computed signature
Signature string
// SignedHeaders is the list of headers included in the signature
SignedHeaders string
// CredentialScope is the credential scope string
CredentialScope string
// SigningTime is the time used for signing
SigningTime time.Time
}
SignedRequest represents a signed HTTP request
type Signer ¶
type Signer struct {
// contains filtered or unexported fields
}
Signer signs HTTP requests using AWS Signature Version 4
func NewSigner ¶
func NewSigner(creds CredentialsProvider, opts ...SignerOption) *Signer
NewSigner creates a new Signer with the given credentials provider and options
type SignerOption ¶
type SignerOption func(*SignerOptions)
SignerOption is a functional option for configuring the Signer
func WithAdditionalSignedHeaders ¶
func WithAdditionalSignedHeaders(headers ...string) SignerOption
WithAdditionalSignedHeaders adds additional headers to be included in the signature
func WithDisableImplicitContentSHA256 ¶
func WithDisableImplicitContentSHA256() SignerOption
WithDisableImplicitContentSHA256 disables automatically adding the X-Amz-Content-Sha256 header
func WithDisableURIPathEscaping ¶
func WithDisableURIPathEscaping() SignerOption
WithDisableURIPathEscaping disables URI path encoding This is typically used for S3-compatible services
func WithSigningTime ¶
func WithSigningTime(t time.Time) SignerOption
WithSigningTime sets a specific signing time (primarily for testing)
func WithUnsignedPayload ¶
func WithUnsignedPayload() SignerOption
WithUnsignedPayload configures the signer to not sign the payload The X-Amz-Content-Sha256 header will be set to "UNSIGNED-PAYLOAD"
type SignerOptions ¶
type SignerOptions struct {
// UnsignedPayload indicates that the payload should not be signed
// The payload hash will be set to "UNSIGNED-PAYLOAD"
UnsignedPayload bool
// DisableURIPathEscaping disables URI path encoding
// This is typically used for S3-compatible services
DisableURIPathEscaping bool
// AdditionalSignedHeaders specifies additional headers to include in the signature
// beyond the default set (host, x-amz-*, content-type)
AdditionalSignedHeaders []string
// DisableImplicitContentSHA256 disables automatically adding the X-Amz-Content-Sha256 header
DisableImplicitContentSHA256 bool
// OverrideSigningTime allows overriding the signing time (primarily for testing)
OverrideSigningTime *time.Time
}
SignerOptions contains configuration options for the Signer
type SigningError ¶
SigningError represents an error that occurred during the signing process
func (*SigningError) Error ¶
func (e *SigningError) Error() string
func (*SigningError) Unwrap ¶
func (e *SigningError) Unwrap() error
type StaticCredentialsProvider ¶
type StaticCredentialsProvider struct {
// contains filtered or unexported fields
}
StaticCredentialsProvider provides credentials from a static source
func NewStaticCredentialsProvider ¶
func NewStaticCredentialsProvider(creds *Credentials) *StaticCredentialsProvider
NewStaticCredentialsProvider creates a new static credentials provider
func (*StaticCredentialsProvider) Retrieve ¶
func (p *StaticCredentialsProvider) Retrieve(ctx context.Context) (*Credentials, error)
Retrieve returns the static credentials
type StringToSign ¶
type StringToSign struct {
// Algorithm is the signing algorithm (AWS4-HMAC-SHA256)
Algorithm string
// RequestDateTime is the ISO8601 timestamp
RequestDateTime string
// CredentialScope is the credential scope string
CredentialScope string
// HashedCanonicalRequest is the SHA256 hash of the canonical request
HashedCanonicalRequest string
}
StringToSign represents the string that will be signed
func BuildStringToSign ¶
func BuildStringToSign(canonicalReq *CanonicalRequest, service, region string, signTime time.Time) (*StringToSign, error)
BuildStringToSign builds the string to sign from a canonical request
func (*StringToSign) String ¶
func (sts *StringToSign) String() string
String returns the string to sign in the AWS SigV4 format: Algorithm + "\n" + RequestDateTime + "\n" + CredentialScope + "\n" + HashedCanonicalRequest
type ValidationError ¶
ValidationError represents a validation error
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error
type VerificationError ¶
VerificationError represents an error that occurred during signature verification
func (*VerificationError) Error ¶
func (e *VerificationError) Error() string
func (*VerificationError) Unwrap ¶
func (e *VerificationError) Unwrap() error
type VerificationResult ¶
type VerificationResult struct {
// Valid indicates whether the signature is valid
Valid bool
// AccessKeyID is the access key ID extracted from the request
AccessKeyID string
// SignedHeaders is the list of headers that were signed
SignedHeaders []string
// RequestTime is the timestamp from the request
RequestTime time.Time
// Service is the service name from the credential scope
Service string
// Region is the region from the credential scope
Region string
// Error contains any error that occurred during verification
Error error
}
VerificationResult represents the result of signature verification
type Verifier ¶
type Verifier struct {
// contains filtered or unexported fields
}
Verifier verifies HTTP request signatures using AWS Signature Version 4
func NewVerifier ¶
func NewVerifier(store CredentialStore, opts ...VerifierOption) *Verifier
NewVerifier creates a new Verifier with the given credential store and options
type VerifierOption ¶
type VerifierOption func(*VerifierOptions)
VerifierOption is a functional option for configuring the Verifier
func WithAllowUnsignedPayload ¶
func WithAllowUnsignedPayload() VerifierOption
WithAllowUnsignedPayload allows requests with unsigned payloads
func WithMaxTimestampDrift ¶
func WithMaxTimestampDrift(duration time.Duration) VerifierOption
WithMaxTimestampDrift sets the maximum allowed time drift for request timestamps Default is 5 minutes if not specified
func WithRequireSecurityToken ¶
func WithRequireSecurityToken() VerifierOption
WithRequireSecurityToken requires the X-Amz-Security-Token header to be present
func WithVerifierCurrentTime ¶
func WithVerifierCurrentTime(t time.Time) VerifierOption
WithVerifierCurrentTime sets the current time for timestamp validation (testing)
func WithVerifierDisableURIPathEscaping ¶
func WithVerifierDisableURIPathEscaping() VerifierOption
WithVerifierDisableURIPathEscaping disables URI path encoding verification
type VerifierOptions ¶
type VerifierOptions struct {
// MaxTimestampDrift is the maximum allowed time difference between
// the request timestamp and the current time
MaxTimestampDrift time.Duration
// DisableURIPathEscaping disables URI path encoding verification
DisableURIPathEscaping bool
// RequireSecurityToken indicates whether the X-Amz-Security-Token header is required
RequireSecurityToken bool
// AllowUnsignedPayload allows requests with "UNSIGNED-PAYLOAD" in the X-Amz-Content-Sha256 header
AllowUnsignedPayload bool
// OverrideCurrentTime allows overriding the current time for timestamp validation (testing)
OverrideCurrentTime *time.Time
}
VerifierOptions contains configuration options for the Verifier