Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/public-api-server/pkg/jws/keyset.go
2506 views
1
// Copyright (c) 2023 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 jws
6
7
import (
8
"crypto/rsa"
9
"crypto/x509"
10
"encoding/pem"
11
"fmt"
12
"io/ioutil"
13
14
"github.com/gitpod-io/gitpod/components/public-api/go/config"
15
)
16
17
type Key struct {
18
ID string
19
Private *rsa.PrivateKey
20
Raw []byte
21
// We don't need PublicKey because we can derive the public key from the private key
22
}
23
24
// KeySet encodes a collection of keys to use
25
// There's always a Signing key, but optionally there are also
26
// older keys which can be used to verify.
27
type KeySet struct {
28
Signing Key
29
Validating []Key
30
}
31
32
func NewKeySetFromAuthPKI(pki config.AuthPKIConfiguration) (KeySet, error) {
33
signing, err := readKeyPair(pki.Signing)
34
if err != nil {
35
return KeySet{}, fmt.Errorf("failed to read signing key: %w", err)
36
}
37
38
var validating []Key
39
for _, keypair := range pki.Validating {
40
key, err := readKeyPair(keypair)
41
if err != nil {
42
return KeySet{}, fmt.Errorf("failed to read validating key: %w", err)
43
}
44
45
validating = append(validating, key)
46
}
47
48
return KeySet{
49
Signing: signing,
50
Validating: validating,
51
}, nil
52
}
53
54
func readKeyPair(keypair config.KeyPair) (Key, error) {
55
pk, raw, err := readPrivateKeyFromFile(keypair.PrivateKeyPath)
56
if err != nil {
57
return Key{}, err
58
}
59
60
return Key{
61
ID: keypair.ID,
62
Private: pk,
63
Raw: raw,
64
}, nil
65
}
66
67
func readPrivateKeyFromFile(filepath string) (*rsa.PrivateKey, []byte, error) {
68
bytes, err := ioutil.ReadFile(filepath)
69
if err != nil {
70
return nil, nil, fmt.Errorf("failed to read private key from %s: %w", filepath, err)
71
}
72
73
block, _ := pem.Decode(bytes)
74
parseResult, _ := x509.ParsePKCS8PrivateKey(block.Bytes)
75
key, ok := parseResult.(*rsa.PrivateKey)
76
if !ok {
77
return nil, nil, fmt.Errorf("file %s does not contain RSA Private Key", filepath)
78
}
79
80
return key, bytes, nil
81
}
82
83