forked from canonical/candid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
344 lines (295 loc) · 11 KB
/
server.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
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package identity
import (
"context"
"fmt"
"html/template"
"net/http"
"runtime/debug"
"time"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/bakery"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/bakery/identchecker"
"github.com/juju/aclstore/v2"
"github.com/juju/loggo"
"github.com/juju/utils/v2/debugstatus"
"github.com/julienschmidt/httprouter"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gopkg.in/errgo.v1"
"gopkg.in/httprequest.v1"
"github.com/kian99/candid/idp"
"github.com/kian99/candid/internal/auth"
"github.com/kian99/candid/internal/auth/httpauth"
"github.com/kian99/candid/internal/mfa"
"github.com/kian99/candid/internal/monitoring"
"github.com/kian99/candid/meeting"
"github.com/kian99/candid/params"
"github.com/kian99/candid/store"
)
const (
defaultAPIMacaroonTimeout = 24 * time.Hour
defaultDischargeMacaroonTimeout = 24 * time.Hour
defaultDischargeTokenTimeout = 6 * time.Hour
)
var logger = loggo.GetLogger("candid.internal.identity")
// NewAPIHandlerFunc is a function that returns set of httprequest
// handlers that uses the given Store pool, and server params.
type NewAPIHandlerFunc func(HandlerParams) ([]httprequest.Handler, error)
// New returns a handler that serves the given identity API versions using the
// db to store identity data. The key of the versions map is the version name.
func New(sp ServerParams, versions map[string]NewAPIHandlerFunc) (*Server, error) {
if len(versions) == 0 {
return nil, errgo.Newf("identity server must serve at least one version of the API")
}
// Create the bakery parts.
if sp.Key == nil {
var err error
sp.Key, err = bakery.GenerateKey()
if err != nil {
return nil, errgo.Notef(err, "cannot generate key")
}
}
locator := bakery.NewThirdPartyStore()
locator.AddInfo(sp.Location, bakery.ThirdPartyInfo{
PublicKey: sp.Key.Public,
Version: bakery.LatestVersion,
})
var rksf func([]bakery.Op) bakery.RootKeyStore
if sp.RootKeyStore != nil {
rksf = func([]bakery.Op) bakery.RootKeyStore {
return sp.RootKeyStore
}
}
oven := bakery.NewOven(bakery.OvenParams{
Namespace: auth.Namespace,
RootKeyStoreForOps: rksf,
Key: sp.Key,
Locator: locator,
Location: "identity",
})
if sp.APIMacaroonTimeout == 0 {
sp.APIMacaroonTimeout = defaultAPIMacaroonTimeout
}
if sp.DischargeMacaroonTimeout == 0 {
sp.DischargeMacaroonTimeout = defaultDischargeMacaroonTimeout
}
if sp.DischargeTokenTimeout == 0 {
sp.DischargeTokenTimeout = defaultDischargeTokenTimeout
}
aclManager, err := aclstore.NewManager(context.Background(), aclstore.Params{
Store: sp.ACLStore,
InitialAdminUsers: []string{auth.AdminUsername},
})
if err != nil {
return nil, errgo.Mask(err)
}
auth, err := auth.New(auth.Params{
AdminPassword: sp.AdminPassword,
Location: sp.Location,
MacaroonVerifier: oven,
Store: sp.Store,
IdentityProviders: sp.IdentityProviders,
ACLManager: aclManager,
})
if err != nil {
return nil, errgo.Mask(err)
}
aclAuthenticator := httpauth.New(oven, auth, sp.APIMacaroonTimeout)
aclHandler := aclManager.NewHandler(aclstore.HandlerParams{
RootPath: "/acl",
Authenticate: func(ctx context.Context, w http.ResponseWriter, req *http.Request) (aclstore.Identity, error) {
ai, err := aclAuthenticator.Auth(ctx, req, identchecker.LoginOp)
if err != nil {
WriteError(ctx, w, err)
return nil, errgo.Mask(err)
}
return ai.Identity.(aclstore.Identity), nil
},
})
if err := auth.SetAdminPublicKey(context.Background(), sp.AdminAgentPublicKey); err != nil {
return nil, errgo.Mask(err)
}
place, err := meeting.NewPlace(meeting.Params{
Store: sp.MeetingStore,
Metrics: monitoring.NewMeetingMetrics(),
ListenAddr: sp.PrivateAddr,
WaitTimeout: sp.RendezvousTimeout,
})
if err != nil {
return nil, errgo.Notef(err, "cannot create meeting place")
}
storeCollector := monitoring.StoreCollector{Store: sp.Store}
prometheus.Register(storeCollector)
// Create the HTTP server.
srv := &Server{
router: httprouter.New(),
meetingPlace: place,
storeCollector: storeCollector,
}
// Disable the automatic rerouting in order to maintain
// compatibility. It might be worthwhile relaxing this in the
// future.
srv.router.RedirectTrailingSlash = false
srv.router.RedirectFixedPath = false
srv.router.NotFound = http.HandlerFunc(notFound)
srv.router.MethodNotAllowed = http.HandlerFunc(srv.methodNotAllowed)
srv.router.Handle("OPTIONS", "/*path", srv.options)
srv.router.Handler("GET", "/metrics", promhttp.Handler())
srv.router.Handler("GET", "/acl/*path", aclHandler)
srv.router.Handler("PUT", "/acl/*path", aclHandler)
srv.router.Handler("POST", "/acl/*path", aclHandler)
srv.router.Handler("GET", "/static/*path", http.StripPrefix("/static", http.FileServer(sp.StaticFileSystem)))
for name, newAPI := range versions {
handlers, err := newAPI(HandlerParams{
ServerParams: sp,
Oven: oven,
Authorizer: auth,
MeetingPlace: place,
})
if err != nil {
return nil, errgo.Notef(err, "cannot create API %s", name)
}
for _, h := range handlers {
srv.router.Handle(h.Method, h.Path, h.Handle)
}
}
return srv, nil
}
// Server serves the identity endpoints.
type Server struct {
router *httprouter.Router
meetingPlace *meeting.Place
storeCollector monitoring.StoreCollector
}
// ServeHTTP implements http.Handler.
func (srv *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer func() {
if v := recover(); v != nil {
logger.Errorf("PANIC!: %v\n%s", v, debug.Stack())
httprequest.WriteJSON(w, http.StatusInternalServerError, params.Error{
Code: "panic",
Message: fmt.Sprintf("%v", v),
})
}
}()
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Bakery-Protocol-Version, Macaroons, X-Requested-With, Content-Type")
w.Header().Set("Access-Control-Cache-Max-Age", "600")
srv.router.ServeHTTP(w, req)
}
// Close closes any resources held by this Handler.
func (s *Server) Close() {
logger.Debugf("Closing Server")
s.meetingPlace.Close()
prometheus.Unregister(s.storeCollector)
}
// ServerParams contains configuration parameters for a server.
type ServerParams struct {
// MeetingStore holds the storage that will be used to store
// rendezvous information.
MeetingStore meeting.Store
// ProviderDataStore holds the storeage that can be used by
// identity providers to store data that is not associated with
// an individual identity.
ProviderDataStore store.ProviderDataStore
// RootKeyStore holds the root key store that will be used to
// store macaroon root keys within the identity server.
RootKeyStore bakery.RootKeyStore
// Store holds the identities store for the identity server.
Store store.Store
// AdminPassword holds the password for admin login.
AdminPassword string
// Key holds the keypair to use with the bakery service.
Key *bakery.KeyPair
// Location holds a URL representing the externally accessible
// base URL of the service, without a trailing slash.
Location string
// PrivateAddr should hold a dialable address that will be used
// for communication between identity servers. Note that this
// should not contain a port.
PrivateAddr string
// IdentityProviders contains the set of identity providers that
// should be initialised by the service.
IdentityProviders []idp.IdentityProvider
// MFAAuthenticator holds the multi-factor authenticator.
MFAAuthenticator *mfa.Authenticator
// DebugTeams contains the set of launchpad teams that may access
// the restricted debug endpoints.
// TODO remove this.
DebugTeams []string
// AdminAgentPublicKey contains the public key of the admin agent.
AdminAgentPublicKey *bakery.PublicKey
// StaticFileSystem contains an http.FileSystem that can be used
// to serve static files.
StaticFileSystem http.FileSystem
// Template contains a set of templates that are used to generate
// html output.
Template *template.Template
// DebugStatusCheckerFuncs contains functions that will be
// executed as part of a /debug/status check.
DebugStatusCheckerFuncs []debugstatus.CheckerFunc
// RendezvousTimeout holds the time after which an interactive discharge wait
// request will time out.
RendezvousTimeout time.Duration
// ACLStore holds the ACLStore for the identity server.
ACLStore aclstore.ACLStore
// RedirectLoginTrustedURLs contains a list of URLs that are
// trusted to be used as return_to URLs during an interactive
// login.
RedirectLoginTrustedURLs []string
// RedirectLoginTrustedDomains contains a list of domain names that
// are fully trusted to be used as return_to URLs during an
// interactive login. If the domain starts with the sequence "*."
// then all subdomains of the subsequent domain will be trusted.
RedirectLoginTrustedDomains []string
// APIMacaroonTimeout is the maximum life of an API macaroon.
APIMacaroonTimeout time.Duration
// DischargeMacaroonTimeout is the maximum life of a Discharge
// macaroon.
DischargeMacaroonTimeout time.Duration
// DischargeTokenTimeout is the maximum life of a Discharge
// token.
DischargeTokenTimeout time.Duration
// SkipLocationForCookiePaths instructs if the Cookie Paths are to
// be set relative to the Location Path or not.
SkipLocationForCookiePaths bool
// EnableEmailLogin enables the login with email address link on the
// authentication required page.
EnableEmailLogin bool
}
type HandlerParams struct {
ServerParams
// Oven contains a bakery.Oven that should be used by handlers to
// mint new macaroons.
Oven *bakery.Oven
// Authorizer contains an auth.Authroizer that should be used by
// handlers to authorize requests.
Authorizer *auth.Authorizer
// MeetingPlace contains the meeting place that should be used by
// handlers to complete rendezvous.
MeetingPlace *meeting.Place
}
// notFound is the handler that is called when a handler cannot be found
// for the requested endpoint.
func notFound(w http.ResponseWriter, req *http.Request) {
WriteError(context.TODO(), w, errgo.WithCausef(nil, params.ErrNotFound, "not found: %s", req.URL.Path))
}
// methodNotAllowed is the handler that is called when a handler cannot
// be found for the requested endpoint with the request method, but
// there is a handler avaiable using a different method.
func (s *Server) methodNotAllowed(w http.ResponseWriter, req *http.Request) {
// Check that the match method is not OPTIONS
for _, method := range []string{"GET", "POST", "PUT", "DELETE", "HEAD", "PATCH"} {
if method == req.Method {
continue
}
if h, _, _ := s.router.Lookup(method, req.URL.Path); h != nil {
WriteError(context.TODO(), w, errgo.WithCausef(nil, params.ErrMethodNotAllowed, "%s not allowed for %s", req.Method, req.URL.Path))
return
}
}
notFound(w, req)
}
// options handles every OPTIONS request and always succeeds.
func (s *Server) options(http.ResponseWriter, *http.Request, httprouter.Params) {}