-
Notifications
You must be signed in to change notification settings - Fork 327
/
main.go
292 lines (241 loc) · 9.39 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
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
/*
Copyright 2020 The Vouch Proxy Authors.
Use of this source code is governed by The MIT License (MIT) that
can be found in the LICENSE file. Software distributed under The
MIT License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
OR CONDITIONS OF ANY KIND, either express or implied.
*/
package main
// Vouch Proxy
// github.com/vouch/vouch-proxy
/*
Hello Developer! Thanks for looking at the code!
Before submitting PRs, please see the README...
https://github.com/vouch/vouch-proxy#submitting-a-pull-request-for-a-new-feature
*/
import (
"embed"
"errors"
"flag"
"fmt"
"io/fs"
"log"
"net"
"net/http"
"os"
"os/user"
"strconv"
"strings"
"time"
// "net/http/pprof"
"github.com/julienschmidt/httprouter"
"go.uber.org/zap"
"github.com/vouch/vouch-proxy/handlers"
"github.com/vouch/vouch-proxy/pkg/cfg"
"github.com/vouch/vouch-proxy/pkg/cookie"
"github.com/vouch/vouch-proxy/pkg/domains"
"github.com/vouch/vouch-proxy/pkg/healthcheck"
"github.com/vouch/vouch-proxy/pkg/jwtmanager"
"github.com/vouch/vouch-proxy/pkg/responses"
"github.com/vouch/vouch-proxy/pkg/timelog"
)
// `version`, `semver` and others are populated during build by..
// go build -i -v -ldflags="-X main.version=$(git describe --always --long) -X main.semver=v$(git semver get)"
var (
version = "undefined"
builddt = "undefined"
host = "undefined"
semver = "undefined"
branch = "undefined"
uname = "undefined"
logger *zap.SugaredLogger
fastlog *zap.Logger
showVersion = flag.Bool("version", false, "display version and exit")
help = flag.Bool("help", false, "show usage")
scheme = map[bool]string{
false: "http",
true: "https",
}
// doProfile = flag.Bool("profile", false, "run profiler at /debug/pprof")
)
//go:embed static
var staticFs embed.FS
//go:embed templates
var templatesFs embed.FS
//go:embed .defaults.yml
var defaultsFs embed.FS
// fwdToZapWriter allows us to use the zap.Logger as our http.Server ErrorLog
// see https://stackoverflow.com/questions/52294334/net-http-set-custom-logger
type fwdToZapWriter struct {
logger *zap.Logger
}
func (fw *fwdToZapWriter) Write(p []byte) (n int, err error) {
fw.logger.Error(string(p))
return len(p), nil
}
// configure() is essentially init()
// for most other projects you would think of this as init()
// this epic issue related to the flag.parse change of behavior for go 1.13 explains some of what's going on here
// https://github.com/golang/go/issues/31859
// essentially, flag.parse() must be called in vouch-proxy's main() and *not* in init()
// this has a cascading effect on the zap logger since the log level can be set on the command line
// configure() explicitly calls package configure functions (domains.Configure() etc) mostly to set the logger
// without this setup testing and logging are screwed up
func configure() {
flag.Parse()
if *help {
flag.PrintDefaults()
os.Exit(1)
}
if *showVersion {
fmt.Printf("%s\n", semver)
os.Exit(0)
}
cfg.Templates = templatesFs
cfg.Defaults = defaultsFs
cfg.Configure()
healthcheck.CheckAndExitIfIsHealthCheck()
logger = cfg.Logging.Logger
fastlog = cfg.Logging.FastLogger
if err := cfg.ValidateConfiguration(); err != nil {
logger.Fatal(err)
}
domains.Configure()
jwtmanager.Configure()
cookie.Configure()
responses.Configure()
handlers.Configure()
timelog.Configure()
}
func main() {
configure()
listenStr := cfg.Cfg.Listen
if !strings.HasPrefix(cfg.Cfg.Listen, "unix:") {
listenStr = cfg.Cfg.Listen + ":" + strconv.Itoa(cfg.Cfg.Port)
checkTCPPortAvailable(listenStr)
}
tls := (cfg.Cfg.TLS.Cert != "" && cfg.Cfg.TLS.Key != "")
logger.Infow("starting "+cfg.Branding.FullName,
// "semver": semver,
"version", version,
"buildtime", builddt,
"uname", uname,
"buildhost", host,
"branch", branch,
"semver", semver,
"listen", scheme[tls]+"://"+listenStr,
"tls", tls,
"document_root", cfg.Cfg.DocumentRoot,
"oauth.provider", cfg.GenOAuth.Provider)
// router := mux.NewRouter()
router := httprouter.New()
if cfg.Cfg.DocumentRoot != "" {
logger.Debugf("adjusting all served URIs to be under %s", cfg.Cfg.DocumentRoot)
}
authH := http.HandlerFunc(handlers.ValidateRequestHandler)
router.HandlerFunc(http.MethodGet, cfg.Cfg.DocumentRoot+"/validate", timelog.TimeLog(jwtmanager.JWTCacheHandler(authH)))
router.HandlerFunc(http.MethodGet, cfg.Cfg.DocumentRoot+"/_external-auth-:id", timelog.TimeLog(jwtmanager.JWTCacheHandler(authH)))
loginH := http.HandlerFunc(handlers.LoginHandler)
router.HandlerFunc(http.MethodGet, cfg.Cfg.DocumentRoot+"/login", timelog.TimeLog(loginH))
logoutH := http.HandlerFunc(handlers.LogoutHandler)
router.HandlerFunc(http.MethodGet, cfg.Cfg.DocumentRoot+"/logout", timelog.TimeLog(logoutH))
callH := http.HandlerFunc(handlers.CallbackHandler)
router.HandlerFunc(http.MethodGet, cfg.Cfg.DocumentRoot+"/auth", timelog.TimeLog(callH))
authStateH := http.HandlerFunc(handlers.AuthStateHandler)
router.HandlerFunc(http.MethodGet, cfg.Cfg.DocumentRoot+"/auth/:state/", timelog.TimeLog(authStateH))
healthH := http.HandlerFunc(handlers.HealthcheckHandler)
router.HandlerFunc(http.MethodGet, "/healthcheck", timelog.TimeLog(healthH))
// this is the documented implemenation for static file serving but it doesn't seem to work with go:embed
// router.ServeFiles("/static/*filepath", http.FS(staticFs))
// so instead we publish all three routes
router.Handler(http.MethodGet, cfg.Cfg.DocumentRoot+"/static/css/main.css", http.StripPrefix(cfg.Cfg.DocumentRoot, http.FileServer(http.FS(staticFs))))
router.Handler(http.MethodGet, cfg.Cfg.DocumentRoot+"/static/img/favicon.ico", http.StripPrefix(cfg.Cfg.DocumentRoot, http.FileServer(http.FS(staticFs))))
router.Handler(http.MethodGet, cfg.Cfg.DocumentRoot+"/static/img/multicolor_V_500x500.png", http.StripPrefix(cfg.Cfg.DocumentRoot, http.FileServer(http.FS(staticFs))))
// this also works for static files
// router.NotFound = http.FileServer(http.FS(staticFs))
//
// if *doProfile {
// addProfilingHandlers(router)
// }
srv := &http.Server{
Handler: router,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: time.Duration(cfg.Cfg.WriteTimeout) * time.Second,
ReadTimeout: time.Duration(cfg.Cfg.ReadTimeout) * time.Second,
IdleTimeout: time.Duration(cfg.Cfg.IdleTimeout) * time.Second,
ErrorLog: log.New(&fwdToZapWriter{fastlog}, "", 0),
}
lis, cleanupFn, err := listen()
if err != nil {
logger.Fatal(err)
}
defer cleanupFn()
if tls {
srv.TLSConfig = cfg.TLSConfig(cfg.Cfg.TLS.Profile)
logger.Fatal(srv.ServeTLS(lis, cfg.Cfg.TLS.Cert, cfg.Cfg.TLS.Key))
} else {
logger.Fatal(srv.Serve(lis))
}
}
func listen() (lis net.Listener, cleanupFn func(), err error) {
if !strings.HasPrefix(cfg.Cfg.Listen, "unix:") {
lis, err = net.Listen("tcp", fmt.Sprintf("%s:%d", cfg.Cfg.Listen, cfg.Cfg.Port))
return lis, func() {}, err
}
socketPath := strings.TrimPrefix(cfg.Cfg.Listen, "unix:")
_, err = os.Stat(socketPath)
if err == nil {
if err = os.Remove(socketPath); err != nil {
return nil, nil, fmt.Errorf("remove existing socket file %s: %w", socketPath, err)
}
} else if !os.IsNotExist(err) {
return nil, nil, fmt.Errorf("stat socket file %s: %w", socketPath, err)
}
lis, err = net.Listen("unix", socketPath)
if err != nil {
return nil, nil, fmt.Errorf("listen %s: %w", socketPath, err)
}
mode := fs.FileMode(cfg.Cfg.SocketMode) // defaults to 0660 - see .defaults.yml
if err = os.Chmod(socketPath, mode); err != nil {
return nil, nil, fmt.Errorf("chmod socket file %s %#o", socketPath, mode)
}
if cfg.Cfg.SocketGroup != "" {
group, err := user.LookupGroup(cfg.Cfg.SocketGroup)
if err != nil {
return nil, nil, fmt.Errorf("lookup socket group: %s %w", cfg.Cfg.SocketGroup, err)
}
gid, err := strconv.Atoi(group.Gid)
if err != nil {
return nil, nil, fmt.Errorf("lookup socket group: invalid gid: %w", err)
}
if err := os.Chown(socketPath, -1, gid); err != nil {
return nil, nil, fmt.Errorf("chown socket: group: %s %w", socketPath, err)
}
}
return lis, func() { _ = os.Remove(socketPath) }, nil
}
func checkTCPPortAvailable(listen string) {
logger.Debug("checking availability of tcp port: " + listen)
conn, err := net.Listen("tcp", listen)
if err != nil {
logger.Error(err)
logger.Fatal(errors.New(listen + " is not available (is " + cfg.Branding.FullName + " already running?)"))
}
if err = conn.Close(); err != nil {
logger.Error(err)
}
}
// if you'd like to enable profiling uncomment these
// func addProfilingHandlers(router *httprouter.Router) {
// // https://stackoverflow.com/questions/47452471/pprof-profile-with-julienschmidtrouter-and-benchmarks-not-profiling-handler
// logger.Debugf("profiling routes added at http://%s:%d/debug/pprof/", cfg.Cfg.Listen, cfg.Cfg.Port)
// router.HandlerFunc(http.MethodGet, "/debug/pprof/", pprof.Index)
// router.HandlerFunc(http.MethodGet, "/debug/pprof/cmdline", pprof.Cmdline)
// router.HandlerFunc(http.MethodGet, "/debug/pprof/profile", pprof.Profile)
// router.HandlerFunc(http.MethodGet, "/debug/pprof/symbol", pprof.Symbol)
// router.HandlerFunc(http.MethodGet, "/debug/pprof/trace", pprof.Trace)
// router.Handler(http.MethodGet, "/debug/pprof/goroutine", pprof.Handler("goroutine"))
// router.Handler(http.MethodGet, "/debug/pprof/heap", pprof.Handler("heap"))
// router.Handler(http.MethodGet, "/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
// router.Handler(http.MethodGet, "/debug/pprof/block", pprof.Handler("block"))
// }