forked from guardtime/goksi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ksi_test.go
362 lines (307 loc) · 11.8 KB
/
ksi_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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
* Copyright 2020 Guardtime, Inc.
*
* This file is part of the Guardtime client SDK.
*
* 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
* http://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, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
* "Guardtime" and "KSI" are trademarks or registered trademarks of
* Guardtime, Inc., and no license to trademarks is granted; Guardtime
* reserves and retains all trademark rights.
*/
package ksi
import (
"encoding/csv"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/vincentracine/goksi/errors"
"github.com/vincentracine/goksi/hash"
"github.com/vincentracine/goksi/log"
"github.com/vincentracine/goksi/pdu"
"github.com/vincentracine/goksi/publications"
"github.com/vincentracine/goksi/service"
"github.com/vincentracine/goksi/signature"
"github.com/vincentracine/goksi/signature/verify/reserr"
"github.com/vincentracine/goksi/signature/verify/result"
"github.com/vincentracine/goksi/test"
"github.com/vincentracine/goksi/test/sysconf"
"github.com/vincentracine/goksi/test/utils"
"github.com/vincentracine/goksi/test/utils/mock"
)
const (
csvComment = '#'
csvComma = ';'
testUser = "anon"
testPass = "anon"
)
type csvField byte
const (
csvFieldSignatureURI csvField = iota
csvFieldVerificationState
csvFieldErrorCode
csvFieldErrorMessage
csvFieldInputHashLevel
csvFieldAggrInputHash
csvFieldCalInputHash
csvFieldCalOutputHash
csvFieldAggrTime
csvFieldPubTime
csvFieldPubString
csvFieldExtendPerm
csvFieldExtendResp
csvFieldPubsFile
csvFieldCertFile
)
type verifyStrategy byte
const (
vsNotImplemented verifyStrategy = iota
vsParseFailure
vsPolicy
)
var (
testRoot = filepath.Join("test")
confFile = filepath.Join(testRoot, "systest.conf.json")
logDir = filepath.Join(testRoot, "out")
resourceDir = filepath.Join(testRoot, "resource")
resourceTestPackDir = filepath.Join(resourceDir, "SignatureTestPack")
)
func TestSysPack(t *testing.T) {
logger, defFunc, err := test.InitLogger(t, logDir, log.DEBUG, t.Name())
if err != nil {
t.Fatal("Failed to initialize logger: ", err)
}
defer defFunc()
// Apply logger.
log.SetLogger(logger)
// Check if system test config is present and load it.
cfg := utils.LoadConfigFile(t, confFile)
test.Suite{
{Func: validSignaturesTests},
{Func: invalidSignaturesTests},
{Func: policyVerificationTests},
{Func: internalPolicySignaturesTests},
}.Runner(t, cfg)
}
const (
ksiSysTestOptCfg = iota
)
func validSignaturesTests(t *testing.T, opt ...interface{}) {
testLoader(t, opt[ksiSysTestOptCfg].(*sysconf.Configuration),
filepath.Join(resourceTestPackDir, "valid-signatures"), "signature-results.csv")
}
func invalidSignaturesTests(t *testing.T, opt ...interface{}) {
testLoader(t, opt[ksiSysTestOptCfg].(*sysconf.Configuration),
filepath.Join(resourceTestPackDir, "invalid-signatures"), "invalid-signature-results.csv")
}
func policyVerificationTests(t *testing.T, opt ...interface{}) {
testLoader(t, opt[ksiSysTestOptCfg].(*sysconf.Configuration),
filepath.Join(resourceTestPackDir, "policy-verification-signatures"), "policy-verification-results.csv")
}
func internalPolicySignaturesTests(t *testing.T, opt ...interface{}) {
testLoader(t, opt[ksiSysTestOptCfg].(*sysconf.Configuration),
filepath.Join(resourceTestPackDir, "internal-policy-signatures"), "internal-policy-results.csv")
}
func testLoader(t *testing.T, cfg *sysconf.Configuration, rootPath, csvFile string) {
csvPath := path.Join(rootPath, csvFile)
recs, err := loadRecords(csvPath)
if err != nil {
t.Fatal("Failed to load CSV records: ", err)
}
log.Debug("TestPack CSV file: ", csvPath)
for _, rec := range recs {
csvLine := strings.Join(rec, ";")
t.Run(csvLine,
func(t *testing.T) {
log.Debug("Test CSV record: ", csvLine)
testRunner(cfg, t, rootPath, rec)
},
)
}
}
func loadRecords(p string) ([][]string, error) {
f, err := os.Open(p)
if err != nil {
return nil, err
}
defer func() {
if err := f.Close(); err != nil {
log.Error("Failed to close file: ", err)
}
}()
r := csv.NewReader(f)
r.Comma = csvComma
r.Comment = csvComment
return r.ReadAll()
}
func testRunner(cfg *sysconf.Configuration, t *testing.T, root string, csvRec []string) {
var (
err error
pfhOpts = []publications.FileHandlerSetting{
publications.FileHandlerSetFileCertConstraints(cfg.Pubfile.Constraints()),
}
verOpts []signature.VerCtxOption
verStrategy verifyStrategy
verPolicy signature.Policy
verErr = reserr.ErrNA
verErrMgs string
)
// Set verification state and policy.
if len(csvRec[csvFieldVerificationState]) > 0 {
switch csvRec[csvFieldVerificationState] {
case "not-implemented":
verStrategy = vsNotImplemented
case "parsing":
verStrategy = vsParseFailure
default:
switch csvRec[csvFieldVerificationState] {
case "calendar":
verPolicy = signature.CalendarBasedVerificationPolicy
case "key":
verPolicy = signature.KeyBasedVerificationPolicy
case "userPublication":
verPolicy = signature.UserProvidedPublicationBasedVerificationPolicy
case "publicationsFile":
verPolicy = signature.PublicationsFileBasedVerificationPolicy
case "internal":
verPolicy = signature.InternalVerificationPolicy
default:
t.Error("Skipping test case because of unknown verification state: ", csvRec[csvFieldVerificationState])
}
verStrategy = vsPolicy
}
}
if verStrategy == vsNotImplemented {
log.Debug("Skipping test.")
t.Skip("Skipping test for 'not_implemented'")
return
}
if len(csvRec[csvFieldCertFile]) > 0 {
pfhOpts = append(pfhOpts, publications.FileHandlerSetTrustedCertificateFromFilePem(path.Join(root, csvRec[csvFieldCertFile])))
}
var pubsFile *publications.File
if len(csvRec[csvFieldPubsFile]) > 0 {
pubsFile, err = publications.NewFile(publications.FileFromFile(path.Join(root, csvRec[csvFieldPubsFile])))
assert(t, err == nil, "Failed to load publications file: ", err)
verOpts = append(verOpts, signature.VerCtxOptPublicationsFile(pubsFile))
} else {
pfhOpts = append(pfhOpts, publications.FileHandlerSetPublicationsURL(cfg.Pubfile.Url))
}
if len(csvRec[csvFieldAggrInputHash]) > 0 {
verOpts = append(verOpts, signature.VerCtxOptDocumentHash(hash.Imprint(utils.StringToBin(csvRec[csvFieldAggrInputHash]))))
}
if len(csvRec[csvFieldInputHashLevel]) > 0 {
tmp, err := strconv.ParseUint(csvRec[csvFieldInputHashLevel], 10, 64)
assert(t, err == nil, "Failed to parse level value: ", err)
assert(t, tmp < (0xff+1), "Input level is to large: ", tmp)
verOpts = append(verOpts, signature.VerCtxOptInputHashLevel(byte(tmp)))
}
if len(csvRec[csvFieldPubString]) > 0 {
tmp, err := pdu.NewPublicationData(pdu.PubDataFromString(csvRec[csvFieldPubString]))
assert(t, err == nil, "Failed to parse publication string:", err)
verOpts = append(verOpts, signature.VerCtxOptUserPublication(tmp))
}
pfh, err := publications.NewFileHandler(pfhOpts...)
if err != nil {
t.Fatal("Failed to initialize publications file handler: ", err)
}
verOpts = append(verOpts, signature.VerCtxOptPublicationsFileHandler(pfh))
if pubsFile != nil {
err = pfh.Verify(pubsFile)
assert(t, err == nil, "Failed to verify publications file: ", err)
}
if len(csvRec[csvFieldExtendPerm]) > 0 && csvRec[csvFieldExtendPerm] == "true" {
verOpts = append(verOpts, signature.VerCtxOptExtendingPermitted(true))
}
if len(csvRec[csvFieldExtendResp]) > 0 {
client := mock.NewFileReaderClient(path.Join(root, csvRec[csvFieldExtendResp]), testUser, testPass)
tmp, err := service.NewExtender(pfh, service.OptNetClient(client))
assert(t, err == nil, "Failed setup extender: ", err)
verOpts = append(verOpts, signature.VerCtxOptCalendarProvider(tmp))
} else {
tmp, err := service.NewExtender(pfh, service.OptEndpoint(cfg.Extender.BuildURI(cfg.Schema.Tcp), cfg.Extender.User, cfg.Extender.Pass))
assert(t, err == nil, "Failed setup extender: ", err)
verOpts = append(verOpts, signature.VerCtxOptCalendarProvider(tmp))
}
sig, err := signature.New(signature.BuildNoVerify(
signature.BuildFromFile(path.Join(root, csvRec[csvFieldSignatureURI]))))
if err != nil {
assert(t, verStrategy == vsParseFailure, "Unexpected failure: ", err)
assert(t, err.(*errors.KsiError).Code() == errors.KsiInvalidFormatError ||
err.(*errors.KsiError).Code() == errors.KsiInvalidStateError,
"Signature parsing did not fail with expected error: ", err.Error())
log.Debug("Signature is expected to fail during parsing stage.")
return
}
assert(t, verStrategy != vsParseFailure, "Signature must have failed during parse stage.")
verCtx, err := signature.NewVerificationContext(sig, verOpts...)
assert(t, err == nil, "Failed to create verification context: ", err)
res, err := verPolicy.Verify(verCtx)
assert(t, err == nil, "Failed to verify: ", err)
// Verify test case expectations match the verification result.
if len(csvRec[csvFieldErrorCode]) > 0 && csvRec[csvFieldErrorCode] != "OK" {
verErr = reserr.CodeByName(csvRec[csvFieldErrorCode])
verErrMgs = csvRec[csvFieldErrorMessage]
assert(t, verErr != reserr.ErrNA, "Unknown error code: ", csvRec[csvFieldErrorCode])
}
if verErr != reserr.ErrNA {
// Verification is expected to fail.
assert(t, res != result.OK, "Signature verification should have failed.")
// Test case has failed as expected. Verify fail result.
verResult, err := verCtx.Result()
assert(t, err == nil, "Failed to get verification result: ", err)
resultErr, ok := verResult.Error().(*errors.KsiError)
assert(t, ok, "Unknown verification result error:", resultErr)
resultCode := reserr.Code(resultErr.ExtCode())
assert(t, resultErr.Code() == errors.KsiVerificationFailure && resultCode == verErr, "Error code mismatch.")
assert(t, verErr.Message() == verErrMgs, "Error message mismatch.")
} else {
// Verification is not expected to fail.
assert(t, res == result.OK, "Signature verification should not fail. Result:", res)
}
if len(csvRec[csvFieldCalInputHash]) > 0 {
hsh, err := sig.AggregationHashChainListAggregate(0)
assert(t, err == nil, "Failed to aggregate hash chains: ", err)
assert(t, hash.Equal(hsh, hash.Imprint(utils.StringToBin(csvRec[csvFieldCalInputHash]))), "Calendar input hash mismatch.")
}
if len(csvRec[csvFieldCalOutputHash]) > 0 {
calChain, err := sig.CalendarChain()
assert(t, err == nil, "Failed to get calendar hash chain:", err)
hsh, err := calChain.Aggregate()
assert(t, err == nil, "Failed to calendar hash chain: ", err)
assert(t, hash.Equal(hsh, hash.Imprint(utils.StringToBin(csvRec[csvFieldCalOutputHash]))), "Calendar output hash mismatch.")
}
if len(csvRec[csvFieldAggrTime]) > 0 {
tmp, err := strconv.ParseUint(csvRec[csvFieldAggrTime], 10, 64)
assert(t, err == nil, "Failed to parse aggregation time:", err)
sigTime, err := sig.SigningTime()
assert(t, err == nil, "Failed to get signing time: ", err)
assert(t, sigTime.Equal(time.Unix(int64(tmp), 0)), "Aggregation time mismatch.")
}
if len(csvRec[csvFieldPubTime]) > 0 {
tmp, err := strconv.ParseUint(csvRec[csvFieldPubTime], 10, 64)
assert(t, err == nil, "Failed to parse pub time:", err)
calChain, err := sig.CalendarChain()
assert(t, err == nil, "Failed to get calendar hash chain:", err)
pubTime, err := calChain.PublicationTime()
assert(t, err == nil, "Failed to get publication time: ", err)
assert(t, pubTime.Equal(time.Unix(int64(tmp), 0)), "Aggregation time mismatch.")
}
}
func assert(t *testing.T, cond bool, msgArgs ...interface{}) {
if !cond {
log.Debug(msgArgs...)
t.Fatal(msgArgs...)
}
}