• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 13717288701

07 Mar 2025 09:03AM UTC coverage: 58.235% (-10.4%) from 68.635%
13717288701

Pull #9546

github

web-flow
Merge b6ecf4d11 into 76808a81a
Pull Request #9546: macaroons: ip range constraint

16 of 35 new or added lines in 2 files covered. (45.71%)

27463 existing lines in 443 files now uncovered.

94371 of 162052 relevant lines covered (58.24%)

1.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

53.25
/macaroons/constraints.go
1
package macaroons
2

3
import (
4
        "bytes"
5
        "context"
6
        "fmt"
7
        "net"
8
        "strings"
9
        "time"
10

11
        "google.golang.org/grpc/peer"
12
        "gopkg.in/macaroon-bakery.v2/bakery/checkers"
13
        macaroon "gopkg.in/macaroon.v2"
14
)
15

16
const (
17
        // CondLndCustom is the first party caveat condition name that is used
18
        // for all custom caveats in lnd. Every custom caveat entry will be
19
        // encoded as the string
20
        // "lnd-custom <custom-caveat-name> <custom-caveat-condition>"
21
        // in the serialized macaroon. We choose a single space as the delimiter
22
        // between the because that is also used by the macaroon bakery library.
23
        CondLndCustom = "lnd-custom"
24
)
25

26
// CustomCaveatAcceptor is an interface that contains a single method for
27
// checking whether a macaroon with the given custom caveat name should be
28
// accepted or not.
29
type CustomCaveatAcceptor interface {
30
        // CustomCaveatSupported returns nil if a macaroon with the given custom
31
        // caveat name can be validated by any component in lnd (for example an
32
        // RPC middleware). If no component is registered to handle the given
33
        // custom caveat then an error must be returned. This method only checks
34
        // the availability of a validating component, not the validity of the
35
        // macaroon itself.
36
        CustomCaveatSupported(customCaveatName string) error
37
}
38

39
// Constraint type adds a layer of indirection over macaroon caveats.
40
type Constraint func(*macaroon.Macaroon) error
41

42
// Checker type adds a layer of indirection over macaroon checkers. A Checker
43
// returns the name of the checker and the checker function; these are used to
44
// register the function with the bakery service's compound checker.
45
type Checker func() (string, checkers.Func)
46

47
// AddConstraints returns new derived macaroon by applying every passed
48
// constraint and tightening its restrictions.
49
func AddConstraints(mac *macaroon.Macaroon,
UNCOV
50
        cs ...Constraint) (*macaroon.Macaroon, error) {
×
UNCOV
51

×
UNCOV
52
        // The macaroon library's Clone() method has a subtle bug that doesn't
×
UNCOV
53
        // correctly clone all caveats. We need to use our own, safe clone
×
UNCOV
54
        // function instead.
×
UNCOV
55
        newMac, err := SafeCopyMacaroon(mac)
×
UNCOV
56
        if err != nil {
×
UNCOV
57
                return nil, err
×
UNCOV
58
        }
×
59

UNCOV
60
        for _, constraint := range cs {
×
UNCOV
61
                if err := constraint(newMac); err != nil {
×
62
                        return nil, err
×
63
                }
×
64
        }
UNCOV
65
        return newMac, nil
×
66
}
67

68
// Each *Constraint function is a functional option, which takes a pointer
69
// to the macaroon and adds another restriction to it. For each *Constraint,
70
// the corresponding *Checker is provided if not provided by default.
71

72
// TimeoutConstraint restricts the lifetime of the macaroon
73
// to the amount of seconds given.
UNCOV
74
func TimeoutConstraint(seconds int64) func(*macaroon.Macaroon) error {
×
UNCOV
75
        return func(mac *macaroon.Macaroon) error {
×
UNCOV
76
                macaroonTimeout := time.Duration(seconds)
×
UNCOV
77
                requestTimeout := time.Now().Add(time.Second * macaroonTimeout)
×
UNCOV
78
                caveat := checkers.TimeBeforeCaveat(requestTimeout)
×
UNCOV
79
                return mac.AddFirstPartyCaveat([]byte(caveat.Condition))
×
UNCOV
80
        }
×
81
}
82

83
// IPLockConstraint locks a macaroon to a specific IP address. If ipAddr is an
84
// empty string, this constraint does nothing to accommodate  default value's
85
// desired behavior.
UNCOV
86
func IPLockConstraint(ipAddr string) func(*macaroon.Macaroon) error {
×
UNCOV
87
        return func(mac *macaroon.Macaroon) error {
×
88
                if ipAddr != "" {
×
89
                        macaroonIPAddr := net.ParseIP(ipAddr)
×
90
                        if macaroonIPAddr == nil {
×
UNCOV
91
                                return fmt.Errorf("incorrect macaroon IP-" +
×
UNCOV
92
                                        "lock address")
×
UNCOV
93
                        }
×
UNCOV
94
                        caveat := checkers.Condition("ipaddr",
×
UNCOV
95
                                macaroonIPAddr.String())
×
NEW
UNCOV
96

×
NEW
UNCOV
97
                        return mac.AddFirstPartyCaveat([]byte(caveat))
×
98
                }
99

NEW
UNCOV
100
                return nil
×
101
        }
102
}
103

104
// IPRangeLockConstraint locks a macaroon to a specific IP address range. If
105
// ipRange is an empty string, this constraint does nothing to accommodate
106
// default value's desired behavior.
NEW
107
func IPRangeLockConstraint(ipRange string) func(*macaroon.Macaroon) error {
×
NEW
108
        return func(mac *macaroon.Macaroon) error {
×
NEW
109
                if ipRange != "" {
×
NEW
110
                        _, net, err := net.ParseCIDR(ipRange)
×
NEW
111
                        if err != nil {
×
NEW
112
                                return fmt.Errorf("incorrect macaroon IP " +
×
NEW
113
                                        "range")
×
NEW
114
                        }
×
NEW
115
                        caveat := checkers.Condition("iprange", net.String())
×
NEW
116

×
117
                        return mac.AddFirstPartyCaveat([]byte(caveat))
×
118
                }
119

120
                return nil
×
121
        }
122
}
123

124
// IPLockChecker accepts client IP from the validation context and compares it
125
// with IP locked in the macaroon. It is of the `Checker` type.
126
func IPLockChecker() (string, checkers.Func) {
3✔
127
        return "ipaddr", func(ctx context.Context, cond, arg string) error {
6✔
128
                // Get peer info and extract IP address from it for macaroon
3✔
129
                // check.
3✔
130
                pr, ok := peer.FromContext(ctx)
3✔
131
                if !ok {
3✔
UNCOV
132
                        return fmt.Errorf("unable to get peer info from context")
×
UNCOV
133
                }
×
134
                peerAddr, _, err := net.SplitHostPort(pr.Addr.String())
3✔
135
                if err != nil {
3✔
UNCOV
136
                        return fmt.Errorf("unable to parse peer address")
×
UNCOV
137
                }
×
138

139
                if !net.ParseIP(arg).Equal(net.ParseIP(peerAddr)) {
6✔
140
                        msg := "macaroon locked to different IP address"
3✔
141
                        return fmt.Errorf(msg)
3✔
142
                }
3✔
143
                return nil
3✔
144
        }
145
}
146

147
// IPRangeLockChecker accepts client IP range from the validation context and
148
// compares it with the IP range locked in the macaroon. It is of the `Checker`
149
// type.
150
func IPRangeLockChecker() (string, checkers.Func) {
3✔
151
        return "iprange", func(ctx context.Context, cond, arg string) error {
6✔
152
                // Get peer info and extract IP range from it for macaroon
3✔
153
                // check.
3✔
154
                pr, ok := peer.FromContext(ctx)
3✔
155
                if !ok {
3✔
NEW
156
                        return fmt.Errorf("unable to get peer info from context")
×
NEW
157
                }
×
158
                peerAddr, _, err := net.SplitHostPort(pr.Addr.String())
3✔
159
                if err != nil {
3✔
NEW
160
                        return fmt.Errorf("unable to parse peer address")
×
NEW
161
                }
×
162

163
                _, ipNet, err := net.ParseCIDR(arg)
3✔
164
                if err != nil {
3✔
NEW
165
                        return fmt.Errorf("unable to parse macaroon IP range")
×
NEW
166
                }
×
167

168
                if !ipNet.Contains(net.ParseIP(peerAddr)) {
6✔
169
                        msg := "macaroon locked to different IP range"
3✔
170
                        return fmt.Errorf(msg)
3✔
171
                }
3✔
172

173
                return nil
3✔
174
        }
175
}
176

177
// CustomConstraint returns a function that adds a custom caveat condition to
178
// a macaroon.
179
func CustomConstraint(name, condition string) func(*macaroon.Macaroon) error {
×
180
        return func(mac *macaroon.Macaroon) error {
×
181
                // We rely on a name being set for the interception, so don't
×
182
                // allow creating a caveat without a name in the first place.
×
183
                if name == "" {
×
184
                        return fmt.Errorf("name cannot be empty")
×
185
                }
×
186

187
                // The inner (custom) condition is optional.
UNCOV
188
                outerCondition := fmt.Sprintf("%s %s", name, condition)
×
UNCOV
189
                if condition == "" {
×
UNCOV
190
                        outerCondition = name
×
UNCOV
191
                }
×
192

UNCOV
193
                caveat := checkers.Condition(CondLndCustom, outerCondition)
×
194
                return mac.AddFirstPartyCaveat([]byte(caveat))
×
195
        }
196
}
197

198
// CustomChecker returns a Checker function that is used by the macaroon bakery
199
// library to check whether a custom caveat is supported by lnd in general or
200
// not. Support in this context means: An additional gRPC interceptor was set up
201
// that validates the content (=condition) of the custom caveat. If such an
202
// interceptor is in place then the acceptor should return a nil error. If no
203
// interceptor exists for the custom caveat in the macaroon of a request context
204
// then a non-nil error should be returned and the macaroon is rejected as a
205
// whole.
206
func CustomChecker(acceptor CustomCaveatAcceptor) Checker {
3✔
207
        // We return the general name of all lnd custom macaroons and a function
3✔
208
        // that splits the outer condition to extract the name of the custom
3✔
209
        // condition and the condition itself. In the bakery library that's used
3✔
210
        // here, a caveat always has the following form:
3✔
211
        //
3✔
212
        // <condition-name> <condition-value>
3✔
213
        //
3✔
214
        // Because a checker function needs to be bound to the condition name we
3✔
215
        // have to choose a static name for the first part ("lnd-custom", see
3✔
216
        // CondLndCustom. Otherwise we'd need to register a new Checker function
3✔
217
        // for each custom caveat that's registered. To allow for a generic
3✔
218
        // custom caveat handling, we just add another layer and expand the
3✔
219
        // initial <condition-value> into
3✔
220
        //
3✔
221
        // "<custom-condition-name> <custom-condition-value>"
3✔
222
        //
3✔
223
        // The full caveat string entry of a macaroon that uses this generic
3✔
224
        // mechanism would therefore look like this:
3✔
225
        //
3✔
226
        // "lnd-custom <custom-condition-name> <custom-condition-value>"
3✔
227
        checker := func(_ context.Context, _, outerCondition string) error {
6✔
228
                if outerCondition != strings.TrimSpace(outerCondition) {
3✔
UNCOV
229
                        return fmt.Errorf("unexpected white space found in " +
×
UNCOV
230
                                "caveat condition")
×
UNCOV
231
                }
×
232
                if outerCondition == "" {
3✔
UNCOV
233
                        return fmt.Errorf("expected custom caveat, got empty " +
×
UNCOV
234
                                "string")
×
UNCOV
235
                }
×
236

237
                // The condition part of the original caveat is now name and
238
                // condition of the custom caveat (we add a layer of conditions
239
                // to allow one custom checker to work for all custom lnd
240
                // conditions that implement arbitrary business logic).
241
                parts := strings.Split(outerCondition, " ")
3✔
242
                customCaveatName := parts[0]
3✔
243

3✔
244
                return acceptor.CustomCaveatSupported(customCaveatName)
3✔
245
        }
246

247
        return func() (string, checkers.Func) {
6✔
248
                return CondLndCustom, checker
3✔
249
        }
3✔
250
}
251

252
// HasCustomCaveat tests if the given macaroon has a custom caveat with the
253
// given custom caveat name.
254
func HasCustomCaveat(mac *macaroon.Macaroon, customCaveatName string) bool {
3✔
255
        if mac == nil {
3✔
UNCOV
256
                return false
×
UNCOV
257
        }
×
258

259
        caveatPrefix := []byte(fmt.Sprintf(
3✔
260
                "%s %s", CondLndCustom, customCaveatName,
3✔
261
        ))
3✔
262
        for _, caveat := range mac.Caveats() {
6✔
263
                if bytes.HasPrefix(caveat.Id, caveatPrefix) {
6✔
264
                        return true
3✔
265
                }
3✔
266
        }
267

268
        return false
3✔
269
}
270

271
// GetCustomCaveatCondition returns the custom caveat condition for the given
272
// custom caveat name from the given macaroon.
273
func GetCustomCaveatCondition(mac *macaroon.Macaroon,
274
        customCaveatName string) string {
3✔
275

3✔
276
        if mac == nil {
3✔
UNCOV
277
                return ""
×
UNCOV
278
        }
×
279

280
        caveatPrefix := []byte(fmt.Sprintf(
3✔
281
                "%s %s ", CondLndCustom, customCaveatName,
3✔
282
        ))
3✔
283
        for _, caveat := range mac.Caveats() {
6✔
284
                // The caveat id has a format of
3✔
285
                // "lnd-custom [custom-caveat-name] [custom-caveat-condition]"
3✔
286
                // and we only want the condition part. If we match the prefix
3✔
287
                // part we return the condition that comes after the prefix.
3✔
288
                if bytes.HasPrefix(caveat.Id, caveatPrefix) {
6✔
289
                        caveatSplit := strings.SplitN(
3✔
290
                                string(caveat.Id),
3✔
291
                                string(caveatPrefix),
3✔
292
                                2,
3✔
293
                        )
3✔
294
                        if len(caveatSplit) == 2 {
6✔
295
                                return caveatSplit[1]
3✔
296
                        }
3✔
297
                }
298
        }
299

300
        // We didn't find a condition for the given custom caveat name.
301
        return ""
3✔
302
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc