macaroons: add GetCustomCaveatCondition func

This adds a `GetCustomCaveatCondition` function that returns the custom
caveat condition for a given macaroon and caveat name. Previously there
was no function for getting the custom caveat condition from a macaroon,
only for setting one.
This commit is contained in:
Daniel McNally 2022-01-20 11:51:03 -05:00
parent f50950640f
commit a4474447c2
No known key found for this signature in database
GPG Key ID: BC19D851B2FC3A00
2 changed files with 44 additions and 0 deletions

View File

@ -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 ""
}

View File

@ -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, "")
}