/
main.go
320 lines (250 loc) · 10.1 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
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
/*
Copyright (c) 2020 TriggerMesh Inc.
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 githubsqs
import (
"context"
"encoding/json"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
clientset "k8s.io/client-go/kubernetes"
"github.com/google/go-github/v32/github"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
"github.com/triggermesh/test-infra/test/e2e/framework"
e2esqs "github.com/triggermesh/test-infra/test/e2e/framework/aws/sqs"
"github.com/triggermesh/test-infra/test/e2e/framework/bridges"
"github.com/triggermesh/test-infra/test/e2e/framework/ducktypes"
e2egithub "github.com/triggermesh/test-infra/test/e2e/framework/github"
"github.com/triggermesh/test-infra/test/e2e/framework/manifest"
)
/* This test suite requires:
- A GitHub OAuth2 access token exported in the environment as GITHUB_API_TOKEN, with the following OAuth scopes: [repo, delete_repo]
- AWS credentials in whichever form (https://docs.aws.amazon.com/sdk-for-go/api/aws/session/#hdr-Sessions_options_from_Shared_Config)
- The name of an AWS region exported in the environment as AWS_REGION
*/
var bridgeAPIVersion = schema.GroupVersion{
Group: "flow.triggermesh.io",
Version: "v1alpha1",
}
const bridgeResource = "bridges"
const ghApiTokenSecretKey = "apiToken"
const awsAccessKeyIDSecretKey = "access_key_id"
const awsSecretAccessKeySecretKey = "secret_access_key"
var _ = Describe("GitHub to SQS", func() {
f := framework.New("github-sqs")
var ghClient *github.Client
var repo *github.Repository
var sqsClient sqsiface.SQSAPI
var sqsQueueURL string
BeforeEach(func() {
var brdgClient dynamic.ResourceInterface
var ghSecret *corev1.Secret
var awsSecret *corev1.Secret
ns := f.UniqueName
gvr := bridgeAPIVersion.WithResource(bridgeResource)
brdgClient = f.DynamicClient.Resource(gvr).Namespace(ns)
ghClient = e2egithub.NewClient()
sess := session.Must(session.NewSession())
sqsClient = sqs.New(sess)
By("creating a GitHub repository", func() {
repo = e2egithub.CreateRepository(ghClient, f)
})
By("creating a SQS queue", func() {
sqsQueueURL = e2esqs.CreateQueue(sqsClient, f)
})
By("creating a Kubernetes Secret containing the GitHub API token", func() {
ghSecret = createAPITokenSecret(f.KubeClient, ns, ghApiTokenSecretKey, e2egithub.APIToken())
})
By("creating a Kubernetes Secret containing the AWS Access Credentials", func() {
awsSecret = createAWSCredsSecret(f.KubeClient, ns, readAWSCredentials(sess))
})
By("creating a Bridge object", func() {
brdgTmpl := manifest.ObjectFromFile("bridges/manifests/github-sqs-bridge.yaml")
brdg, err := bridges.CreateBridge(brdgClient, brdgTmpl, ns, "test-",
withRepo(ownerAndRepo(repo)),
withAPITokenSecret(ghSecret.Name, ghApiTokenSecretKey),
withARN(e2esqs.QueueARN(sqsClient, sqsQueueURL)),
withAWSCredsSecret(awsSecret.Name),
)
Expect(err).ToNot(HaveOccurred())
ducktypes.WaitUntilReady(f.DynamicClient, brdg)
})
})
AfterEach(func() {
By("deleting GitHub repository "+ownerAndRepo(repo), func() {
e2egithub.DeleteRepository(ghClient, *repo.Owner.Login, *repo.Name)
})
By("deleting SQS queue "+sqsQueueURL, func() {
e2esqs.DeleteQueue(sqsClient, sqsQueueURL)
})
})
It("github push event is sent to SQS queue", func() {
var commit *github.Commit
var receivedMsg []byte
By("creating a Git commit", func() {
commit = e2egithub.CreateCommit(ghClient, *repo.Owner.Login, *repo.Name)
})
By("polling the SQS queue", func() {
var receivedMsgs []*sqs.Message
receivedMsgs = e2esqs.ReceiveMessages(sqsClient, sqsQueueURL)
Expect(receivedMsgs).To(HaveLen(1),
"Received %d messages instead of 1", len(receivedMsgs))
receivedMsg = []byte(*receivedMsgs[0].Body)
})
By("inspecting the message payload", func() {
msgData := make(map[string]interface{})
err := json.Unmarshal(receivedMsg, &msgData)
Expect(err).ToNot(HaveOccurred())
Expect(msgData["type"]).To(Equal("dev.knative.source.github.push"))
eventData, err := json.Marshal(msgData["data"])
Expect(err).ToNot(HaveOccurred())
ghEvent := &github.PushEvent{}
err = json.Unmarshal(eventData, ghEvent)
Expect(err).ToNot(HaveOccurred())
Expect(ghEvent.GetHeadCommit().GetID()).To(Equal(commit.GetSHA()))
Expect(ghEvent.GetHeadCommit().GetURL()).To(Equal(commit.GetHTMLURL()))
})
})
})
// ownerAndRepo returns a reference to a GitHub repository in the format
// "owner/repo".
func ownerAndRepo(r *github.Repository) string {
return *r.Owner.Login + "/" + *r.Name
}
// withRepo sets the ownerAndRepo spec field of the GitHubSource.
func withRepo(ownerAndRepo string) bridges.BridgeOption {
return func(brdg *unstructured.Unstructured) {
comps := bridges.Components(brdg)
ghSrc := comps[bridges.SeekComponentByKind(comps, "GitHubSource")]
if err := unstructured.SetNestedField(ghSrc, ownerAndRepo, "object", "spec", "ownerAndRepository"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.ownerAndRepo field: %s", err)
}
// "comps" is a deep copy returned by unstructured.NestedSlice,
// so we need set the modified version on the Bridge object
bridges.SetComponents(brdg, comps)
}
}
// withAPITokenSecret sets the accessToken and secretToken spec fields of the GitHubSource.
func withAPITokenSecret(secretName, apiTokenKey string) bridges.BridgeOption {
return func(brdg *unstructured.Unstructured) {
comps := bridges.Components(brdg)
ghSrc := comps[bridges.SeekComponentByKind(comps, "GitHubSource")]
tokenSecretRef := map[string]interface{}{
"secretKeyRef": map[string]interface{}{
"name": secretName,
"key": apiTokenKey,
},
}
if err := unstructured.SetNestedMap(ghSrc, tokenSecretRef, "object", "spec", "accessToken"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.accessToken field: %s", err)
}
if err := unstructured.SetNestedMap(ghSrc, tokenSecretRef, "object", "spec", "secretToken"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.secretToken field: %s", err)
}
// "comps" is a deep copy returned by unstructured.NestedSlice,
// so we need set the modified version on the Bridge object
bridges.SetComponents(brdg, comps)
}
}
// withARN sets the arn spec field of the AWSSQSTarget.
func withARN(arn string) bridges.BridgeOption {
return func(brdg *unstructured.Unstructured) {
comps := bridges.Components(brdg)
sqsTarget := comps[bridges.SeekComponentByKind(comps, "AWSSQSTarget")]
if err := unstructured.SetNestedField(sqsTarget, arn, "object", "spec", "arn"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.arn field: %s", err)
}
// "comps" is a deep copy returned by unstructured.NestedSlice,
// so we need set the modified version on the Bridge object
bridges.SetComponents(brdg, comps)
}
}
// withAWSCredsSecret sets the awsApiKey and awsApiSecret spec fields of the AWSSQSTarget.
func withAWSCredsSecret(secretName string) bridges.BridgeOption {
return func(brdg *unstructured.Unstructured) {
comps := bridges.Components(brdg)
sqsTarget := comps[bridges.SeekComponentByKind(comps, "AWSSQSTarget")]
apiKeySecretRef := map[string]interface{}{
"secretKeyRef": map[string]interface{}{
"name": secretName,
"key": awsAccessKeyIDSecretKey,
},
}
apiSecretSecretRef := map[string]interface{}{
"secretKeyRef": map[string]interface{}{
"name": secretName,
"key": awsSecretAccessKeySecretKey,
},
}
if err := unstructured.SetNestedMap(sqsTarget, apiKeySecretRef, "object", "spec", "awsApiKey"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.accessToken field: %s", err)
}
if err := unstructured.SetNestedMap(sqsTarget, apiSecretSecretRef, "object", "spec", "awsApiSecret"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.secretToken field: %s", err)
}
// "comps" is a deep copy returned by unstructured.NestedSlice,
// so we need set the modified version on the Bridge object
bridges.SetComponents(brdg, comps)
}
}
// createAPITokenSecret creates a Kubernetes Secret containing a GitHub API token.
func createAPITokenSecret(c clientset.Interface, namespace, tokenKey, tokenVal string) *corev1.Secret {
secr := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
GenerateName: "gh-apitoken-",
},
StringData: map[string]string{
tokenKey: tokenVal,
},
}
var err error
secr, err = c.CoreV1().Secrets(namespace).Create(context.Background(), secr, metav1.CreateOptions{})
if err != nil {
framework.FailfWithOffset(2, "Failed to create Secret: %s", err)
}
return secr
}
func readAWSCredentials(sess *session.Session) credentials.Value {
creds, err := sess.Config.Credentials.Get()
if err != nil {
framework.FailfWithOffset(2, "Error reading AWS credentials: %s", err)
}
return creds
}
// createAWSCredsSecret creates a Kubernetes Secret containing a AWS credentials.
func createAWSCredsSecret(c clientset.Interface, namespace string, creds credentials.Value) *corev1.Secret {
secr := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
GenerateName: "aws-creds-",
},
StringData: map[string]string{
awsAccessKeyIDSecretKey: creds.AccessKeyID,
awsSecretAccessKeySecretKey: creds.SecretAccessKey,
},
}
var err error
secr, err = c.CoreV1().Secrets(namespace).Create(context.Background(), secr, metav1.CreateOptions{})
if err != nil {
framework.FailfWithOffset(2, "Failed to create Secret: %s", err)
}
return secr
}