/
idmtest.go
419 lines (379 loc) · 11.4 KB
/
idmtest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
// Package idmtest holds a mock implementation of the identity manager
// suitable for testing.
package idmtest
import (
"crypto/sha256"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/bakery"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/bakery/checkers"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/bakery/identchecker"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/bakerytest"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/httpbakery"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/httpbakery/agent"
"golang.org/x/net/context"
"gopkg.in/errgo.v1"
"gopkg.in/httprequest.v1"
macaroon "gopkg.in/macaroon.v2"
"github.com/juju/idmclient/v2"
"github.com/juju/idmclient/v2/params"
)
// GroupListGroup is the group that users must belong to in order to
// enquire about other users' groups.
const GroupListGroup = "group-lister"
// Server represents a mock identity server.
// It currently serves only the discharge and groups endpoints.
type Server struct {
// URL holds the URL of the mock identity server.
// The discharger endpoint is located at URL/v1/discharge.
URL *url.URL
// PublicKey holds the public key of the mock identity server.
PublicKey *bakery.PublicKey
// Bakery holds the macaroon bakery used by
// the mock server.
Bakery *identchecker.Bakery
discharger *bakerytest.Discharger
// mu guards the fields below it.
mu sync.Mutex
users map[string]*user
defaultUser string
}
type user struct {
groups []string
key *bakery.KeyPair
}
// NewServer runs a mock identity server. It can discharge
// macaroons and return information on user group membership.
// The returned server should be closed after use.
func NewServer() *Server {
srv := &Server{
users: make(map[string]*user),
}
srv.discharger = bakerytest.NewDischarger(nil)
srv.discharger.Checker = httpbakery.ThirdPartyCaveatCheckerFunc(srv.checkThirdPartyCaveat)
u, err := url.Parse(srv.discharger.Location())
if err != nil {
panic(err)
}
srv.URL = u
key, err := bakery.GenerateKey()
if err != nil {
panic(err)
}
srv.PublicKey = &key.Public
srv.discharger.AddHTTPHandlers(reqServer.Handlers(srv.newHandler))
srv.Bakery = identchecker.NewBakery(identchecker.BakeryParams{
Checker: checker,
Locator: srv,
Key: key,
IdentityClient: identityClient{srv},
Authorizer: identchecker.ACLAuthorizer{
GetACL: srv.getACL,
},
})
return srv
}
var reqServer = httprequest.Server{
ErrorMapper: errToResp,
}
func errToResp(ctx context.Context, err error) (int, interface{}) {
// Allow bakery errors to be returned as the bakery would
// like them, so that httpbakery.Client.Do will work.
if err, ok := errgo.Cause(err).(*httpbakery.Error); ok {
return httpbakery.ErrorToResponse(ctx, err)
}
errorBody := errorResponseBody(err)
status := http.StatusInternalServerError
switch errorBody.Code {
case params.ErrNotFound:
status = http.StatusNotFound
case params.ErrForbidden, params.ErrAlreadyExists:
status = http.StatusForbidden
case params.ErrBadRequest:
status = http.StatusBadRequest
case params.ErrUnauthorized, params.ErrNoAdminCredsProvided:
status = http.StatusUnauthorized
case params.ErrMethodNotAllowed:
status = http.StatusMethodNotAllowed
case params.ErrServiceUnavailable:
status = http.StatusServiceUnavailable
}
return status, errorBody
}
// errorResponse returns an appropriate error response for the provided error.
func errorResponseBody(err error) *params.Error {
errResp := ¶ms.Error{
Message: err.Error(),
}
cause := errgo.Cause(err)
if coder, ok := cause.(errorCoder); ok {
errResp.Code = coder.ErrorCode()
} else if errgo.Cause(err) == httprequest.ErrUnmarshal {
errResp.Code = params.ErrBadRequest
}
return errResp
}
type errorCoder interface {
ErrorCode() params.ErrorCode
}
// Close shuts down the server.
func (srv *Server) Close() {
srv.discharger.Close()
}
// PublicKeyForLocation implements bakery.PublicKeyLocator
// by returning the server's public key for all locations.
func (srv *Server) PublicKeyForLocation(loc string) (*bakery.PublicKey, error) {
return srv.PublicKey, nil
}
// ThirdPartyInfo implements bakery.ThirdPartyLocator.ThirdPartyInfo.
func (srv *Server) ThirdPartyInfo(ctx context.Context, loc string) (bakery.ThirdPartyInfo, error) {
return srv.discharger.ThirdPartyInfo(ctx, loc)
}
// UserPublicKey returns the key for the given user.
// It panics if the user has not been added.
func (srv *Server) UserPublicKey(username string) *bakery.KeyPair {
u := srv.user(username)
if u == nil {
panic("no user found")
}
return u.key
}
// IDMClient returns an identity manager client that takes
// to the given server as the given user name.
func (srv *Server) IDMClient(username string) *idmclient.Client {
c, err := idmclient.New(idmclient.NewParams{
BaseURL: srv.URL.String(),
AgentUsername: username,
Client: srv.Client(username),
})
if err != nil {
panic(err)
}
return c
}
// Client returns a bakery client that will discharge as the given user.
// If the user does not exist, it is added with no groups.
func (srv *Server) Client(username string) *httpbakery.Client {
c := httpbakery.NewClient()
u := srv.user(username)
if u == nil {
srv.AddUser(username)
u = srv.user(username)
}
c.Key = u.key
// Note that this duplicates the SetUpAuth that idmclient.New will do
// but that shouldn't matter as SetUpAuth is idempotent.
agent.SetUpAuth(c, &agent.AuthInfo{
Key: u.key,
Agents: []agent.Agent{{
URL: srv.URL.String(),
Username: username,
}},
})
return c
}
// SetDefaultUser configures the server so that it will discharge for
// the given user if no agent-login cookie is found. The user does not
// need to have been added. Note that this will bypass the
// VisitURL logic.
//
// If the name is empty, there will be no default user.
func (srv *Server) SetDefaultUser(name string) {
srv.mu.Lock()
defer srv.mu.Unlock()
srv.defaultUser = name
}
// AddUser adds a new user that's in the given set of groups.
// If the user already exists, the given groups are
// added to that user's groups.
func (srv *Server) AddUser(name string, groups ...string) {
srv.mu.Lock()
defer srv.mu.Unlock()
u := srv.users[name]
if u == nil {
key, err := bakery.GenerateKey()
if err != nil {
panic(err)
}
srv.users[name] = &user{
groups: groups,
key: key,
}
return
}
for _, g := range groups {
found := false
for _, ug := range u.groups {
if ug == g {
found = true
break
}
}
if !found {
u.groups = append(u.groups, g)
}
}
}
// RemoveUsers removes all added users and resets the
// default user to nothing.
func (srv *Server) RemoveUsers() {
srv.mu.Lock()
defer srv.mu.Unlock()
srv.users = make(map[string]*user)
srv.defaultUser = ""
}
// RemoveUser removes the given user.
func (srv *Server) RemoveUser(user string) {
srv.mu.Lock()
defer srv.mu.Unlock()
delete(srv.users, user)
}
func (srv *Server) user(name string) *user {
srv.mu.Lock()
defer srv.mu.Unlock()
return srv.users[name]
}
func (srv *Server) getACL(ctx context.Context, op bakery.Op) ([]string, bool, error) {
switch op.Action {
case "login":
return []string{identchecker.Everyone}, true, nil
case "list-groups":
return []string{strings.TrimPrefix(op.Entity, "user-"), GroupListGroup}, true, nil
default:
return nil, false, errgo.New("unrecognised operation")
}
}
func (srv *Server) checkThirdPartyCaveat(ctx context.Context, req *http.Request, info *bakery.ThirdPartyCaveatInfo, token *httpbakery.DischargeToken) ([]checkers.Caveat, error) {
if srv.defaultUser != "" {
return []checkers.Caveat{
idmclient.UserDeclaration(srv.defaultUser),
}, nil
}
dischargeID := srv.dischargeID(info)
ctx = contextWithDischargeID(ctx, dischargeID)
if token == nil || token.Kind != "agent" {
ierr := httpbakery.NewInteractionRequiredError(nil, req)
agent.SetInteraction(ierr, "/login/agent?discharge-id="+dischargeID)
return nil, ierr
}
var ms macaroon.Slice
if err := ms.UnmarshalBinary(token.Value); err != nil {
return nil, errgo.Mask(err)
}
ops, _, err := srv.Bakery.Oven.VerifyMacaroon(ctx, ms)
if err != nil {
return nil, errgo.Mask(err)
}
username := ""
for _, op := range ops {
if strings.HasPrefix(op.Entity, "user-") && op.Action == "discharge" {
username = strings.TrimPrefix(op.Entity, "user-")
break
}
}
_, err = srv.Bakery.Checker.Auth(ms).Allow(
ctx,
bakery.Op{
Entity: "user-" + username,
Action: "discharge",
},
)
if err != nil {
return nil, errgo.Mask(err)
}
return []checkers.Caveat{
idmclient.UserDeclaration(username),
}, nil
}
func (srv *Server) dischargeID(info *bakery.ThirdPartyCaveatInfo) string {
sum := sha256.Sum256(info.Caveat)
return fmt.Sprintf("%x", sum[:4])
}
func (srv *Server) newHandler(p httprequest.Params, req interface{}) (*handler, context.Context, error) {
_, err := srv.Bakery.Checker.Auth(httpbakery.RequestMacaroons(p.Request)...).Allow(p.Context, srv.opForRequest(req))
if err == nil {
return &handler{srv}, p.Context, nil
}
derr, ok := errgo.Cause(err).(*bakery.DischargeRequiredError)
if !ok {
return nil, p.Context, errgo.Mask(err)
}
version := httpbakery.RequestVersion(p.Request)
m, err := srv.Bakery.Oven.NewMacaroon(p.Context, version, derr.Caveats, derr.Ops...)
if err != nil {
return nil, p.Context, errgo.Notef(err, "cannot create macaroon")
}
return nil, p.Context, httpbakery.NewDischargeRequiredError(httpbakery.DischargeRequiredErrorParams{
Macaroon: m,
OriginalError: err,
Request: p.Request,
})
}
func (srv *Server) opForRequest(req interface{}) bakery.Op {
switch r := req.(type) {
case *agentMacaroonRequest:
return agentLoginOp
case *groupsRequest:
return bakery.Op{
Entity: "user-" + r.User,
Action: "list-groups",
}
default:
panic("unrecognised request")
}
}
var agentLoginOp = bakery.Op{
Entity: "agent",
Action: "login",
}
type handler struct {
srv *Server
}
type groupsRequest struct {
httprequest.Route `httprequest:"GET /v1/u/:User/groups"`
User string `httprequest:",path"`
}
func (h handler) GetGroups(p httprequest.Params, req *groupsRequest) ([]string, error) {
if u := h.srv.user(req.User); u != nil {
return u.groups, nil
}
return nil, params.ErrNotFound
}
// agentMacaroonRequest represents a request to get the
// agent macaroon that, when discharged, becomes
// the discharge token to complete the discharge.
type agentMacaroonRequest struct {
httprequest.Route `httprequest:"GET /login/agent"`
Username string `httprequest:"username,form"`
PublicKey *bakery.PublicKey `httprequest:"public-key,form"`
DischargeID string `httprequest:"discharge-id,form"`
}
type agentMacaroonResponse struct {
Macaroon *bakery.Macaroon `json:"macaroon"`
}
// Visit implements http.Handler. It performs the agent login interaction flow.
func (h handler) Visit(p httprequest.Params, req *agentMacaroonRequest) (*agentMacaroonResponse, error) {
m, err := h.srv.Bakery.Oven.NewMacaroon(
p.Context,
httpbakery.RequestVersion(p.Request),
[]checkers.Caveat{
dischargeIDCaveat(req.DischargeID),
bakery.LocalThirdPartyCaveat(req.PublicKey, httpbakery.RequestVersion(p.Request)),
},
bakery.Op{
Entity: "user-" + req.Username,
Action: "discharge",
},
)
if err != nil {
return nil, errgo.Mask(err)
}
return &agentMacaroonResponse{
Macaroon: m,
}, nil
}