httpsign

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 17, 2024 License: MIT Imports: 21 Imported by: 2

README

http-signature-go

Signing HTTP Messages implement base on HTTP Signature

GoDoc Go.Dev reference codecov Tests Go Report Card Licence Tag

Usage

Installation

Use go get.

    go get github.com/thinkgos/http-signature-go

Then import the package into your own code.

    import httpsign "github.com/thinkgos/http-signature-go"
Example
Encode
//go:build encoder

package main

import (
	"bytes"
	"io"
	"net/http"
	"time"

	httpsign "github.com/thinkgos/http-signature-go"
)

func main() {
	// this is a test request
	r, err := http.NewRequest("POST", "http://example.com", bytes.NewBufferString("example.com"))
	if err != nil {
		panic(err)
	}

	var body []byte
	var digest string

	if r.Body != nil {
		body, err = io.ReadAll(r.Body)
		if err != nil {
			panic(err)
		}
		r.Body.Close()
		r.Body = io.NopCloser(bytes.NewBuffer(body))
	}
	keyId, keySecret := "key_id_1", "key_secret_1"

	paramter := httpsign.Parameter{
		KeyId:     httpsign.KeyId(keyId),
		Signature: "",
		Algorithm: "",
		Created:   0,
		Expires:   0,
		Headers: []string{
			httpsign.RequestTarget,
			httpsign.Date,
			httpsign.Nonce,
			httpsign.Digest,
		},
		Scheme: httpsign.SchemeSignature,
		Method: httpsign.SigningMethodHmacSha512,
		Key:    []byte(keySecret),
	}

	if len(body) > 0 {
		digest, err = httpsign.NewDigestUsingShared(paramter.Method).
			Sign(body, paramter.Key)
		if err != nil {
			panic(err)
		}
	}
	r.Header.Set(httpsign.Date, time.Now().UTC().Format(http.TimeFormat))
	r.Header.Set(httpsign.Nonce, "abcdefghijklmnopqrstuvwxyz123456") // 32位随机字符串
	r.Header.Set(httpsign.Digest, digest)
	err = paramter.MergerHeader(r)
	if err != nil {
		panic(err)
	}

	// Now: use the request, which carry http signature headers
	// _ = r
}
Decode
//go:build decoder

package main

import (
	httpsign "github.com/thinkgos/http-signature-go"
)

func main() {
	keystone := httpsign.NewKeystoneMemory()

	httpSignParser := httpsign.NewParser(
		httpsign.WithMinimumRequiredHeaders([]string{
			httpsign.RequestTarget,
			httpsign.Date,
			httpsign.Nonce,
			httpsign.Digest,
		}),
		httpsign.WithSigningMethods(
			httpsign.SigningMethodHmacSha256.Alg(),
			func() httpsign.SigningMethod { return httpsign.SigningMethodHmacSha256 },
		),
		httpsign.WithSigningMethods(
			httpsign.SigningMethodHmacSha384.Alg(),
			func() httpsign.SigningMethod { return httpsign.SigningMethodHmacSha384 },
		),
		httpsign.WithSigningMethods(
			httpsign.SigningMethodHmacSha512.Alg(),
			func() httpsign.SigningMethod { return httpsign.SigningMethodHmacSha512 },
		),
		httpsign.WithValidators(
			httpsign.NewDigestUsingSharedValidator(),
			httpsign.NewDateValidator(),
		),
		httpsign.WithKeystone(keystone),
	)

	err := httpSignParser.AddMetadata(
		httpsign.KeyId("key_id_1"),
		httpsign.Metadata{
			Scheme: httpsign.SchemeSignature,
			Alg:    "hmac-sha512",
			Key:    []byte("key_secret_1"),
		},
	)
	if err != nil {
		panic(err)
	}
	err = httpSignParser.AddMetadata(
		httpsign.KeyId("key_id_2"),
		httpsign.Metadata{
			Scheme: httpsign.SchemeSignature,
			Alg:    "hmac-sha512",
			Key:    []byte("key_secret_2"),
		},
	)
	if err != nil {
		panic(err)
	}

	// parser http.Request
	// httpSignParser.ParseFromRequest() and httpSignParser.Verify
	// or
	// httpSignParser.ParseVerify()
}
Encode/Decode
package main

import (
	"context"
	"net/http"
	"reflect"
	"slices"
	"strconv"
	"time"

	httpsign "github.com/thinkgos/http-signature-go"
)

// mock interface always return true
type timeAlwaysValid struct{}

func (v *timeAlwaysValid) Validate(r *http.Request, _ *httpsign.Parameter) error { return nil }

func main() {
	//* encoder

	r, err := http.NewRequestWithContext(context.Background(), "GET", "/", nil)
	if err != nil {
		panic(err)
	}

	p := &httpsign.Parameter{
		KeyId:     "key_id_1",
		Signature: "",
		Algorithm: "",
		Created:   time.Now().Add(-time.Hour).UTC().Unix(),
		Expires:   0,
		Headers:   []string{httpsign.RequestTarget, httpsign.Created, httpsign.Host},
		Scheme:    httpsign.SchemeSignature,
		Method:    httpsign.SigningMethodHmacSha256,
		Key:       []byte("1234"),
	}

	wantCreatedHeader := strconv.FormatInt(p.Created, 10)
	r.Header.Set(httpsign.Created, wantCreatedHeader)
	err = p.MergerHeader(r)
	if err != nil {
		panic(err)
	}

	//* decoder

	// validate created always valid
	parser := httpsign.NewParser(
		httpsign.WithMinimumRequiredHeaders([]string{httpsign.RequestTarget, httpsign.Created, httpsign.Host}),
		httpsign.WithSigningMethods(httpsign.SigningMethodHmacSha256.Alg(), func() httpsign.SigningMethod { return httpsign.SigningMethodHmacSha256 }),
		httpsign.WithValidators(&timeAlwaysValid{}),
	)
	err = parser.AddMetadata("key_id_1", httpsign.Metadata{
		Scheme: httpsign.SchemeUnspecified,
		Alg:    httpsign.SigningMethodHmacSha256.Alg(),
		Key:    []byte("1234"),
	})
	if err != nil {
		panic(err)
	}
	// parser http.Request

	// use httpSignParser.ParseFromRequest() and httpSignParser.Verify
	gotParam, err := parser.ParseFromRequest(r)
	if err != nil {
		panic(err)
	}
	if p.KeyId != gotParam.KeyId ||
		p.Signature != gotParam.Signature ||
		p.Algorithm != gotParam.Algorithm ||
		p.Created != gotParam.Created ||
		p.Expires != gotParam.Expires ||
		!slices.Equal(p.Headers, gotParam.Headers) ||
		p.Scheme != gotParam.Scheme {
		panic("param miss match")
	}
	err = parser.Verify(r, gotParam)
	if err != nil {
		panic(err)
	}
	if p.Method != gotParam.Method ||
		!reflect.DeepEqual(p.Key, gotParam.Key) ||
		p.Scheme != gotParam.Scheme {
		panic("param miss match")
	}
	// or

	// use httpSignParser.ParseVerify()
	gotScheme, err := parser.ParseVerify(r)
	if err != nil {
		panic(err)
	}
	if gotScheme != p.Scheme {
		panic("schema miss match")
	}
}

License

This project is under MIT License. See the LICENSE file for the full license text.

Documentation

Index

Constants

View Source
const (
	HeaderAuthorization = "Authorization"
	HeaderSignature     = "Signature"
)
View Source
const (
	Date          = "date"
	Digest        = "digest"
	Host          = "host"
	Nonce         = "nonce"
	ContentLength = "content-length"
	RequestTarget = "(request-target)"
	Created       = "(created)"
	Expires       = "(expires)"
)
View Source
const (
	// Unspecified scheme, mean unlimited.
	SchemeUnspecified = iota
	// Authentication scheme.
	SchemeAuthentication
	// Signature http header scheme.
	SchemeSignature
)

Variables

View Source
var (
	// ErrSchemeUnsupported scheme not supported with keyId.
	ErrSchemeUnsupported = errors.New("scheme unsupported")
	// ErrNoSignatureInRequest `Signature` not found in request.
	ErrNoSignatureInRequest = errors.New("signature not found in request")
	// ErrKeyIdMissing keyId not in header value.
	ErrKeyIdMissing = errors.New("keyId must be in header value")
	// ErrSignatureMissing signature not in header value.
	ErrSignatureMissing = errors.New("signature must be in header value")
	// ErrKeyIdInvalid KeyID in header does not provided.
	ErrKeyIdInvalid = errors.New("keyId invalid")
	// ErrAlgorithmMismatch Algorithm in header does not match with keyId.
	ErrAlgorithmMismatch = errors.New("algorithm does not match")
	// ErrAlgorithmUnsupported Algorithm not supported.
	ErrAlgorithmUnsupported = errors.New("algorithm unsupported")
	// ErrMinimumRequiredHeader minimum requirement header do not meet.
	ErrMinimumRequiredHeader = errors.New("header field is not meet minimum requirement")
	// ErrDateInvalid invalid 'date' in header.
	ErrDateInvalid = errors.New("date invalid in header")
	// ErrDateNotInRange 'date' not in acceptable range.
	ErrDateNotInRange = errors.New("date is not in acceptable range")
	// ErrCreatedInvalid (created) invalid.
	ErrCreatedInvalid = errors.New("(created) invalid")
	// ErrCreatedNotInRange '(created)' not in acceptable range.
	ErrCreatedNotInRange = errors.New("(created) is not in acceptable range")
	// ErrExpiresInvalid (expires) invalid.
	ErrExpiresInvalid = errors.New("(expires) invalid")
	// ErrSignatureExpired '(expires)' has expired in header
	ErrSignatureExpired = errors.New("signature has be expired")
	// ErrSignatureInvalid signing string do not match
	ErrSignatureInvalid = errors.New("signature invalid")
	// ErrDigestMismatch body do not match with submitted digest
	ErrDigestMismatch = errors.New("body is not match with digest")

	// ErrKeyInvalid key is invalid.
	ErrKeyInvalid = errors.New("key is invalid")
	// ErrKeyTypeInvalid key is invalid type
	ErrKeyTypeInvalid = errors.New("key is invalid type")
	// ErrHashUnavailable the requested hash function is unavailable
	ErrHashUnavailable = errors.New("the requested hash function is unavailable")

	// ErrUnterminatedParameter could not parse value
	ErrUnterminatedParameter = errors.New("Unterminated parameter")
	// ErrMissingDoubleQuote after character = not have double quote
	ErrMissingDoubleQuote = errors.New(`Missing " after = character`)
	// ErrMissingEqualCharacter there is no character = before " or , character
	ErrMissingEqualCharacter = errors.New(`Missing = character =`)
)
View Source
var (
	SigningMethodEcdsaSha256 = &SigningMethodECDSA{"ecdsa-sha256", crypto.SHA256, 32, 256}
	SigningMethodEcdsaSha384 = &SigningMethodECDSA{"ecdsa-sha384", crypto.SHA384, 48, 384}
	SigningMethodEcdsaSha512 = &SigningMethodECDSA{"ecdsa-sha512", crypto.SHA512, 66, 521}
)

Specific instance ecdsa.

View Source
var (
	ErrNotECPublicKey  = errors.New("key is not a valid ECDSA public key")
	ErrNotECPrivateKey = errors.New("key is not a valid ECDSA private key")
)
View Source
var (
	ErrNotEdPrivateKey = errors.New("key is not a valid Ed25519 private key")
	ErrNotEdPublicKey  = errors.New("key is not a valid Ed25519 public key")
)
View Source
var (
	SigningMethodHmacMd5    = &SigningMethodHMAC{"hmac-md5", crypto.MD5}
	SigningMethodHmacSha256 = &SigningMethodHMAC{"hmac-sha256", crypto.SHA256}
	SigningMethodHmacSha384 = &SigningMethodHMAC{"hmac-sha384", crypto.SHA384}
	SigningMethodHmacSha512 = &SigningMethodHMAC{"hmac-sha512", crypto.SHA512}
)

Specific instances for hmac shaXXX

View Source
var (
	SigningMethodRsaSha256 = &SigningMethodRSA{"rsa-sha256", crypto.SHA256}
	SigningMethodRsaSha384 = &SigningMethodRSA{"rsa-sha384", crypto.SHA256}
	SigningMethodRsaSha512 = &SigningMethodRSA{"rsa-sha512", crypto.SHA512}
)

Specific instances for rsa shaXXX

View Source
var (
	SigningMethodRsaPssSha256 = &SigningMethodRSAPSS{
		SigningMethodRSA: &SigningMethodRSA{
			Name: "rsa-pss-sha256",
			Hash: crypto.SHA256,
		},
		Options: &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthEqualsHash,
		},
		VerifyOptions: &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthAuto,
		},
	}
	SigningMethodRsaPssSha384 = &SigningMethodRSAPSS{
		SigningMethodRSA: &SigningMethodRSA{
			Name: "rsa-pss-sha384",
			Hash: crypto.SHA384,
		},
		Options: &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthEqualsHash,
		},
		VerifyOptions: &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthAuto,
		},
	}
	SigningMethodRsaPssSha512 = &SigningMethodRSAPSS{
		SigningMethodRSA: &SigningMethodRSA{
			Name: "rsa-pss-sha512",
			Hash: crypto.SHA512,
		},
		Options: &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthEqualsHash,
		},
		VerifyOptions: &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthAuto,
		},
	}
)

Specific instances for RS/PS and company.

View Source
var (
	ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key")
	ErrNotRSAPrivateKey    = errors.New("key is not a valid RSA private key")
	ErrNotRSAPublicKey     = errors.New("key is not a valid RSA public key")
)
View Source
var SigningMethodEdDSA = &SigningMethodEd25519{}

Specific instance for EdDSA

Functions

func ConstructSignMessageFromRequest

func ConstructSignMessageFromRequest(r *http.Request, p *Parameter) string

func ParseECPrivateKeyFromPEM

func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error)

ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure

func ParseECPublicKeyFromPEM

func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error)

ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key

func ParseEdPrivateKeyFromPEM

func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error)

ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key

func ParseEdPublicKeyFromPEM

func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error)

ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key

func ParseRSAPrivateKeyFromPEM

func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)

ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key

func ParseRSAPrivateKeyFromPEMWithPassword deprecated

func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error)

ParseRSAPrivateKeyFromPEMWithPassword parses a PEM encoded PKCS1 or PKCS8 private key protected with password

Deprecated: This function is deprecated and should not be used anymore. It uses the deprecated x509.DecryptPEMBlock function, which was deprecated since RFC 1423 is regarded insecure by design. Unfortunately, there is no alternative in the Go standard library for now. See https://github.com/golang/go/issues/8860.

func ParseRSAPublicKeyFromPEM

func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)

ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key

Types

type AuthorizationSignatureExtractor

type AuthorizationSignatureExtractor string

AuthorizationSignatureExtractor is an extractor for finding a signature in a header, which the value has prefix `Signature `

func NewAuthorizationSignatureExtractor

func NewAuthorizationSignatureExtractor(h string) AuthorizationSignatureExtractor

NewAuthorizationSignatureExtractor new a signature extractor instance.

func (AuthorizationSignatureExtractor) Extract

type CreatedValidator

type CreatedValidator struct {
	// Gap is max time different between client submit timestamp
	// and server time that considered valid. The time precision is seconds.
	Gap time.Duration
}

CreatedValidator checking validate created range

func NewCreatedValidator

func NewCreatedValidator() *CreatedValidator

NewCreatedValidator return CreatedValidator with default value (30 second)

func (*CreatedValidator) Validate

func (v *CreatedValidator) Validate(r *http.Request, p *Parameter) error

Validate return error when checking if header date is valid or not

type DateValidator

type DateValidator struct {
	// Gap is max time different between client submit timestamp
	// and server time that considered valid. The time precision is millisecond.
	Gap time.Duration
}

DateValidator checking validate by time range

func NewDateValidator

func NewDateValidator() *DateValidator

NewDateValidator return DateValidator with default value (30 second)

func (*DateValidator) Validate

func (v *DateValidator) Validate(r *http.Request, _ *Parameter) error

Validate return error when checking if header date is valid or not

type DigestUsingShared

type DigestUsingShared struct {
	// contains filtered or unexported fields
}

func NewDigestUsingShared

func NewDigestUsingShared(signingMethod SigningMethod) *DigestUsingShared

func (*DigestUsingShared) Sign

func (m *DigestUsingShared) Sign(signingBytes []byte, key any) (string, error)

func (*DigestUsingShared) Verify

func (m *DigestUsingShared) Verify(signingBytes []byte, digestString string, key any) error

type DigestUsingSharedValidator

type DigestUsingSharedValidator struct{}

func NewDigestUsingSharedValidator

func NewDigestUsingSharedValidator() *DigestUsingSharedValidator

NewDigestValidator return pointer of new DigestValidator

func (*DigestUsingSharedValidator) Validate

Validate return error when checking digest match body

type DigestValidator

type DigestValidator struct {
	// contains filtered or unexported fields
}

DigestValidator checking digest in header match body

func NewDigestValidator

func NewDigestValidator(digest digest.Digest) *DigestValidator

NewDigestValidator return pointer of new DigestValidator

func (*DigestValidator) Validate

func (v *DigestValidator) Validate(r *http.Request, _ *Parameter) error

Validate return error when checking digest match body

type ExpiresValidator

type ExpiresValidator struct {
	// Gap is max time different between client submit timestamp
	// and server time that considered valid. The time precision is second.
	Gap time.Duration
}

ExpiresValidator checking validate expires.

func NewExpiresValidator

func NewExpiresValidator() *ExpiresValidator

NewCreatedValidator return ExpiresValidator with default value (30 second)

func (*ExpiresValidator) Validate

func (v *ExpiresValidator) Validate(r *http.Request, p *Parameter) error

Validate return error when checking if header `expires` is valid or not

type Extractor

type Extractor interface {
	Extract(*http.Request) (string, Scheme, error)
}

Extractor is an interface for extracting a signature from a HTTP request. The Extract method should return a signature string, Scheme or an error. If no signature is present, you must return ErrNoSignatureInRequest.

type KeyId

type KeyId string

KeyId define type

type Keystone

type Keystone interface {
	// AddMetadata add metadata
	AddMetadata(KeyId, Metadata) error
	// DeleteMetadata delete metadata
	DeleteMetadata(KeyId) error
	// GetMetadata get metadata
	GetMetadata(KeyId) (Metadata, error)
}

Keystone keyId mapping Metadata manager. Concurrently need to be supported.

type KeystoneMemory

type KeystoneMemory struct {
	// contains filtered or unexported fields
}

KeystoneMemory memory keystone

func NewKeystoneMemory

func NewKeystoneMemory() *KeystoneMemory

NewKeystoneMemory new memory keystone

func (*KeystoneMemory) AddMetadata

func (k *KeystoneMemory) AddMetadata(keyId KeyId, md Metadata) error

AddMetadata implements Keystone.

func (*KeystoneMemory) DeleteMetadata

func (k *KeystoneMemory) DeleteMetadata(keyId KeyId) error

DeleteMetadata implements Keystone.

func (*KeystoneMemory) GetMetadata

func (k *KeystoneMemory) GetMetadata(keyId KeyId) (Metadata, error)

GetMetadata implements Keystone.

type Metadata

type Metadata struct {
	Scheme Scheme
	Alg    string
	Key    any
}

Metadata define key and algorithm that keyId use.

type MultiExtractor

type MultiExtractor []Extractor

MultiExtractor tries Extractors in order until one returns a signature string or an error occurs.

func NewMultiExtractor

func NewMultiExtractor(es ...Extractor) MultiExtractor

NewMultiExtractor new multiple extractor instance.

func (MultiExtractor) Extract

func (e MultiExtractor) Extract(r *http.Request) (string, Scheme, error)

type Parameter

type Parameter struct {
	// REQUIRED. The `keyId` field is an opaque string that the server can
	// use to look up the component they need to validate the signature.
	KeyId KeyId
	// REQUIRED. The `signature` parameter is a base 64 encoded digital signature.
	Signature string
	// RECOMMENDED. The `algorithm` parameter is used to specify the
	// signature string construction mechanism.
	Algorithm string
	// RECOMMENDED. The `created` field expresses when the signature was created.
	// The value MUST be a Unix timestamp integer value.
	Created int64
	// OPTIONAL. The `expires` field expresses when the signature ceases to
	// be valid. The value MUST be a Unix timestamp integer value.
	Expires int64
	// OPTIONAL. The `headers` parameter is used to specify the list of
	// HTTP headers included when generating the signature for the message.
	Headers []string

	// scheme support
	Scheme Scheme
	// signing method
	Method SigningMethod
	// signing method key.
	Key any
	// contains filtered or unexported fields
}

Parameter contains basic info signature parameters.

func (*Parameter) ContainsHeader

func (p *Parameter) ContainsHeader(header string) bool

ContainsHeader returns true if headers contains header. NOTE: init inner headerMap use header when first called this function.

func (*Parameter) MergerHeader

func (p *Parameter) MergerHeader(r *http.Request) error

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser definition how to parse from http request.

func NewParser

func NewParser(opts ...ParserOption) *Parser

NewParser new parser instance. default value see Parser struct definition.

func (*Parser) AddMetadata

func (p *Parser) AddMetadata(keyId KeyId, md Metadata) error

AddMetadata add keyId metadata.

func (*Parser) DeleteMetadata

func (p *Parser) DeleteMetadata(keyId KeyId) error

DeleteMetadata delete the keyId metadata.

func (*Parser) GetMetadata

func (p *Parser) GetMetadata(keyId KeyId) (Metadata, error)

GetMetadata returns the keyId metadata.

func (*Parser) GetSigningMethod

func (p *Parser) GetSigningMethod(alg string) (method SigningMethod)

GetSigningMethod retrieves a signing method from an "alg" string. Returns nil if alg not found.

func (*Parser) GetSigningMethodAlgorithms

func (p *Parser) GetSigningMethodAlgorithms() []string

GetSigningMethodAlgorithms returns a list of add "alg" names

func (*Parser) ParseFromRequest

func (p *Parser) ParseFromRequest(r *http.Request) (*Parameter, error)

func (*Parser) ParseVerify

func (p *Parser) ParseVerify(r *http.Request) (Scheme, error)

ParseVerify parse from http request, and then validate all parameters.

func (*Parser) RegisterSigningMethod

func (p *Parser) RegisterSigningMethod(alg string, f func() SigningMethod) *Parser

RegisterSigningMethod registers the "alg" name and a factory function for signing method.

func (*Parser) Verify

func (p *Parser) Verify(r *http.Request, param *Parameter) error

Verify Parameter. return nil, if successful. then it will set Parameter signing Method and signing Method Key.

type ParserOption

type ParserOption func(*Parser)

func WithExtractor

func WithExtractor(e Extractor) ParserOption

func WithKeystone

func WithKeystone(ks Keystone) ParserOption

func WithMinimumRequiredHeaders

func WithMinimumRequiredHeaders(headers []string) ParserOption

func WithSigningMethods

func WithSigningMethods(alg string, f func() SigningMethod) ParserOption

func WithValidators

func WithValidators(vs ...Validator) ParserOption

type Scheme

type Scheme int

Scheme support Signature or Authorization

type SignatureExtractor

type SignatureExtractor string

SignatureExtractor is an extractor for finding a signature in a header.

func NewSignatureExtractor

func NewSignatureExtractor(h string) SignatureExtractor

NewSignatureExtractor new a signature extractor instance.

func (SignatureExtractor) Extract

func (h SignatureExtractor) Extract(r *http.Request) (string, Scheme, error)

type SigningMethod

type SigningMethod interface {
	// returns the alg identifier for this method.
	Alg() string
	// Returns nil if signature is valid
	Verify(signingBytes []byte, sig []byte, key any) error
	// Returns signature or error
	Sign(signingBytes []byte, key any) ([]byte, error)
}

SigningMethod can be used add new methods for signing or verifying signature. It takes a decoded signature as an input in the Verify function and produces a signature in Sign. The signature is then usually base64 encoded as part of a Signature.

type SigningMethodECDSA

type SigningMethodECDSA struct {
	Name      string
	Hash      crypto.Hash
	KeySize   int
	CurveBits int
}

SigningMethodECDSA implements the ECDSA family of signing methods. Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification

func (*SigningMethodECDSA) Alg

func (m *SigningMethodECDSA) Alg() string

func (*SigningMethodECDSA) Sign

func (m *SigningMethodECDSA) Sign(signingBytes []byte, key any) ([]byte, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an ecdsa.PrivateKey struct

func (*SigningMethodECDSA) Verify

func (m *SigningMethodECDSA) Verify(signingBytes, sig []byte, key any) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an ecdsa.PublicKey struct

type SigningMethodEd25519

type SigningMethodEd25519 struct{}

SigningMethodEd25519 implements the EdDSA family. Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification

func (*SigningMethodEd25519) Alg

func (m *SigningMethodEd25519) Alg() string

func (*SigningMethodEd25519) Sign

func (m *SigningMethodEd25519) Sign(signingBytes []byte, key any) ([]byte, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an ed25519.PrivateKey

func (*SigningMethodEd25519) Verify

func (m *SigningMethodEd25519) Verify(signingBytes, sig []byte, key any) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an ed25519.PublicKey

type SigningMethodHMAC

type SigningMethodHMAC struct {
	Name string
	Hash crypto.Hash
}

SigningMethodHMAC implements the HMAC-SHA family of signing methods. Expects key type of []byte for both signing and validation

func (*SigningMethodHMAC) Alg

func (m *SigningMethodHMAC) Alg() string

func (*SigningMethodHMAC) Sign

func (m *SigningMethodHMAC) Sign(signingBytes []byte, key any) ([]byte, error)

Sign implements signing for the SigningMethod. Key must be []byte.

func (*SigningMethodHMAC) Verify

func (m *SigningMethodHMAC) Verify(signingBytes, sig []byte, key any) error

Verify implements verification for the SigningMethod. Returns nil if the signature is valid. Key must be []byte.

type SigningMethodRSA

type SigningMethodRSA struct {
	Name string
	Hash crypto.Hash
}

SigningMethodRSA implements the RSA family of signing methods. Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation

func (*SigningMethodRSA) Alg

func (m *SigningMethodRSA) Alg() string

func (*SigningMethodRSA) Sign

func (m *SigningMethodRSA) Sign(signingBytes []byte, key any) ([]byte, error)

Sign implements token signing for the SigningMethod For this signing method, must be an *rsa.PrivateKey structure.

func (*SigningMethodRSA) Verify

func (m *SigningMethodRSA) Verify(signingBytes, sig []byte, key any) error

Verify implements token verification for the SigningMethod For this signing method, must be an *rsa.PublicKey structure.

type SigningMethodRSAPSS

type SigningMethodRSAPSS struct {
	*SigningMethodRSA
	Options *rsa.PSSOptions
	// VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS.
	// Used to accept tokens signed with rsa.PSSSaltLengthAuto.
	VerifyOptions *rsa.PSSOptions
}

SigningMethodRSAPSS implements the rsa pss shaXXX family of signing methods signing methods

func (*SigningMethodRSAPSS) Sign

func (m *SigningMethodRSAPSS) Sign(signingBytes []byte, key any) ([]byte, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an rsa.PrivateKey struct

func (*SigningMethodRSAPSS) Verify

func (m *SigningMethodRSAPSS) Verify(signingBytes, sig []byte, key any) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an rsa.PublicKey struct

type Validator

type Validator interface {
	Validate(*http.Request, *Parameter) error
}

Validator interface for checking if a request is valid or not

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL