refactor: move the transport onto the official Gitea SDK
The transport was hand-rolled net/http against the REST API. The payload shapes were ours, in internal/wire, which meant every field Gitea learned was a field somebody here had to notice; and "does this instance have issue dependencies?" had to be guessed from a status code, because a 404 from a missing route and a 404 from a missing issue look alike. The SDK settles both. The shapes are maintained by the people who maintain the server, and the client negotiates the server's version when it is built, so the dependency endpoint is now gated on `>= 1.20.0` — verified against the release where the route appears, not assumed. Below the gate nothing is requested at all. internal/wire keeps what the SDK has no answer for: addressing. The SDK takes an owner, a name and an int64 and never parses, while `42`, `#42`, `owner/repo#42` and an issue URL are four spellings of one address, all four are what somebody has in hand, and Key is what the ledger is keyed by. The payload structs go. Four things that had to survive the move, and did: - request bodies still land in .kettle/payload/, now via an http.RoundTripper on the client the SDK is given — which is better than before, because it files every request rather than the ones a call site remembered to name; - errors still carry the HTTP status AND the response body, and a decode failure on a 2xx is deliberately not an APIError, so the dependency probe cannot read a bad decode as "feature missing"; - the number -> slug ledger is untouched, entries still outlive the files they name; - Client.For(repo) still re-points at another repository for one call. What it cost, written down in AGENTS.md where it happened. internal/mapping's layering test was a fact about the import graph — nothing in its closure could open a socket — and the SDK ships its types and its client in one package, so the test now asserts what is still true: the bridge performs no I/O, checked on direct imports plus a grep for time.Now. A run makes one extra request before it does anything. Gitea's issue edit endpoint carries no labels, so a push whose labels changed needs a second call; push makes it and says so. go.mod requires go 1.26, which the SDK sets and which is now the floor for building this binary. internal/issue and internal/project are byte-identical. The domain did not notice, which is the whole argument for the layering. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
+3
@@ -0,0 +1,3 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.15
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2018, go-fed
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
# httpsig
|
||||
|
||||
Forked from <https://github.com/go-fed/httpsig>
|
||||
|
||||
> HTTP Signatures made simple
|
||||
|
||||
[![Build Status][Build-Status-Image]][Build-Status-Url] [![Go Reference][Go-Reference-Image]][Go-Reference-Url]
|
||||
[![Go Report Card][Go-Report-Card-Image]][Go-Report-Card-Url] [![License][License-Image]][License-Url]
|
||||
[![Chat][Chat-Image]][Chat-Url] [![OpenCollective][OpenCollective-Image]][OpenCollective-Url]
|
||||
|
||||
`go get github.com/42wim/httpsig`
|
||||
|
||||
Implementation of [HTTP Signatures](https://tools.ietf.org/html/draft-cavage-http-signatures).
|
||||
|
||||
Supports many different combinations of MAC, HMAC signing of hash, or RSA
|
||||
signing of hash schemes. Its goals are:
|
||||
|
||||
* Have a very simple interface for signing and validating
|
||||
* Support a variety of signing algorithms and combinations
|
||||
* Support setting either headers (`Authorization` or `Signature`)
|
||||
* Remaining flexible with headers included in the signing string
|
||||
* Support both HTTP requests and responses
|
||||
* Explicitly not support known-cryptographically weak algorithms
|
||||
* Support automatic signing and validating Digest headers
|
||||
|
||||
## How to use
|
||||
|
||||
`import "github.com/42wim/httpsig"`
|
||||
|
||||
### Signing
|
||||
|
||||
Signing a request or response requires creating a new `Signer` and using it:
|
||||
|
||||
```
|
||||
func sign(privateKey crypto.PrivateKey, pubKeyId string, r *http.Request) error {
|
||||
prefs := []httpsig.Algorithm{httpsig.RSA_SHA512, httpsig.RSA_SHA256}
|
||||
digestAlgorithm := DigestSha256
|
||||
// The "Date" and "Digest" headers must already be set on r, as well as r.URL.
|
||||
headersToSign := []string{httpsig.RequestTarget, "date", "digest"}
|
||||
signer, chosenAlgo, err := httpsig.NewSigner(prefs, digestAlgorithm, headersToSign, httpsig.Signature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// To sign the digest, we need to give the signer a copy of the body...
|
||||
// ...but it is optional, no digest will be signed if given "nil"
|
||||
body := ...
|
||||
// If r were a http.ResponseWriter, call SignResponse instead.
|
||||
return signer.SignRequest(privateKey, pubKeyId, r, body)
|
||||
}
|
||||
```
|
||||
|
||||
`Signer`s are not safe for concurrent use by goroutines, so be sure to guard
|
||||
access:
|
||||
|
||||
```
|
||||
type server struct {
|
||||
signer httpsig.Signer
|
||||
mu *sync.Mutex
|
||||
}
|
||||
|
||||
func (s *server) handlerFunc(w http.ResponseWriter, r *http.Request) {
|
||||
privateKey := ...
|
||||
pubKeyId := ...
|
||||
// Set headers and such on w
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
// To sign the digest, we need to give the signer a copy of the response body...
|
||||
// ...but it is optional, no digest will be signed if given "nil"
|
||||
body := ...
|
||||
err := s.signer.SignResponse(privateKey, pubKeyId, w, body)
|
||||
if err != nil {
|
||||
...
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
The `pubKeyId` will be used at verification time.
|
||||
|
||||
### Verifying
|
||||
|
||||
Verifying requires an application to use the `pubKeyId` to both retrieve the key
|
||||
needed for verification as well as determine the algorithm to use. Use a
|
||||
`Verifier`:
|
||||
|
||||
```
|
||||
func verify(r *http.Request) error {
|
||||
verifier, err := httpsig.NewVerifier(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pubKeyId := verifier.KeyId()
|
||||
var algo httpsig.Algorithm = ...
|
||||
var pubKey crypto.PublicKey = ...
|
||||
// The verifier will verify the Digest in addition to the HTTP signature
|
||||
return verifier.Verify(pubKey, algo)
|
||||
}
|
||||
```
|
||||
|
||||
`Verifier`s are not safe for concurrent use by goroutines, but since they are
|
||||
constructed on a per-request or per-response basis it should not be a common
|
||||
restriction.
|
||||
|
||||
[Build-Status-Image]: https://travis-ci.org/42wim/httpsig.svg?branch=master
|
||||
[Build-Status-Url]: https://travis-ci.org/42wim/httpsig
|
||||
[Go-Reference-Image]: https://pkg.go.dev/badge/github.com/42wim/httpsig
|
||||
[Go-Reference-Url]: https://pkg.go.dev/github.com/42wim/httpsig
|
||||
[Go-Report-Card-Image]: https://goreportcard.com/badge/github.com/42wim/httpsig
|
||||
[Go-Report-Card-Url]: https://goreportcard.com/report/github.com/42wim/httpsig
|
||||
[License-Image]: https://img.shields.io/github/license/42wim/httpsig?color=blue
|
||||
[License-Url]: https://opensource.org/licenses/BSD-3-Clause
|
||||
[Chat-Image]: https://img.shields.io/matrix/42wim:feneas.org?server_fqdn=matrix.org
|
||||
[Chat-Url]: https://matrix.to/#/!BLOSvIyKTDLIVjRKSc:feneas.org?via=feneas.org&via=matrix.org
|
||||
[OpenCollective-Image]: https://img.shields.io/opencollective/backers/42wim-activitypub-labs
|
||||
[OpenCollective-Url]: https://opencollective.com/42wim-activitypub-labs
|
||||
+550
@@ -0,0 +1,550 @@
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/hmac"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"crypto/subtle" // Use should trigger great care
|
||||
"encoding/asn1"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/blake2b"
|
||||
"golang.org/x/crypto/blake2s"
|
||||
"golang.org/x/crypto/ed25519"
|
||||
"golang.org/x/crypto/sha3"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
const (
|
||||
hmacPrefix = "hmac"
|
||||
rsaPrefix = "rsa"
|
||||
sshPrefix = "ssh"
|
||||
ecdsaPrefix = "ecdsa"
|
||||
ed25519Prefix = "ed25519"
|
||||
sha224String = "sha224"
|
||||
sha256String = "sha256"
|
||||
sha384String = "sha384"
|
||||
sha512String = "sha512"
|
||||
sha3_224String = "sha3-224"
|
||||
sha3_256String = "sha3-256"
|
||||
sha3_384String = "sha3-384"
|
||||
sha3_512String = "sha3-512"
|
||||
sha512_224String = "sha512-224"
|
||||
sha512_256String = "sha512-256"
|
||||
blake2s_256String = "blake2s-256"
|
||||
blake2b_256String = "blake2b-256"
|
||||
blake2b_384String = "blake2b-384"
|
||||
blake2b_512String = "blake2b-512"
|
||||
)
|
||||
|
||||
var blake2Algorithms = map[crypto.Hash]bool{
|
||||
crypto.BLAKE2s_256: true,
|
||||
crypto.BLAKE2b_256: true,
|
||||
crypto.BLAKE2b_384: true,
|
||||
crypto.BLAKE2b_512: true,
|
||||
}
|
||||
|
||||
var hashToDef = map[crypto.Hash]struct {
|
||||
name string
|
||||
new func(key []byte) (hash.Hash, error) // Only MACers will accept a key
|
||||
}{
|
||||
// Which standard names these?
|
||||
// The spec lists the following as a canonical reference, which is dead:
|
||||
// http://www.iana.org/assignments/signature-algorithms
|
||||
//
|
||||
// Note that the forbidden hashes have an invalid 'new' function.
|
||||
crypto.SHA224: {sha224String, func(key []byte) (hash.Hash, error) { return sha256.New224(), nil }},
|
||||
crypto.SHA256: {sha256String, func(key []byte) (hash.Hash, error) { return sha256.New(), nil }},
|
||||
crypto.SHA384: {sha384String, func(key []byte) (hash.Hash, error) { return sha512.New384(), nil }},
|
||||
crypto.SHA512: {sha512String, func(key []byte) (hash.Hash, error) { return sha512.New(), nil }},
|
||||
crypto.SHA3_224: {sha3_224String, func(key []byte) (hash.Hash, error) { return sha3.New224(), nil }},
|
||||
crypto.SHA3_256: {sha3_256String, func(key []byte) (hash.Hash, error) { return sha3.New256(), nil }},
|
||||
crypto.SHA3_384: {sha3_384String, func(key []byte) (hash.Hash, error) { return sha3.New384(), nil }},
|
||||
crypto.SHA3_512: {sha3_512String, func(key []byte) (hash.Hash, error) { return sha3.New512(), nil }},
|
||||
crypto.SHA512_224: {sha512_224String, func(key []byte) (hash.Hash, error) { return sha512.New512_224(), nil }},
|
||||
crypto.SHA512_256: {sha512_256String, func(key []byte) (hash.Hash, error) { return sha512.New512_256(), nil }},
|
||||
crypto.BLAKE2s_256: {blake2s_256String, func(key []byte) (hash.Hash, error) { return blake2s.New256(key) }},
|
||||
crypto.BLAKE2b_256: {blake2b_256String, func(key []byte) (hash.Hash, error) { return blake2b.New256(key) }},
|
||||
crypto.BLAKE2b_384: {blake2b_384String, func(key []byte) (hash.Hash, error) { return blake2b.New384(key) }},
|
||||
crypto.BLAKE2b_512: {blake2b_512String, func(key []byte) (hash.Hash, error) { return blake2b.New512(key) }},
|
||||
}
|
||||
|
||||
var stringToHash map[string]crypto.Hash
|
||||
|
||||
const (
|
||||
defaultAlgorithm = RSA_SHA256
|
||||
defaultAlgorithmHashing = sha256String
|
||||
)
|
||||
|
||||
func init() {
|
||||
stringToHash = make(map[string]crypto.Hash, len(hashToDef))
|
||||
for k, v := range hashToDef {
|
||||
stringToHash[v.name] = k
|
||||
}
|
||||
// This should guarantee that at runtime the defaultAlgorithm will not
|
||||
// result in errors when fetching a macer or signer (see algorithms.go)
|
||||
if ok, err := isAvailable(string(defaultAlgorithmHashing)); err != nil {
|
||||
panic(err)
|
||||
} else if !ok {
|
||||
panic(fmt.Sprintf("the default httpsig algorithm is unavailable: %q", defaultAlgorithm))
|
||||
}
|
||||
}
|
||||
|
||||
func isForbiddenHash(h crypto.Hash) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// signer is an internally public type.
|
||||
type signer interface {
|
||||
Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error)
|
||||
Verify(pub crypto.PublicKey, toHash, signature []byte) error
|
||||
String() string
|
||||
}
|
||||
|
||||
// macer is an internally public type.
|
||||
type macer interface {
|
||||
Sign(sig, key []byte) ([]byte, error)
|
||||
Equal(sig, actualMAC, key []byte) (bool, error)
|
||||
String() string
|
||||
}
|
||||
|
||||
var _ macer = &hmacAlgorithm{}
|
||||
|
||||
type hmacAlgorithm struct {
|
||||
fn func(key []byte) (hash.Hash, error)
|
||||
kind crypto.Hash
|
||||
}
|
||||
|
||||
func (h *hmacAlgorithm) Sign(sig, key []byte) ([]byte, error) {
|
||||
hs, err := h.fn(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = setSig(hs, sig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hs.Sum(nil), nil
|
||||
}
|
||||
|
||||
func (h *hmacAlgorithm) Equal(sig, actualMAC, key []byte) (bool, error) {
|
||||
hs, err := h.fn(key)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer hs.Reset()
|
||||
err = setSig(hs, sig)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
expected := hs.Sum(nil)
|
||||
return hmac.Equal(actualMAC, expected), nil
|
||||
}
|
||||
|
||||
func (h *hmacAlgorithm) String() string {
|
||||
return fmt.Sprintf("%s-%s", hmacPrefix, hashToDef[h.kind].name)
|
||||
}
|
||||
|
||||
var _ signer = &rsaAlgorithm{}
|
||||
|
||||
type rsaAlgorithm struct {
|
||||
hash.Hash
|
||||
kind crypto.Hash
|
||||
sshSigner ssh.Signer
|
||||
}
|
||||
|
||||
func (r *rsaAlgorithm) setSig(b []byte) error {
|
||||
n, err := r.Write(b)
|
||||
if err != nil {
|
||||
r.Reset()
|
||||
return err
|
||||
} else if n != len(b) {
|
||||
r.Reset()
|
||||
return fmt.Errorf("could only write %d of %d bytes of signature to hash", n, len(b))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Code from https://github.com/cloudtools/ssh-cert-authority/pull/49/files
|
||||
// This interface provides a way to reach the exported, but not accessible SignWithOpts() method
|
||||
// in x/crypto/ssh/agent. Access to this is needed to sign with more secure signing algorithms
|
||||
type agentKeyringSigner interface {
|
||||
SignWithOpts(rand io.Reader, data []byte, opts crypto.SignerOpts) (*ssh.Signature, error)
|
||||
}
|
||||
|
||||
// A struct to wrap an SSH Signer with one that will switch to SHA256 Signatures.
|
||||
// Replaces the call to Sign() with a call to SignWithOpts using HashFunc() algorithm.
|
||||
type Sha256Signer struct {
|
||||
ssh.Signer
|
||||
}
|
||||
|
||||
func (s Sha256Signer) HashFunc() crypto.Hash {
|
||||
return crypto.SHA256
|
||||
}
|
||||
|
||||
func (s Sha256Signer) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
|
||||
if aks, ok := s.Signer.(agentKeyringSigner); !ok {
|
||||
return nil, fmt.Errorf("ssh: can't wrap a non ssh agentKeyringSigner")
|
||||
} else {
|
||||
return aks.SignWithOpts(rand, data, s)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *rsaAlgorithm) Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error) {
|
||||
if r.sshSigner != nil {
|
||||
var (
|
||||
sshsig *ssh.Signature
|
||||
err error
|
||||
)
|
||||
// are we using an SSH Agent
|
||||
if _, ok := r.sshSigner.(agentKeyringSigner); ok {
|
||||
signer := Sha256Signer{r.sshSigner}
|
||||
sshsig, err = signer.Sign(rand, sig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
sshsig, err = r.sshSigner.(ssh.AlgorithmSigner).SignWithAlgorithm(rand, sig, ssh.SigAlgoRSASHA2256)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return sshsig.Blob, nil
|
||||
}
|
||||
defer r.Reset()
|
||||
|
||||
if err := r.setSig(sig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rsaK, ok := p.(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, errors.New("crypto.PrivateKey is not *rsa.PrivateKey")
|
||||
}
|
||||
return rsa.SignPKCS1v15(rand, rsaK, r.kind, r.Sum(nil))
|
||||
}
|
||||
|
||||
func (r *rsaAlgorithm) Verify(pub crypto.PublicKey, toHash, signature []byte) error {
|
||||
defer r.Reset()
|
||||
rsaK, ok := pub.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return errors.New("crypto.PublicKey is not *rsa.PublicKey")
|
||||
}
|
||||
if err := r.setSig(toHash); err != nil {
|
||||
return err
|
||||
}
|
||||
return rsa.VerifyPKCS1v15(rsaK, r.kind, r.Sum(nil), signature)
|
||||
}
|
||||
|
||||
func (r *rsaAlgorithm) String() string {
|
||||
return fmt.Sprintf("%s-%s", rsaPrefix, hashToDef[r.kind].name)
|
||||
}
|
||||
|
||||
var _ signer = &ed25519Algorithm{}
|
||||
|
||||
type ed25519Algorithm struct {
|
||||
sshSigner ssh.Signer
|
||||
}
|
||||
|
||||
func (r *ed25519Algorithm) Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error) {
|
||||
if r.sshSigner != nil {
|
||||
sshsig, err := r.sshSigner.Sign(rand, sig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return sshsig.Blob, nil
|
||||
}
|
||||
ed25519K, ok := p.(ed25519.PrivateKey)
|
||||
if !ok {
|
||||
return nil, errors.New("crypto.PrivateKey is not ed25519.PrivateKey")
|
||||
}
|
||||
return ed25519.Sign(ed25519K, sig), nil
|
||||
}
|
||||
|
||||
func (r *ed25519Algorithm) Verify(pub crypto.PublicKey, toHash, signature []byte) error {
|
||||
ed25519K, ok := pub.(ed25519.PublicKey)
|
||||
if !ok {
|
||||
return errors.New("crypto.PublicKey is not ed25519.PublicKey")
|
||||
}
|
||||
|
||||
if ed25519.Verify(ed25519K, toHash, signature) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("ed25519 verify failed")
|
||||
}
|
||||
|
||||
func (r *ed25519Algorithm) String() string {
|
||||
return fmt.Sprintf("%s", ed25519Prefix)
|
||||
}
|
||||
|
||||
var _ signer = &ecdsaAlgorithm{}
|
||||
|
||||
type ecdsaAlgorithm struct {
|
||||
hash.Hash
|
||||
kind crypto.Hash
|
||||
}
|
||||
|
||||
func (r *ecdsaAlgorithm) setSig(b []byte) error {
|
||||
n, err := r.Write(b)
|
||||
if err != nil {
|
||||
r.Reset()
|
||||
return err
|
||||
} else if n != len(b) {
|
||||
r.Reset()
|
||||
return fmt.Errorf("could only write %d of %d bytes of signature to hash", n, len(b))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type ECDSASignature struct {
|
||||
R, S *big.Int
|
||||
}
|
||||
|
||||
func (r *ecdsaAlgorithm) Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error) {
|
||||
defer r.Reset()
|
||||
if err := r.setSig(sig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ecdsaK, ok := p.(*ecdsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, errors.New("crypto.PrivateKey is not *ecdsa.PrivateKey")
|
||||
}
|
||||
R, S, err := ecdsa.Sign(rand, ecdsaK, r.Sum(nil))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature := ECDSASignature{R: R, S: S}
|
||||
bytes, err := asn1.Marshal(signature)
|
||||
|
||||
return bytes, err
|
||||
}
|
||||
|
||||
func (r *ecdsaAlgorithm) Verify(pub crypto.PublicKey, toHash, signature []byte) error {
|
||||
defer r.Reset()
|
||||
ecdsaK, ok := pub.(*ecdsa.PublicKey)
|
||||
if !ok {
|
||||
return errors.New("crypto.PublicKey is not *ecdsa.PublicKey")
|
||||
}
|
||||
if err := r.setSig(toHash); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sig := new(ECDSASignature)
|
||||
_, err := asn1.Unmarshal(signature, sig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ecdsa.Verify(ecdsaK, r.Sum(nil), sig.R, sig.S) {
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("Invalid signature")
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ecdsaAlgorithm) String() string {
|
||||
return fmt.Sprintf("%s-%s", ecdsaPrefix, hashToDef[r.kind].name)
|
||||
}
|
||||
|
||||
var _ macer = &blakeMacAlgorithm{}
|
||||
|
||||
type blakeMacAlgorithm struct {
|
||||
fn func(key []byte) (hash.Hash, error)
|
||||
kind crypto.Hash
|
||||
}
|
||||
|
||||
func (r *blakeMacAlgorithm) Sign(sig, key []byte) ([]byte, error) {
|
||||
hs, err := r.fn(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = setSig(hs, sig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hs.Sum(nil), nil
|
||||
}
|
||||
|
||||
func (r *blakeMacAlgorithm) Equal(sig, actualMAC, key []byte) (bool, error) {
|
||||
hs, err := r.fn(key)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer hs.Reset()
|
||||
err = setSig(hs, sig)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
expected := hs.Sum(nil)
|
||||
return subtle.ConstantTimeCompare(actualMAC, expected) == 1, nil
|
||||
}
|
||||
|
||||
func (r *blakeMacAlgorithm) String() string {
|
||||
return fmt.Sprintf("%s", hashToDef[r.kind].name)
|
||||
}
|
||||
|
||||
func setSig(a hash.Hash, b []byte) error {
|
||||
n, err := a.Write(b)
|
||||
if err != nil {
|
||||
a.Reset()
|
||||
return err
|
||||
} else if n != len(b) {
|
||||
a.Reset()
|
||||
return fmt.Errorf("could only write %d of %d bytes of signature to hash", n, len(b))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsSupportedHttpSigAlgorithm returns true if the string is supported by this
|
||||
// library, is not a hash known to be weak, and is supported by the hardware.
|
||||
func IsSupportedHttpSigAlgorithm(algo string) bool {
|
||||
a, err := isAvailable(algo)
|
||||
return a && err == nil
|
||||
}
|
||||
|
||||
// isAvailable is an internally public function
|
||||
func isAvailable(algo string) (bool, error) {
|
||||
c, ok := stringToHash[algo]
|
||||
if !ok {
|
||||
return false, fmt.Errorf("no match for %q", algo)
|
||||
}
|
||||
if isForbiddenHash(c) {
|
||||
return false, fmt.Errorf("forbidden hash type in %q", algo)
|
||||
}
|
||||
return c.Available(), nil
|
||||
}
|
||||
|
||||
func newAlgorithmConstructor(algo string) (fn func(k []byte) (hash.Hash, error), c crypto.Hash, e error) {
|
||||
ok := false
|
||||
c, ok = stringToHash[algo]
|
||||
if !ok {
|
||||
e = fmt.Errorf("no match for %q", algo)
|
||||
return
|
||||
}
|
||||
if isForbiddenHash(c) {
|
||||
e = fmt.Errorf("forbidden hash type in %q", algo)
|
||||
return
|
||||
}
|
||||
algoDef, ok := hashToDef[c]
|
||||
if !ok {
|
||||
e = fmt.Errorf("have crypto.Hash %v but no definition", c)
|
||||
return
|
||||
}
|
||||
fn = func(key []byte) (hash.Hash, error) {
|
||||
h, err := algoDef.new(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func newAlgorithm(algo string, key []byte) (hash.Hash, crypto.Hash, error) {
|
||||
fn, c, err := newAlgorithmConstructor(algo)
|
||||
if err != nil {
|
||||
return nil, c, err
|
||||
}
|
||||
h, err := fn(key)
|
||||
return h, c, err
|
||||
}
|
||||
|
||||
func signerFromSSHSigner(sshSigner ssh.Signer, s string) (signer, error) {
|
||||
switch {
|
||||
case strings.HasPrefix(s, rsaPrefix):
|
||||
return &rsaAlgorithm{
|
||||
sshSigner: sshSigner,
|
||||
}, nil
|
||||
case strings.HasPrefix(s, ed25519Prefix):
|
||||
return &ed25519Algorithm{
|
||||
sshSigner: sshSigner,
|
||||
}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("no signer matching %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// signerFromString is an internally public method constructor
|
||||
func signerFromString(s string) (signer, error) {
|
||||
s = strings.ToLower(s)
|
||||
isEcdsa := false
|
||||
isEd25519 := false
|
||||
var algo string = ""
|
||||
if strings.HasPrefix(s, ecdsaPrefix) {
|
||||
algo = strings.TrimPrefix(s, ecdsaPrefix+"-")
|
||||
isEcdsa = true
|
||||
} else if strings.HasPrefix(s, rsaPrefix) {
|
||||
algo = strings.TrimPrefix(s, rsaPrefix+"-")
|
||||
} else if strings.HasPrefix(s, ed25519Prefix) {
|
||||
isEd25519 = true
|
||||
algo = "sha512"
|
||||
} else {
|
||||
return nil, fmt.Errorf("no signer matching %q", s)
|
||||
}
|
||||
hash, cHash, err := newAlgorithm(algo, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isEd25519 {
|
||||
return &ed25519Algorithm{}, nil
|
||||
}
|
||||
if isEcdsa {
|
||||
return &ecdsaAlgorithm{
|
||||
Hash: hash,
|
||||
kind: cHash,
|
||||
}, nil
|
||||
}
|
||||
return &rsaAlgorithm{
|
||||
Hash: hash,
|
||||
kind: cHash,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// macerFromString is an internally public method constructor
|
||||
func macerFromString(s string) (macer, error) {
|
||||
s = strings.ToLower(s)
|
||||
if strings.HasPrefix(s, hmacPrefix) {
|
||||
algo := strings.TrimPrefix(s, hmacPrefix+"-")
|
||||
hashFn, cHash, err := newAlgorithmConstructor(algo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Ensure below does not panic
|
||||
_, err = hashFn(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &hmacAlgorithm{
|
||||
fn: func(key []byte) (hash.Hash, error) {
|
||||
return hmac.New(func() hash.Hash {
|
||||
h, e := hashFn(nil)
|
||||
if e != nil {
|
||||
panic(e)
|
||||
}
|
||||
return h
|
||||
}, key), nil
|
||||
},
|
||||
kind: cHash,
|
||||
}, nil
|
||||
} else if bl, ok := stringToHash[s]; ok && blake2Algorithms[bl] {
|
||||
hashFn, cHash, err := newAlgorithmConstructor(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &blakeMacAlgorithm{
|
||||
fn: hashFn,
|
||||
kind: cHash,
|
||||
}, nil
|
||||
} else {
|
||||
return nil, fmt.Errorf("no MACer matching %q", s)
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"hash"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type DigestAlgorithm string
|
||||
|
||||
const (
|
||||
DigestSha256 DigestAlgorithm = "SHA-256"
|
||||
DigestSha512 = "SHA-512"
|
||||
)
|
||||
|
||||
var digestToDef = map[DigestAlgorithm]crypto.Hash{
|
||||
DigestSha256: crypto.SHA256,
|
||||
DigestSha512: crypto.SHA512,
|
||||
}
|
||||
|
||||
// IsSupportedDigestAlgorithm returns true if hte string is supported by this
|
||||
// library, is not a hash known to be weak, and is supported by the hardware.
|
||||
func IsSupportedDigestAlgorithm(algo string) bool {
|
||||
uc := DigestAlgorithm(strings.ToUpper(algo))
|
||||
c, ok := digestToDef[uc]
|
||||
return ok && c.Available()
|
||||
}
|
||||
|
||||
func getHash(alg DigestAlgorithm) (h hash.Hash, toUse DigestAlgorithm, err error) {
|
||||
upper := DigestAlgorithm(strings.ToUpper(string(alg)))
|
||||
c, ok := digestToDef[upper]
|
||||
if !ok {
|
||||
err = fmt.Errorf("unknown or unsupported Digest algorithm: %s", alg)
|
||||
} else if !c.Available() {
|
||||
err = fmt.Errorf("unavailable Digest algorithm: %s", alg)
|
||||
} else {
|
||||
h = c.New()
|
||||
toUse = upper
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const (
|
||||
digestHeader = "Digest"
|
||||
digestDelim = "="
|
||||
)
|
||||
|
||||
func addDigest(r *http.Request, algo DigestAlgorithm, b []byte) (err error) {
|
||||
_, ok := r.Header[digestHeader]
|
||||
if ok {
|
||||
err = fmt.Errorf("cannot add Digest: Digest is already set")
|
||||
return
|
||||
}
|
||||
var h hash.Hash
|
||||
var a DigestAlgorithm
|
||||
h, a, err = getHash(algo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
h.Write(b)
|
||||
sum := h.Sum(nil)
|
||||
r.Header.Add(digestHeader,
|
||||
fmt.Sprintf("%s%s%s",
|
||||
a,
|
||||
digestDelim,
|
||||
base64.StdEncoding.EncodeToString(sum[:])))
|
||||
return
|
||||
}
|
||||
|
||||
func addDigestResponse(r http.ResponseWriter, algo DigestAlgorithm, b []byte) (err error) {
|
||||
_, ok := r.Header()[digestHeader]
|
||||
if ok {
|
||||
err = fmt.Errorf("cannot add Digest: Digest is already set")
|
||||
return
|
||||
}
|
||||
var h hash.Hash
|
||||
var a DigestAlgorithm
|
||||
h, a, err = getHash(algo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
h.Write(b)
|
||||
sum := h.Sum(nil)
|
||||
r.Header().Add(digestHeader,
|
||||
fmt.Sprintf("%s%s%s",
|
||||
a,
|
||||
digestDelim,
|
||||
base64.StdEncoding.EncodeToString(sum[:])))
|
||||
return
|
||||
}
|
||||
|
||||
func verifyDigest(r *http.Request, body *bytes.Buffer) (err error) {
|
||||
d := r.Header.Get(digestHeader)
|
||||
if len(d) == 0 {
|
||||
err = fmt.Errorf("cannot verify Digest: request has no Digest header")
|
||||
return
|
||||
}
|
||||
elem := strings.SplitN(d, digestDelim, 2)
|
||||
if len(elem) != 2 {
|
||||
err = fmt.Errorf("cannot verify Digest: malformed Digest: %s", d)
|
||||
return
|
||||
}
|
||||
var h hash.Hash
|
||||
h, _, err = getHash(DigestAlgorithm(elem[0]))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
h.Write(body.Bytes())
|
||||
sum := h.Sum(nil)
|
||||
encSum := base64.StdEncoding.EncodeToString(sum[:])
|
||||
if encSum != elem[1] {
|
||||
err = fmt.Errorf("cannot verify Digest: header Digest does not match the digest of the request body")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
// Implements HTTP request and response signing and verification. Supports the
|
||||
// major MAC and asymmetric key signature algorithms. It has several safety
|
||||
// restrictions: One, none of the widely known non-cryptographically safe
|
||||
// algorithms are permitted; Two, the RSA SHA256 algorithms must be available in
|
||||
// the binary (and it should, barring export restrictions); Finally, the library
|
||||
// assumes either the 'Authorizationn' or 'Signature' headers are to be set (but
|
||||
// not both).
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// Algorithm specifies a cryptography secure algorithm for signing HTTP requests
|
||||
// and responses.
|
||||
type Algorithm string
|
||||
|
||||
const (
|
||||
// MAC-based algoirthms.
|
||||
HMAC_SHA224 Algorithm = hmacPrefix + "-" + sha224String
|
||||
HMAC_SHA256 Algorithm = hmacPrefix + "-" + sha256String
|
||||
HMAC_SHA384 Algorithm = hmacPrefix + "-" + sha384String
|
||||
HMAC_SHA512 Algorithm = hmacPrefix + "-" + sha512String
|
||||
HMAC_SHA3_224 Algorithm = hmacPrefix + "-" + sha3_224String
|
||||
HMAC_SHA3_256 Algorithm = hmacPrefix + "-" + sha3_256String
|
||||
HMAC_SHA3_384 Algorithm = hmacPrefix + "-" + sha3_384String
|
||||
HMAC_SHA3_512 Algorithm = hmacPrefix + "-" + sha3_512String
|
||||
HMAC_SHA512_224 Algorithm = hmacPrefix + "-" + sha512_224String
|
||||
HMAC_SHA512_256 Algorithm = hmacPrefix + "-" + sha512_256String
|
||||
HMAC_BLAKE2S_256 Algorithm = hmacPrefix + "-" + blake2s_256String
|
||||
HMAC_BLAKE2B_256 Algorithm = hmacPrefix + "-" + blake2b_256String
|
||||
HMAC_BLAKE2B_384 Algorithm = hmacPrefix + "-" + blake2b_384String
|
||||
HMAC_BLAKE2B_512 Algorithm = hmacPrefix + "-" + blake2b_512String
|
||||
BLAKE2S_256 Algorithm = blake2s_256String
|
||||
BLAKE2B_256 Algorithm = blake2b_256String
|
||||
BLAKE2B_384 Algorithm = blake2b_384String
|
||||
BLAKE2B_512 Algorithm = blake2b_512String
|
||||
// RSA-based algorithms.
|
||||
RSA_SHA224 Algorithm = rsaPrefix + "-" + sha224String
|
||||
// RSA_SHA256 is the default algorithm.
|
||||
RSA_SHA256 Algorithm = rsaPrefix + "-" + sha256String
|
||||
RSA_SHA384 Algorithm = rsaPrefix + "-" + sha384String
|
||||
RSA_SHA512 Algorithm = rsaPrefix + "-" + sha512String
|
||||
// ECDSA algorithms
|
||||
ECDSA_SHA224 Algorithm = ecdsaPrefix + "-" + sha224String
|
||||
ECDSA_SHA256 Algorithm = ecdsaPrefix + "-" + sha256String
|
||||
ECDSA_SHA384 Algorithm = ecdsaPrefix + "-" + sha384String
|
||||
ECDSA_SHA512 Algorithm = ecdsaPrefix + "-" + sha512String
|
||||
// ED25519 algorithms
|
||||
// can only be SHA512
|
||||
ED25519 Algorithm = ed25519Prefix
|
||||
|
||||
// Just because you can glue things together, doesn't mean they will
|
||||
// work. The following options are not supported.
|
||||
rsa_SHA3_224 Algorithm = rsaPrefix + "-" + sha3_224String
|
||||
rsa_SHA3_256 Algorithm = rsaPrefix + "-" + sha3_256String
|
||||
rsa_SHA3_384 Algorithm = rsaPrefix + "-" + sha3_384String
|
||||
rsa_SHA3_512 Algorithm = rsaPrefix + "-" + sha3_512String
|
||||
rsa_SHA512_224 Algorithm = rsaPrefix + "-" + sha512_224String
|
||||
rsa_SHA512_256 Algorithm = rsaPrefix + "-" + sha512_256String
|
||||
rsa_BLAKE2S_256 Algorithm = rsaPrefix + "-" + blake2s_256String
|
||||
rsa_BLAKE2B_256 Algorithm = rsaPrefix + "-" + blake2b_256String
|
||||
rsa_BLAKE2B_384 Algorithm = rsaPrefix + "-" + blake2b_384String
|
||||
rsa_BLAKE2B_512 Algorithm = rsaPrefix + "-" + blake2b_512String
|
||||
)
|
||||
|
||||
// HTTP Signatures can be applied to different HTTP headers, depending on the
|
||||
// expected application behavior.
|
||||
type SignatureScheme string
|
||||
|
||||
const (
|
||||
// Signature will place the HTTP Signature into the 'Signature' HTTP
|
||||
// header.
|
||||
Signature SignatureScheme = "Signature"
|
||||
// Authorization will place the HTTP Signature into the 'Authorization'
|
||||
// HTTP header.
|
||||
Authorization SignatureScheme = "Authorization"
|
||||
)
|
||||
|
||||
const (
|
||||
// The HTTP Signatures specification uses the "Signature" auth-scheme
|
||||
// for the Authorization header. This is coincidentally named, but not
|
||||
// semantically the same, as the "Signature" HTTP header value.
|
||||
signatureAuthScheme = "Signature"
|
||||
)
|
||||
|
||||
// There are subtle differences to the values in the header. The Authorization
|
||||
// header has an 'auth-scheme' value that must be prefixed to the rest of the
|
||||
// key and values.
|
||||
func (s SignatureScheme) authScheme() string {
|
||||
switch s {
|
||||
case Authorization:
|
||||
return signatureAuthScheme
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// Signers will sign HTTP requests or responses based on the algorithms and
|
||||
// headers selected at creation time.
|
||||
//
|
||||
// Signers are not safe to use between multiple goroutines.
|
||||
//
|
||||
// Note that signatures do set the deprecated 'algorithm' parameter for
|
||||
// backwards compatibility.
|
||||
type Signer interface {
|
||||
// SignRequest signs the request using a private key. The public key id
|
||||
// is used by the HTTP server to identify which key to use to verify the
|
||||
// signature.
|
||||
//
|
||||
// If the Signer was created using a MAC based algorithm, then the key
|
||||
// is expected to be of type []byte. If the Signer was created using an
|
||||
// RSA based algorithm, then the private key is expected to be of type
|
||||
// *rsa.PrivateKey.
|
||||
//
|
||||
// A Digest (RFC 3230) will be added to the request. The body provided
|
||||
// must match the body used in the request, and is allowed to be nil.
|
||||
// The Digest ensures the request body is not tampered with in flight,
|
||||
// and if the signer is created to also sign the "Digest" header, the
|
||||
// HTTP Signature will then ensure both the Digest and body are not both
|
||||
// modified to maliciously represent different content.
|
||||
SignRequest(pKey crypto.PrivateKey, pubKeyId string, r *http.Request, body []byte) error
|
||||
// SignResponse signs the response using a private key. The public key
|
||||
// id is used by the HTTP client to identify which key to use to verify
|
||||
// the signature.
|
||||
//
|
||||
// If the Signer was created using a MAC based algorithm, then the key
|
||||
// is expected to be of type []byte. If the Signer was created using an
|
||||
// RSA based algorithm, then the private key is expected to be of type
|
||||
// *rsa.PrivateKey.
|
||||
//
|
||||
// A Digest (RFC 3230) will be added to the response. The body provided
|
||||
// must match the body written in the response, and is allowed to be
|
||||
// nil. The Digest ensures the response body is not tampered with in
|
||||
// flight, and if the signer is created to also sign the "Digest"
|
||||
// header, the HTTP Signature will then ensure both the Digest and body
|
||||
// are not both modified to maliciously represent different content.
|
||||
SignResponse(pKey crypto.PrivateKey, pubKeyId string, r http.ResponseWriter, body []byte) error
|
||||
}
|
||||
|
||||
// NewSigner creates a new Signer with the provided algorithm preferences to
|
||||
// make HTTP signatures. Only the first available algorithm will be used, which
|
||||
// is returned by this function along with the Signer. If none of the preferred
|
||||
// algorithms were available, then the default algorithm is used. The headers
|
||||
// specified will be included into the HTTP signatures.
|
||||
//
|
||||
// The Digest will also be calculated on a request's body using the provided
|
||||
// digest algorithm, if "Digest" is one of the headers listed.
|
||||
//
|
||||
// The provided scheme determines which header is populated with the HTTP
|
||||
// Signature.
|
||||
//
|
||||
// An error is returned if an unknown or a known cryptographically insecure
|
||||
// Algorithm is provided.
|
||||
func NewSigner(prefs []Algorithm, dAlgo DigestAlgorithm, headers []string, scheme SignatureScheme, expiresIn int64) (Signer, Algorithm, error) {
|
||||
for _, pref := range prefs {
|
||||
s, err := newSigner(pref, dAlgo, headers, scheme, expiresIn)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
return s, pref, err
|
||||
}
|
||||
s, err := newSigner(defaultAlgorithm, dAlgo, headers, scheme, expiresIn)
|
||||
return s, defaultAlgorithm, err
|
||||
}
|
||||
|
||||
// Signers will sign HTTP requests or responses based on the algorithms and
|
||||
// headers selected at creation time.
|
||||
//
|
||||
// Signers are not safe to use between multiple goroutines.
|
||||
//
|
||||
// Note that signatures do set the deprecated 'algorithm' parameter for
|
||||
// backwards compatibility.
|
||||
type SSHSigner interface {
|
||||
// SignRequest signs the request using ssh.Signer.
|
||||
// The public key id is used by the HTTP server to identify which key to use
|
||||
// to verify the signature.
|
||||
//
|
||||
// A Digest (RFC 3230) will be added to the request. The body provided
|
||||
// must match the body used in the request, and is allowed to be nil.
|
||||
// The Digest ensures the request body is not tampered with in flight,
|
||||
// and if the signer is created to also sign the "Digest" header, the
|
||||
// HTTP Signature will then ensure both the Digest and body are not both
|
||||
// modified to maliciously represent different content.
|
||||
SignRequest(pubKeyId string, r *http.Request, body []byte) error
|
||||
// SignResponse signs the response using ssh.Signer. The public key
|
||||
// id is used by the HTTP client to identify which key to use to verify
|
||||
// the signature.
|
||||
//
|
||||
// A Digest (RFC 3230) will be added to the response. The body provided
|
||||
// must match the body written in the response, and is allowed to be
|
||||
// nil. The Digest ensures the response body is not tampered with in
|
||||
// flight, and if the signer is created to also sign the "Digest"
|
||||
// header, the HTTP Signature will then ensure both the Digest and body
|
||||
// are not both modified to maliciously represent different content.
|
||||
SignResponse(pubKeyId string, r http.ResponseWriter, body []byte) error
|
||||
}
|
||||
|
||||
// NewwSSHSigner creates a new Signer using the specified ssh.Signer
|
||||
// At the moment only ed25519 ssh keys are supported.
|
||||
// The headers specified will be included into the HTTP signatures.
|
||||
//
|
||||
// The Digest will also be calculated on a request's body using the provided
|
||||
// digest algorithm, if "Digest" is one of the headers listed.
|
||||
//
|
||||
// The provided scheme determines which header is populated with the HTTP
|
||||
// Signature.
|
||||
func NewSSHSigner(s ssh.Signer, dAlgo DigestAlgorithm, headers []string, scheme SignatureScheme, expiresIn int64) (SSHSigner, Algorithm, error) {
|
||||
sshAlgo := getSSHAlgorithm(s.PublicKey().Type())
|
||||
if sshAlgo == "" {
|
||||
return nil, "", fmt.Errorf("key type: %s not supported yet.", s.PublicKey().Type())
|
||||
}
|
||||
|
||||
signer, err := newSSHSigner(s, sshAlgo, dAlgo, headers, scheme, expiresIn)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return signer, sshAlgo, nil
|
||||
}
|
||||
|
||||
func getSSHAlgorithm(pkType string) Algorithm {
|
||||
switch {
|
||||
case strings.HasPrefix(pkType, sshPrefix+"-"+ed25519Prefix):
|
||||
return ED25519
|
||||
case strings.HasPrefix(pkType, sshPrefix+"-"+rsaPrefix):
|
||||
return RSA_SHA256
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// Verifier verifies HTTP Signatures.
|
||||
//
|
||||
// It will determine which of the supported headers has the parameters
|
||||
// that define the signature.
|
||||
//
|
||||
// Verifiers are not safe to use between multiple goroutines.
|
||||
//
|
||||
// Note that verification ignores the deprecated 'algorithm' parameter.
|
||||
type Verifier interface {
|
||||
// KeyId gets the public key id that the signature is signed with.
|
||||
//
|
||||
// Note that the application is expected to determine the algorithm
|
||||
// used based on metadata or out-of-band information for this key id.
|
||||
KeyId() string
|
||||
// Verify accepts the public key specified by KeyId and returns an
|
||||
// error if verification fails or if the signature is malformed. The
|
||||
// algorithm must be the one used to create the signature in order to
|
||||
// pass verification. The algorithm is determined based on metadata or
|
||||
// out-of-band information for the key id.
|
||||
//
|
||||
// If the signature was created using a MAC based algorithm, then the
|
||||
// key is expected to be of type []byte. If the signature was created
|
||||
// using an RSA based algorithm, then the public key is expected to be
|
||||
// of type *rsa.PublicKey.
|
||||
Verify(pKey crypto.PublicKey, algo Algorithm) error
|
||||
}
|
||||
|
||||
const (
|
||||
// host is treated specially because golang may not include it in the
|
||||
// request header map on the server side of a request.
|
||||
hostHeader = "Host"
|
||||
)
|
||||
|
||||
// NewVerifier verifies the given request. It returns an error if the HTTP
|
||||
// Signature parameters are not present in any headers, are present in more than
|
||||
// one header, are malformed, or are missing required parameters. It ignores
|
||||
// unknown HTTP Signature parameters.
|
||||
func NewVerifier(r *http.Request) (Verifier, error) {
|
||||
h := r.Header
|
||||
if _, hasHostHeader := h[hostHeader]; len(r.Host) > 0 && !hasHostHeader {
|
||||
h[hostHeader] = []string{r.Host}
|
||||
}
|
||||
return newVerifier(h, func(h http.Header, toInclude []string, created int64, expires int64) (string, error) {
|
||||
return signatureString(h, toInclude, addRequestTarget(r), created, expires)
|
||||
})
|
||||
}
|
||||
|
||||
// NewResponseVerifier verifies the given response. It returns errors under the
|
||||
// same conditions as NewVerifier.
|
||||
func NewResponseVerifier(r *http.Response) (Verifier, error) {
|
||||
return newVerifier(r.Header, func(h http.Header, toInclude []string, created int64, expires int64) (string, error) {
|
||||
return signatureString(h, toInclude, requestTargetNotPermitted, created, expires)
|
||||
})
|
||||
}
|
||||
|
||||
func newSSHSigner(sshSigner ssh.Signer, algo Algorithm, dAlgo DigestAlgorithm, headers []string, scheme SignatureScheme, expiresIn int64) (SSHSigner, error) {
|
||||
var expires, created int64 = 0, 0
|
||||
|
||||
if expiresIn != 0 {
|
||||
created = time.Now().Unix()
|
||||
expires = created + expiresIn
|
||||
}
|
||||
|
||||
s, err := signerFromSSHSigner(sshSigner, string(algo))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("no crypto implementation available for ssh algo %q: %s", algo, err)
|
||||
}
|
||||
|
||||
a := &asymmSSHSigner{
|
||||
asymmSigner: &asymmSigner{
|
||||
s: s,
|
||||
dAlgo: dAlgo,
|
||||
headers: headers,
|
||||
targetHeader: scheme,
|
||||
prefix: scheme.authScheme(),
|
||||
created: created,
|
||||
expires: expires,
|
||||
},
|
||||
}
|
||||
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func newSigner(algo Algorithm, dAlgo DigestAlgorithm, headers []string, scheme SignatureScheme, expiresIn int64) (Signer, error) {
|
||||
var expires, created int64 = 0, 0
|
||||
if expiresIn != 0 {
|
||||
created = time.Now().Unix()
|
||||
expires = created + expiresIn
|
||||
}
|
||||
|
||||
s, err := signerFromString(string(algo))
|
||||
if err == nil {
|
||||
a := &asymmSigner{
|
||||
s: s,
|
||||
dAlgo: dAlgo,
|
||||
headers: headers,
|
||||
targetHeader: scheme,
|
||||
prefix: scheme.authScheme(),
|
||||
created: created,
|
||||
expires: expires,
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
m, err := macerFromString(string(algo))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("no crypto implementation available for %q: %s", algo, err)
|
||||
}
|
||||
c := &macSigner{
|
||||
m: m,
|
||||
dAlgo: dAlgo,
|
||||
headers: headers,
|
||||
targetHeader: scheme,
|
||||
prefix: scheme.authScheme(),
|
||||
created: created,
|
||||
expires: expires,
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
// Signature Parameters
|
||||
keyIdParameter = "keyId"
|
||||
algorithmParameter = "algorithm"
|
||||
headersParameter = "headers"
|
||||
signatureParameter = "signature"
|
||||
prefixSeparater = " "
|
||||
parameterKVSeparater = "="
|
||||
parameterValueDelimiter = "\""
|
||||
parameterSeparater = ","
|
||||
headerParameterValueDelim = " "
|
||||
// RequestTarget specifies to include the http request method and
|
||||
// entire URI in the signature. Pass it as a header to NewSigner.
|
||||
RequestTarget = "(request-target)"
|
||||
createdKey = "created"
|
||||
expiresKey = "expires"
|
||||
dateHeader = "date"
|
||||
|
||||
// Signature String Construction
|
||||
headerFieldDelimiter = ": "
|
||||
headersDelimiter = "\n"
|
||||
headerValueDelimiter = ", "
|
||||
requestTargetSeparator = " "
|
||||
)
|
||||
|
||||
var defaultHeaders = []string{dateHeader}
|
||||
|
||||
var _ Signer = &macSigner{}
|
||||
|
||||
type macSigner struct {
|
||||
m macer
|
||||
makeDigest bool
|
||||
dAlgo DigestAlgorithm
|
||||
headers []string
|
||||
targetHeader SignatureScheme
|
||||
prefix string
|
||||
created int64
|
||||
expires int64
|
||||
}
|
||||
|
||||
func (m *macSigner) SignRequest(pKey crypto.PrivateKey, pubKeyId string, r *http.Request, body []byte) error {
|
||||
if body != nil {
|
||||
err := addDigest(r, m.dAlgo, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s, err := m.signatureString(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc, err := m.signSignature(pKey, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setSignatureHeader(r.Header, string(m.targetHeader), m.prefix, pubKeyId, m.m.String(), enc, m.headers, m.created, m.expires)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *macSigner) SignResponse(pKey crypto.PrivateKey, pubKeyId string, r http.ResponseWriter, body []byte) error {
|
||||
if body != nil {
|
||||
err := addDigestResponse(r, m.dAlgo, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s, err := m.signatureStringResponse(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc, err := m.signSignature(pKey, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setSignatureHeader(r.Header(), string(m.targetHeader), m.prefix, pubKeyId, m.m.String(), enc, m.headers, m.created, m.expires)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *macSigner) signSignature(pKey crypto.PrivateKey, s string) (string, error) {
|
||||
pKeyBytes, ok := pKey.([]byte)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("private key for MAC signing must be of type []byte")
|
||||
}
|
||||
sig, err := m.m.Sign([]byte(s), pKeyBytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
enc := base64.StdEncoding.EncodeToString(sig)
|
||||
return enc, nil
|
||||
}
|
||||
|
||||
func (m *macSigner) signatureString(r *http.Request) (string, error) {
|
||||
return signatureString(r.Header, m.headers, addRequestTarget(r), m.created, m.expires)
|
||||
}
|
||||
|
||||
func (m *macSigner) signatureStringResponse(r http.ResponseWriter) (string, error) {
|
||||
return signatureString(r.Header(), m.headers, requestTargetNotPermitted, m.created, m.expires)
|
||||
}
|
||||
|
||||
var _ Signer = &asymmSigner{}
|
||||
|
||||
type asymmSigner struct {
|
||||
s signer
|
||||
makeDigest bool
|
||||
dAlgo DigestAlgorithm
|
||||
headers []string
|
||||
targetHeader SignatureScheme
|
||||
prefix string
|
||||
created int64
|
||||
expires int64
|
||||
}
|
||||
|
||||
func (a *asymmSigner) SignRequest(pKey crypto.PrivateKey, pubKeyId string, r *http.Request, body []byte) error {
|
||||
if body != nil {
|
||||
err := addDigest(r, a.dAlgo, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s, err := a.signatureString(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc, err := a.signSignature(pKey, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setSignatureHeader(r.Header, string(a.targetHeader), a.prefix, pubKeyId, a.s.String(), enc, a.headers, a.created, a.expires)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *asymmSigner) SignResponse(pKey crypto.PrivateKey, pubKeyId string, r http.ResponseWriter, body []byte) error {
|
||||
if body != nil {
|
||||
err := addDigestResponse(r, a.dAlgo, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s, err := a.signatureStringResponse(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc, err := a.signSignature(pKey, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setSignatureHeader(r.Header(), string(a.targetHeader), a.prefix, pubKeyId, a.s.String(), enc, a.headers, a.created, a.expires)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *asymmSigner) signSignature(pKey crypto.PrivateKey, s string) (string, error) {
|
||||
sig, err := a.s.Sign(rand.Reader, pKey, []byte(s))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
enc := base64.StdEncoding.EncodeToString(sig)
|
||||
return enc, nil
|
||||
}
|
||||
|
||||
func (a *asymmSigner) signatureString(r *http.Request) (string, error) {
|
||||
return signatureString(r.Header, a.headers, addRequestTarget(r), a.created, a.expires)
|
||||
}
|
||||
|
||||
func (a *asymmSigner) signatureStringResponse(r http.ResponseWriter) (string, error) {
|
||||
return signatureString(r.Header(), a.headers, requestTargetNotPermitted, a.created, a.expires)
|
||||
}
|
||||
|
||||
var _ SSHSigner = &asymmSSHSigner{}
|
||||
|
||||
type asymmSSHSigner struct {
|
||||
*asymmSigner
|
||||
}
|
||||
|
||||
func (a *asymmSSHSigner) SignRequest(pubKeyId string, r *http.Request, body []byte) error {
|
||||
return a.asymmSigner.SignRequest(nil, pubKeyId, r, body)
|
||||
}
|
||||
|
||||
func (a *asymmSSHSigner) SignResponse(pubKeyId string, r http.ResponseWriter, body []byte) error {
|
||||
return a.asymmSigner.SignResponse(nil, pubKeyId, r, body)
|
||||
}
|
||||
|
||||
func setSignatureHeader(h http.Header, targetHeader, prefix, pubKeyId, algo, enc string, headers []string, created int64, expires int64) {
|
||||
if len(headers) == 0 {
|
||||
headers = defaultHeaders
|
||||
}
|
||||
var b bytes.Buffer
|
||||
// KeyId
|
||||
b.WriteString(prefix)
|
||||
if len(prefix) > 0 {
|
||||
b.WriteString(prefixSeparater)
|
||||
}
|
||||
b.WriteString(keyIdParameter)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(pubKeyId)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(parameterSeparater)
|
||||
// Algorithm
|
||||
b.WriteString(algorithmParameter)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString("hs2019") //real algorithm is hidden, see newest version of spec draft
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(parameterSeparater)
|
||||
|
||||
hasCreated := false
|
||||
hasExpires := false
|
||||
for _, h := range headers {
|
||||
val := strings.ToLower(h)
|
||||
if val == "("+createdKey+")" {
|
||||
hasCreated = true
|
||||
} else if val == "("+expiresKey+")" {
|
||||
hasExpires = true
|
||||
}
|
||||
}
|
||||
|
||||
// Created
|
||||
if hasCreated == true {
|
||||
b.WriteString(createdKey)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(strconv.FormatInt(created, 10))
|
||||
b.WriteString(parameterSeparater)
|
||||
}
|
||||
|
||||
// Expires
|
||||
if hasExpires == true {
|
||||
b.WriteString(expiresKey)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(strconv.FormatInt(expires, 10))
|
||||
b.WriteString(parameterSeparater)
|
||||
}
|
||||
|
||||
// Headers
|
||||
b.WriteString(headersParameter)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
for i, h := range headers {
|
||||
b.WriteString(strings.ToLower(h))
|
||||
if i != len(headers)-1 {
|
||||
b.WriteString(headerParameterValueDelim)
|
||||
}
|
||||
}
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(parameterSeparater)
|
||||
// Signature
|
||||
b.WriteString(signatureParameter)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(enc)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
h.Add(targetHeader, b.String())
|
||||
}
|
||||
|
||||
func requestTargetNotPermitted(b *bytes.Buffer) error {
|
||||
return fmt.Errorf("cannot sign with %q on anything other than an http request", RequestTarget)
|
||||
}
|
||||
|
||||
func addRequestTarget(r *http.Request) func(b *bytes.Buffer) error {
|
||||
return func(b *bytes.Buffer) error {
|
||||
b.WriteString(RequestTarget)
|
||||
b.WriteString(headerFieldDelimiter)
|
||||
b.WriteString(strings.ToLower(r.Method))
|
||||
b.WriteString(requestTargetSeparator)
|
||||
b.WriteString(r.URL.Path)
|
||||
|
||||
if r.URL.RawQuery != "" {
|
||||
b.WriteString("?")
|
||||
b.WriteString(r.URL.RawQuery)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func signatureString(values http.Header, include []string, requestTargetFn func(b *bytes.Buffer) error, created int64, expires int64) (string, error) {
|
||||
if len(include) == 0 {
|
||||
include = defaultHeaders
|
||||
}
|
||||
var b bytes.Buffer
|
||||
for n, i := range include {
|
||||
i := strings.ToLower(i)
|
||||
if i == RequestTarget {
|
||||
err := requestTargetFn(&b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else if i == "("+expiresKey+")" {
|
||||
if expires == 0 {
|
||||
return "", fmt.Errorf("missing expires value")
|
||||
}
|
||||
b.WriteString(i)
|
||||
b.WriteString(headerFieldDelimiter)
|
||||
b.WriteString(strconv.FormatInt(expires, 10))
|
||||
} else if i == "("+createdKey+")" {
|
||||
if created == 0 {
|
||||
return "", fmt.Errorf("missing created value")
|
||||
}
|
||||
b.WriteString(i)
|
||||
b.WriteString(headerFieldDelimiter)
|
||||
b.WriteString(strconv.FormatInt(created, 10))
|
||||
} else {
|
||||
hv, ok := values[textproto.CanonicalMIMEHeaderKey(i)]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing header %q", i)
|
||||
}
|
||||
b.WriteString(i)
|
||||
b.WriteString(headerFieldDelimiter)
|
||||
for i, v := range hv {
|
||||
b.WriteString(strings.TrimSpace(v))
|
||||
if i < len(hv)-1 {
|
||||
b.WriteString(headerValueDelimiter)
|
||||
}
|
||||
}
|
||||
}
|
||||
if n < len(include)-1 {
|
||||
b.WriteString(headersDelimiter)
|
||||
}
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Verifier = &verifier{}
|
||||
|
||||
type verifier struct {
|
||||
header http.Header
|
||||
kId string
|
||||
signature string
|
||||
created int64
|
||||
expires int64
|
||||
headers []string
|
||||
sigStringFn func(http.Header, []string, int64, int64) (string, error)
|
||||
}
|
||||
|
||||
func newVerifier(h http.Header, sigStringFn func(http.Header, []string, int64, int64) (string, error)) (*verifier, error) {
|
||||
scheme, s, err := getSignatureScheme(h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kId, sig, headers, created, expires, err := getSignatureComponents(scheme, s)
|
||||
if created != 0 {
|
||||
//check if created is not in the future, we assume a maximum clock offset of 10 seconds
|
||||
now := time.Now().Unix()
|
||||
if created-now > 10 {
|
||||
return nil, errors.New("created is in the future")
|
||||
}
|
||||
}
|
||||
if expires != 0 {
|
||||
//check if expires is in the past, we assume a maximum clock offset of 10 seconds
|
||||
now := time.Now().Unix()
|
||||
if now-expires > 10 {
|
||||
return nil, errors.New("signature expired")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &verifier{
|
||||
header: h,
|
||||
kId: kId,
|
||||
signature: sig,
|
||||
created: created,
|
||||
expires: expires,
|
||||
headers: headers,
|
||||
sigStringFn: sigStringFn,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (v *verifier) KeyId() string {
|
||||
return v.kId
|
||||
}
|
||||
|
||||
func (v *verifier) Verify(pKey crypto.PublicKey, algo Algorithm) error {
|
||||
s, err := signerFromString(string(algo))
|
||||
if err == nil {
|
||||
return v.asymmVerify(s, pKey)
|
||||
}
|
||||
m, err := macerFromString(string(algo))
|
||||
if err == nil {
|
||||
return v.macVerify(m, pKey)
|
||||
}
|
||||
return fmt.Errorf("no crypto implementation available for %q: %s", algo, err)
|
||||
}
|
||||
|
||||
func (v *verifier) macVerify(m macer, pKey crypto.PublicKey) error {
|
||||
key, ok := pKey.([]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("public key for MAC verifying must be of type []byte")
|
||||
}
|
||||
signature, err := v.sigStringFn(v.header, v.headers, v.created, v.expires)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actualMAC, err := base64.StdEncoding.DecodeString(v.signature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ok, err = m.Equal([]byte(signature), actualMAC, key)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !ok {
|
||||
return fmt.Errorf("invalid http signature")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *verifier) asymmVerify(s signer, pKey crypto.PublicKey) error {
|
||||
toHash, err := v.sigStringFn(v.header, v.headers, v.created, v.expires)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
signature, err := base64.StdEncoding.DecodeString(v.signature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.Verify(pKey, []byte(toHash), signature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getSignatureScheme(h http.Header) (scheme SignatureScheme, val string, err error) {
|
||||
s := h.Get(string(Signature))
|
||||
sigHasAll := strings.Contains(s, keyIdParameter) ||
|
||||
strings.Contains(s, headersParameter) ||
|
||||
strings.Contains(s, signatureParameter)
|
||||
a := h.Get(string(Authorization))
|
||||
authHasAll := strings.Contains(a, keyIdParameter) ||
|
||||
strings.Contains(a, headersParameter) ||
|
||||
strings.Contains(a, signatureParameter)
|
||||
if sigHasAll && authHasAll {
|
||||
err = fmt.Errorf("both %q and %q have signature parameters", Signature, Authorization)
|
||||
return
|
||||
} else if !sigHasAll && !authHasAll {
|
||||
err = fmt.Errorf("neither %q nor %q have signature parameters", Signature, Authorization)
|
||||
return
|
||||
} else if sigHasAll {
|
||||
val = s
|
||||
scheme = Signature
|
||||
return
|
||||
} else { // authHasAll
|
||||
val = a
|
||||
scheme = Authorization
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func getSignatureComponents(scheme SignatureScheme, s string) (kId, sig string, headers []string, created int64, expires int64, err error) {
|
||||
if as := scheme.authScheme(); len(as) > 0 {
|
||||
s = strings.TrimPrefix(s, as+prefixSeparater)
|
||||
}
|
||||
params := strings.Split(s, parameterSeparater)
|
||||
for _, p := range params {
|
||||
kv := strings.SplitN(p, parameterKVSeparater, 2)
|
||||
if len(kv) != 2 {
|
||||
err = fmt.Errorf("malformed http signature parameter: %v", kv)
|
||||
return
|
||||
}
|
||||
k := kv[0]
|
||||
v := strings.Trim(kv[1], parameterValueDelimiter)
|
||||
switch k {
|
||||
case keyIdParameter:
|
||||
kId = v
|
||||
case createdKey:
|
||||
created, err = strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
case expiresKey:
|
||||
expires, err = strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
case algorithmParameter:
|
||||
// Deprecated, ignore
|
||||
case headersParameter:
|
||||
headers = strings.Split(v, headerParameterValueDelim)
|
||||
case signatureParameter:
|
||||
sig = v
|
||||
default:
|
||||
// Ignore unrecognized parameters
|
||||
}
|
||||
}
|
||||
if len(kId) == 0 {
|
||||
err = fmt.Errorf("missing %q parameter in http signature", keyIdParameter)
|
||||
} else if len(sig) == 0 {
|
||||
err = fmt.Errorf("missing %q parameter in http signature", signatureParameter)
|
||||
} else if len(headers) == 0 { // Optional
|
||||
headers = defaultHeaders
|
||||
}
|
||||
return
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
Copyright (c) 2014 David Mzareulyan
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
|
||||
and associated documentation files (the "Software"), to deal in the Software without restriction,
|
||||
including without limitation the rights to use, copy, modify, merge, publish, distribute,
|
||||
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
|
||||
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
[](https://godoc.org/github.com/davidmz/go-pageant)
|
||||
|
||||
Package pageant provides an interface to PyTTY pageant.exe utility.
|
||||
|
||||
This package is windows-only.
|
||||
|
||||
See documentation on [GoDoc](http://godoc.org/github.com/davidmz/go-pageant)
|
||||
|
||||
License: MIT
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package pageant
|
||||
|
||||
import (
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/crypto/ssh/agent"
|
||||
)
|
||||
|
||||
// New returns new ssh-agent instance (see http://golang.org/x/crypto/ssh/agent)
|
||||
func New() agent.Agent {
|
||||
return agent.NewClient(&conn{})
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
sync.Mutex
|
||||
buf []byte
|
||||
}
|
||||
|
||||
func (c *conn) Write(p []byte) (int, error) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
resp, err := query(p)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.buf = append(c.buf, resp...)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (c *conn) Read(p []byte) (int, error) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
if len(c.buf) == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, c.buf)
|
||||
c.buf = c.buf[n:]
|
||||
return n, nil
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
// Package pageant provides an interface to PyTTY pageant.exe utility.
|
||||
// This package is windows-only
|
||||
package pageant
|
||||
|
||||
// see https://github.com/Yasushi/putty/blob/master/windows/winpgntc.c#L155
|
||||
// see https://github.com/paramiko/paramiko/blob/master/paramiko/win_pageant.py
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// MaxMessageLen defines maximum size of message can be sent to pageant
|
||||
const MaxMessageLen = 8192
|
||||
|
||||
var (
|
||||
// ErrPageantNotFound returns when pageant process not found
|
||||
ErrPageantNotFound = errors.New("pageant process not found")
|
||||
// ErrSendMessage returns when message to pageant cannt be sent
|
||||
ErrSendMessage = errors.New("error sending message")
|
||||
|
||||
// ErrMessageTooLong returns when message is too long (see MaxMessageLen)
|
||||
ErrMessageTooLong = errors.New("message too long")
|
||||
// ErrInvalidMessageFormat returns when message have invalid fomat
|
||||
ErrInvalidMessageFormat = errors.New("invalid message format")
|
||||
// ErrResponseTooLong returns when response from pageant is too long
|
||||
ErrResponseTooLong = errors.New("response too long")
|
||||
)
|
||||
|
||||
/////////////////////////
|
||||
|
||||
const (
|
||||
agentCopydataID = 0x804e50ba
|
||||
wmCopydata = 74
|
||||
)
|
||||
|
||||
type copyData struct {
|
||||
dwData uintptr
|
||||
cbData uint32
|
||||
lpData unsafe.Pointer
|
||||
}
|
||||
|
||||
var (
|
||||
lock sync.Mutex
|
||||
|
||||
winFindWindow = winAPI("user32.dll", "FindWindowW")
|
||||
winGetCurrentThreadID = winAPI("kernel32.dll", "GetCurrentThreadId")
|
||||
winSendMessage = winAPI("user32.dll", "SendMessageW")
|
||||
)
|
||||
|
||||
func winAPI(dllName, funcName string) func(...uintptr) (uintptr, uintptr, error) {
|
||||
proc := syscall.MustLoadDLL(dllName).MustFindProc(funcName)
|
||||
return func(a ...uintptr) (uintptr, uintptr, error) { return proc.Call(a...) }
|
||||
}
|
||||
|
||||
// Available returns true if Pageant is started
|
||||
func Available() bool { return pageantWindow() != 0 }
|
||||
|
||||
// Query sends message msg to Pageant and returns response or error.
|
||||
// 'msg' is raw agent request with length prefix
|
||||
// Response is raw agent response with length prefix
|
||||
func query(msg []byte) ([]byte, error) {
|
||||
if len(msg) > MaxMessageLen {
|
||||
return nil, ErrMessageTooLong
|
||||
}
|
||||
|
||||
msgLen := binary.BigEndian.Uint32(msg[:4])
|
||||
if len(msg) != int(msgLen)+4 {
|
||||
return nil, ErrInvalidMessageFormat
|
||||
}
|
||||
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
paWin := pageantWindow()
|
||||
|
||||
if paWin == 0 {
|
||||
return nil, ErrPageantNotFound
|
||||
}
|
||||
|
||||
thID, _, _ := winGetCurrentThreadID()
|
||||
mapName := fmt.Sprintf("PageantRequest%08x", thID)
|
||||
pMapName, _ := syscall.UTF16PtrFromString(mapName)
|
||||
|
||||
mmap, err := syscall.CreateFileMapping(syscall.InvalidHandle, nil, syscall.PAGE_READWRITE, 0, MaxMessageLen+4, pMapName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer syscall.CloseHandle(mmap)
|
||||
|
||||
ptr, err := syscall.MapViewOfFile(mmap, syscall.FILE_MAP_WRITE, 0, 0, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer syscall.UnmapViewOfFile(ptr)
|
||||
|
||||
mmSlice := (*(*[MaxMessageLen]byte)(unsafe.Pointer(ptr)))[:]
|
||||
|
||||
copy(mmSlice, msg)
|
||||
|
||||
mapNameBytesZ := append([]byte(mapName), 0)
|
||||
|
||||
cds := copyData{
|
||||
dwData: agentCopydataID,
|
||||
cbData: uint32(len(mapNameBytesZ)),
|
||||
lpData: unsafe.Pointer(&(mapNameBytesZ[0])),
|
||||
}
|
||||
|
||||
resp, _, _ := winSendMessage(paWin, wmCopydata, 0, uintptr(unsafe.Pointer(&cds)))
|
||||
|
||||
if resp == 0 {
|
||||
return nil, ErrSendMessage
|
||||
}
|
||||
|
||||
respLen := binary.BigEndian.Uint32(mmSlice[:4])
|
||||
if respLen > MaxMessageLen-4 {
|
||||
return nil, ErrResponseTooLong
|
||||
}
|
||||
|
||||
respData := make([]byte, respLen+4)
|
||||
copy(respData, mmSlice)
|
||||
|
||||
return respData, nil
|
||||
}
|
||||
|
||||
func pageantWindow() uintptr {
|
||||
nameP, _ := syscall.UTF16PtrFromString("Pageant")
|
||||
h, _, _ := winFindWindow(uintptr(unsafe.Pointer(nameP)), uintptr(unsafe.Pointer(nameP)))
|
||||
return h
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2018, go-fed
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
# httpsig
|
||||
|
||||
`go get github.com/go-fed/httpsig`
|
||||
|
||||
Implementation of [HTTP Signatures](https://tools.ietf.org/html/draft-cavage-http-signatures).
|
||||
|
||||
Supports many different combinations of MAC, HMAC signing of hash, or RSA
|
||||
signing of hash schemes. Its goals are:
|
||||
|
||||
* Have a very simple interface for signing and validating
|
||||
* Support a variety of signing algorithms and combinations
|
||||
* Support setting either headers (`Authorization` or `Signature`)
|
||||
* Remaining flexible with headers included in the signing string
|
||||
* Support both HTTP requests and responses
|
||||
* Explicitly not support known-cryptographically weak algorithms
|
||||
* Support automatic signing and validating Digest headers
|
||||
|
||||
## How to use
|
||||
|
||||
`import "github.com/go-fed/httpsig"`
|
||||
|
||||
### Signing
|
||||
|
||||
Signing a request or response requires creating a new `Signer` and using it:
|
||||
|
||||
```
|
||||
func sign(privateKey crypto.PrivateKey, pubKeyId string, r *http.Request) error {
|
||||
prefs := []httpsig.Algorithm{httpsig.RSA_SHA512, httpsig.RSA_SHA256}
|
||||
digestAlgorithm := DigestSha256
|
||||
// The "Date" and "Digest" headers must already be set on r, as well as r.URL.
|
||||
headersToSign := []string{httpsig.RequestTarget, "date", "digest"}
|
||||
signer, chosenAlgo, err := httpsig.NewSigner(prefs, digestAlgorithm, headersToSign, httpsig.Signature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// To sign the digest, we need to give the signer a copy of the body...
|
||||
// ...but it is optional, no digest will be signed if given "nil"
|
||||
body := ...
|
||||
// If r were a http.ResponseWriter, call SignResponse instead.
|
||||
return signer.SignRequest(privateKey, pubKeyId, r, body)
|
||||
}
|
||||
```
|
||||
|
||||
`Signer`s are not safe for concurrent use by goroutines, so be sure to guard
|
||||
access:
|
||||
|
||||
```
|
||||
type server struct {
|
||||
signer httpsig.Signer
|
||||
mu *sync.Mutex
|
||||
}
|
||||
|
||||
func (s *server) handlerFunc(w http.ResponseWriter, r *http.Request) {
|
||||
privateKey := ...
|
||||
pubKeyId := ...
|
||||
// Set headers and such on w
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
// To sign the digest, we need to give the signer a copy of the response body...
|
||||
// ...but it is optional, no digest will be signed if given "nil"
|
||||
body := ...
|
||||
err := s.signer.SignResponse(privateKey, pubKeyId, w, body)
|
||||
if err != nil {
|
||||
...
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
The `pubKeyId` will be used at verification time.
|
||||
|
||||
### Verifying
|
||||
|
||||
Verifying requires an application to use the `pubKeyId` to both retrieve the key
|
||||
needed for verification as well as determine the algorithm to use. Use a
|
||||
`Verifier`:
|
||||
|
||||
```
|
||||
func verify(r *http.Request) error {
|
||||
verifier, err := httpsig.NewVerifier(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pubKeyId := verifier.KeyId()
|
||||
var algo httpsig.Algorithm = ...
|
||||
var pubKey crypto.PublicKey = ...
|
||||
// The verifier will verify the Digest in addition to the HTTP signature
|
||||
return verifier.Verify(pubKey, algo)
|
||||
}
|
||||
```
|
||||
|
||||
`Verifier`s are not safe for concurrent use by goroutines, but since they are
|
||||
constructed on a per-request or per-response basis it should not be a common
|
||||
restriction.
|
||||
+532
@@ -0,0 +1,532 @@
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/hmac"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"crypto/subtle" // Use should trigger great care
|
||||
"encoding/asn1"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/blake2b"
|
||||
"golang.org/x/crypto/blake2s"
|
||||
"golang.org/x/crypto/ed25519"
|
||||
"golang.org/x/crypto/ripemd160"
|
||||
"golang.org/x/crypto/sha3"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
const (
|
||||
hmacPrefix = "hmac"
|
||||
rsaPrefix = "rsa"
|
||||
sshPrefix = "ssh"
|
||||
ecdsaPrefix = "ecdsa"
|
||||
ed25519Prefix = "ed25519"
|
||||
md4String = "md4"
|
||||
md5String = "md5"
|
||||
sha1String = "sha1"
|
||||
sha224String = "sha224"
|
||||
sha256String = "sha256"
|
||||
sha384String = "sha384"
|
||||
sha512String = "sha512"
|
||||
md5sha1String = "md5sha1"
|
||||
ripemd160String = "ripemd160"
|
||||
sha3_224String = "sha3-224"
|
||||
sha3_256String = "sha3-256"
|
||||
sha3_384String = "sha3-384"
|
||||
sha3_512String = "sha3-512"
|
||||
sha512_224String = "sha512-224"
|
||||
sha512_256String = "sha512-256"
|
||||
blake2s_256String = "blake2s-256"
|
||||
blake2b_256String = "blake2b-256"
|
||||
blake2b_384String = "blake2b-384"
|
||||
blake2b_512String = "blake2b-512"
|
||||
)
|
||||
|
||||
var blake2Algorithms = map[crypto.Hash]bool{
|
||||
crypto.BLAKE2s_256: true,
|
||||
crypto.BLAKE2b_256: true,
|
||||
crypto.BLAKE2b_384: true,
|
||||
crypto.BLAKE2b_512: true,
|
||||
}
|
||||
|
||||
var hashToDef = map[crypto.Hash]struct {
|
||||
name string
|
||||
new func(key []byte) (hash.Hash, error) // Only MACers will accept a key
|
||||
}{
|
||||
// Which standard names these?
|
||||
// The spec lists the following as a canonical reference, which is dead:
|
||||
// http://www.iana.org/assignments/signature-algorithms
|
||||
//
|
||||
// Note that the forbidden hashes have an invalid 'new' function.
|
||||
crypto.MD4: {md4String, func(key []byte) (hash.Hash, error) { return nil, nil }},
|
||||
crypto.MD5: {md5String, func(key []byte) (hash.Hash, error) { return nil, nil }},
|
||||
// Temporarily enable SHA1 because of issue https://github.com/golang/go/issues/37278
|
||||
crypto.SHA1: {sha1String, func(key []byte) (hash.Hash, error) { return sha1.New(), nil }},
|
||||
crypto.SHA224: {sha224String, func(key []byte) (hash.Hash, error) { return sha256.New224(), nil }},
|
||||
crypto.SHA256: {sha256String, func(key []byte) (hash.Hash, error) { return sha256.New(), nil }},
|
||||
crypto.SHA384: {sha384String, func(key []byte) (hash.Hash, error) { return sha512.New384(), nil }},
|
||||
crypto.SHA512: {sha512String, func(key []byte) (hash.Hash, error) { return sha512.New(), nil }},
|
||||
crypto.MD5SHA1: {md5sha1String, func(key []byte) (hash.Hash, error) { return nil, nil }},
|
||||
crypto.RIPEMD160: {ripemd160String, func(key []byte) (hash.Hash, error) { return ripemd160.New(), nil }},
|
||||
crypto.SHA3_224: {sha3_224String, func(key []byte) (hash.Hash, error) { return sha3.New224(), nil }},
|
||||
crypto.SHA3_256: {sha3_256String, func(key []byte) (hash.Hash, error) { return sha3.New256(), nil }},
|
||||
crypto.SHA3_384: {sha3_384String, func(key []byte) (hash.Hash, error) { return sha3.New384(), nil }},
|
||||
crypto.SHA3_512: {sha3_512String, func(key []byte) (hash.Hash, error) { return sha3.New512(), nil }},
|
||||
crypto.SHA512_224: {sha512_224String, func(key []byte) (hash.Hash, error) { return sha512.New512_224(), nil }},
|
||||
crypto.SHA512_256: {sha512_256String, func(key []byte) (hash.Hash, error) { return sha512.New512_256(), nil }},
|
||||
crypto.BLAKE2s_256: {blake2s_256String, func(key []byte) (hash.Hash, error) { return blake2s.New256(key) }},
|
||||
crypto.BLAKE2b_256: {blake2b_256String, func(key []byte) (hash.Hash, error) { return blake2b.New256(key) }},
|
||||
crypto.BLAKE2b_384: {blake2b_384String, func(key []byte) (hash.Hash, error) { return blake2b.New384(key) }},
|
||||
crypto.BLAKE2b_512: {blake2b_512String, func(key []byte) (hash.Hash, error) { return blake2b.New512(key) }},
|
||||
}
|
||||
|
||||
var stringToHash map[string]crypto.Hash
|
||||
|
||||
const (
|
||||
defaultAlgorithm = RSA_SHA256
|
||||
defaultAlgorithmHashing = sha256String
|
||||
)
|
||||
|
||||
func init() {
|
||||
stringToHash = make(map[string]crypto.Hash, len(hashToDef))
|
||||
for k, v := range hashToDef {
|
||||
stringToHash[v.name] = k
|
||||
}
|
||||
// This should guarantee that at runtime the defaultAlgorithm will not
|
||||
// result in errors when fetching a macer or signer (see algorithms.go)
|
||||
if ok, err := isAvailable(string(defaultAlgorithmHashing)); err != nil {
|
||||
panic(err)
|
||||
} else if !ok {
|
||||
panic(fmt.Sprintf("the default httpsig algorithm is unavailable: %q", defaultAlgorithm))
|
||||
}
|
||||
}
|
||||
|
||||
func isForbiddenHash(h crypto.Hash) bool {
|
||||
switch h {
|
||||
// Not actually cryptographically secure
|
||||
case crypto.MD4:
|
||||
fallthrough
|
||||
case crypto.MD5:
|
||||
fallthrough
|
||||
case crypto.MD5SHA1: // shorthand for crypto/tls, not actually implemented
|
||||
return true
|
||||
}
|
||||
// Still cryptographically secure
|
||||
return false
|
||||
}
|
||||
|
||||
// signer is an internally public type.
|
||||
type signer interface {
|
||||
Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error)
|
||||
Verify(pub crypto.PublicKey, toHash, signature []byte) error
|
||||
String() string
|
||||
}
|
||||
|
||||
// macer is an internally public type.
|
||||
type macer interface {
|
||||
Sign(sig, key []byte) ([]byte, error)
|
||||
Equal(sig, actualMAC, key []byte) (bool, error)
|
||||
String() string
|
||||
}
|
||||
|
||||
var _ macer = &hmacAlgorithm{}
|
||||
|
||||
type hmacAlgorithm struct {
|
||||
fn func(key []byte) (hash.Hash, error)
|
||||
kind crypto.Hash
|
||||
}
|
||||
|
||||
func (h *hmacAlgorithm) Sign(sig, key []byte) ([]byte, error) {
|
||||
hs, err := h.fn(key)
|
||||
if err = setSig(hs, sig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hs.Sum(nil), nil
|
||||
}
|
||||
|
||||
func (h *hmacAlgorithm) Equal(sig, actualMAC, key []byte) (bool, error) {
|
||||
hs, err := h.fn(key)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer hs.Reset()
|
||||
err = setSig(hs, sig)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
expected := hs.Sum(nil)
|
||||
return hmac.Equal(actualMAC, expected), nil
|
||||
}
|
||||
|
||||
func (h *hmacAlgorithm) String() string {
|
||||
return fmt.Sprintf("%s-%s", hmacPrefix, hashToDef[h.kind].name)
|
||||
}
|
||||
|
||||
var _ signer = &rsaAlgorithm{}
|
||||
|
||||
type rsaAlgorithm struct {
|
||||
hash.Hash
|
||||
kind crypto.Hash
|
||||
sshSigner ssh.Signer
|
||||
}
|
||||
|
||||
func (r *rsaAlgorithm) setSig(b []byte) error {
|
||||
n, err := r.Write(b)
|
||||
if err != nil {
|
||||
r.Reset()
|
||||
return err
|
||||
} else if n != len(b) {
|
||||
r.Reset()
|
||||
return fmt.Errorf("could only write %d of %d bytes of signature to hash", n, len(b))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *rsaAlgorithm) Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error) {
|
||||
if r.sshSigner != nil {
|
||||
sshsig, err := r.sshSigner.Sign(rand, sig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return sshsig.Blob, nil
|
||||
}
|
||||
defer r.Reset()
|
||||
|
||||
if err := r.setSig(sig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rsaK, ok := p.(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, errors.New("crypto.PrivateKey is not *rsa.PrivateKey")
|
||||
}
|
||||
return rsa.SignPKCS1v15(rand, rsaK, r.kind, r.Sum(nil))
|
||||
}
|
||||
|
||||
func (r *rsaAlgorithm) Verify(pub crypto.PublicKey, toHash, signature []byte) error {
|
||||
defer r.Reset()
|
||||
rsaK, ok := pub.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return errors.New("crypto.PublicKey is not *rsa.PublicKey")
|
||||
}
|
||||
if err := r.setSig(toHash); err != nil {
|
||||
return err
|
||||
}
|
||||
return rsa.VerifyPKCS1v15(rsaK, r.kind, r.Sum(nil), signature)
|
||||
}
|
||||
|
||||
func (r *rsaAlgorithm) String() string {
|
||||
return fmt.Sprintf("%s-%s", rsaPrefix, hashToDef[r.kind].name)
|
||||
}
|
||||
|
||||
var _ signer = &ed25519Algorithm{}
|
||||
|
||||
type ed25519Algorithm struct {
|
||||
sshSigner ssh.Signer
|
||||
}
|
||||
|
||||
func (r *ed25519Algorithm) Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error) {
|
||||
if r.sshSigner != nil {
|
||||
sshsig, err := r.sshSigner.Sign(rand, sig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return sshsig.Blob, nil
|
||||
}
|
||||
ed25519K, ok := p.(ed25519.PrivateKey)
|
||||
if !ok {
|
||||
return nil, errors.New("crypto.PrivateKey is not ed25519.PrivateKey")
|
||||
}
|
||||
return ed25519.Sign(ed25519K, sig), nil
|
||||
}
|
||||
|
||||
func (r *ed25519Algorithm) Verify(pub crypto.PublicKey, toHash, signature []byte) error {
|
||||
ed25519K, ok := pub.(ed25519.PublicKey)
|
||||
if !ok {
|
||||
return errors.New("crypto.PublicKey is not ed25519.PublicKey")
|
||||
}
|
||||
|
||||
if ed25519.Verify(ed25519K, toHash, signature) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("ed25519 verify failed")
|
||||
}
|
||||
|
||||
func (r *ed25519Algorithm) String() string {
|
||||
return fmt.Sprintf("%s", ed25519Prefix)
|
||||
}
|
||||
|
||||
var _ signer = &ecdsaAlgorithm{}
|
||||
|
||||
type ecdsaAlgorithm struct {
|
||||
hash.Hash
|
||||
kind crypto.Hash
|
||||
}
|
||||
|
||||
func (r *ecdsaAlgorithm) setSig(b []byte) error {
|
||||
n, err := r.Write(b)
|
||||
if err != nil {
|
||||
r.Reset()
|
||||
return err
|
||||
} else if n != len(b) {
|
||||
r.Reset()
|
||||
return fmt.Errorf("could only write %d of %d bytes of signature to hash", n, len(b))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type ECDSASignature struct {
|
||||
R, S *big.Int
|
||||
}
|
||||
|
||||
func (r *ecdsaAlgorithm) Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error) {
|
||||
defer r.Reset()
|
||||
if err := r.setSig(sig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ecdsaK, ok := p.(*ecdsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, errors.New("crypto.PrivateKey is not *ecdsa.PrivateKey")
|
||||
}
|
||||
R, S, err := ecdsa.Sign(rand, ecdsaK, r.Sum(nil))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature := ECDSASignature{R: R, S: S}
|
||||
bytes, err := asn1.Marshal(signature)
|
||||
|
||||
return bytes, err
|
||||
}
|
||||
|
||||
func (r *ecdsaAlgorithm) Verify(pub crypto.PublicKey, toHash, signature []byte) error {
|
||||
defer r.Reset()
|
||||
ecdsaK, ok := pub.(*ecdsa.PublicKey)
|
||||
if !ok {
|
||||
return errors.New("crypto.PublicKey is not *ecdsa.PublicKey")
|
||||
}
|
||||
if err := r.setSig(toHash); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sig := new(ECDSASignature)
|
||||
_, err := asn1.Unmarshal(signature, sig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ecdsa.Verify(ecdsaK, r.Sum(nil), sig.R, sig.S) {
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("Invalid signature")
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ecdsaAlgorithm) String() string {
|
||||
return fmt.Sprintf("%s-%s", ecdsaPrefix, hashToDef[r.kind].name)
|
||||
}
|
||||
|
||||
var _ macer = &blakeMacAlgorithm{}
|
||||
|
||||
type blakeMacAlgorithm struct {
|
||||
fn func(key []byte) (hash.Hash, error)
|
||||
kind crypto.Hash
|
||||
}
|
||||
|
||||
func (r *blakeMacAlgorithm) Sign(sig, key []byte) ([]byte, error) {
|
||||
hs, err := r.fn(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = setSig(hs, sig); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hs.Sum(nil), nil
|
||||
}
|
||||
|
||||
func (r *blakeMacAlgorithm) Equal(sig, actualMAC, key []byte) (bool, error) {
|
||||
hs, err := r.fn(key)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer hs.Reset()
|
||||
err = setSig(hs, sig)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
expected := hs.Sum(nil)
|
||||
return subtle.ConstantTimeCompare(actualMAC, expected) == 1, nil
|
||||
}
|
||||
|
||||
func (r *blakeMacAlgorithm) String() string {
|
||||
return fmt.Sprintf("%s", hashToDef[r.kind].name)
|
||||
}
|
||||
|
||||
func setSig(a hash.Hash, b []byte) error {
|
||||
n, err := a.Write(b)
|
||||
if err != nil {
|
||||
a.Reset()
|
||||
return err
|
||||
} else if n != len(b) {
|
||||
a.Reset()
|
||||
return fmt.Errorf("could only write %d of %d bytes of signature to hash", n, len(b))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsSupportedHttpSigAlgorithm returns true if the string is supported by this
|
||||
// library, is not a hash known to be weak, and is supported by the hardware.
|
||||
func IsSupportedHttpSigAlgorithm(algo string) bool {
|
||||
a, err := isAvailable(algo)
|
||||
return a && err == nil
|
||||
}
|
||||
|
||||
// isAvailable is an internally public function
|
||||
func isAvailable(algo string) (bool, error) {
|
||||
c, ok := stringToHash[algo]
|
||||
if !ok {
|
||||
return false, fmt.Errorf("no match for %q", algo)
|
||||
}
|
||||
if isForbiddenHash(c) {
|
||||
return false, fmt.Errorf("forbidden hash type in %q", algo)
|
||||
}
|
||||
return c.Available(), nil
|
||||
}
|
||||
|
||||
func newAlgorithmConstructor(algo string) (fn func(k []byte) (hash.Hash, error), c crypto.Hash, e error) {
|
||||
ok := false
|
||||
c, ok = stringToHash[algo]
|
||||
if !ok {
|
||||
e = fmt.Errorf("no match for %q", algo)
|
||||
return
|
||||
}
|
||||
if isForbiddenHash(c) {
|
||||
e = fmt.Errorf("forbidden hash type in %q", algo)
|
||||
return
|
||||
}
|
||||
algoDef, ok := hashToDef[c]
|
||||
if !ok {
|
||||
e = fmt.Errorf("have crypto.Hash %v but no definition", c)
|
||||
return
|
||||
}
|
||||
fn = func(key []byte) (hash.Hash, error) {
|
||||
h, err := algoDef.new(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func newAlgorithm(algo string, key []byte) (hash.Hash, crypto.Hash, error) {
|
||||
fn, c, err := newAlgorithmConstructor(algo)
|
||||
if err != nil {
|
||||
return nil, c, err
|
||||
}
|
||||
h, err := fn(key)
|
||||
return h, c, err
|
||||
}
|
||||
|
||||
func signerFromSSHSigner(sshSigner ssh.Signer, s string) (signer, error) {
|
||||
switch {
|
||||
case strings.HasPrefix(s, rsaPrefix):
|
||||
return &rsaAlgorithm{
|
||||
sshSigner: sshSigner,
|
||||
}, nil
|
||||
case strings.HasPrefix(s, ed25519Prefix):
|
||||
return &ed25519Algorithm{
|
||||
sshSigner: sshSigner,
|
||||
}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("no signer matching %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// signerFromString is an internally public method constructor
|
||||
func signerFromString(s string) (signer, error) {
|
||||
s = strings.ToLower(s)
|
||||
isEcdsa := false
|
||||
isEd25519 := false
|
||||
var algo string = ""
|
||||
if strings.HasPrefix(s, ecdsaPrefix) {
|
||||
algo = strings.TrimPrefix(s, ecdsaPrefix+"-")
|
||||
isEcdsa = true
|
||||
} else if strings.HasPrefix(s, rsaPrefix) {
|
||||
algo = strings.TrimPrefix(s, rsaPrefix+"-")
|
||||
} else if strings.HasPrefix(s, ed25519Prefix) {
|
||||
isEd25519 = true
|
||||
algo = "sha512"
|
||||
} else {
|
||||
return nil, fmt.Errorf("no signer matching %q", s)
|
||||
}
|
||||
hash, cHash, err := newAlgorithm(algo, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isEd25519 {
|
||||
return &ed25519Algorithm{}, nil
|
||||
}
|
||||
if isEcdsa {
|
||||
return &ecdsaAlgorithm{
|
||||
Hash: hash,
|
||||
kind: cHash,
|
||||
}, nil
|
||||
}
|
||||
return &rsaAlgorithm{
|
||||
Hash: hash,
|
||||
kind: cHash,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// macerFromString is an internally public method constructor
|
||||
func macerFromString(s string) (macer, error) {
|
||||
s = strings.ToLower(s)
|
||||
if strings.HasPrefix(s, hmacPrefix) {
|
||||
algo := strings.TrimPrefix(s, hmacPrefix+"-")
|
||||
hashFn, cHash, err := newAlgorithmConstructor(algo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Ensure below does not panic
|
||||
_, err = hashFn(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &hmacAlgorithm{
|
||||
fn: func(key []byte) (hash.Hash, error) {
|
||||
return hmac.New(func() hash.Hash {
|
||||
h, e := hashFn(nil)
|
||||
if e != nil {
|
||||
panic(e)
|
||||
}
|
||||
return h
|
||||
}, key), nil
|
||||
},
|
||||
kind: cHash,
|
||||
}, nil
|
||||
} else if bl, ok := stringToHash[s]; ok && blake2Algorithms[bl] {
|
||||
hashFn, cHash, err := newAlgorithmConstructor(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &blakeMacAlgorithm{
|
||||
fn: hashFn,
|
||||
kind: cHash,
|
||||
}, nil
|
||||
} else {
|
||||
return nil, fmt.Errorf("no MACer matching %q", s)
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"hash"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type DigestAlgorithm string
|
||||
|
||||
const (
|
||||
DigestSha256 DigestAlgorithm = "SHA-256"
|
||||
DigestSha512 = "SHA-512"
|
||||
)
|
||||
|
||||
var digestToDef = map[DigestAlgorithm]crypto.Hash{
|
||||
DigestSha256: crypto.SHA256,
|
||||
DigestSha512: crypto.SHA512,
|
||||
}
|
||||
|
||||
// IsSupportedDigestAlgorithm returns true if hte string is supported by this
|
||||
// library, is not a hash known to be weak, and is supported by the hardware.
|
||||
func IsSupportedDigestAlgorithm(algo string) bool {
|
||||
uc := DigestAlgorithm(strings.ToUpper(algo))
|
||||
c, ok := digestToDef[uc]
|
||||
return ok && c.Available()
|
||||
}
|
||||
|
||||
func getHash(alg DigestAlgorithm) (h hash.Hash, toUse DigestAlgorithm, err error) {
|
||||
upper := DigestAlgorithm(strings.ToUpper(string(alg)))
|
||||
c, ok := digestToDef[upper]
|
||||
if !ok {
|
||||
err = fmt.Errorf("unknown or unsupported Digest algorithm: %s", alg)
|
||||
} else if !c.Available() {
|
||||
err = fmt.Errorf("unavailable Digest algorithm: %s", alg)
|
||||
} else {
|
||||
h = c.New()
|
||||
toUse = upper
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const (
|
||||
digestHeader = "Digest"
|
||||
digestDelim = "="
|
||||
)
|
||||
|
||||
func addDigest(r *http.Request, algo DigestAlgorithm, b []byte) (err error) {
|
||||
_, ok := r.Header[digestHeader]
|
||||
if ok {
|
||||
err = fmt.Errorf("cannot add Digest: Digest is already set")
|
||||
return
|
||||
}
|
||||
var h hash.Hash
|
||||
var a DigestAlgorithm
|
||||
h, a, err = getHash(algo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
h.Write(b)
|
||||
sum := h.Sum(nil)
|
||||
r.Header.Add(digestHeader,
|
||||
fmt.Sprintf("%s%s%s",
|
||||
a,
|
||||
digestDelim,
|
||||
base64.StdEncoding.EncodeToString(sum[:])))
|
||||
return
|
||||
}
|
||||
|
||||
func addDigestResponse(r http.ResponseWriter, algo DigestAlgorithm, b []byte) (err error) {
|
||||
_, ok := r.Header()[digestHeader]
|
||||
if ok {
|
||||
err = fmt.Errorf("cannot add Digest: Digest is already set")
|
||||
return
|
||||
}
|
||||
var h hash.Hash
|
||||
var a DigestAlgorithm
|
||||
h, a, err = getHash(algo)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
h.Write(b)
|
||||
sum := h.Sum(nil)
|
||||
r.Header().Add(digestHeader,
|
||||
fmt.Sprintf("%s%s%s",
|
||||
a,
|
||||
digestDelim,
|
||||
base64.StdEncoding.EncodeToString(sum[:])))
|
||||
return
|
||||
}
|
||||
|
||||
func verifyDigest(r *http.Request, body *bytes.Buffer) (err error) {
|
||||
d := r.Header.Get(digestHeader)
|
||||
if len(d) == 0 {
|
||||
err = fmt.Errorf("cannot verify Digest: request has no Digest header")
|
||||
return
|
||||
}
|
||||
elem := strings.SplitN(d, digestDelim, 2)
|
||||
if len(elem) != 2 {
|
||||
err = fmt.Errorf("cannot verify Digest: malformed Digest: %s", d)
|
||||
return
|
||||
}
|
||||
var h hash.Hash
|
||||
h, _, err = getHash(DigestAlgorithm(elem[0]))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
h.Write(body.Bytes())
|
||||
sum := h.Sum(nil)
|
||||
encSum := base64.StdEncoding.EncodeToString(sum[:])
|
||||
if encSum != elem[1] {
|
||||
err = fmt.Errorf("cannot verify Digest: header Digest does not match the digest of the request body")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
// Implements HTTP request and response signing and verification. Supports the
|
||||
// major MAC and asymmetric key signature algorithms. It has several safety
|
||||
// restrictions: One, none of the widely known non-cryptographically safe
|
||||
// algorithms are permitted; Two, the RSA SHA256 algorithms must be available in
|
||||
// the binary (and it should, barring export restrictions); Finally, the library
|
||||
// assumes either the 'Authorizationn' or 'Signature' headers are to be set (but
|
||||
// not both).
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// Algorithm specifies a cryptography secure algorithm for signing HTTP requests
|
||||
// and responses.
|
||||
type Algorithm string
|
||||
|
||||
const (
|
||||
// MAC-based algoirthms.
|
||||
HMAC_SHA224 Algorithm = hmacPrefix + "-" + sha224String
|
||||
HMAC_SHA256 Algorithm = hmacPrefix + "-" + sha256String
|
||||
HMAC_SHA384 Algorithm = hmacPrefix + "-" + sha384String
|
||||
HMAC_SHA512 Algorithm = hmacPrefix + "-" + sha512String
|
||||
HMAC_RIPEMD160 Algorithm = hmacPrefix + "-" + ripemd160String
|
||||
HMAC_SHA3_224 Algorithm = hmacPrefix + "-" + sha3_224String
|
||||
HMAC_SHA3_256 Algorithm = hmacPrefix + "-" + sha3_256String
|
||||
HMAC_SHA3_384 Algorithm = hmacPrefix + "-" + sha3_384String
|
||||
HMAC_SHA3_512 Algorithm = hmacPrefix + "-" + sha3_512String
|
||||
HMAC_SHA512_224 Algorithm = hmacPrefix + "-" + sha512_224String
|
||||
HMAC_SHA512_256 Algorithm = hmacPrefix + "-" + sha512_256String
|
||||
HMAC_BLAKE2S_256 Algorithm = hmacPrefix + "-" + blake2s_256String
|
||||
HMAC_BLAKE2B_256 Algorithm = hmacPrefix + "-" + blake2b_256String
|
||||
HMAC_BLAKE2B_384 Algorithm = hmacPrefix + "-" + blake2b_384String
|
||||
HMAC_BLAKE2B_512 Algorithm = hmacPrefix + "-" + blake2b_512String
|
||||
BLAKE2S_256 Algorithm = blake2s_256String
|
||||
BLAKE2B_256 Algorithm = blake2b_256String
|
||||
BLAKE2B_384 Algorithm = blake2b_384String
|
||||
BLAKE2B_512 Algorithm = blake2b_512String
|
||||
// RSA-based algorithms.
|
||||
RSA_SHA1 Algorithm = rsaPrefix + "-" + sha1String
|
||||
RSA_SHA224 Algorithm = rsaPrefix + "-" + sha224String
|
||||
// RSA_SHA256 is the default algorithm.
|
||||
RSA_SHA256 Algorithm = rsaPrefix + "-" + sha256String
|
||||
RSA_SHA384 Algorithm = rsaPrefix + "-" + sha384String
|
||||
RSA_SHA512 Algorithm = rsaPrefix + "-" + sha512String
|
||||
RSA_RIPEMD160 Algorithm = rsaPrefix + "-" + ripemd160String
|
||||
// ECDSA algorithms
|
||||
ECDSA_SHA224 Algorithm = ecdsaPrefix + "-" + sha224String
|
||||
ECDSA_SHA256 Algorithm = ecdsaPrefix + "-" + sha256String
|
||||
ECDSA_SHA384 Algorithm = ecdsaPrefix + "-" + sha384String
|
||||
ECDSA_SHA512 Algorithm = ecdsaPrefix + "-" + sha512String
|
||||
ECDSA_RIPEMD160 Algorithm = ecdsaPrefix + "-" + ripemd160String
|
||||
// ED25519 algorithms
|
||||
// can only be SHA512
|
||||
ED25519 Algorithm = ed25519Prefix
|
||||
|
||||
// Just because you can glue things together, doesn't mean they will
|
||||
// work. The following options are not supported.
|
||||
rsa_SHA3_224 Algorithm = rsaPrefix + "-" + sha3_224String
|
||||
rsa_SHA3_256 Algorithm = rsaPrefix + "-" + sha3_256String
|
||||
rsa_SHA3_384 Algorithm = rsaPrefix + "-" + sha3_384String
|
||||
rsa_SHA3_512 Algorithm = rsaPrefix + "-" + sha3_512String
|
||||
rsa_SHA512_224 Algorithm = rsaPrefix + "-" + sha512_224String
|
||||
rsa_SHA512_256 Algorithm = rsaPrefix + "-" + sha512_256String
|
||||
rsa_BLAKE2S_256 Algorithm = rsaPrefix + "-" + blake2s_256String
|
||||
rsa_BLAKE2B_256 Algorithm = rsaPrefix + "-" + blake2b_256String
|
||||
rsa_BLAKE2B_384 Algorithm = rsaPrefix + "-" + blake2b_384String
|
||||
rsa_BLAKE2B_512 Algorithm = rsaPrefix + "-" + blake2b_512String
|
||||
)
|
||||
|
||||
// HTTP Signatures can be applied to different HTTP headers, depending on the
|
||||
// expected application behavior.
|
||||
type SignatureScheme string
|
||||
|
||||
const (
|
||||
// Signature will place the HTTP Signature into the 'Signature' HTTP
|
||||
// header.
|
||||
Signature SignatureScheme = "Signature"
|
||||
// Authorization will place the HTTP Signature into the 'Authorization'
|
||||
// HTTP header.
|
||||
Authorization SignatureScheme = "Authorization"
|
||||
)
|
||||
|
||||
const (
|
||||
// The HTTP Signatures specification uses the "Signature" auth-scheme
|
||||
// for the Authorization header. This is coincidentally named, but not
|
||||
// semantically the same, as the "Signature" HTTP header value.
|
||||
signatureAuthScheme = "Signature"
|
||||
)
|
||||
|
||||
// There are subtle differences to the values in the header. The Authorization
|
||||
// header has an 'auth-scheme' value that must be prefixed to the rest of the
|
||||
// key and values.
|
||||
func (s SignatureScheme) authScheme() string {
|
||||
switch s {
|
||||
case Authorization:
|
||||
return signatureAuthScheme
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// Signers will sign HTTP requests or responses based on the algorithms and
|
||||
// headers selected at creation time.
|
||||
//
|
||||
// Signers are not safe to use between multiple goroutines.
|
||||
//
|
||||
// Note that signatures do set the deprecated 'algorithm' parameter for
|
||||
// backwards compatibility.
|
||||
type Signer interface {
|
||||
// SignRequest signs the request using a private key. The public key id
|
||||
// is used by the HTTP server to identify which key to use to verify the
|
||||
// signature.
|
||||
//
|
||||
// If the Signer was created using a MAC based algorithm, then the key
|
||||
// is expected to be of type []byte. If the Signer was created using an
|
||||
// RSA based algorithm, then the private key is expected to be of type
|
||||
// *rsa.PrivateKey.
|
||||
//
|
||||
// A Digest (RFC 3230) will be added to the request. The body provided
|
||||
// must match the body used in the request, and is allowed to be nil.
|
||||
// The Digest ensures the request body is not tampered with in flight,
|
||||
// and if the signer is created to also sign the "Digest" header, the
|
||||
// HTTP Signature will then ensure both the Digest and body are not both
|
||||
// modified to maliciously represent different content.
|
||||
SignRequest(pKey crypto.PrivateKey, pubKeyId string, r *http.Request, body []byte) error
|
||||
// SignResponse signs the response using a private key. The public key
|
||||
// id is used by the HTTP client to identify which key to use to verify
|
||||
// the signature.
|
||||
//
|
||||
// If the Signer was created using a MAC based algorithm, then the key
|
||||
// is expected to be of type []byte. If the Signer was created using an
|
||||
// RSA based algorithm, then the private key is expected to be of type
|
||||
// *rsa.PrivateKey.
|
||||
//
|
||||
// A Digest (RFC 3230) will be added to the response. The body provided
|
||||
// must match the body written in the response, and is allowed to be
|
||||
// nil. The Digest ensures the response body is not tampered with in
|
||||
// flight, and if the signer is created to also sign the "Digest"
|
||||
// header, the HTTP Signature will then ensure both the Digest and body
|
||||
// are not both modified to maliciously represent different content.
|
||||
SignResponse(pKey crypto.PrivateKey, pubKeyId string, r http.ResponseWriter, body []byte) error
|
||||
}
|
||||
|
||||
// NewSigner creates a new Signer with the provided algorithm preferences to
|
||||
// make HTTP signatures. Only the first available algorithm will be used, which
|
||||
// is returned by this function along with the Signer. If none of the preferred
|
||||
// algorithms were available, then the default algorithm is used. The headers
|
||||
// specified will be included into the HTTP signatures.
|
||||
//
|
||||
// The Digest will also be calculated on a request's body using the provided
|
||||
// digest algorithm, if "Digest" is one of the headers listed.
|
||||
//
|
||||
// The provided scheme determines which header is populated with the HTTP
|
||||
// Signature.
|
||||
//
|
||||
// An error is returned if an unknown or a known cryptographically insecure
|
||||
// Algorithm is provided.
|
||||
func NewSigner(prefs []Algorithm, dAlgo DigestAlgorithm, headers []string, scheme SignatureScheme, expiresIn int64) (Signer, Algorithm, error) {
|
||||
for _, pref := range prefs {
|
||||
s, err := newSigner(pref, dAlgo, headers, scheme, expiresIn)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
return s, pref, err
|
||||
}
|
||||
s, err := newSigner(defaultAlgorithm, dAlgo, headers, scheme, expiresIn)
|
||||
return s, defaultAlgorithm, err
|
||||
}
|
||||
|
||||
// Signers will sign HTTP requests or responses based on the algorithms and
|
||||
// headers selected at creation time.
|
||||
//
|
||||
// Signers are not safe to use between multiple goroutines.
|
||||
//
|
||||
// Note that signatures do set the deprecated 'algorithm' parameter for
|
||||
// backwards compatibility.
|
||||
type SSHSigner interface {
|
||||
// SignRequest signs the request using ssh.Signer.
|
||||
// The public key id is used by the HTTP server to identify which key to use
|
||||
// to verify the signature.
|
||||
//
|
||||
// A Digest (RFC 3230) will be added to the request. The body provided
|
||||
// must match the body used in the request, and is allowed to be nil.
|
||||
// The Digest ensures the request body is not tampered with in flight,
|
||||
// and if the signer is created to also sign the "Digest" header, the
|
||||
// HTTP Signature will then ensure both the Digest and body are not both
|
||||
// modified to maliciously represent different content.
|
||||
SignRequest(pubKeyId string, r *http.Request, body []byte) error
|
||||
// SignResponse signs the response using ssh.Signer. The public key
|
||||
// id is used by the HTTP client to identify which key to use to verify
|
||||
// the signature.
|
||||
//
|
||||
// A Digest (RFC 3230) will be added to the response. The body provided
|
||||
// must match the body written in the response, and is allowed to be
|
||||
// nil. The Digest ensures the response body is not tampered with in
|
||||
// flight, and if the signer is created to also sign the "Digest"
|
||||
// header, the HTTP Signature will then ensure both the Digest and body
|
||||
// are not both modified to maliciously represent different content.
|
||||
SignResponse(pubKeyId string, r http.ResponseWriter, body []byte) error
|
||||
}
|
||||
|
||||
// NewwSSHSigner creates a new Signer using the specified ssh.Signer
|
||||
// At the moment only ed25519 ssh keys are supported.
|
||||
// The headers specified will be included into the HTTP signatures.
|
||||
//
|
||||
// The Digest will also be calculated on a request's body using the provided
|
||||
// digest algorithm, if "Digest" is one of the headers listed.
|
||||
//
|
||||
// The provided scheme determines which header is populated with the HTTP
|
||||
// Signature.
|
||||
func NewSSHSigner(s ssh.Signer, dAlgo DigestAlgorithm, headers []string, scheme SignatureScheme, expiresIn int64) (SSHSigner, Algorithm, error) {
|
||||
sshAlgo := getSSHAlgorithm(s.PublicKey().Type())
|
||||
if sshAlgo == "" {
|
||||
return nil, "", fmt.Errorf("key type: %s not supported yet.", s.PublicKey().Type())
|
||||
}
|
||||
|
||||
signer, err := newSSHSigner(s, sshAlgo, dAlgo, headers, scheme, expiresIn)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return signer, sshAlgo, nil
|
||||
}
|
||||
|
||||
func getSSHAlgorithm(pkType string) Algorithm {
|
||||
switch {
|
||||
case strings.HasPrefix(pkType, sshPrefix+"-"+ed25519Prefix):
|
||||
return ED25519
|
||||
case strings.HasPrefix(pkType, sshPrefix+"-"+rsaPrefix):
|
||||
return RSA_SHA1
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// Verifier verifies HTTP Signatures.
|
||||
//
|
||||
// It will determine which of the supported headers has the parameters
|
||||
// that define the signature.
|
||||
//
|
||||
// Verifiers are not safe to use between multiple goroutines.
|
||||
//
|
||||
// Note that verification ignores the deprecated 'algorithm' parameter.
|
||||
type Verifier interface {
|
||||
// KeyId gets the public key id that the signature is signed with.
|
||||
//
|
||||
// Note that the application is expected to determine the algorithm
|
||||
// used based on metadata or out-of-band information for this key id.
|
||||
KeyId() string
|
||||
// Verify accepts the public key specified by KeyId and returns an
|
||||
// error if verification fails or if the signature is malformed. The
|
||||
// algorithm must be the one used to create the signature in order to
|
||||
// pass verification. The algorithm is determined based on metadata or
|
||||
// out-of-band information for the key id.
|
||||
//
|
||||
// If the signature was created using a MAC based algorithm, then the
|
||||
// key is expected to be of type []byte. If the signature was created
|
||||
// using an RSA based algorithm, then the public key is expected to be
|
||||
// of type *rsa.PublicKey.
|
||||
Verify(pKey crypto.PublicKey, algo Algorithm) error
|
||||
}
|
||||
|
||||
const (
|
||||
// host is treated specially because golang may not include it in the
|
||||
// request header map on the server side of a request.
|
||||
hostHeader = "Host"
|
||||
)
|
||||
|
||||
// NewVerifier verifies the given request. It returns an error if the HTTP
|
||||
// Signature parameters are not present in any headers, are present in more than
|
||||
// one header, are malformed, or are missing required parameters. It ignores
|
||||
// unknown HTTP Signature parameters.
|
||||
func NewVerifier(r *http.Request) (Verifier, error) {
|
||||
h := r.Header
|
||||
if _, hasHostHeader := h[hostHeader]; len(r.Host) > 0 && !hasHostHeader {
|
||||
h[hostHeader] = []string{r.Host}
|
||||
}
|
||||
return newVerifier(h, func(h http.Header, toInclude []string, created int64, expires int64) (string, error) {
|
||||
return signatureString(h, toInclude, addRequestTarget(r), created, expires)
|
||||
})
|
||||
}
|
||||
|
||||
// NewResponseVerifier verifies the given response. It returns errors under the
|
||||
// same conditions as NewVerifier.
|
||||
func NewResponseVerifier(r *http.Response) (Verifier, error) {
|
||||
return newVerifier(r.Header, func(h http.Header, toInclude []string, created int64, expires int64) (string, error) {
|
||||
return signatureString(h, toInclude, requestTargetNotPermitted, created, expires)
|
||||
})
|
||||
}
|
||||
|
||||
func newSSHSigner(sshSigner ssh.Signer, algo Algorithm, dAlgo DigestAlgorithm, headers []string, scheme SignatureScheme, expiresIn int64) (SSHSigner, error) {
|
||||
var expires, created int64 = 0, 0
|
||||
|
||||
if expiresIn != 0 {
|
||||
created = time.Now().Unix()
|
||||
expires = created + expiresIn
|
||||
}
|
||||
|
||||
s, err := signerFromSSHSigner(sshSigner, string(algo))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("no crypto implementation available for ssh algo %q", algo)
|
||||
}
|
||||
|
||||
a := &asymmSSHSigner{
|
||||
asymmSigner: &asymmSigner{
|
||||
s: s,
|
||||
dAlgo: dAlgo,
|
||||
headers: headers,
|
||||
targetHeader: scheme,
|
||||
prefix: scheme.authScheme(),
|
||||
created: created,
|
||||
expires: expires,
|
||||
},
|
||||
}
|
||||
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func newSigner(algo Algorithm, dAlgo DigestAlgorithm, headers []string, scheme SignatureScheme, expiresIn int64) (Signer, error) {
|
||||
|
||||
var expires, created int64 = 0, 0
|
||||
if expiresIn != 0 {
|
||||
created = time.Now().Unix()
|
||||
expires = created + expiresIn
|
||||
}
|
||||
|
||||
s, err := signerFromString(string(algo))
|
||||
if err == nil {
|
||||
a := &asymmSigner{
|
||||
s: s,
|
||||
dAlgo: dAlgo,
|
||||
headers: headers,
|
||||
targetHeader: scheme,
|
||||
prefix: scheme.authScheme(),
|
||||
created: created,
|
||||
expires: expires,
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
m, err := macerFromString(string(algo))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("no crypto implementation available for %q", algo)
|
||||
}
|
||||
c := &macSigner{
|
||||
m: m,
|
||||
dAlgo: dAlgo,
|
||||
headers: headers,
|
||||
targetHeader: scheme,
|
||||
prefix: scheme.authScheme(),
|
||||
created: created,
|
||||
expires: expires,
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
// Signature Parameters
|
||||
keyIdParameter = "keyId"
|
||||
algorithmParameter = "algorithm"
|
||||
headersParameter = "headers"
|
||||
signatureParameter = "signature"
|
||||
prefixSeparater = " "
|
||||
parameterKVSeparater = "="
|
||||
parameterValueDelimiter = "\""
|
||||
parameterSeparater = ","
|
||||
headerParameterValueDelim = " "
|
||||
// RequestTarget specifies to include the http request method and
|
||||
// entire URI in the signature. Pass it as a header to NewSigner.
|
||||
RequestTarget = "(request-target)"
|
||||
createdKey = "created"
|
||||
expiresKey = "expires"
|
||||
dateHeader = "date"
|
||||
|
||||
// Signature String Construction
|
||||
headerFieldDelimiter = ": "
|
||||
headersDelimiter = "\n"
|
||||
headerValueDelimiter = ", "
|
||||
requestTargetSeparator = " "
|
||||
)
|
||||
|
||||
var defaultHeaders = []string{dateHeader}
|
||||
|
||||
var _ Signer = &macSigner{}
|
||||
|
||||
type macSigner struct {
|
||||
m macer
|
||||
makeDigest bool
|
||||
dAlgo DigestAlgorithm
|
||||
headers []string
|
||||
targetHeader SignatureScheme
|
||||
prefix string
|
||||
created int64
|
||||
expires int64
|
||||
}
|
||||
|
||||
func (m *macSigner) SignRequest(pKey crypto.PrivateKey, pubKeyId string, r *http.Request, body []byte) error {
|
||||
if body != nil {
|
||||
err := addDigest(r, m.dAlgo, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s, err := m.signatureString(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc, err := m.signSignature(pKey, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setSignatureHeader(r.Header, string(m.targetHeader), m.prefix, pubKeyId, m.m.String(), enc, m.headers, m.created, m.expires)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *macSigner) SignResponse(pKey crypto.PrivateKey, pubKeyId string, r http.ResponseWriter, body []byte) error {
|
||||
if body != nil {
|
||||
err := addDigestResponse(r, m.dAlgo, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s, err := m.signatureStringResponse(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc, err := m.signSignature(pKey, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setSignatureHeader(r.Header(), string(m.targetHeader), m.prefix, pubKeyId, m.m.String(), enc, m.headers, m.created, m.expires)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *macSigner) signSignature(pKey crypto.PrivateKey, s string) (string, error) {
|
||||
pKeyBytes, ok := pKey.([]byte)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("private key for MAC signing must be of type []byte")
|
||||
}
|
||||
sig, err := m.m.Sign([]byte(s), pKeyBytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
enc := base64.StdEncoding.EncodeToString(sig)
|
||||
return enc, nil
|
||||
}
|
||||
|
||||
func (m *macSigner) signatureString(r *http.Request) (string, error) {
|
||||
return signatureString(r.Header, m.headers, addRequestTarget(r), m.created, m.expires)
|
||||
}
|
||||
|
||||
func (m *macSigner) signatureStringResponse(r http.ResponseWriter) (string, error) {
|
||||
return signatureString(r.Header(), m.headers, requestTargetNotPermitted, m.created, m.expires)
|
||||
}
|
||||
|
||||
var _ Signer = &asymmSigner{}
|
||||
|
||||
type asymmSigner struct {
|
||||
s signer
|
||||
makeDigest bool
|
||||
dAlgo DigestAlgorithm
|
||||
headers []string
|
||||
targetHeader SignatureScheme
|
||||
prefix string
|
||||
created int64
|
||||
expires int64
|
||||
}
|
||||
|
||||
func (a *asymmSigner) SignRequest(pKey crypto.PrivateKey, pubKeyId string, r *http.Request, body []byte) error {
|
||||
if body != nil {
|
||||
err := addDigest(r, a.dAlgo, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s, err := a.signatureString(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc, err := a.signSignature(pKey, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setSignatureHeader(r.Header, string(a.targetHeader), a.prefix, pubKeyId, a.s.String(), enc, a.headers, a.created, a.expires)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *asymmSigner) SignResponse(pKey crypto.PrivateKey, pubKeyId string, r http.ResponseWriter, body []byte) error {
|
||||
if body != nil {
|
||||
err := addDigestResponse(r, a.dAlgo, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s, err := a.signatureStringResponse(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
enc, err := a.signSignature(pKey, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setSignatureHeader(r.Header(), string(a.targetHeader), a.prefix, pubKeyId, a.s.String(), enc, a.headers, a.created, a.expires)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *asymmSigner) signSignature(pKey crypto.PrivateKey, s string) (string, error) {
|
||||
sig, err := a.s.Sign(rand.Reader, pKey, []byte(s))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
enc := base64.StdEncoding.EncodeToString(sig)
|
||||
return enc, nil
|
||||
}
|
||||
|
||||
func (a *asymmSigner) signatureString(r *http.Request) (string, error) {
|
||||
return signatureString(r.Header, a.headers, addRequestTarget(r), a.created, a.expires)
|
||||
}
|
||||
|
||||
func (a *asymmSigner) signatureStringResponse(r http.ResponseWriter) (string, error) {
|
||||
return signatureString(r.Header(), a.headers, requestTargetNotPermitted, a.created, a.expires)
|
||||
}
|
||||
|
||||
var _ SSHSigner = &asymmSSHSigner{}
|
||||
|
||||
type asymmSSHSigner struct {
|
||||
*asymmSigner
|
||||
}
|
||||
|
||||
func (a *asymmSSHSigner) SignRequest(pubKeyId string, r *http.Request, body []byte) error {
|
||||
return a.asymmSigner.SignRequest(nil, pubKeyId, r, body)
|
||||
}
|
||||
|
||||
func (a *asymmSSHSigner) SignResponse(pubKeyId string, r http.ResponseWriter, body []byte) error {
|
||||
return a.asymmSigner.SignResponse(nil, pubKeyId, r, body)
|
||||
}
|
||||
|
||||
func setSignatureHeader(h http.Header, targetHeader, prefix, pubKeyId, algo, enc string, headers []string, created int64, expires int64) {
|
||||
if len(headers) == 0 {
|
||||
headers = defaultHeaders
|
||||
}
|
||||
var b bytes.Buffer
|
||||
// KeyId
|
||||
b.WriteString(prefix)
|
||||
if len(prefix) > 0 {
|
||||
b.WriteString(prefixSeparater)
|
||||
}
|
||||
b.WriteString(keyIdParameter)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(pubKeyId)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(parameterSeparater)
|
||||
// Algorithm
|
||||
b.WriteString(algorithmParameter)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString("hs2019") //real algorithm is hidden, see newest version of spec draft
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(parameterSeparater)
|
||||
|
||||
hasCreated := false
|
||||
hasExpires := false
|
||||
for _, h := range headers {
|
||||
val := strings.ToLower(h)
|
||||
if val == "("+createdKey+")" {
|
||||
hasCreated = true
|
||||
} else if val == "("+expiresKey+")" {
|
||||
hasExpires = true
|
||||
}
|
||||
}
|
||||
|
||||
// Created
|
||||
if hasCreated == true {
|
||||
b.WriteString(createdKey)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(strconv.FormatInt(created, 10))
|
||||
b.WriteString(parameterSeparater)
|
||||
}
|
||||
|
||||
// Expires
|
||||
if hasExpires == true {
|
||||
b.WriteString(expiresKey)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(strconv.FormatInt(expires, 10))
|
||||
b.WriteString(parameterSeparater)
|
||||
}
|
||||
|
||||
// Headers
|
||||
b.WriteString(headersParameter)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
for i, h := range headers {
|
||||
b.WriteString(strings.ToLower(h))
|
||||
if i != len(headers)-1 {
|
||||
b.WriteString(headerParameterValueDelim)
|
||||
}
|
||||
}
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(parameterSeparater)
|
||||
// Signature
|
||||
b.WriteString(signatureParameter)
|
||||
b.WriteString(parameterKVSeparater)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
b.WriteString(enc)
|
||||
b.WriteString(parameterValueDelimiter)
|
||||
h.Add(targetHeader, b.String())
|
||||
}
|
||||
|
||||
func requestTargetNotPermitted(b *bytes.Buffer) error {
|
||||
return fmt.Errorf("cannot sign with %q on anything other than an http request", RequestTarget)
|
||||
}
|
||||
|
||||
func addRequestTarget(r *http.Request) func(b *bytes.Buffer) error {
|
||||
return func(b *bytes.Buffer) error {
|
||||
b.WriteString(RequestTarget)
|
||||
b.WriteString(headerFieldDelimiter)
|
||||
b.WriteString(strings.ToLower(r.Method))
|
||||
b.WriteString(requestTargetSeparator)
|
||||
b.WriteString(r.URL.Path)
|
||||
|
||||
if r.URL.RawQuery != "" {
|
||||
b.WriteString("?")
|
||||
b.WriteString(r.URL.RawQuery)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func signatureString(values http.Header, include []string, requestTargetFn func(b *bytes.Buffer) error, created int64, expires int64) (string, error) {
|
||||
if len(include) == 0 {
|
||||
include = defaultHeaders
|
||||
}
|
||||
var b bytes.Buffer
|
||||
for n, i := range include {
|
||||
i := strings.ToLower(i)
|
||||
if i == RequestTarget {
|
||||
err := requestTargetFn(&b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else if i == "("+expiresKey+")" {
|
||||
if expires == 0 {
|
||||
return "", fmt.Errorf("missing expires value")
|
||||
}
|
||||
b.WriteString(i)
|
||||
b.WriteString(headerFieldDelimiter)
|
||||
b.WriteString(strconv.FormatInt(expires, 10))
|
||||
} else if i == "("+createdKey+")" {
|
||||
if created == 0 {
|
||||
return "", fmt.Errorf("missing created value")
|
||||
}
|
||||
b.WriteString(i)
|
||||
b.WriteString(headerFieldDelimiter)
|
||||
b.WriteString(strconv.FormatInt(created, 10))
|
||||
} else {
|
||||
hv, ok := values[textproto.CanonicalMIMEHeaderKey(i)]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing header %q", i)
|
||||
}
|
||||
b.WriteString(i)
|
||||
b.WriteString(headerFieldDelimiter)
|
||||
for i, v := range hv {
|
||||
b.WriteString(strings.TrimSpace(v))
|
||||
if i < len(hv)-1 {
|
||||
b.WriteString(headerValueDelimiter)
|
||||
}
|
||||
}
|
||||
}
|
||||
if n < len(include)-1 {
|
||||
b.WriteString(headersDelimiter)
|
||||
}
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
package httpsig
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Verifier = &verifier{}
|
||||
|
||||
type verifier struct {
|
||||
header http.Header
|
||||
kId string
|
||||
signature string
|
||||
created int64
|
||||
expires int64
|
||||
headers []string
|
||||
sigStringFn func(http.Header, []string, int64, int64) (string, error)
|
||||
}
|
||||
|
||||
func newVerifier(h http.Header, sigStringFn func(http.Header, []string, int64, int64) (string, error)) (*verifier, error) {
|
||||
scheme, s, err := getSignatureScheme(h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kId, sig, headers, created, expires, err := getSignatureComponents(scheme, s)
|
||||
if created != 0 {
|
||||
//check if created is not in the future, we assume a maximum clock offset of 10 seconds
|
||||
now := time.Now().Unix()
|
||||
if created-now > 10 {
|
||||
return nil, errors.New("created is in the future")
|
||||
}
|
||||
}
|
||||
if expires != 0 {
|
||||
//check if expires is in the past, we assume a maximum clock offset of 10 seconds
|
||||
now := time.Now().Unix()
|
||||
if now-expires > 10 {
|
||||
return nil, errors.New("signature expired")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &verifier{
|
||||
header: h,
|
||||
kId: kId,
|
||||
signature: sig,
|
||||
created: created,
|
||||
expires: expires,
|
||||
headers: headers,
|
||||
sigStringFn: sigStringFn,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (v *verifier) KeyId() string {
|
||||
return v.kId
|
||||
}
|
||||
|
||||
func (v *verifier) Verify(pKey crypto.PublicKey, algo Algorithm) error {
|
||||
s, err := signerFromString(string(algo))
|
||||
if err == nil {
|
||||
return v.asymmVerify(s, pKey)
|
||||
}
|
||||
m, err := macerFromString(string(algo))
|
||||
if err == nil {
|
||||
return v.macVerify(m, pKey)
|
||||
}
|
||||
return fmt.Errorf("no crypto implementation available for %q", algo)
|
||||
}
|
||||
|
||||
func (v *verifier) macVerify(m macer, pKey crypto.PublicKey) error {
|
||||
key, ok := pKey.([]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("public key for MAC verifying must be of type []byte")
|
||||
}
|
||||
signature, err := v.sigStringFn(v.header, v.headers, v.created, v.expires)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actualMAC, err := base64.StdEncoding.DecodeString(v.signature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ok, err = m.Equal([]byte(signature), actualMAC, key)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !ok {
|
||||
return fmt.Errorf("invalid http signature")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *verifier) asymmVerify(s signer, pKey crypto.PublicKey) error {
|
||||
toHash, err := v.sigStringFn(v.header, v.headers, v.created, v.expires)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
signature, err := base64.StdEncoding.DecodeString(v.signature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.Verify(pKey, []byte(toHash), signature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getSignatureScheme(h http.Header) (scheme SignatureScheme, val string, err error) {
|
||||
s := h.Get(string(Signature))
|
||||
sigHasAll := strings.Contains(s, keyIdParameter) ||
|
||||
strings.Contains(s, headersParameter) ||
|
||||
strings.Contains(s, signatureParameter)
|
||||
a := h.Get(string(Authorization))
|
||||
authHasAll := strings.Contains(a, keyIdParameter) ||
|
||||
strings.Contains(a, headersParameter) ||
|
||||
strings.Contains(a, signatureParameter)
|
||||
if sigHasAll && authHasAll {
|
||||
err = fmt.Errorf("both %q and %q have signature parameters", Signature, Authorization)
|
||||
return
|
||||
} else if !sigHasAll && !authHasAll {
|
||||
err = fmt.Errorf("neither %q nor %q have signature parameters", Signature, Authorization)
|
||||
return
|
||||
} else if sigHasAll {
|
||||
val = s
|
||||
scheme = Signature
|
||||
return
|
||||
} else { // authHasAll
|
||||
val = a
|
||||
scheme = Authorization
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func getSignatureComponents(scheme SignatureScheme, s string) (kId, sig string, headers []string, created int64, expires int64, err error) {
|
||||
if as := scheme.authScheme(); len(as) > 0 {
|
||||
s = strings.TrimPrefix(s, as+prefixSeparater)
|
||||
}
|
||||
params := strings.Split(s, parameterSeparater)
|
||||
for _, p := range params {
|
||||
kv := strings.SplitN(p, parameterKVSeparater, 2)
|
||||
if len(kv) != 2 {
|
||||
err = fmt.Errorf("malformed http signature parameter: %v", kv)
|
||||
return
|
||||
}
|
||||
k := kv[0]
|
||||
v := strings.Trim(kv[1], parameterValueDelimiter)
|
||||
switch k {
|
||||
case keyIdParameter:
|
||||
kId = v
|
||||
case createdKey:
|
||||
created, err = strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
case expiresKey:
|
||||
expires, err = strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
case algorithmParameter:
|
||||
// Deprecated, ignore
|
||||
case headersParameter:
|
||||
headers = strings.Split(v, headerParameterValueDelim)
|
||||
case signatureParameter:
|
||||
sig = v
|
||||
default:
|
||||
// Ignore unrecognized parameters
|
||||
}
|
||||
}
|
||||
if len(kId) == 0 {
|
||||
err = fmt.Errorf("missing %q parameter in http signature", keyIdParameter)
|
||||
} else if len(sig) == 0 {
|
||||
err = fmt.Errorf("missing %q parameter in http signature", signatureParameter)
|
||||
} else if len(headers) == 0 { // Optional
|
||||
headers = defaultHeaders
|
||||
}
|
||||
return
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
# 1.9.0 (Mar 30, 2026)
|
||||
|
||||
ENHANCEMENTS:
|
||||
|
||||
Support parsing versions with custom prefixes via opt-in option in https://github.com/hashicorp/go-version/pull/79
|
||||
|
||||
INTERNAL:
|
||||
|
||||
- Bump the github-actions-backward-compatible group across 1 directory with 2 updates in https://github.com/hashicorp/go-version/pull/179
|
||||
- Bump the github-actions-breaking group with 4 updates in https://github.com/hashicorp/go-version/pull/180
|
||||
- Bump the github-actions-backward-compatible group with 3 updates in https://github.com/hashicorp/go-version/pull/182
|
||||
- Update GitHub Actions to trigger on pull requests and update go version in https://github.com/hashicorp/go-version/pull/185
|
||||
- Bump actions/upload-artifact from 6.0.0 to 7.0.0 in the github-actions-breaking group across 1 directory in https://github.com/hashicorp/go-version/pull/183
|
||||
- Bump the github-actions-backward-compatible group across 1 directory with 2 updates in https://github.com/hashicorp/go-version/pull/186
|
||||
|
||||
# 1.8.0 (Nov 28, 2025)
|
||||
|
||||
ENHANCEMENTS:
|
||||
|
||||
- Add benchmark test for version.String() in https://github.com/hashicorp/go-version/pull/159
|
||||
- Bytes implementation in https://github.com/hashicorp/go-version/pull/161
|
||||
|
||||
INTERNAL:
|
||||
|
||||
- Add CODEOWNERS file in .github/CODEOWNERS in https://github.com/hashicorp/go-version/pull/145
|
||||
- Linting in https://github.com/hashicorp/go-version/pull/151
|
||||
- Correct typos in comments in https://github.com/hashicorp/go-version/pull/134
|
||||
- Migrate GitHub Actions updates from TSCCR to Dependabot in https://github.com/hashicorp/go-version/pull/155
|
||||
- Bump the github-actions-backward-compatible group with 2 updates in https://github.com/hashicorp/go-version/pull/157
|
||||
- Update doc reference in README in https://github.com/hashicorp/go-version/pull/135
|
||||
- Bump the github-actions-breaking group with 3 updates in https://github.com/hashicorp/go-version/pull/156
|
||||
- [Compliance] - PR Template Changes Required in https://github.com/hashicorp/go-version/pull/158
|
||||
- Bump actions/cache from 4.2.3 to 4.2.4 in the github-actions-backward-compatible group in https://github.com/hashicorp/go-version/pull/167
|
||||
- Bump actions/checkout from 4.2.2 to 5.0.0 in the github-actions-breaking group in https://github.com/hashicorp/go-version/pull/166
|
||||
- Bump the github-actions-breaking group across 1 directory with 2 updates in https://github.com/hashicorp/go-version/pull/171
|
||||
- [IND-4226] [COMPLIANCE] Update Copyright Headers in https://github.com/hashicorp/go-version/pull/172
|
||||
- drop init() in https://github.com/hashicorp/go-version/pull/175
|
||||
|
||||
# 1.7.0 (May 24, 2024)
|
||||
|
||||
ENHANCEMENTS:
|
||||
|
||||
- Remove `reflect` dependency ([#91](https://github.com/hashicorp/go-version/pull/91))
|
||||
- Implement the `database/sql.Scanner` and `database/sql/driver.Value` interfaces for `Version` ([#133](https://github.com/hashicorp/go-version/pull/133))
|
||||
|
||||
INTERNAL:
|
||||
|
||||
- [COMPLIANCE] Add Copyright and License Headers ([#115](https://github.com/hashicorp/go-version/pull/115))
|
||||
- [COMPLIANCE] Update MPL-2.0 LICENSE ([#105](https://github.com/hashicorp/go-version/pull/105))
|
||||
- Bump actions/cache from 3.0.11 to 3.2.5 ([#116](https://github.com/hashicorp/go-version/pull/116))
|
||||
- Bump actions/checkout from 3.2.0 to 3.3.0 ([#111](https://github.com/hashicorp/go-version/pull/111))
|
||||
- Bump actions/upload-artifact from 3.1.1 to 3.1.2 ([#112](https://github.com/hashicorp/go-version/pull/112))
|
||||
- GHA Migration ([#103](https://github.com/hashicorp/go-version/pull/103))
|
||||
- github: Pin external GitHub Actions to hashes ([#107](https://github.com/hashicorp/go-version/pull/107))
|
||||
- SEC-090: Automated trusted workflow pinning (2023-04-05) ([#124](https://github.com/hashicorp/go-version/pull/124))
|
||||
- update readme ([#104](https://github.com/hashicorp/go-version/pull/104))
|
||||
|
||||
# 1.6.0 (June 28, 2022)
|
||||
|
||||
FEATURES:
|
||||
|
||||
- Add `Prerelease` function to `Constraint` to return true if the version includes a prerelease field ([#100](https://github.com/hashicorp/go-version/pull/100))
|
||||
|
||||
# 1.5.0 (May 18, 2022)
|
||||
|
||||
FEATURES:
|
||||
|
||||
- Use `encoding` `TextMarshaler` & `TextUnmarshaler` instead of JSON equivalents ([#95](https://github.com/hashicorp/go-version/pull/95))
|
||||
- Add JSON handlers to allow parsing from/to JSON ([#93](https://github.com/hashicorp/go-version/pull/93))
|
||||
|
||||
# 1.4.0 (January 5, 2022)
|
||||
|
||||
FEATURES:
|
||||
|
||||
- Introduce `MustConstraints()` ([#87](https://github.com/hashicorp/go-version/pull/87))
|
||||
- `Constraints`: Introduce `Equals()` and `sort.Interface` methods ([#88](https://github.com/hashicorp/go-version/pull/88))
|
||||
|
||||
# 1.3.0 (March 31, 2021)
|
||||
|
||||
Please note that CHANGELOG.md does not exist in the source code prior to this release.
|
||||
|
||||
FEATURES:
|
||||
- Add `Core` function to return a version without prerelease or metadata ([#85](https://github.com/hashicorp/go-version/pull/85))
|
||||
|
||||
# 1.2.1 (June 17, 2020)
|
||||
|
||||
BUG FIXES:
|
||||
- Prevent `Version.Equal` method from panicking on `nil` encounter ([#73](https://github.com/hashicorp/go-version/pull/73))
|
||||
|
||||
# 1.2.0 (April 23, 2019)
|
||||
|
||||
FEATURES:
|
||||
- Add `GreaterThanOrEqual` and `LessThanOrEqual` helper methods ([#53](https://github.com/hashicorp/go-version/pull/53))
|
||||
|
||||
# 1.1.0 (Jan 07, 2019)
|
||||
|
||||
FEATURES:
|
||||
- Add `NewSemver` constructor ([#45](https://github.com/hashicorp/go-version/pull/45))
|
||||
|
||||
# 1.0.0 (August 24, 2018)
|
||||
|
||||
Initial release.
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
Copyright IBM Corp. 2014, 2025
|
||||
|
||||
Mozilla Public License, version 2.0
|
||||
|
||||
1. Definitions
|
||||
|
||||
1.1. “Contributor”
|
||||
|
||||
means each individual or legal entity that creates, contributes to the
|
||||
creation of, or owns Covered Software.
|
||||
|
||||
1.2. “Contributor Version”
|
||||
|
||||
means the combination of the Contributions of others (if any) used by a
|
||||
Contributor and that particular Contributor’s Contribution.
|
||||
|
||||
1.3. “Contribution”
|
||||
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. “Covered Software”
|
||||
|
||||
means Source Code Form to which the initial Contributor has attached the
|
||||
notice in Exhibit A, the Executable Form of such Source Code Form, and
|
||||
Modifications of such Source Code Form, in each case including portions
|
||||
thereof.
|
||||
|
||||
1.5. “Incompatible With Secondary Licenses”
|
||||
means
|
||||
|
||||
a. that the initial Contributor has attached the notice described in
|
||||
Exhibit B to the Covered Software; or
|
||||
|
||||
b. that the Covered Software was made available under the terms of version
|
||||
1.1 or earlier of the License, but not also under the terms of a
|
||||
Secondary License.
|
||||
|
||||
1.6. “Executable Form”
|
||||
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. “Larger Work”
|
||||
|
||||
means a work that combines Covered Software with other material, in a separate
|
||||
file or files, that is not Covered Software.
|
||||
|
||||
1.8. “License”
|
||||
|
||||
means this document.
|
||||
|
||||
1.9. “Licensable”
|
||||
|
||||
means having the right to grant, to the maximum extent possible, whether at the
|
||||
time of the initial grant or subsequently, any and all of the rights conveyed by
|
||||
this License.
|
||||
|
||||
1.10. “Modifications”
|
||||
|
||||
means any of the following:
|
||||
|
||||
a. any file in Source Code Form that results from an addition to, deletion
|
||||
from, or modification of the contents of Covered Software; or
|
||||
|
||||
b. any new file in Source Code Form that contains any Covered Software.
|
||||
|
||||
1.11. “Patent Claims” of a Contributor
|
||||
|
||||
means any patent claim(s), including without limitation, method, process,
|
||||
and apparatus claims, in any patent Licensable by such Contributor that
|
||||
would be infringed, but for the grant of the License, by the making,
|
||||
using, selling, offering for sale, having made, import, or transfer of
|
||||
either its Contributions or its Contributor Version.
|
||||
|
||||
1.12. “Secondary License”
|
||||
|
||||
means either the GNU General Public License, Version 2.0, the GNU Lesser
|
||||
General Public License, Version 2.1, the GNU Affero General Public
|
||||
License, Version 3.0, or any later versions of those licenses.
|
||||
|
||||
1.13. “Source Code Form”
|
||||
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. “You” (or “Your”)
|
||||
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, “You” includes any entity that controls, is
|
||||
controlled by, or is under common control with You. For purposes of this
|
||||
definition, “control” means (a) the power, direct or indirect, to cause
|
||||
the direction or management of such entity, whether by contract or
|
||||
otherwise, or (b) ownership of more than fifty percent (50%) of the
|
||||
outstanding shares or beneficial ownership of such entity.
|
||||
|
||||
|
||||
2. License Grants and Conditions
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
a. under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or as
|
||||
part of a Larger Work; and
|
||||
|
||||
b. under Patent Claims of such Contributor to make, use, sell, offer for
|
||||
sale, have made, import, and otherwise transfer either its Contributions
|
||||
or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution become
|
||||
effective for each Contribution on the date the Contributor first distributes
|
||||
such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under this
|
||||
License. No additional rights or licenses will be implied from the distribution
|
||||
or licensing of Covered Software under this License. Notwithstanding Section
|
||||
2.1(b) above, no patent license is granted by a Contributor:
|
||||
|
||||
a. for any code that a Contributor has removed from Covered Software; or
|
||||
|
||||
b. for infringements caused by: (i) Your and any other third party’s
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
c. under Patent Claims infringed by Covered Software in the absence of its
|
||||
Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks, or
|
||||
logos of any Contributor (except as may be necessary to comply with the
|
||||
notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this License
|
||||
(see Section 10.2) or under the terms of a Secondary License (if permitted
|
||||
under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its Contributions
|
||||
are its original creation(s) or it has sufficient rights to grant the
|
||||
rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under applicable
|
||||
copyright doctrines of fair use, fair dealing, or other equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
|
||||
Section 2.1.
|
||||
|
||||
|
||||
3. Responsibilities
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under the
|
||||
terms of this License. You must inform recipients that the Source Code Form
|
||||
of the Covered Software is governed by the terms of this License, and how
|
||||
they can obtain a copy of this License. You may not attempt to alter or
|
||||
restrict the recipients’ rights in the Source Code Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
a. such Covered Software must also be made available in Source Code Form,
|
||||
as described in Section 3.1, and You must inform recipients of the
|
||||
Executable Form how they can obtain a copy of such Source Code Form by
|
||||
reasonable means in a timely manner, at a charge no more than the cost
|
||||
of distribution to the recipient; and
|
||||
|
||||
b. You may distribute such Executable Form under the terms of this License,
|
||||
or sublicense it under different terms, provided that the license for
|
||||
the Executable Form does not attempt to limit or alter the recipients’
|
||||
rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for the
|
||||
Covered Software. If the Larger Work is a combination of Covered Software
|
||||
with a work governed by one or more Secondary Licenses, and the Covered
|
||||
Software is not Incompatible With Secondary Licenses, this License permits
|
||||
You to additionally distribute such Covered Software under the terms of
|
||||
such Secondary License(s), so that the recipient of the Larger Work may, at
|
||||
their option, further distribute the Covered Software under the terms of
|
||||
either this License or such Secondary License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices (including
|
||||
copyright notices, patent notices, disclaimers of warranty, or limitations
|
||||
of liability) contained within the Source Code Form of the Covered
|
||||
Software, except that You may alter any license notices to the extent
|
||||
required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on behalf
|
||||
of any Contributor. You must make it absolutely clear that any such
|
||||
warranty, support, indemnity, or liability obligation is offered by You
|
||||
alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this License
|
||||
with respect to some or all of the Covered Software due to statute, judicial
|
||||
order, or regulation then You must: (a) comply with the terms of this License
|
||||
to the maximum extent possible; and (b) describe the limitations and the code
|
||||
they affect. Such description must be placed in a text file included with all
|
||||
distributions of the Covered Software under this License. Except to the
|
||||
extent prohibited by statute or regulation, such description must be
|
||||
sufficiently detailed for a recipient of ordinary skill to be able to
|
||||
understand it.
|
||||
|
||||
5. Termination
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically if You
|
||||
fail to comply with any of its terms. However, if You become compliant,
|
||||
then the rights granted under this License from a particular Contributor
|
||||
are reinstated (a) provisionally, unless and until such Contributor
|
||||
explicitly and finally terminates Your grants, and (b) on an ongoing basis,
|
||||
if such Contributor fails to notify You of the non-compliance by some
|
||||
reasonable means prior to 60 days after You have come back into compliance.
|
||||
Moreover, Your grants from a particular Contributor are reinstated on an
|
||||
ongoing basis if such Contributor notifies You of the non-compliance by
|
||||
some reasonable means, this is the first time You have received notice of
|
||||
non-compliance with this License from such Contributor, and You become
|
||||
compliant prior to 30 days after Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions, counter-claims,
|
||||
and cross-claims) alleging that a Contributor Version directly or
|
||||
indirectly infringes any patent, then the rights granted to You by any and
|
||||
all Contributors for the Covered Software under Section 2.1 of this License
|
||||
shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
|
||||
license agreements (excluding distributors and resellers) which have been
|
||||
validly granted by You or Your distributors under this License prior to
|
||||
termination shall survive termination.
|
||||
|
||||
6. Disclaimer of Warranty
|
||||
|
||||
Covered Software is provided under this License on an “as is” basis, without
|
||||
warranty of any kind, either expressed, implied, or statutory, including,
|
||||
without limitation, warranties that the Covered Software is free of defects,
|
||||
merchantable, fit for a particular purpose or non-infringing. The entire
|
||||
risk as to the quality and performance of the Covered Software is with You.
|
||||
Should any Covered Software prove defective in any respect, You (not any
|
||||
Contributor) assume the cost of any necessary servicing, repair, or
|
||||
correction. This disclaimer of warranty constitutes an essential part of this
|
||||
License. No use of any Covered Software is authorized under this License
|
||||
except under this disclaimer.
|
||||
|
||||
7. Limitation of Liability
|
||||
|
||||
Under no circumstances and under no legal theory, whether tort (including
|
||||
negligence), contract, or otherwise, shall any Contributor, or anyone who
|
||||
distributes Covered Software as permitted above, be liable to You for any
|
||||
direct, indirect, special, incidental, or consequential damages of any
|
||||
character including, without limitation, damages for lost profits, loss of
|
||||
goodwill, work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses, even if such party shall have been
|
||||
informed of the possibility of such damages. This limitation of liability
|
||||
shall not apply to liability for death or personal injury resulting from such
|
||||
party’s negligence to the extent applicable law prohibits such limitation.
|
||||
Some jurisdictions do not allow the exclusion or limitation of incidental or
|
||||
consequential damages, so this exclusion and limitation may not apply to You.
|
||||
|
||||
8. Litigation
|
||||
|
||||
Any litigation relating to this License may be brought only in the courts of
|
||||
a jurisdiction where the defendant maintains its principal place of business
|
||||
and such litigation shall be governed by laws of that jurisdiction, without
|
||||
reference to its conflict-of-law provisions. Nothing in this Section shall
|
||||
prevent a party’s ability to bring cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
|
||||
This License represents the complete agreement concerning the subject matter
|
||||
hereof. If any provision of this License is held to be unenforceable, such
|
||||
provision shall be reformed only to the extent necessary to make it
|
||||
enforceable. Any law or regulation which provides that the language of a
|
||||
contract shall be construed against the drafter shall not be used to construe
|
||||
this License against a Contributor.
|
||||
|
||||
|
||||
10. Versions of the License
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version of
|
||||
the License under which You originally received the Covered Software, or
|
||||
under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a modified
|
||||
version of this License if you rename the license and remove any
|
||||
references to the name of the license steward (except to note that such
|
||||
modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular file, then
|
||||
You may include the notice in a location (such as a LICENSE file in a relevant
|
||||
directory) where a recipient would be likely to look for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - “Incompatible With Secondary Licenses” Notice
|
||||
|
||||
This Source Code Form is “Incompatible
|
||||
With Secondary Licenses”, as defined by
|
||||
the Mozilla Public License, v. 2.0.
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
# Versioning Library for Go
|
||||
|
||||

|
||||
[](https://pkg.go.dev/github.com/hashicorp/go-version)
|
||||
|
||||
go-version is a library for parsing versions and version constraints,
|
||||
and verifying versions against a set of constraints. go-version
|
||||
can sort a collection of versions properly, handles prerelease/beta
|
||||
versions, can increment versions, etc.
|
||||
|
||||
Versions used with go-version must follow [SemVer](http://semver.org/).
|
||||
|
||||
## Installation and Usage
|
||||
|
||||
Package documentation can be found on
|
||||
[Go Reference](https://pkg.go.dev/github.com/hashicorp/go-version).
|
||||
|
||||
Installation can be done with a normal `go get`:
|
||||
|
||||
```
|
||||
$ go get github.com/hashicorp/go-version
|
||||
```
|
||||
|
||||
#### Version Parsing and Comparison
|
||||
|
||||
```go
|
||||
v1, err := version.NewVersion("1.2")
|
||||
v2, err := version.NewVersion("1.5+metadata")
|
||||
|
||||
// Comparison example. There is also GreaterThan, Equal, and just
|
||||
// a simple Compare that returns an int allowing easy >=, <=, etc.
|
||||
if v1.LessThan(v2) {
|
||||
fmt.Printf("%s is less than %s", v1, v2)
|
||||
}
|
||||
```
|
||||
|
||||
#### Version Parsing and Comparison with Prefixes
|
||||
|
||||
The library also supports parsing versions with a custom prefix.
|
||||
Using the `WithPrefix` option, you can specify a prefix to strip
|
||||
before parsing the version.
|
||||
|
||||
Use `WithPrefix` when your input strings carry a known release prefix such as
|
||||
`deployment-`, `controller-`, etc.
|
||||
|
||||
After parsing, the prefix is not part of the canonical version value. This
|
||||
means the regular comparison methods such as `Compare`, `LessThan`, `Equal`,
|
||||
and `GreaterThan` compare only the stripped version. If you compare versions
|
||||
from different prefixes with these methods, the prefixes are ignored. If you
|
||||
need to reject cross-prefix comparisons, inspect the parsed prefixes before
|
||||
comparing the versions.
|
||||
|
||||
```go
|
||||
v1, _ := version.NewVersion("deployment-v1.2.3-beta+metadata", version.WithPrefix("deployment-"))
|
||||
v2, _ := version.NewVersion("deployment-v1.2.4", version.WithPrefix("deployment-"))
|
||||
|
||||
if v1.LessThan(v2) {
|
||||
fmt.Printf("%s (%s) is less than %s (%s)\n", v1, v1.Original(), v2, v2.Original())
|
||||
// Outputs: 1.2.3-beta+metadata (deployment-v1.2.3-beta+metadata) is less than 1.2.4 (deployment-v1.2.4)
|
||||
}
|
||||
```
|
||||
|
||||
#### Version Constraints
|
||||
|
||||
```go
|
||||
v1, err := version.NewVersion("1.2")
|
||||
|
||||
// Constraints example.
|
||||
constraints, err := version.NewConstraint(">= 1.0, < 1.4")
|
||||
if constraints.Check(v1) {
|
||||
fmt.Printf("%s satisfies constraints %s", v1, constraints)
|
||||
}
|
||||
```
|
||||
|
||||
#### Version Sorting
|
||||
|
||||
```go
|
||||
versionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"}
|
||||
versions := make([]*version.Version, len(versionsRaw))
|
||||
for i, raw := range versionsRaw {
|
||||
v, _ := version.NewVersion(raw)
|
||||
versions[i] = v
|
||||
}
|
||||
|
||||
// After this, the versions are properly sorted
|
||||
sort.Sort(version.Collection(versions))
|
||||
```
|
||||
|
||||
## Issues and Contributing
|
||||
|
||||
If you find an issue with this library, please report an issue. If you'd
|
||||
like, we welcome any contributions. Fork this library and submit a pull
|
||||
request.
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
// Copyright IBM Corp. 2014, 2025
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
package version
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
constraintRegexp *regexp.Regexp
|
||||
constraintRegexpOnce sync.Once
|
||||
)
|
||||
|
||||
func getConstraintRegexp() *regexp.Regexp {
|
||||
constraintRegexpOnce.Do(func() {
|
||||
// This heavy lifting only happens the first time this function is called
|
||||
constraintRegexp = regexp.MustCompile(fmt.Sprintf(
|
||||
`^\s*(%s)\s*(%s)\s*$`,
|
||||
`<=|>=|!=|~>|<|>|=|`,
|
||||
VersionRegexpRaw,
|
||||
))
|
||||
})
|
||||
return constraintRegexp
|
||||
}
|
||||
|
||||
// Constraint represents a single constraint for a version, such as
|
||||
// ">= 1.0".
|
||||
type Constraint struct {
|
||||
f constraintFunc
|
||||
op operator
|
||||
check *Version
|
||||
original string
|
||||
}
|
||||
|
||||
func (c *Constraint) Equals(con *Constraint) bool {
|
||||
return c.op == con.op && c.check.Equal(con.check)
|
||||
}
|
||||
|
||||
// Constraints is a slice of constraints. We make a custom type so that
|
||||
// we can add methods to it.
|
||||
type Constraints []*Constraint
|
||||
|
||||
type constraintFunc func(v, c *Version) bool
|
||||
|
||||
type constraintOperation struct {
|
||||
op operator
|
||||
f constraintFunc
|
||||
}
|
||||
|
||||
// NewConstraint will parse one or more constraints from the given
|
||||
// constraint string. The string must be a comma-separated list of
|
||||
// constraints.
|
||||
func NewConstraint(v string) (Constraints, error) {
|
||||
vs := strings.Split(v, ",")
|
||||
result := make([]*Constraint, len(vs))
|
||||
for i, single := range vs {
|
||||
c, err := parseSingle(single)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result[i] = c
|
||||
}
|
||||
|
||||
return Constraints(result), nil
|
||||
}
|
||||
|
||||
// MustConstraints is a helper that wraps a call to a function
|
||||
// returning (Constraints, error) and panics if error is non-nil.
|
||||
func MustConstraints(c Constraints, err error) Constraints {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
// Check tests if a version satisfies all the constraints.
|
||||
func (cs Constraints) Check(v *Version) bool {
|
||||
for _, c := range cs {
|
||||
if !c.Check(v) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Equals compares Constraints with other Constraints
|
||||
// for equality. This may not represent logical equivalence
|
||||
// of compared constraints.
|
||||
// e.g. even though '>0.1,>0.2' is logically equivalent
|
||||
// to '>0.2' it is *NOT* treated as equal.
|
||||
//
|
||||
// Missing operator is treated as equal to '=', whitespaces
|
||||
// are ignored and constraints are sorted before comparison.
|
||||
func (cs Constraints) Equals(c Constraints) bool {
|
||||
if len(cs) != len(c) {
|
||||
return false
|
||||
}
|
||||
|
||||
// make copies to retain order of the original slices
|
||||
left := make(Constraints, len(cs))
|
||||
copy(left, cs)
|
||||
sort.Stable(left)
|
||||
right := make(Constraints, len(c))
|
||||
copy(right, c)
|
||||
sort.Stable(right)
|
||||
|
||||
// compare sorted slices
|
||||
for i, con := range left {
|
||||
if !con.Equals(right[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (cs Constraints) Len() int {
|
||||
return len(cs)
|
||||
}
|
||||
|
||||
func (cs Constraints) Less(i, j int) bool {
|
||||
if cs[i].op < cs[j].op {
|
||||
return true
|
||||
}
|
||||
if cs[i].op > cs[j].op {
|
||||
return false
|
||||
}
|
||||
|
||||
return cs[i].check.LessThan(cs[j].check)
|
||||
}
|
||||
|
||||
func (cs Constraints) Swap(i, j int) {
|
||||
cs[i], cs[j] = cs[j], cs[i]
|
||||
}
|
||||
|
||||
// Returns the string format of the constraints
|
||||
func (cs Constraints) String() string {
|
||||
csStr := make([]string, len(cs))
|
||||
for i, c := range cs {
|
||||
csStr[i] = c.String()
|
||||
}
|
||||
|
||||
return strings.Join(csStr, ",")
|
||||
}
|
||||
|
||||
// Check tests if a constraint is validated by the given version.
|
||||
func (c *Constraint) Check(v *Version) bool {
|
||||
return c.f(v, c.check)
|
||||
}
|
||||
|
||||
// Prerelease returns true if the version underlying this constraint
|
||||
// contains a prerelease field.
|
||||
func (c *Constraint) Prerelease() bool {
|
||||
return len(c.check.Prerelease()) > 0
|
||||
}
|
||||
|
||||
func (c *Constraint) String() string {
|
||||
return c.original
|
||||
}
|
||||
|
||||
func parseSingle(v string) (*Constraint, error) {
|
||||
matches := getConstraintRegexp().FindStringSubmatch(v)
|
||||
if matches == nil {
|
||||
return nil, fmt.Errorf("malformed constraint: %s", v)
|
||||
}
|
||||
|
||||
check, err := NewVersion(matches[2])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var cop constraintOperation
|
||||
switch matches[1] {
|
||||
case "=":
|
||||
cop = constraintOperation{op: equal, f: constraintEqual}
|
||||
case "!=":
|
||||
cop = constraintOperation{op: notEqual, f: constraintNotEqual}
|
||||
case ">":
|
||||
cop = constraintOperation{op: greaterThan, f: constraintGreaterThan}
|
||||
case "<":
|
||||
cop = constraintOperation{op: lessThan, f: constraintLessThan}
|
||||
case ">=":
|
||||
cop = constraintOperation{op: greaterThanEqual, f: constraintGreaterThanEqual}
|
||||
case "<=":
|
||||
cop = constraintOperation{op: lessThanEqual, f: constraintLessThanEqual}
|
||||
case "~>":
|
||||
cop = constraintOperation{op: pessimistic, f: constraintPessimistic}
|
||||
default:
|
||||
cop = constraintOperation{op: equal, f: constraintEqual}
|
||||
}
|
||||
|
||||
return &Constraint{
|
||||
f: cop.f,
|
||||
op: cop.op,
|
||||
check: check,
|
||||
original: v,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func prereleaseCheck(v, c *Version) bool {
|
||||
switch vPre, cPre := v.Prerelease() != "", c.Prerelease() != ""; {
|
||||
case cPre && vPre:
|
||||
// A constraint with a pre-release can only match a pre-release version
|
||||
// with the same base segments.
|
||||
return v.equalSegments(c)
|
||||
|
||||
case !cPre && vPre:
|
||||
// A constraint without a pre-release can only match a version without a
|
||||
// pre-release.
|
||||
return false
|
||||
|
||||
case cPre && !vPre:
|
||||
// OK, except with the pessimistic operator
|
||||
case !cPre && !vPre:
|
||||
// OK
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
//-------------------------------------------------------------------
|
||||
// Constraint functions
|
||||
//-------------------------------------------------------------------
|
||||
|
||||
type operator rune
|
||||
|
||||
const (
|
||||
equal operator = '='
|
||||
notEqual operator = '≠'
|
||||
greaterThan operator = '>'
|
||||
lessThan operator = '<'
|
||||
greaterThanEqual operator = '≥'
|
||||
lessThanEqual operator = '≤'
|
||||
pessimistic operator = '~'
|
||||
)
|
||||
|
||||
func constraintEqual(v, c *Version) bool {
|
||||
return v.Equal(c)
|
||||
}
|
||||
|
||||
func constraintNotEqual(v, c *Version) bool {
|
||||
return !v.Equal(c)
|
||||
}
|
||||
|
||||
func constraintGreaterThan(v, c *Version) bool {
|
||||
return prereleaseCheck(v, c) && v.Compare(c) == 1
|
||||
}
|
||||
|
||||
func constraintLessThan(v, c *Version) bool {
|
||||
return prereleaseCheck(v, c) && v.Compare(c) == -1
|
||||
}
|
||||
|
||||
func constraintGreaterThanEqual(v, c *Version) bool {
|
||||
return prereleaseCheck(v, c) && v.Compare(c) >= 0
|
||||
}
|
||||
|
||||
func constraintLessThanEqual(v, c *Version) bool {
|
||||
return prereleaseCheck(v, c) && v.Compare(c) <= 0
|
||||
}
|
||||
|
||||
func constraintPessimistic(v, c *Version) bool {
|
||||
// Using a pessimistic constraint with a pre-release, restricts versions to pre-releases
|
||||
if !prereleaseCheck(v, c) || (c.Prerelease() != "" && v.Prerelease() == "") {
|
||||
return false
|
||||
}
|
||||
|
||||
// If the version being checked is naturally less than the constraint, then there
|
||||
// is no way for the version to be valid against the constraint
|
||||
if v.LessThan(c) {
|
||||
return false
|
||||
}
|
||||
// We'll use this more than once, so grab the length now so it's a little cleaner
|
||||
// to write the later checks
|
||||
cs := len(c.segments)
|
||||
|
||||
// If the version being checked has less specificity than the constraint, then there
|
||||
// is no way for the version to be valid against the constraint
|
||||
if cs > len(v.segments) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check the segments in the constraint against those in the version. If the version
|
||||
// being checked, at any point, does not have the same values in each index of the
|
||||
// constraints segments, then it cannot be valid against the constraint.
|
||||
for i := 0; i < c.si-1; i++ {
|
||||
if v.segments[i] != c.segments[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Check the last part of the segment in the constraint. If the version segment at
|
||||
// this index is less than the constraints segment at this index, then it cannot
|
||||
// be valid against the constraint
|
||||
if c.segments[cs-1] > v.segments[cs-1] {
|
||||
return false
|
||||
}
|
||||
|
||||
// If nothing has rejected the version by now, it's valid
|
||||
return true
|
||||
}
|
||||
+505
@@ -0,0 +1,505 @@
|
||||
// Copyright IBM Corp. 2014, 2025
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
package version
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// The compiled regular expression used to test the validity of a version.
|
||||
var (
|
||||
versionRegexp *regexp.Regexp
|
||||
versionRegexpOnce sync.Once
|
||||
semverRegexp *regexp.Regexp
|
||||
semverRegexpOnce sync.Once
|
||||
)
|
||||
|
||||
func getVersionRegexp() *regexp.Regexp {
|
||||
versionRegexpOnce.Do(func() {
|
||||
versionRegexp = regexp.MustCompile("^" + VersionRegexpRaw + "$")
|
||||
})
|
||||
return versionRegexp
|
||||
}
|
||||
|
||||
func getSemverRegexp() *regexp.Regexp {
|
||||
semverRegexpOnce.Do(func() {
|
||||
semverRegexp = regexp.MustCompile("^" + SemverRegexpRaw + "$")
|
||||
})
|
||||
return semverRegexp
|
||||
}
|
||||
|
||||
// The raw regular expression string used for testing the validity
|
||||
// of a version.
|
||||
const (
|
||||
VersionRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` +
|
||||
`(-([0-9]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)|(-?([A-Za-z\-~]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)))?` +
|
||||
`(\+([0-9A-Za-z\-~]+(\.[0-9A-Za-z\-~]+)*))?` +
|
||||
`?`
|
||||
|
||||
// SemverRegexpRaw requires a separator between version and prerelease
|
||||
SemverRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` +
|
||||
`(-([0-9]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)|(-([A-Za-z\-~]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)))?` +
|
||||
`(\+([0-9A-Za-z\-~]+(\.[0-9A-Za-z\-~]+)*))?` +
|
||||
`?`
|
||||
)
|
||||
|
||||
// Optional options for NewVersion function.
|
||||
type options struct {
|
||||
// If set, this prefix will be trimmed from the version string before parsing.
|
||||
prefix string
|
||||
}
|
||||
|
||||
// Option is a functional option for NewVersion.
|
||||
type Option func(*options)
|
||||
|
||||
// WithPrefix is a functional option that sets a prefix to be removed from the
|
||||
// version string before parsing.
|
||||
func WithPrefix(prefix string) Option {
|
||||
return func(o *options) {
|
||||
o.prefix = prefix
|
||||
}
|
||||
}
|
||||
|
||||
// Version represents a single version.
|
||||
type Version struct {
|
||||
metadata string
|
||||
pre string
|
||||
segments []int64
|
||||
si int
|
||||
original string
|
||||
prefix string
|
||||
}
|
||||
|
||||
// NewVersion parses the given version and returns a new Version.
|
||||
//
|
||||
// Optional parsing behavior can be enabled with Option values such as
|
||||
// WithPrefix, which validates and strips an expected prefix before parsing.
|
||||
func NewVersion(v string, opts ...Option) (*Version, error) {
|
||||
options := &options{}
|
||||
for _, opt := range opts {
|
||||
if opt != nil {
|
||||
opt(options)
|
||||
}
|
||||
}
|
||||
|
||||
vToParse := v
|
||||
if options.prefix != "" {
|
||||
if !strings.HasPrefix(v, options.prefix) {
|
||||
return nil, fmt.Errorf("version %q does not have prefix %q", v, options.prefix)
|
||||
}
|
||||
vToParse = strings.TrimPrefix(v, options.prefix)
|
||||
}
|
||||
|
||||
ver, err := newVersion(vToParse, getVersionRegexp())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ver.prefix = options.prefix
|
||||
ver.original = v
|
||||
return ver, nil
|
||||
}
|
||||
|
||||
// NewSemver parses the given version and returns a new
|
||||
// Version that adheres strictly to SemVer specs
|
||||
// https://semver.org/
|
||||
func NewSemver(v string) (*Version, error) {
|
||||
return newVersion(v, getSemverRegexp())
|
||||
}
|
||||
|
||||
func newVersion(v string, pattern *regexp.Regexp) (*Version, error) {
|
||||
matches := pattern.FindStringSubmatch(v)
|
||||
if matches == nil {
|
||||
return nil, fmt.Errorf("malformed version: %s", v)
|
||||
}
|
||||
segmentsStr := strings.Split(matches[1], ".")
|
||||
segments := make([]int64, len(segmentsStr))
|
||||
for i, str := range segmentsStr {
|
||||
val, err := strconv.ParseInt(str, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"error parsing version: %s", err)
|
||||
}
|
||||
|
||||
segments[i] = val
|
||||
}
|
||||
|
||||
// Even though we could support more than three segments, if we
|
||||
// got less than three, pad it with 0s. This is to cover the basic
|
||||
// default usecase of semver, which is MAJOR.MINOR.PATCH at the minimum
|
||||
for i := len(segments); i < 3; i++ {
|
||||
segments = append(segments, 0)
|
||||
}
|
||||
|
||||
pre := matches[7]
|
||||
if pre == "" {
|
||||
pre = matches[4]
|
||||
}
|
||||
|
||||
return &Version{
|
||||
metadata: matches[10],
|
||||
pre: pre,
|
||||
segments: segments,
|
||||
si: len(segmentsStr),
|
||||
original: v,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Must is a helper that wraps a call to a function returning (*Version, error)
|
||||
// and panics if error is non-nil.
|
||||
func Must(v *Version, err error) *Version {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
// Compare compares this version to another version. This
|
||||
// returns -1, 0, or 1 if this version is smaller, equal,
|
||||
// or larger than the other version, respectively.
|
||||
//
|
||||
// If you want boolean results, use the LessThan, Equal,
|
||||
// GreaterThan, GreaterThanOrEqual or LessThanOrEqual methods.
|
||||
func (v *Version) Compare(other *Version) int {
|
||||
// A quick, efficient equality check
|
||||
if v.String() == other.String() {
|
||||
return 0
|
||||
}
|
||||
|
||||
// If the segments are the same, we must compare on prerelease info
|
||||
if v.equalSegments(other) {
|
||||
preSelf := v.Prerelease()
|
||||
preOther := other.Prerelease()
|
||||
if preSelf == "" && preOther == "" {
|
||||
return 0
|
||||
}
|
||||
if preSelf == "" {
|
||||
return 1
|
||||
}
|
||||
if preOther == "" {
|
||||
return -1
|
||||
}
|
||||
|
||||
return comparePrereleases(preSelf, preOther)
|
||||
}
|
||||
|
||||
segmentsSelf := v.Segments64()
|
||||
segmentsOther := other.Segments64()
|
||||
// Get the highest specificity (hS), or if they're equal, just use segmentSelf length
|
||||
lenSelf := len(segmentsSelf)
|
||||
lenOther := len(segmentsOther)
|
||||
hS := lenSelf
|
||||
if lenSelf < lenOther {
|
||||
hS = lenOther
|
||||
}
|
||||
// Compare the segments
|
||||
// Because a constraint could have more/less specificity than the version it's
|
||||
// checking, we need to account for a lopsided or jagged comparison
|
||||
for i := 0; i < hS; i++ {
|
||||
if i > lenSelf-1 {
|
||||
// This means Self had the lower specificity
|
||||
// Check to see if the remaining segments in Other are all zeros
|
||||
if !allZero(segmentsOther[i:]) {
|
||||
// if not, it means that Other has to be greater than Self
|
||||
return -1
|
||||
}
|
||||
break
|
||||
} else if i > lenOther-1 {
|
||||
// this means Other had the lower specificity
|
||||
// Check to see if the remaining segments in Self are all zeros -
|
||||
if !allZero(segmentsSelf[i:]) {
|
||||
// if not, it means that Self has to be greater than Other
|
||||
return 1
|
||||
}
|
||||
break
|
||||
}
|
||||
lhs := segmentsSelf[i]
|
||||
rhs := segmentsOther[i]
|
||||
if lhs == rhs {
|
||||
continue
|
||||
} else if lhs < rhs {
|
||||
return -1
|
||||
}
|
||||
// Otherwise, rhs was > lhs, they're not equal
|
||||
return 1
|
||||
}
|
||||
|
||||
// if we got this far, they're equal
|
||||
return 0
|
||||
}
|
||||
|
||||
func (v *Version) equalSegments(other *Version) bool {
|
||||
segmentsSelf := v.Segments64()
|
||||
segmentsOther := other.Segments64()
|
||||
|
||||
if len(segmentsSelf) != len(segmentsOther) {
|
||||
return false
|
||||
}
|
||||
for i, v := range segmentsSelf {
|
||||
if v != segmentsOther[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func allZero(segs []int64) bool {
|
||||
for _, s := range segs {
|
||||
if s != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func comparePart(preSelf string, preOther string) int {
|
||||
if preSelf == preOther {
|
||||
return 0
|
||||
}
|
||||
|
||||
var selfInt int64
|
||||
selfNumeric := true
|
||||
selfInt, err := strconv.ParseInt(preSelf, 10, 64)
|
||||
if err != nil {
|
||||
selfNumeric = false
|
||||
}
|
||||
|
||||
var otherInt int64
|
||||
otherNumeric := true
|
||||
otherInt, err = strconv.ParseInt(preOther, 10, 64)
|
||||
if err != nil {
|
||||
otherNumeric = false
|
||||
}
|
||||
|
||||
// if a part is empty, we use the other to decide
|
||||
if preSelf == "" {
|
||||
if otherNumeric {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
if preOther == "" {
|
||||
if selfNumeric {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
if selfNumeric && !otherNumeric {
|
||||
return -1
|
||||
} else if !selfNumeric && otherNumeric {
|
||||
return 1
|
||||
} else if !selfNumeric && !otherNumeric && preSelf > preOther {
|
||||
return 1
|
||||
} else if selfInt > otherInt {
|
||||
return 1
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
||||
|
||||
func comparePrereleases(v string, other string) int {
|
||||
// the same pre release!
|
||||
if v == other {
|
||||
return 0
|
||||
}
|
||||
|
||||
// split both pre releases for analyse their parts
|
||||
selfPreReleaseMeta := strings.Split(v, ".")
|
||||
otherPreReleaseMeta := strings.Split(other, ".")
|
||||
|
||||
selfPreReleaseLen := len(selfPreReleaseMeta)
|
||||
otherPreReleaseLen := len(otherPreReleaseMeta)
|
||||
|
||||
biggestLen := otherPreReleaseLen
|
||||
if selfPreReleaseLen > otherPreReleaseLen {
|
||||
biggestLen = selfPreReleaseLen
|
||||
}
|
||||
|
||||
// loop for parts to find the first difference
|
||||
for i := 0; i < biggestLen; i = i + 1 {
|
||||
partSelfPre := ""
|
||||
if i < selfPreReleaseLen {
|
||||
partSelfPre = selfPreReleaseMeta[i]
|
||||
}
|
||||
|
||||
partOtherPre := ""
|
||||
if i < otherPreReleaseLen {
|
||||
partOtherPre = otherPreReleaseMeta[i]
|
||||
}
|
||||
|
||||
compare := comparePart(partSelfPre, partOtherPre)
|
||||
// if parts are equals, continue the loop
|
||||
if compare != 0 {
|
||||
return compare
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
// Core returns a new version constructed from only the MAJOR.MINOR.PATCH
|
||||
// segments of the version, without prerelease or metadata.
|
||||
func (v *Version) Core() *Version {
|
||||
segments := v.Segments64()
|
||||
segmentsOnly := fmt.Sprintf("%d.%d.%d", segments[0], segments[1], segments[2])
|
||||
return Must(NewVersion(segmentsOnly))
|
||||
}
|
||||
|
||||
// Equal tests if two versions are equal.
|
||||
func (v *Version) Equal(o *Version) bool {
|
||||
if v == nil || o == nil {
|
||||
return v == o
|
||||
}
|
||||
|
||||
return v.Compare(o) == 0
|
||||
}
|
||||
|
||||
// GreaterThan tests if this version is greater than another version.
|
||||
func (v *Version) GreaterThan(o *Version) bool {
|
||||
return v.Compare(o) > 0
|
||||
}
|
||||
|
||||
// GreaterThanOrEqual tests if this version is greater than or equal to another version.
|
||||
func (v *Version) GreaterThanOrEqual(o *Version) bool {
|
||||
return v.Compare(o) >= 0
|
||||
}
|
||||
|
||||
// LessThan tests if this version is less than another version.
|
||||
func (v *Version) LessThan(o *Version) bool {
|
||||
return v.Compare(o) < 0
|
||||
}
|
||||
|
||||
// LessThanOrEqual tests if this version is less than or equal to another version.
|
||||
func (v *Version) LessThanOrEqual(o *Version) bool {
|
||||
return v.Compare(o) <= 0
|
||||
}
|
||||
|
||||
// Metadata returns any metadata that was part of the version
|
||||
// string.
|
||||
//
|
||||
// Metadata is anything that comes after the "+" in the version.
|
||||
// For example, with "1.2.3+beta", the metadata is "beta".
|
||||
func (v *Version) Metadata() string {
|
||||
return v.metadata
|
||||
}
|
||||
|
||||
// Prerelease returns any prerelease data that is part of the version,
|
||||
// or blank if there is no prerelease data.
|
||||
//
|
||||
// Prerelease information is anything that comes after the "-" in the
|
||||
// version (but before any metadata). For example, with "1.2.3-beta",
|
||||
// the prerelease information is "beta".
|
||||
func (v *Version) Prerelease() string {
|
||||
return v.pre
|
||||
}
|
||||
|
||||
// Segments returns the numeric segments of the version as a slice of ints.
|
||||
//
|
||||
// This excludes any metadata or pre-release information. For example,
|
||||
// for a version "1.2.3-beta", segments will return a slice of
|
||||
// 1, 2, 3.
|
||||
func (v *Version) Segments() []int {
|
||||
segmentSlice := make([]int, len(v.segments))
|
||||
for i, v := range v.segments {
|
||||
segmentSlice[i] = int(v)
|
||||
}
|
||||
return segmentSlice
|
||||
}
|
||||
|
||||
// Segments64 returns the numeric segments of the version as a slice of int64s.
|
||||
//
|
||||
// This excludes any metadata or pre-release information. For example,
|
||||
// for a version "1.2.3-beta", segments will return a slice of
|
||||
// 1, 2, 3.
|
||||
func (v *Version) Segments64() []int64 {
|
||||
result := make([]int64, len(v.segments))
|
||||
copy(result, v.segments)
|
||||
return result
|
||||
}
|
||||
|
||||
// String returns the full version string included pre-release
|
||||
// and metadata information.
|
||||
//
|
||||
// This value is rebuilt according to the parsed segments and other
|
||||
// information. Therefore, ambiguities in the version string such as
|
||||
// prefixed zeroes (1.04.0 => 1.4.0), `v` prefix (v1.0.0 => 1.0.0), and
|
||||
// missing parts (1.0 => 1.0.0) will be made into a canonicalized form
|
||||
// as shown in the parenthesized examples.
|
||||
func (v *Version) String() string {
|
||||
return string(v.bytes())
|
||||
}
|
||||
|
||||
func (v *Version) bytes() []byte {
|
||||
var buf []byte
|
||||
for i, s := range v.segments {
|
||||
if i > 0 {
|
||||
buf = append(buf, '.')
|
||||
}
|
||||
buf = strconv.AppendInt(buf, s, 10)
|
||||
}
|
||||
|
||||
if v.pre != "" {
|
||||
buf = append(buf, '-')
|
||||
buf = append(buf, v.pre...)
|
||||
}
|
||||
|
||||
if v.metadata != "" {
|
||||
buf = append(buf, '+')
|
||||
buf = append(buf, v.metadata...)
|
||||
}
|
||||
|
||||
return buf
|
||||
}
|
||||
|
||||
// Original returns the original parsed version as-is, including any
|
||||
// potential whitespace, `v` prefix, etc.
|
||||
func (v *Version) Original() string {
|
||||
return v.original
|
||||
}
|
||||
|
||||
// Prefix returns the explicit prefix used with WithPrefix, if any.
|
||||
func (v *Version) Prefix() string {
|
||||
return v.prefix
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler interface.
|
||||
func (v *Version) UnmarshalText(b []byte) error {
|
||||
temp, err := NewVersion(string(b))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*v = *temp
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler interface.
|
||||
func (v *Version) MarshalText() ([]byte, error) {
|
||||
return []byte(v.String()), nil
|
||||
}
|
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
func (v *Version) Scan(src interface{}) error {
|
||||
switch src := src.(type) {
|
||||
case string:
|
||||
return v.UnmarshalText([]byte(src))
|
||||
case nil:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("cannot scan %T as Version", src)
|
||||
}
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface.
|
||||
func (v *Version) Value() (driver.Value, error) {
|
||||
return v.String(), nil
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
// Copyright IBM Corp. 2014, 2025
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
package version
|
||||
|
||||
// Collection is a type that implements the sort.Interface interface
|
||||
// so that versions can be sorted.
|
||||
type Collection []*Version
|
||||
|
||||
func (v Collection) Len() int {
|
||||
return len(v)
|
||||
}
|
||||
|
||||
func (v Collection) Less(i, j int) bool {
|
||||
return v[i].LessThan(v[j])
|
||||
}
|
||||
|
||||
func (v Collection) Swap(i, j int) {
|
||||
v[i], v[j] = v[j], v[i]
|
||||
}
|
||||
Reference in New Issue
Block a user