Skip to content

Commit a46b9a6

Browse files
committed
Fix lint warnings in inventory server and PKI
1 parent 2d35179 commit a46b9a6

File tree

5 files changed

+131
-111
lines changed

5 files changed

+131
-111
lines changed

pkg/pki/ca.go

Lines changed: 31 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,21 @@ import (
1818
)
1919

2020
const (
21-
defaultCAValidity = 10 * 365 * 24 * time.Hour
22-
defaultCertificateTTL = 8 * time.Hour
23-
defaultClockSkew = 5 * time.Minute
24-
permOwnerReadWrite = 0o600
25-
permOwnerReadExecute = 0o750
26-
permOwnerReadGroup = 0o640
27-
maxSerialShift = 128
28-
initialCapacity = 0
29-
bigIntOne = 1
30-
21+
defaultCAValidity = 10 * 365 * 24 * time.Hour
22+
defaultCertificateTTL = 8 * time.Hour
23+
defaultClockSkew = 5 * time.Minute
24+
permOwnerReadWrite = 0o600
25+
permOwnerReadExecute = 0o750
26+
permOwnerReadGroup = 0o640
27+
maxSerialShift = 128
28+
initialCapacity = 0
29+
bigIntOne = 1
30+
zeroDuration time.Duration = 0
31+
3132
// Error messages
32-
errParseCACert = "failed to parse CA certificate PEM"
33-
errParseCAKey = "failed to parse CA key PEM"
34-
errUnexpectedKeyType = "unexpected CA private key type"
33+
errParseCACert = "failed to parse CA certificate PEM"
34+
errParseCAKey = "failed to parse CA key PEM"
35+
errUnexpectedKeyType = "unexpected CA private key type"
3536
)
3637

3738
// validatePath ensures the path is safe from directory traversal attacks
@@ -63,7 +64,7 @@ func LoadOrCreateCA(certPath, keyPath, commonName string, validFor time.Duration
6364
if err := validatePath(keyPath); err != nil {
6465
return nil, fmt.Errorf("invalid key path: %w", err)
6566
}
66-
67+
6768
if err := os.MkdirAll(filepath.Dir(certPath), permOwnerReadExecute); err != nil {
6869
return nil, fmt.Errorf("failed to create certificate directory: %w", err)
6970
}
@@ -75,7 +76,7 @@ func LoadOrCreateCA(certPath, keyPath, commonName string, validFor time.Duration
7576
return LoadCA(certPath, keyPath)
7677
}
7778

78-
if validFor == 0 {
79+
if validFor == zeroDuration {
7980
validFor = defaultCAValidity
8081
}
8182

@@ -109,20 +110,20 @@ func LoadOrCreateCA(certPath, keyPath, commonName string, validFor time.Duration
109110
return nil, err
110111
}
111112

112-
if err := writeFileSecure(certPath, permOwnerReadGroup, func(f *os.File) error {
113+
if writeErr := writeFileSecure(certPath, permOwnerReadGroup, func(f *os.File) error {
113114
return pem.Encode(f, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
114-
}); err != nil {
115-
return nil, err
115+
}); writeErr != nil {
116+
return nil, writeErr
116117
}
117118

118119
encoded, err := x509.MarshalPKCS8PrivateKey(priv)
119120
if err != nil {
120121
return nil, err
121122
}
122-
if err := writeFileSecure(keyPath, permOwnerReadWrite, func(f *os.File) error {
123+
if writeErr := writeFileSecure(keyPath, permOwnerReadWrite, func(f *os.File) error {
123124
return pem.Encode(f, &pem.Block{Type: "PRIVATE KEY", Bytes: encoded})
124-
}); err != nil {
125-
return nil, err
125+
}); writeErr != nil {
126+
return nil, writeErr
126127
}
127128

128129
return LoadCA(certPath, keyPath)
@@ -193,7 +194,7 @@ func writeFileSecure(path string, perm os.FileMode, writeFn func(*os.File) error
193194
}
194195

195196
func (c *CertificateAuthority) IssueCertificate(subject pkix.Name, uris []string, dnsNames []string, ttl time.Duration, publicKey any) ([]byte, error) {
196-
if ttl == 0 {
197+
if ttl == zeroDuration {
197198
ttl = defaultCertificateTTL
198199
}
199200

@@ -211,18 +212,18 @@ func (c *CertificateAuthority) IssueCertificate(subject pkix.Name, uris []string
211212
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
212213
}
213214

214-
if len(dnsNames) > 0 {
215+
if len(dnsNames) > initialCapacity {
215216
tpl.DNSNames = dnsNames
216217
}
217218

218-
if len(uris) > 0 {
219-
parsed := make([]*url.URL, 0, len(uris))
219+
if len(uris) > initialCapacity {
220+
parsed := make([]*url.URL, initialCapacity, len(uris))
220221
for _, raw := range uris {
221-
u, err := url.Parse(raw)
222-
if err != nil {
223-
return nil, err
222+
parsedURL, parseErr := url.Parse(raw)
223+
if parseErr != nil {
224+
return nil, parseErr
224225
}
225-
parsed = append(parsed, u)
226+
parsed = append(parsed, parsedURL)
226227
}
227228
tpl.URIs = parsed
228229
}
@@ -240,7 +241,7 @@ func (c *CertificateAuthority) SignCSR(csr *x509.CertificateRequest, ttl time.Du
240241
if err := csr.CheckSignature(); err != nil {
241242
return nil, err
242243
}
243-
if ttl == 0 {
244+
if ttl == zeroDuration {
244245
ttl = defaultCertificateTTL
245246
}
246247
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(bigIntOne), maxSerialShift))

pkg/pki/ca_test.go

Lines changed: 51 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,24 @@ const (
1818
testCAName = "test-ca"
1919
testCADefault = "test-ca-default"
2020

21-
testDeviceCN = "test-device"
22-
testDeviceOrg = "test-org"
23-
testDeviceURI = "spiffe://example.com/device/123"
24-
testDeviceDNS = "device.example.com"
25-
testDeviceTTLH = time.Hour
21+
testDeviceCN = "test-device"
22+
testDeviceOrg = "test-org"
23+
testDeviceURI = "spiffe://example.com/device/123"
24+
testDeviceDNS = "device.example.com"
25+
testDeviceTTLH = time.Hour
26+
testCACertFilename = "ca.pem"
27+
testCAKeyFilename = "ca-key.pem"
28+
benchCACertFilename = "bench-ca.pem"
29+
benchCAKeyFilename = "bench-ca-key.pem"
30+
msgFailedCreateCA = "Failed to create CA: %v"
31+
msgFailedGenerateKey = "Failed to generate key: %v"
32+
benchmarkNextOffset = 1
2633
)
2734

2835
func TestLoadOrCreateCA(t *testing.T) {
2936
tmpDir := t.TempDir()
30-
certPath := filepath.Join(tmpDir, "ca.pem")
31-
keyPath := filepath.Join(tmpDir, "ca-key.pem")
37+
certPath := filepath.Join(tmpDir, testCACertFilename)
38+
keyPath := filepath.Join(tmpDir, testCAKeyFilename)
3239

3340
t.Run("creates new CA when files don't exist", func(t *testing.T) {
3441
ca, err := LoadOrCreateCA(certPath, keyPath, testCAName, time.Hour*24*365)
@@ -71,8 +78,8 @@ func TestLoadOrCreateCA(t *testing.T) {
7178

7279
t.Run("uses default validity period when zero", func(t *testing.T) {
7380
tmpDir2 := t.TempDir()
74-
certPath2 := filepath.Join(tmpDir2, "ca.pem")
75-
keyPath2 := filepath.Join(tmpDir2, "ca-key.pem")
81+
certPath2 := filepath.Join(tmpDir2, testCACertFilename)
82+
keyPath2 := filepath.Join(tmpDir2, testCAKeyFilename)
7683

7784
ca, err := LoadOrCreateCA(certPath2, keyPath2, testCADefault, 0)
7885
if err != nil {
@@ -95,11 +102,11 @@ func TestLoadCA(t *testing.T) {
95102
keyPath := filepath.Join(tmpDir, "key.pem")
96103

97104
// Write invalid certificate
98-
if err := os.WriteFile(certPath, []byte("invalid pem"), defaultCertPerm); err != nil {
99-
t.Fatalf("failed to write invalid certificate: %v", err)
105+
if writeErr := os.WriteFile(certPath, []byte("invalid pem"), defaultCertPerm); writeErr != nil {
106+
t.Fatalf("failed to write invalid certificate: %v", writeErr)
100107
}
101-
if err := os.WriteFile(keyPath, []byte("-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg\n-----END PRIVATE KEY-----"), defaultKeyPerm); err != nil {
102-
t.Fatalf("failed to write invalid key: %v", err)
108+
if writeErr := os.WriteFile(keyPath, []byte("-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg\n-----END PRIVATE KEY-----"), defaultKeyPerm); writeErr != nil {
109+
t.Fatalf("failed to write invalid key: %v", writeErr)
103110
}
104111

105112
_, err := LoadCA(certPath, keyPath)
@@ -123,8 +130,8 @@ func TestLoadCA(t *testing.T) {
123130
}
124131

125132
// Now corrupt the key file
126-
if err := os.WriteFile(keyPath, []byte("invalid key pem"), defaultKeyPerm); err != nil {
127-
t.Fatalf("failed to corrupt key file: %v", err)
133+
if writeErr := os.WriteFile(keyPath, []byte("invalid key pem"), defaultKeyPerm); writeErr != nil {
134+
t.Fatalf("failed to corrupt key file: %v", writeErr)
128135
}
129136

130137
_, err = LoadCA(certPath, keyPath)
@@ -148,8 +155,8 @@ func TestLoadCA(t *testing.T) {
148155
}
149156

150157
// Remove key file
151-
if err := os.Remove(keyPath); err != nil {
152-
t.Fatalf("failed to remove key file: %v", err)
158+
if removeErr := os.Remove(keyPath); removeErr != nil {
159+
t.Fatalf("failed to remove key file: %v", removeErr)
153160
}
154161

155162
_, err = LoadCA(certPath, keyPath)
@@ -161,18 +168,18 @@ func TestLoadCA(t *testing.T) {
161168

162169
func TestCertificateAuthority_IssueCertificate(t *testing.T) {
163170
tmpDir := t.TempDir()
164-
certPath := filepath.Join(tmpDir, "ca.pem")
165-
keyPath := filepath.Join(tmpDir, "ca-key.pem")
171+
certPath := filepath.Join(tmpDir, testCACertFilename)
172+
keyPath := filepath.Join(tmpDir, testCAKeyFilename)
166173

167174
ca, err := LoadOrCreateCA(certPath, keyPath, testCAName, 24*time.Hour)
168175
if err != nil {
169-
t.Fatalf("Failed to create CA: %v", err)
176+
t.Fatalf(msgFailedCreateCA, err)
170177
}
171178

172179
// Generate a key for the certificate
173180
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
174181
if err != nil {
175-
t.Fatalf("Failed to generate key: %v", err)
182+
t.Fatalf(msgFailedGenerateKey, err)
176183
}
177184

178185
t.Run("issues valid certificate", func(t *testing.T) {
@@ -232,6 +239,9 @@ func TestCertificateAuthority_IssueCertificate(t *testing.T) {
232239
}
233240

234241
block, _ := pem.Decode(certPEM)
242+
if block == nil {
243+
t.Fatal("Failed to decode certificate PEM")
244+
}
235245
cert, err := x509.ParseCertificate(block.Bytes)
236246
if err != nil {
237247
t.Fatalf("Failed to parse certificate: %v", err)
@@ -257,18 +267,18 @@ func TestCertificateAuthority_IssueCertificate(t *testing.T) {
257267

258268
func TestCertificateAuthority_SignCSR(t *testing.T) {
259269
tmpDir := t.TempDir()
260-
certPath := filepath.Join(tmpDir, "ca.pem")
261-
keyPath := filepath.Join(tmpDir, "ca-key.pem")
270+
certPath := filepath.Join(tmpDir, testCACertFilename)
271+
keyPath := filepath.Join(tmpDir, testCAKeyFilename)
262272

263273
ca, err := LoadOrCreateCA(certPath, keyPath, testCAName, 24*time.Hour)
264274
if err != nil {
265-
t.Fatalf("Failed to create CA: %v", err)
275+
t.Fatalf(msgFailedCreateCA, err)
266276
}
267277

268278
// Generate a key and CSR
269279
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
270280
if err != nil {
271-
t.Fatalf("Failed to generate key: %v", err)
281+
t.Fatalf(msgFailedGenerateKey, err)
272282
}
273283

274284
t.Run("signs valid CSR", func(t *testing.T) {
@@ -298,6 +308,9 @@ func TestCertificateAuthority_SignCSR(t *testing.T) {
298308

299309
// Parse and verify the certificate
300310
block, _ := pem.Decode(certPEM)
311+
if block == nil {
312+
t.Fatal("Failed to decode certificate PEM")
313+
}
301314
cert, err := x509.ParseCertificate(block.Bytes)
302315
if err != nil {
303316
t.Fatalf("Failed to parse certificate: %v", err)
@@ -385,12 +398,12 @@ func TestCertificateAuthority_SignCSR(t *testing.T) {
385398

386399
func TestCertificateAuthority_CertificatePEM(t *testing.T) {
387400
tmpDir := t.TempDir()
388-
certPath := filepath.Join(tmpDir, "ca.pem")
389-
keyPath := filepath.Join(tmpDir, "ca-key.pem")
401+
certPath := filepath.Join(tmpDir, testCACertFilename)
402+
keyPath := filepath.Join(tmpDir, testCAKeyFilename)
390403

391404
ca, err := LoadOrCreateCA(certPath, keyPath, testCAName, time.Hour*24)
392405
if err != nil {
393-
t.Fatalf("Failed to create CA: %v", err)
406+
t.Fatalf(msgFailedCreateCA, err)
394407
}
395408

396409
t.Run("returns valid PEM data", func(t *testing.T) {
@@ -402,7 +415,7 @@ func TestCertificateAuthority_CertificatePEM(t *testing.T) {
402415
// Verify it's valid PEM
403416
block, _ := pem.Decode(pemData)
404417
if block == nil {
405-
t.Error("Failed to decode PEM data")
418+
t.Fatalf("Failed to decode PEM data")
406419
}
407420

408421
if block.Type != "CERTIFICATE" {
@@ -426,17 +439,17 @@ func BenchmarkLoadOrCreateCA(b *testing.B) {
426439
tmpDir := b.TempDir()
427440

428441
b.ResetTimer()
429-
for i := 0; i < b.N; i++ {
430-
certPath := filepath.Join(tmpDir, "bench-ca.pem")
431-
keyPath := filepath.Join(tmpDir, "bench-ca-key.pem")
442+
for i := initialCapacity; i < b.N; i++ {
443+
certPath := filepath.Join(tmpDir, benchCACertFilename)
444+
keyPath := filepath.Join(tmpDir, benchCAKeyFilename)
432445

433446
_, err := LoadOrCreateCA(certPath, keyPath, "bench-ca", time.Hour*24)
434447
if err != nil {
435448
b.Fatalf("LoadOrCreateCA failed: %v", err)
436449
}
437450

438451
// Clean up for next iteration (except last)
439-
if i < b.N-1 {
452+
if i < b.N-benchmarkNextOffset {
440453
os.Remove(certPath)
441454
os.Remove(keyPath)
442455
}
@@ -445,23 +458,23 @@ func BenchmarkLoadOrCreateCA(b *testing.B) {
445458

446459
func BenchmarkIssueCertificate(b *testing.B) {
447460
tmpDir := b.TempDir()
448-
certPath := filepath.Join(tmpDir, "ca.pem")
449-
keyPath := filepath.Join(tmpDir, "ca-key.pem")
461+
certPath := filepath.Join(tmpDir, testCACertFilename)
462+
keyPath := filepath.Join(tmpDir, testCAKeyFilename)
450463

451464
ca, err := LoadOrCreateCA(certPath, keyPath, "bench-ca", time.Hour*24)
452465
if err != nil {
453-
b.Fatalf("Failed to create CA: %v", err)
466+
b.Fatalf(msgFailedCreateCA, err)
454467
}
455468

456469
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
457470
if err != nil {
458-
b.Fatalf("Failed to generate key: %v", err)
471+
b.Fatalf(msgFailedGenerateKey, err)
459472
}
460473

461474
subject := pkix.Name{CommonName: "bench-device"}
462475

463476
b.ResetTimer()
464-
for i := 0; i < b.N; i++ {
477+
for i := initialCapacity; i < b.N; i++ {
465478
_, err := ca.IssueCertificate(subject, nil, nil, time.Hour, &priv.PublicKey)
466479
if err != nil {
467480
b.Fatalf("IssueCertificate failed: %v", err)

0 commit comments

Comments
 (0)