-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
441 lines (385 loc) · 12.1 KB
/
auth.go
File metadata and controls
441 lines (385 loc) · 12.1 KB
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package main
import (
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
type AuthConfig struct {
ClientID string
ClientSecret string
SessionSecret []byte
CookieDomain string
GitHubOrg string
AllowedUsers map[string]bool
}
type AuthClaims struct {
Username string `json:"sub"`
AvatarURL string `json:"avatar"`
ExpiresAt int64 `json:"exp"`
}
type User struct {
Username string
AvatarURL string
}
type contextKey string
const userContextKey contextKey = "user"
// contributorCache caches authorized usernames so we don't re-check GitHub every request.
var contributorCache = struct {
sync.RWMutex
users map[string]time.Time
}{users: make(map[string]time.Time)}
func userFromContext(r *http.Request) *User {
u, _ := r.Context().Value(userContextKey).(*User)
return u
}
func (s *Server) isLocal() bool {
return strings.HasPrefix(s.config.Domain, "localhost") || strings.HasPrefix(s.config.Domain, "127.0.0.1")
}
func (s *Server) baseURL() string {
if s.isLocal() {
return "http://" + s.config.Domain
}
return "https://" + s.config.Domain
}
// --- Cookie signing ---
func (s *Server) signCookie(claims AuthClaims) (string, error) {
payload, err := json.Marshal(claims)
if err != nil {
return "", err
}
encoded := base64.RawURLEncoding.EncodeToString(payload)
mac := hmac.New(sha256.New, s.auth.SessionSecret)
mac.Write([]byte(encoded))
sig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
return encoded + "." + sig, nil
}
func (s *Server) verifyCookie(value string) (*AuthClaims, bool) {
parts := strings.SplitN(value, ".", 2)
if len(parts) != 2 {
return nil, false
}
mac := hmac.New(sha256.New, s.auth.SessionSecret)
mac.Write([]byte(parts[0]))
expectedSig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
if !hmac.Equal([]byte(parts[1]), []byte(expectedSig)) {
return nil, false
}
payload, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return nil, false
}
var claims AuthClaims
if err := json.Unmarshal(payload, &claims); err != nil {
return nil, false
}
if time.Now().Unix() > claims.ExpiresAt {
return nil, false
}
return &claims, true
}
// --- Middleware ---
func (s *Server) authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host := r.Host
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
// Always allow auth endpoints on the main domain
// Compare against domain with and without port
mainDomain := s.config.Domain
if h, _, err := net.SplitHostPort(mainDomain); err == nil {
mainDomain = h
}
if (host == mainDomain || r.Host == s.config.Domain) && strings.HasPrefix(r.URL.Path, "/auth/") {
next.ServeHTTP(w, r)
return
}
// Always allow Caddy's domain check (internal)
if r.URL.Path == "/api/check-domain" {
next.ServeHTTP(w, r)
return
}
// In local dev, skip auth for PR subdomains — *.localhost cookies
// are unreliable across browsers. In prod the cookie domain works fine.
if s.isLocal() && host != mainDomain {
next.ServeHTTP(w, r)
return
}
// Check session cookie
cookie, err := r.Cookie("tl_preview")
if err != nil {
s.sendUnauth(w, r)
return
}
claims, ok := s.verifyCookie(cookie.Value)
if !ok {
s.sendUnauth(w, r)
return
}
user := &User{Username: claims.Username, AvatarURL: claims.AvatarURL}
ctx := context.WithValue(r.Context(), userContextKey, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (s *Server) sendUnauth(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
jsonError(w, "unauthorized", http.StatusUnauthorized)
return
}
http.Redirect(w, r, s.baseURL()+"/auth/login", http.StatusFound)
}
// --- OAuth handlers ---
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
// Generate CSRF state
stateBytes := make([]byte, 16)
rand.Read(stateBytes)
state := hex.EncodeToString(stateBytes)
http.SetCookie(w, &http.Cookie{
Name: "tl_oauth_state",
Value: state,
Path: "/auth/",
MaxAge: 600,
HttpOnly: true,
Secure: !s.isLocal(),
SameSite: http.SameSiteLaxMode,
})
params := url.Values{
"client_id": {s.auth.ClientID},
"redirect_uri": {s.baseURL() + "/auth/callback"},
"scope": {"read:org read:user"},
"state": {state},
}
http.Redirect(w, r, "https://github.com/login/oauth/authorize?"+params.Encode(), http.StatusFound)
}
func (s *Server) handleOAuthCallback(w http.ResponseWriter, r *http.Request) {
// Verify state
stateCookie, err := r.Cookie("tl_oauth_state")
if err != nil || stateCookie.Value != r.URL.Query().Get("state") {
http.Error(w, "Invalid OAuth state", http.StatusBadRequest)
return
}
code := r.URL.Query().Get("code")
if code == "" {
http.Error(w, "Missing code", http.StatusBadRequest)
return
}
// Exchange code for access token
token, err := s.exchangeCode(code)
if err != nil {
log.Printf("OAuth token exchange failed: %v", err)
http.Error(w, "Authentication failed", http.StatusInternalServerError)
return
}
// Get user info
username, avatarURL, err := s.getGitHubUser(token)
if err != nil {
log.Printf("Failed to get GitHub user: %v", err)
http.Error(w, "Failed to get user info", http.StatusInternalServerError)
return
}
// Check if authorized
if !s.isAuthorized(username, token) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, `<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Access Denied</title>
<style>
body { background: #0e0e16; color: #e0e0ef; font-family: -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
.card { background: #171723; border: 1px solid #2a2a3d; border-radius: 10px; padding: 2rem; max-width: 440px; text-align: center; }
h2 { font-size: 1.1rem; margin-bottom: 0.5rem; }
p { color: #8888a0; font-size: 0.85rem; line-height: 1.6; }
a { color: #9b7fff; }
</style></head><body>
<div class="card">
<h2>Access Denied</h2>
<p>Sorry <strong>%s</strong>, this preview service is available to TheLounge contributors.</p>
<p>You need to be a <a href="https://github.com/thelounge">thelounge</a> org member or have a merged PR to <a href="https://github.com/thelounge/thelounge">thelounge/thelounge</a>.</p>
</div></body></html>`, username)
return
}
log.Printf("User %s authenticated successfully", username)
// Set session cookie
claims := AuthClaims{
Username: username,
AvatarURL: avatarURL,
ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(),
}
cookieValue, err := s.signCookie(claims)
if err != nil {
http.Error(w, "Failed to create session", http.StatusInternalServerError)
return
}
http.SetCookie(w, &http.Cookie{
Name: "tl_preview",
Value: cookieValue,
Path: "/",
Domain: s.auth.CookieDomain,
MaxAge: 7 * 24 * 60 * 60,
HttpOnly: true,
Secure: !s.isLocal(),
SameSite: http.SameSiteLaxMode,
})
// Clear state cookie
http.SetCookie(w, &http.Cookie{
Name: "tl_oauth_state",
Path: "/auth/",
MaxAge: -1,
})
http.Redirect(w, r, s.baseURL()+"/", http.StatusFound)
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "tl_preview",
Path: "/",
Domain: s.auth.CookieDomain,
MaxAge: -1,
})
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, `<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Logged out</title>
<style>
body { background: #0e0e16; color: #e0e0ef; font-family: -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
.card { background: #171723; border: 1px solid #2a2a3d; border-radius: 10px; padding: 2rem; max-width: 440px; text-align: center; }
a { color: #9b7fff; text-decoration: none; border: 1px solid #2a2a3d; padding: 0.5rem 1rem; border-radius: 6px; display: inline-block; margin-top: 1rem; }
a:hover { border-color: #7c5cff; }
</style></head><body>
<div class="card">
<p>You've been logged out.</p>
<a href="/auth/login">Sign in again</a>
</div></body></html>`)
}
// --- GitHub API helpers ---
func (s *Server) exchangeCode(code string) (string, error) {
data := url.Values{
"client_id": {s.auth.ClientID},
"client_secret": {s.auth.ClientSecret},
"code": {code},
}
req, _ := http.NewRequest("POST", "https://github.com/login/oauth/access_token", strings.NewReader(data.Encode()))
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
var result struct {
AccessToken string `json:"access_token"`
Error string `json:"error"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", err
}
if result.Error != "" {
return "", fmt.Errorf("oauth error: %s", result.Error)
}
return result.AccessToken, nil
}
func (s *Server) getGitHubUser(token string) (username, avatarURL string, err error) {
req, _ := http.NewRequest("GET", "https://api.github.com/user", nil)
req.Header.Set("Authorization", "token "+token)
req.Header.Set("Accept", "application/vnd.github.v3+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", "", err
}
defer resp.Body.Close()
var user struct {
Login string `json:"login"`
AvatarURL string `json:"avatar_url"`
}
if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
return "", "", err
}
return user.Login, user.AvatarURL, nil
}
func (s *Server) isAuthorized(username, token string) bool {
// Manual allowlist
if s.auth.AllowedUsers[strings.ToLower(username)] {
log.Printf("User %s authorized via allowlist", username)
return true
}
// Check contributor cache
contributorCache.RLock()
if t, ok := contributorCache.users[username]; ok && time.Since(t) < 24*time.Hour {
contributorCache.RUnlock()
return true
}
contributorCache.RUnlock()
authorized := s.checkOrgMember(username, token) || s.checkMergedPRs(username, token)
if authorized {
contributorCache.Lock()
contributorCache.users[username] = time.Now()
contributorCache.Unlock()
}
return authorized
}
func (s *Server) checkOrgMember(username, token string) bool {
url := fmt.Sprintf("https://api.github.com/user/memberships/orgs/%s", s.auth.GitHubOrg)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "token "+token)
req.Header.Set("Accept", "application/vnd.github.v3+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("Org membership check failed: %v", err)
return false
}
defer resp.Body.Close()
io.Copy(io.Discard, resp.Body)
if resp.StatusCode == 200 {
log.Printf("User %s is a %s org member", username, s.auth.GitHubOrg)
return true
}
return false
}
func (s *Server) checkMergedPRs(username, token string) bool {
q := fmt.Sprintf("repo:%s type:pr author:%s is:merged", s.config.GitHubRepo, username)
searchURL := fmt.Sprintf("https://api.github.com/search/issues?q=%s&per_page=1", url.QueryEscape(q))
req, _ := http.NewRequest("GET", searchURL, nil)
req.Header.Set("Authorization", "token "+token)
req.Header.Set("Accept", "application/vnd.github.v3+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("Merged PR check failed: %v", err)
return false
}
defer resp.Body.Close()
var result struct {
TotalCount int `json:"total_count"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return false
}
if result.TotalCount > 0 {
log.Printf("User %s has %d merged PRs in %s", username, result.TotalCount, s.config.GitHubRepo)
return true
}
return false
}
// --- Session secret management ---
func loadOrCreateSecret(dataDir string) []byte {
path := filepath.Join(dataDir, ".session_secret")
if data, err := os.ReadFile(path); err == nil && len(data) == 32 {
return data
}
secret := make([]byte, 32)
rand.Read(secret)
os.WriteFile(path, secret, 0o600)
log.Printf("Generated new session secret")
return secret
}