~bigbes/core-go

ref: 1d358dfe62e09d96ab92ad6c2ffa0e7a5bb331d7 core-go/auth/middleware.go -rw-r--r-- 17.1 KiB
1d358dfe — Drew DeVault model: import from gql.sr.ht 5 years 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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
package auth

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

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

	"git.sr.ht/~sircmpwn/core-go/client"
	"git.sr.ht/~sircmpwn/core-go/config"
	"git.sr.ht/~sircmpwn/core-go/crypto"
	"git.sr.ht/~sircmpwn/core-go/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
)

type AuthContext struct {
	UserID           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, username string) (*AuthContext, error) {
	var auth AuthContext
	if err := database.WithTx(ctx, &sql.TxOptions{
		Isolation: 0,
		ReadOnly: true,
	}, func(tx *sql.Tx) error {
		var (
			err  error
			rows *sql.Rows
		)
		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(tx).Query(); err != nil {
			panic(err)
		}
		defer rows.Close()

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

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

	return &auth, nil
}

func authForOAuthClient(ctx context.Context, clientUUID string) (*AuthContext, error) {
	var auth AuthContext
	if err := database.WithTx(ctx, &sql.TxOptions{
		Isolation: 0,
		ReadOnly: true,
	}, func(tx *sql.Tx) error {
		var (
			err  error
			rows *sql.Rows
		)
		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(`"oauth2_client" client`).
			Join(`"user" u ON u.id = client.owner_id`).
			Where(`client.client_uuid = ?`, clientUUID)
		if rows, err = query.RunWith(tx).Query(); err != nil {
			panic(err)
		}
		defer rows.Close()

		if !rows.Next() {
			if err := rows.Err(); err != nil {
				panic(err)
			}
			return fmt.Errorf("Authenticating for unknown client ID %s", clientUUID)
		}
		if err := rows.Scan(&auth.UserID, &auth.Username, &auth.Created,
			&auth.Updated, &auth.Email, &auth.UserType, &auth.URL, &auth.Location,
			&auth.Bio, &auth.SuspensionNotice); err != nil {
			panic(err)
		}
		if rows.Next() {
			// TODO: Fetch user info from meta if necessary
			if err := rows.Err(); err != nil {
				panic(err)
			}
			panic(errors.New("Multiple matching user accounts; invariant broken"))
		}
		return nil
	}); err != nil {
		return nil, err
	}

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

	return &auth, nil
}

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

func cookieAuth(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 authCookie AuthCookie
	if err := json.Unmarshal(payload, &authCookie); err != nil {
		panic(err) // Programmer error
	}

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

	auth.AuthMethod = AUTH_COOKIE

	ctx := context.WithValue(r.Context(), userCtxKey, auth)
	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"`

	// Only used by specific meta.sr.ht routes
	OAuthClientUUID string `json:"oauth_client_id",omit-empty`
}

func internalAuth(internalNet []*net.IPNet, 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 internalAuth InternalAuth
	if err := json.Unmarshal(payload, &internalAuth); err != nil {
		panic(err) // Programmer error
	}

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

	var auth *AuthContext
	if internalAuth.OAuthClientUUID != "" {
		auth, err = authForOAuthClient(r.Context(), internalAuth.OAuthClientUUID)
	} else {
		auth, err = authForUsername(r.Context(), internalAuth.Name)
	}
	if err != nil {
		authError(w, err.Error(), http.StatusForbidden)
		return
	}

	auth.AuthMethod = AUTH_INTERNAL
	auth.InternalAuth = internalAuth

	ctx := context.WithValue(r.Context(), userCtxKey, auth)
	r = r.WithContext(ctx)
	next.ServeHTTP(w, r)
}

func FetchMetaProfile(ctx context.Context, username string, user *AuthContext) error {
	if config.ServiceName(ctx) == "meta.sr.ht" {
		panic(errors.New("Cannot fetch profile from ourselves"))
	}

	type GraphQLProfile struct {
		ID               int     `json:"id"`
		Username         string  `json:"username"`
		Email            string  `json:"email"`
		URL              *string `json:"url"`
		Location         *string `json:"location"`
		Bio              *string `json:"bio"`
		UserType         string  `json:"userType"`
		SuspensionNotice string  `json:"suspensionNotice"`
	}

	type GraphQLResponse struct {
		Data struct {
			Me GraphQLProfile `json:"me"`
		} `json:"data"`
	}

	query := client.GraphQLQuery{
		Query: `
			query {
				me {
					id
					username
					email
					url
					location
					bio
					userType
				}
			}`,
	}

	var result GraphQLResponse
	if err := client.Execute(ctx, username,
		"meta.sr.ht", query, &result); err != nil {
		return err
	}

	profile := result.Data.Me
	return database.WithTx(ctx, nil, func(tx *sql.Tx) error {
		row := tx.QueryRowContext(ctx, `
			INSERT INTO "user" (
				created,
				updated,
				username,
				email,
				user_type,
				url,
				location,
				bio,
				suspension_notice
			)
			VALUES (
				NOW() at time zone 'utc',
				NOW() at time zone 'utc',
				$1, $2, $3, $4, $5, $6, $7
			)
			ON CONFLICT DO NOTHING
			RETURNING (
				id,
				created,
				updated,
				username,
				email,
				user_type,
				url,
				location,
				bio,
				suspension_notice
			);`,
			profile.Username, profile.Email, profile.UserType, profile.URL,
			profile.Location, profile.Bio, profile.SuspensionNotice)

		// TODO: Register webhooks
		if err := row.Scan(&user.UserID, user.Created, user.Updated,
			&user.Username, &user.Email, &user.UserType, &user.URL,
			&user.Location, &user.Bio, &user.SuspensionNotice); err != nil {
			if err == sql.ErrNoRows {
				panic(errors.New("Failed to upsert user record from meta.sr.ht"))
			}
			return err
		}
		return nil
	})
}

func LookupUser(ctx context.Context, username string, user *AuthContext) error {
	return database.WithTx(ctx, &sql.TxOptions{
		Isolation: 0,
		ReadOnly: true,
	}, func(tx *sql.Tx) error {
		var (
			err  error
			rows *sql.Rows
		)
		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(tx).Query(); err != nil {
			return err
		}
		defer rows.Close()

		if !rows.Next() {
			if err = rows.Err(); err != nil {
				return err
			}
			return FetchMetaProfile(ctx, username, user)
		}
		if err = rows.Scan(
			&user.UserID, &user.Username,
			&user.Created, &user.Updated,
			&user.Email,
			&user.UserType,
			&user.URL,
			&user.Location,
			&user.Bio,
			&user.SuspensionNotice); err != nil {
			return err
		}
		if rows.Next() {
			if err = rows.Err(); err != nil {
				return err
			}
			panic(errors.New("Multiple users of the same username; invariant broken"))
		}
		return nil
	})
}

// Returns true if this token or client ID has been revoked (and therefore
// should not be trusted)
func LookupTokenRevocation(ctx context.Context,
	username string, hash [64]byte, clientID string) (bool, error) {
	type GraphQLResponse struct {
		Data struct {
			RevocationStatus bool `json:"tokenRevocationStatus"`
		} `json:"data"`
	}

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

	var result GraphQLResponse
	if err := client.Execute(ctx, username,
		"meta.sr.ht", query, &result); err != nil {
		return true, err
	}
	return result.Data.RevocationStatus, nil
}

func OAuth2(token string, hash [64]byte, w http.ResponseWriter,
	r *http.Request, next http.Handler) {
	var (
		auth    AuthContext
		err     error
		res     int32
		tempErr int32
		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()
		err = LookupUser(r.Context(), ot.Username, &auth)
		if err != nil {
			log.Printf("LookupUser: %e", err)
			atomic.AddInt32(&tempErr, 1)
		} else {
			atomic.AddInt32(&res, 1)
		}
	}()

	go func() {
		defer wg.Done()
		isRevoked, err := LookupTokenRevocation(r.Context(),
			ot.Username, hash, ot.ClientID)
		if err != nil {
			log.Printf("LookupTokenRevocation: %e", err)
			atomic.AddInt32(&tempErr, 1)
		} else if !isRevoked {
			atomic.AddInt32(&res, 1)
		}
	}()

	wg.Wait()
	if res != 2 {
		if tempErr != 0 {
			authError(w, "Temporary error; try again later", http.StatusInternalServerError)
		} else {
			authError(w, "Invalid or expired OAuth 2.0 bearer token", http.StatusForbidden)
		}
		return
	}

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

	auth.AuthMethod = AUTH_OAUTH2
	auth.OAuth2Token = ot

	if ot.Grants != "" {
		auth.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(fmt.Errorf("OAuth grant '%s' without service/scope format", grant))
			}
			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()) {
				auth.Access[scope] = access
			}
		}
	}

	ctx := context.WithValue(r.Context(), userCtxKey, &auth)
	r = r.WithContext(ctx)
	next.ServeHTTP(w, r)
}

// TODO: Remove legacy OAuth support
func LegacyOAuth(bearer string, hash [64]byte, w http.ResponseWriter,
	r *http.Request, next http.Handler) {
	var (
		auth    AuthContext
		expires time.Time
		scopes  string
	)
	if err := database.WithTx(r.Context(), &sql.TxOptions{
		Isolation: 0,
		ReadOnly: true,
	}, func(tx *sql.Tx) error {
		var (
			err  error
			rows *sql.Rows
		)
		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(tx).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 nil
		}
		if err := rows.Scan(&expires, &scopes,
			&auth.UserID, &auth.Username,
			&auth.Created, &auth.Updated,
			&auth.Email,
			&auth.UserType,
			&auth.URL,
			&auth.Location,
			&auth.Bio,
			&auth.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"))
		}
		return nil
	}); err != nil {
		panic(err)
	}

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

	if auth.UserType == USER_SUSPENDED {
		authError(w, fmt.Sprintf(
			"Account suspended with the following notice: %s\nContact support",
			auth.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
	}

	auth.AuthMethod = AUTH_OAUTH_LEGACY

	ctx := context.WithValue(r.Context(), userCtxKey, &auth)
	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
			}

			cookie, err := r.Cookie("sr.ht.unified-login.v1")
			if err == nil {
				cookieAuth(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(bearer, hash, w, r, next)
					return
				}
				if oauthBearerRegex.Match(token) {
					hash := sha512.Sum512(token)
					bearer = hex.EncodeToString(hash[:])
					LegacyOAuth(bearer, hash, w, r, next)
					return
				}
				authError(w, "Invalid OAuth bearer token", http.StatusBadRequest)
				return
			case "Internal":
				payload := []byte(z[1])
				internalAuth(internalNet, payload, w, r, next)
				return
			default:
				authError(w, "Invalid Authorization header", http.StatusBadRequest)
				return
			}

		})
	}
}

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