-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathapi_session_certificates_test.go
338 lines (250 loc) · 10.4 KB
/
api_session_certificates_test.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//go:build apitests
/*
Copyright NetFoundry 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
https://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 tests
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/Jeffail/gabs"
"github.com/michaelquigley/pfxlog"
"github.com/openziti/edge-api/rest_client_api_client/current_api_session"
"github.com/openziti/edge-api/rest_model"
"github.com/openziti/identity/certtools"
edge_apis "github.com/openziti/sdk-golang/edge-apis"
"github.com/openziti/ziti/common/spiffehlp"
"net/http"
"net/url"
"os"
"strings"
"testing"
)
func Test_Api_Session_Certs(t *testing.T) {
ctx := NewTestContext(t)
defer ctx.Teardown()
ctx.StartServer()
t.Run("as the default admin, session certs, using legacy authentication", func(t *testing.T) {
var createdResponseBody *gabs.Container //used across multiple subtests, set in first
var createdId string //used across multiple subtests, set in first
t.Run("can be created", func(t *testing.T) {
ctx.testContextChanged(t)
ctx.RequireAdminManagementApiLogin()
ctx.RequireAdminClientApiLogin()
csr, _, err := generateCsr()
ctx.Req.NoError(err)
csrPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csr})
ctx.Req.NotEmpty(csrPem)
request := ctx.AdminClientSession.newAuthenticatedRequest()
body := gabs.New()
_, err = body.Set(string(csrPem), "csr")
ctx.Req.NoError(err)
bodyStr := body.String()
request.SetBody(bodyStr)
resp, err := request.Post("current-api-session/certificates")
ctx.Req.NoError(err)
standardJsonResponseTests(resp, http.StatusCreated, t)
createdResponseBody, err = gabs.ParseJSON(resp.Body())
ctx.Req.NoError(err)
var ok bool
createdId, ok = createdResponseBody.Path("data.id").Data().(string)
ctx.Req.True(ok)
ctx.Req.NotEmpty(createdId)
certificate := createdResponseBody.Path("data.certificate").Data().(string)
ctx.Req.NotEmpty(certificate)
x509Cert, err := certtools.LoadCert([]byte(certificate))
ctx.Req.NotEmpty(x509Cert)
ctx.Req.NoError(err)
})
t.Run("can be listed", func(t *testing.T) {
ctx.testContextChanged(t)
resp, err := ctx.AdminClientSession.newAuthenticatedRequest().Get("current-api-session/certificates")
ctx.Req.NoError(err)
ctx.Req.Equal(http.StatusOK, resp.StatusCode())
t.Run("list contains the API session cert", func(t *testing.T) {
ctx.testContextChanged(t)
bodyStr := resp.Body()
body, err := gabs.ParseJSON(bodyStr)
ctx.Req.NoError(err)
data := body.Path("data")
ctx.Req.NotEmpty(data)
children, err := data.Children()
ctx.Req.NoError(err)
ctx.Req.Len(children, 1)
subject := children[0].Path("subject").Data().(string)
ctx.Req.NotEmpty(subject)
fingerprint := children[0].Path("fingerprint").Data().(string)
ctx.Req.NotEmpty(fingerprint)
validFrom := children[0].Path("validFrom").Data().(string)
ctx.Req.NotEmpty(validFrom)
validTo := children[0].Path("validTo").Data().(string)
ctx.Req.NotEmpty(validTo)
certificate := children[0].Path("certificate").Data().(string)
ctx.Req.NotEmpty(certificate)
x509Cert, err := certtools.LoadCert([]byte(certificate))
ctx.Req.NotEmpty(x509Cert)
ctx.Req.NoError(err)
})
})
t.Run("can be detailed", func(t *testing.T) {
ctx.testContextChanged(t)
resp, err := ctx.AdminClientSession.newAuthenticatedRequest().Get("current-api-session/certificates/" + createdId)
ctx.Req.NoError(err)
ctx.Req.Equal(http.StatusOK, resp.StatusCode())
t.Run("contains proper values", func(t *testing.T) {
ctx.testContextChanged(t)
bodyStr := resp.Body()
body, err := gabs.ParseJSON(bodyStr)
ctx.Req.NoError(err)
data := body.Path("data")
ctx.Req.NotEmpty(data)
subject := data.Path("subject").Data().(string)
ctx.Req.NotEmpty(subject)
fingerprint := data.Path("fingerprint").Data().(string)
ctx.Req.NotEmpty(fingerprint)
validFrom := data.Path("validFrom").Data().(string)
ctx.Req.NotEmpty(validFrom)
validTo := data.Path("validTo").Data().(string)
ctx.Req.NotEmpty(validTo)
certificate := data.Path("certificate").Data().(string)
ctx.Req.NotEmpty(certificate)
x509Cert, err := certtools.LoadCert([]byte(certificate))
ctx.Req.NotEmpty(x509Cert)
ctx.Req.NoError(err)
})
})
t.Run("can be deleted", func(t *testing.T) {
ctx.testContextChanged(t)
resp, err := ctx.AdminClientSession.newAuthenticatedRequest().Delete("current-api-session/certificates/" + createdId)
ctx.Req.NoError(err)
standardJsonResponseTests(resp, http.StatusOK, t)
})
})
t.Run("as admin using oidc authentication", func(t *testing.T) {
ctx.testContextChanged(t)
adminCreds := edge_apis.NewUpdbCredentials(ctx.AdminAuthenticator.Username, ctx.AdminAuthenticator.Password)
clientApiUrl, err := url.Parse("https://" + ctx.ApiHost + EdgeClientApiPath)
ctx.Req.NoError(err)
adminClientClient := edge_apis.NewClientApiClient([]*url.URL{clientApiUrl}, ctx.ControllerConfig.Id.CA(), func(strings chan string) {
strings <- "123"
})
adminClientClient.SetUseOidc(true)
adminClientApiSession, err := adminClientClient.Authenticate(adminCreds, nil)
ctx.Req.NoError(err)
ctx.Req.NotNil(adminClientApiSession)
managementApiUrl, err := url.Parse("https://" + ctx.ApiHost + EdgeManagementApiPath)
ctx.Req.NoError(err)
adminManagementClient := edge_apis.NewManagementApiClient([]*url.URL{managementApiUrl}, ctx.ControllerConfig.Id.CA(), func(strings chan string) {
strings <- "123"
})
adminManagementClient.SetUseOidc(true)
adminManagementApiSession, err := adminManagementClient.Authenticate(adminCreds, nil)
ctx.Req.NoError(err)
ctx.Req.NotNil(adminManagementApiSession)
t.Run("can create a new session certificate", func(t *testing.T) {
ctx.testContextChanged(t)
csrBytes, privateKey, err := generateCsr()
ctx.Req.NoError(err)
ctx.Req.NotNil(privateKey)
ctx.Req.NotEmpty(csrBytes)
csrPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes})
ctx.Req.NotEmpty(csrPem)
csr := string(csrPem)
params := ¤t_api_session.CreateCurrentAPISessionCertificateParams{
SessionCertificate: &rest_model.CurrentAPISessionCertificateCreate{
Csr: &csr,
},
}
resp, err := adminClientClient.API.CurrentAPISession.CreateCurrentAPISessionCertificate(params, nil)
ctx.Req.NoError(err)
ctx.Req.NotNil(resp)
ctx.Req.NotNil(resp.Payload)
ctx.Req.NotNil(resp.Payload.Data)
ctx.Req.NotNil(resp.Payload.Data.Certificate)
t.Run("a parsable certificate chain is returned", func(t *testing.T) {
ctx.testContextChanged(t)
certs, err := parsePEMBundle([]byte(*resp.Payload.Data.Certificate))
ctx.Req.NoError(err)
ctx.Req.True(len(certs) > 0, "no certificates found")
t.Run("the first certificate is a leaf", func(t *testing.T) {
ctx.testContextChanged(t)
ctx.False(certs[0].IsCA, "expected IsCA to be false and indicate a leaf certificate")
})
t.Run("the first certificate has the client authentication usage", func(t *testing.T) {
ctx.testContextChanged(t)
ctx.Req.True(certs[0].KeyUsage&x509.KeyUsageDigitalSignature > 0, "expected key usage digital signature")
ctx.Req.True(certs[0].KeyUsage&x509.KeyUsageKeyEncipherment > 0, "expected key usage key encipherment")
ctx.Req.Contains(certs[0].ExtKeyUsage, x509.ExtKeyUsageClientAuth)
})
t.Run("the response includes a certificate chain", func(t *testing.T) {
ctx.testContextChanged(t)
ctx.Req.True(len(certs) > 1, "no certificate chain found, potentially a leaf only result")
t.Run("the chain is in signer order", func(t *testing.T) {
ctx.testContextChanged(t)
var prevCert *x509.Certificate
for i, cert := range certs {
if prevCert != nil {
ctx.Req.True(cert.IsCA, "expected certificate at index %d to be a CA as it is not the first (leaf) certificate", i)
ctx.Req.Equal(cert.Subject.String(), prevCert.Subject.String(), "expected certificate subject to equal previous certificates issuer")
ctx.Req.NoError(prevCert.CheckSignatureFrom(cert), "expected the previous cert to be signed by the current cert, but got error: %v", err)
}
}
})
t.Run("the last certificate is not a root certificate", func(t *testing.T) {
ctx.testContextChanged(t)
lastCert := certs[len(certs)-1]
ctx.Req.True(lastCert.IsCA, "expected the last certificate in the chain to be a CA")
ctx.Req.True(lastCert.Subject.String() != lastCert.Issuer.String(), "expected the last certificate subject to not equal the last certificate (indicates a root is present)")
})
})
t.Run("the certificate contains the proper SPIFFE id", func(t *testing.T) {
ctx.testContextChanged(t)
spiffeId, err := spiffehlp.GetSpiffeIdFromCert(certs[0])
ctx.Req.NoError(err)
ctx.Req.NotEmpty(spiffeId)
apiSession := *adminClientClient.ApiSession.Load()
apiSessionId := apiSession.GetId()
identityId := apiSession.GetIdentityId()
expectedId := fmt.Sprintf("%s/identity/%s/apiSession/%s/apiSessionCertificate/", ctx.ControllerConfig.SpiffeIdTrustDomain, identityId, apiSessionId)
ctx.Req.True(strings.HasPrefix(spiffeId.String(), expectedId), "expected the spiffe id to have the prefix %s, but got %s", expectedId, spiffeId)
})
})
})
})
}
func generateCsr() ([]byte, crypto.PrivateKey, error) {
p384 := elliptic.P384()
pfxlog.Logger().Infof("generating %s EC key", p384.Params().Name)
privateKey, err := ecdsa.GenerateKey(p384, rand.Reader)
if err != nil {
return nil, nil, err
}
hostname, err := os.Hostname()
if err != nil {
return nil, nil, err
}
request, err := certtools.NewCertRequest(map[string]string{
"C": "US", "O": "TEST", "CN": hostname,
}, nil)
if err != nil {
return nil, nil, err
}
csr, err := x509.CreateCertificateRequest(rand.Reader, request, privateKey)
if err != nil {
return nil, nil, err
}
return csr, privateKey, nil
}