-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
95 lines (83 loc) · 2.47 KB
/
handler.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
package main
import (
"bytes"
"context"
"sync"
"time"
"github.com/juju/httprequest"
errgo "gopkg.in/errgo.v1"
"gopkg.in/macaroon-bakery.v2-unstable/bakery"
"gopkg.in/macaroon-bakery.v2-unstable/httpbakery"
"github.com/rogpeppe/macaroon-cmd/params"
)
var rootKeyId = []byte("0")
const expiryDuration = 24 * time.Hour
type handler struct {
srv *server
mu sync.Mutex
rootKey []byte
}
var accessOp = bakery.Op{
Entity: "global",
Action: "access",
}
func (srv *server) newHandler(p httprequest.Params, req interface{}) (*handler, context.Context, error) {
switch req.(type) {
case *params.AccessRequest,
*params.SetPasswordRequest:
// Both these requests check the password held in the request.
default:
// All other requests require the access token.
_, err := srv.bakery.Checker.Auth(httpbakery.RequestMacaroons(p.Request)...).Allow(p.Context, accessOp)
if err != nil {
return nil, nil, errgo.Mask(err)
}
}
return &handler{
srv: srv,
}, p.Context, nil
}
func (h *handler) SetPassword(req *params.SetPasswordRequest) error {
if err := h.srv.setPassword(req.OldPassword, req.NewPassword); err != nil {
return errgo.Mask(err)
}
return nil
}
func (h *handler) NewRootKey(p httprequest.Params, req *params.NewRootKeyRequest) (*params.NewRootKeyResponse, error) {
masterKey, err := h.srv.getMasterKey()
if err != nil {
return nil, errgo.Mask(err)
}
// TODO use master key to decrypt root key stored elsewhere.
return ¶ms.NewRootKeyResponse{
Id: rootKeyId,
RootKey: masterKey,
}, nil
}
func (h *handler) FindRootKey(p httprequest.Params, req *params.FindRootKeyRequest) (*params.FindRootKeyResponse, error) {
if !bytes.Equal([]byte(req.Id), rootKeyId) {
return nil, params.ErrNotFound
}
masterKey, err := h.srv.getMasterKey()
if err != nil {
return nil, errgo.Mask(err)
}
return ¶ms.FindRootKeyResponse{
RootKey: masterKey,
}, nil
}
func (h *handler) Access(p httprequest.Params, req *params.AccessRequest) (*params.AccessResponse, error) {
if h.srv.needsPassword() {
return nil, errgo.WithCausef(nil, params.ErrInitialPasswordNeeded, "")
}
if err := h.srv.checkPassword(req.Password); err != nil {
return nil, errgo.WithCausef(err, params.ErrUnauthorized, "")
}
m, err := h.srv.bakery.Oven.NewMacaroon(p.Context, httpbakery.RequestVersion(p.Request), time.Now().Add(expiryDuration), nil, accessOp)
if err != nil {
return nil, errgo.Notef(err, "cannot make macaroon")
}
return ¶ms.AccessResponse{
Macaroon: m,
}, nil
}