blob: bc520096ed6e14716b73c3e4d3d7ea0ea519037e [file] [log] [blame]
Jiri Simsad7616c92015-03-24 23:44:30 -07001// Copyright 2015 The Vanadium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Suharsh Sivakumard308c7e2014-10-03 12:46:50 -07005package util
6
7import (
8 "bytes"
9 "crypto/rand"
10 "testing"
11)
12
13func TestMacaroon(t *testing.T) {
Asim Shankar13a05012015-02-15 13:14:11 -080014 var (
15 key = randBytes(t)
16 incorrectKey = randBytes(t)
17 input = randBytes(t)
18 m = NewMacaroon(key, input)
19 )
Suharsh Sivakumard308c7e2014-10-03 12:46:50 -070020
21 // Test incorrect key.
22 decoded, err := m.Decode(incorrectKey)
23 if err == nil {
24 t.Errorf("m.Decode should have failed")
25 }
26 if decoded != nil {
27 t.Errorf("decoded value should be nil when decode fails")
28 }
29
30 // Test correct key.
31 if decoded, err = m.Decode(key); err != nil {
32 t.Errorf("m.Decode should have succeeded")
33 }
34 if !bytes.Equal(decoded, input) {
35 t.Errorf("decoded value should equal input")
36 }
37}
38
Asim Shankar13a05012015-02-15 13:14:11 -080039func TestBadMacaroon(t *testing.T) {
40 var (
41 key = []byte{0xd4, 0x4f, 0x6b, 0x5c, 0xf2, 0x5f, 0xc4, 0x3, 0x68, 0x34, 0x15, 0xc6, 0x26, 0xc5, 0x1, 0x8a}
42 tests = []Macaroon{
43 "Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r-", // valid
44 "Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r", // truncated
45 "Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r=", // truncated content but valid base64
46 "Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r--", // extended
47 "Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r-A=", // extended content but valid base64
48 "AAA_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r-", // modified data
49 "Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_XXXX-", // modified HMAC
50 "", // zero value
51 }
52 )
53 // Test data above was generated by:
54 //{
55 // key := randBytes(t)
56 // t.Logf("key=%#v\ntests = []Macaroon{\n\t%q, // valid\n}", key, NewMacaroon(key, randBytes(t)))
57 //}
58
59 // Make sure that "valid" is indeed valid!
60 if data, err := tests[0].Decode(key); err != nil || data == nil {
61 t.Fatalf("Bad test data: Got (%v, %v), want (<non-empty>, nil)", data, err)
62 }
63 // And all others are not:
64 for idx, test := range tests[1:] {
65 if _, err := test.Decode(key); err == nil {
66 t.Errorf("Should have failed to decode invalid macaroon #%d", idx)
67 }
68 }
69}
70
Suharsh Sivakumard308c7e2014-10-03 12:46:50 -070071func randBytes(t *testing.T) []byte {
72 b := make([]byte, 16)
73 if _, err := rand.Read(b); err != nil {
74 t.Fatalf("bytes creation failed: %v", err)
75 }
76 return b
77}