forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
social.go
476 lines (452 loc) · 15.8 KB
/
social.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
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
// Copyright 2018 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package social
import (
"bytes"
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
// Client is responsible for making calls to different providers
type Client struct {
sync.RWMutex
googleCerts []*rsa.PublicKey
googleCertsRefreshAt int64
gamecenterCaCert *x509.Certificate
client *http.Client
}
// FacebookProfile is an abbreviated version of a Facebook profile.
type FacebookProfile struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Gender string `json:"gender"`
Locale string `json:"locale"`
Timezone float64 `json:"timezone"`
}
type facebookPagingCursors struct {
After string `json:"after"`
Before string `json:"before"`
}
type facebookPaging struct {
Cursors facebookPagingCursors `json:"cursors"`
Previous string `json:"previous"`
Next string `json:"next"`
}
type facebookFriends struct {
Data []FacebookProfile `json:"data"`
Paging facebookPaging `json:"paging"`
}
// GoogleProfile is an abbreviated version of a Google profile extracted from in a verified ID token.
type GoogleProfile struct {
// Fields available in all tokens.
Iss string `json:"iss"`
Sub string `json:"sub"`
Azp string `json:"azp"`
Aud string `json:"aud"`
Iat int64 `json:"iat"`
Exp int64 `json:"exp"`
// Fields available only if the user granted the "profile" and "email" OAuth scopes.
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
Picture string `json:"picture"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Locale string `json:"locale"`
}
// SteamProfile is an abbreviated version of a Steam profile.
type SteamProfile struct {
SteamID uint64 `json:"steamid"`
}
// NewClient creates a new Social Client
func NewClient(timeout time.Duration) *Client {
// From https://knowledge.symantec.com/support/code-signing-support/index?page=content&actp=CROSSLINK&id=AR2170
// Issued to: Symantec Class 3 SHA256 Code Signing CA
// Issued by: VeriSign Class 3 Public Primary Certification Authority - G5
// Valid from: 12/9/2013 to 12/9/2023
// Serial Number: 3d 78 d7 f9 76 49 60 b2 61 7d f4 f0 1e ca 86 2a
caData := []byte(`-----BEGIN CERTIFICATE-----
MIIFWTCCBEGgAwIBAgIQPXjX+XZJYLJhffTwHsqGKjANBgkqhkiG9w0BAQsFADCB
yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp
U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW
ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0
aG9yaXR5IC0gRzUwHhcNMTMxMjEwMDAwMDAwWhcNMjMxMjA5MjM1OTU5WjB/MQsw
CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV
BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxMDAuBgNVBAMTJ1N5bWFudGVjIENs
YXNzIDMgU0hBMjU2IENvZGUgU2lnbmluZyBDQTCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBAJeDHgAWryyx0gjE12iTUWAecfbiR7TbWE0jYmq0v1obUfej
DRh3aLvYNqsvIVDanvPnXydOC8KXyAlwk6naXA1OpA2RoLTsFM6RclQuzqPbROlS
Gz9BPMpK5KrA6DmrU8wh0MzPf5vmwsxYaoIV7j02zxzFlwckjvF7vjEtPW7ctZlC
n0thlV8ccO4XfduL5WGJeMdoG68ReBq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E-----`)
caBlock, _ := pem.Decode(caData)
caCert, _ := x509.ParseCertificate(caBlock.Bytes)
return &Client{
client: &http.Client{
Timeout: timeout,
},
gamecenterCaCert: caCert,
}
}
// GetFacebookProfile retrieves the user's Facebook Profile given the accessToken
func (c *Client) GetFacebookProfile(accessToken string) (*FacebookProfile, error) {
path := "https://graph.facebook.com/v2.12/me?access_token=" + url.QueryEscape(accessToken) +
"&fields=" + url.QueryEscape("name,email,gender,locale,timezone")
var profile FacebookProfile
err := c.request("facebook profile", path, nil, &profile)
if err != nil {
return nil, err
}
return &profile, nil
}
// GetFacebookFriends queries the Facebook Graph.
// Token is expected to also have the "user_friends" permission.
func (c *Client) GetFacebookFriends(accessToken string) ([]FacebookProfile, error) {
friends := make([]FacebookProfile, 0)
after := ""
for {
// In FB Graph API 2.0+ this only returns friends that also use the same app.
path := "https://graph.facebook.com/v2.12/me/friends?access_token=" + url.QueryEscape(accessToken)
if after != "" {
path += "&after=" + after
}
var currentFriends facebookFriends
err := c.request("facebook friends", path, nil, ¤tFriends)
if err != nil {
return friends, err
}
friends = append(friends, currentFriends.Data...)
// When there are no more items, this will be "" and end the loop.
if currentFriends.Paging.Next == "" {
return friends, nil
}
after = currentFriends.Paging.Cursors.After
}
}
// CheckGoogleToken extracts the user's Google Profile from a given ID token.
func (c *Client) CheckGoogleToken(idToken string) (*GoogleProfile, error) {
c.RLock()
if c.googleCertsRefreshAt < time.Now().UTC().Unix() {
// Release the read lock and perform a certificate refresh.
c.RUnlock()
c.Lock()
if c.googleCertsRefreshAt < time.Now().UTC().Unix() {
certs := make(map[string]string, 3)
err := c.request("google cert", "https://www.googleapis.com/oauth2/v1/certs", nil, &certs)
if err != nil {
c.Unlock()
return nil, err
}
newCerts := make([]*rsa.PublicKey, 0, 3)
var newRefreshAt int64
for _, data := range certs {
currentBlock, _ := pem.Decode([]byte(data))
if currentBlock == nil {
// Block was invalid, ignore it and try the next.
continue
}
currentCert, err := x509.ParseCertificate(currentBlock.Bytes)
if err != nil {
// Certificate was invalid, ignore it and try the next.
continue
}
t := time.Now()
if currentCert.NotBefore.After(t) || currentCert.NotAfter.Before(t) {
// Certificate not yet valid or has already expired, skip it.
continue
}
pub, ok := currentCert.PublicKey.(*rsa.PublicKey)
if !ok {
// Certificate was not an RSA public key.
continue
}
newCerts = append(newCerts, pub)
if newRefreshAt == 0 || newRefreshAt > currentCert.NotAfter.UTC().Unix() {
// Refresh all certs 1 hour before the soonest expiry is due.
newRefreshAt = currentCert.NotAfter.UTC().Unix() - 3600
}
}
if len(newCerts) == 0 {
c.Unlock()
return nil, errors.New("error finding valid google cert")
}
c.googleCerts = newCerts
c.googleCertsRefreshAt = newRefreshAt
}
c.Unlock()
c.RLock()
}
var err error
var token *jwt.Token
for _, cert := range c.googleCerts {
// Try to parse and verify the token with each of the currently available certificates.
token, err = jwt.Parse(idToken, func(token *jwt.Token) (interface{}, error) {
if s, ok := token.Method.(*jwt.SigningMethodRSA); !ok || s.Hash != crypto.SHA256 {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
claims := token.Claims.(jwt.MapClaims)
if !claims.VerifyIssuer("accounts.google.com", true) && !claims.VerifyIssuer("https://accounts.google.com", true) {
return nil, fmt.Errorf("unexpected issuer: %v", claims["iss"])
}
return cert, nil
})
if err == nil {
// If any certificate worked, the token is valid.
break
}
}
// All verification attempts failed.
if token == nil {
c.RUnlock()
return nil, errors.New("google id token invalid")
}
claims := token.Claims.(jwt.MapClaims)
profile := &GoogleProfile{}
if v, ok := claims["iss"]; ok {
if profile.Iss, ok = v.(string); !ok {
return nil, errors.New("google id token iss field invalid")
}
} else {
return nil, errors.New("google id token iss field missing")
}
if v, ok := claims["sub"]; ok {
if profile.Sub, ok = v.(string); !ok {
return nil, errors.New("google id token sub field invalid")
}
} else {
return nil, errors.New("google id token sub field missing")
}
if v, ok := claims["azp"]; ok {
if profile.Azp, ok = v.(string); !ok {
return nil, errors.New("google id token azp field invalid")
}
} else {
return nil, errors.New("google id token azp field missing")
}
if v, ok := claims["aud"]; ok {
if profile.Aud, ok = v.(string); !ok {
return nil, errors.New("google id token aud field invalid")
}
} else {
return nil, errors.New("google id token aud field missing")
}
if v, ok := claims["iat"]; ok {
switch v.(type) {
case string:
if vi, err := strconv.Atoi(v.(string)); err != nil {
return nil, errors.New("google id token iat field invalid")
} else {
profile.Iat = int64(vi)
}
case float64:
profile.Iat = int64(v.(float64))
case int64:
profile.Iat = v.(int64)
default:
return nil, errors.New("google id token iat field unknown")
}
}
if v, ok := claims["exp"]; ok {
switch v.(type) {
case string:
if vi, err := strconv.Atoi(v.(string)); err != nil {
return nil, errors.New("google id token exp field invalid")
} else {
profile.Exp = int64(vi)
}
case float64:
profile.Exp = int64(v.(float64))
case int64:
profile.Exp = v.(int64)
default:
return nil, errors.New("google id token exp field unknown")
}
}
if v, ok := claims["email"]; ok {
if profile.Email, ok = v.(string); !ok {
return nil, errors.New("google id token email field invalid")
}
}
if v, ok := claims["email_verified"]; ok {
switch v.(type) {
case bool:
profile.EmailVerified = v.(bool)
case string:
if vb, err := strconv.ParseBool(v.(string)); err != nil {
return nil, errors.New("google id token email_verified field invalid")
} else {
profile.EmailVerified = vb
}
default:
return nil, errors.New("google id token email_verified field unknown")
}
}
if v, ok := claims["name"]; ok {
if profile.Name, ok = v.(string); !ok {
return nil, errors.New("google id token name field invalid")
}
}
if v, ok := claims["picture"]; ok {
if profile.Picture, ok = v.(string); !ok {
return nil, errors.New("google id token picture field invalid")
}
}
if v, ok := claims["given_name"]; ok {
if profile.GivenName, ok = v.(string); !ok {
return nil, errors.New("google id token given name field invalid")
}
}
if v, ok := claims["family_name"]; ok {
if profile.FamilyName, ok = v.(string); !ok {
return nil, errors.New("google id token family name field invalid")
}
}
if v, ok := claims["locale"]; ok {
if profile.Locale, ok = v.(string); !ok {
return nil, errors.New("google id token locale field invalid")
}
}
// Check token has not expired.
if profile.Exp != 0 && profile.Exp < time.Now().UTC().Unix() {
return nil, errors.New("google id token expired")
}
return profile, nil
}
// CheckGameCenterID checks to see validity of the GameCenter playerID
func (c *Client) CheckGameCenterID(playerID string, bundleID string, timestamp int64, salt string, signature string, publicKeyURL string) (bool, error) {
pub, err := url.Parse(publicKeyURL)
if err != nil {
return false, fmt.Errorf("gamecenter check error: invalid public key url: %v", err.Error())
} else if pub.Scheme != "https" {
return false, errors.New("gamecenter check error: invalid public key url scheme")
} else if pub.Path == "" || pub.Path == "/" {
return false, errors.New("gamecenter check error: invalid public key url path")
} else if !strings.HasSuffix(pub.Host, ".apple.com") {
return false, errors.New("gamecenter check error: invalid public key url domain")
}
slt, err := base64.StdEncoding.DecodeString(salt)
if err != nil {
return false, errors.New("gamecenter check error: error decoding salt")
}
sig, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return false, errors.New("gamecenter check error: error decoding signature")
}
body, err := c.requestRaw("apple public key url", publicKeyURL, nil)
if err != nil {
return false, err
}
// Parse the public key, check issuer, check signature.
pubBlock, rest := pem.Decode([]byte(body))
if pubBlock == nil {
pubBlock, _ = pem.Decode([]byte("\n-----BEGIN CERTIFICATE-----\n" + base64.StdEncoding.EncodeToString(rest) + "\n-----END CERTIFICATE-----"))
if pubBlock == nil {
return false, errors.New("gamecenter check error: error decoding public key")
}
}
pubCert, err := x509.ParseCertificate(pubBlock.Bytes)
if err != nil {
return false, fmt.Errorf("gamecenter check error: error parsing public block: %v", err.Error())
}
err = pubCert.CheckSignatureFrom(c.gamecenterCaCert)
if err != nil {
return false, fmt.Errorf("gamecenter check error: bad public key signature: %v", err.Error())
}
ts := make([]byte, 8)
binary.BigEndian.PutUint64(ts, uint64(timestamp))
payload := [][]byte{[]byte(playerID), []byte(bundleID), ts, slt}
err = pubCert.CheckSignature(x509.SHA256WithRSA, bytes.Join(payload, []byte{}), sig)
if err != nil {
return false, fmt.Errorf("gamecenter check error: signature mismatch: %v", err.Error())
}
return true, nil
}
// GetSteamProfile retrieves the user's Steam Profile.
// Key and App ID should be configured at the application level.
// See: https://partner.steamgames.com/documentation/auth#client_to_backend_webapi
func (c *Client) GetSteamProfile(publisherKey string, appID int, ticket string) (*SteamProfile, error) {
path := "https://api.steampowered.com/ISteamUserAuth/AuthenticateUserTicket/v0001/?format=json" +
"&key=" + url.QueryEscape(publisherKey) + "&appid=" + strconv.Itoa(appID) + "&ticket=" + url.QueryEscape(ticket)
var profile SteamProfile
err := c.request("steam profile", path, nil, &profile)
if err != nil {
return nil, err
}
return &profile, nil
}
func (c *Client) request(provider, path string, headers map[string]string, to interface{}) error {
body, err := c.requestRaw(provider, path, headers)
if err != nil {
return err
}
err = json.Unmarshal(body, to)
if err != nil {
return err
}
return nil
}
func (c *Client) requestRaw(provider, path string, headers map[string]string) ([]byte, error) {
req, err := http.NewRequest("GET", path, nil)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Add(k, v)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("%v error url %v, status code %v, body %s", provider, path, resp.StatusCode, body)
}
return body, nil
}