-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
80 lines (68 loc) · 1.88 KB
/
main.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
package main
import (
"context"
"crypto/ecdsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"net/http"
"strings"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "copilot-extension",
Short: "Shopware Copilot Extension",
}
func main() {
rootCmd.ExecuteContext(context.Background())
}
// fetchPublicKey fetches the keys used to sign messages from copilot. Checking
// the signature with one of these keys verifies that the request to the
// completions API comes from GitHub and not elsewhere on the internet.
func fetchPublicKey() (*ecdsa.PublicKey, error) {
resp, err := http.Get("https://api.github.com/meta/public_keys/copilot_api")
if err != nil {
return nil, fmt.Errorf("failed to fetch public key: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch public key: %s", resp.Status)
}
var respBody struct {
PublicKeys []struct {
Key string `json:"key"`
IsCurrent bool `json:"is_current"`
} `json:"public_keys"`
}
if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil {
return nil, fmt.Errorf("failed to decode public key: %w", err)
}
var rawKey string
for _, pk := range respBody.PublicKeys {
if pk.IsCurrent {
rawKey = pk.Key
break
}
}
if rawKey == "" {
return nil, fmt.Errorf("could not find current public key")
}
pubPemStr := strings.ReplaceAll(rawKey, "\\n", "\n")
// Decode the Public Key
block, _ := pem.Decode([]byte(pubPemStr))
if block == nil {
return nil, fmt.Errorf("error parsing PEM block with GitHub public key")
}
// Create our ECDSA Public Key
key, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
// Because of documentation, we know it's a *ecdsa.PublicKey
ecdsaKey, ok := key.(*ecdsa.PublicKey)
if !ok {
return nil, fmt.Errorf("GitHub key is not ECDSA")
}
return ecdsaKey, nil
}