-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
292 lines (255 loc) · 8.59 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
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
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"time"
gkms "cloud.google.com/go/kms/apiv1"
gsecretmanager "cloud.google.com/go/secretmanager/apiv1"
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
akms "github.com/aws/aws-sdk-go-v2/service/kms"
asecretsmanager "github.com/aws/aws-sdk-go-v2/service/secretsmanager"
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/gittuf/github-app/internal/awskms"
"github.com/gittuf/github-app/internal/webhook"
"github.com/golang-jwt/jwt/v4"
"github.com/kelseyhightower/envconfig"
"github.com/octo-sts/app/pkg/gcpkms"
"golang.org/x/crypto/ssh"
)
const (
cloudProviderAWS = "aws"
cloudProviderGCP = "gcp"
)
func main() {
/*
This is heavily inspired by the webhook in
https://github.com/chainguard-dev/octo-sts written by @wlynch.
*/
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
var env webhook.EnvConfig
if err := envconfig.Process("", &env); err != nil {
log.Panicf("unable to process environment variables: %s", err.Error())
}
log.Default().Println("Processed env vars")
var (
signer ghinstallation.Signer
err error
)
if env.DevMode {
// TODO: we should eventually remove this code path altogether
log.Default().Println("App is deployed in dev mode, loading GitHub app signer from disk...")
keyBytes, err := os.ReadFile(env.KMSKey)
if err != nil {
log.Panicf("unable to read signing key: %v", err)
}
_, rawKey, err := decodeAndParsePEM(keyBytes)
if err != nil {
log.Panicf("unable to parse signing key: %v", err)
}
key, ok := rawKey.(*rsa.PrivateKey)
if !ok {
log.Panicf("invalid key type, must be RSA")
}
signer = ghinstallation.NewRSASigner(jwt.SigningMethodRS256, key)
log.Printf("Created signer using on disk key")
} else {
switch env.CloudProvider {
case cloudProviderAWS:
log.Panic("AWS support isn't complete yet :(")
kms := akms.New(akms.Options{})
signer, err = awskms.New(ctx, kms, env.KMSKey)
if err != nil {
log.Panicf("error creating AWS signer: %v", err)
}
case cloudProviderGCP:
kms, err := gkms.NewKeyManagementClient(ctx)
if err != nil {
log.Panicf("could not create kms client: %v", err)
}
signer, err = gcpkms.New(ctx, kms, env.KMSKey)
if err != nil {
log.Panicf("error creating GCP signer: %v", err)
}
}
}
transport, err := ghinstallation.NewAppsTransportWithOptions(http.DefaultTransport, env.AppID, ghinstallation.WithSigner(signer))
if err != nil {
log.Panicf("error creating GitHub App transport: %v", err)
}
if env.GitHubURL != webhook.DefaultGitHubURL {
transport.BaseURL = fmt.Sprintf("%s/%s/%s/", env.GitHubURL, "api", "v3")
}
// Set up app signing key, assuming it's ssh and therefore a secret.
// TODO: we should switch this to gitsign
if err := os.MkdirAll("/root/.ssh", 0o755); err != nil {
log.Panicf("unable to create /root/.ssh: %v", err)
}
webhookSecrets := [][]byte{}
if env.DevMode {
// TODO: we should eventually remove this code path altogether
log.Default().Println("App is deployed in dev mode, loading webhook secrets from environment variable...")
webhookSecrets = append(webhookSecrets, []byte(env.WebhookSecret))
log.Default().Println("App is deployed in dev mode, loading metadata and commit signer from disk...")
privkeyBytes, err := os.ReadFile(env.AppSigningKey)
if err != nil {
log.Panicf("error reading app signing key: %v", err)
}
if err := os.WriteFile(webhook.SSHAppSigningKeyPath, privkeyBytes, 0o600); err != nil {
log.Panicf("error writing app signing key: %v", err)
}
pubkeyBytes, err := os.ReadFile(env.AppSigningPubKey)
if err != nil {
log.Panicf("error reading app public key: %v", err)
}
pubkeyPath := fmt.Sprintf("%s.pub", webhook.SSHAppSigningKeyPath)
if err := os.WriteFile(pubkeyPath, pubkeyBytes, 0o600); err != nil {
log.Panicf("error writing app public key: %v", err)
}
} else {
switch env.CloudProvider {
case cloudProviderAWS:
log.Panic("AWS support isn't complete yet :(")
secretmanager := asecretsmanager.New(asecretsmanager.Options{}) // TODO
for _, name := range strings.Split(env.WebhookSecret, ",") {
resp, err := secretmanager.GetSecretValue(ctx, &asecretsmanager.GetSecretValueInput{
SecretId: &name,
})
if err != nil {
log.Panicf("error fetching webhook secret '%s' from AWS: %v", name, err)
}
// TODO: may be SecretBinary?
webhookSecrets = append(webhookSecrets, []byte(*resp.SecretString))
}
case cloudProviderGCP:
secretmanager, err := gsecretmanager.NewClient(ctx)
if err != nil {
log.Panicf("could not create secret manager client: %v", err)
}
for _, name := range strings.Split(env.WebhookSecret, ",") {
resp, err := secretmanager.AccessSecretVersion(ctx, &secretmanagerpb.AccessSecretVersionRequest{
Name: name,
})
if err != nil {
log.Panicf("error fetching webhook secret %s: %v", name, err)
}
webhookSecrets = append(webhookSecrets, resp.GetPayload().GetData())
}
resp, err := secretmanager.AccessSecretVersion(ctx, &secretmanagerpb.AccessSecretVersionRequest{
Name: env.AppSigningKey,
})
if err != nil {
log.Panicf("error fetching signing key: %v", err)
}
if err := os.WriteFile(webhook.SSHAppSigningKeyPath, resp.GetPayload().GetData(), 0o600); err != nil {
log.Panicf("unable to write private key; %v", err)
}
resp, err = secretmanager.AccessSecretVersion(ctx, &secretmanagerpb.AccessSecretVersionRequest{
Name: env.AppSigningPubKey,
})
if err != nil {
log.Panicf("error fetching public key: %v", err)
}
pubkeyPath := fmt.Sprintf("%s.pub", webhook.SSHAppSigningKeyPath)
if err := os.WriteFile(pubkeyPath, resp.GetPayload().GetData(), 0o600); err != nil {
log.Panicf("unable to write public key; %v", err)
}
}
}
mux := http.NewServeMux()
mux.Handle("/", &webhook.GittufApp{
Transport: transport,
WebhookSecret: webhookSecrets,
Params: &env,
})
log.Default().Println("Serving...")
srv := &http.Server{
Addr: fmt.Sprintf(":%d", env.Port),
ReadHeaderTimeout: 10 * time.Second,
Handler: mux,
}
log.Panic(srv.ListenAndServe())
}
// This entire section needs to go once we hook this up with a secrets manager.
var (
// ErrNoPEMBlock gets triggered when there is no PEM block in the provided file
ErrNoPEMBlock = errors.New("failed to decode the data as PEM block (are you sure this is a pem file?)")
// ErrFailedPEMParsing gets returned when PKCS1, PKCS8 or PKIX key parsing fails
ErrFailedPEMParsing = errors.New("failed parsing the PEM block: unsupported PEM type")
// ErrUnknownKeyType gets returned when we can't recognize the key type
ErrUnknownKeyType = errors.New("unknown key type")
)
/*
decodeAndParsePEM receives potential PEM bytes decodes them via pem.Decode
and pushes them to parseKey. If any error occurs during this process,
the function will return nil and an error (either ErrFailedPEMParsing
or ErrNoPEMBlock). On success it will return the decoded pemData, the
key object interface and nil as error. We need the decoded pemData,
because LoadKey relies on decoded pemData for operating system
interoperability.
*/
func decodeAndParsePEM(pemBytes []byte) (*pem.Block, any, error) {
// pem.Decode returns the parsed pem block and a rest.
// The rest is everything, that could not be parsed as PEM block.
// Therefore we can drop this via using the blank identifier "_"
data, _ := pem.Decode(pemBytes)
if data == nil {
return nil, nil, ErrNoPEMBlock
}
// Try to load private key, if this fails try to load
// key as public key
key, err := parsePEMKey(data.Bytes)
if err == nil {
return data, key, nil
}
// Try to parse SSH private key
key, err = ssh.ParseRawPrivateKey(pemBytes)
if err == nil {
return data, key, nil
}
return nil, nil, ErrUnknownKeyType
}
/*
parseKey tries to parse a PEM []byte slice using:
- PKCS8
- PKCS1
- PKIX
- EC
On success it returns the parsed key and nil.
On failure it returns nil and the error ErrFailedPEMParsing
*/
func parsePEMKey(data []byte) (any, error) {
// Parse private keys
key, err := x509.ParsePKCS8PrivateKey(data)
if err == nil {
return key, nil
}
key, err = x509.ParsePKCS1PrivateKey(data)
if err == nil {
return key, nil
}
key, err = x509.ParseECPrivateKey(data)
if err == nil {
return key, nil
}
// Parse public keys
key, err = x509.ParsePKIXPublicKey(data)
if err == nil {
return key, nil
}
key, err = x509.ParsePKCS1PublicKey(data)
if err == nil {
return key, nil
}
return nil, ErrFailedPEMParsing
}