-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
353 lines (305 loc) · 11.5 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
package main
import (
"bufio"
"errors"
"fmt"
"html/template"
"log/slog"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"github.com/caarlos0/env/v11"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
// config contains all options why may be configured via environment variables.
// See the README for more details.
var config struct {
CookieName string `env:"COOKIE_NAME,notEmpty"`
JWTValidity time.Duration `env:"JWT_VALIDITY" envDefault:"1h"`
JWTSecret string `env:"JWT_APP_SECRET,notEmpty,unset"`
JWTIssuer string `env:"JWT_APP_ID,notEmpty"`
JWTAudience string `env:"JWT_AUDIENCE" envDefault:"jitsi"`
JWTLeeway time.Duration `env:"JWT_LEEWAY" envDefault:"1m"`
JitsiURL url.URL `env:"PUBLIC_URL,notEmpty"`
HTMLDocRoot string `env:"HTML_DOCROOT" envDefault:"./html"`
HTMLTitle string `env:"HTML_TITLE" envDefault:"Jitsi Moderator Login"`
ModsFile string `env:"MODS_FILE" envDefault:"./mods.htpasswd"`
HTTPAddr string `env:"HTTP_ADDR" envDefault:":8080"`
}
// JitsiClaims defines the schema of the JWT generated by this program.
// Besides the standard JWT claims, it contains two Jitsi specific claims:
// "room" (restricting what rooms the JWT is valid for) and "context" (providing
// additional user context, such as their moderator status).
type JitsiClaims struct {
jwt.RegisteredClaims
Room string `json:"room,omitempty"`
Context *Context `json:"context,omitempty"`
}
// Context contains the user context
type Context struct {
User User `json:"user,omitempty"`
}
// User is the user context defining if the token-presenting user should have
// moderator rights or not
type User struct {
Moderator bool `json:"moderator,omitempty"`
}
// loadTokenFromCookie loads and verifies a JWT from a HTTP cookie. If the
// cookie and the contained JWT is valid, the raw token and its "context" claim
// are returned. If the JWT contained in the cookie is invalid, an error is returned.
// If no cookie was found in the HTTP request, http.ErrNoCookie is returned.
func loadTokenFromCookie(r *http.Request) (token string, context *Context, err error) {
c, err := r.Cookie(config.CookieName)
if err != nil {
return "", nil, err // no cookie
}
err = c.Valid()
if err != nil {
return "", nil, err // invalid cookie
}
claims := JitsiClaims{}
t, err := jwt.ParseWithClaims(c.Value, &claims,
func(token *jwt.Token) (interface{}, error) {
return []byte(config.JWTSecret), nil
},
jwt.WithExpirationRequired(),
jwt.WithIssuedAt(),
jwt.WithAudience(config.JWTAudience),
jwt.WithIssuer(config.JWTIssuer),
jwt.WithLeeway(config.JWTLeeway))
if err != nil {
return "", nil, err // invalid JWT
}
return t.Raw, claims.Context, nil
}
// generateToken generates and signs a new JWT. With the exception of the passed
// in context (which may be nil), all claims and the signing secret are read
// from the global config struct.
func generateToken(context *Context) (token string, err error) {
now := time.Now()
claims := JitsiClaims{
RegisteredClaims: jwt.RegisteredClaims{
Audience: []string{config.JWTAudience},
Issuer: config.JWTIssuer,
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(config.JWTValidity)),
},
Room: "*", // valid for all Jitsi rooms
Context: context,
}
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return t.SignedString([]byte(config.JWTSecret))
}
// redirectToJitsi redirects the current HTTP request back to Jitsi, presenting
// the JWT contained in rawToken if redirecting back to a room
func redirectToJitsi(w http.ResponseWriter, r *http.Request, context *Context, rawToken string) {
// Jitsi base URL
jitsiURL := url.URL{
Scheme: config.JitsiURL.Scheme,
Host: config.JitsiURL.Host,
}
// If a `room` query parameter was provided to us, we construct a URL
// containing the JWT, allowing the user to join the room automatically.
// If the room parameter is empty or missing, we redirect to the welcome
// page and do not present a JWT token.
room := r.URL.Query().Get("room")
if room != "" {
// Appends room name to target URL
jitsiURL.Path = room
// Jitsi expects the JWT to be passed via query parameter (`?jwt=...`)
jitsiURL.RawQuery = url.Values{
"jwt": []string{
rawToken,
},
}.Encode()
// If a room query parameter is present, we assume the user was redirected
// here by clicking on the "Join" button. Once we redirect the user back
// to Jitsi with a valid JWT, they would have to click the "Join"
// button again. Since this would lead to a bad user experience (i.e. the
// user has to press the "Join" button twice for no apparent reason),
// we tell Jitsi via URL config override to skip the prejoin screen and
// immediately join the meeting (effectively pressing the "Join" button
// for them the second time).
jitsiURL.Fragment = `config.prejoinConfig.enabled=false`
// BUG: Prosody (Jitsi's room and user management component) seems to flap
// the moderator status of users providing a any JWT, i.e. temporarily
// granting moderator rights even to regular users without a moderator
// token. That moderator right is taken away immediately to users without
// a moderator claim in their JWT, but still causes the web interface
// to show a "You're now a moderator" message, even though they are not.
//
// Therefore, as a workaround, we disable the "You're now a moderator"
// popup if the current JWT does not grant moderator rights to the
// current user.
isModerator := context != nil && context.User.Moderator
if !isModerator {
jitsiURL.Fragment += `&config.disabledNotifications=["notify.moderator"]`
}
}
http.Redirect(w, r, jitsiURL.String(), http.StatusSeeOther)
}
// htpasswd is a map containing usernames as key and bcrypt hashes as values
type htpasswd map[string]string
// loadHTPasswd parses a htpasswd formatted file and returns a map of users
// with their corresponding password hash.
func loadHTPasswd(file string) (htpasswd, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
lineNo := 0
h := htpasswd{}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lineNo++
// Skip empty lines or lines starting with `#` (i.e. comments)
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
// Expects every line to be formatted as `user:hash`
user, hash, ok := strings.Cut(line, ":")
if !ok {
return nil, fmt.Errorf("invalid htpasswd file (line %d): %s", lineNo, file)
}
h[user] = hash
}
if err := scanner.Err(); err != nil {
return nil, err
}
return h, nil
}
// isAuthenticated returns true if (and only if) the provided username and
// password match an entry in the htpasswd file
func (h htpasswd) isAuthenticated(username, password string) bool {
expectedPass, ok := h[username]
if !ok {
return false
}
err := bcrypt.CompareHashAndPassword([]byte(expectedPass), []byte(password))
return err == nil
}
// loginPage renders a HTML login page. An optional error message
// and HTTP status code can be passed in (e.g. if the previous login failed).
func loginPage(w http.ResponseWriter, error string, code int) {
// Load the HTML template file from the doc root folder
t, err := template.ParseFiles(path.Join(config.HTMLDocRoot, "login.tmpl.html"))
if err != nil {
slog.Error("failed to parse template", slog.Any("error", err))
http.Error(w, "failed to parse template", http.StatusInternalServerError)
return
}
// Render the template, passing in the .Error and .Title values
w.WriteHeader(code)
err = t.Execute(w, struct {
Title string
Error string
}{
Title: config.HTMLTitle,
Error: error,
})
if err != nil {
slog.Error("failed to render template", slog.Any("error", err))
return
}
}
// modLogin processes a moderator login request. We expect a HTTP POST request
// containing a "username" and "password" form value. Those credentials are
// checked against to the moderator file.
// If the credentials are valid, a JWT with a "Moderator" claim is
// generated, which Jitsi's `token_affiliation` plugin will use to grant
// moderator rights to the current user.
// The generated token is stored in a cookie, which is presented whenever the
// autologin callback is invoked by Jitsi. This ensures moderators do not have
// to provide their password again as long they still have a valid JWT.
func modLogin(w http.ResponseWriter, r *http.Request) {
// Load moderator password file
mods, err := loadHTPasswd(config.ModsFile)
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
slog.Error("failed to load htpasswd", slog.Any("error", err))
return
}
// Check for valid HTTP POST request
if err := r.ParseForm(); err != nil {
http.Error(w, fmt.Sprintf("invalid request: %s", err), http.StatusInternalServerError)
return
}
// Check username and password against mods map
user, pass := r.PostFormValue("username"), r.PostFormValue("password")
if !mods.isAuthenticated(user, pass) {
loginPage(w, "invalid username or password", http.StatusUnauthorized)
return
}
// User is authenticated, therefore we generate a token with a "Moderator"
// context claim
slog.Info("Generating moderator token", slog.String("user", user))
context := &Context{User: User{Moderator: true}}
token, err := generateToken(context)
if err != nil {
http.Error(w, fmt.Sprintf("unable to generate token: %s", err), http.StatusInternalServerError)
return
}
// Store the token in a cookie. This cookie is valid for the same duration
// as the JWT. The cookie is read by the autologin callback to skip the
// creation of a regular user JWT in favor of this higher-privilege
// moderator JWT
http.SetCookie(w, &http.Cookie{
Name: config.CookieName,
Value: token,
Path: "/autologin",
MaxAge: int(config.JWTValidity.Seconds()),
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode,
})
redirectToJitsi(w, r, context, token)
}
// autoLogin is the callback invoked by Jitsi whenever it requires a JWT
// for the current user
func autoLogin(w http.ResponseWriter, r *http.Request) {
// If the user previously logged in as a moderator, we stored their JWT
// token in a cookie. If the cookie and the contained JWT are both still
// valid, we present that JWT to Jitsi.
// If there is no cookie or the presented token is invalid,
// we generate a new regular user token without moderator permission.
token, context, err := loadTokenFromCookie(r)
if err != nil {
if !errors.Is(err, http.ErrNoCookie) {
slog.Info("failed validate cookie token", slog.Any("error", err), slog.Any("url", r.URL))
}
// No valid cookie was presented, generate a regular user token
context = nil
token, err = generateToken(context)
if err != nil {
http.Error(w, fmt.Sprintf("unable to generate token: %s", err), http.StatusInternalServerError)
return
}
}
redirectToJitsi(w, r, context, token)
}
func main() {
// Read configuration values from environment variables
if err := env.Parse(&config); err != nil {
slog.Error("failed to parse env variables", slog.Any("error", err))
os.Exit(1)
}
// HTTP endpoints and server
mux := http.NewServeMux()
mux.Handle("POST /login", http.HandlerFunc(modLogin))
mux.Handle("GET /login", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
loginPage(w, "", http.StatusOK)
}))
mux.Handle("GET /autologin", http.HandlerFunc(autoLogin))
slog.Info("starting HTTP server", "addr", config.HTTPAddr)
err := http.ListenAndServe(config.HTTPAddr, mux)
if !errors.Is(err, http.ErrServerClosed) {
slog.Error("listener failed", slog.Any("error", err))
os.Exit(1)
}
}