-
Notifications
You must be signed in to change notification settings - Fork 14
/
common.go
391 lines (315 loc) · 9.11 KB
/
common.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package session
import (
"bytes"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
"github.com/nspcc-dev/neofs-api-go/v2/session"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/nspcc-dev/neofs-sdk-go/user"
)
type commonData struct {
idSet bool
id uuid.UUID
issuerSet bool
issuer user.ID
lifetimeSet bool
iat, nbf, exp uint64
authKey []byte
sigSet bool
sig refs.Signature
}
type contextReader func(session.TokenContext, bool) error
func (x commonData) copyTo(dst *commonData) {
dst.idSet = x.idSet
copy(dst.id[:], x.id[:])
dst.issuerSet = x.issuerSet
iss := x.issuer
dst.issuer = iss
dst.lifetimeSet = x.lifetimeSet
dst.iat = x.iat
dst.nbf = x.nbf
dst.exp = x.exp
if auth := x.authKey; auth != nil {
dst.authKey = make([]byte, len(x.authKey))
copy(dst.authKey, x.authKey)
} else {
dst.authKey = nil
}
dst.sigSet = x.sigSet
if sig := x.sig.GetKey(); sig != nil {
bts := make([]byte, len(sig))
copy(bts, sig)
dst.sig.SetKey(bts)
} else {
dst.sig.SetKey(nil)
}
dst.sig.SetScheme(x.sig.GetScheme())
if sign := x.sig.GetSign(); sign != nil {
bts := make([]byte, len(sign))
copy(bts, sign)
dst.sig.SetSign(sign)
} else {
dst.sig.SetSign(nil)
}
}
// reads commonData and custom context from the session.Token message.
// If checkFieldPresence is set, returns an error on absence of any protocol-required
// field. Verifies format of any presented field according to NeoFS API V2 protocol.
// Calls contextReader if session context is set. Passes checkFieldPresence into contextReader.
func (x *commonData) readFromV2(m session.Token, checkFieldPresence bool, r contextReader) error {
var err error
body := m.GetBody()
if checkFieldPresence && body == nil {
return errors.New("missing token body")
}
binID := body.GetID()
if x.idSet = len(binID) > 0; x.idSet {
err = x.id.UnmarshalBinary(binID)
if err != nil {
return fmt.Errorf("invalid session ID: %w", err)
} else if ver := x.id.Version(); ver != 4 {
return fmt.Errorf("invalid session UUID version %d", ver)
}
} else if checkFieldPresence {
return errors.New("missing session ID")
}
issuer := body.GetOwnerID()
if x.issuerSet = issuer != nil; x.issuerSet {
err = x.issuer.ReadFromV2(*issuer)
if err != nil {
return fmt.Errorf("invalid session issuer: %w", err)
}
} else if checkFieldPresence {
return errors.New("missing session issuer")
}
lifetime := body.GetLifetime()
if x.lifetimeSet = lifetime != nil; x.lifetimeSet {
x.iat = lifetime.GetIat()
x.nbf = lifetime.GetNbf()
x.exp = lifetime.GetExp()
} else if checkFieldPresence {
return errors.New("missing token lifetime")
}
x.authKey = body.GetSessionKey()
if checkFieldPresence && len(x.authKey) == 0 {
return errors.New("missing session public key")
}
c := body.GetContext()
if c != nil {
err = r(c, checkFieldPresence)
if err != nil {
return fmt.Errorf("invalid context: %w", err)
}
} else if checkFieldPresence {
return errors.New("missing session context")
}
sig := m.GetSignature()
if x.sigSet = sig != nil; sig != nil {
x.sig = *sig
} else if checkFieldPresence {
return errors.New("missing body signature")
}
return nil
}
type contextWriter func() session.TokenContext
func (x commonData) fillBody(w contextWriter) *session.TokenBody {
var body session.TokenBody
if x.idSet {
binID, err := x.id.MarshalBinary()
if err != nil {
panic(fmt.Sprintf("unexpected error from UUID.MarshalBinary: %v", err))
}
body.SetID(binID)
}
if x.issuerSet {
var issuer refs.OwnerID
x.issuer.WriteToV2(&issuer)
body.SetOwnerID(&issuer)
}
if x.lifetimeSet {
var lifetime session.TokenLifetime
lifetime.SetIat(x.iat)
lifetime.SetNbf(x.nbf)
lifetime.SetExp(x.exp)
body.SetLifetime(&lifetime)
}
body.SetSessionKey(x.authKey)
body.SetContext(w())
return &body
}
func (x commonData) writeToV2(m *session.Token, w contextWriter) {
body := x.fillBody(w)
m.SetBody(body)
var sig *refs.Signature
if x.sigSet {
sig = &x.sig
}
m.SetSignature(sig)
}
func (x commonData) signedData(w contextWriter) []byte {
return x.fillBody(w).StableMarshal(nil)
}
func (x *commonData) sign(signer user.Signer, w contextWriter) error {
if !x.issuerSet {
x.issuer = signer.UserID()
x.issuerSet = true
}
var sig neofscrypto.Signature
err := sig.Calculate(signer, x.signedData(w))
if err != nil {
return err
}
sig.WriteToV2(&x.sig)
x.sigSet = true
return nil
}
func (x commonData) verifySignature(w contextWriter) bool {
if !x.sigSet {
return false
}
var sig neofscrypto.Signature
// TODO: (#233) check owner<->key relation
return sig.ReadFromV2(x.sig) == nil && sig.Verify(x.signedData(w))
}
func (x commonData) marshal(w contextWriter) []byte {
var m session.Token
x.writeToV2(&m, w)
return m.StableMarshal(nil)
}
func (x *commonData) unmarshal(data []byte, r contextReader) error {
var m session.Token
err := m.Unmarshal(data)
if err != nil {
return err
}
return x.readFromV2(m, false, r)
}
func (x commonData) marshalJSON(w contextWriter) ([]byte, error) {
var m session.Token
x.writeToV2(&m, w)
return m.MarshalJSON()
}
func (x *commonData) unmarshalJSON(data []byte, r contextReader) error {
var m session.Token
err := m.UnmarshalJSON(data)
if err != nil {
return err
}
return x.readFromV2(m, false, r)
}
// SetExp sets "exp" (expiration time) claim which identifies the expiration
// time (in NeoFS epochs) after which the session MUST NOT be accepted for
// processing. The processing of the "exp" claim requires that the current
// epoch MUST be before or equal to the expiration epoch listed in the "exp"
// claim.
//
// Naming is inspired by https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4.
//
// See also ExpiredAt.
func (x *commonData) SetExp(exp uint64) {
x.exp = exp
x.lifetimeSet = true
}
// SetNbf sets "nbf" (not before) claim which identifies the time (in NeoFS
// epochs) before which the session MUST NOT be accepted for processing.
// The processing of the "nbf" claim requires that the current date/time MUST be
// after or equal to the not-before date/time listed in the "nbf" claim.
//
// Naming is inspired by https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5.
//
// See also InvalidAt.
func (x *commonData) SetNbf(nbf uint64) {
x.nbf = nbf
x.lifetimeSet = true
}
// SetIat sets "iat" (issued at) claim which identifies the time (in NeoFS
// epochs) at which the session was issued. This claim can be used to
// determine the age of the session.
//
// Naming is inspired by https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6.
//
// See also InvalidAt.
func (x *commonData) SetIat(iat uint64) {
x.iat = iat
x.lifetimeSet = true
}
func (x commonData) expiredAt(epoch uint64) bool {
return !x.lifetimeSet || x.exp < epoch
}
// InvalidAt asserts "exp", "nbf" and "iat" claims.
//
// Zero session is invalid in any epoch.
//
// See also SetExp, SetNbf, SetIat.
func (x commonData) InvalidAt(epoch uint64) bool {
return x.expiredAt(epoch) || x.nbf > epoch || x.iat > epoch
}
// SetID sets a unique identifier for the session. The identifier value MUST be
// assigned in a manner that ensures that there is a negligible probability
// that the same value will be accidentally assigned to a different session.
//
// ID format MUST be UUID version 4 (random). uuid.New can be used to generate
// a new ID. See https://datatracker.ietf.org/doc/html/rfc4122 and
// github.com/google/uuid package docs for details.
//
// See also ID.
func (x *commonData) SetID(id uuid.UUID) {
x.id = id
x.idSet = true
}
// ID returns a unique identifier for the session.
//
// Zero session has empty UUID (all zeros, see uuid.Nil) which is legitimate
// but most likely not suitable.
//
// See also SetID.
func (x commonData) ID() uuid.UUID {
if x.idSet {
return x.id
}
return uuid.Nil
}
// SetAuthKey public key corresponding to the private key bound to the session.
//
// See also AssertAuthKey.
func (x *commonData) SetAuthKey(key neofscrypto.PublicKey) {
x.authKey = neofscrypto.PublicKeyBytes(key)
}
// SetIssuer allows to set issuer before Sign call.
// Using this method is not required when Sign is used (issuer will be derived from the signer automatically).
// When using it please ensure that the token is signed with the same signer as the issuer passed here.
func (x *commonData) SetIssuer(id user.ID) {
x.issuer = id
x.issuerSet = true
}
// AssertAuthKey asserts public key bound to the session.
//
// Zero session fails the check.
//
// See also SetAuthKey.
func (x commonData) AssertAuthKey(key neofscrypto.PublicKey) bool {
return bytes.Equal(neofscrypto.PublicKeyBytes(key), x.authKey)
}
// Issuer returns user ID of the session issuer.
//
// Makes sense only for signed session instances. For unsigned instances,
// Issuer returns zero user.ID.
//
// See also Sign.
func (x commonData) Issuer() user.ID {
if x.issuerSet {
return x.issuer
}
return user.ID{}
}
// IssuerPublicKeyBytes returns binary-encoded public key of the session issuer.
//
// IssuerPublicKeyBytes MUST NOT be called before ReadFromV2 or Sign methods.
func (x *commonData) IssuerPublicKeyBytes() []byte {
if x.sigSet {
return x.sig.GetKey()
}
return nil
}