/
handler.go
279 lines (236 loc) · 8.23 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
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
/*
* Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
* @copyright 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*/
package server
import (
"crypto/tls"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"github.com/gorilla/context"
"github.com/julienschmidt/httprouter"
"github.com/meatballhat/negroni-logrus"
"github.com/ory/go-convenience/corsx"
"github.com/ory/graceful"
"github.com/ory/herodot"
"github.com/ory/hydra/client"
"github.com/ory/hydra/config"
"github.com/ory/hydra/consent"
"github.com/ory/hydra/health"
"github.com/ory/hydra/jwk"
"github.com/ory/hydra/oauth2"
"github.com/ory/hydra/pkg"
"github.com/ory/metrics-middleware"
"github.com/pkg/errors"
"github.com/rs/cors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/urfave/negroni"
)
var _ = &consent.Handler{}
func enhanceRouter(c *config.Config, cmd *cobra.Command, serverHandler *Handler, router *httprouter.Router, middlewares []negroni.Handler, enableCors bool) http.Handler {
n := negroni.New()
for _, m := range middlewares {
n.Use(m)
}
n.UseFunc(serverHandler.rejectInsecureRequests)
n.UseHandler(router)
if enableCors {
c.GetLogger().Info("Enabled CORS")
options := corsx.ParseOptions()
return context.ClearHandler(cors.New(options).Handler(n))
} else {
return context.ClearHandler(n)
}
}
func RunServeAdmin(c *config.Config) func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
c.MustValidate()
checkDatabaseAllowed(c)
serverHandler, _, backend, mws := setup(c, cmd, args, "admin")
var wg sync.WaitGroup
wg.Add(2)
cert := getOrCreateTLSCertificate(cmd, c)
// go serve(c, cmd, enhanceRouter(c, cmd, serverHandler, frontend), c.GetFrontendAddress(), &wg)
go serve(c, cmd, enhanceRouter(c, cmd, serverHandler, backend, mws, viper.GetString("CORS_ENABLED") == "true"), c.GetBackendAddress(), &wg, cert)
wg.Wait()
}
}
func RunServePublic(c *config.Config) func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
c.MustValidate()
checkDatabaseAllowed(c)
serverHandler, frontend, _, mws := setup(c, cmd, args, "public")
var wg sync.WaitGroup
wg.Add(2)
cert := getOrCreateTLSCertificate(cmd, c)
go serve(c, cmd, enhanceRouter(c, cmd, serverHandler, frontend, mws, false), c.GetFrontendAddress(), &wg, cert)
// go serve(c, cmd, enhanceRouter(c, cmd, serverHandler, backend), c.GetBackendAddress(), &wg)
wg.Wait()
}
}
func RunServeAll(c *config.Config) func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
c.MustValidate()
serverHandler, frontend, backend, mws := setup(c, cmd, args, "all")
var wg sync.WaitGroup
wg.Add(2)
cert := getOrCreateTLSCertificate(cmd, c)
go serve(c, cmd, enhanceRouter(c, cmd, serverHandler, frontend, mws, false), c.GetFrontendAddress(), &wg, cert)
go serve(c, cmd, enhanceRouter(c, cmd, serverHandler, backend, mws, viper.GetString("CORS_ENABLED") == "true"), c.GetBackendAddress(), &wg, cert)
wg.Wait()
}
}
func setup(c *config.Config, cmd *cobra.Command, args []string, name string) (handler *Handler, frontend, backend *httprouter.Router, middlewares []negroni.Handler) {
fmt.Println(banner(c.BuildVersion))
frontend = httprouter.New()
backend = httprouter.New()
logger := c.GetLogger()
w := herodot.NewJSONWriter(logger)
w.ErrorEnhancer = nil
handler = NewHandler(c, w)
handler.registerRoutes(frontend, backend)
c.ForceHTTP, _ = cmd.Flags().GetBool("dangerous-force-http")
if !c.ForceHTTP {
if c.Issuer == "" {
logger.Fatalln("IssuerURL must be explicitly specified unless --dangerous-force-http is passed. To find out more, use `hydra help serve`.")
}
issuer, err := url.Parse(c.Issuer)
pkg.Must(err, "Could not parse issuer URL: %s", err)
if issuer.Scheme != "https" {
logger.Fatalln("IssuerURL must use HTTPS unless --dangerous-force-http is passed. To find out more, use `hydra help serve`.")
}
}
middlewares = append(
middlewares,
negronilogrus.NewMiddlewareFromLogger(c.GetLogger(), c.Issuer),
c.GetPrometheusMetrics(),
)
if ok, _ := cmd.Flags().GetBool("disable-telemetry"); !ok {
c.GetLogger().Println("Transmission of telemetry data is enabled, to learn more go to: https://www.ory.sh/docs/guides/latest/telemetry/")
enable := !(c.DatabaseURL == "" || c.DatabaseURL == "memory" || c.Issuer == "" || strings.Contains(c.Issuer, "localhost"))
m := metrics.NewMetricsManager(
metrics.Hash(c.Issuer+"|"+c.DatabaseURL),
enable,
"h8dRH3kVCWKkIFWydBmWsyYHR4M0u0vr",
[]string{
client.ClientsHandlerPath,
jwk.KeyHandlerPath,
jwk.WellKnownKeysPath,
oauth2.DefaultConsentPath,
oauth2.TokenPath,
oauth2.AuthPath,
oauth2.UserinfoPath,
oauth2.WellKnownPath,
oauth2.IntrospectPath,
oauth2.RevocationPath,
consent.ConsentPath,
consent.LoginPath,
health.AliveCheckPath,
health.ReadyCheckPath,
health.VersionPath,
health.MetricsPrometheusPath,
"/oauth2/auth/sessions/login",
"/oauth2/auth/sessions/consent",
"/health/status",
"/",
},
c.GetLogger(),
"ory-hydra",
)
go m.RegisterSegment(c.BuildVersion, c.BuildHash, c.BuildTime)
go m.CommitMemoryStatistics()
middlewares = append(middlewares, m)
}
return
}
func checkDatabaseAllowed(c *config.Config) {
if c.DatabaseURL == "memory" {
c.GetLogger().Fatalf(`When using "hydra serve admin" or "hydra serve public" the DATABASE_URL can not be set to "memory".`)
}
}
func serve(c *config.Config, cmd *cobra.Command, handler http.Handler, address string, wg *sync.WaitGroup, cert tls.Certificate) {
defer wg.Done()
var srv = graceful.WithDefaults(&http.Server{
Addr: address,
Handler: handler,
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
},
})
err := graceful.Graceful(func() error {
var err error
c.GetLogger().Infof("Setting up http server on %s", address)
if c.ForceHTTP {
c.GetLogger().Warnln("HTTPS disabled. Never do this in production.")
err = srv.ListenAndServe()
} else if c.AllowTLSTermination != "" {
c.GetLogger().Infoln("TLS termination enabled, disabling https.")
err = srv.ListenAndServe()
} else {
err = srv.ListenAndServeTLS("", "")
}
return err
}, srv.Shutdown)
if err != nil {
c.GetLogger().WithError(err).Fatal("Could not gracefully run server")
}
}
type Handler struct {
Clients *client.Handler
Keys *jwk.Handler
OAuth2 *oauth2.Handler
Consent *consent.Handler
Config *config.Config
H herodot.Writer
}
func NewHandler(c *config.Config, h herodot.Writer) *Handler {
return &Handler{Config: c, H: h}
}
func (h *Handler) registerRoutes(frontend, backend *httprouter.Router) {
c := h.Config
ctx := c.Context()
// Set up dependencies
injectJWKManager(c)
clientsManager := newClientManager(c)
injectFositeStore(c, clientsManager)
injectConsentManager(c, clientsManager)
oauth2Provider := newOAuth2Provider(c)
// Set up handlers
h.Clients = newClientHandler(c, backend, clientsManager)
h.Keys = newJWKHandler(c, frontend, backend)
h.Consent = newConsentHandler(c, frontend, backend)
h.OAuth2 = newOAuth2Handler(c, frontend, backend, ctx.ConsentManager, oauth2Provider, clientsManager)
_ = newHealthHandler(c, backend)
}
func (h *Handler) rejectInsecureRequests(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if r.TLS != nil || h.Config.ForceHTTP {
next.ServeHTTP(rw, r)
return
}
if err := h.Config.DoesRequestSatisfyTermination(r); err == nil {
next.ServeHTTP(rw, r)
return
} else {
h.Config.GetLogger().WithError(err).Warnln("Could not serve http connection")
}
h.H.WriteErrorCode(rw, r, http.StatusBadGateway, errors.New("Can not serve request over insecure http"))
}