~sircmpwn/gql.sr.ht

ref: 1fd9e352177eb4f56583e66123eba997931321dc gql.sr.ht/auth/middleware.go -rw-r--r-- 13.6 KiB
1fd9e352Drew DeVault s/Scopes/Grants/g a month ago
                                                                                
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
package auth

import (
	"bytes"
	"context"
	"crypto/sha512"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"regexp"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/vaughan0/go-ini"
	"github.com/vektah/gqlparser/gqlerror"

	"git.sr.ht/~sircmpwn/gql.sr.ht/config"
	"git.sr.ht/~sircmpwn/gql.sr.ht/crypto"
	"git.sr.ht/~sircmpwn/gql.sr.ht/database"
)

var userCtxKey = &contextKey{"user"}

type contextKey struct {
	name string
}

var (
	oauthBearerRegex = regexp.MustCompile(`^[0-9a-f]{32}$`)
	oauth2BearerRegex = regexp.MustCompile(`^[0-9a-zA-Z_+/]{33,}$`)
)

const (
	USER_UNCONFIRMED       = "unconfirmed"
	USER_ACTIVE_NON_PAYING = "active_non_paying"
	USER_ACTIVE_FREE       = "active_free"
	USER_ACTIVE_PAYING     = "active_paying"
	USER_ACTIVE_DELINQUENT = "active_delinquent"
	USER_ADMIN             = "admin"
	USER_UNKNOWN           = "unknown"
	USER_SUSPENDED         = "suspended"
)

const (
	AUTH_OAUTH_LEGACY = iota
	AUTH_OAUTH2 = iota
	AUTH_COOKIE = iota
	AUTH_INTERNAL = iota
)

// XXX: Rename to AuthContext
type User struct {
	ID               int
	Created          time.Time
	Updated          time.Time
	Username         string
	Email            string
	UserType         string
	URL              *string
	Location         *string
	Bio              *string
	SuspensionNotice *string
	AuthMethod       int

	// Only filled out if AuthMethod == AUTH_INTERNAL
	InternalAuth InternalAuth

	// Only filled out if AuthMethod == AUTH_OAUTH2
	OAuth2Token *OAuth2Token
	Access      map[string]string
}

func authError(w http.ResponseWriter, reason string, code int) {
	gqlerr := gqlerror.Errorf("Authentication error: %s", reason)
	b, err := json.Marshal(gqlerr)
	if err != nil {
		panic(err)
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	w.Write(b)
}

func authForUsername(ctx context.Context, db *sql.DB, username string) (*User, error) {
	var (
		err  error
		rows *sql.Rows
		user User
	)

	query := database.
		Select(ctx, []string{
			`u.id`, `u.username`,
			`u.created`, `u.updated`,
			`u.email`,
			`u.user_type`,
			`u.url`, `u.location`, `u.bio`,
			`u.suspension_notice`,
		}).
		From(`"user" u`).
		Where(`u.username = ?`, username)
	if rows, err = query.RunWith(db).Query(); err != nil {
		panic(err)
	}
	defer rows.Close()

	if !rows.Next() {
		if err := rows.Err(); err != nil {
			panic(err)
		}
		return nil, fmt.Errorf("Authenticating for unknown user %s", username)
	}
	if err := rows.Scan(&user.ID, &user.Username, &user.Created, &user.Updated,
		&user.Email, &user.UserType, &user.URL, &user.Location, &user.Bio,
		&user.SuspensionNotice); err != nil {
		panic(err)
	}
	if rows.Next() {
		if err := rows.Err(); err != nil {
			panic(err)
		}
		panic(errors.New("Multiple matching user accounts; invariant broken"))
	}

	if user.UserType == USER_SUSPENDED {
		return nil, fmt.Errorf("Account suspended with the following notice: %s\nContact support", user.SuspensionNotice)
	}

	return &user, nil
}

type AuthCookie struct {
	// The username of the authenticated user
	Name string `json:"name"`
}

func cookieAuth(db *sql.DB, cookie *http.Cookie,
	w http.ResponseWriter, r *http.Request, next http.Handler) {

	payload := crypto.Decrypt([]byte(cookie.Value))
	if payload == nil {
		authError(w, "Invalid authentication cookie", http.StatusForbidden)
		return
	}

	var auth AuthCookie
	if err := json.Unmarshal(payload, &auth); err != nil {
		panic(err) // Programmer error
	}

	user, err := authForUsername(r.Context(), db, auth.Name)
	if err != nil {
		authError(w, err.Error(), http.StatusForbidden)
		return
	}

	user.AuthMethod = AUTH_COOKIE

	ctx := context.WithValue(r.Context(), userCtxKey, user)

	r = r.WithContext(ctx)
	next.ServeHTTP(w, r)
}

type InternalAuth struct {
	// The username of the authenticated user
	Name     string `json:"name"`

	// An arbitrary identifier for this internal user, e.g. "git.sr.ht"
	ClientID string `json:"client_id"`

	// An arbitrary identifier for this internal node, e.g. "us-east-3.git.sr.ht"
	NodeID   string `json:"node_id"`
}

func internalAuth(internalNet []*net.IPNet, db *sql.DB, payload []byte,
	w http.ResponseWriter, r *http.Request, next http.Handler) {

	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		host = r.RemoteAddr
	}
	ip := net.ParseIP(host)
	if ip == nil {
		panic(fmt.Errorf("Unable to parse remote address"))
	}
	var ok bool = false
	for _, ipnet := range internalNet {
		ok = ok || ipnet.Contains(ip)
		if ok {
			break
		}
	}
	if !ok {
		authError(w, "Invalid source IP for internal auth", http.StatusForbidden)
		return
	}

	payload = crypto.DecryptWithExpiration(payload, 30*time.Second)
	if payload == nil {
		authError(w, "Invalid Authorization header", http.StatusForbidden)
		return
	}

	var auth InternalAuth
	if err := json.Unmarshal(payload, &auth); err != nil {
		panic(err) // Programmer error
	}

	if auth.ClientID == "" || auth.NodeID == "" {
		authError(w, "Invalid Authorization header", http.StatusForbidden)
	}

	user, err := authForUsername(r.Context(), db, auth.Name)
	if err != nil {
		authError(w, err.Error(), http.StatusForbidden)
		return
	}

	user.AuthMethod = AUTH_INTERNAL
	user.InternalAuth = auth

	ctx := context.WithValue(r.Context(), userCtxKey, user)

	r = r.WithContext(ctx)
	next.ServeHTTP(w, r)
}

func OAuth2(db *sql.DB, token string, hash [64]byte,
	w http.ResponseWriter, r *http.Request, next http.Handler) {

	var (
		err  error
		res  int32
		rows *sql.Rows
		user User
		wg   sync.WaitGroup
	)
	wg.Add(2)

	ot := DecodeToken(token)
	if ot == nil {
		authError(w, `Invalid or expired OAuth 2.0 bearer token`, http.StatusForbidden)
		return
	}

	go func() {
		defer wg.Done()
		// XXX: This branch could probably be eliminated if we:
		// - Revoked all tokens upon suspending a user
		// - Deferred loading the additional user details from the database
		//   until they were necessary (e.g. resolving query { me })

		query := database.
			Select(r.Context(), []string{
				`u.id`, `u.username`,
				`u.created`, `u.updated`,
				`u.email`,
				`u.user_type`,
				`u.url`, `u.location`, `u.bio`,
				`u.suspension_notice`,
			}).
			From(`"user" u`).
			Where(`u.username = ?`, ot.Username)
		if rows, err = query.RunWith(db).Query(); err != nil {
			panic(err)
		}
		defer rows.Close()

		if !rows.Next() {
			if err := rows.Err(); err != nil {
				panic(err)
			}
			log.Println("Failed to look up user associated with bearer token")
			return
		}
		if err := rows.Scan(
			&user.ID, &user.Username,
			&user.Created, &user.Updated,
			&user.Email,
			&user.UserType,
			&user.URL,
			&user.Location,
			&user.Bio,
			&user.SuspensionNotice); err != nil {
			panic(err)
		}
		if rows.Next() {
			if err := rows.Err(); err != nil {
				panic(err)
			}
			panic(errors.New("Multiple users of the same username; invariant broken"))
		}

		atomic.AddInt32(&res, 1)
	}()

	go func() {
		defer wg.Done()
		// Fetch revocation status for this token

		conf := config.ForContext(r.Context())
		meta, ok := conf.Get("meta.sr.ht", "origin")
		if !ok {
			panic(errors.New("No meta.sr.ht origin specified in config.ini"))
		}

		type GraphQLQuery struct {
			Query     string                 `json:"query"`
			Variables map[string]interface{} `json:"variables"`
		}
		type GraphQLResponse struct {
			Data struct {
				RevocationStatus bool `json:"tokenRevocationStatus"`
			} `json:"data"`
		}

		query := GraphQLQuery{
			Query: `
				query RevocationStatus($hash: String!, $clientId: String) {
					tokenRevocationStatus(hash: $hash, clientId: $clientId)
				}`,
			Variables: map[string]interface{} {
				"hash": hex.EncodeToString(hash[:]),
				"clientId": ot.ClientID,
			},
		}

		body, err := json.Marshal(query)
		if err != nil {
			panic(err) // Programmer error
		}

		reader := bytes.NewBuffer(body)
		req, err := http.NewRequestWithContext(r.Context(),
			"POST", fmt.Sprintf("%s/query", meta), reader)
		if err != nil {
			log.Printf("http.NewRequest: %e")
			return
		}
		req.Header.Add("Content-Type", "application/json")
		auth := InternalAuth{
			Name:     ot.Username,
			// TODO: Populate these better
			ClientID: "gql.sr.ht",
			NodeID:   "gql.sr.ht",
		}
		authBlob, err := json.Marshal(&auth)
		if err != nil {
			panic(err) // Programmer error
		}
		req.Header.Add("Authorization", fmt.Sprintf("Internal %s",
			crypto.Encrypt(authBlob)))
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			log.Printf("http.Do: %e", err)
			return
		}

		defer resp.Body.Close()

		respBody, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Printf("ioutil.ReadAll: %e")
			return
		}

		if resp.StatusCode != 200 {
			log.Printf("meta.sr.ht returned status %d: %s",
				resp.StatusCode, string(respBody))
			return
		}

		var result GraphQLResponse
		if err = json.Unmarshal(respBody, &result); err != nil {
			log.Printf("json.Unmarshal: %e")
			return
		}

		if !result.Data.RevocationStatus {
			atomic.AddInt32(&res, 1)
		}
	}()

	wg.Wait()
	if res != 2 {
		authError(w, "Invalid or expired OAuth 2.0 bearer token", http.StatusForbidden)
		return
	}

	if user.UserType == USER_SUSPENDED {
		authError(w, fmt.Sprintf("Account suspended with the following notice: %s\nContact support",
			user.SuspensionNotice), http.StatusForbidden)
		return
	}

	user.AuthMethod = AUTH_OAUTH2
	user.OAuth2Token = ot

	if ot.Grants != "" {
		user.Access = make(map[string]string)
		for _, grant := range strings.Split(ot.Grants, ",") {
			var (
				service string
				scope   string
				access  string
			)
			parts := strings.Split(grant, "/")
			if len(parts) != 2 {
				panic(errors.New("OAuth grant without service/scope format"))
			}
			service = parts[0]
			parts = strings.Split(parts[1], ":")
			scope = parts[0]
			if len(parts) == 1 {
				access = "RO"
			} else {
				access = parts[1]
			}
			if service == config.ServiceName(r.Context()) {
				user.Access[scope] = access
			}
		}
	}

	ctx := context.WithValue(r.Context(), userCtxKey, &user)

	r = r.WithContext(ctx)
	next.ServeHTTP(w, r)
}

// TODO: Remove legacy OAuth support
func LegacyOAuth(db *sql.DB, bearer string, hash [64]byte,
	w http.ResponseWriter, r *http.Request, next http.Handler) {

	var (
		err     error
		expires time.Time
		rows    *sql.Rows
		scopes  string
		user    User
	)
	query := database.
		Select(r.Context(), []string{
			`ot.expires`,
			`ot.scopes`,
			`u.id`, `u.username`,
			`u.created`, `u.updated`,
			`u.email`,
			`u.user_type`,
			`u.url`, `u.location`, `u.bio`,
			`u.suspension_notice`,
		}).
		From(`oauthtoken ot`).
		Join(`"user" u ON u.id = ot.user_id`).
		Where(`ot.token_hash = ?`, bearer)
	if rows, err = query.RunWith(db).Query(); err != nil {
		panic(err)
	}
	defer rows.Close()

	if !rows.Next() {
		if err := rows.Err(); err != nil {
			panic(err)
		}
		authError(w, "Invalid or expired OAuth token", http.StatusForbidden)
		return
	}
	if err := rows.Scan(&expires, &scopes,
		&user.ID, &user.Username,
		&user.Created, &user.Updated,
		&user.Email,
		&user.UserType,
		&user.URL,
		&user.Location,
		&user.Bio,
		&user.SuspensionNotice); err != nil {
		panic(err)
	}
	if rows.Next() {
		if err := rows.Err(); err != nil {
			panic(err)
		}
		panic(errors.New("Multiple matching OAuth tokens; invariant broken"))
	}

	if time.Now().UTC().After(expires) {
		authError(w, "Invalid or expired OAuth token", http.StatusForbidden)
		return
	}

	if user.UserType == USER_SUSPENDED {
		authError(w, fmt.Sprintf("Account suspended with the following notice: %s\nContact support",
			user.SuspensionNotice), http.StatusForbidden)
		return
	}

	if scopes != "*" {
		authError(w, "Presently, OAuth authentication to the GraphQL API is only supported for OAuth tokens with all permissions, namely '*'.", http.StatusForbidden)
		return
	}

	user.AuthMethod = AUTH_OAUTH_LEGACY

	ctx := context.WithValue(r.Context(), userCtxKey, &user)

	r = r.WithContext(ctx)
	next.ServeHTTP(w, r)
}

func Middleware(conf ini.File, apiconf string) func(http.Handler) http.Handler {
	var internalNet []*net.IPNet
	src, ok := conf.Get(apiconf, "internal-ipnet")
	if !ok {
		// Conservative default
		src = "127.0.0.1/24,::1/64"
	}
	for _, cidr := range strings.Split(src, ",") {
		_, ipnet, err := net.ParseCIDR(cidr)
		if err != nil {
			panic(err)
		}
		internalNet = append(internalNet, ipnet)
	}

	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.URL.Path != "/query" {
				next.ServeHTTP(w, r)
				return
			}

			db := database.ForContext(r.Context())

			cookie, err := r.Cookie("sr.ht.unified-login.v1")
			if err == nil {
				cookieAuth(db, cookie, w, r, next)
				return
			}

			auth := r.Header.Get("Authorization")
			if auth == "" {
				authError(w, `Authorization header is required. Expected 'Authorization: Bearer <token>'`, http.StatusForbidden)
				return
			}

			z := strings.SplitN(auth, " ", 2)
			if len(z) != 2 {
				authError(w, "Invalid Authorization header", http.StatusBadRequest)
				return
			}

			var bearer string
			switch z[0] {
			case "Bearer":
				token := []byte(z[1])
				if oauth2BearerRegex.Match(token) {
					hash := sha512.Sum512(token)
					bearer = z[1]
					OAuth2(db, bearer, hash, w, r, next)
					return
				}
				if oauthBearerRegex.Match(token) {
					hash := sha512.Sum512(token)
					bearer = hex.EncodeToString(hash[:])
					LegacyOAuth(db, bearer, hash, w, r, next)
					return
				}
				authError(w, "Invalid OAuth bearer token", http.StatusBadRequest)
				return
			case "Internal":
				payload := []byte(z[1])
				internalAuth(internalNet, db, payload, w, r, next)
				return
			default:
				authError(w, "Invalid Authorization header", http.StatusBadRequest)
				return
			}

		})
	}
}


func ForContext(ctx context.Context) *User {
	raw, ok := ctx.Value(userCtxKey).(*User)
	if !ok {
		panic(errors.New("Invalid authentication context"))
	}
	return raw
}