~sircmpwn/gql.sr.ht

ref: 1fd9e352177eb4f56583e66123eba997931321dc gql.sr.ht/auth/token.go -rw-r--r-- 1.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
package auth

import (
	"encoding/base64"
	"encoding/hex"
	"log"
	"time"

	"git.sr.ht/~sircmpwn/go-bare"

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

const TokenVersion uint = 0

type Timestamp int64

func (t Timestamp) Time() time.Time {
	return time.Unix(int64(t), 0)
}

func ToTimestamp(t time.Time) Timestamp {
	return Timestamp(t.Unix())
}

type OAuth2Token struct {
	Version  uint
	Expires  Timestamp
	Grants   string
	ClientID string
	Username string
}

func (ot *OAuth2Token) Encode() string {
	plain, err := bare.Marshal(ot)
	if err != nil {
		panic(err)
	}
	mac := crypto.HMAC(plain)
	return base64.RawStdEncoding.EncodeToString(append(plain, mac...))
}

func DecodeToken(token string) *OAuth2Token {
	payload, err := base64.RawStdEncoding.DecodeString(token)
	if err != nil {
		log.Printf("Invalid bearer token: invalid base64 %e", err)
		return nil
	}
	if len(payload) <= 32 {
		log.Printf("Invalid bearer token: payload <32 bytes")
		return nil
	}

	mac := payload[len(payload) - 32:]
	payload = payload[:len(payload) - 32]
	if crypto.HMACVerify(payload, mac) == false {
		log.Printf("Invalid bearer token: HMAC verification failed (MAC: [%d]%s; payload: [%d]%s)",
			len(mac), hex.EncodeToString(mac), len(payload), hex.EncodeToString(payload))
		return nil
	}

	var ot OAuth2Token
	err = bare.Unmarshal(payload, &ot)
	if err != nil {
		log.Printf("Invalid bearer token: BARE unmarshal failed: %e", err)
		return nil
	}
	if ot.Version != TokenVersion {
		log.Printf("Invalid bearer token: invalid token version")
		return nil
	}
	if time.Now().UTC().After(ot.Expires.Time()) {
		log.Printf("Invalid bearer token: token expired")
		return nil
	}
	return &ot
}