Skip to content

Commit a8c2e00

Browse files
Fix linting issues: replace magic numbers and string literals with constants
- services/mfa/server.go: Add and use constants for response fields, status values, and URL parameters - pkg/metrics/metrics.go: Extract histogram buckets and policy names into constants - pkg/pki/*_test.go: Use existing file permission constants instead of hardcoded octal values This addresses magic number and string literal linting issues by extracting common values into named constants, improving code maintainability and reducing duplication. Co-authored-by: Amp <[email protected]> Amp-Thread-ID: https://ampcode.com/threads/T-5be4213f-26eb-400c-bb7b-d4c79b7ee6fe
1 parent ef110b2 commit a8c2e00

File tree

4 files changed

+48
-22
lines changed

4 files changed

+48
-22
lines changed

pkg/metrics/metrics.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,18 @@ import (
77
"github.com/prometheus/client_golang/prometheus/promauto"
88
)
99

10+
const (
11+
// Policy constants
12+
keepAllowPolicy = "keep/allow"
13+
)
14+
15+
// Histogram bucket constants
16+
var (
17+
opaEvaluationBuckets = []float64{0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0}
18+
trustScoreBuckets = []float64{0, 20, 40, 60, 80, 100}
19+
databaseQueryBuckets = []float64{0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0}
20+
)
21+
1022
var (
1123
// HTTP request metrics
1224
HTTPRequestsTotal = promauto.NewCounterVec(
@@ -39,7 +51,7 @@ var (
3951
prometheus.HistogramOpts{
4052
Name: "opa_evaluation_duration_seconds",
4153
Help: "OPA policy evaluation duration in seconds",
42-
Buckets: []float64{0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0},
54+
Buckets: opaEvaluationBuckets,
4355
},
4456
[]string{"service", "policy"},
4557
)
@@ -57,7 +69,7 @@ var (
5769
prometheus.HistogramOpts{
5870
Name: "device_trust_scores",
5971
Help: "Device trust score distribution",
60-
Buckets: []float64{0, 20, 40, 60, 80, 100},
72+
Buckets: trustScoreBuckets,
6173
},
6274
[]string{"service", "posture"},
6375
)
@@ -100,7 +112,7 @@ var (
100112
prometheus.HistogramOpts{
101113
Name: "database_query_duration_seconds",
102114
Help: "Database query duration in seconds",
103-
Buckets: []float64{0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0},
115+
Buckets: databaseQueryBuckets,
104116
},
105117
[]string{"service", "query_type"},
106118
)
@@ -115,7 +127,7 @@ func RecordHTTPRequest(service, method, path, status string, duration time.Durat
115127
// RecordAuthzDecision records authorization decision metrics
116128
func RecordAuthzDecision(service, decision, reason string, duration time.Duration) {
117129
AuthzDecisionsTotal.WithLabelValues(service, decision, reason).Inc()
118-
OPAEvaluationDuration.WithLabelValues(service, "keep/allow").Observe(duration.Seconds())
130+
OPAEvaluationDuration.WithLabelValues(service, keepAllowPolicy).Observe(duration.Seconds())
119131
}
120132

121133
// RecordDeviceRegistration records device registration metrics

pkg/pki/ca_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,10 @@ func TestLoadCA(t *testing.T) {
9595
keyPath := filepath.Join(tmpDir, "key.pem")
9696

9797
// Write invalid certificate
98-
if err := os.WriteFile(certPath, []byte("invalid pem"), 0o600); err != nil {
98+
if err := os.WriteFile(certPath, []byte("invalid pem"), defaultCertPerm); err != nil {
9999
t.Fatalf("failed to write invalid certificate: %v", err)
100100
}
101-
if err := os.WriteFile(keyPath, []byte("-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg\n-----END PRIVATE KEY-----"), 0o600); err != nil {
101+
if err := os.WriteFile(keyPath, []byte("-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg\n-----END PRIVATE KEY-----"), defaultKeyPerm); err != nil {
102102
t.Fatalf("failed to write invalid key: %v", err)
103103
}
104104

@@ -123,7 +123,7 @@ func TestLoadCA(t *testing.T) {
123123
}
124124

125125
// Now corrupt the key file
126-
if err := os.WriteFile(keyPath, []byte("invalid key pem"), 0o600); err != nil {
126+
if err := os.WriteFile(keyPath, []byte("invalid key pem"), defaultKeyPerm); err != nil {
127127
t.Fatalf("failed to corrupt key file: %v", err)
128128
}
129129

pkg/pki/device_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func TestGenerateSigningKey(t *testing.T) {
4040
t.Fatalf("Key file not created: %v", err)
4141
}
4242

43-
if fileInfo.Mode().Perm() != 0o600 {
43+
if fileInfo.Mode().Perm() != defaultKeyPerm {
4444
t.Errorf("Expected file permissions 0600, got %v", fileInfo.Mode().Perm())
4545
}
4646
})
@@ -152,7 +152,7 @@ func TestLoadSigningKey(t *testing.T) {
152152

153153
t.Run("fails with invalid PEM", func(t *testing.T) {
154154
invalidPEMPath := filepath.Join(tmpDir, "invalid.key")
155-
if err := os.WriteFile(invalidPEMPath, []byte("not a pem file"), 0o600); err != nil {
155+
if err := os.WriteFile(invalidPEMPath, []byte("not a pem file"), defaultKeyPerm); err != nil {
156156
t.Fatalf("Failed to write invalid PEM file: %v", err)
157157
}
158158

@@ -176,7 +176,7 @@ MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7VJTUt9Us8cKB
176176
wHVKYdZyLkmMdVNjJqLs2Nx7e62VQqTrqTqhqY+HVhMV7HjfRqNVM6pYsf3VrGQh
177177
-----END PRIVATE KEY-----`)
178178

179-
if err := os.WriteFile(rsaKeyPath, keyData, 0o600); err != nil {
179+
if err := os.WriteFile(rsaKeyPath, keyData, defaultKeyPerm); err != nil {
180180
t.Fatalf("Failed to write RSA key: %v", err)
181181
}
182182

@@ -194,7 +194,7 @@ wHVKYdZyLkmMdVNjJqLs2Nx7e62VQqTrqTqhqY+HVhMV7HjfRqNVM6pYsf3VrGQh
194194
invalidbase64data!!!
195195
-----END PRIVATE KEY-----`
196196

197-
if err := os.WriteFile(corruptPath, []byte(corruptPEM), 0o600); err != nil {
197+
if err := os.WriteFile(corruptPath, []byte(corruptPEM), defaultKeyPerm); err != nil {
198198
t.Fatalf("Failed to write corrupt PEM: %v", err)
199199
}
200200

@@ -363,7 +363,7 @@ c3QtY2VydDAeFw0yM...")
363363
}
364364

365365
// Verify permissions
366-
if fileInfo.Mode().Perm() != 0o600 {
366+
if fileInfo.Mode().Perm() != defaultKeyPerm {
367367
t.Errorf("Expected file permissions 0600, got %v", fileInfo.Mode().Perm())
368368
}
369369

services/mfa/server.go

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,20 @@ const (
3535
writeTimeout = 30 * time.Second
3636
idleTimeout = 60 * time.Second
3737
requestTimeout = 30 * time.Second
38+
// Response fields
39+
fieldChallenge = "challenge"
40+
fieldCode = "code"
41+
fieldStatus = "status"
42+
fieldMessage = "message"
43+
fieldToken = "token"
44+
fieldAttempts = "attempts"
45+
// Status values
46+
statusOK = "ok"
47+
statusVerified = "verified"
48+
// Messages
49+
msgMFASuccess = "MFA verification successful"
50+
// URL params
51+
paramSessionID = "sessionID"
3852
)
3953

4054
// Server implements a basic MFA service for step-up authentication
@@ -171,10 +185,10 @@ func (s *Server) challengeHandler(w http.ResponseWriter, r *http.Request) {
171185

172186
w.Header().Set(headerContentType, contentTypeJSON)
173187
response := map[string]interface{}{
174-
"session_id": session.SessionID,
175-
"challenge": session.Challenge,
176-
"expires_at": session.ExpiresAt,
177-
"code": code, // Only for PoC testing
188+
"session_id": session.SessionID,
189+
fieldChallenge: session.Challenge,
190+
"expires_at": session.ExpiresAt,
191+
fieldCode: code, // Only for PoC testing
178192
}
179193
if err := json.NewEncoder(w).Encode(response); err != nil {
180194
log.Error().Err(err).Msg("failed to encode MFA challenge response")
@@ -238,9 +252,9 @@ func (s *Server) verifyHandler(w http.ResponseWriter, r *http.Request) {
238252

239253
w.Header().Set(headerContentType, contentTypeJSON)
240254
response := map[string]interface{}{
241-
"status": "verified",
242-
"message": "MFA verification successful",
243-
"token": generateMFAToken(session), // Short-lived MFA verification token
255+
fieldStatus: statusVerified,
256+
fieldMessage: msgMFASuccess,
257+
fieldToken: generateMFAToken(session), // Short-lived MFA verification token
244258
}
245259
if err := json.NewEncoder(w).Encode(response); err != nil {
246260
log.Error().Err(err).Msg("failed to encode MFA verify response")
@@ -249,7 +263,7 @@ func (s *Server) verifyHandler(w http.ResponseWriter, r *http.Request) {
249263

250264
// statusHandler returns MFA session status
251265
func (s *Server) statusHandler(w http.ResponseWriter, r *http.Request) {
252-
sessionID := chi.URLParam(r, "sessionID")
266+
sessionID := chi.URLParam(r, paramSessionID)
253267

254268
s.mu.RLock()
255269
session, exists := s.sessions[sessionID]
@@ -278,11 +292,11 @@ func (s *Server) healthHandler(w http.ResponseWriter, _ *http.Request) {
278292
s.mu.RUnlock()
279293

280294
health := map[string]interface{}{
281-
"status": "ok",
295+
fieldStatus: statusOK,
282296
"active_sessions": sessionCount,
283297
}
284298

285-
w.Header().Set("Content-Type", "application/json")
299+
w.Header().Set(headerContentType, contentTypeJSON)
286300
if err := json.NewEncoder(w).Encode(health); err != nil {
287301
log.Error().Err(err).Msg("failed to encode MFA health response")
288302
}

0 commit comments

Comments
 (0)