-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi_key_integration_test.go
More file actions
334 lines (279 loc) · 10.3 KB
/
api_key_integration_test.go
File metadata and controls
334 lines (279 loc) · 10.3 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright (c) Codesphere Inc.
// SPDX-License-Identifier: Apache-2.0
//go:build integration
// +build integration
package cmd_test
import (
"fmt"
"os"
"os/exec"
"strings"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/codesphere-cloud/oms/cli/cmd"
"github.com/codesphere-cloud/oms/internal/portal"
)
var _ = Describe("API Key Integration Tests", func() {
var (
portalClient portal.Portal
testOwner string
testOrg string
testRole string
registeredKey *portal.ApiKey
originalAdminKey string
expiresAt time.Time
extendedExpiry time.Time
)
BeforeEach(func() {
apiKey := os.Getenv("OMS_PORTAL_API_KEY")
apiURL := os.Getenv("OMS_PORTAL_API")
if apiKey == "" || apiURL == "" {
Fail("Integration tests require OMS_PORTAL_API_KEY and OMS_PORTAL_API environment variables")
}
originalAdminKey = apiKey
portalClient = portal.NewPortalClient()
// test env wrapper
portalClient.(*portal.PortalClient).Env = NewTestEnv(apiKey, os.Getenv("OMS_PORTAL_API"), "")
// test data
testOwner = fmt.Sprintf("integration-test-%d@test.com", time.Now().Unix())
testOrg = "IntegrationTestOrg"
testRole = "Ext"
expiresAt = time.Now().Add(24 * time.Hour)
extendedExpiry = time.Now().Add(48 * time.Hour)
})
Describe("Standalone created-key behavior", func() {
It("created API key can list builds when used", func() {
registerCmd := cmd.RegisterCmd{
Opts: cmd.RegisterOpts{
Owner: fmt.Sprintf("standalone-test-%d@test.com", time.Now().Unix()),
Organization: "StandaloneTestOrg",
Role: "Ext",
ExpiresAt: time.Now().Add(1 * time.Hour).Format(time.RFC3339),
},
}
GinkgoWriter.Printf("Attempting to register API key for owner: %s at API: %s\n", registerCmd.Opts.Owner, os.Getenv("OMS_PORTAL_API"))
newKey, err := registerCmd.Register(portalClient)
if err != nil {
GinkgoWriter.Printf("Registration failed: %v\n", err)
}
Expect(err).To(BeNil(), "API key registration should succeed")
Expect(newKey).NotTo(BeNil(), "Register should return the created API key")
keys, err := portalClient.ListAPIKeys()
Expect(err).To(BeNil(), "Listing API keys should succeed")
var created *portal.ApiKey
for i := range keys {
if keys[i].Owner == registerCmd.Opts.Owner {
created = &keys[i]
break
}
}
Expect(created).NotTo(BeNil(), "Should find the created API key")
Expect(newKey.ApiKey).NotTo(BeEmpty(), "Created API key must include secret value")
client := portal.NewPortalClient()
client.Env = NewTestEnv(newKey.ApiKey, os.Getenv("OMS_PORTAL_API"), "")
builds, err := client.ListBuilds(portal.CodesphereProduct)
Expect(err).To(BeNil(), "Listing builds with created key should succeed")
Expect(builds.Builds).NotTo(BeEmpty(), "Created key should be able to see builds")
})
})
Describe("Complete API Key Flow", func() {
It("should successfully complete the full API key lifecycle", func() {
By("Registering a new customer API key")
registerCmd := cmd.RegisterCmd{
Opts: cmd.RegisterOpts{
Owner: testOwner,
Organization: testOrg,
Role: testRole,
ExpiresAt: expiresAt.Format(time.RFC3339),
},
}
GinkgoWriter.Printf("[DEBUG] Attempting to register API key for owner: %s, org: %s at API: %s\n",
testOwner, testOrg, os.Getenv("OMS_PORTAL_API"))
newKey, err := registerCmd.Register(portalClient)
if err != nil {
GinkgoWriter.Printf("[ERROR] Registration failed: %v\n", err)
}
Expect(err).To(BeNil(), "API key registration should succeed")
Expect(newKey).NotTo(BeNil(), "Register should return the created API key")
By("Listing API keys to get the newly registered key")
keys, err := portalClient.ListAPIKeys()
Expect(err).To(BeNil(), "Listing API keys should succeed")
Expect(keys).NotTo(BeEmpty(), "Should have at least one API key")
// Find the new key
for i := range keys {
if keys[i].Owner == testOwner {
registeredKey = &keys[i]
break
}
}
Expect(registeredKey).NotTo(BeNil(), "Should find the registered API key")
Expect(registeredKey.Owner).To(Equal(testOwner))
Expect(registeredKey.Organization).To(Equal(testOrg))
Expect(registeredKey.Role).To(Equal(testRole))
By("Ensuring the customer can see builds")
Expect(newKey.ApiKey).NotTo(BeEmpty(), "Registered key must include the API key value")
p := portal.NewPortalClient()
// switch to the new key
p.Env = NewTestEnv(newKey.ApiKey, os.Getenv("OMS_PORTAL_API"), "")
builds, err := p.ListBuilds(portal.CodesphereProduct)
Expect(err).To(BeNil(), "Listing builds with new key should succeed")
Expect(builds.Builds).NotTo(BeEmpty(), "Should have at least one build available")
// restore admin key
portalClient.(*portal.PortalClient).Env = NewTestEnv(originalAdminKey, os.Getenv("OMS_PORTAL_API"), "")
By("Extending the API Key to a future date")
updateCmd := cmd.UpdateAPIKeyCmd{
Opts: cmd.UpdateAPIKeyOpts{
APIKeyID: registeredKey.KeyID,
ExpiresAtStr: extendedExpiry.Format(time.RFC3339),
},
}
err = updateCmd.UpdateAPIKey(portalClient)
Expect(err).To(BeNil(), "API key update should succeed")
By("Verifying the API key was updated")
keys, err = portalClient.ListAPIKeys()
Expect(err).To(BeNil(), "Listing API keys should succeed")
// Find the updated key
var updatedKey *portal.ApiKey
for i := range keys {
if keys[i].KeyID == registeredKey.KeyID {
updatedKey = &keys[i]
break
}
}
Expect(updatedKey).NotTo(BeNil(), "Should find the updated API key")
Expect(updatedKey.ExpiresAt).To(BeTemporally("~", extendedExpiry, 5*time.Second))
By("Revoking the API Key")
revokeCmd := cmd.RevokeAPIKeyCmd{
Opts: cmd.RevokeAPIKeyOpts{
ID: registeredKey.KeyID,
},
}
err = revokeCmd.Revoke(portalClient)
Expect(err).To(BeNil(), "API key revocation should succeed")
By("Ensuring the API Key is not valid anymore")
keyFound := true
for attempt := 0; attempt < 5; attempt++ {
keys, err = portalClient.ListAPIKeys()
Expect(err).To(BeNil(), "Listing API keys should succeed")
keyFound = false
for i := range keys {
if keys[i].KeyID == registeredKey.KeyID {
keyFound = true
break
}
}
if !keyFound {
break
}
time.Sleep(1 * time.Second)
}
if keyFound {
revokedClient := portal.NewPortalClient()
revokedClient.Env = NewTestEnv(newKey.ApiKey, os.Getenv("OMS_PORTAL_API"), "")
_, useErr := revokedClient.ListBuilds(portal.CodesphereProduct)
Expect(useErr).NotTo(BeNil(), "Using a revoked API key should fail")
} else {
Expect(keyFound).To(BeFalse(), "Revoked API key should not be in the list")
}
})
})
Describe("API Key Update With Wrong Input", func() {
It("should handle update with invalid date format", func() {
updateCmd := cmd.UpdateAPIKeyCmd{
Opts: cmd.UpdateAPIKeyOpts{
APIKeyID: "test-key-id",
ExpiresAtStr: "invalid-date",
},
}
err := updateCmd.UpdateAPIKey(portalClient)
Expect(err).NotTo(BeNil(), "Should fail with invalid date format")
Expect(err.Error()).To(ContainSubstring("invalid date format"))
})
})
Describe("Old API Key Detection and Warning", func() {
var (
cliPath = "../../oms"
)
Context("when using a 25-character old API key format", func() {
It("should detect the old format and attempt to upgrade", func() {
cmd := exec.Command(cliPath, "version")
cmd.Env = append(os.Environ(),
"OMS_PORTAL_API_KEY=fakeapikeywith25character", // 25 characters
"OMS_PORTAL_API=http://localhost:3000/api",
)
output, err := cmd.CombinedOutput()
outputStr := string(output)
if err != nil {
GinkgoWriter.Printf("Command error: %v, Output: %s\n", err, outputStr)
}
Expect(outputStr).To(ContainSubstring("OMS CLI version"))
})
})
Context("when using a new long-format API key", func() {
It("should not show any warning", func() {
cmd := exec.Command(cliPath, "version")
cmd.Env = append(os.Environ(),
"OMS_PORTAL_API_KEY=fake-api-key",
"OMS_PORTAL_API=http://localhost:3000/api",
)
output, err := cmd.CombinedOutput()
outputStr := string(output)
if err != nil {
GinkgoWriter.Printf("Command error: %v, Output: %s\n", err, outputStr)
}
Expect(outputStr).To(ContainSubstring("OMS CLI version"))
Expect(outputStr).NotTo(ContainSubstring("old API key"))
Expect(outputStr).NotTo(ContainSubstring("Failed to upgrade"))
})
})
Context("when using a 25-character key with list api-keys command", func() {
It("should attempt the upgrade and handle the error gracefully", func() {
cmd := exec.Command(cliPath, "list", "api-keys")
cmd.Env = append(os.Environ(),
"OMS_PORTAL_API_KEY=fakeapikeywith25character", // 25 characters (old format)
"OMS_PORTAL_API=http://localhost:3000/api",
)
output, err := cmd.CombinedOutput()
outputStr := string(output)
Expect(err).To(HaveOccurred())
hasWarning := strings.Contains(outputStr, "old API key") ||
strings.Contains(outputStr, "Failed to upgrade") ||
strings.Contains(outputStr, "Unauthorized")
Expect(hasWarning).To(BeTrue(),
"Should contain warning about old key or auth failure. Got: "+outputStr)
})
})
Context("when checking key length detection", func() {
It("should correctly identify 25-character old format", func() {
oldKey := "fakeapikeywith25character"
Expect(len(oldKey)).To(Equal(25))
})
It("should correctly identify new long format", func() {
newKey := "4hBieJRj2pWeB9qKJ9wQGE3CrcldLnLwP8fz6qutMjkf1n1"
Expect(len(newKey)).NotTo(Equal(25))
Expect(len(newKey)).To(BeNumerically(">", 25))
})
})
})
Describe("PreRun Hook Execution", func() {
var (
cliPath = "../../oms"
)
Context("when running any OMS command", func() {
It("should execute the PreRun hook", func() {
cmd := exec.Command(cliPath, "version")
cmd.Env = append(os.Environ(),
"OMS_PORTAL_API_KEY=valid-key-format-short",
"OMS_PORTAL_API=http://localhost:3000/api",
)
output, err := cmd.CombinedOutput()
outputStr := string(output)
if err != nil {
GinkgoWriter.Printf("Command error: %v, Output: %s\n", err, outputStr)
}
Expect(outputStr).To(ContainSubstring("OMS CLI version"))
})
})
})
})