2017-08-18 03:50:15 +02:00
|
|
|
package macaroons
|
|
|
|
|
|
|
|
import (
|
2019-09-29 01:10:57 +02:00
|
|
|
"context"
|
2017-08-18 03:50:15 +02:00
|
|
|
"encoding/hex"
|
|
|
|
|
2018-01-16 17:18:41 +01:00
|
|
|
macaroon "gopkg.in/macaroon.v2"
|
2017-08-18 03:50:15 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// MacaroonCredential wraps a macaroon to implement the
|
|
|
|
// credentials.PerRPCCredentials interface.
|
|
|
|
type MacaroonCredential struct {
|
|
|
|
*macaroon.Macaroon
|
|
|
|
}
|
|
|
|
|
|
|
|
// RequireTransportSecurity implements the PerRPCCredentials interface.
|
|
|
|
func (m MacaroonCredential) RequireTransportSecurity() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2017-08-22 08:18:19 +02:00
|
|
|
// GetRequestMetadata implements the PerRPCCredentials interface. This method
|
|
|
|
// is required in order to pass the wrapped macaroon into the gRPC context.
|
|
|
|
// With this, the macaroon will be available within the request handling scope
|
|
|
|
// of the ultimate gRPC server implementation.
|
2017-08-18 03:50:15 +02:00
|
|
|
func (m MacaroonCredential) GetRequestMetadata(ctx context.Context,
|
|
|
|
uri ...string) (map[string]string, error) {
|
2017-08-22 08:18:19 +02:00
|
|
|
|
2017-08-18 03:50:15 +02:00
|
|
|
macBytes, err := m.MarshalBinary()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-08-22 08:18:19 +02:00
|
|
|
|
2017-08-18 03:50:15 +02:00
|
|
|
md := make(map[string]string)
|
|
|
|
md["macaroon"] = hex.EncodeToString(macBytes)
|
|
|
|
return md, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewMacaroonCredential returns a copy of the passed macaroon wrapped in a
|
|
|
|
// MacaroonCredential struct which implements PerRPCCredentials.
|
2021-08-12 16:07:18 +02:00
|
|
|
func NewMacaroonCredential(m *macaroon.Macaroon) (MacaroonCredential, error) {
|
2017-08-18 03:50:15 +02:00
|
|
|
ms := MacaroonCredential{}
|
2021-08-12 16:07:18 +02:00
|
|
|
|
|
|
|
// The macaroon library's Clone() method has a subtle bug that doesn't
|
|
|
|
// correctly clone all caveats. We need to use our own, safe clone
|
|
|
|
// function instead.
|
|
|
|
var err error
|
|
|
|
ms.Macaroon, err = SafeCopyMacaroon(m)
|
|
|
|
if err != nil {
|
|
|
|
return ms, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return ms, nil
|
2017-08-18 03:50:15 +02:00
|
|
|
}
|