1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
|
/*
* Copyright 2018 The NATS Authors
* 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.
*/
package jwt
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"testing"
"time"
"github.com/nats-io/nkeys"
)
func TestNewToken(t *testing.T) {
kp, err := nkeys.CreateAccount()
if err != nil {
t.Fatal("unable to create account key", err)
}
claims := NewGenericClaims(publicKey(createUserNKey(t), t))
claims.Data["foo"] = "bar"
token, err := claims.Encode(kp)
if err != nil {
t.Fatal("error encoding token", err)
}
c, err := DecodeGeneric(token)
if err != nil {
t.Fatal(err)
}
if claims.NotBefore != c.NotBefore {
t.Fatal("notbefore don't match")
}
if claims.Issuer != c.Issuer {
t.Fatal("notbefore don't match")
}
if !reflect.DeepEqual(claims.Data, c.Data) {
t.Fatal("data sections don't match")
}
}
func TestBadType(t *testing.T) {
kp, err := nkeys.CreateAccount()
if err != nil {
t.Fatal("unable to create account key", err)
}
h := Header{"JWS", AlgorithmNkey}
c := NewGenericClaims(publicKey(createUserNKey(t), t))
c.Data["foo"] = "bar"
token, err := c.doEncode(&h, kp, c)
if err != nil {
t.Fatal(err)
}
claim, err := DecodeGeneric(token)
if claim != nil {
t.Fatal("non nil claim on bad token")
}
if err == nil {
t.Fatal("nil error on bad token")
}
if err.Error() != fmt.Sprintf("not supported type %q", "JWS") {
t.Fatal("expected not supported type error")
}
}
func TestBadAlgo(t *testing.T) {
kp, err := nkeys.CreateAccount()
if err != nil {
t.Fatal("unable to create account key", err)
}
h := Header{TokenTypeJwt, "foobar"}
c := NewGenericClaims(publicKey(createUserNKey(t), t))
c.Data["foo"] = "bar"
token, err := c.doEncode(&h, kp, c)
if err != nil {
t.Fatal(err)
}
claim, err := DecodeGeneric(token)
if claim != nil {
t.Fatal("non nil claim on bad token")
}
if err == nil {
t.Fatal("nil error on bad token")
}
if err.Error() != fmt.Sprintf("unexpected %q algorithm", "foobar") {
t.Fatal("expected unexpected algorithm")
}
}
func TestBadJWT(t *testing.T) {
kp, err := nkeys.CreateAccount()
if err != nil {
t.Fatal("unable to create account key", err)
}
h := Header{"JWS", AlgorithmNkey}
c := NewGenericClaims(publicKey(createUserNKey(t), t))
c.Data["foo"] = "bar"
token, err := c.doEncode(&h, kp, c)
if err != nil {
t.Fatal(err)
}
chunks := strings.Split(token, ".")
badToken := fmt.Sprintf("%s.%s", chunks[0], chunks[1])
claim, err := DecodeGeneric(badToken)
if claim != nil {
t.Fatal("non nil claim on bad token")
}
if err == nil {
t.Fatal("nil error on bad token")
}
if err.Error() != "expected 3 chunks" {
t.Fatalf("unexpeced error: %q", err.Error())
}
}
func TestBadSignature(t *testing.T) {
kp := createAccountNKey(t)
h := Header{TokenTypeJwt, AlgorithmNkey}
c := NewGenericClaims(publicKey(createUserNKey(t), t))
c.Data["foo"] = "bar"
token, err := c.doEncode(&h, kp, c)
if err != nil {
t.Fatal(err)
}
token = token + "A"
claim, err := DecodeGeneric(token)
if claim != nil {
t.Fatal("non nil claim on bad token")
}
if err == nil {
t.Fatal("nil error on bad token")
}
if err.Error() != "claim failed signature verification" {
m := fmt.Sprintf("expected failed signature: %q", err.Error())
t.Fatal(m)
}
}
func TestDifferentPayload(t *testing.T) {
akp1 := createAccountNKey(t)
c1 := NewGenericClaims(publicKey(createUserNKey(t), t))
c1.Data["foo"] = "barz"
jwt1 := encode(c1, akp1, t)
c1t := strings.Split(jwt1, ".")
c1.Data["foo"] = "bar"
kp2 := createAccountNKey(t)
token2 := encode(c1, kp2, t)
c2t := strings.Split(token2, ".")
c1t[1] = c2t[1]
claim, err := DecodeGeneric(fmt.Sprintf("%s.%s.%s", c1t[0], c1t[1], c1t[2]))
if claim != nil {
t.Fatal("non nil claim on bad token")
}
if err == nil {
t.Fatal("nil error on bad token")
}
if err.Error() != "claim failed signature verification" {
m := fmt.Sprintf("expected failed signature: %q", err.Error())
t.Fatal(m)
}
}
func TestExpiredToken(t *testing.T) {
akp := createAccountNKey(t)
c := NewGenericClaims(publicKey(akp, t))
c.Expires = time.Now().UTC().Unix() - 100
c.Data["foo"] = "barz"
vr := CreateValidationResults()
c.Validate(vr)
if !vr.IsBlocking(true) {
t.Fatalf("expired tokens should be blocking when time is included")
}
if vr.IsBlocking(false) {
t.Fatalf("expired tokens should not be blocking when time is not included")
}
}
func TestNotYetValid(t *testing.T) {
akp1, err := nkeys.CreateAccount()
if err != nil {
t.Fatal("unable to create account key", err)
}
c := NewGenericClaims(publicKey(akp1, t))
c.NotBefore = time.Now().Add(time.Duration(1) * time.Hour).UTC().Unix()
vr := CreateValidationResults()
c.Validate(vr)
if !vr.IsBlocking(true) {
t.Fatalf("not yet valid tokens should be blocking when time is included")
}
if vr.IsBlocking(false) {
t.Fatalf("not yet valid tokens should not be blocking when time is not included")
}
}
func TestIssuedAtIsSet(t *testing.T) {
akp := createAccountNKey(t)
c := NewGenericClaims(publicKey(akp, t))
c.Data["foo"] = "barz"
token, err := c.Encode(akp)
if err != nil {
t.Fatal(err)
}
claim, err := DecodeGeneric(token)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if claim.IssuedAt == 0 {
t.Fatalf("issued at is not set")
}
}
func TestSample(t *testing.T) {
// Need a private key to sign the claim
akp := createAccountNKey(t)
claims := NewGenericClaims(publicKey(akp, t))
// add a bunch of claims
claims.Data["foo"] = "bar"
// serialize the claim to a JWT token
token, err := claims.Encode(akp)
if err != nil {
t.Fatal("error encoding token", err)
}
// on the receiving side, decode the token
c, err := DecodeGeneric(token)
if err != nil {
t.Fatal(err)
}
// if the token was decoded, it means that it
// validated and it wasn't tampered. the remaining and
// required test is to insure the issuer is trusted
pk, err := akp.PublicKey()
if err != nil {
t.Fatalf("unable to read public key: %v", err)
}
if c.Issuer != string(pk) {
t.Fatalf("the public key is not trusted")
}
}
func TestBadHeaderEncoding(t *testing.T) {
// the '=' will be illegal
_, err := parseHeaders("=hello=")
if err == nil {
t.Fatal("should have failed it is not encoded")
}
}
func TestBadClaimsEncoding(t *testing.T) {
// the '=' will be illegal
c := GenericClaims{}
err := parseClaims("=hello=", &c)
if err == nil {
t.Fatal("should have failed it is not encoded")
}
}
func TestBadHeaderJSON(t *testing.T) {
payload := encodeToString([]byte("{foo: bar}"))
_, err := parseHeaders(payload)
if err == nil {
t.Fatal("should have failed bad json")
}
}
func TestBadClaimsJSON(t *testing.T) {
payload := encodeToString([]byte("{foo: bar}"))
c := GenericClaims{}
err := parseClaims(payload, &c)
if err == nil {
t.Fatal("should have failed bad json")
}
}
func TestBadPublicKeyDecodeGeneric(t *testing.T) {
c := &GenericClaims{}
c.Issuer = "foo"
if ok := c.Verify("foo", []byte("bar")); ok {
t.Fatal("Should have failed to verify")
}
}
func TestBadSig(t *testing.T) {
opk := createOperatorNKey(t)
kp := createAccountNKey(t)
claims := NewGenericClaims(publicKey(kp, t))
claims.Data["foo"] = "bar"
// serialize the claim to a JWT token
token := encode(claims, opk, t)
tokens := strings.Split(token, ".")
badToken := fmt.Sprintf("%s.%s.=hello=", tokens[0], tokens[1])
_, err := DecodeGeneric(badToken)
if err == nil {
t.Fatal("should have failed to base64 decode signature")
}
}
func TestClaimsStringIsJSON(t *testing.T) {
akp := createAccountNKey(t)
claims := NewGenericClaims(publicKey(akp, t))
// add a bunch of claims
claims.Data["foo"] = "bar"
claims2 := NewGenericClaims(publicKey(akp, t))
json.Unmarshal([]byte(claims.String()), claims2)
if claims2.Data["foo"] != "bar" {
t.Fatalf("Failed to decode expected claim from String representation: %q", claims.String())
}
}
func TestDoEncodeNilHeader(t *testing.T) {
akp := createAccountNKey(t)
claims := NewGenericClaims(publicKey(akp, t))
_, err := claims.doEncode(nil, nil, claims)
if err == nil {
t.Fatal("should have failed to encode")
}
if err.Error() != "header is required" {
t.Fatalf("unexpected error on encode: %v", err)
}
}
func TestDoEncodeNilKeyPair(t *testing.T) {
akp := createAccountNKey(t)
claims := NewGenericClaims(publicKey(akp, t))
_, err := claims.doEncode(&Header{}, nil, claims)
if err == nil {
t.Fatal("should have failed to encode")
}
if err.Error() != "keypair is required" {
t.Fatalf("unexpected error on encode: %v", err)
}
}
// if this fails, the URL decoder was changed and JWTs will flap
func TestUsingURLDecoder(t *testing.T) {
token := "eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJGQ1lZRjJLR0EzQTZHTlZQR0pIVjNUSExYR1VZWkFUREZLV1JTT1czUUo1T0k3QlJST0ZRIiwiaWF0IjoxNTQzOTQzNjc1LCJpc3MiOiJBQ1NKWkhOWlI0QUFUVE1KNzdUV1JONUJHVUZFWFhUS0gzWEtGTldDRkFCVzJRWldOUTRDQkhRRSIsInN1YiI6IkFEVEFHWVZYRkpPRENRM0g0VUZQQU43R1dXWk1BVU9FTTJMMkRWQkFWVFdLM01TU0xUS1JUTzVGIiwidHlwZSI6ImFjdGl2YXRpb24iLCJuYXRzIjp7InN1YmplY3QiOiJmb28iLCJ0eXBlIjoic2VydmljZSJ9fQ.HCZTCF-7wolS3Wjx3swQWMkoDhoo_4gp9EsuM5diJfZrH8s6NTpO0iT7_fKZm7dNDeEoqjwU--3ebp8j-Mm_Aw"
ac, err := DecodeActivationClaims(token)
if err != nil {
t.Fatal("shouldn't have failed to decode", err)
}
if ac == nil {
t.Fatal("should have returned activation")
}
}
|