Debian Codegraph @

signature/jws/conformance_test.go

raw
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package jws
15
16 import (
17 "crypto/elliptic"
18 "crypto/x509"
19 "encoding/json"
20 "os"
21 "reflect"
22 "sort"
23 "strings"
24 "testing"
25 "time"
26
27 "github.com/notaryproject/notation-core-go/signature"
28 "github.com/notaryproject/notation-core-go/testhelper"
29 )
30
31 var (
32 // prepare signing time
33 signingTime, _ = time.Parse("2006-01-02 15:04:05", "2022-08-29 13:50:00")
34 expiry, _ = time.Parse("2006-01-02 15:04:05", "2099-08-29 13:50:00")
35 // signedAttributes for signing request
36 signedAttributes = signature.SignedAttributes{
37 SigningScheme: "notary.x509",
38 SigningTime: signingTime,
39 Expiry: expiry.Add(time.Hour * 24),
40 ExtendedAttributes: sortAttributes([]signature.Attribute{
41 {Key: "signedCritKey1", Value: "signedCritValue1", Critical: true},
42 {Key: "signedKey1", Value: "signedValue1", Critical: false},
43 {Key: "signedKey2", Value: "signedValue1", Critical: false},
44 {Key: "signedKey3", Value: "signedValue1", Critical: false},
45 {Key: "signedKey4", Value: "signedValue1", Critical: false},
46 }),
47 }
48 // unsignedAttributes for signing request
49 unsignedAttributes = signature.UnsignedAttributes{
50 SigningAgent: "NotationConformanceTest/1.0.0",
51 }
52 // payload to be signed
53 payload = signature.Payload{
54 ContentType: "application/vnd.cncf.notary.payload.v1+json",
55 Content: []byte(`{"key":"hello JWS"}`),
56 }
57 // certificate chain for signer
58 leafCertTuple = testhelper.GetECCertTuple(elliptic.P256())
59 certs = []*x509.Certificate{leafCertTuple.Cert, testhelper.GetECRootCertificate().Cert}
60 )
61
62 func conformanceTestSignReq() *signature.SignRequest {
63 signer, err := signature.NewLocalSigner(certs, leafCertTuple.PrivateKey)
64 if err != nil {
65 panic(err)
66 }
67
68 return &signature.SignRequest{
69 Payload: payload,
70 Signer: signer,
71 SigningTime: signedAttributes.SigningTime,
72 Expiry: signedAttributes.Expiry,
73 ExtendedSignedAttributes: signedAttributes.ExtendedAttributes,
74 SigningAgent: unsignedAttributes.SigningAgent,
75 SigningScheme: signedAttributes.SigningScheme,
76 }
77 }
78
79 // TestSignedMessageConformance check the conformance between the encoded message
80 // and the valid encoded message in conformance.json
81 //
82 // check payload, protected and signingAgent section
83 func TestSignedMessageConformance(t *testing.T) {
84 // get encoded message
85 env := envelope{}
86 signReq := conformanceTestSignReq()
87 encoded, err := env.Sign(signReq)
88 checkNoError(t, err)
89
90 // parse encoded message to be a map
91 envMap, err := unmarshalEncodedMessage(encoded)
92 checkNoError(t, err)
93 // load validation encoded message
94 validEnvMap, err := getValidEnvelopeMap()
95 checkNoError(t, err)
96
97 // check payload section conformance
98 if !reflect.DeepEqual(envMap["payload"], validEnvMap["payload"]) {
99 t.Fatal("signed message payload test failed.")
100 }
101
102 // check protected section conformance
103 if !reflect.DeepEqual(envMap["protected"], validEnvMap["protected"]) {
104 t.Fatal("signed message protected test failed.")
105 }
106
107 // prepare header
108 header, ok := envMap["header"].(map[string]interface{})
109 if !ok {
110 t.Fatal("signed message header format error.")
111 }
112 validHeader, ok := validEnvMap["header"].(map[string]interface{})
113 if !ok {
114 t.Fatal("conformance.json header format error.")
115 }
116 // check io.cncf.notary.signingAgent conformance
117 if !reflect.DeepEqual(header["io.cncf.notary.signingAgent"], validHeader["io.cncf.notary.signingAgent"]) {
118 t.Fatal("signed message signingAgent test failed.")
119 }
120 }
121
122 func getValidEnvelopeMap() (map[string]interface{}, error) {
123 encoded, err := os.ReadFile("./testdata/conformance.json")
124 if err != nil {
125 return nil, err
126 }
127 return unmarshalEncodedMessage(encoded)
128 }
129
130 func unmarshalEncodedMessage(encoded []byte) (envelopeMap map[string]interface{}, err error) {
131 err = json.Unmarshal(encoded, &envelopeMap)
132 return
133 }
134
135 // TestVerifyConformance generates JWS encoded message, parses the encoded message and
136 // verify the payload, signed/unsigned attributes conformance.
137 func TestVerifyConformance(t *testing.T) {
138 env := envelope{}
139 signReq := conformanceTestSignReq()
140 encoded, err := env.Sign(signReq)
141 checkNoError(t, err)
142
143 // parse envelope
144 var e jwsEnvelope
145 err = json.Unmarshal(encoded, &e)
146 checkNoError(t, err)
147 newEnv := envelope{base: &e}
148
149 // verify validity
150 content, err := newEnv.Verify()
151 checkNoError(t, err)
152
153 // check payload conformance
154 verifyPayload(t, &content.Payload)
155
156 // check signed/unsigned attributes conformance
157 verifyAttributes(t, &content.SignerInfo)
158 }
159
160 func verifyPayload(t *testing.T, gotPayload *signature.Payload) {
161 if !reflect.DeepEqual(&payload, gotPayload) {
162 t.Fatalf("verify payload failed. want: %+v got: %+v\n", &payload, gotPayload)
163 }
164 }
165
166 func verifyAttributes(t *testing.T, signerInfo *signature.SignerInfo) {
167 // check unsigned attributes
168 if !reflect.DeepEqual(&unsignedAttributes, &signerInfo.UnsignedAttributes) {
169 t.Fatalf("verify UnsignedAttributes failed. want: %+v got: %+v\n", &unsignedAttributes, &signerInfo.UnsignedAttributes)
170 }
171
172 // check signed attributes
173 sortAttributes(signerInfo.SignedAttributes.ExtendedAttributes)
174 if !reflect.DeepEqual(&signedAttributes, &signerInfo.SignedAttributes) {
175 t.Fatalf("verify SignedAttributes failed. want: %+v got: %+v\n", &signedAttributes, &signerInfo.SignedAttributes)
176 }
177
178 // check signature algorithm
179 keySpec, err := signature.ExtractKeySpec(certs[0])
180 checkNoError(t, err)
181 if keySpec.SignatureAlgorithm() != signerInfo.SignatureAlgorithm {
182 t.Fatalf("verify signature algorithm failed. want: %d got: %d\n", keySpec.SignatureAlgorithm(), signerInfo.SignatureAlgorithm)
183 }
184
185 // check certificate chain
186 if !reflect.DeepEqual(signerInfo.CertificateChain, certs) {
187 t.Fatalf("verify certificate chain failed. want: %+v got: %+v\n", &signerInfo.CertificateChain, certs)
188 }
189 }
190
191 func sortAttributes(attributes []signature.Attribute) []signature.Attribute {
192 sort.Slice(attributes, func(i, j int) bool {
193 key1, key2 := attributes[i].Key.(string), attributes[j].Key.(string)
194 return strings.Compare(key1, key2) < 0
195 })
196 return attributes
197 }