[#283] pkg/session: Implement Sign/Verify methods on Token

Implement `Token.Sign` method which calculates signature of the data of the
`Token` and writes the signature into it. Implement `Token.VerifySignature`
which checks if `Token` signature is presented and valid. These methods
allow to abstract the external context from the details of what kind of data
is being signed and how the signature is stored.

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2021-05-28 10:56:30 +03:00 committed by Leonard Lyubich
parent 5fe5af5bf9
commit 05e74d56db

View file

@ -1,9 +1,14 @@
package session package session
import ( import (
"crypto/ecdsa"
"github.com/nspcc-dev/neofs-api-go/pkg" "github.com/nspcc-dev/neofs-api-go/pkg"
"github.com/nspcc-dev/neofs-api-go/pkg/owner" "github.com/nspcc-dev/neofs-api-go/pkg/owner"
"github.com/nspcc-dev/neofs-api-go/util/signature"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
"github.com/nspcc-dev/neofs-api-go/v2/session" "github.com/nspcc-dev/neofs-api-go/v2/session"
v2signature "github.com/nspcc-dev/neofs-api-go/v2/signature"
) )
// Token represents NeoFS API v2-compatible // Token represents NeoFS API v2-compatible
@ -84,6 +89,44 @@ func (t *Token) SetSessionKey(v []byte) {
}) })
} }
// Sign calculates and writes signature of the Token data.
//
// Returns signature calculation errors.
func (t *Token) Sign(key *ecdsa.PrivateKey) error {
tV2 := (*session.SessionToken)(t)
signedData := v2signature.StableMarshalerWrapper{
SM: tV2.GetBody(),
}
return signature.SignDataWithHandler(key, signedData, func(key, sig []byte) {
tSig := tV2.GetSignature()
if tSig == nil {
tSig = new(refs.Signature)
}
tSig.SetKey(key)
tSig.SetSign(sig)
tV2.SetSignature(tSig)
})
}
// VerifySignature checks if token signature is
// presented and valid.
func (t *Token) VerifySignature() bool {
tV2 := (*session.SessionToken)(t)
signedData := v2signature.StableMarshalerWrapper{
SM: tV2.GetBody(),
}
return signature.VerifyDataWithSource(signedData, func() (key, sig []byte) {
tSig := tV2.GetSignature()
return tSig.GetKey(), tSig.GetSign()
}) == nil
}
// Signature returns Token signature. // Signature returns Token signature.
func (t *Token) Signature() *pkg.Signature { func (t *Token) Signature() *pkg.Signature {
return pkg.NewSignatureFromV2( return pkg.NewSignatureFromV2(