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
|
package main
import (
"context"
"crypto/rand"
"embed"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"html/template"
"io"
"io/fs"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/peterbourgon/ff/v3"
"golang.org/x/oauth2"
)
var (
//go:embed static/*
_staticFiles embed.FS
staticFiles, _ = fs.Sub(_staticFiles, "static")
//go:embed static/index.gotmpl
indexFile string
indexTmpl = template.Must(template.New("").Parse(indexFile))
)
func randString(nByte int) (string, error) {
b := make([]byte, nByte)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func setCallbackCookie(w http.ResponseWriter, r *http.Request, name, value string) {
c := &http.Cookie{
Name: name,
Value: value,
MaxAge: int(time.Hour.Seconds()),
Secure: r.TLS != nil,
HttpOnly: true,
}
http.SetCookie(w, c)
}
type args struct {
clientProvider string
clientID string
clientSecret string
port int
scopes string
origin string
}
func (a args) redirect() string {
return strings.TrimSuffix(a.origin, "/") + "/callback"
}
type OIDCConfig struct {
ClientProvider string `json:"client_provider"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Scopes string `json:"scopes"`
}
type Server struct {
args args
issuer string
scopes string
provider *oidc.Provider
verifier *oidc.IDTokenVerifier
oauth2Config *oauth2.Config
}
type IndexContext struct {
Issuer string
ClientID string
ClientSecret string
Scopes string
RedirectURI string
Results bool
TokenClaims string
UserInfo string
TokenResponse string
}
func (s *Server) updateConfig(ctx context.Context, config *OIDCConfig) error {
if config.ClientProvider == "" || config.ClientID == "" {
return fmt.Errorf("client provider and client ID are required")
}
provider, err := oidc.NewProvider(ctx, config.ClientProvider)
if err != nil {
return fmt.Errorf("failed to create OIDC provider: %v", err)
}
oidcConfig := &oidc.Config{
ClientID: config.ClientID,
}
verifier := provider.Verifier(oidcConfig)
scopes := strings.Fields(config.Scopes)
if len(scopes) == 0 {
scopes = []string{"profile", "email"}
}
oauth2Config := &oauth2.Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
Endpoint: provider.Endpoint(),
RedirectURL: s.args.redirect(),
Scopes: append([]string{oidc.ScopeOpenID}, scopes...),
}
s.issuer = config.ClientProvider
s.scopes = config.Scopes
s.provider = provider
s.verifier = verifier
s.oauth2Config = oauth2Config
return nil
}
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
config := OIDCConfig{
ClientProvider: r.FormValue("client_provider"),
ClientID: r.FormValue("client_id"),
ClientSecret: r.FormValue("client_secret"),
Scopes: r.FormValue("scopes"),
}
if config.ClientProvider == "" || config.ClientID == "" {
http.Error(w, "Client provider and client ID are required", http.StatusBadRequest)
return
}
if err := s.updateConfig(r.Context(), &config); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
http.Redirect(w, r, "/auth", http.StatusFound)
return
}
indexTmpl.Execute(w, IndexContext{
Issuer: s.args.clientProvider,
ClientID: s.args.clientID,
ClientSecret: s.args.clientSecret,
Scopes: s.args.scopes,
RedirectURI: s.args.redirect(),
})
}
func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
config := s.oauth2Config
if config == nil {
http.Error(w, "OIDC not configured", http.StatusBadRequest)
return
}
state, err := randString(16)
if err != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
nonce, err := randString(16)
if err != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
setCallbackCookie(w, r, "state", state)
setCallbackCookie(w, r, "nonce", nonce)
http.Redirect(w, r, config.AuthCodeURL(state, oidc.Nonce(nonce)), http.StatusFound)
}
func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
config := s.oauth2Config
provider := s.provider
verifier := s.verifier
if config == nil || provider == nil || verifier == nil {
http.Error(w, "OIDC not configured", http.StatusBadRequest)
return
}
state, err := r.Cookie("state")
if err != nil {
http.Error(w, "state not found", http.StatusBadRequest)
return
}
if r.URL.Query().Get("state") != state.Value {
http.Error(w, "state did not match", http.StatusBadRequest)
return
}
oauth2Token, err := config.Exchange(r.Context(), r.URL.Query().Get("code"))
if err != nil {
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
return
}
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
http.Error(w, "No id_token field in oauth2 token.", http.StatusInternalServerError)
return
}
idToken, err := verifier.Verify(r.Context(), rawIDToken)
if err != nil {
http.Error(w, "Failed to verify ID Token: "+err.Error(), http.StatusInternalServerError)
return
}
nonce, err := r.Cookie("nonce")
if err != nil {
http.Error(w, "nonce not found", http.StatusBadRequest)
return
}
if idToken.Nonce != nonce.Value {
http.Error(w, "nonce did not match", http.StatusBadRequest)
return
}
userInfo, err := provider.UserInfo(r.Context(), oauth2.StaticTokenSource(oauth2Token))
if err != nil {
http.Error(w, "Failed to get userinfo: "+err.Error(), http.StatusInternalServerError)
return
}
var tokenClaims json.RawMessage
if err := idToken.Claims(&tokenClaims); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tokenClaimsJSON, err := json.MarshalIndent(tokenClaims, "", "\t")
if err != nil {
http.Error(w, "Could not marshal token claims JSON: "+err.Error(), http.StatusInternalServerError)
return
}
userInfoJSON, err := json.MarshalIndent(userInfo, "", "\t")
if err != nil {
http.Error(w, "Could not marshal userinfo JSON: "+err.Error(), http.StatusInternalServerError)
return
}
tokenResponseJSON, err := json.MarshalIndent(oauth2Token, "", "\t")
if err != nil {
http.Error(w, "Could not marshal oauth2 token response JSON: "+err.Error(), http.StatusInternalServerError)
return
}
indexTmpl.Execute(w, IndexContext{
Issuer: s.issuer,
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
Scopes: s.scopes,
RedirectURI: config.RedirectURL,
Results: true,
TokenClaims: string(tokenClaimsJSON),
UserInfo: string(userInfoJSON),
TokenResponse: string(tokenResponseJSON),
})
}
func main() {
var args args
fs := flag.NewFlagSet("oidc", flag.ExitOnError)
fs.StringVar(&args.clientProvider, "client-provider", "", "Default client provider (e.g. https://accounts.google.com)")
fs.StringVar(&args.clientID, "client-id", "", "Default client ID")
fs.StringVar(&args.clientSecret, "client-secret", "", "Default client secret")
fs.IntVar(&args.port, "port", 8000, "Port to run on")
fs.StringVar(&args.scopes, "scopes", "profile email", "Default scopes")
fs.StringVar(&args.origin, "origin", "http://localhost:8000", "Web origin")
fs.String("config", ".env", "Env config")
if err := ff.Parse(fs, os.Args[1:],
ff.WithEnvVarPrefix("OIDC"),
ff.WithConfigFileFlag("config"),
ff.WithAllowMissingConfigFile(true),
ff.WithConfigFileParser(ff.EnvParser),
); err != nil {
log.Fatal(err)
}
server := &Server{
args: args,
}
if args.clientProvider != "" && args.clientID != "" {
defaultConfig := &OIDCConfig{
ClientProvider: args.clientProvider,
ClientID: args.clientID,
ClientSecret: args.clientSecret,
Scopes: args.scopes,
}
if err := server.updateConfig(context.Background(), defaultConfig); err != nil {
log.Printf("Warning: Failed to initialize default config: %v", err)
}
}
mux := http.NewServeMux()
mux.HandleFunc("/", server.handleIndex)
mux.Handle("/_/", http.StripPrefix("/_/", http.FileServerFS(staticFiles)))
mux.HandleFunc("/auth", server.handleAuth)
mux.HandleFunc("/callback", server.handleCallback)
bind := fmt.Sprintf(":%d", args.port)
log.Println("listening on http://localhost" + bind)
log.Fatal(http.ListenAndServe(bind, mux))
}
|