aboutsummaryrefslogtreecommitdiff
path: root/oidc.go
blob: add2242d102d6df7bb7b0e0dc2abe231f062ba7f (plain) (blame)
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
/*
 * OpenID Connect for fbfp.
 *
 * Copyright (C) 2024  Runxi Yu <https://runxiyu.org>
 * SPDX-License-Identifier: AGPL-3.0-or-later
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/MicahParks/keyfunc/v3"
	"github.com/golang-jwt/jwt/v5"
)

var openid_configuration struct {
	AuthorizationEndpoint string `json:"authorization_endpoint"`
	TokenEndpoint         string `json:"token_endpoint"`
	JwksUri               string `json:"jwks_uri"`
	UserinfoEndpoint      string `json:"userinfo_endpoint"`
}

var openid_keyfunc keyfunc.Keyfunc

type msclaims_t struct {
	/* TODO: These may be non-portable Microsoft attributes */
	Name  string `json:"name"`  /* Scope: profile */
	Email string `json:"email"` /* Scope: email   */
	jwt.RegisteredClaims
}

/*
 * Fetch the OpenID Connect configuration. The endpoint specified in
 * the configuration is incomplete and we fetch the OpenID Connect
 * configuration from the well-known endpoint.
 * This seems to be supported by many authentication providers.
 * The following work, as config.Openid.Endpoint:
 * - https://login.microsoftonline.com/common
 * - https://accounts.google.com/.well-known/openid-configuration
 */
func get_openid_config(endpoint string) {
	resp := er(http.Get(endpoint + "/.well-known/openid-configuration"))
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		log.Fatal(fmt.Sprintf(
			"Got response code %d from openid-configuration\n",
			resp.StatusCode,
		))
	}
	e(json.NewDecoder(resp.Body).Decode(&openid_configuration))

	resp = er(http.Get(openid_configuration.JwksUri))
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		log.Fatal(fmt.Sprintf(
			"Got response code %d from JwksUri\n",
			resp.StatusCode,
		))
	}

	if config.Openid.Authorize != "" {
		openid_configuration.AuthorizationEndpoint =
			config.Openid.Authorize
	}

	jwks_json := er(io.ReadAll(resp.Body))

	/*
	 * TODO: The key set is never updated, which is technically incorrect.
	 * We could use keyfunc's auto-update mechanism, but I'd prefer
	 * controlling when to do it manually. Remember to wrap it around a
	 * mutex or some semaphores though.
	 */
	openid_keyfunc = er(keyfunc.NewJWKSetJSON(jwks_json))
}

func generate_authorization_url() string {
	/*
	 * TODO: Handle nonces and anti-replay. Incremental nonces would be
	 * nice on memory and speed (depending on how maps are implemented in
	 * Go, hopefully it's some sort of btree), but that requires either
	 * hacky atomics or having a multiple goroutines to handle
	 * authentication, neither of which are desirable.
	 */
	nonce := random(30)
	return fmt.Sprintf(
		"%s"+
			"?client_id=%s"+
			"&response_type=id_token"+
			"&redirect_uri=%s/oidc"+
			"&response_mode=form_post"+
			"&scope=openid+profile+email"+
			"&nonce=%s",
		openid_configuration.AuthorizationEndpoint,
		config.Openid.Client,
		config.Url,
		nonce,
	)
}

func handle_oidc(w http.ResponseWriter, req *http.Request) {
	if req.Method != "POST" {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(405)
		w.Write([]byte(
			"Error\n" +
				"Only POST is allowed on the OIDC callback.\n" +
				"Please return to the login page and retry.\n",
		))
		return
	}

	err := req.ParseForm()
	if err != nil {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(400)
		w.Write([]byte(fmt.Sprintf(
			"Error\n"+
				"Malformed form data.\n%s\n",
			err,
		)))
		return
	}

	returned_error := req.PostFormValue("error")
	if returned_error != "" {
		returned_error_description :=
			req.PostFormValue("error_description")
		if returned_error_description == "" {
			w.Header().Set(
				"Content-Type",
				"text/plain; charset=utf-8",
			)
			w.WriteHeader(400)
			w.Write([]byte(fmt.Sprintf(
				"Error\n%s\n",
				returned_error,
			)))
			return
		} else {
			w.Header().Set(
				"Content-Type",
				"text/plain; charset=utf-8",
			)
			w.WriteHeader(400)
			w.Write([]byte(fmt.Sprintf(
				"Error\n%s\n%s\n",
				returned_error,
				returned_error_description,
			)))
			return
		}
	}

	id_token_string := req.PostFormValue("id_token")
	if id_token_string == "" {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(400)
		w.Write([]byte(fmt.Sprintf("Error\nMissing id_token.\n")))
		return
	}

	token, err := jwt.ParseWithClaims(
		id_token_string,
		&msclaims_t{},
		openid_keyfunc.Keyfunc,
	)
	if err != nil {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(400)
		w.Write([]byte(fmt.Sprintf(
			"Error\n"+
				"Cannot parse claims.\n%s\n",
			err,
		)))
		return
	}

	switch {
	case token.Valid:
		break
	case errors.Is(err, jwt.ErrTokenMalformed):
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(400)
		w.Write([]byte(fmt.Sprintf("Error\nMalformed JWT token.\n")))
		return
	case errors.Is(err, jwt.ErrTokenSignatureInvalid):
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(400)
		w.Write([]byte(fmt.Sprintf("Error\nInvalid JWS signature.\n")))
		return
	case errors.Is(err, jwt.ErrTokenExpired) ||
		errors.Is(err, jwt.ErrTokenNotValidYet):
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(400)
		w.Write([]byte(fmt.Sprintf(
			"Error\n" +
				"JWT token expired or not yet valid.\n",
		)))
		return
	default:
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(400)
		w.Write([]byte(fmt.Sprintf("Error\nInvalid JWT token.\n")))
		return
	}

	claims, claims_ok := token.Claims.(*msclaims_t)

	if !claims_ok {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(400)
		w.Write([]byte(fmt.Sprintf("Error\nCannot unpack claims.\n")))
		return
	}

	cookie_value := random(20)

	cookie := http.Cookie{
		Name:     "session",
		Value:    cookie_value,
		SameSite: http.SameSiteLaxMode,
		HttpOnly: true,
		Secure:   config.Prod,
	}

	http.SetCookie(w, &cookie)
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")

	result, err := db.Exec(
		"INSERT INTO users (id, name, email) VALUES (?, ?, ?)",
		claims.Subject,
		claims.Name,
		claims.Email,
	)
	// TODO: handle err

	fmt.Println(result, err)

	http.Redirect(w, req, "/", 303)

	return

}