blob: bc520096ed6e14716b73c3e4d3d7ea0ea519037e [file] [log] [blame]
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package util
import (
"bytes"
"crypto/rand"
"testing"
)
func TestMacaroon(t *testing.T) {
var (
key = randBytes(t)
incorrectKey = randBytes(t)
input = randBytes(t)
m = NewMacaroon(key, input)
)
// Test incorrect key.
decoded, err := m.Decode(incorrectKey)
if err == nil {
t.Errorf("m.Decode should have failed")
}
if decoded != nil {
t.Errorf("decoded value should be nil when decode fails")
}
// Test correct key.
if decoded, err = m.Decode(key); err != nil {
t.Errorf("m.Decode should have succeeded")
}
if !bytes.Equal(decoded, input) {
t.Errorf("decoded value should equal input")
}
}
func TestBadMacaroon(t *testing.T) {
var (
key = []byte{0xd4, 0x4f, 0x6b, 0x5c, 0xf2, 0x5f, 0xc4, 0x3, 0x68, 0x34, 0x15, 0xc6, 0x26, 0xc5, 0x1, 0x8a}
tests = []Macaroon{
"Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r-", // valid
"Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r", // truncated
"Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r=", // truncated content but valid base64
"Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r--", // extended
"Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r-A=", // extended content but valid base64
"AAA_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_2m4r-", // modified data
"Hkd_PqB1ekct6eH1rTntfJYFgYpGFQpM7z0Ur8cuAcVQscWa-FNV4_kTfC_XXXX-", // modified HMAC
"", // zero value
}
)
// Test data above was generated by:
//{
// key := randBytes(t)
// t.Logf("key=%#v\ntests = []Macaroon{\n\t%q, // valid\n}", key, NewMacaroon(key, randBytes(t)))
//}
// Make sure that "valid" is indeed valid!
if data, err := tests[0].Decode(key); err != nil || data == nil {
t.Fatalf("Bad test data: Got (%v, %v), want (<non-empty>, nil)", data, err)
}
// And all others are not:
for idx, test := range tests[1:] {
if _, err := test.Decode(key); err == nil {
t.Errorf("Should have failed to decode invalid macaroon #%d", idx)
}
}
}
func randBytes(t *testing.T) []byte {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
t.Fatalf("bytes creation failed: %v", err)
}
return b
}