Debian Codegraph @

jws.go

raw symbols SCIP
1 /*-
2 * Copyright 2014 Square Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package jose
18
19 import (
20 "errors"
21 "fmt"
22 "strings"
23
24 "gopkg.in/square/go-jose.v1/json"
25 )
26
27 // rawJsonWebSignature represents a raw JWS JSON object. Used for parsing/serializing.
28 type rawJsonWebSignature struct {
29 Payload *byteBuffer `json:"payload,omitempty"`
30 Signatures []rawSignatureInfo `json:"signatures,omitempty"`
31 Protected *byteBuffer `json:"protected,omitempty"`
32 Header *rawHeader `json:"header,omitempty"`
33 Signature *byteBuffer `json:"signature,omitempty"`
34 }
35
36 // rawSignatureInfo represents a single JWS signature over the JWS payload and protected header.
37 type rawSignatureInfo struct {
38 Protected *byteBuffer `json:"protected,omitempty"`
39 Header *rawHeader `json:"header,omitempty"`
40 Signature *byteBuffer `json:"signature,omitempty"`
41 }
42
43 // JsonWebSignature represents a signed JWS object after parsing.
44 type JsonWebSignature struct {
45 payload []byte
46 // Signatures attached to this object (may be more than one for multi-sig).
47 // Be careful about accessing these directly, prefer to use Verify() or
48 // VerifyMulti() to ensure that the data you're getting is verified.
49 Signatures []Signature
50 }
51
52 // Signature represents a single signature over the JWS payload and protected header.
53 type Signature struct {
54 // Header fields, such as the signature algorithm
55 Header JoseHeader
56
57 // The actual signature value
58 Signature []byte
59
60 protected *rawHeader
61 header *rawHeader
62 original *rawSignatureInfo
63 }
64
65 // ParseSigned parses a signed message in compact or full serialization format.
66 func ParseSigned(input string) (*JsonWebSignature, error) {
67 input = stripWhitespace(input)
68 if strings.HasPrefix(input, "{") {
69 return parseSignedFull(input)
70 }
71
72 return parseSignedCompact(input)
73 }
74
75 // Get a header value
76 func (sig Signature) mergedHeaders() rawHeader {
77 out := rawHeader{}
78 out.merge(sig.protected)
79 out.merge(sig.header)
80 return out
81 }
82
83 // Compute data to be signed
84 func (obj JsonWebSignature) computeAuthData(signature *Signature) []byte {
85 var serializedProtected string
86
87 if signature.original != nil && signature.original.Protected != nil {
88 serializedProtected = signature.original.Protected.base64()
89 } else if signature.protected != nil {
90 serializedProtected = base64URLEncode(mustSerializeJSON(signature.protected))
91 } else {
92 serializedProtected = ""
93 }
94
95 return []byte(fmt.Sprintf("%s.%s",
96 serializedProtected,
97 base64URLEncode(obj.payload)))
98 }
99
100 // parseSignedFull parses a message in full format.
101 func parseSignedFull(input string) (*JsonWebSignature, error) {
102 var parsed rawJsonWebSignature
103 err := json.Unmarshal([]byte(input), &parsed)
104 if err != nil {
105 return nil, err
106 }
107
108 return parsed.sanitized()
109 }
110
111 // sanitized produces a cleaned-up JWS object from the raw JSON.
112 func (parsed *rawJsonWebSignature) sanitized() (*JsonWebSignature, error) {
113 if parsed.Payload == nil {
114 return nil, fmt.Errorf("square/go-jose: missing payload in JWS message")
115 }
116
117 obj := &JsonWebSignature{
118 payload: parsed.Payload.bytes(),
119 Signatures: make([]Signature, len(parsed.Signatures)),
120 }
121
122 if len(parsed.Signatures) == 0 {
123 // No signatures array, must be flattened serialization
124 signature := Signature{}
125 if parsed.Protected != nil && len(parsed.Protected.bytes()) > 0 {
126 signature.protected = &rawHeader{}
127 err := json.Unmarshal(parsed.Protected.bytes(), signature.protected)
128 if err != nil {
129 return nil, err
130 }
131 }
132
133 // Check that there is not a nonce in the unprotected header
134 if parsed.Header != nil && parsed.Header.Nonce != "" {
135 return nil, ErrUnprotectedNonce
136 }
137
138 signature.header = parsed.Header
139 signature.Signature = parsed.Signature.bytes()
140 // Make a fake "original" rawSignatureInfo to store the unprocessed
141 // Protected header. This is necessary because the Protected header can
142 // contain arbitrary fields not registered as part of the spec. See
143 // https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-4
144 // If we unmarshal Protected into a rawHeader with its explicit list of fields,
145 // we cannot marshal losslessly. So we have to keep around the original bytes.
146 // This is used in computeAuthData, which will first attempt to use
147 // the original bytes of a protected header, and fall back on marshaling the
148 // header struct only if those bytes are not available.
149 signature.original = &rawSignatureInfo{
150 Protected: parsed.Protected,
151 Header: parsed.Header,
152 Signature: parsed.Signature,
153 }
154
155 signature.Header = signature.mergedHeaders().sanitized()
156
157 // As per RFC 7515 Section 4.1.3, only public keys are allowed to be embedded.
158 jwk := signature.Header.JsonWebKey
159 if jwk != nil && (!jwk.Valid() || !jwk.IsPublic()) {
160 return nil, errors.New("square/go-jose: invalid embedded jwk, must be public key")
161 }
162
163 obj.Signatures = append(obj.Signatures, signature)
164 }
165
166 for i, sig := range parsed.Signatures {
167 if sig.Protected != nil && len(sig.Protected.bytes()) > 0 {
168 obj.Signatures[i].protected = &rawHeader{}
169 err := json.Unmarshal(sig.Protected.bytes(), obj.Signatures[i].protected)
170 if err != nil {
171 return nil, err
172 }
173 }
174
175 // Check that there is not a nonce in the unprotected header
176 if sig.Header != nil && sig.Header.Nonce != "" {
177 return nil, ErrUnprotectedNonce
178 }
179
180 obj.Signatures[i].Header = obj.Signatures[i].mergedHeaders().sanitized()
181 obj.Signatures[i].Signature = sig.Signature.bytes()
182
183 // As per RFC 7515 Section 4.1.3, only public keys are allowed to be embedded.
184 jwk := obj.Signatures[i].Header.JsonWebKey
185 if jwk != nil && (!jwk.Valid() || !jwk.IsPublic()) {
186 return nil, errors.New("square/go-jose: invalid embedded jwk, must be public key")
187 }
188
189 // Copy value of sig
190 original := sig
191
192 obj.Signatures[i].header = sig.Header
193 obj.Signatures[i].original = &original
194 }
195
196 return obj, nil
197 }
198
199 // parseSignedCompact parses a message in compact format.
200 func parseSignedCompact(input string) (*JsonWebSignature, error) {
201 parts := strings.Split(input, ".")
202 if len(parts) != 3 {
203 return nil, fmt.Errorf("square/go-jose: compact JWS format must have three parts")
204 }
205
206 rawProtected, err := base64URLDecode(parts[0])
207 if err != nil {
208 return nil, err
209 }
210
211 payload, err := base64URLDecode(parts[1])
212 if err != nil {
213 return nil, err
214 }
215
216 signature, err := base64URLDecode(parts[2])
217 if err != nil {
218 return nil, err
219 }
220
221 raw := &rawJsonWebSignature{
222 Payload: newBuffer(payload),
223 Protected: newBuffer(rawProtected),
224 Signature: newBuffer(signature),
225 }
226 return raw.sanitized()
227 }
228
229 // CompactSerialize serializes an object using the compact serialization format.
230 func (obj JsonWebSignature) CompactSerialize() (string, error) {
231 if len(obj.Signatures) != 1 || obj.Signatures[0].header != nil || obj.Signatures[0].protected == nil {
232 return "", ErrNotSupported
233 }
234
235 serializedProtected := mustSerializeJSON(obj.Signatures[0].protected)
236
237 return fmt.Sprintf(
238 "%s.%s.%s",
239 base64URLEncode(serializedProtected),
240 base64URLEncode(obj.payload),
241 base64URLEncode(obj.Signatures[0].Signature)), nil
242 }
243
244 // FullSerialize serializes an object using the full JSON serialization format.
245 func (obj JsonWebSignature) FullSerialize() string {
246 raw := rawJsonWebSignature{
247 Payload: newBuffer(obj.payload),
248 }
249
250 if len(obj.Signatures) == 1 {
251 if obj.Signatures[0].protected != nil {
252 serializedProtected := mustSerializeJSON(obj.Signatures[0].protected)
253 raw.Protected = newBuffer(serializedProtected)
254 }
255 raw.Header = obj.Signatures[0].header
256 raw.Signature = newBuffer(obj.Signatures[0].Signature)
257 } else {
258 raw.Signatures = make([]rawSignatureInfo, len(obj.Signatures))
259 for i, signature := range obj.Signatures {
260 raw.Signatures[i] = rawSignatureInfo{
261 Header: signature.header,
262 Signature: newBuffer(signature.Signature),
263 }
264
265 if signature.protected != nil {
266 raw.Signatures[i].Protected = newBuffer(mustSerializeJSON(signature.protected))
267 }
268 }
269 }
270
271 return string(mustSerializeJSON(raw))
272 }