-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
377 lines (322 loc) · 9.87 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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package main
import (
"context"
"embed"
"flag"
"fmt"
"io"
"io/fs"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/google/uuid"
"github.com/lstoll/cookiesession"
"github.com/lstoll/oidc"
"github.com/lstoll/oidc/core"
"github.com/lstoll/oidc/core/staticclients"
"github.com/lstoll/oidc/discovery"
"github.com/oklog/run"
"github.com/prometheus/client_golang/prometheus"
versioncollector "github.com/prometheus/client_golang/prometheus/collectors/version"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/version"
"github.com/tink-crypto/tink-go/v2/keyset"
"golang.org/x/sys/unix"
)
const progname = "webauthn-oidc-idp"
//go:embed web/public/*
var staticFiles embed.FS
func init() {
if version.Version == "" {
version.Version = "devel"
}
if version.Branch == "" {
version.Branch = "unknown"
}
prometheus.MustRegister(versioncollector.NewCollector(strings.ReplaceAll(progname, "-", "_")))
}
func main() {
ver := flag.Bool("version", false, "Print the version and exit.")
debug := flag.Bool("debug", false, "Enable debug logging")
addr := flag.String("http", "127.0.0.1:8085", "Run the IDP server on the given host:port.")
metrics := flag.String("metrics", "", "Expose Prometheus metrics on the given host:port.")
configFile := flag.String("config", "config.json", "Path to the config file.")
enroll := flag.Bool("enroll", false, "Enroll a user into the system.")
email := flag.String("email", "", "Email address for the user.")
fullname := flag.String("fullname", "", "Full name of the user.")
addCredential := flag.Bool("add-credential", false, "Generate a new credential enrollment URL for a user")
userID := flag.String("user-id", "", "ID of user to add credential to.")
listCredential := flag.Bool("list-credentials", false, "List credentials for the user-id")
flag.Parse()
if *ver {
fmt.Fprintln(os.Stdout, version.Print(progname))
os.Exit(0)
}
b, err := os.ReadFile(*configFile)
if err != nil {
fatalf("read config file: %v", err)
}
var cfg config
if err := loadConfig(b, &cfg); err != nil {
fatalf("load config file: %v", err)
}
var level slog.Leveler
if *debug {
level = slog.LevelDebug
}
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})))
ctx := context.Background()
db, err := openDB(cfg.Database)
if err != nil {
fatalf("open database at %s: %v", cfg.Database, err)
}
if *enroll {
if *email == "" {
fatal("required flag missing: email")
}
if *fullname == "" {
fatal("required flag missing: fullname")
}
user, err := db.CreateUser(User{
Email: *email,
FullName: *fullname,
})
if err != nil {
fatalf("create user: %v", err)
}
reloadDB(*addr)
fmt.Printf("Enroll at: %s\n", registrationURL(cfg.Issuer[0].URL, user))
return
} else if *addCredential {
if *userID == "" {
fatal("required flag missing: user-id")
}
user, err := db.GetUserByID(*userID)
if err != nil {
fatalf("get user %s: %w", userID, err)
}
user.EnrollmentKey = uuid.NewString()
if err := db.UpdateUser(user); err != nil {
fatalf("update user %s: %w", userID, err)
}
reloadDB(*addr)
fmt.Printf("Enroll at: %s\n", registrationURL(cfg.Issuer[0].URL, user))
return
} else if *listCredential {
if *userID == "" {
fatal("required flag missing: user-id")
}
user, err := db.GetUserByID(*userID)
if err != nil {
fatalf("get user %s: %w", userID, err)
}
for _, c := range user.Credentials {
fmt.Printf("credential: %s (added at %s)\n", c.Name, c.AddedAt)
}
return
}
if *addr == "" {
fatal("required flag missing: http")
}
issuer := cfg.Issuer[0]
if err := serve(ctx, db, issuer, *addr, *metrics); err != nil {
fatalf("start server: %v", err)
}
}
func serve(ctx context.Context, db *DB, issuer issuerConfig, addr, metrics string) error {
ksm, err := NewKeysetManager(db)
if err != nil {
return fmt.Errorf("creating OIDC keyset manager: %w", err)
}
oidcHandles := ksm.Handles(KeysetOIDC)
oidcmd := discovery.DefaultCoreMetadata(issuer.URL.String())
oidcmd.AuthorizationEndpoint = issuer.URL.String() + "/auth"
oidcmd.TokenEndpoint = issuer.URL.String() + "/token"
oidcmd.ScopesSupported = []string{oidc.ScopeOpenID, oidc.ScopeEmail, oidc.ScopeProfile, "offline"}
oidcmd.UserinfoEndpoint = issuer.URL.String() + "/userinfo"
discoh, err := discovery.NewConfigurationHandler(oidcmd, oidcHandles)
if err != nil {
return fmt.Errorf("configuring metadata handler: %w", err)
}
oidcsvr, err := core.New(&core.Config{
Issuer: issuer.URL.String(),
AuthValidityTime: 5 * time.Minute,
CodeValidityTime: 5 * time.Minute,
}, db.SessionManager(), &staticclients.Clients{Clients: issuer.Clients}, oidcHandles)
if err != nil {
return fmt.Errorf("failed to create OIDC server instance: %w", err)
}
webSessMgr, err := cookiesession.New[webSession]("idp", func() *keyset.Handle {
h, err := ksm.Handles(KeysetCookie).Handle(context.Background())
if err != nil {
// we should not hit this, the load comes from the DB TODO(lstoll)
// get a consistent way of looking up handles.
slog.Error("refreshing keyset", logErr(err))
os.Exit(1)
}
return h
}, cookiesession.Options{
MaxAge: 0, // Scopes it to browser lifecycle, which I think is good for now
Path: "/",
SameSite: http.SameSiteLaxMode,
Insecure: issuer.URL.Hostname() == "localhost", // safari is picky about this
})
if err != nil {
return fmt.Errorf("creating cookie session for webauthn: %w", err)
}
mux := http.NewServeMux()
mux.Handle("GET /.well-known/openid-configuration", discoh)
mux.Handle("GET /.well-known/jwks.json", discoh)
heh := &httpErrHandler{}
wn, err := webauthn.New(&webauthn.Config{
RPDisplayName: issuer.URL.Hostname(), // Display Name for your site
RPID: issuer.URL.Hostname(), // Generally the FQDN for your site
RPOrigins: []string{
issuer.URL.String(),
},
AuthenticatorSelection: protocol.AuthenticatorSelection{
UserVerification: protocol.VerificationRequired,
RequireResidentKey: ptr(true),
},
})
if err != nil {
return fmt.Errorf("configuring webauthn: %w", err)
}
// start configuration of webauthn manager
mgr := &webauthnManager{
db: db,
webauthn: wn,
sessmgr: webSessMgr,
}
mgr.AddHandlers(mux)
svr := oidcServer{
issuer: issuer.URL.String(),
oidcsvr: oidcsvr,
eh: heh,
tokenValidFor: 15 * time.Minute,
refreshValidFor: 12 * time.Hour,
sessmgr: webSessMgr,
// upstreamPolicy: []byte(ucp),
webauthn: wn,
db: db,
}
pubContent, err := fs.Sub(fs.FS(staticFiles), "web")
if err != nil {
return fmt.Errorf("creating public subfs: %w", err)
}
fs := http.FileServer(http.FS(pubContent))
mux.Handle("/public/", fs)
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("OK"))
})
_, loopback, err := net.ParseCIDR("127.0.0.0/8")
if err != nil {
return err
}
mux.HandleFunc("/reloaddb", func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if !loopback.Contains(net.ParseIP(ip)) {
w.WriteHeader(http.StatusForbidden)
return
}
if err := db.Reload(); err != nil {
slog.ErrorContext(r.Context(), "database reload failed", slog.Any("error", err))
http.Error(w, fmt.Sprintf("reload failed: %v", err), http.StatusInternalServerError)
} else {
slog.InfoContext(r.Context(), "database reloaded")
}
})
svr.AddHandlers(mux)
var g run.Group
g.Add(run.SignalHandler(ctx, os.Interrupt, unix.SIGTERM))
g.Add(ksm.Run, ksm.Interrupt)
// this will always try and create a session for discovery and stuff,
// but we shouldn't save it. but, we need it for logging and stuff. TODO
// at some point consider splitting the middleware, but then we might
// need to dup the middleware wrap or something.
hh := baseMiddleware(mux, webSessMgr)
hs := &http.Server{
Addr: addr,
Handler: hh,
}
g.Add(func() error {
slog.Info("server listing", slog.String("addr", "http://"+addr))
if err := hs.ListenAndServe(); err != nil {
return fmt.Errorf("serving http: %v", err)
}
return nil
}, func(error) {
// new context for this, parent is likely already shut down
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
_ = hs.Shutdown(ctx)
})
{
if metrics != "" {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
promsrv := &http.Server{Addr: metrics, Handler: mux}
g.Add(func() error {
slog.Info("metrics server listing", slog.String("addr", "http://"+metrics))
if err := promsrv.ListenAndServe(); err != nil {
return fmt.Errorf("serving metrics: %v", err)
}
return nil
}, func(error) {
promsrv.Close()
})
}
}
return g.Run()
}
func registrationURL(iss *url.URL, user User) *url.URL {
u := *iss
if !strings.HasSuffix(u.Path, "/") {
u.Path += "/"
}
u2, err := u.Parse("/registration")
if err != nil {
panic(err)
}
q := u2.Query()
q.Add("user_id", user.ID)
q.Add("enrollment_token", user.EnrollmentKey)
u2.RawQuery = q.Encode()
return u2
}
// reloadDB tells the server running on addr to reload its database from disk.
func reloadDB(addr string) {
resp, err := http.Get("http://" + addr + "/reloaddb")
if err != nil {
fatalf("database reload failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
fatalf("database reload failed: %s", string(b))
}
}
func fatal(s string) {
fmt.Fprintf(os.Stderr, "%s: %s\n", progname, s)
os.Exit(1)
}
func fatalf(s string, args ...any) {
fmt.Fprintf(os.Stderr, fmt.Sprintf("%s: %s\n", progname, s), args...)
os.Exit(1)
}
func logErr(err error) slog.Attr {
return slog.Any("error", err)
}
func ptr[T any](v T) *T {
return &v
}