bake_test.go
1 package macaroons_test 2 3 import ( 4 "encoding/hex" 5 "testing" 6 7 "github.com/lightningnetwork/lnd/macaroons" 8 "github.com/stretchr/testify/require" 9 "google.golang.org/grpc/metadata" 10 "gopkg.in/macaroon-bakery.v2/bakery" 11 ) 12 13 // TestBakeFromRootKey tests that a macaroon can be baked from a root key 14 // directly without needing to create a store or service first. 15 func TestBakeFromRootKey(t *testing.T) { 16 // Create a test store and unlock it. 17 _, store := newTestStore(t) 18 19 pw := []byte("weks") 20 err := store.CreateUnlock(&pw) 21 require.NoError(t, err) 22 23 // Force the store to create a new random root key. 24 key, id, err := store.RootKey(defaultRootKeyIDContext) 25 require.NoError(t, err) 26 require.Len(t, key, 32) 27 28 tmpKey, err := store.Get(defaultRootKeyIDContext, id) 29 require.NoError(t, err) 30 require.Equal(t, key, tmpKey) 31 32 // Create a service that uses the root key store. 33 service, err := macaroons.NewService(store, "lnd", false) 34 require.NoError(t, err, "Error creating new service") 35 defer func() { 36 require.NoError(t, service.Close()) 37 }() 38 39 // Call the BakeFromRootKey function that derives a macaroon directly 40 // from the root key. 41 perms := []bakery.Op{{Entity: "foo", Action: "bar"}} 42 mac, err := macaroons.BakeFromRootKey(key, perms) 43 require.NoError(t, err) 44 45 macaroonBytes, err := mac.MarshalBinary() 46 require.NoError(t, err) 47 48 md := metadata.New(map[string]string{ 49 "macaroon": hex.EncodeToString(macaroonBytes), 50 }) 51 macCtx := metadata.NewIncomingContext(t.Context(), md) 52 53 // The macaroon should be valid for the service, since the root key was 54 // the same. 55 err = service.ValidateMacaroon(macCtx, nil, "baz") 56 require.NoError(t, err) 57 }