Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/local-app/pkg/auth/pkce.go
2500 views
1
// Copyright (c) 2021 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package auth
6
7
import (
8
crypto_rand "crypto/rand"
9
"crypto/sha256"
10
"encoding/base64"
11
"encoding/binary"
12
"math/rand"
13
math_rand "math/rand"
14
"time"
15
)
16
17
func init() {
18
PKCEInit()
19
}
20
21
// PKCEInit ensures we use random values to generate the PKCE verifier
22
func PKCEInit() {
23
var seed int64
24
var b [8]byte
25
// We'd like more entropy than UnixNano() for PKCE
26
_, err := crypto_rand.Read(b[:])
27
if err == nil {
28
seed = int64(binary.LittleEndian.Uint64(b[:]))
29
} else {
30
// ... but will accept it if we have to
31
seed = time.Now().UnixNano()
32
}
33
math_rand.Seed(seed)
34
}
35
36
// PKCEVerifier generates a string of pkce allowed chars
37
func PKCEVerifier(length int) string {
38
if length > 128 {
39
length = 128
40
}
41
if length < 43 {
42
length = 43
43
}
44
const charset = "abcdefghijklmnopqrstuvwxyz" +
45
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"
46
b := make([]byte, length)
47
for i := range b {
48
b[i] = charset[rand.Intn(len(charset))]
49
}
50
return string(b)
51
}
52
53
// PKCEChallenge base64-URL-encodes the SHA256 hash of verifier, per rfc 7636
54
func PKCEChallenge(verifier string) string {
55
sum := sha256.Sum256([]byte(verifier))
56
challenge := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(sum[:])
57
return (challenge)
58
}
59
60