forked from stakwork/sphinx-tribes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
168 lines (139 loc) · 3.95 KB
/
auth.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
package main
import (
"context"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"net/http"
"strings"
"time"
btcecdsa "github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/form3tech-oss/jwt-go"
)
var (
// signedMsgPrefix is a special prefix that we'll prepend to any
// messages we sign/verify. We do this to ensure that we don't
// accidentally sign a sighash, or other sensitive material. By
// prepending this fragment, we mind message signing to our particular
// context.
signedMsgPrefix = []byte("Lightning Signed Message:")
)
type contextKey string
// ContextKey ...
var ContextKey = contextKey("key")
// PubKeyContext parses pukey from signed timestamp
func PubKeyContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token")
if token == "" {
token = r.Header.Get("x-jwt")
}
if token == "" {
fmt.Println("[auth] no token")
http.Error(w, http.StatusText(401), 401)
return
}
isJwt := strings.Contains(token, ".")
if isJwt {
claims, err := DecodeToken(token)
if err != nil {
fmt.Println("Failed to parse JWT")
http.Error(w, http.StatusText(401), 401)
return
}
if claims.VerifyExpiresAt(time.Now().UnixNano(), true) {
fmt.Println("Token has expired")
http.Error(w, http.StatusText(401), 401)
return
}
ctx := context.WithValue(r.Context(), ContextKey, claims["pubkey"])
next.ServeHTTP(w, r.WithContext(ctx))
} else {
pubkey, err := VerifyTribeUUID(token, true)
if pubkey == "" || err != nil {
fmt.Println("[auth] no pubkey || err != nil")
if err != nil {
fmt.Println(err)
}
http.Error(w, http.StatusText(401), 401)
return
}
ctx := context.WithValue(r.Context(), ContextKey, pubkey)
next.ServeHTTP(w, r.WithContext(ctx))
}
})
}
// VerifyTribeUUID takes base64 uuid and returns hex pubkey
func VerifyTribeUUID(uuid string, checkTimestamp bool) (string, error) {
sigByes, err := base64.URLEncoding.DecodeString(uuid)
if err != nil {
return "", err
}
timeBuf := sigByes[:4] // unix timestamp is 4 bytes, or uint32
sigBuf := sigByes[4:]
pubkey, valid, err := VerifyAndExtract(timeBuf, sigBuf)
if err != nil || !valid || pubkey == "" {
return "", err
}
if checkTimestamp {
// 5 MINUTE MAX
ts := int64(binary.BigEndian.Uint32(timeBuf))
now := time.Now().Unix()
if ts < now-300 {
fmt.Println("TOO LATE!")
return "", errors.New("too late")
}
}
return pubkey, nil
}
// VerifyArbitrary takes base64 sig and msg and returns hex pubkey
func VerifyArbitrary(sig string, msg string) (string, error) {
sigByes, err := base64.URLEncoding.DecodeString(sig)
if err != nil {
return "", err
}
pubkey, valid, err := VerifyAndExtract([]byte(msg), sigByes)
if err != nil || !valid || pubkey == "" {
return "", err
}
return pubkey, nil
}
// VerifyAndExtract ... pubkey comes out hex encoded
func VerifyAndExtract(msg, sig []byte) (string, bool, error) {
if sig == nil || msg == nil {
return "", false, errors.New("bad")
}
msg = append(signedMsgPrefix, msg...)
digest := chainhash.DoubleHashB(msg)
// RecoverCompact both recovers the pubkey and validates the signature.
pubKey, valid, err := btcecdsa.RecoverCompact(sig, digest)
if err != nil {
fmt.Printf("ERR: %+v\n", err)
return "", false, err
}
pubKeyHex := hex.EncodeToString(pubKey.SerializeCompressed())
return pubKeyHex, valid, nil
}
func DecodeToken(token string) (jwt.MapClaims, error) {
claims := jwt.MapClaims{}
_, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
key := jwtKey
return []byte(key), nil
})
return claims, err
}
func EncodeToken(pubkey string) (string, error) {
exp := ExpireInHours(24 * 7)
claims := jwt.MapClaims{
"pubkey": pubkey,
"exp": exp,
}
_, tokenString, err := TokenAuth.Encode(claims)
if err != nil {
return "", err
}
return tokenString, nil
}