forked from lestrrat-go/jwx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
341 lines (285 loc) · 8.39 KB
/
message.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
package jws
import (
"context"
"github.com/lestrrat-go/jwx/internal/base64"
"github.com/lestrrat-go/jwx/internal/json"
"github.com/lestrrat-go/jwx/internal/pool"
"github.com/lestrrat-go/jwx/jwk"
"github.com/pkg/errors"
)
func NewSignature() *Signature {
return &Signature{}
}
func (s Signature) PublicHeaders() Headers {
return s.headers
}
func (s *Signature) SetPublicHeaders(v Headers) *Signature {
s.headers = v
return s
}
func (s Signature) ProtectedHeaders() Headers {
return s.protected
}
func (s *Signature) SetProtectedHeaders(v Headers) *Signature {
s.protected = v
return s
}
func (s Signature) Signature() []byte {
return s.signature
}
func (s *Signature) SetSignature(v []byte) *Signature {
s.signature = v
return s
}
// Sign populates the signature field, with a signature generated by
// given the signer object and payload.
//
// The first return value is the raw signature in binary format.
// The second return value s the full three-segment signature
// (e.g. "eyXXXX.XXXXX.XXXX")
func (s *Signature) Sign(payload []byte, signer Signer, key interface{}) ([]byte, []byte, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hdrs, err := mergeHeaders(ctx, s.headers, s.protected)
if err != nil {
return nil, nil, errors.Wrap(err, `failed to merge headers`)
}
if err := hdrs.Set(AlgorithmKey, signer.Algorithm()); err != nil {
return nil, nil, errors.Wrap(err, `failed to set "alg"`)
}
// If the key is a jwk.Key instance, obtain the raw key
if jwkKey, ok := key.(jwk.Key); ok {
// If we have a key ID specified by this jwk.Key, use that in the header
if kid := jwkKey.KeyID(); kid != "" {
if err := hdrs.Set(jwk.KeyIDKey, kid); err != nil {
return nil, nil, errors.Wrap(err, `set key ID from jwk.Key`)
}
}
}
hdrbuf, err := json.Marshal(hdrs)
if err != nil {
return nil, nil, errors.Wrap(err, `failed to marshal headers`)
}
buf := pool.GetBytesBuffer()
defer pool.ReleaseBytesBuffer(buf)
buf.WriteString(base64.EncodeToString(hdrbuf))
buf.WriteByte('.')
buf.WriteString(base64.EncodeToString(payload))
signature, err := signer.Sign(buf.Bytes(), key)
if err != nil {
return nil, nil, errors.Wrap(err, `failed to sign payload`)
}
s.signature = signature
buf.WriteByte('.')
buf.WriteString(base64.EncodeToString(signature))
ret := make([]byte, buf.Len())
copy(ret, buf.Bytes())
return signature, ret, nil
}
func NewMessage() *Message {
return &Message{}
}
// Payload returns the decoded payload
func (m Message) Payload() []byte {
return m.payload
}
func (m *Message) SetPayload(v []byte) *Message {
m.payload = v
return m
}
func (m Message) Signatures() []*Signature {
return m.signatures
}
func (m *Message) AppendSignature(v *Signature) *Message {
m.signatures = append(m.signatures, v)
return m
}
func (m *Message) ClearSignatures() *Message {
m.signatures = nil
return m
}
// LookupSignature looks up a particular signature entry using
// the `kid` value
func (m Message) LookupSignature(kid string) []*Signature {
var sigs []*Signature
for _, sig := range m.signatures {
if hdr := sig.PublicHeaders(); hdr != nil {
hdrKeyID := hdr.KeyID()
if hdrKeyID == kid {
sigs = append(sigs, sig)
continue
}
}
if hdr := sig.ProtectedHeaders(); hdr != nil {
hdrKeyID := hdr.KeyID()
if hdrKeyID == kid {
sigs = append(sigs, sig)
continue
}
}
}
return sigs
}
type messageProxy struct {
Payload string `json:"payload"` // base64 URL encoded
Signatures []*signatureProxy `json:"signatures,omitempty"`
// These are only available when we're using flattened JSON
// (normally I would embed *signatureProxy, but because
// signatureProxy is not exported, we can't use that)
Header *json.RawMessage `json:"header,omitempty"`
Protected *string `json:"protected,omitempty"`
Signature *string `json:"signature,omitempty"`
}
type signatureProxy struct {
Header json.RawMessage `json:"header"`
Protected string `json:"protected"`
Signature string `json:"signature"`
}
func (m *Message) UnmarshalJSON(buf []byte) error {
var proxy messageProxy
if err := json.Unmarshal(buf, &proxy); err != nil {
return errors.Wrap(err, `failed to unmarshal into temporary structure`)
}
// Everything in the proxy is base64 encoded, except for signatures.header
if len(proxy.Payload) == 0 {
return errors.New(`"payload" must be non-empty`)
}
buf, err := base64.DecodeString(proxy.Payload)
if err != nil {
return errors.Wrap(err, `failed to decode payload`)
}
m.payload = buf
if proxy.Signature != nil {
if len(proxy.Signatures) > 0 {
return errors.Wrap(err, `invalid format ("signatures" and "signature" keys cannot both be present)`)
}
var sigproxy signatureProxy
if hdr := proxy.Header; hdr != nil {
sigproxy.Header = *hdr
}
if hdr := proxy.Protected; hdr != nil {
sigproxy.Protected = *hdr
}
sigproxy.Signature = *proxy.Signature
proxy.Signatures = append(proxy.Signatures, &sigproxy)
}
for i, sigproxy := range proxy.Signatures {
var sig Signature
if len(sigproxy.Header) > 0 {
sig.headers = NewHeaders()
if err := json.Unmarshal(sigproxy.Header, sig.headers); err != nil {
return errors.Wrapf(err, `failed to unmarshal "header" for signature #%d`, i+1)
}
}
if len(sigproxy.Protected) > 0 {
buf, err = base64.DecodeString(sigproxy.Protected)
if err != nil {
return errors.Wrapf(err, `failed to decode "protected" for signature #%d`, i+1)
}
sig.protected = NewHeaders()
if err := json.Unmarshal(buf, sig.protected); err != nil {
return errors.Wrapf(err, `failed to unmarshal "protected" for signature #%d`, i+1)
}
}
if len(sigproxy.Signature) == 0 {
return errors.Errorf(`"signature" must be non-empty for signature #%d`, i+1)
}
buf, err = base64.DecodeString(sigproxy.Signature)
if err != nil {
return errors.Wrapf(err, `failed to decode "signature" for signature #%d`, i+1)
}
sig.signature = buf
m.signatures = append(m.signatures, &sig)
}
return nil
}
func (m Message) MarshalJSON() ([]byte, error) {
if len(m.signatures) == 1 {
return m.marshalFlattened()
}
return m.marshalFull()
}
func (m Message) marshalFlattened() ([]byte, error) {
buf := pool.GetBytesBuffer()
defer pool.ReleaseBytesBuffer(buf)
sig := m.signatures[0]
buf.WriteRune('{')
var wrote bool
if hdr := sig.headers; hdr != nil {
hdrjs, err := hdr.MarshalJSON()
if err != nil {
return nil, errors.Wrap(err, `failed to marshal "header" (flattened format)`)
}
buf.WriteString(`"header":`)
buf.Write(hdrjs)
wrote = true
}
if wrote {
buf.WriteRune(',')
}
buf.WriteString(`"payload":"`)
buf.WriteString(base64.EncodeToString(m.payload))
buf.WriteRune('"')
if protected := sig.protected; protected != nil {
protectedbuf, err := protected.MarshalJSON()
if err != nil {
return nil, errors.Wrap(err, `failed to marshal "protected" (flattened format)`)
}
buf.WriteString(`,"protected":"`)
buf.WriteString(base64.EncodeToString(protectedbuf))
buf.WriteRune('"')
}
buf.WriteString(`,"signature":"`)
buf.WriteString(base64.EncodeToString(sig.signature))
buf.WriteRune('"')
buf.WriteRune('}')
ret := make([]byte, buf.Len())
copy(ret, buf.Bytes())
return ret, nil
}
func (m Message) marshalFull() ([]byte, error) {
buf := pool.GetBytesBuffer()
defer pool.ReleaseBytesBuffer(buf)
buf.WriteString(`{"payload":"`)
buf.WriteString(base64.EncodeToString(m.payload))
buf.WriteString(`","signatures":[`)
for i, sig := range m.signatures {
if i > 0 {
buf.WriteRune(',')
}
buf.WriteRune('{')
var wrote bool
if hdr := sig.headers; hdr != nil {
hdrbuf, err := hdr.MarshalJSON()
if err != nil {
return nil, errors.Wrapf(err, `failed to marshal "header" for signature #%d`, i+1)
}
buf.WriteString(`"header":`)
buf.Write(hdrbuf)
wrote = true
}
if protected := sig.protected; protected != nil {
protectedbuf, err := protected.MarshalJSON()
if err != nil {
return nil, errors.Wrapf(err, `failed to marshal "protected" for signature #%d`, i+1)
}
if wrote {
buf.WriteRune(',')
}
buf.WriteString(`"protected":"`)
buf.WriteString(base64.EncodeToString(protectedbuf))
buf.WriteRune('"')
wrote = true
}
if wrote {
buf.WriteRune(',')
}
buf.WriteString(`"signature":"`)
buf.WriteString(base64.EncodeToString(sig.signature))
buf.WriteString(`"}`)
}
buf.WriteString(`]}`)
ret := make([]byte, buf.Len())
copy(ret, buf.Bytes())
return ret, nil
}