mirror of
https://github.com/arangodb/kube-arangodb.git
synced 2024-12-14 11:57:37 +00:00
Added pod probes
This commit is contained in:
parent
6ec749cd43
commit
ae47017455
43 changed files with 2424 additions and 20 deletions
1
Makefile
1
Makefile
|
@ -79,6 +79,7 @@ update-vendor:
|
|||
k8s.io/apiextensions-apiserver \
|
||||
github.com/cenkalti/backoff \
|
||||
github.com/dchest/uniuri \
|
||||
github.com/dgrijalva/jwt-go \
|
||||
github.com/pkg/errors \
|
||||
github.com/prometheus/client_golang/prometheus \
|
||||
github.com/pulcy/pulsar \
|
||||
|
|
5
deps/github.com/dgrijalva/jwt-go/.travis.yml
vendored
5
deps/github.com/dgrijalva/jwt-go/.travis.yml
vendored
|
@ -1,8 +1,13 @@
|
|||
language: go
|
||||
|
||||
script:
|
||||
- go vet ./...
|
||||
- go test -v ./...
|
||||
|
||||
go:
|
||||
- 1.3
|
||||
- 1.4
|
||||
- 1.5
|
||||
- 1.6
|
||||
- 1.7
|
||||
- tip
|
||||
|
|
|
@ -56,8 +56,9 @@ This simple parsing example:
|
|||
is directly mapped to:
|
||||
|
||||
```go
|
||||
if token, err := request.ParseFromRequest(tokenString, request.OAuth2Extractor, req, keyLookupFunc); err == nil {
|
||||
fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"])
|
||||
if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil {
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"])
|
||||
}
|
||||
```
|
||||
|
||||
|
|
6
deps/github.com/dgrijalva/jwt-go/README.md
vendored
6
deps/github.com/dgrijalva/jwt-go/README.md
vendored
|
@ -4,7 +4,7 @@ A [go](http://www.golang.org) (or 'golang' for search engine friendliness) imple
|
|||
|
||||
**BREAKING CHANGES:*** Version 3.0.0 is here. It includes _a lot_ of changes including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code.
|
||||
|
||||
**NOTICE:** A vulnerability in JWT was [recently published](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). As this library doesn't force users to validate the `alg` is what they expected, it's possible your usage is effected. There will be an update soon to remedy this, and it will likey require backwards-incompatible changes to the API. In the short term, please make sure your implementation verifies the `alg` is what you expect.
|
||||
**NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided.
|
||||
|
||||
|
||||
## What the heck is a JWT?
|
||||
|
@ -74,7 +74,7 @@ It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is
|
|||
|
||||
Without going too far down the rabbit hole, here's a description of the interaction of these technologies:
|
||||
|
||||
* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
|
||||
* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
|
||||
* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
|
||||
* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.
|
||||
|
||||
|
@ -82,4 +82,4 @@ Without going too far down the rabbit hole, here's a description of the interact
|
|||
|
||||
Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go).
|
||||
|
||||
The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in to documentation.
|
||||
The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation.
|
||||
|
|
|
@ -1,5 +1,11 @@
|
|||
## `jwt-go` Version History
|
||||
|
||||
#### 3.1.0
|
||||
|
||||
* Improvements to `jwt` command line tool
|
||||
* Added `SkipClaimsValidation` option to `Parser`
|
||||
* Documentation updates
|
||||
|
||||
#### 3.0.0
|
||||
|
||||
* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code
|
||||
|
|
13
deps/github.com/dgrijalva/jwt-go/cmd/jwt/README.md
vendored
Normal file
13
deps/github.com/dgrijalva/jwt-go/cmd/jwt/README.md
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
`jwt` command-line tool
|
||||
=======================
|
||||
|
||||
This is a simple tool to sign, verify and show JSON Web Tokens from
|
||||
the command line.
|
||||
|
||||
The following will create and sign a token, then verify it and output the original claims:
|
||||
|
||||
echo {\"foo\":\"bar\"} | ./jwt -key ../../test/sample_key -alg RS256 -sign - | ./jwt -key ../../test/sample_key.pub -alg RS256 -verify -
|
||||
|
||||
To simply display a token, use:
|
||||
|
||||
echo $JWT | ./jwt -show -
|
282
deps/github.com/dgrijalva/jwt-go/cmd/jwt/app.go
vendored
Normal file
282
deps/github.com/dgrijalva/jwt-go/cmd/jwt/app.go
vendored
Normal file
|
@ -0,0 +1,282 @@
|
|||
// A useful example app. You can use this to debug your tokens on the command line.
|
||||
// This is also a great place to look at how you might use this library.
|
||||
//
|
||||
// Example usage:
|
||||
// The following will create and sign a token, then verify it and output the original claims.
|
||||
// echo {\"foo\":\"bar\"} | bin/jwt -key test/sample_key -alg RS256 -sign - | bin/jwt -key test/sample_key.pub -verify -
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
var (
|
||||
// Options
|
||||
flagAlg = flag.String("alg", "", "signing algorithm identifier")
|
||||
flagKey = flag.String("key", "", "path to key file or '-' to read from stdin")
|
||||
flagCompact = flag.Bool("compact", false, "output compact JSON")
|
||||
flagDebug = flag.Bool("debug", false, "print out all kinds of debug data")
|
||||
flagClaims = make(ArgList)
|
||||
flagHead = make(ArgList)
|
||||
|
||||
// Modes - exactly one of these is required
|
||||
flagSign = flag.String("sign", "", "path to claims object to sign, '-' to read from stdin, or '+' to use only -claim args")
|
||||
flagVerify = flag.String("verify", "", "path to JWT token to verify or '-' to read from stdin")
|
||||
flagShow = flag.String("show", "", "path to JWT file or '-' to read from stdin")
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Plug in Var flags
|
||||
flag.Var(flagClaims, "claim", "add additional claims. may be used more than once")
|
||||
flag.Var(flagHead, "header", "add additional header params. may be used more than once")
|
||||
|
||||
// Usage message if you ask for -help or if you mess up inputs.
|
||||
flag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
|
||||
fmt.Fprintf(os.Stderr, " One of the following flags is required: sign, verify\n")
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
|
||||
// Parse command line options
|
||||
flag.Parse()
|
||||
|
||||
// Do the thing. If something goes wrong, print error to stderr
|
||||
// and exit with a non-zero status code
|
||||
if err := start(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Figure out which thing to do and then do that
|
||||
func start() error {
|
||||
if *flagSign != "" {
|
||||
return signToken()
|
||||
} else if *flagVerify != "" {
|
||||
return verifyToken()
|
||||
} else if *flagShow != "" {
|
||||
return showToken()
|
||||
} else {
|
||||
flag.Usage()
|
||||
return fmt.Errorf("None of the required flags are present. What do you want me to do?")
|
||||
}
|
||||
}
|
||||
|
||||
// Helper func: Read input from specified file or stdin
|
||||
func loadData(p string) ([]byte, error) {
|
||||
if p == "" {
|
||||
return nil, fmt.Errorf("No path specified")
|
||||
}
|
||||
|
||||
var rdr io.Reader
|
||||
if p == "-" {
|
||||
rdr = os.Stdin
|
||||
} else if p == "+" {
|
||||
return []byte("{}"), nil
|
||||
} else {
|
||||
if f, err := os.Open(p); err == nil {
|
||||
rdr = f
|
||||
defer f.Close()
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return ioutil.ReadAll(rdr)
|
||||
}
|
||||
|
||||
// Print a json object in accordance with the prophecy (or the command line options)
|
||||
func printJSON(j interface{}) error {
|
||||
var out []byte
|
||||
var err error
|
||||
|
||||
if *flagCompact == false {
|
||||
out, err = json.MarshalIndent(j, "", " ")
|
||||
} else {
|
||||
out, err = json.Marshal(j)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
fmt.Println(string(out))
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify a token and output the claims. This is a great example
|
||||
// of how to verify and view a token.
|
||||
func verifyToken() error {
|
||||
// get the token
|
||||
tokData, err := loadData(*flagVerify)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't read token: %v", err)
|
||||
}
|
||||
|
||||
// trim possible whitespace from token
|
||||
tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
|
||||
if *flagDebug {
|
||||
fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
|
||||
}
|
||||
|
||||
// Parse the token. Load the key from command line option
|
||||
token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) {
|
||||
data, err := loadData(*flagKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isEs() {
|
||||
return jwt.ParseECPublicKeyFromPEM(data)
|
||||
} else if isRs() {
|
||||
return jwt.ParseRSAPublicKeyFromPEM(data)
|
||||
}
|
||||
return data, nil
|
||||
})
|
||||
|
||||
// Print some debug data
|
||||
if *flagDebug && token != nil {
|
||||
fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header)
|
||||
fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims)
|
||||
}
|
||||
|
||||
// Print an error if we can't parse for some reason
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't parse token: %v", err)
|
||||
}
|
||||
|
||||
// Is token invalid?
|
||||
if !token.Valid {
|
||||
return fmt.Errorf("Token is invalid")
|
||||
}
|
||||
|
||||
// Print the token details
|
||||
if err := printJSON(token.Claims); err != nil {
|
||||
return fmt.Errorf("Failed to output claims: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create, sign, and output a token. This is a great, simple example of
|
||||
// how to use this library to create and sign a token.
|
||||
func signToken() error {
|
||||
// get the token data from command line arguments
|
||||
tokData, err := loadData(*flagSign)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't read token: %v", err)
|
||||
} else if *flagDebug {
|
||||
fmt.Fprintf(os.Stderr, "Token: %v bytes", len(tokData))
|
||||
}
|
||||
|
||||
// parse the JSON of the claims
|
||||
var claims jwt.MapClaims
|
||||
if err := json.Unmarshal(tokData, &claims); err != nil {
|
||||
return fmt.Errorf("Couldn't parse claims JSON: %v", err)
|
||||
}
|
||||
|
||||
// add command line claims
|
||||
if len(flagClaims) > 0 {
|
||||
for k, v := range flagClaims {
|
||||
claims[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// get the key
|
||||
var key interface{}
|
||||
key, err = loadData(*flagKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't read key: %v", err)
|
||||
}
|
||||
|
||||
// get the signing alg
|
||||
alg := jwt.GetSigningMethod(*flagAlg)
|
||||
if alg == nil {
|
||||
return fmt.Errorf("Couldn't find signing method: %v", *flagAlg)
|
||||
}
|
||||
|
||||
// create a new token
|
||||
token := jwt.NewWithClaims(alg, claims)
|
||||
|
||||
// add command line headers
|
||||
if len(flagHead) > 0 {
|
||||
for k, v := range flagHead {
|
||||
token.Header[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
if isEs() {
|
||||
if k, ok := key.([]byte); !ok {
|
||||
return fmt.Errorf("Couldn't convert key data to key")
|
||||
} else {
|
||||
key, err = jwt.ParseECPrivateKeyFromPEM(k)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if isRs() {
|
||||
if k, ok := key.([]byte); !ok {
|
||||
return fmt.Errorf("Couldn't convert key data to key")
|
||||
} else {
|
||||
key, err = jwt.ParseRSAPrivateKeyFromPEM(k)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if out, err := token.SignedString(key); err == nil {
|
||||
fmt.Println(out)
|
||||
} else {
|
||||
return fmt.Errorf("Error signing token: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// showToken pretty-prints the token on the command line.
|
||||
func showToken() error {
|
||||
// get the token
|
||||
tokData, err := loadData(*flagShow)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't read token: %v", err)
|
||||
}
|
||||
|
||||
// trim possible whitespace from token
|
||||
tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
|
||||
if *flagDebug {
|
||||
fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(string(tokData), nil)
|
||||
if token == nil {
|
||||
return fmt.Errorf("malformed token: %v", err)
|
||||
}
|
||||
|
||||
// Print the token details
|
||||
fmt.Println("Header:")
|
||||
if err := printJSON(token.Header); err != nil {
|
||||
return fmt.Errorf("Failed to output header: %v", err)
|
||||
}
|
||||
|
||||
fmt.Println("Claims:")
|
||||
if err := printJSON(token.Claims); err != nil {
|
||||
return fmt.Errorf("Failed to output claims: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isEs() bool {
|
||||
return strings.HasPrefix(*flagAlg, "ES")
|
||||
}
|
||||
|
||||
func isRs() bool {
|
||||
return strings.HasPrefix(*flagAlg, "RS")
|
||||
}
|
23
deps/github.com/dgrijalva/jwt-go/cmd/jwt/args.go
vendored
Normal file
23
deps/github.com/dgrijalva/jwt-go/cmd/jwt/args.go
vendored
Normal file
|
@ -0,0 +1,23 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ArgList map[string]string
|
||||
|
||||
func (l ArgList) String() string {
|
||||
data, _ := json.Marshal(l)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func (l ArgList) Set(arg string) error {
|
||||
parts := strings.SplitN(arg, "=", 2)
|
||||
if len(parts) != 2 {
|
||||
return fmt.Errorf("Invalid argument '%v'. Must use format 'key=value'. %v", arg, parts)
|
||||
}
|
||||
l[parts[0]] = parts[1]
|
||||
return nil
|
||||
}
|
100
deps/github.com/dgrijalva/jwt-go/ecdsa_test.go
vendored
Normal file
100
deps/github.com/dgrijalva/jwt-go/ecdsa_test.go
vendored
Normal file
|
@ -0,0 +1,100 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
var ecdsaTestData = []struct {
|
||||
name string
|
||||
keys map[string]string
|
||||
tokenString string
|
||||
alg string
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"Basic ES256",
|
||||
map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"},
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJmb28iOiJiYXIifQ.feG39E-bn8HXAKhzDZq7yEAPWYDhZlwTn3sePJnU9VrGMmwdXAIEyoOnrjreYlVM_Z4N13eK9-TmMTWyfKJtHQ",
|
||||
"ES256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic ES384",
|
||||
map[string]string{"private": "test/ec384-private.pem", "public": "test/ec384-public.pem"},
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzM4NCJ9.eyJmb28iOiJiYXIifQ.ngAfKMbJUh0WWubSIYe5GMsA-aHNKwFbJk_wq3lq23aPp8H2anb1rRILIzVR0gUf4a8WzDtrzmiikuPWyCS6CN4-PwdgTk-5nehC7JXqlaBZU05p3toM3nWCwm_LXcld",
|
||||
"ES384",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic ES512",
|
||||
map[string]string{"private": "test/ec512-private.pem", "public": "test/ec512-public.pem"},
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzUxMiJ9.eyJmb28iOiJiYXIifQ.AAU0TvGQOcdg2OvrwY73NHKgfk26UDekh9Prz-L_iWuTBIBqOFCWwwLsRiHB1JOddfKAls5do1W0jR_F30JpVd-6AJeTjGKA4C1A1H6gIKwRY0o_tFDIydZCl_lMBMeG5VNFAjO86-WCSKwc3hqaGkq1MugPRq_qrF9AVbuEB4JPLyL5",
|
||||
"ES512",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"basic ES256 invalid: foo => bar",
|
||||
map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"},
|
||||
"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MEQCIHoSJnmGlPaVQDqacx_2XlXEhhqtWceVopjomc2PJLtdAiAUTeGPoNYxZw0z8mgOnnIcjoxRuNDVZvybRZF3wR1l8W",
|
||||
"ES256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
func TestECDSAVerify(t *testing.T) {
|
||||
for _, data := range ecdsaTestData {
|
||||
var err error
|
||||
|
||||
key, _ := ioutil.ReadFile(data.keys["public"])
|
||||
|
||||
var ecdsaKey *ecdsa.PublicKey
|
||||
if ecdsaKey, err = jwt.ParseECPublicKeyFromPEM(key); err != nil {
|
||||
t.Errorf("Unable to parse ECDSA public key: %v", err)
|
||||
}
|
||||
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err = method.Verify(strings.Join(parts[0:2], "."), parts[2], ecdsaKey)
|
||||
if data.valid && err != nil {
|
||||
t.Errorf("[%v] Error while verifying key: %v", data.name, err)
|
||||
}
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid key passed validation", data.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestECDSASign(t *testing.T) {
|
||||
for _, data := range ecdsaTestData {
|
||||
var err error
|
||||
key, _ := ioutil.ReadFile(data.keys["private"])
|
||||
|
||||
var ecdsaKey *ecdsa.PrivateKey
|
||||
if ecdsaKey, err = jwt.ParseECPrivateKeyFromPEM(key); err != nil {
|
||||
t.Errorf("Unable to parse ECDSA private key: %v", err)
|
||||
}
|
||||
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), ecdsaKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", data.name, err)
|
||||
}
|
||||
if sig == parts[2] {
|
||||
t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
6
deps/github.com/dgrijalva/jwt-go/errors.go
vendored
6
deps/github.com/dgrijalva/jwt-go/errors.go
vendored
|
@ -51,13 +51,9 @@ func (e ValidationError) Error() string {
|
|||
} else {
|
||||
return "token is invalid"
|
||||
}
|
||||
return e.Inner.Error()
|
||||
}
|
||||
|
||||
// No errors
|
||||
func (e *ValidationError) valid() bool {
|
||||
if e.Errors > 0 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
return e.Errors == 0
|
||||
}
|
||||
|
|
114
deps/github.com/dgrijalva/jwt-go/example_test.go
vendored
Normal file
114
deps/github.com/dgrijalva/jwt-go/example_test.go
vendored
Normal file
|
@ -0,0 +1,114 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Example (atypical) using the StandardClaims type by itself to parse a token.
|
||||
// The StandardClaims type is designed to be embedded into your custom types
|
||||
// to provide standard validation features. You can use it alone, but there's
|
||||
// no way to retrieve other fields after parsing.
|
||||
// See the CustomClaimsType example for intended usage.
|
||||
func ExampleNewWithClaims_standardClaims() {
|
||||
mySigningKey := []byte("AllYourBase")
|
||||
|
||||
// Create the Claims
|
||||
claims := &jwt.StandardClaims{
|
||||
ExpiresAt: 15000,
|
||||
Issuer: "test",
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
ss, err := token.SignedString(mySigningKey)
|
||||
fmt.Printf("%v %v", ss, err)
|
||||
//Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 <nil>
|
||||
}
|
||||
|
||||
// Example creating a token using a custom claims type. The StandardClaim is embedded
|
||||
// in the custom type to allow for easy encoding, parsing and validation of standard claims.
|
||||
func ExampleNewWithClaims_customClaimsType() {
|
||||
mySigningKey := []byte("AllYourBase")
|
||||
|
||||
type MyCustomClaims struct {
|
||||
Foo string `json:"foo"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
// Create the Claims
|
||||
claims := MyCustomClaims{
|
||||
"bar",
|
||||
jwt.StandardClaims{
|
||||
ExpiresAt: 15000,
|
||||
Issuer: "test",
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
ss, err := token.SignedString(mySigningKey)
|
||||
fmt.Printf("%v %v", ss, err)
|
||||
//Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c <nil>
|
||||
}
|
||||
|
||||
// Example creating a token using a custom claims type. The StandardClaim is embedded
|
||||
// in the custom type to allow for easy encoding, parsing and validation of standard claims.
|
||||
func ExampleParseWithClaims_customClaimsType() {
|
||||
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
|
||||
|
||||
type MyCustomClaims struct {
|
||||
Foo string `json:"foo"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
// sample token is expired. override time so it parses as valid
|
||||
at(time.Unix(0, 0), func() {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte("AllYourBase"), nil
|
||||
})
|
||||
|
||||
if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
|
||||
fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
|
||||
} else {
|
||||
fmt.Println(err)
|
||||
}
|
||||
})
|
||||
|
||||
// Output: bar 15000
|
||||
}
|
||||
|
||||
// Override time value for tests. Restore default value after.
|
||||
func at(t time.Time, f func()) {
|
||||
jwt.TimeFunc = func() time.Time {
|
||||
return t
|
||||
}
|
||||
f()
|
||||
jwt.TimeFunc = time.Now
|
||||
}
|
||||
|
||||
// An example of parsing the error types using bitfield checks
|
||||
func ExampleParse_errorChecking() {
|
||||
// Token from another example. This token is expired
|
||||
var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
|
||||
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte("AllYourBase"), nil
|
||||
})
|
||||
|
||||
if token.Valid {
|
||||
fmt.Println("You look nice today")
|
||||
} else if ve, ok := err.(*jwt.ValidationError); ok {
|
||||
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
|
||||
fmt.Println("That's not even a token")
|
||||
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
|
||||
// Token is either expired or not active yet
|
||||
fmt.Println("Timing is everything")
|
||||
} else {
|
||||
fmt.Println("Couldn't handle this token:", err)
|
||||
}
|
||||
} else {
|
||||
fmt.Println("Couldn't handle this token:", err)
|
||||
}
|
||||
|
||||
// Output: Timing is everything
|
||||
}
|
66
deps/github.com/dgrijalva/jwt-go/hmac_example_test.go
vendored
Normal file
66
deps/github.com/dgrijalva/jwt-go/hmac_example_test.go
vendored
Normal file
|
@ -0,0 +1,66 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"io/ioutil"
|
||||
"time"
|
||||
)
|
||||
|
||||
// For HMAC signing method, the key can be any []byte. It is recommended to generate
|
||||
// a key using crypto/rand or something equivalent. You need the same key for signing
|
||||
// and validating.
|
||||
var hmacSampleSecret []byte
|
||||
|
||||
func init() {
|
||||
// Load sample key data
|
||||
if keyData, e := ioutil.ReadFile("test/hmacTestKey"); e == nil {
|
||||
hmacSampleSecret = keyData
|
||||
} else {
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Example creating, signing, and encoding a JWT token using the HMAC signing method
|
||||
func ExampleNew_hmac() {
|
||||
// Create a new token object, specifying signing method and the claims
|
||||
// you would like it to contain.
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"foo": "bar",
|
||||
"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
|
||||
})
|
||||
|
||||
// Sign and get the complete encoded token as a string using the secret
|
||||
tokenString, err := token.SignedString(hmacSampleSecret)
|
||||
|
||||
fmt.Println(tokenString, err)
|
||||
// Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU <nil>
|
||||
}
|
||||
|
||||
// Example parsing and validating a token using the HMAC signing method
|
||||
func ExampleParse_hmac() {
|
||||
// sample token string taken from the New example
|
||||
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU"
|
||||
|
||||
// Parse takes the token string and a function for looking up the key. The latter is especially
|
||||
// useful if you use multiple keys for your application. The standard is to use 'kid' in the
|
||||
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
|
||||
// to the callback, providing flexibility.
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
// Don't forget to validate the alg is what you expect:
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
|
||||
return hmacSampleSecret, nil
|
||||
})
|
||||
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
fmt.Println(claims["foo"], claims["nbf"])
|
||||
} else {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
// Output: bar 1.4444784e+09
|
||||
}
|
91
deps/github.com/dgrijalva/jwt-go/hmac_test.go
vendored
Normal file
91
deps/github.com/dgrijalva/jwt-go/hmac_test.go
vendored
Normal file
|
@ -0,0 +1,91 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var hmacTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
alg string
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"web sample",
|
||||
"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
|
||||
"HS256",
|
||||
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"HS384",
|
||||
"eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.KWZEuOD5lbBxZ34g7F-SlVLAQ_r5KApWNWlZIIMyQVz5Zs58a7XdNzj5_0EcNoOy",
|
||||
"HS384",
|
||||
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"HS512",
|
||||
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.CN7YijRX6Aw1n2jyI2Id1w90ja-DEMYiWixhYCyHnrZ1VfJRaFQz1bEbjjA5Fn4CLYaUG432dEYmSbS4Saokmw",
|
||||
"HS512",
|
||||
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"web sample: invalid",
|
||||
"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXo",
|
||||
"HS256",
|
||||
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
// Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1
|
||||
var hmacTestKey, _ = ioutil.ReadFile("test/hmacTestKey")
|
||||
|
||||
func TestHMACVerify(t *testing.T) {
|
||||
for _, data := range hmacTestData {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], hmacTestKey)
|
||||
if data.valid && err != nil {
|
||||
t.Errorf("[%v] Error while verifying key: %v", data.name, err)
|
||||
}
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid key passed validation", data.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHMACSign(t *testing.T) {
|
||||
for _, data := range hmacTestData {
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), hmacTestKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", data.name, err)
|
||||
}
|
||||
if sig != parts[2] {
|
||||
t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkHS256Signing(b *testing.B) {
|
||||
benchmarkSigning(b, jwt.SigningMethodHS256, hmacTestKey)
|
||||
}
|
||||
|
||||
func BenchmarkHS384Signing(b *testing.B) {
|
||||
benchmarkSigning(b, jwt.SigningMethodHS384, hmacTestKey)
|
||||
}
|
||||
|
||||
func BenchmarkHS512Signing(b *testing.B) {
|
||||
benchmarkSigning(b, jwt.SigningMethodHS512, hmacTestKey)
|
||||
}
|
216
deps/github.com/dgrijalva/jwt-go/http_example_test.go
vendored
Normal file
216
deps/github.com/dgrijalva/jwt-go/http_example_test.go
vendored
Normal file
|
@ -0,0 +1,216 @@
|
|||
package jwt_test
|
||||
|
||||
// Example HTTP auth using asymmetric crypto/RSA keys
|
||||
// This is based on a (now outdated) example at https://gist.github.com/cryptix/45c33ecf0ae54828e63b
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/dgrijalva/jwt-go/request"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// location of the files used for signing and verification
|
||||
const (
|
||||
privKeyPath = "test/sample_key" // openssl genrsa -out app.rsa keysize
|
||||
pubKeyPath = "test/sample_key.pub" // openssl rsa -in app.rsa -pubout > app.rsa.pub
|
||||
)
|
||||
|
||||
var (
|
||||
verifyKey *rsa.PublicKey
|
||||
signKey *rsa.PrivateKey
|
||||
serverPort int
|
||||
// storing sample username/password pairs
|
||||
// don't do this on a real server
|
||||
users = map[string]string{
|
||||
"test": "known",
|
||||
}
|
||||
)
|
||||
|
||||
// read the key files before starting http handlers
|
||||
func init() {
|
||||
signBytes, err := ioutil.ReadFile(privKeyPath)
|
||||
fatal(err)
|
||||
|
||||
signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
|
||||
fatal(err)
|
||||
|
||||
verifyBytes, err := ioutil.ReadFile(pubKeyPath)
|
||||
fatal(err)
|
||||
|
||||
verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
|
||||
fatal(err)
|
||||
|
||||
http.HandleFunc("/authenticate", authHandler)
|
||||
http.HandleFunc("/restricted", restrictedHandler)
|
||||
|
||||
// Setup listener
|
||||
listener, err := net.ListenTCP("tcp", &net.TCPAddr{})
|
||||
serverPort = listener.Addr().(*net.TCPAddr).Port
|
||||
|
||||
log.Println("Listening...")
|
||||
go func() {
|
||||
fatal(http.Serve(listener, nil))
|
||||
}()
|
||||
}
|
||||
|
||||
var start func()
|
||||
|
||||
func fatal(err error) {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Define some custom types were going to use within our tokens
|
||||
type CustomerInfo struct {
|
||||
Name string
|
||||
Kind string
|
||||
}
|
||||
|
||||
type CustomClaimsExample struct {
|
||||
*jwt.StandardClaims
|
||||
TokenType string
|
||||
CustomerInfo
|
||||
}
|
||||
|
||||
func Example_getTokenViaHTTP() {
|
||||
// See func authHandler for an example auth handler that produces a token
|
||||
res, err := http.PostForm(fmt.Sprintf("http://localhost:%v/authenticate", serverPort), url.Values{
|
||||
"user": {"test"},
|
||||
"pass": {"known"},
|
||||
})
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
|
||||
if res.StatusCode != 200 {
|
||||
fmt.Println("Unexpected status code", res.StatusCode)
|
||||
}
|
||||
|
||||
// Read the token out of the response body
|
||||
buf := new(bytes.Buffer)
|
||||
io.Copy(buf, res.Body)
|
||||
res.Body.Close()
|
||||
tokenString := strings.TrimSpace(buf.String())
|
||||
|
||||
// Parse the token
|
||||
token, err := jwt.ParseWithClaims(tokenString, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) {
|
||||
// since we only use the one private key to sign the tokens,
|
||||
// we also only use its public counter part to verify
|
||||
return verifyKey, nil
|
||||
})
|
||||
fatal(err)
|
||||
|
||||
claims := token.Claims.(*CustomClaimsExample)
|
||||
fmt.Println(claims.CustomerInfo.Name)
|
||||
|
||||
//Output: test
|
||||
}
|
||||
|
||||
func Example_useTokenViaHTTP() {
|
||||
|
||||
// Make a sample token
|
||||
// In a real world situation, this token will have been acquired from
|
||||
// some other API call (see Example_getTokenViaHTTP)
|
||||
token, err := createToken("foo")
|
||||
fatal(err)
|
||||
|
||||
// Make request. See func restrictedHandler for example request processor
|
||||
req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%v/restricted", serverPort), nil)
|
||||
fatal(err)
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
fatal(err)
|
||||
|
||||
// Read the response body
|
||||
buf := new(bytes.Buffer)
|
||||
io.Copy(buf, res.Body)
|
||||
res.Body.Close()
|
||||
fmt.Println(buf.String())
|
||||
|
||||
// Output: Welcome, foo
|
||||
}
|
||||
|
||||
func createToken(user string) (string, error) {
|
||||
// create a signer for rsa 256
|
||||
t := jwt.New(jwt.GetSigningMethod("RS256"))
|
||||
|
||||
// set our claims
|
||||
t.Claims = &CustomClaimsExample{
|
||||
&jwt.StandardClaims{
|
||||
// set the expire time
|
||||
// see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4
|
||||
ExpiresAt: time.Now().Add(time.Minute * 1).Unix(),
|
||||
},
|
||||
"level1",
|
||||
CustomerInfo{user, "human"},
|
||||
}
|
||||
|
||||
// Creat token string
|
||||
return t.SignedString(signKey)
|
||||
}
|
||||
|
||||
// reads the form values, checks them and creates the token
|
||||
func authHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// make sure its post
|
||||
if r.Method != "POST" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprintln(w, "No POST", r.Method)
|
||||
return
|
||||
}
|
||||
|
||||
user := r.FormValue("user")
|
||||
pass := r.FormValue("pass")
|
||||
|
||||
log.Printf("Authenticate: user[%s] pass[%s]\n", user, pass)
|
||||
|
||||
// check values
|
||||
if user != "test" || pass != "known" {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
fmt.Fprintln(w, "Wrong info")
|
||||
return
|
||||
}
|
||||
|
||||
tokenString, err := createToken(user)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprintln(w, "Sorry, error while Signing Token!")
|
||||
log.Printf("Token Signing error: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/jwt")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprintln(w, tokenString)
|
||||
}
|
||||
|
||||
// only accessible with a valid token
|
||||
func restrictedHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// Get token from request
|
||||
token, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) {
|
||||
// since we only use the one private key to sign the tokens,
|
||||
// we also only use its public counter part to verify
|
||||
return verifyKey, nil
|
||||
})
|
||||
|
||||
// If the token is missing or invalid, return error
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
fmt.Fprintln(w, "Invalid token:", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Token is valid
|
||||
fmt.Fprintln(w, "Welcome,", token.Claims.(*CustomClaimsExample).Name)
|
||||
return
|
||||
}
|
72
deps/github.com/dgrijalva/jwt-go/none_test.go
vendored
Normal file
72
deps/github.com/dgrijalva/jwt-go/none_test.go
vendored
Normal file
|
@ -0,0 +1,72 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var noneTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
alg string
|
||||
key interface{}
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"Basic",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.",
|
||||
"none",
|
||||
jwt.UnsafeAllowNoneSignatureType,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic - no key",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.",
|
||||
"none",
|
||||
nil,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"Signed",
|
||||
"eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw",
|
||||
"none",
|
||||
jwt.UnsafeAllowNoneSignatureType,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
func TestNoneVerify(t *testing.T) {
|
||||
for _, data := range noneTestData {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], data.key)
|
||||
if data.valid && err != nil {
|
||||
t.Errorf("[%v] Error while verifying key: %v", data.name, err)
|
||||
}
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid key passed validation", data.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoneSign(t *testing.T) {
|
||||
for _, data := range noneTestData {
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), data.key)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", data.name, err)
|
||||
}
|
||||
if sig != parts[2] {
|
||||
t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
261
deps/github.com/dgrijalva/jwt-go/parser_test.go
vendored
Normal file
261
deps/github.com/dgrijalva/jwt-go/parser_test.go
vendored
Normal file
|
@ -0,0 +1,261 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/dgrijalva/jwt-go/test"
|
||||
)
|
||||
|
||||
var keyFuncError error = fmt.Errorf("error loading key")
|
||||
|
||||
var (
|
||||
jwtTestDefaultKey *rsa.PublicKey
|
||||
defaultKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return jwtTestDefaultKey, nil }
|
||||
emptyKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, nil }
|
||||
errorKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, keyFuncError }
|
||||
nilKeyFunc jwt.Keyfunc = nil
|
||||
)
|
||||
|
||||
func init() {
|
||||
jwtTestDefaultKey = test.LoadRSAPublicKeyFromDisk("test/sample_key.pub")
|
||||
}
|
||||
|
||||
var jwtTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
keyfunc jwt.Keyfunc
|
||||
claims jwt.Claims
|
||||
valid bool
|
||||
errors uint32
|
||||
parser *jwt.Parser
|
||||
}{
|
||||
{
|
||||
"basic",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
true,
|
||||
0,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"basic expired",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar", "exp": float64(time.Now().Unix() - 100)},
|
||||
false,
|
||||
jwt.ValidationErrorExpired,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"basic nbf",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)},
|
||||
false,
|
||||
jwt.ValidationErrorNotValidYet,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"expired and nbf",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)},
|
||||
false,
|
||||
jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"basic invalid",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
false,
|
||||
jwt.ValidationErrorSignatureInvalid,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"basic nokeyfunc",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
nilKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
false,
|
||||
jwt.ValidationErrorUnverifiable,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"basic nokey",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
emptyKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
false,
|
||||
jwt.ValidationErrorSignatureInvalid,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"basic errorkey",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
errorKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
false,
|
||||
jwt.ValidationErrorUnverifiable,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"invalid signing method",
|
||||
"",
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
false,
|
||||
jwt.ValidationErrorSignatureInvalid,
|
||||
&jwt.Parser{ValidMethods: []string{"HS256"}},
|
||||
},
|
||||
{
|
||||
"valid signing method",
|
||||
"",
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
true,
|
||||
0,
|
||||
&jwt.Parser{ValidMethods: []string{"RS256", "HS256"}},
|
||||
},
|
||||
{
|
||||
"JSON Number",
|
||||
"",
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": json.Number("123.4")},
|
||||
true,
|
||||
0,
|
||||
&jwt.Parser{UseJSONNumber: true},
|
||||
},
|
||||
{
|
||||
"Standard Claims",
|
||||
"",
|
||||
defaultKeyFunc,
|
||||
&jwt.StandardClaims{
|
||||
ExpiresAt: time.Now().Add(time.Second * 10).Unix(),
|
||||
},
|
||||
true,
|
||||
0,
|
||||
&jwt.Parser{UseJSONNumber: true},
|
||||
},
|
||||
{
|
||||
"JSON Number - basic expired",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar", "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))},
|
||||
false,
|
||||
jwt.ValidationErrorExpired,
|
||||
&jwt.Parser{UseJSONNumber: true},
|
||||
},
|
||||
{
|
||||
"JSON Number - basic nbf",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))},
|
||||
false,
|
||||
jwt.ValidationErrorNotValidYet,
|
||||
&jwt.Parser{UseJSONNumber: true},
|
||||
},
|
||||
{
|
||||
"JSON Number - expired and nbf",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100)), "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))},
|
||||
false,
|
||||
jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired,
|
||||
&jwt.Parser{UseJSONNumber: true},
|
||||
},
|
||||
{
|
||||
"SkipClaimsValidation during token parsing",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))},
|
||||
true,
|
||||
0,
|
||||
&jwt.Parser{UseJSONNumber: true, SkipClaimsValidation: true},
|
||||
},
|
||||
}
|
||||
|
||||
func TestParser_Parse(t *testing.T) {
|
||||
privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key")
|
||||
|
||||
// Iterate over test data set and run tests
|
||||
for _, data := range jwtTestData {
|
||||
// If the token string is blank, use helper function to generate string
|
||||
if data.tokenString == "" {
|
||||
data.tokenString = test.MakeSampleToken(data.claims, privateKey)
|
||||
}
|
||||
|
||||
// Parse the token
|
||||
var token *jwt.Token
|
||||
var err error
|
||||
var parser = data.parser
|
||||
if parser == nil {
|
||||
parser = new(jwt.Parser)
|
||||
}
|
||||
// Figure out correct claims type
|
||||
switch data.claims.(type) {
|
||||
case jwt.MapClaims:
|
||||
token, err = parser.ParseWithClaims(data.tokenString, jwt.MapClaims{}, data.keyfunc)
|
||||
case *jwt.StandardClaims:
|
||||
token, err = parser.ParseWithClaims(data.tokenString, &jwt.StandardClaims{}, data.keyfunc)
|
||||
}
|
||||
|
||||
// Verify result matches expectation
|
||||
if !reflect.DeepEqual(data.claims, token.Claims) {
|
||||
t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims)
|
||||
}
|
||||
|
||||
if data.valid && err != nil {
|
||||
t.Errorf("[%v] Error while verifying token: %T:%v", data.name, err, err)
|
||||
}
|
||||
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid token passed validation", data.name)
|
||||
}
|
||||
|
||||
if (err == nil && !token.Valid) || (err != nil && token.Valid) {
|
||||
t.Errorf("[%v] Inconsistent behavior between returned error and token.Valid", data.name)
|
||||
}
|
||||
|
||||
if data.errors != 0 {
|
||||
if err == nil {
|
||||
t.Errorf("[%v] Expecting error. Didn't get one.", data.name)
|
||||
} else {
|
||||
|
||||
ve := err.(*jwt.ValidationError)
|
||||
// compare the bitfield part of the error
|
||||
if e := ve.Errors; e != data.errors {
|
||||
t.Errorf("[%v] Errors don't match expectation. %v != %v", data.name, e, data.errors)
|
||||
}
|
||||
|
||||
if err.Error() == keyFuncError.Error() && ve.Inner != keyFuncError {
|
||||
t.Errorf("[%v] Inner error does not match expectation. %v != %v", data.name, ve.Inner, keyFuncError)
|
||||
}
|
||||
}
|
||||
}
|
||||
if data.valid && token.Signature == "" {
|
||||
t.Errorf("[%v] Signature is left unpopulated after parsing", data.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper method for benchmarking various methods
|
||||
func benchmarkSigning(b *testing.B, method jwt.SigningMethod, key interface{}) {
|
||||
t := jwt.New(method)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
if _, err := t.SignedString(key); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
7
deps/github.com/dgrijalva/jwt-go/request/doc.go
vendored
Normal file
7
deps/github.com/dgrijalva/jwt-go/request/doc.go
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
// Utility package for extracting JWT tokens from
|
||||
// HTTP requests.
|
||||
//
|
||||
// The main function is ParseFromRequest and it's WithClaims variant.
|
||||
// See examples for how to use the various Extractor implementations
|
||||
// or roll your own.
|
||||
package request
|
81
deps/github.com/dgrijalva/jwt-go/request/extractor.go
vendored
Normal file
81
deps/github.com/dgrijalva/jwt-go/request/extractor.go
vendored
Normal file
|
@ -0,0 +1,81 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Errors
|
||||
var (
|
||||
ErrNoTokenInRequest = errors.New("no token present in request")
|
||||
)
|
||||
|
||||
// Interface for extracting a token from an HTTP request.
|
||||
// The ExtractToken method should return a token string or an error.
|
||||
// If no token is present, you must return ErrNoTokenInRequest.
|
||||
type Extractor interface {
|
||||
ExtractToken(*http.Request) (string, error)
|
||||
}
|
||||
|
||||
// Extractor for finding a token in a header. Looks at each specified
|
||||
// header in order until there's a match
|
||||
type HeaderExtractor []string
|
||||
|
||||
func (e HeaderExtractor) ExtractToken(req *http.Request) (string, error) {
|
||||
// loop over header names and return the first one that contains data
|
||||
for _, header := range e {
|
||||
if ah := req.Header.Get(header); ah != "" {
|
||||
return ah, nil
|
||||
}
|
||||
}
|
||||
return "", ErrNoTokenInRequest
|
||||
}
|
||||
|
||||
// Extract token from request arguments. This includes a POSTed form or
|
||||
// GET URL arguments. Argument names are tried in order until there's a match.
|
||||
// This extractor calls `ParseMultipartForm` on the request
|
||||
type ArgumentExtractor []string
|
||||
|
||||
func (e ArgumentExtractor) ExtractToken(req *http.Request) (string, error) {
|
||||
// Make sure form is parsed
|
||||
req.ParseMultipartForm(10e6)
|
||||
|
||||
// loop over arg names and return the first one that contains data
|
||||
for _, arg := range e {
|
||||
if ah := req.Form.Get(arg); ah != "" {
|
||||
return ah, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", ErrNoTokenInRequest
|
||||
}
|
||||
|
||||
// Tries Extractors in order until one returns a token string or an error occurs
|
||||
type MultiExtractor []Extractor
|
||||
|
||||
func (e MultiExtractor) ExtractToken(req *http.Request) (string, error) {
|
||||
// loop over header names and return the first one that contains data
|
||||
for _, extractor := range e {
|
||||
if tok, err := extractor.ExtractToken(req); tok != "" {
|
||||
return tok, nil
|
||||
} else if err != ErrNoTokenInRequest {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return "", ErrNoTokenInRequest
|
||||
}
|
||||
|
||||
// Wrap an Extractor in this to post-process the value before it's handed off.
|
||||
// See AuthorizationHeaderExtractor for an example
|
||||
type PostExtractionFilter struct {
|
||||
Extractor
|
||||
Filter func(string) (string, error)
|
||||
}
|
||||
|
||||
func (e *PostExtractionFilter) ExtractToken(req *http.Request) (string, error) {
|
||||
if tok, err := e.Extractor.ExtractToken(req); tok != "" {
|
||||
return e.Filter(tok)
|
||||
} else {
|
||||
return "", err
|
||||
}
|
||||
}
|
32
deps/github.com/dgrijalva/jwt-go/request/extractor_example_test.go
vendored
Normal file
32
deps/github.com/dgrijalva/jwt-go/request/extractor_example_test.go
vendored
Normal file
|
@ -0,0 +1,32 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const (
|
||||
exampleTokenA = "A"
|
||||
)
|
||||
|
||||
func ExampleHeaderExtractor() {
|
||||
req := makeExampleRequest("GET", "/", map[string]string{"Token": exampleTokenA}, nil)
|
||||
tokenString, err := HeaderExtractor{"Token"}.ExtractToken(req)
|
||||
if err == nil {
|
||||
fmt.Println(tokenString)
|
||||
} else {
|
||||
fmt.Println(err)
|
||||
}
|
||||
//Output: A
|
||||
}
|
||||
|
||||
func ExampleArgumentExtractor() {
|
||||
req := makeExampleRequest("GET", "/", nil, url.Values{"token": {extractorTestTokenA}})
|
||||
tokenString, err := ArgumentExtractor{"token"}.ExtractToken(req)
|
||||
if err == nil {
|
||||
fmt.Println(tokenString)
|
||||
} else {
|
||||
fmt.Println(err)
|
||||
}
|
||||
//Output: A
|
||||
}
|
91
deps/github.com/dgrijalva/jwt-go/request/extractor_test.go
vendored
Normal file
91
deps/github.com/dgrijalva/jwt-go/request/extractor_test.go
vendored
Normal file
|
@ -0,0 +1,91 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var extractorTestTokenA = "A"
|
||||
var extractorTestTokenB = "B"
|
||||
|
||||
var extractorTestData = []struct {
|
||||
name string
|
||||
extractor Extractor
|
||||
headers map[string]string
|
||||
query url.Values
|
||||
token string
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "simple header",
|
||||
extractor: HeaderExtractor{"Foo"},
|
||||
headers: map[string]string{"Foo": extractorTestTokenA},
|
||||
query: nil,
|
||||
token: extractorTestTokenA,
|
||||
err: nil,
|
||||
},
|
||||
{
|
||||
name: "simple argument",
|
||||
extractor: ArgumentExtractor{"token"},
|
||||
headers: map[string]string{},
|
||||
query: url.Values{"token": {extractorTestTokenA}},
|
||||
token: extractorTestTokenA,
|
||||
err: nil,
|
||||
},
|
||||
{
|
||||
name: "multiple extractors",
|
||||
extractor: MultiExtractor{
|
||||
HeaderExtractor{"Foo"},
|
||||
ArgumentExtractor{"token"},
|
||||
},
|
||||
headers: map[string]string{"Foo": extractorTestTokenA},
|
||||
query: url.Values{"token": {extractorTestTokenB}},
|
||||
token: extractorTestTokenA,
|
||||
err: nil,
|
||||
},
|
||||
{
|
||||
name: "simple miss",
|
||||
extractor: HeaderExtractor{"This-Header-Is-Not-Set"},
|
||||
headers: map[string]string{"Foo": extractorTestTokenA},
|
||||
query: nil,
|
||||
token: "",
|
||||
err: ErrNoTokenInRequest,
|
||||
},
|
||||
{
|
||||
name: "filter",
|
||||
extractor: AuthorizationHeaderExtractor,
|
||||
headers: map[string]string{"Authorization": "Bearer " + extractorTestTokenA},
|
||||
query: nil,
|
||||
token: extractorTestTokenA,
|
||||
err: nil,
|
||||
},
|
||||
}
|
||||
|
||||
func TestExtractor(t *testing.T) {
|
||||
// Bearer token request
|
||||
for _, data := range extractorTestData {
|
||||
// Make request from test struct
|
||||
r := makeExampleRequest("GET", "/", data.headers, data.query)
|
||||
|
||||
// Test extractor
|
||||
token, err := data.extractor.ExtractToken(r)
|
||||
if token != data.token {
|
||||
t.Errorf("[%v] Expected token '%v'. Got '%v'", data.name, data.token, token)
|
||||
continue
|
||||
}
|
||||
if err != data.err {
|
||||
t.Errorf("[%v] Expected error '%v'. Got '%v'", data.name, data.err, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeExampleRequest(method, path string, headers map[string]string, urlArgs url.Values) *http.Request {
|
||||
r, _ := http.NewRequest(method, fmt.Sprintf("%v?%v", path, urlArgs.Encode()), nil)
|
||||
for k, v := range headers {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
return r
|
||||
}
|
28
deps/github.com/dgrijalva/jwt-go/request/oauth2.go
vendored
Normal file
28
deps/github.com/dgrijalva/jwt-go/request/oauth2.go
vendored
Normal file
|
@ -0,0 +1,28 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Strips 'Bearer ' prefix from bearer token string
|
||||
func stripBearerPrefixFromTokenString(tok string) (string, error) {
|
||||
// Should be a bearer token
|
||||
if len(tok) > 6 && strings.ToUpper(tok[0:7]) == "BEARER " {
|
||||
return tok[7:], nil
|
||||
}
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// Extract bearer token from Authorization header
|
||||
// Uses PostExtractionFilter to strip "Bearer " prefix from header
|
||||
var AuthorizationHeaderExtractor = &PostExtractionFilter{
|
||||
HeaderExtractor{"Authorization"},
|
||||
stripBearerPrefixFromTokenString,
|
||||
}
|
||||
|
||||
// Extractor for OAuth2 access tokens. Looks in 'Authorization'
|
||||
// header then 'access_token' argument for a token.
|
||||
var OAuth2Extractor = &MultiExtractor{
|
||||
AuthorizationHeaderExtractor,
|
||||
ArgumentExtractor{"access_token"},
|
||||
}
|
24
deps/github.com/dgrijalva/jwt-go/request/request.go
vendored
Normal file
24
deps/github.com/dgrijalva/jwt-go/request/request.go
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Extract and parse a JWT token from an HTTP request.
|
||||
// This behaves the same as Parse, but accepts a request and an extractor
|
||||
// instead of a token string. The Extractor interface allows you to define
|
||||
// the logic for extracting a token. Several useful implementations are provided.
|
||||
func ParseFromRequest(req *http.Request, extractor Extractor, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) {
|
||||
return ParseFromRequestWithClaims(req, extractor, jwt.MapClaims{}, keyFunc)
|
||||
}
|
||||
|
||||
// ParseFromRequest but with custom Claims type
|
||||
func ParseFromRequestWithClaims(req *http.Request, extractor Extractor, claims jwt.Claims, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) {
|
||||
// Extract token from request
|
||||
if tokStr, err := extractor.ExtractToken(req); err == nil {
|
||||
return jwt.ParseWithClaims(tokStr, claims, keyFunc)
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
103
deps/github.com/dgrijalva/jwt-go/request/request_test.go
vendored
Normal file
103
deps/github.com/dgrijalva/jwt-go/request/request_test.go
vendored
Normal file
|
@ -0,0 +1,103 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/dgrijalva/jwt-go/test"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var requestTestData = []struct {
|
||||
name string
|
||||
claims jwt.MapClaims
|
||||
extractor Extractor
|
||||
headers map[string]string
|
||||
query url.Values
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"authorization bearer token",
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
AuthorizationHeaderExtractor,
|
||||
map[string]string{"Authorization": "Bearer %v"},
|
||||
url.Values{},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"oauth bearer token - header",
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
OAuth2Extractor,
|
||||
map[string]string{"Authorization": "Bearer %v"},
|
||||
url.Values{},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"oauth bearer token - url",
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
OAuth2Extractor,
|
||||
map[string]string{},
|
||||
url.Values{"access_token": {"%v"}},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"url token",
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
ArgumentExtractor{"token"},
|
||||
map[string]string{},
|
||||
url.Values{"token": {"%v"}},
|
||||
true,
|
||||
},
|
||||
}
|
||||
|
||||
func TestParseRequest(t *testing.T) {
|
||||
// load keys from disk
|
||||
privateKey := test.LoadRSAPrivateKeyFromDisk("../test/sample_key")
|
||||
publicKey := test.LoadRSAPublicKeyFromDisk("../test/sample_key.pub")
|
||||
keyfunc := func(*jwt.Token) (interface{}, error) {
|
||||
return publicKey, nil
|
||||
}
|
||||
|
||||
// Bearer token request
|
||||
for _, data := range requestTestData {
|
||||
// Make token from claims
|
||||
tokenString := test.MakeSampleToken(data.claims, privateKey)
|
||||
|
||||
// Make query string
|
||||
for k, vv := range data.query {
|
||||
for i, v := range vv {
|
||||
if strings.Contains(v, "%v") {
|
||||
data.query[k][i] = fmt.Sprintf(v, tokenString)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make request from test struct
|
||||
r, _ := http.NewRequest("GET", fmt.Sprintf("/?%v", data.query.Encode()), nil)
|
||||
for k, v := range data.headers {
|
||||
if strings.Contains(v, "%v") {
|
||||
r.Header.Set(k, fmt.Sprintf(v, tokenString))
|
||||
} else {
|
||||
r.Header.Set(k, tokenString)
|
||||
}
|
||||
}
|
||||
token, err := ParseFromRequestWithClaims(r, data.extractor, jwt.MapClaims{}, keyfunc)
|
||||
|
||||
if token == nil {
|
||||
t.Errorf("[%v] Token was not found: %v", data.name, err)
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(data.claims, token.Claims) {
|
||||
t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims)
|
||||
}
|
||||
if data.valid && err != nil {
|
||||
t.Errorf("[%v] Error while verifying token: %v", data.name, err)
|
||||
}
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid token passed validation", data.name)
|
||||
}
|
||||
}
|
||||
}
|
96
deps/github.com/dgrijalva/jwt-go/rsa_pss_test.go
vendored
Normal file
96
deps/github.com/dgrijalva/jwt-go/rsa_pss_test.go
vendored
Normal file
|
@ -0,0 +1,96 @@
|
|||
// +build go1.4
|
||||
|
||||
package jwt_test
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
var rsaPSSTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
alg string
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"Basic PS256",
|
||||
"eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9w",
|
||||
"PS256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic PS384",
|
||||
"eyJhbGciOiJQUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.w7-qqgj97gK4fJsq_DCqdYQiylJjzWONvD0qWWWhqEOFk2P1eDULPnqHRnjgTXoO4HAw4YIWCsZPet7nR3Xxq4ZhMqvKW8b7KlfRTb9cH8zqFvzMmybQ4jv2hKc3bXYqVow3AoR7hN_CWXI3Dv6Kd2X5xhtxRHI6IL39oTVDUQ74LACe-9t4c3QRPuj6Pq1H4FAT2E2kW_0KOc6EQhCLWEhm2Z2__OZskDC8AiPpP8Kv4k2vB7l0IKQu8Pr4RcNBlqJdq8dA5D3hk5TLxP8V5nG1Ib80MOMMqoS3FQvSLyolFX-R_jZ3-zfq6Ebsqr0yEb0AH2CfsECF7935Pa0FKQ",
|
||||
"PS384",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic PS512",
|
||||
"eyJhbGciOiJQUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.GX1HWGzFaJevuSLavqqFYaW8_TpvcjQ8KfC5fXiSDzSiT9UD9nB_ikSmDNyDILNdtjZLSvVKfXxZJqCfefxAtiozEDDdJthZ-F0uO4SPFHlGiXszvKeodh7BuTWRI2wL9-ZO4mFa8nq3GMeQAfo9cx11i7nfN8n2YNQ9SHGovG7_T_AvaMZB_jT6jkDHpwGR9mz7x1sycckEo6teLdHRnH_ZdlHlxqknmyTu8Odr5Xh0sJFOL8BepWbbvIIn-P161rRHHiDWFv6nhlHwZnVzjx7HQrWSGb6-s2cdLie9QL_8XaMcUpjLkfOMKkDOfHo6AvpL7Jbwi83Z2ZTHjJWB-A",
|
||||
"PS512",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"basic PS256 invalid: foo => bar",
|
||||
"eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9W",
|
||||
"PS256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
func TestRSAPSSVerify(t *testing.T) {
|
||||
var err error
|
||||
|
||||
key, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
var rsaPSSKey *rsa.PublicKey
|
||||
if rsaPSSKey, err = jwt.ParseRSAPublicKeyFromPEM(key); err != nil {
|
||||
t.Errorf("Unable to parse RSA public key: %v", err)
|
||||
}
|
||||
|
||||
for _, data := range rsaPSSTestData {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], rsaPSSKey)
|
||||
if data.valid && err != nil {
|
||||
t.Errorf("[%v] Error while verifying key: %v", data.name, err)
|
||||
}
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid key passed validation", data.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRSAPSSSign(t *testing.T) {
|
||||
var err error
|
||||
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
var rsaPSSKey *rsa.PrivateKey
|
||||
if rsaPSSKey, err = jwt.ParseRSAPrivateKeyFromPEM(key); err != nil {
|
||||
t.Errorf("Unable to parse RSA private key: %v", err)
|
||||
}
|
||||
|
||||
for _, data := range rsaPSSTestData {
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), rsaPSSKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", data.name, err)
|
||||
}
|
||||
if sig == parts[2] {
|
||||
t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, sig, parts[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
176
deps/github.com/dgrijalva/jwt-go/rsa_test.go
vendored
Normal file
176
deps/github.com/dgrijalva/jwt-go/rsa_test.go
vendored
Normal file
|
@ -0,0 +1,176 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var rsaTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
alg string
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"Basic RS256",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
"RS256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic RS384",
|
||||
"eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw",
|
||||
"RS384",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic RS512",
|
||||
"eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.zBlLlmRrUxx4SJPUbV37Q1joRcI9EW13grnKduK3wtYKmDXbgDpF1cZ6B-2Jsm5RB8REmMiLpGms-EjXhgnyh2TSHE-9W2gA_jvshegLWtwRVDX40ODSkTb7OVuaWgiy9y7llvcknFBTIg-FnVPVpXMmeV_pvwQyhaz1SSwSPrDyxEmksz1hq7YONXhXPpGaNbMMeDTNP_1oj8DZaqTIL9TwV8_1wb2Odt_Fy58Ke2RVFijsOLdnyEAjt2n9Mxihu9i3PhNBkkxa2GbnXBfq3kzvZ_xxGGopLdHhJjcGWXO-NiwI9_tiu14NRv4L2xC0ItD9Yz68v2ZIZEp_DuzwRQ",
|
||||
"RS512",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"basic invalid: foo => bar",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
"RS256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
func TestRSAVerify(t *testing.T) {
|
||||
keyData, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
key, _ := jwt.ParseRSAPublicKeyFromPEM(keyData)
|
||||
|
||||
for _, data := range rsaTestData {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], key)
|
||||
if data.valid && err != nil {
|
||||
t.Errorf("[%v] Error while verifying key: %v", data.name, err)
|
||||
}
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid key passed validation", data.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRSASign(t *testing.T) {
|
||||
keyData, _ := ioutil.ReadFile("test/sample_key")
|
||||
key, _ := jwt.ParseRSAPrivateKeyFromPEM(keyData)
|
||||
|
||||
for _, data := range rsaTestData {
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), key)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", data.name, err)
|
||||
}
|
||||
if sig != parts[2] {
|
||||
t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
parsedKey, err := jwt.ParseRSAPublicKeyFromPEM(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testData := rsaTestData[0]
|
||||
parts := strings.Split(testData.tokenString, ".")
|
||||
err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error while verifying key: %v", testData.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRSAWithPreParsedPrivateKey(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testData := rsaTestData[0]
|
||||
parts := strings.Split(testData.tokenString, ".")
|
||||
sig, err := jwt.SigningMethodRS256.Sign(strings.Join(parts[0:2], "."), parsedKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", testData.name, err)
|
||||
}
|
||||
if sig != parts[2] {
|
||||
t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRSAKeyParsing(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
pubKey, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
badKey := []byte("All your base are belong to key")
|
||||
|
||||
// Test parsePrivateKey
|
||||
if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil {
|
||||
t.Errorf("Failed to parse valid private key: %v", e)
|
||||
}
|
||||
|
||||
if k, e := jwt.ParseRSAPrivateKeyFromPEM(pubKey); e == nil {
|
||||
t.Errorf("Parsed public key as valid private key: %v", k)
|
||||
}
|
||||
|
||||
if k, e := jwt.ParseRSAPrivateKeyFromPEM(badKey); e == nil {
|
||||
t.Errorf("Parsed invalid key as valid private key: %v", k)
|
||||
}
|
||||
|
||||
// Test parsePublicKey
|
||||
if _, e := jwt.ParseRSAPublicKeyFromPEM(pubKey); e != nil {
|
||||
t.Errorf("Failed to parse valid public key: %v", e)
|
||||
}
|
||||
|
||||
if k, e := jwt.ParseRSAPublicKeyFromPEM(key); e == nil {
|
||||
t.Errorf("Parsed private key as valid public key: %v", k)
|
||||
}
|
||||
|
||||
if k, e := jwt.ParseRSAPublicKeyFromPEM(badKey); e == nil {
|
||||
t.Errorf("Parsed invalid key as valid private key: %v", k)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func BenchmarkRS256Signing(b *testing.B) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
benchmarkSigning(b, jwt.SigningMethodRS256, parsedKey)
|
||||
}
|
||||
|
||||
func BenchmarkRS384Signing(b *testing.B) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
benchmarkSigning(b, jwt.SigningMethodRS384, parsedKey)
|
||||
}
|
||||
|
||||
func BenchmarkRS512Signing(b *testing.B) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
benchmarkSigning(b, jwt.SigningMethodRS512, parsedKey)
|
||||
}
|
5
deps/github.com/dgrijalva/jwt-go/test/ec256-private.pem
vendored
Normal file
5
deps/github.com/dgrijalva/jwt-go/test/ec256-private.pem
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIAh5qA3rmqQQuu0vbKV/+zouz/y/Iy2pLpIcWUSyImSwoAoGCCqGSM49
|
||||
AwEHoUQDQgAEYD54V/vp+54P9DXarYqx4MPcm+HKRIQzNasYSoRQHQ/6S6Ps8tpM
|
||||
cT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg==
|
||||
-----END EC PRIVATE KEY-----
|
4
deps/github.com/dgrijalva/jwt-go/test/ec256-public.pem
vendored
Normal file
4
deps/github.com/dgrijalva/jwt-go/test/ec256-public.pem
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYD54V/vp+54P9DXarYqx4MPcm+HK
|
||||
RIQzNasYSoRQHQ/6S6Ps8tpMcT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg==
|
||||
-----END PUBLIC KEY-----
|
6
deps/github.com/dgrijalva/jwt-go/test/ec384-private.pem
vendored
Normal file
6
deps/github.com/dgrijalva/jwt-go/test/ec384-private.pem
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
-----BEGIN EC PRIVATE KEY-----
|
||||
MIGkAgEBBDCaCvMHKhcG/qT7xsNLYnDT7sE/D+TtWIol1ROdaK1a564vx5pHbsRy
|
||||
SEKcIxISi1igBwYFK4EEACKhZANiAATYa7rJaU7feLMqrAx6adZFNQOpaUH/Uylb
|
||||
ZLriOLON5YFVwtVUpO1FfEXZUIQpptRPtc5ixIPY658yhBSb6irfIJUSP9aYTflJ
|
||||
GKk/mDkK4t8mWBzhiD5B6jg9cEGhGgA=
|
||||
-----END EC PRIVATE KEY-----
|
5
deps/github.com/dgrijalva/jwt-go/test/ec384-public.pem
vendored
Normal file
5
deps/github.com/dgrijalva/jwt-go/test/ec384-public.pem
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE2Gu6yWlO33izKqwMemnWRTUDqWlB/1Mp
|
||||
W2S64jizjeWBVcLVVKTtRXxF2VCEKabUT7XOYsSD2OufMoQUm+oq3yCVEj/WmE35
|
||||
SRipP5g5CuLfJlgc4Yg+Qeo4PXBBoRoA
|
||||
-----END PUBLIC KEY-----
|
7
deps/github.com/dgrijalva/jwt-go/test/ec512-private.pem
vendored
Normal file
7
deps/github.com/dgrijalva/jwt-go/test/ec512-private.pem
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
-----BEGIN EC PRIVATE KEY-----
|
||||
MIHcAgEBBEIB0pE4uFaWRx7t03BsYlYvF1YvKaBGyvoakxnodm9ou0R9wC+sJAjH
|
||||
QZZJikOg4SwNqgQ/hyrOuDK2oAVHhgVGcYmgBwYFK4EEACOhgYkDgYYABAAJXIuw
|
||||
12MUzpHggia9POBFYXSxaOGKGbMjIyDI+6q7wi7LMw3HgbaOmgIqFG72o8JBQwYN
|
||||
4IbXHf+f86CRY1AA2wHzbHvt6IhkCXTNxBEffa1yMUgu8n9cKKF2iLgyQKcKqW33
|
||||
8fGOw/n3Rm2Yd/EB56u2rnD29qS+nOM9eGS+gy39OQ==
|
||||
-----END EC PRIVATE KEY-----
|
6
deps/github.com/dgrijalva/jwt-go/test/ec512-public.pem
vendored
Normal file
6
deps/github.com/dgrijalva/jwt-go/test/ec512-public.pem
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQACVyLsNdjFM6R4IImvTzgRWF0sWjh
|
||||
ihmzIyMgyPuqu8IuyzMNx4G2jpoCKhRu9qPCQUMGDeCG1x3/n/OgkWNQANsB82x7
|
||||
7eiIZAl0zcQRH32tcjFILvJ/XCihdoi4MkCnCqlt9/HxjsP590ZtmHfxAeertq5w
|
||||
9vakvpzjPXhkvoMt/Tk=
|
||||
-----END PUBLIC KEY-----
|
42
deps/github.com/dgrijalva/jwt-go/test/helpers.go
vendored
Normal file
42
deps/github.com/dgrijalva/jwt-go/test/helpers.go
vendored
Normal file
|
@ -0,0 +1,42 @@
|
|||
package test
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
func LoadRSAPrivateKeyFromDisk(location string) *rsa.PrivateKey {
|
||||
keyData, e := ioutil.ReadFile(location)
|
||||
if e != nil {
|
||||
panic(e.Error())
|
||||
}
|
||||
key, e := jwt.ParseRSAPrivateKeyFromPEM(keyData)
|
||||
if e != nil {
|
||||
panic(e.Error())
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func LoadRSAPublicKeyFromDisk(location string) *rsa.PublicKey {
|
||||
keyData, e := ioutil.ReadFile(location)
|
||||
if e != nil {
|
||||
panic(e.Error())
|
||||
}
|
||||
key, e := jwt.ParseRSAPublicKeyFromPEM(keyData)
|
||||
if e != nil {
|
||||
panic(e.Error())
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func MakeSampleToken(c jwt.Claims, key interface{}) string {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodRS256, c)
|
||||
s, e := token.SignedString(key)
|
||||
|
||||
if e != nil {
|
||||
panic(e.Error())
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
1
deps/github.com/dgrijalva/jwt-go/test/hmacTestKey
vendored
Normal file
1
deps/github.com/dgrijalva/jwt-go/test/hmacTestKey
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
#5K+・シミew{ヲ住ウ(跼Tノ(ゥ┫メP.ソモ燾辻G<>感テwb="=.!r.Oタヘ奎gミ」
|
27
deps/github.com/dgrijalva/jwt-go/test/sample_key
vendored
Normal file
27
deps/github.com/dgrijalva/jwt-go/test/sample_key
vendored
Normal file
|
@ -0,0 +1,27 @@
|
|||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEU/wT8RDtn
|
||||
SgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7mCpz9Er5qLaMXJwZxzHzAahlfA0i
|
||||
cqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBpHssPnpYGIn20ZZuNlX2BrClciHhC
|
||||
PUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2XrHhR+1DcKJzQBSTAGnpYVaqpsAR
|
||||
ap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3bODIRe1AuTyHceAbewn8b462yEWKA
|
||||
Rdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy7wIDAQABAoIBAQCwia1k7+2oZ2d3
|
||||
n6agCAbqIE1QXfCmh41ZqJHbOY3oRQG3X1wpcGH4Gk+O+zDVTV2JszdcOt7E5dAy
|
||||
MaomETAhRxB7hlIOnEN7WKm+dGNrKRvV0wDU5ReFMRHg31/Lnu8c+5BvGjZX+ky9
|
||||
POIhFFYJqwCRlopGSUIxmVj5rSgtzk3iWOQXr+ah1bjEXvlxDOWkHN6YfpV5ThdE
|
||||
KdBIPGEVqa63r9n2h+qazKrtiRqJqGnOrHzOECYbRFYhexsNFz7YT02xdfSHn7gM
|
||||
IvabDDP/Qp0PjE1jdouiMaFHYnLBbgvlnZW9yuVf/rpXTUq/njxIXMmvmEyyvSDn
|
||||
FcFikB8pAoGBAPF77hK4m3/rdGT7X8a/gwvZ2R121aBcdPwEaUhvj/36dx596zvY
|
||||
mEOjrWfZhF083/nYWE2kVquj2wjs+otCLfifEEgXcVPTnEOPO9Zg3uNSL0nNQghj
|
||||
FuD3iGLTUBCtM66oTe0jLSslHe8gLGEQqyMzHOzYxNqibxcOZIe8Qt0NAoGBAO+U
|
||||
I5+XWjWEgDmvyC3TrOSf/KCGjtu0TSv30ipv27bDLMrpvPmD/5lpptTFwcxvVhCs
|
||||
2b+chCjlghFSWFbBULBrfci2FtliClOVMYrlNBdUSJhf3aYSG2Doe6Bgt1n2CpNn
|
||||
/iu37Y3NfemZBJA7hNl4dYe+f+uzM87cdQ214+jrAoGAXA0XxX8ll2+ToOLJsaNT
|
||||
OvNB9h9Uc5qK5X5w+7G7O998BN2PC/MWp8H+2fVqpXgNENpNXttkRm1hk1dych86
|
||||
EunfdPuqsX+as44oCyJGFHVBnWpm33eWQw9YqANRI+pCJzP08I5WK3osnPiwshd+
|
||||
hR54yjgfYhBFNI7B95PmEQkCgYBzFSz7h1+s34Ycr8SvxsOBWxymG5zaCsUbPsL0
|
||||
4aCgLScCHb9J+E86aVbbVFdglYa5Id7DPTL61ixhl7WZjujspeXZGSbmq0Kcnckb
|
||||
mDgqkLECiOJW2NHP/j0McAkDLL4tysF8TLDO8gvuvzNC+WQ6drO2ThrypLVZQ+ry
|
||||
eBIPmwKBgEZxhqa0gVvHQG/7Od69KWj4eJP28kq13RhKay8JOoN0vPmspXJo1HY3
|
||||
CKuHRG+AP579dncdUnOMvfXOtkdM4vk0+hWASBQzM9xzVcztCa+koAugjVaLS9A+
|
||||
9uQoqEeVNTckxx0S2bYevRy7hGQmUJTyQm3j1zEUR5jpdbL83Fbq
|
||||
-----END RSA PRIVATE KEY-----
|
9
deps/github.com/dgrijalva/jwt-go/test/sample_key.pub
vendored
Normal file
9
deps/github.com/dgrijalva/jwt-go/test/sample_key.pub
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem/V41
|
||||
fGnJm6gOdrj8ym3rFkEU/wT8RDtnSgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7
|
||||
mCpz9Er5qLaMXJwZxzHzAahlfA0icqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBp
|
||||
HssPnpYGIn20ZZuNlX2BrClciHhCPUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2
|
||||
XrHhR+1DcKJzQBSTAGnpYVaqpsARap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3b
|
||||
ODIRe1AuTyHceAbewn8b462yEWKARdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy
|
||||
7wIDAQAB
|
||||
-----END PUBLIC KEY-----
|
|
@ -161,7 +161,13 @@ type AuthenticationSpec struct {
|
|||
}
|
||||
|
||||
// Validate the given spec
|
||||
func (s AuthenticationSpec) Validate() error {
|
||||
func (s AuthenticationSpec) Validate(required, allowed bool) error {
|
||||
if required && s.JWTSecretName == "" {
|
||||
return maskAny(errors.Wrap(ValidationError, "Missing JWT secret"))
|
||||
}
|
||||
if !allowed && s.JWTSecretName != "" {
|
||||
return maskAny(errors.Wrap(ValidationError, "Non-empty JWT secret name is not allowed"))
|
||||
}
|
||||
if err := k8sutil.ValidateOptionalResourceName(s.JWTSecretName); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
|
@ -195,11 +201,32 @@ func (s *SSLSpec) SetDefaults() {
|
|||
}
|
||||
}
|
||||
|
||||
// MonitoringSpec holds monitoring specific configuration settings
|
||||
type MonitoringSpec struct {
|
||||
TokenSecretName string `json:"tokenSecretName,omitempty"`
|
||||
}
|
||||
|
||||
// Validate the given spec
|
||||
func (s MonitoringSpec) Validate() error {
|
||||
if err := k8sutil.ValidateOptionalResourceName(s.TokenSecretName); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetDefaults fills in missing defaults
|
||||
func (s *MonitoringSpec) SetDefaults() {
|
||||
// Nothing needed
|
||||
}
|
||||
|
||||
// SyncSpec holds dc2dc replication specific configuration settings
|
||||
type SyncSpec struct {
|
||||
Enabled bool `json:"enabled,omitempty"`
|
||||
Image string `json:"image,omitempty"`
|
||||
ImagePullPolicy v1.PullPolicy `json:"imagePullPolicy,omitempty"`
|
||||
|
||||
Authentication AuthenticationSpec `json:"auth"`
|
||||
Monitoring MonitoringSpec `json:"monitoring"`
|
||||
}
|
||||
|
||||
// Validate the given spec
|
||||
|
@ -210,6 +237,12 @@ func (s SyncSpec) Validate(mode DeploymentMode) error {
|
|||
if s.Image == "" {
|
||||
return maskAny(errors.Wrapf(ValidationError, "image must be set"))
|
||||
}
|
||||
if err := s.Authentication.Validate(s.Enabled, s.Enabled); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
if err := s.Monitoring.Validate(); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -221,6 +254,8 @@ func (s *SyncSpec) SetDefaults(defaultImage string, defaulPullPolicy v1.PullPoli
|
|||
if s.ImagePullPolicy == "" {
|
||||
s.ImagePullPolicy = defaulPullPolicy
|
||||
}
|
||||
s.Authentication.SetDefaults()
|
||||
s.Monitoring.SetDefaults()
|
||||
}
|
||||
|
||||
type ServerGroup int
|
||||
|
@ -347,6 +382,16 @@ type DeploymentSpec struct {
|
|||
SyncWorkers ServerGroupSpec `json:"syncworkers"`
|
||||
}
|
||||
|
||||
// IsAuthenticated returns true when authentication is enabled
|
||||
func (s DeploymentSpec) IsAuthenticated() bool {
|
||||
return s.Authentication.JWTSecretName != ""
|
||||
}
|
||||
|
||||
// IsSecure returns true when SSL is enabled
|
||||
func (s DeploymentSpec) IsSecure() bool {
|
||||
return s.SSL.KeySecretName != ""
|
||||
}
|
||||
|
||||
// SetDefaults fills in default values when a field is not specified.
|
||||
func (s *DeploymentSpec) SetDefaults() {
|
||||
if s.Mode == "" {
|
||||
|
@ -397,7 +442,7 @@ func (s *DeploymentSpec) Validate() error {
|
|||
if err := s.RocksDB.Validate(); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
if err := s.Authentication.Validate(); err != nil {
|
||||
if err := s.Authentication.Validate(false, true); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
if err := s.SSL.Validate(); err != nil {
|
||||
|
|
|
@ -210,6 +210,22 @@ func (in *MemberStatus) DeepCopy() *MemberStatus {
|
|||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *MonitoringSpec) DeepCopyInto(out *MonitoringSpec) {
|
||||
*out = *in
|
||||
return
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MonitoringSpec.
|
||||
func (in *MonitoringSpec) DeepCopy() *MonitoringSpec {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(MonitoringSpec)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *RocksDBSpec) DeepCopyInto(out *RocksDBSpec) {
|
||||
*out = *in
|
||||
|
@ -268,6 +284,8 @@ func (in *ServerGroupSpec) DeepCopy() *ServerGroupSpec {
|
|||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *SyncSpec) DeepCopyInto(out *SyncSpec) {
|
||||
*out = *in
|
||||
out.Authentication = in.Authentication
|
||||
out.Monitoring = in.Monitoring
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
@ -29,6 +29,7 @@ import (
|
|||
|
||||
api "github.com/arangodb/k8s-operator/pkg/apis/arangodb/v1alpha"
|
||||
|
||||
"github.com/arangodb/k8s-operator/pkg/util/arangod"
|
||||
"github.com/arangodb/k8s-operator/pkg/util/k8sutil"
|
||||
)
|
||||
|
||||
|
@ -200,6 +201,87 @@ func (d *Deployment) createArangoSyncArgs(apiObject *api.ArangoDeployment, group
|
|||
return nil
|
||||
}
|
||||
|
||||
// createLivenessProbe creates configuration for a liveness probe of a server in the given group.
|
||||
func (d *Deployment) createLivenessProbe(apiObject *api.ArangoDeployment, group api.ServerGroup) (*k8sutil.HTTPProbeConfig, error) {
|
||||
switch group {
|
||||
case api.ServerGroupSingle, api.ServerGroupAgents, api.ServerGroupDBServers:
|
||||
authorization := ""
|
||||
if apiObject.Spec.IsAuthenticated() {
|
||||
secretData, err := d.getJWTSecret(apiObject)
|
||||
if err != nil {
|
||||
return nil, maskAny(err)
|
||||
}
|
||||
authorization, err = arangod.CreateArangodJwtAuthorizationHeader(secretData)
|
||||
if err != nil {
|
||||
return nil, maskAny(err)
|
||||
}
|
||||
}
|
||||
return &k8sutil.HTTPProbeConfig{
|
||||
LocalPath: "/_api/version",
|
||||
Secure: apiObject.Spec.IsSecure(),
|
||||
Authorization: authorization,
|
||||
}, nil
|
||||
case api.ServerGroupCoordinators:
|
||||
return nil, nil
|
||||
case api.ServerGroupSyncMasters, api.ServerGroupSyncWorkers:
|
||||
authorization := ""
|
||||
if apiObject.Spec.Sync.Monitoring.TokenSecretName != "" {
|
||||
// Use monitoring token
|
||||
token, err := d.getSyncMonitoringToken(apiObject)
|
||||
if err != nil {
|
||||
return nil, maskAny(err)
|
||||
}
|
||||
authorization = "bearer: " + token
|
||||
if err != nil {
|
||||
return nil, maskAny(err)
|
||||
}
|
||||
} else if group == api.ServerGroupSyncMasters {
|
||||
// Fall back to JWT secret
|
||||
secretData, err := d.getSyncJWTSecret(apiObject)
|
||||
if err != nil {
|
||||
return nil, maskAny(err)
|
||||
}
|
||||
authorization, err = arangod.CreateArangodJwtAuthorizationHeader(secretData)
|
||||
if err != nil {
|
||||
return nil, maskAny(err)
|
||||
}
|
||||
} else {
|
||||
// Don't have a probe
|
||||
return nil, nil
|
||||
}
|
||||
return &k8sutil.HTTPProbeConfig{
|
||||
LocalPath: "/_api/version",
|
||||
Secure: apiObject.Spec.IsSecure(),
|
||||
Authorization: authorization,
|
||||
}, nil
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// createReadinessProbe creates configuration for a readiness probe of a server in the given group.
|
||||
func (d *Deployment) createReadinessProbe(apiObject *api.ArangoDeployment, group api.ServerGroup) (*k8sutil.HTTPProbeConfig, error) {
|
||||
if group != api.ServerGroupCoordinators {
|
||||
return nil, nil
|
||||
}
|
||||
authorization := ""
|
||||
if apiObject.Spec.IsAuthenticated() {
|
||||
secretData, err := d.getJWTSecret(apiObject)
|
||||
if err != nil {
|
||||
return nil, maskAny(err)
|
||||
}
|
||||
authorization, err = arangod.CreateArangodJwtAuthorizationHeader(secretData)
|
||||
if err != nil {
|
||||
return nil, maskAny(err)
|
||||
}
|
||||
}
|
||||
return &k8sutil.HTTPProbeConfig{
|
||||
LocalPath: "/_api/version",
|
||||
Secure: apiObject.Spec.IsSecure(),
|
||||
Authorization: authorization,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ensurePods creates all Pods listed in member status
|
||||
func (d *Deployment) ensurePods(apiObject *api.ArangoDeployment) error {
|
||||
kubecli := d.deps.KubeCli
|
||||
|
@ -207,19 +289,41 @@ func (d *Deployment) ensurePods(apiObject *api.ArangoDeployment) error {
|
|||
|
||||
if err := apiObject.ForeachServerGroup(func(group api.ServerGroup, spec api.ServerGroupSpec, status *api.MemberStatusList) error {
|
||||
for _, m := range *status {
|
||||
if m.State != api.MemberStateNone {
|
||||
continue
|
||||
}
|
||||
role := group.AsRole()
|
||||
if group.IsArangod() {
|
||||
args := d.createArangodArgs(apiObject, group, spec, d.status.Members.Agents, m.ID)
|
||||
env := make(map[string]string)
|
||||
if err := k8sutil.CreateArangodPod(kubecli, apiObject, role, m.ID, m.PersistentVolumeClaimName, apiObject.Spec.Image, apiObject.Spec.ImagePullPolicy, args, env, owner); err != nil {
|
||||
livenessProbe, err := d.createLivenessProbe(apiObject, group)
|
||||
if err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
readinessProbe, err := d.createReadinessProbe(apiObject, group)
|
||||
if err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
if err := k8sutil.CreateArangodPod(kubecli, apiObject, role, m.ID, m.PersistentVolumeClaimName, apiObject.Spec.Image, apiObject.Spec.ImagePullPolicy, args, env, livenessProbe, readinessProbe, owner); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
} else if group.IsArangosync() {
|
||||
args := d.createArangoSyncArgs(apiObject, group, spec, d.status.Members.Agents, m.ID)
|
||||
env := make(map[string]string)
|
||||
if err := k8sutil.CreateArangoSyncPod(kubecli, apiObject, role, m.ID, apiObject.Spec.Sync.Image, apiObject.Spec.Sync.ImagePullPolicy, args, env, owner); err != nil {
|
||||
livenessProbe, err := d.createLivenessProbe(apiObject, group)
|
||||
if err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
if err := k8sutil.CreateArangoSyncPod(kubecli, apiObject, role, m.ID, apiObject.Spec.Sync.Image, apiObject.Spec.Sync.ImagePullPolicy, args, env, livenessProbe, owner); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
}
|
||||
m.State = api.MemberStateCreating
|
||||
if err := status.Update(m); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
if err := d.updateCRStatus(); err != nil {
|
||||
return maskAny(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
|
78
pkg/deployment/secrets.go
Normal file
78
pkg/deployment/secrets.go
Normal file
|
@ -0,0 +1,78 @@
|
|||
//
|
||||
// DISCLAIMER
|
||||
//
|
||||
// Copyright 2018 ArangoDB GmbH, Cologne, Germany
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Copyright holder is ArangoDB GmbH, Cologne, Germany
|
||||
//
|
||||
// Author Ewout Prangsma
|
||||
//
|
||||
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
api "github.com/arangodb/k8s-operator/pkg/apis/arangodb/v1alpha"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
// getJWTSecret loads the JWT secret from a Secret configured in apiObject.Spec.Authentication.JWTSecretName.
|
||||
func (d *Deployment) getJWTSecret(apiObject *api.ArangoDeployment) (string, error) {
|
||||
if !apiObject.Spec.IsAuthenticated() {
|
||||
return "", nil
|
||||
}
|
||||
kubecli := d.deps.KubeCli
|
||||
secretName := apiObject.Spec.Authentication.JWTSecretName
|
||||
s, err := kubecli.CoreV1().Secrets(apiObject.GetNamespace()).Get(secretName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
d.deps.Log.Debug().Err(err).Str("secret-name", secretName).Msg("Failed to get JWT secret")
|
||||
}
|
||||
// Take the first data
|
||||
for _, v := range s.Data {
|
||||
return string(v), nil
|
||||
}
|
||||
return "", maskAny(fmt.Errorf("No data found in secret '%s'", secretName))
|
||||
}
|
||||
|
||||
// getSyncJWTSecret loads the JWT secret used for syncmasters from a Secret configured in apiObject.Spec.Sync.Authentication.JWTSecretName.
|
||||
func (d *Deployment) getSyncJWTSecret(apiObject *api.ArangoDeployment) (string, error) {
|
||||
kubecli := d.deps.KubeCli
|
||||
secretName := apiObject.Spec.Sync.Authentication.JWTSecretName
|
||||
s, err := kubecli.CoreV1().Secrets(apiObject.GetNamespace()).Get(secretName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
d.deps.Log.Debug().Err(err).Str("secret-name", secretName).Msg("Failed to get sync JWT secret")
|
||||
}
|
||||
// Take the first data
|
||||
for _, v := range s.Data {
|
||||
return string(v), nil
|
||||
}
|
||||
return "", maskAny(fmt.Errorf("No data found in secret '%s'", secretName))
|
||||
}
|
||||
|
||||
// getSyncMonitoringToken loads the token secret used for monitoring sync masters & workers.
|
||||
func (d *Deployment) getSyncMonitoringToken(apiObject *api.ArangoDeployment) (string, error) {
|
||||
kubecli := d.deps.KubeCli
|
||||
secretName := apiObject.Spec.Sync.Monitoring.TokenSecretName
|
||||
s, err := kubecli.CoreV1().Secrets(apiObject.GetNamespace()).Get(secretName, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
d.deps.Log.Debug().Err(err).Str("secret-name", secretName).Msg("Failed to get monitoring token secret")
|
||||
}
|
||||
// Take the first data
|
||||
for _, v := range s.Data {
|
||||
return string(v), nil
|
||||
}
|
||||
return "", maskAny(fmt.Errorf("No data found in secret '%s'", secretName))
|
||||
}
|
29
pkg/util/arangod/error.go
Normal file
29
pkg/util/arangod/error.go
Normal file
|
@ -0,0 +1,29 @@
|
|||
//
|
||||
// DISCLAIMER
|
||||
//
|
||||
// Copyright 2018 ArangoDB GmbH, Cologne, Germany
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Copyright holder is ArangoDB GmbH, Cologne, Germany
|
||||
//
|
||||
// Author Ewout Prangsma
|
||||
//
|
||||
|
||||
package arangod
|
||||
|
||||
import "github.com/pkg/errors"
|
||||
|
||||
var (
|
||||
maskAny = errors.WithStack
|
||||
)
|
54
pkg/util/arangod/jwt.go
Normal file
54
pkg/util/arangod/jwt.go
Normal file
|
@ -0,0 +1,54 @@
|
|||
//
|
||||
// DISCLAIMER
|
||||
//
|
||||
// Copyright 2018 ArangoDB GmbH, Cologne, Germany
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Copyright holder is ArangoDB GmbH, Cologne, Germany
|
||||
//
|
||||
// Author Ewout Prangsma
|
||||
//
|
||||
|
||||
package arangod
|
||||
|
||||
import (
|
||||
jg "github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
const (
|
||||
issArangod = "arangodb"
|
||||
)
|
||||
|
||||
// CreateArangodJwtAuthorizationHeader calculates a JWT authorization header, for authorization
|
||||
// of a request to an arangod server, based on the given secret.
|
||||
// If the secret is empty, nothing is done.
|
||||
func CreateArangodJwtAuthorizationHeader(jwtSecret string) (string, error) {
|
||||
if jwtSecret == "" {
|
||||
return "", nil
|
||||
}
|
||||
// Create a new token object, specifying signing method and the claims
|
||||
// you would like it to contain.
|
||||
token := jg.NewWithClaims(jg.SigningMethodHS256, jg.MapClaims{
|
||||
"iss": issArangod,
|
||||
"server_id": "foo",
|
||||
})
|
||||
|
||||
// Sign and get the complete encoded token as a string using the secret
|
||||
signedToken, err := token.SignedString([]byte(jwtSecret))
|
||||
if err != nil {
|
||||
return "", maskAny(err)
|
||||
}
|
||||
|
||||
return "bearer " + signedToken, nil
|
||||
}
|
|
@ -47,7 +47,7 @@ func arangodVolumeMounts() []v1.VolumeMount {
|
|||
}
|
||||
|
||||
// arangodContainer creates a container configured to run `arangod`.
|
||||
func arangodContainer(name string, image string, imagePullPolicy v1.PullPolicy, args []string, env map[string]string) v1.Container {
|
||||
func arangodContainer(name string, image string, imagePullPolicy v1.PullPolicy, args []string, env map[string]string, livenessProbe *HTTPProbeConfig, readinessProbe *HTTPProbeConfig) v1.Container {
|
||||
c := v1.Container{
|
||||
Command: append([]string{"/usr/sbin/arangod"}, args...),
|
||||
Name: name,
|
||||
|
@ -68,12 +68,18 @@ func arangodContainer(name string, image string, imagePullPolicy v1.PullPolicy,
|
|||
Value: v,
|
||||
})
|
||||
}
|
||||
if livenessProbe != nil {
|
||||
c.LivenessProbe = livenessProbe.Create()
|
||||
}
|
||||
if readinessProbe != nil {
|
||||
c.ReadinessProbe = readinessProbe.Create()
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
// arangosyncContainer creates a container configured to run `arangosync`.
|
||||
func arangosyncContainer(name string, image string, imagePullPolicy v1.PullPolicy, args []string, env map[string]string) v1.Container {
|
||||
func arangosyncContainer(name string, image string, imagePullPolicy v1.PullPolicy, args []string, env map[string]string, livenessProbe *HTTPProbeConfig) v1.Container {
|
||||
c := v1.Container{
|
||||
Command: append([]string{"/usr/sbin/arangosync"}, args...),
|
||||
Name: name,
|
||||
|
@ -93,6 +99,9 @@ func arangosyncContainer(name string, image string, imagePullPolicy v1.PullPolic
|
|||
Value: v,
|
||||
})
|
||||
}
|
||||
if livenessProbe != nil {
|
||||
c.LivenessProbe = livenessProbe.Create()
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
@ -116,12 +125,13 @@ func newPod(deploymentName, ns, role, id string) v1.Pod {
|
|||
// CreateArangodPod creates a Pod that runs `arangod`.
|
||||
// If the pod already exists, nil is returned.
|
||||
// If another error occurs, that error is returned.
|
||||
func CreateArangodPod(kubecli kubernetes.Interface, deployment metav1.Object, role, id, pvcName, image string, imagePullPolicy v1.PullPolicy, args []string, env map[string]string, owner metav1.OwnerReference) error {
|
||||
func CreateArangodPod(kubecli kubernetes.Interface, deployment metav1.Object, role, id, pvcName, image string, imagePullPolicy v1.PullPolicy,
|
||||
args []string, env map[string]string, livenessProbe *HTTPProbeConfig, readinessProbe *HTTPProbeConfig, owner metav1.OwnerReference) error {
|
||||
// Prepare basic pod
|
||||
p := newPod(deployment.GetName(), deployment.GetNamespace(), role, id)
|
||||
|
||||
// Add arangod container
|
||||
c := arangodContainer(p.GetName(), image, imagePullPolicy, args, env)
|
||||
c := arangodContainer(p.GetName(), image, imagePullPolicy, args, env, livenessProbe, readinessProbe)
|
||||
p.Spec.Containers = append(p.Spec.Containers, c)
|
||||
|
||||
// Add volume
|
||||
|
@ -156,12 +166,13 @@ func CreateArangodPod(kubecli kubernetes.Interface, deployment metav1.Object, ro
|
|||
// CreateArangoSyncPod creates a Pod that runs `arangosync`.
|
||||
// If the pod already exists, nil is returned.
|
||||
// If another error occurs, that error is returned.
|
||||
func CreateArangoSyncPod(kubecli kubernetes.Interface, deployment metav1.Object, role, id, image string, imagePullPolicy v1.PullPolicy, args []string, env map[string]string, owner metav1.OwnerReference) error {
|
||||
func CreateArangoSyncPod(kubecli kubernetes.Interface, deployment metav1.Object, role, id, image string, imagePullPolicy v1.PullPolicy,
|
||||
args []string, env map[string]string, livenessProbe *HTTPProbeConfig, owner metav1.OwnerReference) error {
|
||||
// Prepare basic pod
|
||||
p := newPod(deployment.GetName(), deployment.GetNamespace(), role, id)
|
||||
|
||||
// Add arangosync container
|
||||
c := arangosyncContainer(p.GetName(), image, imagePullPolicy, args, env)
|
||||
c := arangosyncContainer(p.GetName(), image, imagePullPolicy, args, env, livenessProbe)
|
||||
p.Spec.Containers = append(p.Spec.Containers, c)
|
||||
|
||||
if err := createPod(kubecli, &p, deployment.GetNamespace(), owner); err != nil {
|
||||
|
|
68
pkg/util/k8sutil/probes.go
Normal file
68
pkg/util/k8sutil/probes.go
Normal file
|
@ -0,0 +1,68 @@
|
|||
//
|
||||
// DISCLAIMER
|
||||
//
|
||||
// Copyright 2018 ArangoDB GmbH, Cologne, Germany
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Copyright holder is ArangoDB GmbH, Cologne, Germany
|
||||
//
|
||||
// Author Ewout Prangsma
|
||||
//
|
||||
|
||||
package k8sutil
|
||||
|
||||
import (
|
||||
"k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/util/intstr"
|
||||
)
|
||||
|
||||
// HTTPProbeConfig contains settings for creating a liveness/readiness probe.
|
||||
type HTTPProbeConfig struct {
|
||||
// Local path to GET
|
||||
LocalPath string // `e.g. /_api/version`
|
||||
// Secure connection?
|
||||
Secure bool
|
||||
// Value for an Authorization header (can be empty)
|
||||
Authorization string
|
||||
}
|
||||
|
||||
// Create creates a probe from given config
|
||||
func (config HTTPProbeConfig) Create() *v1.Probe {
|
||||
scheme := v1.URISchemeHTTP
|
||||
if config.Secure {
|
||||
scheme = v1.URISchemeHTTPS
|
||||
}
|
||||
var headers []v1.HTTPHeader
|
||||
if config.Authorization != "" {
|
||||
headers = append(headers, v1.HTTPHeader{
|
||||
Name: "Authorization",
|
||||
Value: config.Authorization,
|
||||
})
|
||||
}
|
||||
return &v1.Probe{
|
||||
Handler: v1.Handler{
|
||||
HTTPGet: &v1.HTTPGetAction{
|
||||
Path: config.LocalPath,
|
||||
Port: intstr.FromInt(ArangoPort),
|
||||
Scheme: scheme,
|
||||
HTTPHeaders: headers,
|
||||
},
|
||||
},
|
||||
InitialDelaySeconds: 30, // Wait 30s before first probe
|
||||
TimeoutSeconds: 2, // Timeout of each probe is 2s
|
||||
PeriodSeconds: 10, // Interval between probes is 10s
|
||||
SuccessThreshold: 1, // Single probe is enough to indicate success
|
||||
FailureThreshold: 3, // Need 3 failed probes to consider a failed state
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue