Repository navigation
Expand file tree
/
Copy pathjson_test.go
More file actions
276 lines (230 loc) · 7.27 KB
/
Copy pathjson_test.go
File metadata and controls
276 lines (230 loc) · 7.27 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
package cmd
import (
"bytes"
"encoding/json"
"io"
"os"
"path/filepath"
"testing"
)
func TestJSONOutput(t *testing.T) {
// Create a temporary directory for test outputs
tmpDir, err := os.MkdirTemp("", "certwiz-json-test-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
// Test generate command with JSON output
t.Run("GenerateJSON", func(t *testing.T) {
// Set up command parameters
generateCN = "test.example.com"
generateOutput = tmpDir
generateKeySize = 2048
generateDays = 365
jsonOutput = true
// Capture stdout
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
// Run the command
_ = generateCmd.RunE(generateCmd, []string{})
// Restore stdout and read output
_ = w.Close()
os.Stdout = old
var buf bytes.Buffer
_, _ = io.Copy(&buf, r)
// Parse JSON output
var result map[string]interface{}
err := json.Unmarshal(buf.Bytes(), &result)
if err != nil {
t.Fatalf("Failed to parse JSON output: %v", err)
}
// Verify JSON structure
if success, ok := result["success"].(bool); !ok || !success {
t.Error("Expected success: true in JSON output")
}
if files, ok := result["files"].([]interface{}); !ok || len(files) != 2 {
t.Error("Expected 2 files in JSON output")
}
// Reset for other tests
jsonOutput = false
})
// Test inspect command with JSON output
t.Run("InspectJSON", func(t *testing.T) {
// First generate a certificate
generateCN = "inspect-test.local"
generateOutput = tmpDir
generateKeySize = 2048
generateDays = 365
jsonOutput = false
_ = generateCmd.RunE(generateCmd, []string{})
// Now inspect it with JSON output
certPath := filepath.Join(tmpDir, "inspect-test.local.crt")
jsonOutput = true
// Capture stdout
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
// Run inspect command
_ = inspectCmd.RunE(inspectCmd, []string{certPath})
// Restore stdout and read output
_ = w.Close()
os.Stdout = old
var buf bytes.Buffer
_, _ = io.Copy(&buf, r)
// Parse JSON output
var cert map[string]interface{}
err = json.Unmarshal(buf.Bytes(), &cert)
if err != nil {
t.Fatalf("Failed to parse certificate JSON: %v", err)
}
// Verify certificate fields
if subject, ok := cert["subject"].(map[string]interface{}); ok {
if cn, ok := subject["common_name"].(string); !ok || cn != "inspect-test.local" {
t.Errorf("Expected common_name to be inspect-test.local, got %v", cn)
}
} else {
t.Error("Missing subject in certificate JSON")
}
if _, ok := cert["serial_number"].(string); !ok {
t.Error("Missing serial_number in certificate JSON")
}
if _, ok := cert["not_before"].(string); !ok {
t.Error("Missing not_before in certificate JSON")
}
if _, ok := cert["not_after"].(string); !ok {
t.Error("Missing not_after in certificate JSON")
}
// Reset for other tests
jsonOutput = false
})
// Test verify command with JSON output
t.Run("VerifyJSON", func(t *testing.T) {
// Use the certificate generated in previous test
certPath := filepath.Join(tmpDir, "inspect-test.local.crt")
jsonOutput = true
verifyHost = ""
verifyCA = ""
// Capture stdout
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
// Run verify command
_ = verifyCmd.RunE(verifyCmd, []string{certPath})
// Restore stdout and read output
_ = w.Close()
os.Stdout = old
var buf bytes.Buffer
_, _ = io.Copy(&buf, r)
// Parse JSON output
var result map[string]interface{}
err := json.Unmarshal(buf.Bytes(), &result)
if err != nil {
t.Fatalf("Failed to parse verification JSON: %v", err)
}
// Check verification result
if _, ok := result["is_valid"].(bool); !ok {
t.Error("Missing is_valid in verification JSON")
}
if cert, ok := result["certificate"].(map[string]interface{}); !ok {
t.Error("Missing certificate in verification JSON")
} else {
if subject, ok := cert["subject"].(map[string]interface{}); ok {
if cn, ok := subject["common_name"].(string); !ok || cn != "inspect-test.local" {
t.Errorf("Expected certificate CN to be inspect-test.local, got %v", cn)
}
}
}
// Reset for other tests
jsonOutput = false
})
// Helper to run a command's RunE with JSON output and return the parsed result
runJSON := func(t *testing.T, run func() error) (map[string]interface{}, error) {
t.Helper()
jsonOutput = true
defer func() { jsonOutput = false }()
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
runErr := run()
_ = w.Close()
os.Stdout = old
var buf bytes.Buffer
_, _ = io.Copy(&buf, r)
var result map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &result); err != nil {
t.Fatalf("Failed to parse JSON output: %v\nOutput: %s", err, buf.String())
}
return result, runErr
}
checkOperationResult := func(t *testing.T, result map[string]interface{}, wantFiles int) {
t.Helper()
if success, ok := result["success"].(bool); !ok || !success {
t.Error("Expected success: true in JSON output")
}
if files, ok := result["files"].([]interface{}); !ok || len(files) != wantFiles {
t.Errorf("Expected %d files in JSON output, got %v", wantFiles, result["files"])
}
}
// Test ca command with JSON output
t.Run("CAJSON", func(t *testing.T) {
caCN = "JSON Test CA"
caOutput = tmpDir
caKeySize = 2048
caDays = 365
result, err := runJSON(t, func() error { return caCmd.RunE(caCmd, []string{}) })
if err != nil {
t.Fatalf("ca command failed: %v", err)
}
checkOperationResult(t, result, 2)
})
// Test csr command with JSON output
t.Run("CSRJSON", func(t *testing.T) {
csrCN = "csr-json-test.local"
csrOutput = tmpDir
csrKeySize = 2048
result, err := runJSON(t, func() error { return csrCmd.RunE(csrCmd, []string{}) })
if err != nil {
t.Fatalf("csr command failed: %v", err)
}
checkOperationResult(t, result, 2)
})
// Test sign command with JSON output (uses the CA and CSR created above)
t.Run("SignJSON", func(t *testing.T) {
signCSR = filepath.Join(tmpDir, "csr-json-test.local.csr")
signCA = filepath.Join(tmpDir, "JSON_Test_CA-ca.crt")
signCAKey = filepath.Join(tmpDir, "JSON_Test_CA-ca.key")
signOutput = tmpDir
signDays = 365
result, err := runJSON(t, func() error { return signCmd.RunE(signCmd, []string{}) })
if err != nil {
t.Fatalf("sign command failed: %v", err)
}
checkOperationResult(t, result, 1)
})
// Test convert command with JSON output
t.Run("ConvertJSON", func(t *testing.T) {
inputPath := filepath.Join(tmpDir, "inspect-test.local.crt")
outputPath := filepath.Join(tmpDir, "inspect-test.local.der")
convertFormat = "der"
result, err := runJSON(t, func() error { return convertCmd.RunE(convertCmd, []string{inputPath, outputPath}) })
if err != nil {
t.Fatalf("convert command failed: %v", err)
}
checkOperationResult(t, result, 1)
})
// Test that JSON errors are emitted as JSON payloads
t.Run("ErrorJSON", func(t *testing.T) {
caCN = ""
result, err := runJSON(t, func() error { return caCmd.RunE(caCmd, []string{}) })
if err == nil {
t.Fatal("Expected error for missing --cn")
}
if success, ok := result["success"].(bool); !ok || success {
t.Error("Expected success: false in JSON error output")
}
if msg, ok := result["error"].(string); !ok || msg == "" {
t.Error("Expected non-empty error message in JSON error output")
}
})
}