diff --git a/macaroons/constraints.go b/macaroons/constraints.go index 2cb36cacc..bd8741006 100644 --- a/macaroons/constraints.go +++ b/macaroons/constraints.go @@ -216,3 +216,37 @@ func HasCustomCaveat(mac *macaroon.Macaroon, customCaveatName string) bool { return false } + +// GetCustomCaveatCondition returns the custom caveat condition for the given +// custom caveat name from the given macaroon. +func GetCustomCaveatCondition(mac *macaroon.Macaroon, + customCaveatName string) string { + + if mac == nil { + return "" + } + + caveatPrefix := []byte(fmt.Sprintf( + "%s %s ", CondLndCustom, customCaveatName, + )) + for _, caveat := range mac.Caveats() { + + // The caveat id has a format of + // "lnd-custom [custom-caveat-name] [custom-caveat-condition]" + // and we only want the condition part. If we match the prefix + // part we return the condition that comes after the prefix. + if bytes.HasPrefix(caveat.Id, caveatPrefix) { + caveatSplit := strings.SplitN( + string(caveat.Id), + string(caveatPrefix), + 2, + ) + if len(caveatSplit) == 2 { + return caveatSplit[1] + } + } + } + + // We didn't find a condition for the given custom caveat name. + return "" +} diff --git a/macaroons/constraints_test.go b/macaroons/constraints_test.go index 659b5d724..6e1e243d1 100644 --- a/macaroons/constraints_test.go +++ b/macaroons/constraints_test.go @@ -132,6 +132,11 @@ func TestCustomConstraint(t *testing.T) { require.False(t, macaroons.HasCustomCaveat(testMacaroon, "something")) require.False(t, macaroons.HasCustomCaveat(nil, "foo")) + customCaveatCondition := macaroons.GetCustomCaveatCondition( + testMacaroon, "unit-test", + ) + require.Equal(t, customCaveatCondition, "test-value") + // Custom caveats don't necessarily need a value, just the name is fine // too to create a tagged macaroon. constraintFunc = macaroons.CustomConstraint("unit-test", "") @@ -144,4 +149,9 @@ func TestCustomConstraint(t *testing.T) { require.True(t, macaroons.HasCustomCaveat(testMacaroon, "unit-test")) require.False(t, macaroons.HasCustomCaveat(testMacaroon, "test-value")) require.False(t, macaroons.HasCustomCaveat(testMacaroon, "something")) + + customCaveatCondition = macaroons.GetCustomCaveatCondition( + testMacaroon, "unit-test", + ) + require.Equal(t, customCaveatCondition, "") }