-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
249 lines (217 loc) · 7.27 KB
/
main.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
// Copyright The Linux Foundation and its contributors.
// SPDX-License-Identifier: MIT
// The auth0-cas-service-go service.
package main
import (
"context"
_ "expvar"
"flag"
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/evalphobia/logrus_fluent"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
semconv "go.opentelemetry.io/otel/semconv/v1.10.0"
"go.opentelemetry.io/otel/trace"
)
type contextID int
const (
logEntryID contextID = iota
serviceName = "auth0-cas-server-go"
)
var (
httpClient = http.DefaultClient
)
// main parses optional flags and starts http listener.
func main() {
var debug = flag.Bool("d", false, "enable debug logging")
var logJSON = flag.Bool("json", false, "force json logging to console (default: autodetect enviroment)")
var noTrace = flag.Bool("notrace", false, "disable OTLP tracing output")
var port = flag.String("p", "5000", "port")
var bind = flag.String("bind", "*", "interface to bind on")
flag.Usage = func() {
flag.PrintDefaults()
os.Exit(2)
}
flag.Parse()
// Optional debug logging.
if os.Getenv("DEBUG") != "" || *debug {
logrus.SetLevel(logrus.DebugLevel)
}
_, isECS := os.LookupEnv("ECS_CONTAINER_METADATA_URI_V4")
switch {
case isECS:
// Assume output to CloudWatch logs which has native timestamps. Use
// "message" for cleaner integration with log aggregation service.
logrus.SetFormatter(&logrus.JSONFormatter{
DisableTimestamp: true,
FieldMap: logrus.FieldMap{
logrus.FieldKeyMsg: "message",
},
})
case *logJSON:
logrus.SetFormatter(&logrus.JSONFormatter{})
}
if fluentHost, useFluent := os.LookupEnv("FLUENT_HOST"); useFluent {
var fluentPort int64 = 24224
if fluentPortEnv, ok := os.LookupEnv("FLUENT_PORT"); ok {
var err error
fluentPort, err = strconv.ParseInt(fluentPortEnv, 10, 32)
if err != nil {
logrus.WithField("fluent_port", fluentPortEnv).WithError(err).Fatal("unable to parse FLUENT_PORT")
}
}
hook, err := logrus_fluent.NewWithConfig(logrus_fluent.Config{
Host: fluentHost,
Port: int(fluentPort),
AsyncConnect: true,
})
if err != nil {
logrus.WithFields(logrus.Fields{
"host": fluentHost,
"port": fluentPort,
logrus.ErrorKey: err,
}).Fatal("could not set up fluentd logger")
}
hook.SetTag(serviceName + ".log")
// Convert error struct to string.
hook.AddFilter(logrus.ErrorKey, logrus_fluent.FilterError)
logrus.AddHook(hook)
}
// Instrument Open Telemetry.
if !*noTrace {
// Start OTLP forwarder and register the global tracing provider.
shutdownOTLP := initOTLP()
defer shutdownOTLP()
// Instrument HTTP clients.
auth0Client.Transport = otelhttp.NewTransport(
auth0Client.Transport,
otelhttp.WithSpanNameFormatter(func(_ string, r *http.Request) string {
// Update the span name to include the remote host. This is disabled by
// default to avoid high-cardinality problems for services that connect
// to many different servers, such as with dynamic service discovery.
// This should not be a problem for this service.
return fmt.Sprintf("%s %s", r.Method, r.URL.Host)
}),
)
httpClient = &http.Client{Transport: otelhttp.NewTransport(nil)}
}
// Support GET/POST monitoring "ping".
http.HandleFunc("/ping", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "OK\n")
})
// CAS protocol 2 and 3.
http.HandleFunc("/cas/login", casLogin)
http.HandleFunc("/cas/logout", casLogout)
http.HandleFunc("/cas/serviceValidate", casServiceValidate)
http.HandleFunc("/cas/p3/serviceValidate", casServiceValidate)
http.HandleFunc("/cas/proxyValidate", casServiceValidate)
http.HandleFunc("/cas/p3/proxyValidate", casServiceValidate)
http.HandleFunc("/cas/proxy", casProxy)
// Interstitial page to implement OIDC callback to redirect to CAS service.
http.HandleFunc("/cas/oidc_callback", oauth2Callback)
// Set up middleware.
mux := loggingHandler(http.DefaultServeMux)
// Add middleware to instrument our HTTP server.
if !*noTrace {
// Per OpenTelemetry spec, http.server_name should be a *configured* (not
// determined by incoming request headers) virtual host, otherwise *unset*.
vhost := ""
mux = routeTagHandler(mux)
mux = otelhttp.NewHandler(
mux,
vhost,
otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
// Use "vhost/path/to/resource" as the span name. Pattern-based routers
// should not do this: but this service only serves up discrete paths.
return fmt.Sprintf("%s%s", operation, r.URL.Path)
}),
)
}
// Set up http listener using provided command line parameters.
var addr string
if *bind == "*" {
addr = ":" + *port
} else {
addr = *bind + ":" + *port
}
server := &http.Server{
Addr: addr,
Handler: mux,
ReadHeaderTimeout: 3 * time.Second,
}
err := server.ListenAndServe()
if err != nil {
logrus.WithError(err).Fatal("http listener error")
}
}
// routeTagHandler sets the OpenTelemetry route to the current path. Based on
// otelhttp.WithRoute, but implemented as middleware. This is different from
// instrumenting the request itself, which is done with otelhttp.NewHandler.
func routeTagHandler(inner http.Handler) http.Handler {
mw := func(w http.ResponseWriter, r *http.Request) {
span := trace.SpanFromContext(r.Context())
// (Note: for pattern-based routers, replace r.URL.Path with the matched
// pattern!)
span.SetAttributes(semconv.HTTPRouteKey.String(r.URL.Path))
inner.ServeHTTP(w, r)
}
return http.HandlerFunc(mw)
}
// loggingHandler adds a logrus.Entry into the context of the current request.
func loggingHandler(inner http.Handler) http.Handler {
mw := func(w http.ResponseWriter, r *http.Request) {
ctx := withLogger(r.Context(), requestLogger(r))
inner.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(mw)
}
func withLogger(ctx context.Context, logger *logrus.Entry) context.Context {
return context.WithValue(ctx, logEntryID, logger)
}
func appLogger(ctx context.Context) *logrus.Entry {
if ctx == nil {
return logrus.NewEntry(logrus.StandardLogger())
}
if logger, ok := ctx.Value(logEntryID).(*logrus.Entry); ok {
return logger
}
return logrus.NewEntry(logrus.StandardLogger())
}
func requestLogger(r *http.Request) *logrus.Entry {
e := logrus.WithFields(logrus.Fields{
"method": r.Method,
"url": r.URL.Path,
"query": r.URL.RawQuery,
})
var headerIP string
if cfg.RemoteIPHeader != "" {
headerIP = r.Header.Get(cfg.RemoteIPHeader)
}
if referer := r.Header.Get("Referer"); referer != "" {
e = e.WithField("referer", referer)
}
switch headerIP {
case "":
// Log the client IP.
e = e.WithField("client", r.RemoteAddr)
default:
// Log the IP recorded in the configured header.
e = e.WithField("client", headerIP)
}
// Add trace and span IDs (if any) for log/trace correlation.
spanContext := trace.SpanContextFromContext(r.Context())
if traceID := spanContext.TraceID(); traceID.IsValid() {
e = e.WithField("trace_id", traceID.String())
e = e.WithField("dd.trace_id", convertTraceID(traceID.String()))
}
if spanID := spanContext.SpanID(); spanID.IsValid() {
e = e.WithField("span_id", spanID.String())
e = e.WithField("dd.span_id", convertTraceID(spanID.String()))
}
e = e.WithField("trace_flags", spanContext.TraceFlags().String())
return e
}