/
certificates.go
305 lines (255 loc) · 9.01 KB
/
certificates.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
//go:build linux && cgo && !agent
package cluster
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"github.com/canonical/lxd/lxd/certificate"
"github.com/canonical/lxd/lxd/db/query"
"github.com/canonical/lxd/shared/api"
)
// Certificate is here to pass the certificates content from the database around.
type Certificate struct {
ID int
Fingerprint string `db:"primary=yes"`
Type certificate.Type
Name string
Certificate string
Restricted bool
}
// CertificateFilter specifies potential query parameter fields.
type CertificateFilter struct {
ID *int
Fingerprint *string
Name *string
Type *certificate.Type
}
// ToAPIType returns the API equivalent type.
func (cert *Certificate) ToAPIType() string {
switch cert.Type {
case certificate.TypeClient:
return api.CertificateTypeClient
case certificate.TypeServer:
return api.CertificateTypeServer
case certificate.TypeMetrics:
return api.CertificateTypeMetrics
}
return api.CertificateTypeUnknown
}
// ToIdentityType returns a suitable IdentityType for the certificate.
func (cert *Certificate) ToIdentityType() (IdentityType, error) {
switch cert.Type {
case certificate.TypeClient:
if cert.Restricted {
return api.IdentityTypeCertificateClientRestricted, nil
}
return api.IdentityTypeCertificateClientUnrestricted, nil
case certificate.TypeServer:
return api.IdentityTypeCertificateServer, nil
case certificate.TypeMetrics:
if cert.Restricted {
return api.IdentityTypeCertificateMetricsRestricted, nil
}
return api.IdentityTypeCertificateMetricsUnrestricted, nil
}
return "", fmt.Errorf("Unknown certificate type `%d`", cert.Type)
}
// ToAPI converts the database Certificate struct to an api.Certificate
// entry filling fields from the database as necessary.
func (cert *Certificate) ToAPI(ctx context.Context, tx *sql.Tx) (*api.Certificate, error) {
resp := api.Certificate{}
resp.Fingerprint = cert.Fingerprint
resp.Certificate = cert.Certificate
resp.Name = cert.Name
resp.Restricted = cert.Restricted
resp.Type = cert.ToAPIType()
projects, err := GetCertificateProjects(ctx, tx, cert.ID)
if err != nil {
return nil, err
}
resp.Projects = make([]string, len(projects))
for i, p := range projects {
resp.Projects[i] = p.Name
}
return &resp, nil
}
// ToIdentity converts a Certificate to an Identity.
func (cert Certificate) ToIdentity() (*Identity, error) {
identityType, err := cert.ToIdentityType()
if err != nil {
return nil, fmt.Errorf("Failed converting certificate to identity: %w", err)
}
b, err := json.Marshal(CertificateMetadata{Certificate: cert.Certificate})
if err != nil {
return nil, fmt.Errorf("Failed converting certificate to identity: %w", err)
}
identity := &Identity{
ID: cert.ID,
AuthMethod: AuthMethod(api.AuthenticationMethodTLS),
Type: identityType,
Identifier: cert.Fingerprint,
Name: cert.Name,
Metadata: string(b),
}
return identity, nil
}
// GetCertificateByFingerprintPrefix gets an CertBaseInfo object from the database.
// The argument fingerprint will be queried with a LIKE query, means you can
// pass a shortform and will get the full fingerprint.
// There can never be more than one certificate with a given fingerprint, as it is
// enforced by a UNIQUE constraint in the schema.
func GetCertificateByFingerprintPrefix(ctx context.Context, tx *sql.Tx, fingerprintPrefix string) (*Certificate, error) {
var err error
var cert *Certificate
sql := `
SELECT identities.identifier
FROM identities
WHERE identities.identifier LIKE ? AND auth_method = ?
ORDER BY identities.identifier
`
fingerprints, err := query.SelectStrings(ctx, tx, sql, fingerprintPrefix+"%", AuthMethod(api.AuthenticationMethodTLS))
if err != nil {
return nil, fmt.Errorf("Failed to fetch certificates fingerprints matching prefix %q: %w", fingerprintPrefix, err)
}
if len(fingerprints) > 1 {
return nil, fmt.Errorf("More than one certificate matches")
}
if len(fingerprints) == 0 {
return nil, api.StatusErrorf(http.StatusNotFound, "Certificate not found")
}
cert, err = GetCertificate(ctx, tx, fingerprints[0])
if err != nil {
return nil, err
}
return cert, nil
}
// CreateCertificateWithProjects stores a CertInfo object in the db, and associates it to a list of project names.
// It will ignore the ID field from the CertInfo.
func CreateCertificateWithProjects(ctx context.Context, tx *sql.Tx, cert Certificate, projectNames []string) (int64, error) {
var id int64
var err error
id, err = CreateCertificate(ctx, tx, cert)
if err != nil {
return -1, err
}
err = UpdateCertificateProjects(ctx, tx, int(id), projectNames)
if err != nil {
return -1, err
}
return id, err
}
// GetCertificates returns all available certificates.
func GetCertificates(ctx context.Context, tx *sql.Tx, filters ...CertificateFilter) ([]Certificate, error) {
authMethod := AuthMethod(api.AuthenticationMethodTLS)
identityFilters := make([]IdentityFilter, 0, len(filters))
for _, filter := range filters {
var identityTypes []IdentityType
if filter.Type != nil {
switch *filter.Type {
case certificate.TypeClient:
identityTypes = append(identityTypes, api.IdentityTypeCertificateClientRestricted, api.IdentityTypeCertificateClientUnrestricted)
case certificate.TypeServer:
identityTypes = append(identityTypes, api.IdentityTypeCertificateServer)
case certificate.TypeMetrics:
identityTypes = append(identityTypes, api.IdentityTypeCertificateMetricsRestricted, api.IdentityTypeCertificateMetricsUnrestricted)
}
}
for _, identityType := range identityTypes {
idType := identityType
identityFilters = append(identityFilters, IdentityFilter{
ID: filter.ID,
AuthMethod: &authMethod,
Type: &idType,
Identifier: filter.Fingerprint,
Name: filter.Name,
})
}
}
if len(identityFilters) == 0 {
identityFilters = []IdentityFilter{
{
AuthMethod: &authMethod,
},
}
}
certificateIdentities, err := GetIdentitys(ctx, tx, identityFilters...)
if err != nil {
return nil, err
}
certificates := make([]Certificate, 0, len(certificateIdentities))
for _, certificateIdentity := range certificateIdentities {
cert, err := certificateIdentity.ToCertificate()
if err != nil {
return nil, err
}
certificates = append(certificates, *cert)
}
return certificates, nil
}
// GetCertificate returns the certificate with the given key.
func GetCertificate(ctx context.Context, tx *sql.Tx, fingerprint string) (*Certificate, error) {
identity, err := GetIdentity(ctx, tx, api.AuthenticationMethodTLS, fingerprint)
if err != nil {
return nil, err
}
return identity.ToCertificate()
}
// GetCertificateID return the ID of the certificate with the given key.
func GetCertificateID(ctx context.Context, tx *sql.Tx, fingerprint string) (int64, error) {
identity, err := GetIdentity(ctx, tx, api.AuthenticationMethodTLS, fingerprint)
if err != nil {
return 0, err
}
return int64(identity.ID), nil
}
// CertificateExists checks if a certificate with the given key exists.
func CertificateExists(ctx context.Context, tx *sql.Tx, fingerprint string) (bool, error) {
_, err := GetIdentity(ctx, tx, api.AuthenticationMethodTLS, fingerprint)
if err != nil && !api.StatusErrorCheck(err, http.StatusNotFound) {
return false, err
} else if err != nil {
return false, nil
}
return true, nil
}
// CreateCertificate adds a new certificate to the database.
func CreateCertificate(ctx context.Context, tx *sql.Tx, object Certificate) (int64, error) {
identity, err := object.ToIdentity()
if err != nil {
return 0, err
}
return CreateIdentity(ctx, tx, *identity)
}
// DeleteCertificate deletes the certificate matching the given key parameters.
func DeleteCertificate(ctx context.Context, tx *sql.Tx, fingerprint string) error {
return DeleteIdentity(ctx, tx, api.AuthenticationMethodTLS, fingerprint)
}
// DeleteCertificates deletes the certificate matching the given key parameters.
func DeleteCertificates(ctx context.Context, tx *sql.Tx, name string, certificateType certificate.Type) error {
if certificateType == certificate.TypeClient {
err := DeleteIdentitys(ctx, tx, name, api.IdentityTypeCertificateClientRestricted)
if err != nil {
return err
}
return DeleteIdentitys(ctx, tx, name, api.IdentityTypeCertificateClientUnrestricted)
} else if certificateType == certificate.TypeServer {
return DeleteIdentitys(ctx, tx, name, api.IdentityTypeCertificateServer)
} else if certificateType == certificate.TypeMetrics {
err := DeleteIdentitys(ctx, tx, name, api.IdentityTypeCertificateMetricsRestricted)
if err != nil {
return err
}
return DeleteIdentitys(ctx, tx, name, api.IdentityTypeCertificateMetricsUnrestricted)
}
return nil
}
// UpdateCertificate updates the certificate matching the given key parameters.
func UpdateCertificate(ctx context.Context, tx *sql.Tx, fingerprint string, object Certificate) error {
identity, err := object.ToIdentity()
if err != nil {
return err
}
return UpdateIdentity(ctx, tx, AuthMethod(api.AuthenticationMethodTLS), fingerprint, *identity)
}