Replace signature package from neofs-api-go (#401)

close #219
This commit is contained in:
Roman Khimov 2023-04-26 17:17:12 +03:00 committed by GitHub
commit 28a3708b4e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
52 changed files with 1153 additions and 531 deletions

View file

@ -1,7 +1,6 @@
package bearer
import (
"crypto/ecdsa"
"errors"
"fmt"
@ -9,7 +8,6 @@ import (
"github.com/nspcc-dev/neofs-api-go/v2/refs"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/eacl"
"github.com/nspcc-dev/neofs-sdk-go/user"
)
@ -245,7 +243,7 @@ func (b Token) AssertUser(id user.ID) bool {
return !b.targetUserSet || b.targetUser.Equals(id)
}
// Sign calculates and writes signature of the Token data using issuer's secret.
// Sign calculates and writes signature of the Token data using issuer's signer.
// Returns signature calculation errors.
//
// Sign MUST be called if Token is going to be transmitted over
@ -255,10 +253,10 @@ func (b Token) AssertUser(id user.ID) bool {
// expected to be calculated as a final stage of Token formation.
//
// See also VerifySignature, Issuer.
func (b *Token) Sign(key ecdsa.PrivateKey) error {
func (b *Token) Sign(signer neofscrypto.Signer) error {
var sig neofscrypto.Signature
err := sig.Calculate(neofsecdsa.Signer(key), b.signedData())
err := sig.Calculate(signer, b.signedData())
if err != nil {
return err
}
@ -360,9 +358,8 @@ func ResolveIssuer(b Token) (usr user.ID) {
binKey := b.SigningKeyBytes()
if len(binKey) != 0 {
var key neofsecdsa.PublicKey
if key.Decode(binKey) == nil {
user.IDFromKey(&usr, ecdsa.PublicKey(key))
if err := user.IDFromKey(&usr, binKey); err != nil {
usr = user.ID{}
}
}

View file

@ -5,14 +5,13 @@ import (
"math/rand"
"testing"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neofs-api-go/v2/acl"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
"github.com/nspcc-dev/neofs-sdk-go/bearer"
bearertest "github.com/nspcc-dev/neofs-sdk-go/bearer/test"
cidtest "github.com/nspcc-dev/neofs-sdk-go/container/id/test"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/nspcc-dev/neofs-sdk-go/eacl"
eacltest "github.com/nspcc-dev/neofs-sdk-go/eacl/test"
"github.com/nspcc-dev/neofs-sdk-go/user"
@ -38,7 +37,7 @@ func isEqualEACLTables(t1, t2 eacl.Table) bool {
func TestToken_SetEACLTable(t *testing.T) {
var val bearer.Token
var m acl.BearerToken
filled := bearertest.Token()
filled := bearertest.Token(t)
val.WriteToV2(&m)
require.Zero(t, m.GetBody())
@ -58,7 +57,7 @@ func TestToken_SetEACLTable(t *testing.T) {
// set value
eaclTable := *eacltest.Table()
eaclTable := *eacltest.Table(t)
val.SetEACLTable(eaclTable)
require.True(t, isEqualEACLTables(eaclTable, val.EACLTable()))
@ -84,7 +83,7 @@ func TestToken_SetEACLTable(t *testing.T) {
func TestToken_ForUser(t *testing.T) {
var val bearer.Token
var m acl.BearerToken
filled := bearertest.Token()
filled := bearertest.Token(t)
val.WriteToV2(&m)
require.Zero(t, m.GetBody())
@ -107,7 +106,7 @@ func TestToken_ForUser(t *testing.T) {
require.Zero(t, m.GetBody())
// set value
usr := *usertest.ID()
usr := *usertest.ID(t)
var usrV2 refs.OwnerID
usr.WriteToV2(&usrV2)
@ -138,7 +137,7 @@ func TestToken_ForUser(t *testing.T) {
func testLifetimeClaim(t *testing.T, setter func(*bearer.Token, uint64), getter func(*acl.BearerToken) uint64) {
var val bearer.Token
var m acl.BearerToken
filled := bearertest.Token()
filled := bearertest.Token(t)
val.WriteToV2(&m)
require.Zero(t, m.GetBody())
@ -230,7 +229,7 @@ func TestToken_AssertContainer(t *testing.T) {
require.True(t, val.AssertContainer(cnr))
eaclTable := *eacltest.Table()
eaclTable := *eacltest.Table(t)
eaclTable.SetCID(cidtest.ID())
val.SetEACLTable(eaclTable)
@ -243,11 +242,11 @@ func TestToken_AssertContainer(t *testing.T) {
func TestToken_AssertUser(t *testing.T) {
var val bearer.Token
usr := *usertest.ID()
usr := *usertest.ID(t)
require.True(t, val.AssertUser(usr))
val.ForUser(*usertest.ID())
val.ForUser(*usertest.ID(t))
require.False(t, val.AssertUser(usr))
val.ForUser(usr)
@ -259,13 +258,11 @@ func TestToken_Sign(t *testing.T) {
require.False(t, val.VerifySignature())
k, err := keys.NewPrivateKey()
require.NoError(t, err)
signer := test.RandomSigner(t)
key := k.PrivateKey
val = bearertest.Token()
val = bearertest.Token(t)
require.NoError(t, val.Sign(key))
require.NoError(t, val.Sign(signer))
require.True(t, val.VerifySignature())
@ -275,7 +272,7 @@ func TestToken_Sign(t *testing.T) {
require.NotZero(t, m.GetSignature().GetKey())
require.NotZero(t, m.GetSignature().GetSign())
val2 := bearertest.Token()
val2 := bearertest.Token(t)
require.NoError(t, val2.Unmarshal(val.Marshal()))
require.True(t, val2.VerifySignature())
@ -283,7 +280,7 @@ func TestToken_Sign(t *testing.T) {
jd, err := val.MarshalJSON()
require.NoError(t, err)
val2 = bearertest.Token()
val2 = bearertest.Token(t)
require.NoError(t, val2.UnmarshalJSON(jd))
require.True(t, val2.VerifySignature())
}
@ -299,7 +296,7 @@ func TestToken_ReadFromV2(t *testing.T) {
require.Error(t, val.ReadFromV2(m))
eaclTable := eacltest.Table().ToV2()
eaclTable := eacltest.Table(t).ToV2()
body.SetEACL(eaclTable)
require.Error(t, val.ReadFromV2(m))
@ -328,7 +325,7 @@ func TestToken_ReadFromV2(t *testing.T) {
val.WriteToV2(&m2)
require.Equal(t, m, m2)
usr, usr2 := *usertest.ID(), *usertest.ID()
usr, usr2 := *usertest.ID(t), *usertest.ID(t)
require.True(t, val.AssertUser(usr))
require.True(t, val.AssertUser(usr2))
@ -346,10 +343,7 @@ func TestToken_ReadFromV2(t *testing.T) {
require.True(t, val.AssertUser(usr))
require.False(t, val.AssertUser(usr2))
k, err := keys.NewPrivateKey()
require.NoError(t, err)
signer := neofsecdsa.Signer(k.PrivateKey)
signer := test.RandomSigner(t)
var s neofscrypto.Signature
@ -363,8 +357,7 @@ func TestToken_ReadFromV2(t *testing.T) {
}
func TestResolveIssuer(t *testing.T) {
k, err := keys.NewPrivateKey()
require.NoError(t, err)
signer := test.RandomSigner(t)
var val bearer.Token
@ -381,10 +374,10 @@ func TestResolveIssuer(t *testing.T) {
require.Zero(t, bearer.ResolveIssuer(val))
require.NoError(t, val.Sign(k.PrivateKey))
require.NoError(t, val.Sign(signer))
var usr user.ID
user.IDFromKey(&usr, k.PrivateKey.PublicKey)
require.NoError(t, user.IDFromSigner(&usr, signer))
require.Equal(t, usr, bearer.ResolveIssuer(val))
}

View file

@ -1,6 +1,8 @@
package bearertest
import (
"testing"
"github.com/nspcc-dev/neofs-sdk-go/bearer"
eacltest "github.com/nspcc-dev/neofs-sdk-go/eacl/test"
usertest "github.com/nspcc-dev/neofs-sdk-go/user/test"
@ -9,12 +11,12 @@ import (
// Token returns random bearer.Token.
//
// Resulting token is unsigned.
func Token() (t bearer.Token) {
t.SetExp(3)
t.SetNbf(2)
t.SetIat(1)
t.ForUser(*usertest.ID())
t.SetEACLTable(*eacltest.Table())
func Token(t testing.TB) (tok bearer.Token) {
tok.SetExp(3)
tok.SetNbf(2)
tok.SetIat(1)
tok.ForUser(*usertest.ID(t))
tok.SetEACLTable(*eacltest.Table(t))
return t
return tok
}

View file

@ -2,7 +2,6 @@ package client
import (
"context"
"crypto/ecdsa"
"crypto/tls"
"errors"
"time"
@ -10,6 +9,7 @@ import (
v2accounting "github.com/nspcc-dev/neofs-api-go/v2/accounting"
"github.com/nspcc-dev/neofs-api-go/v2/rpc"
"github.com/nspcc-dev/neofs-api-go/v2/rpc/client"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
)
// Client represents virtual connection to the NeoFS network to communicate
@ -148,19 +148,19 @@ func (c *Client) Close() error {
type PrmInit struct {
resolveNeoFSErrors bool
key ecdsa.PrivateKey
signer neofscrypto.Signer
cbRespInfo func(ResponseMetaInfo) error
netMagic uint64
}
// SetDefaultPrivateKey sets Client private key to be used for the protocol
// SetDefaultSigner sets Client private signer to be used for the protocol
// communication by default.
//
// Required for operations without custom key parametrization (see corresponding Prm* docs).
func (x *PrmInit) SetDefaultPrivateKey(key ecdsa.PrivateKey) {
x.key = key
// Required for operations without custom signer parametrization (see corresponding Prm* docs).
func (x *PrmInit) SetDefaultSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// ResolveNeoFSFailures makes the Client to resolve failure statuses of the

View file

@ -2,12 +2,10 @@ package client
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"testing"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/stretchr/testify/require"
)
@ -15,8 +13,6 @@ import (
File contains common functionality used for client package testing.
*/
var key, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
var statusErr apistatus.ServerInternal
func init() {
@ -28,9 +24,9 @@ func assertStatusErr(tb testing.TB, res interface{ Status() apistatus.Status })
require.Equal(tb, statusErr.Message(), res.Status().(*apistatus.ServerInternal).Message())
}
func newClient(server neoFSAPIServer) *Client {
func newClient(signer neofscrypto.Signer, server neoFSAPIServer) *Client {
var prm PrmInit
prm.SetDefaultPrivateKey(*key)
prm.SetDefaultSigner(signer)
var c Client
c.Init(prm)

View file

@ -1,14 +1,13 @@
package client
import (
"crypto/ecdsa"
"fmt"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
"github.com/nspcc-dev/neofs-api-go/v2/rpc/client"
v2session "github.com/nspcc-dev/neofs-api-go/v2/session"
"github.com/nspcc-dev/neofs-api-go/v2/signature"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/nspcc-dev/neofs-sdk-go/version"
)
@ -75,6 +74,7 @@ const (
panicMsgMissingContext = "missing context"
panicMsgMissingContainer = "missing container"
panicMsgMissingObject = "missing object"
panicMsgOwnerExtract = "extract owner failed"
)
// groups all the details required to send a single request and process a response to it.
@ -91,8 +91,8 @@ type contextCall struct {
// ==================================================
// shared parameters which are set uniformly on all calls
// request signing key
key ecdsa.PrivateKey
// request signer
signer neofscrypto.Signer
// callback prior to processing the response by the client
callbackResp func(ResponseMetaInfo) error
@ -112,7 +112,7 @@ type contextCall struct {
// structure of the call result
statusRes resCommon
// request to be signed with a key and sent
// request to be signed with a signer and sent
req request
// function to send a request (unary) and receive a response
@ -187,7 +187,7 @@ func (x *contextCall) writeRequest() bool {
x.req.SetVerificationHeader(nil)
// sign the request
x.err = signature.SignServiceMessage(&x.key, x.req)
x.err = signServiceMessage(x.signer, x.req)
if x.err != nil {
x.err = fmt.Errorf("sign request: %w", x.err)
return false
@ -226,7 +226,7 @@ func (x *contextCall) processResponse() bool {
// while verification needs marshaling
// verify response signature
x.err = signature.VerifyServiceMessage(x.resp)
x.err = verifyServiceMessage(x.resp)
if x.err != nil {
x.err = fmt.Errorf("invalid response signature: %w", x.err)
return false
@ -250,7 +250,7 @@ func (x *contextCall) processResponse() bool {
// processResponse verifies response signature and converts status to an error if needed.
func (c *Client) processResponse(resp responseV2) (apistatus.Status, error) {
err := signature.VerifyServiceMessage(resp)
err := verifyServiceMessage(resp)
if err != nil {
return nil, fmt.Errorf("invalid response signature: %w", err)
}
@ -328,7 +328,7 @@ func (x *contextCall) processCall() bool {
// initializes static cross-call parameters inherited from client.
func (c *Client) initCallContext(ctx *contextCall) {
ctx.key = c.prm.key
ctx.signer = c.prm.signer
ctx.resolveAPIFailures = c.prm.resolveNeoFSErrors
ctx.callbackResp = c.prm.cbRespInfo
ctx.netMagic = c.prm.netMagic

View file

@ -13,7 +13,6 @@ import (
"github.com/nspcc-dev/neofs-sdk-go/container"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/eacl"
"github.com/nspcc-dev/neofs-sdk-go/session"
"github.com/nspcc-dev/neofs-sdk-go/user"
@ -53,7 +52,7 @@ func (x *PrmContainerPut) SetSigner(signer neofscrypto.Signer) {
//
// Session is optional, if set the following requirements apply:
// - session operation MUST be session.VerbContainerPut (ForVerb)
// - token MUST be signed using private key of the owner of the container to be saved
// - token MUST be signed using private signer of the owner of the container to be saved
func (x *PrmContainerPut) WithinSession(s session.Container) {
x.session = s
x.sessionSet = true
@ -74,7 +73,7 @@ func (x ResContainerPut) ID() cid.ID {
}
func (c *Client) defaultSigner() neofscrypto.Signer {
return neofsecdsa.SignerRFC6979(c.prm.key)
return c.prm.signer
}
// ContainerPut sends request to save container in NeoFS.
@ -104,7 +103,7 @@ func (c *Client) ContainerPut(ctx context.Context, prm PrmContainerPut) (*ResCon
panic(panicMsgMissingContainer)
}
// TODO: check private key is set before forming the request
// TODO: check private signer is set before forming the request
// sign container
var cnr v2container.Container
prm.cnr.WriteToV2(&cnr)
@ -657,7 +656,7 @@ func (x *PrmContainerSetEACL) SetSigner(signer neofscrypto.Signer) {
// - if particular container is specified (ApplyOnlyTo), it MUST equal the container
// for which extended ACL is going to be set
// - session operation MUST be session.VerbContainerSetEACL (ForVerb)
// - token MUST be signed using private key of the owner of the container to be saved
// - token MUST be signed using private signer of the owner of the container to be saved
func (x *PrmContainerSetEACL) WithinSession(s session.Container) {
x.session = s
x.sessionSet = true

View file

@ -11,7 +11,7 @@ Create client instance:
Initialize client state:
var prm client.PrmInit
prm.SetDefaultPrivateKey(key)
prm.SetDefaultSigner(signer)
// ...
c.Init(prm)
@ -20,7 +20,7 @@ Connect to the NeoFS server:
var prm client.PrmDial
prm.SetServerURI("localhost:8080")
prm.SetDefaultPrivateKey(key)
prm.SetDefaultSigner(signer)
// ...
err := c.Dial(prm)

View file

@ -11,6 +11,7 @@ import (
"github.com/nspcc-dev/neofs-sdk-go/container"
"github.com/nspcc-dev/neofs-sdk-go/container/acl"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/netmap"
"github.com/nspcc-dev/neofs-sdk-go/user"
)
@ -25,12 +26,16 @@ func ExampleClient_ContainerPut() {
panic(err)
}
// decode account from user's key
user.IDFromKey(&accountID, key.PrivateKey.PublicKey)
signer := neofsecdsa.SignerRFC6979(key.PrivateKey)
// decode account from user's signer
if err = user.IDFromSigner(&accountID, signer); err != nil {
panic(err)
}
// prepare client
var prmInit client.PrmInit
prmInit.SetDefaultPrivateKey(key.PrivateKey) // private key for request signing
prmInit.SetDefaultSigner(signer) // private signer for request signing
prmInit.ResolveNeoFSFailures() // enable erroneous status parsing
var c client.Client

View file

@ -8,7 +8,6 @@ import (
rpcapi "github.com/nspcc-dev/neofs-api-go/v2/rpc"
"github.com/nspcc-dev/neofs-api-go/v2/rpc/client"
v2session "github.com/nspcc-dev/neofs-api-go/v2/session"
"github.com/nspcc-dev/neofs-api-go/v2/signature"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
"github.com/nspcc-dev/neofs-sdk-go/netmap"
"github.com/nspcc-dev/neofs-sdk-go/version"
@ -248,7 +247,7 @@ func (c *Client) NetMapSnapshot(ctx context.Context, _ PrmNetMapSnapshot) (*ResN
req.SetBody(&body)
c.prepareRequest(&req, &meta)
err := signature.SignServiceMessage(&c.prm.key, &req)
err := signServiceMessage(c.prm.signer, &req)
if err != nil {
return nil, fmt.Errorf("sign request: %w", err)
}

View file

@ -8,8 +8,9 @@ import (
v2netmap "github.com/nspcc-dev/neofs-api-go/v2/netmap"
"github.com/nspcc-dev/neofs-api-go/v2/session"
"github.com/nspcc-dev/neofs-api-go/v2/signature"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/nspcc-dev/neofs-sdk-go/netmap"
"github.com/stretchr/testify/require"
)
@ -23,10 +24,12 @@ type serverNetMap struct {
setNetMap bool
netMap v2netmap.NetMap
signer neofscrypto.Signer
}
func (x *serverNetMap) netMapSnapshot(ctx context.Context, req v2netmap.SnapshotRequest) (*v2netmap.SnapshotResponse, error) {
err := signature.VerifyServiceMessage(&req)
err := verifyServiceMessage(&req)
if err != nil {
return nil, err
}
@ -52,7 +55,7 @@ func (x *serverNetMap) netMapSnapshot(ctx context.Context, req v2netmap.Snapshot
resp.SetMetaHeader(&meta)
if x.signResponse {
err = signature.SignServiceMessage(key, &resp)
err = signServiceMessage(x.signer, &resp)
if err != nil {
panic(fmt.Sprintf("sign response: %v", err))
}
@ -66,7 +69,12 @@ func TestClient_NetMapSnapshot(t *testing.T) {
var prm PrmNetMapSnapshot
var res *ResNetMapSnapshot
var srv serverNetMap
c := newClient(&srv)
signer := test.RandomSignerRFC6979(t)
srv.signer = signer
c := newClient(signer, &srv)
ctx := context.Background()
// missing context

View file

@ -2,7 +2,6 @@ package client
import (
"context"
"crypto/ecdsa"
"fmt"
"github.com/nspcc-dev/neofs-api-go/v2/acl"
@ -11,10 +10,10 @@ import (
rpcapi "github.com/nspcc-dev/neofs-api-go/v2/rpc"
"github.com/nspcc-dev/neofs-api-go/v2/rpc/client"
v2session "github.com/nspcc-dev/neofs-api-go/v2/session"
"github.com/nspcc-dev/neofs-api-go/v2/signature"
"github.com/nspcc-dev/neofs-sdk-go/bearer"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
"github.com/nspcc-dev/neofs-sdk-go/session"
)
@ -28,7 +27,7 @@ type PrmObjectDelete struct {
addr v2refs.Address
keySet bool
key ecdsa.PrivateKey
signer neofscrypto.Signer
}
// WithinSession specifies session within which object should be read.
@ -73,11 +72,11 @@ func (x *PrmObjectDelete) ByID(id oid.ID) {
x.addr.SetObjectID(&idV2)
}
// UseKey specifies private key to sign the requests.
// If key is not provided, then Client default key is used.
func (x *PrmObjectDelete) UseKey(key ecdsa.PrivateKey) {
// UseSigner specifies private signer to sign the requests.
// If signer is not provided, then Client default signer is used.
func (x *PrmObjectDelete) UseSigner(signer neofscrypto.Signer) {
x.keySet = true
x.key = key
x.signer = signer
}
// WithXHeaders specifies list of extended headers (string key-value pairs)
@ -141,12 +140,12 @@ func (c *Client) ObjectDelete(ctx context.Context, prm PrmObjectDelete) (*ResObj
req.SetBody(&prm.body)
c.prepareRequest(&req, &prm.meta)
key := c.prm.key
if prm.keySet {
key = prm.key
signer := prm.signer
if signer == nil {
signer = c.prm.signer
}
err := signature.SignServiceMessage(&key, &req)
err := signServiceMessage(signer, &req)
if err != nil {
return nil, fmt.Errorf("sign request: %w", err)
}

View file

@ -2,7 +2,6 @@ package client
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"io"
@ -13,10 +12,10 @@ import (
rpcapi "github.com/nspcc-dev/neofs-api-go/v2/rpc"
"github.com/nspcc-dev/neofs-api-go/v2/rpc/client"
v2session "github.com/nspcc-dev/neofs-api-go/v2/session"
"github.com/nspcc-dev/neofs-api-go/v2/signature"
"github.com/nspcc-dev/neofs-sdk-go/bearer"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/nspcc-dev/neofs-sdk-go/object"
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
"github.com/nspcc-dev/neofs-sdk-go/session"
@ -92,7 +91,7 @@ func (x *prmObjectRead) ByID(id oid.ID) {
type PrmObjectGet struct {
prmObjectRead
key *ecdsa.PrivateKey
signer neofscrypto.Signer
}
// ResObjectGet groups the final result values of ObjectGetInit operation.
@ -120,10 +119,10 @@ type ObjectReader struct {
remainingPayloadLen int
}
// UseKey specifies private key to sign the requests.
// If key is not provided, then Client default key is used.
func (x *PrmObjectGet) UseKey(key ecdsa.PrivateKey) {
x.key = &key
// UseSigner specifies private signer to sign the requests.
// If signer is not provided, then Client default signer is used.
func (x *PrmObjectGet) UseSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// ReadHeader reads header of the object. Result means success.
@ -321,12 +320,12 @@ func (c *Client) ObjectGetInit(ctx context.Context, prm PrmObjectGet) (*ObjectRe
req.SetBody(&body)
c.prepareRequest(&req, &prm.meta)
key := prm.key
if key == nil {
key = &c.prm.key
signer := prm.signer
if signer == nil {
signer = c.prm.signer
}
err := signature.SignServiceMessage(key, &req)
err := signServiceMessage(signer, &req)
if err != nil {
return nil, fmt.Errorf("sign request: %w", err)
}
@ -351,15 +350,13 @@ func (c *Client) ObjectGetInit(ctx context.Context, prm PrmObjectGet) (*ObjectRe
type PrmObjectHead struct {
prmObjectRead
keySet bool
key ecdsa.PrivateKey
signer neofscrypto.Signer
}
// UseKey specifies private key to sign the requests.
// If key is not provided, then Client default key is used.
func (x *PrmObjectHead) UseKey(key ecdsa.PrivateKey) {
x.keySet = true
x.key = key
// UseSigner specifies private signer to sign the requests.
// If signer is not provided, then Client default signer is used.
func (x *PrmObjectHead) UseSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// ResObjectHead groups resulting values of ObjectHead operation.
@ -432,13 +429,13 @@ func (c *Client) ObjectHead(ctx context.Context, prm PrmObjectHead) (*ResObjectH
req.SetBody(&body)
c.prepareRequest(&req, &prm.meta)
key := c.prm.key
if prm.keySet {
key = prm.key
signer := prm.signer
if signer == nil {
signer = c.prm.signer
}
// sign the request
err := signature.SignServiceMessage(&key, &req)
err := signServiceMessage(signer, &req)
if err != nil {
return nil, fmt.Errorf("sign request: %w", err)
}
@ -476,7 +473,7 @@ func (c *Client) ObjectHead(ctx context.Context, prm PrmObjectHead) (*ResObjectH
type PrmObjectRange struct {
prmObjectRead
key *ecdsa.PrivateKey
signer neofscrypto.Signer
rng v2object.Range
}
@ -493,10 +490,10 @@ func (x *PrmObjectRange) SetLength(ln uint64) {
x.rng.SetLength(ln)
}
// UseKey specifies private key to sign the requests.
// If key is not provided, then Client default key is used.
func (x *PrmObjectRange) UseKey(key ecdsa.PrivateKey) {
x.key = &key
// UseSigner specifies private signer to sign the requests.
// If signer is not provided, then Client default signer is used.
func (x *PrmObjectRange) UseSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// ResObjectRange groups the final result values of ObjectRange operation.
@ -691,12 +688,12 @@ func (c *Client) ObjectRangeInit(ctx context.Context, prm PrmObjectRange) (*Obje
req.SetBody(&body)
c.prepareRequest(&req, &prm.meta)
key := prm.key
if key == nil {
key = &c.prm.key
signer := prm.signer
if signer == nil {
signer = c.prm.signer
}
err := signature.SignServiceMessage(key, &req)
err := signServiceMessage(signer, &req)
if err != nil {
return nil, fmt.Errorf("sign request: %w", err)
}

View file

@ -2,7 +2,6 @@ package client
import (
"context"
"crypto/ecdsa"
"fmt"
"github.com/nspcc-dev/neofs-api-go/v2/acl"
@ -11,10 +10,10 @@ import (
rpcapi "github.com/nspcc-dev/neofs-api-go/v2/rpc"
"github.com/nspcc-dev/neofs-api-go/v2/rpc/client"
v2session "github.com/nspcc-dev/neofs-api-go/v2/session"
"github.com/nspcc-dev/neofs-api-go/v2/signature"
"github.com/nspcc-dev/neofs-sdk-go/bearer"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
"github.com/nspcc-dev/neofs-sdk-go/session"
)
@ -29,15 +28,13 @@ type PrmObjectHash struct {
addr v2refs.Address
keySet bool
key ecdsa.PrivateKey
signer neofscrypto.Signer
}
// UseKey specifies private key to sign the requests.
// If key is not provided, then Client default key is used.
func (x *PrmObjectHash) UseKey(key ecdsa.PrivateKey) {
x.keySet = true
x.key = key
// UseSigner specifies private signer to sign the requests.
// If signer is not provided, then Client default signer is used.
func (x *PrmObjectHash) UseSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// MarkLocal tells the server to execute the operation locally.
@ -187,12 +184,12 @@ func (c *Client) ObjectHash(ctx context.Context, prm PrmObjectHash) (*ResObjectH
c.prepareRequest(&req, &prm.meta)
req.SetBody(&prm.body)
key := c.prm.key
if prm.keySet {
key = prm.key
signer := prm.signer
if signer == nil {
signer = c.prm.signer
}
err := signature.SignServiceMessage(&key, &req)
err := signServiceMessage(signer, &req)
if err != nil {
return nil, fmt.Errorf("sign request: %w", err)
}

View file

@ -2,7 +2,6 @@ package client
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"io"
@ -12,9 +11,9 @@ import (
rpcapi "github.com/nspcc-dev/neofs-api-go/v2/rpc"
"github.com/nspcc-dev/neofs-api-go/v2/rpc/client"
v2session "github.com/nspcc-dev/neofs-api-go/v2/session"
"github.com/nspcc-dev/neofs-api-go/v2/signature"
"github.com/nspcc-dev/neofs-sdk-go/bearer"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/nspcc-dev/neofs-sdk-go/object"
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
"github.com/nspcc-dev/neofs-sdk-go/session"
@ -23,7 +22,7 @@ import (
// PrmObjectPutInit groups parameters of ObjectPutInit operation.
type PrmObjectPutInit struct {
copyNum uint32
key *ecdsa.PrivateKey
signer neofscrypto.Signer
meta v2session.RequestMetaHeader
}
@ -57,7 +56,7 @@ type ObjectWriter struct {
Close() error
}
key *ecdsa.PrivateKey
signer neofscrypto.Signer
res ResObjectPut
err error
@ -69,10 +68,10 @@ type ObjectWriter struct {
partChunk v2object.PutObjectPartChunk
}
// UseKey specifies private key to sign the requests.
// If key is not provided, then Client default key is used.
func (x *PrmObjectPutInit) UseKey(key ecdsa.PrivateKey) {
x.key = &key
// UseSigner specifies private signer to sign the requests.
// If signer is not provided, then Client default signer is used.
func (x *PrmObjectPutInit) UseSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// WithBearerToken attaches bearer token to be used for the operation.
@ -117,7 +116,7 @@ func (x *ObjectWriter) WriteHeader(hdr object.Object) bool {
x.req.GetBody().SetObjectPart(&x.partInit)
x.req.SetVerificationHeader(nil)
x.err = signature.SignServiceMessage(x.key, &x.req)
x.err = signServiceMessage(x.signer, &x.req)
if x.err != nil {
x.err = fmt.Errorf("sign message: %w", x.err)
return false
@ -159,7 +158,7 @@ func (x *ObjectWriter) WritePayloadChunk(chunk []byte) bool {
x.partChunk.SetChunk(chunk[:ln])
x.req.SetVerificationHeader(nil)
x.err = signature.SignServiceMessage(x.key, &x.req)
x.err = signServiceMessage(x.signer, &x.req)
if x.err != nil {
x.err = fmt.Errorf("sign message: %w", x.err)
return false
@ -251,9 +250,9 @@ func (c *Client) ObjectPutInit(ctx context.Context, prm PrmObjectPutInit) (*Obje
return nil, fmt.Errorf("open stream: %w", err)
}
w.key = &c.prm.key
if prm.key != nil {
w.key = prm.key
w.signer = prm.signer
if w.signer == nil {
w.signer = c.prm.signer
}
w.cancelCtxStream = cancel
w.client = c

View file

@ -2,7 +2,6 @@ package client
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"io"
@ -13,10 +12,10 @@ import (
rpcapi "github.com/nspcc-dev/neofs-api-go/v2/rpc"
"github.com/nspcc-dev/neofs-api-go/v2/rpc/client"
v2session "github.com/nspcc-dev/neofs-api-go/v2/session"
"github.com/nspcc-dev/neofs-api-go/v2/signature"
"github.com/nspcc-dev/neofs-sdk-go/bearer"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/nspcc-dev/neofs-sdk-go/object"
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
"github.com/nspcc-dev/neofs-sdk-go/session"
@ -26,7 +25,7 @@ import (
type PrmObjectSearch struct {
meta v2session.RequestMetaHeader
key *ecdsa.PrivateKey
signer neofscrypto.Signer
cnrSet bool
cnrID cid.ID
@ -70,10 +69,10 @@ func (x *PrmObjectSearch) WithXHeaders(hs ...string) {
writeXHeadersToMeta(hs, &x.meta)
}
// UseKey specifies private key to sign the requests.
// If key is not provided, then Client default key is used.
func (x *PrmObjectSearch) UseKey(key ecdsa.PrivateKey) {
x.key = &key
// UseSigner specifies private signer to sign the requests.
// If signer is not provided, then Client default signer is used.
func (x *PrmObjectSearch) UseSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// InContainer specifies the container in which to look for objects.
@ -242,12 +241,12 @@ func (c *Client) ObjectSearchInit(ctx context.Context, prm PrmObjectSearch) (*Ob
req.SetBody(&body)
c.prepareRequest(&req, &prm.meta)
key := prm.key
if key == nil {
key = &c.prm.key
signer := prm.signer
if signer == nil {
signer = c.prm.signer
}
err := signature.SignServiceMessage(key, &req)
err := signServiceMessage(signer, &req)
if err != nil {
return nil, fmt.Errorf("sign request: %w", err)
}

View file

@ -1,16 +1,15 @@
package client
import (
"crypto/ecdsa"
"errors"
"fmt"
"io"
"testing"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
v2object "github.com/nspcc-dev/neofs-api-go/v2/object"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
signatureV2 "github.com/nspcc-dev/neofs-api-go/v2/signature"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
oidtest "github.com/nspcc-dev/neofs-sdk-go/object/id/test"
"github.com/stretchr/testify/require"
@ -86,7 +85,7 @@ func TestObjectIterate(t *testing.T) {
p, resp := testListReaderResponse(t)
var actual []oid.ID
resp.stream = &singleStreamResponder{key: p, idList: [][]oid.ID{ids}}
resp.stream = &singleStreamResponder{signer: p, idList: [][]oid.ID{ids}}
require.NoError(t, resp.Iterate(func(id oid.ID) bool {
actual = append(actual, id)
return len(actual) == 2
@ -109,27 +108,24 @@ func TestObjectIterate(t *testing.T) {
})
}
func testListReaderResponse(t *testing.T) (*ecdsa.PrivateKey, *ObjectListReader) {
p, err := keys.NewPrivateKey()
require.NoError(t, err)
return &p.PrivateKey, &ObjectListReader{
func testListReaderResponse(t *testing.T) (neofscrypto.Signer, *ObjectListReader) {
return test.RandomSigner(t), &ObjectListReader{
cancelCtxStream: func() {},
client: &Client{},
tail: nil,
}
}
func newSearchStream(key *ecdsa.PrivateKey, endError error, idList ...[]oid.ID) *singleStreamResponder {
func newSearchStream(signer neofscrypto.Signer, endError error, idList ...[]oid.ID) *singleStreamResponder {
return &singleStreamResponder{
key: key,
signer: signer,
endError: endError,
idList: idList,
}
}
type singleStreamResponder struct {
key *ecdsa.PrivateKey
signer neofscrypto.Signer
n int
endError error
idList [][]oid.ID
@ -154,7 +150,7 @@ func (s *singleStreamResponder) Read(resp *v2object.SearchResponse) error {
}
resp.SetBody(&body)
err := signatureV2.SignServiceMessage(s.key, resp)
err := signServiceMessage(s.signer, resp)
if err != nil {
panic(fmt.Errorf("error: %w", err))
}

View file

@ -2,12 +2,12 @@ package client
import (
"context"
"crypto/ecdsa"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
rpcapi "github.com/nspcc-dev/neofs-api-go/v2/rpc"
"github.com/nspcc-dev/neofs-api-go/v2/rpc/client"
v2session "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"
)
@ -17,8 +17,7 @@ type PrmSessionCreate struct {
exp uint64
keySet bool
key ecdsa.PrivateKey
signer neofscrypto.Signer
}
// SetExp sets number of the last NepFS epoch in the lifetime of the session after which it will be expired.
@ -26,11 +25,10 @@ func (x *PrmSessionCreate) SetExp(exp uint64) {
x.exp = exp
}
// UseKey specifies private key to sign the requests and compute token owner.
// If key is not provided, then Client default key is used.
func (x *PrmSessionCreate) UseKey(key ecdsa.PrivateKey) {
x.keySet = true
x.key = key
// UseSigner specifies private signer to sign the requests and compute token owner.
// If signer is not provided, then Client default signer is used.
func (x *PrmSessionCreate) UseSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// ResSessionCreate groups resulting values of SessionCreate operation.
@ -83,12 +81,10 @@ func (c *Client) SessionCreate(ctx context.Context, prm PrmSessionCreate) (*ResS
panic(panicMsgMissingContext)
}
ownerKey := c.prm.key.PublicKey
if prm.keySet {
ownerKey = prm.key.PublicKey
}
var ownerID user.ID
user.IDFromKey(&ownerID, ownerKey)
if err := user.IDFromSigner(&ownerID, prm.signer); err != nil {
panic(panicMsgOwnerExtract)
}
var ownerIDV2 refs.OwnerID
ownerID.WriteToV2(&ownerIDV2)
@ -111,8 +107,9 @@ func (c *Client) SessionCreate(ctx context.Context, prm PrmSessionCreate) (*ResS
)
c.initCallContext(&cc)
if prm.keySet {
cc.key = prm.key
cc.signer = prm.signer
if cc.signer == nil {
cc.signer = c.prm.signer
}
cc.meta = prm.prmCommonMeta

394
client/sign.go Normal file
View file

@ -0,0 +1,394 @@
package client
import (
"errors"
"fmt"
"github.com/nspcc-dev/neofs-api-go/v2/accounting"
"github.com/nspcc-dev/neofs-api-go/v2/container"
"github.com/nspcc-dev/neofs-api-go/v2/netmap"
"github.com/nspcc-dev/neofs-api-go/v2/object"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
"github.com/nspcc-dev/neofs-api-go/v2/reputation"
"github.com/nspcc-dev/neofs-api-go/v2/session"
"github.com/nspcc-dev/neofs-api-go/v2/util/signature"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
)
type serviceRequest interface {
GetMetaHeader() *session.RequestMetaHeader
GetVerificationHeader() *session.RequestVerificationHeader
SetVerificationHeader(*session.RequestVerificationHeader)
}
type serviceResponse interface {
GetMetaHeader() *session.ResponseMetaHeader
GetVerificationHeader() *session.ResponseVerificationHeader
SetVerificationHeader(*session.ResponseVerificationHeader)
}
type stableMarshaler interface {
StableMarshal([]byte) []byte
StableSize() int
}
type stableMarshalerWrapper struct {
SM stableMarshaler
}
type metaHeader interface {
stableMarshaler
getOrigin() metaHeader
}
type verificationHeader interface {
stableMarshaler
GetBodySignature() *refs.Signature
SetBodySignature(*refs.Signature)
GetMetaSignature() *refs.Signature
SetMetaSignature(*refs.Signature)
GetOriginSignature() *refs.Signature
SetOriginSignature(*refs.Signature)
setOrigin(stableMarshaler)
getOrigin() verificationHeader
}
type requestMetaHeader struct {
*session.RequestMetaHeader
}
type responseMetaHeader struct {
*session.ResponseMetaHeader
}
type requestVerificationHeader struct {
*session.RequestVerificationHeader
}
type responseVerificationHeader struct {
*session.ResponseVerificationHeader
}
func (h *requestMetaHeader) getOrigin() metaHeader {
return &requestMetaHeader{
RequestMetaHeader: h.GetOrigin(),
}
}
func (h *responseMetaHeader) getOrigin() metaHeader {
return &responseMetaHeader{
ResponseMetaHeader: h.GetOrigin(),
}
}
func (h *requestVerificationHeader) getOrigin() verificationHeader {
if origin := h.GetOrigin(); origin != nil {
return &requestVerificationHeader{
RequestVerificationHeader: origin,
}
}
return nil
}
func (h *requestVerificationHeader) setOrigin(m stableMarshaler) {
if m != nil {
h.SetOrigin(m.(*session.RequestVerificationHeader))
}
}
func (r *responseVerificationHeader) getOrigin() verificationHeader {
if origin := r.GetOrigin(); origin != nil {
return &responseVerificationHeader{
ResponseVerificationHeader: origin,
}
}
return nil
}
func (r *responseVerificationHeader) setOrigin(m stableMarshaler) {
if m != nil {
r.SetOrigin(m.(*session.ResponseVerificationHeader))
}
}
func (s stableMarshalerWrapper) ReadSignedData(buf []byte) ([]byte, error) {
if s.SM != nil {
return s.SM.StableMarshal(buf), nil
}
return nil, nil
}
func (s stableMarshalerWrapper) SignedDataSize() int {
if s.SM != nil {
return s.SM.StableSize()
}
return 0
}
// signServiceMessage signing request or response messages which can be sent or received from neofs endpoint.
func signServiceMessage(signer neofscrypto.Signer, msg interface{}) error {
var (
body, meta, verifyOrigin stableMarshaler
verifyHdr verificationHeader
verifyHdrSetter func(verificationHeader)
)
switch v := msg.(type) {
case nil:
return nil
case serviceRequest:
body = serviceMessageBody(v)
meta = v.GetMetaHeader()
verifyHdr = &requestVerificationHeader{new(session.RequestVerificationHeader)}
verifyHdrSetter = func(h verificationHeader) {
v.SetVerificationHeader(h.(*requestVerificationHeader).RequestVerificationHeader)
}
if h := v.GetVerificationHeader(); h != nil {
verifyOrigin = h
}
case serviceResponse:
body = serviceMessageBody(v)
meta = v.GetMetaHeader()
verifyHdr = &responseVerificationHeader{new(session.ResponseVerificationHeader)}
verifyHdrSetter = func(h verificationHeader) {
v.SetVerificationHeader(h.(*responseVerificationHeader).ResponseVerificationHeader)
}
if h := v.GetVerificationHeader(); h != nil {
verifyOrigin = h
}
default:
panic(fmt.Sprintf("unsupported session message %T", v))
}
if verifyOrigin == nil {
// sign session message body
if err := signServiceMessagePart(signer, body, verifyHdr.SetBodySignature); err != nil {
return fmt.Errorf("could not sign body: %w", err)
}
}
// sign meta header
if err := signServiceMessagePart(signer, meta, verifyHdr.SetMetaSignature); err != nil {
return fmt.Errorf("could not sign meta header: %w", err)
}
// sign verification header origin
if err := signServiceMessagePart(signer, verifyOrigin, verifyHdr.SetOriginSignature); err != nil {
return fmt.Errorf("could not sign origin of verification header: %w", err)
}
// wrap origin verification header
verifyHdr.setOrigin(verifyOrigin)
// update matryoshka verification header
verifyHdrSetter(verifyHdr)
return nil
}
func signServiceMessagePart(signer neofscrypto.Signer, part stableMarshaler, sigWrite func(*refs.Signature)) error {
var sig neofscrypto.Signature
var sigv2 refs.Signature
m := &stableMarshalerWrapper{part}
data, err := m.ReadSignedData(nil)
if err != nil {
return fmt.Errorf("ReadSignedData %w", err)
}
if err = sig.Calculate(signer, data); err != nil {
return fmt.Errorf("calculate %w", err)
}
sig.WriteToV2(&sigv2)
sigWrite(&sigv2)
return nil
}
func verifyServiceMessage(msg interface{}) error {
var (
meta metaHeader
verify verificationHeader
)
switch v := msg.(type) {
case nil:
return nil
case serviceRequest:
meta = &requestMetaHeader{
RequestMetaHeader: v.GetMetaHeader(),
}
verify = &requestVerificationHeader{
RequestVerificationHeader: v.GetVerificationHeader(),
}
case serviceResponse:
meta = &responseMetaHeader{
ResponseMetaHeader: v.GetMetaHeader(),
}
verify = &responseVerificationHeader{
ResponseVerificationHeader: v.GetVerificationHeader(),
}
default:
panic(fmt.Sprintf("unsupported session message %T", v))
}
body := serviceMessageBody(msg)
size := body.StableSize()
if sz := meta.StableSize(); sz > size {
size = sz
}
if sz := verify.StableSize(); sz > size {
size = sz
}
buf := make([]byte, 0, size)
return verifyMatryoshkaLevel(body, meta, verify, buf)
}
func verifyMatryoshkaLevel(body stableMarshaler, meta metaHeader, verify verificationHeader, buf []byte) error {
if err := verifyServiceMessagePart(meta, verify.GetMetaSignature, buf); err != nil {
return fmt.Errorf("could not verify meta header: %w", err)
}
origin := verify.getOrigin()
if err := verifyServiceMessagePart(origin, verify.GetOriginSignature, buf); err != nil {
return fmt.Errorf("could not verify origin of verification header: %w", err)
}
if origin == nil {
if err := verifyServiceMessagePart(body, verify.GetBodySignature, buf); err != nil {
return fmt.Errorf("could not verify body: %w", err)
}
return nil
}
if verify.GetBodySignature() != nil {
return errors.New("body signature at the matryoshka upper level")
}
return verifyMatryoshkaLevel(body, meta.getOrigin(), origin, buf)
}
func verifyServiceMessagePart(part stableMarshaler, sigRdr func() *refs.Signature, buf []byte) error {
return signature.VerifyDataWithSource(
&stableMarshalerWrapper{part},
sigRdr,
signature.WithBuffer(buf),
)
}
func serviceMessageBody(req any) stableMarshaler {
switch v := req.(type) {
default:
panic(fmt.Sprintf("unsupported session message %T", req))
/* Accounting */
case *accounting.BalanceRequest:
return v.GetBody()
case *accounting.BalanceResponse:
return v.GetBody()
/* Session */
case *session.CreateRequest:
return v.GetBody()
case *session.CreateResponse:
return v.GetBody()
/* Container */
case *container.PutRequest:
return v.GetBody()
case *container.PutResponse:
return v.GetBody()
case *container.DeleteRequest:
return v.GetBody()
case *container.DeleteResponse:
return v.GetBody()
case *container.GetRequest:
return v.GetBody()
case *container.GetResponse:
return v.GetBody()
case *container.ListRequest:
return v.GetBody()
case *container.ListResponse:
return v.GetBody()
case *container.SetExtendedACLRequest:
return v.GetBody()
case *container.SetExtendedACLResponse:
return v.GetBody()
case *container.GetExtendedACLRequest:
return v.GetBody()
case *container.GetExtendedACLResponse:
return v.GetBody()
case *container.AnnounceUsedSpaceRequest:
return v.GetBody()
case *container.AnnounceUsedSpaceResponse:
return v.GetBody()
/* Object */
case *object.PutRequest:
return v.GetBody()
case *object.PutResponse:
return v.GetBody()
case *object.GetRequest:
return v.GetBody()
case *object.GetResponse:
return v.GetBody()
case *object.HeadRequest:
return v.GetBody()
case *object.HeadResponse:
return v.GetBody()
case *object.SearchRequest:
return v.GetBody()
case *object.SearchResponse:
return v.GetBody()
case *object.DeleteRequest:
return v.GetBody()
case *object.DeleteResponse:
return v.GetBody()
case *object.GetRangeRequest:
return v.GetBody()
case *object.GetRangeResponse:
return v.GetBody()
case *object.GetRangeHashRequest:
return v.GetBody()
case *object.GetRangeHashResponse:
return v.GetBody()
/* Netmap */
case *netmap.LocalNodeInfoRequest:
return v.GetBody()
case *netmap.LocalNodeInfoResponse:
return v.GetBody()
case *netmap.NetworkInfoRequest:
return v.GetBody()
case *netmap.NetworkInfoResponse:
return v.GetBody()
case *netmap.SnapshotRequest:
return v.GetBody()
case *netmap.SnapshotResponse:
return v.GetBody()
/* Reputation */
case *reputation.AnnounceLocalTrustRequest:
return v.GetBody()
case *reputation.AnnounceLocalTrustResponse:
return v.GetBody()
case *reputation.AnnounceIntermediateResultRequest:
return v.GetBody()
case *reputation.AnnounceIntermediateResultResponse:
return v.GetBody()
}
}

247
client/sign_test.go Normal file
View file

@ -0,0 +1,247 @@
package client
import (
"crypto/rand"
"testing"
"github.com/nspcc-dev/neofs-api-go/v2/accounting"
"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/crypto/test"
"github.com/nspcc-dev/neofs-sdk-go/user"
"github.com/stretchr/testify/require"
)
type testResponse interface {
SetMetaHeader(*session.ResponseMetaHeader)
GetMetaHeader() *session.ResponseMetaHeader
}
func testOwner(t *testing.T, owner *refs.OwnerID, req any) {
originalValue := owner.GetValue()
owner.SetValue([]byte{1, 2, 3})
// verification must fail
require.Error(t, verifyServiceMessage(req))
owner.SetValue(originalValue)
require.NoError(t, verifyServiceMessage(req))
}
func testRequestSign(t *testing.T, signer neofscrypto.Signer, meta *session.RequestMetaHeader, req request) {
require.Error(t, verifyServiceMessage(req))
// sign request
require.NoError(t, signServiceMessage(signer, req))
// verification must pass
require.NoError(t, verifyServiceMessage(req))
meta.SetOrigin(req.GetMetaHeader())
req.SetMetaHeader(meta)
// sign request
require.NoError(t, signServiceMessage(signer, req))
// verification must pass
require.NoError(t, verifyServiceMessage(req))
}
func testRequestMeta(t *testing.T, meta *session.RequestMetaHeader, req serviceRequest) {
// corrupt meta header
meta.SetTTL(meta.GetTTL() + 1)
// verification must fail
require.Error(t, verifyServiceMessage(req))
// restore meta header
meta.SetTTL(meta.GetTTL() - 1)
// corrupt origin verification header
req.GetVerificationHeader().SetOrigin(nil)
// verification must fail
require.Error(t, verifyServiceMessage(req))
}
func testResponseSign(t *testing.T, signer neofscrypto.Signer, meta *session.ResponseMetaHeader, resp testResponse) {
require.Error(t, verifyServiceMessage(resp))
// sign request
require.NoError(t, signServiceMessage(signer, resp))
// verification must pass
require.NoError(t, verifyServiceMessage(resp))
meta.SetOrigin(resp.GetMetaHeader())
resp.SetMetaHeader(meta)
// sign request
require.NoError(t, signServiceMessage(signer, resp))
// verification must pass
require.NoError(t, verifyServiceMessage(resp))
}
func testResponseMeta(t *testing.T, meta *session.ResponseMetaHeader, req serviceResponse) {
// corrupt meta header
meta.SetTTL(meta.GetTTL() + 1)
// verification must fail
require.Error(t, verifyServiceMessage(req))
// restore meta header
meta.SetTTL(meta.GetTTL() - 1)
// corrupt origin verification header
req.GetVerificationHeader().SetOrigin(nil)
// verification must fail
require.Error(t, verifyServiceMessage(req))
}
func TestEmptyMessage(t *testing.T) {
signer := test.RandomSignerRFC6979(t)
require.NoError(t, verifyServiceMessage(nil))
require.NoError(t, signServiceMessage(signer, nil))
}
func TestBalanceRequest(t *testing.T) {
signer := test.RandomSignerRFC6979(t)
var id user.ID
require.NoError(t, user.IDFromSigner(&id, signer))
var ownerID refs.OwnerID
id.WriteToV2(&ownerID)
body := accounting.BalanceRequestBody{}
body.SetOwnerID(&ownerID)
meta := &session.RequestMetaHeader{}
meta.SetTTL(1)
req := &accounting.BalanceRequest{}
req.SetBody(&body)
req.SetMetaHeader(meta)
// add level to meta header matryoshka
meta = &session.RequestMetaHeader{}
testRequestSign(t, signer, meta, req)
testOwner(t, &ownerID, req)
testRequestMeta(t, meta, req)
}
func TestBalanceResponse(t *testing.T) {
signer := test.RandomSignerRFC6979(t)
dec := new(accounting.Decimal)
dec.SetValue(100)
body := new(accounting.BalanceResponseBody)
body.SetBalance(dec)
meta := new(session.ResponseMetaHeader)
meta.SetTTL(1)
resp := new(accounting.BalanceResponse)
resp.SetBody(body)
resp.SetMetaHeader(meta)
// add level to meta header matryoshka
meta = new(session.ResponseMetaHeader)
testResponseSign(t, signer, meta, resp)
// corrupt body
dec.SetValue(dec.GetValue() + 1)
// verification must fail
require.Error(t, verifyServiceMessage(resp))
// restore body
dec.SetValue(dec.GetValue() - 1)
testResponseMeta(t, meta, resp)
}
func TestCreateRequest(t *testing.T) {
signer := test.RandomSignerRFC6979(t)
var id user.ID
require.NoError(t, user.IDFromSigner(&id, signer))
var ownerID refs.OwnerID
id.WriteToV2(&ownerID)
body := session.CreateRequestBody{}
body.SetOwnerID(&ownerID)
body.SetExpiration(100)
meta := &session.RequestMetaHeader{}
meta.SetTTL(1)
req := &session.CreateRequest{}
req.SetBody(&body)
req.SetMetaHeader(meta)
// add level to meta header matryoshka
meta = &session.RequestMetaHeader{}
testRequestSign(t, signer, meta, req)
testOwner(t, &ownerID, req)
// corrupt body
body.SetExpiration(body.GetExpiration() + 1)
// verification must fail
require.Error(t, verifyServiceMessage(req))
// restore body
body.SetExpiration(body.GetExpiration() - 1)
testRequestMeta(t, meta, req)
}
func TestCreateResponse(t *testing.T) {
signer := test.RandomSignerRFC6979(t)
id := make([]byte, 8)
_, err := rand.Read(id)
require.NoError(t, err)
sessionKey := make([]byte, 8)
_, err = rand.Read(sessionKey)
require.NoError(t, err)
body := session.CreateResponseBody{}
body.SetID(id)
body.SetSessionKey(sessionKey)
meta := &session.ResponseMetaHeader{}
meta.SetTTL(1)
req := &session.CreateResponse{}
req.SetBody(&body)
req.SetMetaHeader(meta)
// add level to meta header matryoshka
meta = &session.ResponseMetaHeader{}
testResponseSign(t, signer, meta, req)
// corrupt body
body.SetID([]byte{1})
// verification must fail
require.Error(t, verifyServiceMessage(req))
// restore body
body.SetID(id)
// corrupt body
body.SetSessionKey([]byte{1})
// verification must fail
require.Error(t, verifyServiceMessage(req))
// restore body
body.SetSessionKey(id)
testResponseMeta(t, meta, req)
}

View file

@ -7,7 +7,6 @@ import (
"time"
"github.com/google/uuid"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
v2container "github.com/nspcc-dev/neofs-api-go/v2/container"
v2netmap "github.com/nspcc-dev/neofs-api-go/v2/netmap"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
@ -16,7 +15,7 @@ import (
cidtest "github.com/nspcc-dev/neofs-sdk-go/container/id/test"
containertest "github.com/nspcc-dev/neofs-sdk-go/container/test"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
netmaptest "github.com/nspcc-dev/neofs-sdk-go/netmap/test"
subnetid "github.com/nspcc-dev/neofs-sdk-go/subnet/id"
subnetidtest "github.com/nspcc-dev/neofs-sdk-go/subnet/id/test"
@ -26,7 +25,7 @@ import (
)
func TestPlacementPolicyEncoding(t *testing.T) {
v := containertest.Container()
v := containertest.Container(t)
t.Run("binary", func(t *testing.T) {
var v2 container.Container
@ -47,7 +46,7 @@ func TestPlacementPolicyEncoding(t *testing.T) {
}
func TestContainer_Init(t *testing.T) {
val := containertest.Container()
val := containertest.Container(t)
val.Init()
@ -79,9 +78,9 @@ func TestContainer_Owner(t *testing.T) {
require.Zero(t, val.Owner())
val = containertest.Container()
val = containertest.Container(t)
owner := *usertest.ID()
owner := *usertest.ID(t)
val.SetOwner(owner)
@ -104,7 +103,7 @@ func TestContainer_BasicACL(t *testing.T) {
require.Zero(t, val.BasicACL())
val = containertest.Container()
val = containertest.Container(t)
basicACL := containertest.BasicACL()
val.SetBasicACL(basicACL)
@ -125,7 +124,7 @@ func TestContainer_PlacementPolicy(t *testing.T) {
require.Zero(t, val.PlacementPolicy())
val = containertest.Container()
val = containertest.Container(t)
pp := netmaptest.PlacementPolicy()
val.SetPlacementPolicy(pp)
@ -156,7 +155,7 @@ func TestContainer_Attribute(t *testing.T) {
const attrKey1, attrKey2 = "key1", "key2"
const attrVal1, attrVal2 = "val1", "val2"
val := containertest.Container()
val := containertest.Container(t)
val.SetAttribute(attrKey1, attrVal1)
val.SetAttribute(attrKey2, attrVal2)
@ -195,7 +194,7 @@ func TestSetName(t *testing.T) {
container.SetName(&val, "")
})
val = containertest.Container()
val = containertest.Container(t)
const name = "some name"
@ -217,7 +216,7 @@ func TestSetCreationTime(t *testing.T) {
require.Zero(t, container.CreatedAt(val).Unix())
val = containertest.Container()
val = containertest.Container(t)
creat := time.Now()
@ -239,7 +238,7 @@ func TestSetSubnet(t *testing.T) {
require.True(t, subnetid.IsZero(container.Subnet(val)))
val = containertest.Container()
val = containertest.Container(t)
sub := subnetidtest.ID()
@ -261,7 +260,7 @@ func TestDisableHomomorphicHashing(t *testing.T) {
require.False(t, container.IsHomomorphicHashingDisabled(val))
val = containertest.Container()
val = containertest.Container(t)
container.DisableHomomorphicHashing(&val)
@ -281,7 +280,7 @@ func TestWriteDomain(t *testing.T) {
require.Zero(t, container.ReadDomain(val).Name())
val = containertest.Container()
val = containertest.Container(t)
const name = "domain name"
@ -313,7 +312,7 @@ func TestWriteDomain(t *testing.T) {
}
func TestCalculateID(t *testing.T) {
val := containertest.Container()
val := containertest.Container(t)
require.False(t, container.AssertID(cidtest.ID(), val))
@ -333,14 +332,11 @@ func TestCalculateID(t *testing.T) {
}
func TestCalculateSignature(t *testing.T) {
key, err := keys.NewPrivateKey()
require.NoError(t, err)
val := containertest.Container()
val := containertest.Container(t)
var sig neofscrypto.Signature
require.NoError(t, container.CalculateSignature(&sig, val, neofsecdsa.SignerRFC6979(key.PrivateKey)))
require.NoError(t, container.CalculateSignature(&sig, val, test.RandomSignerRFC6979(t)))
var msg refs.Signature
sig.WriteToV2(&msg)

View file

@ -10,7 +10,7 @@ import (
)
func TestContainer_NetworkConfig(t *testing.T) {
c := containertest.Container()
c := containertest.Container(t)
nc := netmaptest.NetworkInfo()
t.Run("default", func(t *testing.T) {

View file

@ -2,6 +2,7 @@ package containertest
import (
"math/rand"
"testing"
"github.com/nspcc-dev/neofs-sdk-go/container"
"github.com/nspcc-dev/neofs-sdk-go/container/acl"
@ -11,8 +12,8 @@ import (
)
// Container returns random container.Container.
func Container() (x container.Container) {
owner := usertest.ID()
func Container(t *testing.T) (x container.Container) {
owner := usertest.ID(t)
x.Init()
x.SetAttribute("some attribute", "value")

33
crypto/test/tests.go Normal file
View file

@ -0,0 +1,33 @@
/*
Package tests provides special help functions for testing NeoFS API and its environment.
All functions accepting `t *testing.T` that emphasize there are only for tests purposes.
*/
package test
import (
"testing"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/stretchr/testify/require"
)
// RandomSigner return neofscrypto.Signer ONLY for TESTs purposes.
// It may be used like helper to get new neofscrypto.Signer if you need it in yours tests.
func RandomSigner(tb testing.TB) neofscrypto.Signer {
p, err := keys.NewPrivateKey()
require.NoError(tb, err)
return neofsecdsa.Signer(p.PrivateKey)
}
// RandomSignerRFC6979 return neofscrypto.Signer ONLY for TESTs purposes.
// It may be used like helper to get new neofscrypto.Signer if you need it in yours tests.
func RandomSignerRFC6979(tb testing.TB) neofscrypto.Signer {
p, err := keys.NewPrivateKey()
require.NoError(tb, err)
return neofsecdsa.SignerRFC6979(p.PrivateKey)
}

View file

@ -154,7 +154,7 @@ func TestReservedRecords(t *testing.T) {
v = versiontest.Version()
oid = oidtest.ID()
cid = cidtest.ID()
ownerid = usertest.ID()
ownerid = usertest.ID(t)
h = checksumtest.Checksum()
typ = new(object.Type)
)

View file

@ -66,7 +66,7 @@ func TestTable_AddRecord(t *testing.T) {
}
func TestTableEncoding(t *testing.T) {
tab := eacltest.Table()
tab := eacltest.Table(t)
t.Run("binary", func(t *testing.T) {
data, err := tab.Marshal()

View file

@ -1,6 +1,8 @@
package eacltest
import (
"testing"
cidtest "github.com/nspcc-dev/neofs-sdk-go/container/id/test"
"github.com/nspcc-dev/neofs-sdk-go/eacl"
usertest "github.com/nspcc-dev/neofs-sdk-go/user/test"
@ -21,24 +23,24 @@ func Target() *eacl.Target {
}
// Record returns random eacl.Record.
func Record() *eacl.Record {
func Record(tb testing.TB) *eacl.Record {
x := eacl.NewRecord()
x.SetAction(eacl.ActionAllow)
x.SetOperation(eacl.OperationRangeHash)
x.SetTargets(*Target(), *Target())
x.AddObjectContainerIDFilter(eacl.MatchStringEqual, cidtest.ID())
x.AddObjectOwnerIDFilter(eacl.MatchStringNotEqual, usertest.ID())
x.AddObjectOwnerIDFilter(eacl.MatchStringNotEqual, usertest.ID(tb))
return x
}
func Table() *eacl.Table {
func Table(tb testing.TB) *eacl.Table {
x := eacl.NewTable()
x.SetCID(cidtest.ID())
x.AddRecord(Record())
x.AddRecord(Record())
x.AddRecord(Record(tb))
x.AddRecord(Record(tb))
x.SetVersion(versiontest.Version())
return x

View file

@ -2,7 +2,6 @@ package object
import (
"bytes"
"crypto/ecdsa"
"crypto/sha256"
"errors"
"fmt"
@ -96,13 +95,13 @@ func VerifyID(obj *Object) error {
// CalculateAndSetSignature signs id with provided key and sets that signature to
// the object.
func CalculateAndSetSignature(key ecdsa.PrivateKey, obj *Object) error {
func CalculateAndSetSignature(signer neofscrypto.Signer, obj *Object) error {
oID, set := obj.ID()
if !set {
return errOIDNotSet
}
sig, err := oID.CalculateIDSignature(key)
sig, err := oID.CalculateIDSignature(signer)
if err != nil {
return err
}
@ -132,12 +131,12 @@ func (o *Object) VerifyIDSignature() bool {
}
// SetIDWithSignature sets object identifier and signature.
func SetIDWithSignature(key ecdsa.PrivateKey, obj *Object) error {
func SetIDWithSignature(signer neofscrypto.Signer, obj *Object) error {
if err := CalculateAndSetID(obj); err != nil {
return fmt.Errorf("could not set identifier: %w", err)
}
if err := CalculateAndSetSignature(key, obj); err != nil {
if err := CalculateAndSetSignature(signer, obj); err != nil {
return fmt.Errorf("could not set signature: %w", err)
}
@ -145,10 +144,10 @@ func SetIDWithSignature(key ecdsa.PrivateKey, obj *Object) error {
}
// SetVerificationFields calculates and sets all verification fields of the object.
func SetVerificationFields(key ecdsa.PrivateKey, obj *Object) error {
func SetVerificationFields(signer neofscrypto.Signer, obj *Object) error {
CalculateAndSetPayloadChecksum(obj)
return SetIDWithSignature(key, obj)
return SetIDWithSignature(signer, obj)
}
// CheckVerificationFields checks all verification fields of the object.

View file

@ -4,7 +4,7 @@ import (
"crypto/rand"
"testing"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/stretchr/testify/require"
)
@ -17,9 +17,7 @@ func TestVerificationFields(t *testing.T) {
obj.SetPayload(payload)
obj.SetPayloadSize(uint64(len(payload)))
p, err := keys.NewPrivateKey()
require.NoError(t, err)
require.NoError(t, SetVerificationFields(p.PrivateKey, obj))
require.NoError(t, SetVerificationFields(test.RandomSigner(t), obj))
require.NoError(t, CheckVerificationFields(obj))

View file

@ -1,14 +1,12 @@
package oid
import (
"crypto/ecdsa"
"crypto/sha256"
"fmt"
"github.com/mr-tron/base58"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
)
// ID represents NeoFS object identifier in a container.
@ -117,7 +115,7 @@ func (id ID) String() string {
}
// CalculateIDSignature signs object id with provided key.
func (id ID) CalculateIDSignature(key ecdsa.PrivateKey) (neofscrypto.Signature, error) {
func (id ID) CalculateIDSignature(signer neofscrypto.Signer) (neofscrypto.Signature, error) {
data, err := id.Marshal()
if err != nil {
return neofscrypto.Signature{}, fmt.Errorf("marshal ID: %w", err)
@ -125,7 +123,7 @@ func (id ID) CalculateIDSignature(key ecdsa.PrivateKey) (neofscrypto.Signature,
var sig neofscrypto.Signature
return sig, sig.Calculate(neofsecdsa.Signer(key), data)
return sig, sig.Calculate(signer, data)
}
// Marshal marshals ID into a protobuf binary form.

View file

@ -12,7 +12,7 @@ import (
func TestInitCreation(t *testing.T) {
var o object.Object
cnr := cidtest.ID()
own := *usertest.ID()
own := *usertest.ID(t)
object.InitCreation(&o, object.RequiredFields{
Container: cnr,

View file

@ -1,6 +1,8 @@
package objecttest
import (
"testing"
"github.com/google/uuid"
checksumtest "github.com/nspcc-dev/neofs-sdk-go/checksum/test"
cidtest "github.com/nspcc-dev/neofs-sdk-go/container/id/test"
@ -41,14 +43,14 @@ func SplitID() *object.SplitID {
return x
}
func generate(withParent bool) *object.Object {
func generate(t *testing.T, withParent bool) *object.Object {
x := object.New()
ver := version.Current()
x.SetID(oidtest.ID())
x.SetSessionToken(sessiontest.Object())
x.SetPayload([]byte{1, 2, 3})
x.SetOwnerID(usertest.ID())
x.SetOwnerID(usertest.ID(t))
x.SetContainerID(cidtest.ID())
x.SetType(object.TypeTombstone)
x.SetVersion(&ver)
@ -63,7 +65,7 @@ func generate(withParent bool) *object.Object {
x.SetPayloadHomomorphicHash(checksumtest.Checksum())
if withParent {
x.SetParent(generate(false))
x.SetParent(generate(t, false))
}
return x
@ -71,13 +73,13 @@ func generate(withParent bool) *object.Object {
// Raw returns random object.Object.
// Deprecated: (v1.0.0) use Object instead.
func Raw() *object.Object {
return Object()
func Raw(t *testing.T) *object.Object {
return Object(t)
}
// Object returns random object.Object.
func Object() *object.Object {
return generate(true)
func Object(t *testing.T) *object.Object {
return generate(t, true)
}
// Tombstone returns random object.Tombstone.

View file

@ -3,7 +3,7 @@ package pool
import (
"testing"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/nspcc-dev/neofs-sdk-go/session"
sessiontest "github.com/nspcc-dev/neofs-sdk-go/session/test"
"github.com/stretchr/testify/require"
@ -13,9 +13,6 @@ func TestSessionCache_GetUnmodifiedToken(t *testing.T) {
const key = "Foo"
target := *sessiontest.Object()
pk, err := keys.NewPrivateKey()
require.NoError(t, err)
check := func(t *testing.T, tok session.Object, extra string) {
require.False(t, tok.VerifySignature(), extra)
}
@ -28,7 +25,7 @@ func TestSessionCache_GetUnmodifiedToken(t *testing.T) {
require.True(t, ok)
check(t, value, "before sign")
err = value.Sign(pk.PrivateKey)
err = value.Sign(test.RandomSigner(t))
require.NoError(t, err)
value, ok = cache.Get(key)

View file

@ -11,7 +11,7 @@ This InitParameters will make pool use 192.168.130.71 node while it is healthy.
:
var prm pool.InitParameters
prm.SetKey(key)
prm.SetSigner(signer)
prm.AddNode(NewNodeParam(1, "192.168.130.71", 1))
prm.AddNode(NewNodeParam(2, "192.168.130.72", 9))
prm.AddNode(NewNodeParam(2, "192.168.130.73", 1))

View file

@ -2,7 +2,6 @@ package pool
import (
"context"
"crypto/ecdsa"
"errors"
"github.com/google/uuid"
@ -12,7 +11,7 @@ import (
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
"github.com/nspcc-dev/neofs-sdk-go/container"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/nspcc-dev/neofs-sdk-go/eacl"
"github.com/nspcc-dev/neofs-sdk-go/netmap"
"github.com/nspcc-dev/neofs-sdk-go/object"
@ -21,7 +20,7 @@ import (
)
type mockClient struct {
key ecdsa.PrivateKey
signer neofscrypto.Signer
clientStatusMonitor
errorOnDial bool
@ -31,9 +30,9 @@ type mockClient struct {
stOnGetObject apistatus.Status
}
func newMockClient(addr string, key ecdsa.PrivateKey) *mockClient {
func newMockClient(addr string, signer neofscrypto.Signer) *mockClient {
return &mockClient{
key: key,
signer: signer,
clientStatusMonitor: newClientStatusMonitor(addr, 10),
}
}
@ -65,11 +64,13 @@ func (m *mockClient) statusOnGetObject(st apistatus.Status) {
m.stOnGetObject = st
}
func newToken(key ecdsa.PrivateKey) *session.Object {
func newToken(signer neofscrypto.Signer) *session.Object {
var tok session.Object
tok.SetID(uuid.New())
pk := neofsecdsa.PublicKey(key.PublicKey)
tok.SetAuthKey(&pk)
public := signer.Public()
tok.SetAuthKey(public)
return &tok
}
@ -159,7 +160,7 @@ func (m *mockClient) sessionCreate(context.Context, prmCreateSession) (resCreate
return resCreateSession{}, m.handleError(nil, errors.New("error"))
}
tok := newToken(m.key)
tok := newToken(m.signer)
var v2tok sessionv2.Token
tok.WriteToV2(&v2tok)

View file

@ -3,7 +3,6 @@ package pool
import (
"bytes"
"context"
"crypto/ecdsa"
"errors"
"fmt"
"io"
@ -14,13 +13,13 @@ import (
"time"
"github.com/google/uuid"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neofs-sdk-go/accounting"
"github.com/nspcc-dev/neofs-sdk-go/bearer"
sdkClient "github.com/nspcc-dev/neofs-sdk-go/client"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
"github.com/nspcc-dev/neofs-sdk-go/container"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/eacl"
"github.com/nspcc-dev/neofs-sdk-go/netmap"
@ -227,7 +226,7 @@ type clientWrapper struct {
// wrapperPrm is params to create clientWrapper.
type wrapperPrm struct {
address string
key ecdsa.PrivateKey
signer neofscrypto.Signer
dialTimeout time.Duration
streamTimeout time.Duration
errorThreshold uint32
@ -240,9 +239,9 @@ func (x *wrapperPrm) setAddress(address string) {
x.address = address
}
// setKey sets sdkClient.Client private key to be used for the protocol communication by default.
func (x *wrapperPrm) setKey(key ecdsa.PrivateKey) {
x.key = key
// setSigner sets sdkClient.Client private signer to be used for the protocol communication by default.
func (x *wrapperPrm) setSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// setDialTimeout sets the timeout for connection to be established.
@ -275,7 +274,7 @@ func (x *wrapperPrm) setResponseInfoCallback(f func(sdkClient.ResponseMetaInfo)
func newWrapper(prm wrapperPrm) *clientWrapper {
var cl sdkClient.Client
var prmInit sdkClient.PrmInit
prmInit.SetDefaultPrivateKey(prm.key)
prmInit.SetDefaultSigner(prm.signer)
prmInit.SetResponseInfoCallback(prm.responseInfoCallback)
cl.Init(prmInit)
@ -324,7 +323,7 @@ func (c *clientWrapper) restartIfUnhealthy(ctx context.Context) (healthy, change
var cl sdkClient.Client
var prmInit sdkClient.PrmInit
prmInit.SetDefaultPrivateKey(c.prm.key)
prmInit.SetDefaultSigner(c.prm.signer)
prmInit.SetResponseInfoCallback(c.prm.responseInfoCallback)
cl.Init(prmInit)
@ -619,8 +618,8 @@ func (c *clientWrapper) objectPut(ctx context.Context, prm PrmObjectPut) (oid.ID
if prm.stoken != nil {
cliPrm.WithinSession(*prm.stoken)
}
if prm.key != nil {
cliPrm.UseKey(*prm.key)
if prm.signer != nil {
cliPrm.UseSigner(prm.signer)
}
if prm.btoken != nil {
cliPrm.WithBearerToken(*prm.btoken)
@ -709,8 +708,8 @@ func (c *clientWrapper) objectDelete(ctx context.Context, prm PrmObjectDelete) e
cliPrm.WithBearerToken(*prm.btoken)
}
if prm.key != nil {
cliPrm.UseKey(*prm.key)
if prm.signer != nil {
cliPrm.UseSigner(prm.signer)
}
start := time.Now()
@ -745,8 +744,8 @@ func (c *clientWrapper) objectGet(ctx context.Context, prm PrmObjectGet) (ResGet
cliPrm.WithBearerToken(*prm.btoken)
}
if prm.key != nil {
cliPrm.UseKey(*prm.key)
if prm.signer != nil {
cliPrm.UseSigner(prm.signer)
}
var res ResGetObject
@ -801,8 +800,8 @@ func (c *clientWrapper) objectHead(ctx context.Context, prm PrmObjectHead) (obje
cliPrm.WithBearerToken(*prm.btoken)
}
if prm.key != nil {
cliPrm.UseKey(*prm.key)
if prm.signer != nil {
cliPrm.UseSigner(prm.signer)
}
var obj object.Object
@ -845,8 +844,8 @@ func (c *clientWrapper) objectRange(ctx context.Context, prm PrmObjectRange) (Re
cliPrm.WithBearerToken(*prm.btoken)
}
if prm.key != nil {
cliPrm.UseKey(*prm.key)
if prm.signer != nil {
cliPrm.UseSigner(prm.signer)
}
start := time.Now()
@ -884,8 +883,8 @@ func (c *clientWrapper) objectSearch(ctx context.Context, prm PrmObjectSearch) (
cliPrm.WithBearerToken(*prm.btoken)
}
if prm.key != nil {
cliPrm.UseKey(*prm.key)
if prm.signer != nil {
cliPrm.UseSigner(prm.signer)
}
res, err := cl.ObjectSearchInit(ctx, cliPrm)
@ -905,7 +904,7 @@ func (c *clientWrapper) sessionCreate(ctx context.Context, prm prmCreateSession)
var cliPrm sdkClient.PrmSessionCreate
cliPrm.SetExp(prm.exp)
cliPrm.UseKey(prm.key)
cliPrm.UseSigner(prm.signer)
start := time.Now()
res, err := cl.SessionCreate(ctx, cliPrm)
@ -1022,7 +1021,7 @@ type RequestInfo struct {
// InitParameters contains values used to initialize connection Pool.
type InitParameters struct {
key *ecdsa.PrivateKey
signer neofscrypto.Signer
logger *zap.Logger
nodeDialTimeout time.Duration
nodeStreamTimeout time.Duration
@ -1036,9 +1035,9 @@ type InitParameters struct {
clientBuilder clientBuilder
}
// SetKey specifies default key to be used for the protocol communication by default.
func (x *InitParameters) SetKey(key *ecdsa.PrivateKey) {
x.key = key
// SetSigner specifies default signer to be used for the protocol communication by default.
func (x *InitParameters) SetSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// SetLogger specifies logger.
@ -1209,15 +1208,15 @@ func (x *prmContext) useVerb(verb session.ObjectVerb) {
}
type prmCommon struct {
key *ecdsa.PrivateKey
signer neofscrypto.Signer
btoken *bearer.Token
stoken *session.Object
}
// UseKey specifies private key to sign the requests.
// If key is not provided, then Pool default key is used.
func (x *prmCommon) UseKey(key *ecdsa.PrivateKey) {
x.key = key
// UseSigner specifies private signer to sign the requests.
// If signer is not provided, then Pool default signer is used.
func (x *prmCommon) UseSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// UseBearer attaches bearer token to be used for the operation.
@ -1484,7 +1483,7 @@ func (x *PrmBalanceGet) SetAccount(id user.ID) {
// prmEndpointInfo groups parameters of sessionCreate operation.
type prmCreateSession struct {
exp uint64
key ecdsa.PrivateKey
signer neofscrypto.Signer
}
// setExp sets number of the last NeoFS epoch in the lifetime of the session after which it will be expired.
@ -1492,10 +1491,10 @@ func (x *prmCreateSession) setExp(exp uint64) {
x.exp = exp
}
// useKey specifies owner private key for session token.
// If key is not provided, then Pool default key is used.
func (x *prmCreateSession) useKey(key ecdsa.PrivateKey) {
x.key = key
// useSigner specifies owner private signer for session token.
// If signer is not provided, then Pool default signer is used.
func (x *prmCreateSession) useSigner(signer neofscrypto.Signer) {
x.signer = signer
}
// prmEndpointInfo groups parameters of endpointInfo operation.
@ -1534,7 +1533,7 @@ type resCreateSession struct {
// See pool package overview to get some examples.
type Pool struct {
innerPools []*innerPool
key *ecdsa.PrivateKey
signer neofscrypto.Signer
cancel context.CancelFunc
closedCh chan struct{}
cache *sessionCache
@ -1562,8 +1561,8 @@ const (
// NewPool creates connection pool using parameters.
func NewPool(options InitParameters) (*Pool, error) {
if options.key == nil {
return nil, fmt.Errorf("missed required parameter 'Key'")
if options.signer == nil {
return nil, fmt.Errorf("missed required parameter 'Signer'")
}
nodesParams, err := adjustNodeParams(options.nodeParams)
@ -1579,7 +1578,7 @@ func NewPool(options InitParameters) (*Pool, error) {
fillDefaultInitParams(&options, cache)
pool := &Pool{
key: options.key,
signer: options.signer,
cache: cache,
logger: options.logger,
stokenDuration: options.sessionExpirationDuration,
@ -1619,7 +1618,7 @@ func (p *Pool) Dial(ctx context.Context) error {
}
var st session.Object
err := initSessionForDuration(ctx, &st, clients[j], p.rebalanceParams.sessionExpirationDuration, *p.key)
err := initSessionForDuration(ctx, &st, clients[j], p.rebalanceParams.sessionExpirationDuration, p.signer)
if err != nil {
clients[j].setUnhealthy()
if p.logger != nil {
@ -1629,7 +1628,7 @@ func (p *Pool) Dial(ctx context.Context) error {
continue
}
_ = p.cache.Put(formCacheKey(addr, p.key), st)
_ = p.cache.Put(formCacheKey(addr, p.signer), st)
atLeastOneHealthy = true
}
source := rand.NewSource(time.Now().UnixNano())
@ -1683,7 +1682,7 @@ func fillDefaultInitParams(params *InitParameters, cache *sessionCache) {
params.setClientBuilder(func(addr string) client {
var prm wrapperPrm
prm.setAddress(addr)
prm.setKey(*params.key)
prm.setSigner(params.signer)
prm.setDialTimeout(params.nodeDialTimeout)
prm.setStreamTimeout(params.nodeStreamTimeout)
prm.setErrorThreshold(params.errorThreshold)
@ -1849,9 +1848,11 @@ func (p *innerPool) connection() (client, error) {
return nil, errors.New("no healthy client")
}
func formCacheKey(address string, key *ecdsa.PrivateKey) string {
k := keys.PrivateKey{PrivateKey: *key}
return address + k.String()
func formCacheKey(address string, signer neofscrypto.Signer) string {
b := make([]byte, signer.Public().MaxEncodedSize())
signer.Public().Encode(b)
return address + string(b)
}
func (p *Pool) checkSessionTokenErr(err error, address string) bool {
@ -1867,7 +1868,7 @@ func (p *Pool) checkSessionTokenErr(err error, address string) bool {
return false
}
func initSessionForDuration(ctx context.Context, dst *session.Object, c client, dur uint64, ownerKey ecdsa.PrivateKey) error {
func initSessionForDuration(ctx context.Context, dst *session.Object, c client, dur uint64, signer neofscrypto.Signer) error {
ni, err := c.networkInfo(ctx, prmNetworkInfo{})
if err != nil {
return err
@ -1883,7 +1884,7 @@ func initSessionForDuration(ctx context.Context, dst *session.Object, c client,
}
var prm prmCreateSession
prm.setExp(exp)
prm.useKey(ownerKey)
prm.useSigner(signer)
res, err := c.sessionCreate(ctx, prm)
if err != nil {
@ -1921,7 +1922,7 @@ type callContext struct {
endpoint string
// request signer
key *ecdsa.PrivateKey
signer neofscrypto.Signer
// flag to open default session if session token is missing
sessionDefault bool
@ -1938,10 +1939,10 @@ func (p *Pool) initCallContext(ctx *callContext, cfg prmCommon, prmCtx prmContex
return err
}
ctx.key = cfg.key
if ctx.key == nil {
// use pool key if caller didn't specify its own
ctx.key = p.key
ctx.signer = cfg.signer
if ctx.signer == nil {
// use pool signer if caller didn't specify its own
ctx.signer = p.signer
}
ctx.endpoint = cp.address()
@ -1966,12 +1967,12 @@ func (p *Pool) initCallContext(ctx *callContext, cfg prmCommon, prmCtx prmContex
// opens new session or uses cached one.
// Must be called only on initialized callContext with set sessionTarget.
func (p *Pool) openDefaultSession(ctx *callContext) error {
cacheKey := formCacheKey(ctx.endpoint, ctx.key)
cacheKey := formCacheKey(ctx.endpoint, ctx.signer)
tok, ok := p.cache.Get(cacheKey)
if !ok {
// init new session
err := initSessionForDuration(ctx, &tok, ctx.client, p.stokenDuration, *ctx.key)
err := initSessionForDuration(ctx, &tok, ctx.client, p.stokenDuration, ctx.signer)
if err != nil {
return fmt.Errorf("session API client: %w", err)
}
@ -1988,7 +1989,7 @@ func (p *Pool) openDefaultSession(ctx *callContext) error {
}
// sign the token
if err := tok.Sign(*ctx.key); err != nil {
if err := tok.Sign(ctx.signer); err != nil {
return fmt.Errorf("sign token of the opened session: %w", err)
}
@ -2015,10 +2016,10 @@ func (p *Pool) call(ctx *callContext, f func() error) error {
return err
}
// fillAppropriateKey use pool key if caller didn't specify its own.
func (p *Pool) fillAppropriateKey(prm *prmCommon) {
if prm.key == nil {
prm.key = p.key
// fillAppropriateSigner use pool signer if caller didn't specify its own.
func (p *Pool) fillAppropriateSigner(prm *prmCommon) {
if prm.signer == nil {
prm.signer = p.signer
}
}
@ -2033,7 +2034,7 @@ func (p *Pool) PutObject(ctx context.Context, prm PrmObjectPut) (oid.ID, error)
prmCtx.useVerb(session.VerbObjectPut)
prmCtx.useContainer(cnr)
p.fillAppropriateKey(&prm.prmCommon)
p.fillAppropriateSigner(&prm.prmCommon)
var ctxCall callContext
@ -2085,7 +2086,7 @@ func (p *Pool) DeleteObject(ctx context.Context, prm PrmObjectDelete) error {
}
}
p.fillAppropriateKey(&prm.prmCommon)
p.fillAppropriateSigner(&prm.prmCommon)
var cc callContext
@ -2146,7 +2147,7 @@ type ResGetObject struct {
//
// Main return value MUST NOT be processed on an erroneous return.
func (p *Pool) GetObject(ctx context.Context, prm PrmObjectGet) (ResGetObject, error) {
p.fillAppropriateKey(&prm.prmCommon)
p.fillAppropriateSigner(&prm.prmCommon)
var cc callContext
cc.Context = ctx
@ -2169,7 +2170,7 @@ func (p *Pool) GetObject(ctx context.Context, prm PrmObjectGet) (ResGetObject, e
//
// Main return value MUST NOT be processed on an erroneous return.
func (p *Pool) HeadObject(ctx context.Context, prm PrmObjectHead) (object.Object, error) {
p.fillAppropriateKey(&prm.prmCommon)
p.fillAppropriateSigner(&prm.prmCommon)
var cc callContext
@ -2219,7 +2220,7 @@ func (x *ResObjectRange) Close() error {
//
// Main return value MUST NOT be processed on an erroneous return.
func (p *Pool) ObjectRange(ctx context.Context, prm PrmObjectRange) (ResObjectRange, error) {
p.fillAppropriateKey(&prm.prmCommon)
p.fillAppropriateSigner(&prm.prmCommon)
var cc callContext
cc.Context = ctx
@ -2281,7 +2282,7 @@ func (x *ResObjectSearch) Close() {
//
// Main return value MUST NOT be processed on an erroneous return.
func (p *Pool) SearchObjects(ctx context.Context, prm PrmObjectSearch) (ResObjectSearch, error) {
p.fillAppropriateKey(&prm.prmCommon)
p.fillAppropriateSigner(&prm.prmCommon)
var cc callContext

View file

@ -2,16 +2,15 @@ package pool
import (
"context"
"crypto/ecdsa"
"errors"
"strconv"
"testing"
"time"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/nspcc-dev/neofs-sdk-go/object"
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
"github.com/nspcc-dev/neofs-sdk-go/session"
@ -22,13 +21,13 @@ import (
func TestBuildPoolClientFailed(t *testing.T) {
mockClientBuilder := func(addr string) client {
mockCli := newMockClient(addr, *newPrivateKey(t))
mockCli := newMockClient(addr, test.RandomSigner(t))
mockCli.errOnDial()
return mockCli
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: []NodeParam{{1, "peer0", 1}},
}
opts.setClientBuilder(mockClientBuilder)
@ -41,13 +40,13 @@ func TestBuildPoolClientFailed(t *testing.T) {
func TestBuildPoolCreateSessionFailed(t *testing.T) {
clientMockBuilder := func(addr string) client {
mockCli := newMockClient(addr, *newPrivateKey(t))
mockCli := newMockClient(addr, test.RandomSigner(t))
mockCli.errOnCreateSession()
return mockCli
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: []NodeParam{{1, "peer0", 1}},
}
opts.setClientBuilder(clientMockBuilder)
@ -58,36 +57,30 @@ func TestBuildPoolCreateSessionFailed(t *testing.T) {
require.Error(t, err)
}
func newPrivateKey(t *testing.T) *ecdsa.PrivateKey {
p, err := keys.NewPrivateKey()
require.NoError(t, err)
return &p.PrivateKey
}
func TestBuildPoolOneNodeFailed(t *testing.T) {
nodes := []NodeParam{
{1, "peer0", 1},
{2, "peer1", 1},
}
var clientKeys []*ecdsa.PrivateKey
var clientKeys []neofscrypto.Signer
mockClientBuilder := func(addr string) client {
key := newPrivateKey(t)
key := test.RandomSigner(t)
clientKeys = append(clientKeys, key)
if addr == nodes[0].address {
mockCli := newMockClient(addr, *key)
mockCli := newMockClient(addr, key)
mockCli.errOnEndpointInfo()
return mockCli
}
return newMockClient(addr, *key)
return newMockClient(addr, key)
}
log, err := zap.NewProduction()
require.NoError(t, err)
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
clientRebalanceInterval: 1000 * time.Millisecond,
logger: log,
nodeParams: nodes,
@ -100,14 +93,14 @@ func TestBuildPoolOneNodeFailed(t *testing.T) {
require.NoError(t, err)
t.Cleanup(clientPool.Close)
expectedAuthKey := neofsecdsa.PublicKey(clientKeys[1].PublicKey)
expectedAuthKey := clientKeys[1].Public()
condition := func() bool {
cp, err := clientPool.connection()
if err != nil {
return false
}
st, _ := clientPool.cache.Get(formCacheKey(cp.address(), clientPool.key))
return st.AssertAuthKey(&expectedAuthKey)
st, _ := clientPool.cache.Get(formCacheKey(cp.address(), clientPool.signer))
return st.AssertAuthKey(expectedAuthKey)
}
require.Never(t, condition, 900*time.Millisecond, 100*time.Millisecond)
require.Eventually(t, condition, 3*time.Second, 300*time.Millisecond)
@ -115,20 +108,20 @@ func TestBuildPoolOneNodeFailed(t *testing.T) {
func TestBuildPoolZeroNodes(t *testing.T) {
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
}
_, err := NewPool(opts)
require.Error(t, err)
}
func TestOneNode(t *testing.T) {
key1 := newPrivateKey(t)
key1 := test.RandomSigner(t)
mockClientBuilder := func(addr string) client {
return newMockClient(addr, *key1)
return newMockClient(addr, key1)
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: []NodeParam{{1, "peer0", 1}},
}
opts.setClientBuilder(mockClientBuilder)
@ -141,21 +134,20 @@ func TestOneNode(t *testing.T) {
cp, err := pool.connection()
require.NoError(t, err)
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.key))
expectedAuthKey := neofsecdsa.PublicKey(key1.PublicKey)
require.True(t, st.AssertAuthKey(&expectedAuthKey))
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.signer))
require.True(t, st.AssertAuthKey(key1.Public()))
}
func TestTwoNodes(t *testing.T) {
var clientKeys []*ecdsa.PrivateKey
var clientKeys []neofscrypto.Signer
mockClientBuilder := func(addr string) client {
key := newPrivateKey(t)
key := test.RandomSigner(t)
clientKeys = append(clientKeys, key)
return newMockClient(addr, *key)
return newMockClient(addr, key)
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: []NodeParam{
{1, "peer0", 1},
{1, "peer1", 1},
@ -171,14 +163,14 @@ func TestTwoNodes(t *testing.T) {
cp, err := pool.connection()
require.NoError(t, err)
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.key))
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.signer))
require.True(t, assertAuthKeyForAny(st, clientKeys))
}
func assertAuthKeyForAny(st session.Object, clientKeys []*ecdsa.PrivateKey) bool {
func assertAuthKeyForAny(st session.Object, clientKeys []neofscrypto.Signer) bool {
for _, key := range clientKeys {
expectedAuthKey := neofsecdsa.PublicKey(key.PublicKey)
if st.AssertAuthKey(&expectedAuthKey) {
expectedAuthKey := key.Public()
if st.AssertAuthKey(expectedAuthKey) {
return true
}
}
@ -191,23 +183,23 @@ func TestOneOfTwoFailed(t *testing.T) {
{9, "peer1", 1},
}
var clientKeys []*ecdsa.PrivateKey
var clientKeys []neofscrypto.Signer
mockClientBuilder := func(addr string) client {
key := newPrivateKey(t)
key := test.RandomSigner(t)
clientKeys = append(clientKeys, key)
if addr == nodes[0].address {
return newMockClient(addr, *key)
return newMockClient(addr, key)
}
mockCli := newMockClient(addr, *key)
mockCli := newMockClient(addr, key)
mockCli.errOnEndpointInfo()
mockCli.errOnNetworkInfo()
return mockCli
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: nodes,
clientRebalanceInterval: 200 * time.Millisecond,
}
@ -226,23 +218,23 @@ func TestOneOfTwoFailed(t *testing.T) {
for i := 0; i < 5; i++ {
cp, err := pool.connection()
require.NoError(t, err)
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.key))
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.signer))
require.True(t, assertAuthKeyForAny(st, clientKeys))
}
}
func TestTwoFailed(t *testing.T) {
var clientKeys []*ecdsa.PrivateKey
var clientKeys []neofscrypto.Signer
mockClientBuilder := func(addr string) client {
key := newPrivateKey(t)
key := test.RandomSigner(t)
clientKeys = append(clientKeys, key)
mockCli := newMockClient(addr, *key)
mockCli := newMockClient(addr, key)
mockCli.errOnEndpointInfo()
return mockCli
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: []NodeParam{
{1, "peer0", 1},
{1, "peer1", 1},
@ -266,17 +258,16 @@ func TestTwoFailed(t *testing.T) {
}
func TestSessionCache(t *testing.T) {
key := newPrivateKey(t)
expectedAuthKey := neofsecdsa.PublicKey(key.PublicKey)
key := test.RandomSigner(t)
mockClientBuilder := func(addr string) client {
mockCli := newMockClient(addr, *key)
mockCli := newMockClient(addr, key)
mockCli.statusOnGetObject(apistatus.SessionTokenNotFound{})
return mockCli
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: []NodeParam{
{1, "peer0", 1},
},
@ -296,8 +287,8 @@ func TestSessionCache(t *testing.T) {
// cache must contain session token
cp, err := pool.connection()
require.NoError(t, err)
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.key))
require.True(t, st.AssertAuthKey(&expectedAuthKey))
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.signer))
require.True(t, st.AssertAuthKey(key.Public()))
var prm PrmObjectGet
prm.SetAddress(oid.Address{})
@ -309,7 +300,7 @@ func TestSessionCache(t *testing.T) {
// cache must not contain session token
cp, err = pool.connection()
require.NoError(t, err)
_, ok := pool.cache.Get(formCacheKey(cp.address(), pool.key))
_, ok := pool.cache.Get(formCacheKey(cp.address(), pool.signer))
require.False(t, ok)
var prm2 PrmObjectPut
@ -321,8 +312,8 @@ func TestSessionCache(t *testing.T) {
// cache must contain session token
cp, err = pool.connection()
require.NoError(t, err)
st, _ = pool.cache.Get(formCacheKey(cp.address(), pool.key))
require.True(t, st.AssertAuthKey(&expectedAuthKey))
st, _ = pool.cache.Get(formCacheKey(cp.address(), pool.signer))
require.True(t, st.AssertAuthKey(key.Public()))
}
func TestPriority(t *testing.T) {
@ -331,22 +322,22 @@ func TestPriority(t *testing.T) {
{2, "peer1", 100},
}
var clientKeys []*ecdsa.PrivateKey
var clientKeys []neofscrypto.Signer
mockClientBuilder := func(addr string) client {
key := newPrivateKey(t)
key := test.RandomSigner(t)
clientKeys = append(clientKeys, key)
if addr == nodes[0].address {
mockCli := newMockClient(addr, *key)
mockCli := newMockClient(addr, key)
mockCli.errOnEndpointInfo()
return mockCli
}
return newMockClient(addr, *key)
return newMockClient(addr, key)
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: nodes,
clientRebalanceInterval: 1500 * time.Millisecond,
}
@ -361,20 +352,20 @@ func TestPriority(t *testing.T) {
require.NoError(t, err)
t.Cleanup(pool.Close)
expectedAuthKey1 := neofsecdsa.PublicKey(clientKeys[0].PublicKey)
expectedAuthKey1 := clientKeys[0].Public()
firstNode := func() bool {
cp, err := pool.connection()
require.NoError(t, err)
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.key))
return st.AssertAuthKey(&expectedAuthKey1)
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.signer))
return st.AssertAuthKey(expectedAuthKey1)
}
expectedAuthKey2 := neofsecdsa.PublicKey(clientKeys[1].PublicKey)
expectedAuthKey2 := clientKeys[1].Public()
secondNode := func() bool {
cp, err := pool.connection()
require.NoError(t, err)
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.key))
return st.AssertAuthKey(&expectedAuthKey2)
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.signer))
return st.AssertAuthKey(expectedAuthKey2)
}
require.Never(t, secondNode, time.Second, 200*time.Millisecond)
@ -383,15 +374,14 @@ func TestPriority(t *testing.T) {
}
func TestSessionCacheWithKey(t *testing.T) {
key := newPrivateKey(t)
expectedAuthKey := neofsecdsa.PublicKey(key.PublicKey)
key := test.RandomSigner(t)
mockClientBuilder := func(addr string) client {
return newMockClient(addr, *key)
return newMockClient(addr, key)
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: []NodeParam{
{1, "peer0", 1},
},
@ -410,28 +400,28 @@ func TestSessionCacheWithKey(t *testing.T) {
// cache must contain session token
cp, err := pool.connection()
require.NoError(t, err)
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.key))
require.True(t, st.AssertAuthKey(&expectedAuthKey))
st, _ := pool.cache.Get(formCacheKey(cp.address(), pool.signer))
require.True(t, st.AssertAuthKey(key.Public()))
var prm PrmObjectDelete
prm.SetAddress(oid.Address{})
anonKey := newPrivateKey(t)
prm.UseKey(anonKey)
anonKey := test.RandomSigner(t)
prm.UseSigner(anonKey)
err = pool.DeleteObject(ctx, prm)
require.NoError(t, err)
st, _ = pool.cache.Get(formCacheKey(cp.address(), anonKey))
require.True(t, st.AssertAuthKey(&expectedAuthKey))
require.True(t, st.AssertAuthKey(key.Public()))
}
func TestSessionTokenOwner(t *testing.T) {
mockClientBuilder := func(addr string) client {
key := newPrivateKey(t)
return newMockClient(addr, *key)
key := test.RandomSigner(t)
return newMockClient(addr, key)
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: []NodeParam{
{1, "peer0", 1},
},
@ -447,12 +437,12 @@ func TestSessionTokenOwner(t *testing.T) {
require.NoError(t, err)
t.Cleanup(p.Close)
anonKey := newPrivateKey(t)
anonKey := test.RandomSigner(t)
var anonOwner user.ID
user.IDFromKey(&anonOwner, anonKey.PublicKey)
require.NoError(t, user.IDFromSigner(&anonOwner, anonKey))
var prm prmCommon
prm.UseKey(anonKey)
prm.UseSigner(anonKey)
var prmCtx prmContext
prmCtx.useDefaultSession()
@ -472,7 +462,7 @@ func TestSessionTokenOwner(t *testing.T) {
}
func TestWaitPresence(t *testing.T) {
mockCli := newMockClient("", *newPrivateKey(t))
mockCli := newMockClient("", test.RandomSigner(t))
t.Run("context canceled", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
@ -620,23 +610,23 @@ func TestSwitchAfterErrorThreshold(t *testing.T) {
errorThreshold := 5
var clientKeys []*ecdsa.PrivateKey
var clientKeys []neofscrypto.Signer
mockClientBuilder := func(addr string) client {
key := newPrivateKey(t)
key := test.RandomSigner(t)
clientKeys = append(clientKeys, key)
if addr == nodes[0].address {
mockCli := newMockClient(addr, *key)
mockCli := newMockClient(addr, key)
mockCli.setThreshold(uint32(errorThreshold))
mockCli.statusOnGetObject(apistatus.ServerInternal{})
return mockCli
}
return newMockClient(addr, *key)
return newMockClient(addr, key)
}
opts := InitParameters{
key: newPrivateKey(t),
signer: test.RandomSigner(t),
nodeParams: nodes,
clientRebalanceInterval: 30 * time.Second,
}

View file

@ -5,6 +5,7 @@ import (
"math/rand"
"testing"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/stretchr/testify/require"
)
@ -50,10 +51,10 @@ func TestHealthyReweight(t *testing.T) {
cache, err := newCache()
require.NoError(t, err)
client1 := newMockClient(names[0], *newPrivateKey(t))
client1 := newMockClient(names[0], test.RandomSigner(t))
client1.errOnDial()
client2 := newMockClient(names[1], *newPrivateKey(t))
client2 := newMockClient(names[1], test.RandomSigner(t))
inner := &innerPool{
sampler: newSampler(weights, rand.NewSource(0)),
@ -62,7 +63,7 @@ func TestHealthyReweight(t *testing.T) {
p := &Pool{
innerPools: []*innerPool{inner},
cache: cache,
key: newPrivateKey(t),
signer: test.RandomSigner(t),
rebalanceParams: rebalanceParameters{nodesParams: []*nodesParam{{weights: weights}}},
}
@ -81,7 +82,7 @@ func TestHealthyReweight(t *testing.T) {
// enabled first node again
inner.lock.Lock()
inner.clients[0] = newMockClient(names[0], *newPrivateKey(t))
inner.clients[0] = newMockClient(names[0], test.RandomSigner(t))
inner.lock.Unlock()
p.updateInnerNodesHealth(context.TODO(), 0, buffer)
@ -104,8 +105,8 @@ func TestHealthyNoReweight(t *testing.T) {
inner := &innerPool{
sampler: sampl,
clients: []client{
newMockClient(names[0], *newPrivateKey(t)),
newMockClient(names[1], *newPrivateKey(t)),
newMockClient(names[0], test.RandomSigner(t)),
newMockClient(names[1], test.RandomSigner(t)),
},
}
p := &Pool{

View file

@ -1,10 +1,10 @@
package reputationtest
import (
"fmt"
"testing"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/nspcc-dev/neofs-sdk-go/reputation"
)
@ -41,17 +41,11 @@ func GlobalTrust() (v reputation.GlobalTrust) {
return
}
func SignedGlobalTrust() reputation.GlobalTrust {
func SignedGlobalTrust(t *testing.T) reputation.GlobalTrust {
gt := GlobalTrust()
p, err := keys.NewPrivateKey()
if err != nil {
panic(fmt.Sprintf("unexpected error from key creator: %v", err))
}
err = gt.Sign(neofsecdsa.Signer(p.PrivateKey))
if err != nil {
panic(fmt.Sprintf("unexpected error from GlobalTrust.Sign: %v", err))
if err := gt.Sign(test.RandomSigner(t)); err != nil {
t.Fatalf("unexpected error from GlobalTrust.Sign: %v", err)
}
return gt

View file

@ -3,10 +3,9 @@ package reputation_test
import (
"testing"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
v2reputation "github.com/nspcc-dev/neofs-api-go/v2/reputation"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/nspcc-dev/neofs-sdk-go/reputation"
reputationtest "github.com/nspcc-dev/neofs-sdk-go/reputation/test"
"github.com/nspcc-dev/neofs-sdk-go/version"
@ -128,7 +127,7 @@ func TestGlobalTrust_Manager(t *testing.T) {
require.Zero(t, val.Manager())
val = reputationtest.SignedGlobalTrust()
val = reputationtest.SignedGlobalTrust(t)
peer := reputationtest.PeerID()
@ -153,7 +152,7 @@ func TestGlobalTrust_Trust(t *testing.T) {
require.Zero(t, val.Trust())
val = reputationtest.SignedGlobalTrust()
val = reputationtest.SignedGlobalTrust(t)
trust := reputationtest.Trust()
@ -174,14 +173,11 @@ func TestGlobalTrust_Trust(t *testing.T) {
}
func TestGlobalTrust_Sign(t *testing.T) {
k, err := keys.NewPrivateKey()
require.NoError(t, err)
val := reputationtest.GlobalTrust()
require.False(t, val.VerifySignature())
require.NoError(t, val.Sign(neofsecdsa.Signer(k.PrivateKey)))
require.NoError(t, val.Sign(test.RandomSigner(t)))
var valV2 v2reputation.GlobalTrust
val.WriteToV2(&valV2)
@ -195,7 +191,7 @@ func TestGlobalTrust_Sign(t *testing.T) {
}
func TestGlobalTrustEncoding(t *testing.T) {
val := reputationtest.SignedGlobalTrust()
val := reputationtest.SignedGlobalTrust(t)
t.Run("binary", func(t *testing.T) {
data := val.Marshal()

View file

@ -2,7 +2,6 @@ package session
import (
"bytes"
"crypto/ecdsa"
"errors"
"fmt"
@ -10,7 +9,6 @@ import (
"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"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/user"
)
@ -155,13 +153,16 @@ func (x commonData) signedData(w contextWriter) []byte {
return x.fillBody(w).StableMarshal(nil)
}
func (x *commonData) sign(key ecdsa.PrivateKey, w contextWriter) error {
user.IDFromKey(&x.issuer, key.PublicKey)
func (x *commonData) sign(signer neofscrypto.Signer, w contextWriter) error {
if err := user.IDFromSigner(&x.issuer, signer); err != nil {
return err
}
x.issuerSet = true
var sig neofscrypto.Signature
err := sig.Calculate(neofsecdsa.Signer(key), x.signedData(w))
err := sig.Calculate(signer, x.signedData(w))
if err != nil {
return err
}

View file

@ -1,7 +1,6 @@
package session
import (
"crypto/ecdsa"
"errors"
"fmt"
@ -136,8 +135,8 @@ func (x *Container) UnmarshalJSON(data []byte) error {
// expected to be calculated as a final stage of Container formation.
//
// See also VerifySignature.
func (x *Container) Sign(key ecdsa.PrivateKey) error {
return x.sign(key, x.writeContext)
func (x *Container) Sign(signer neofscrypto.Signer) error {
return x.sign(signer, x.writeContext)
}
// VerifySignature checks if Container signature is presented and valid.

View file

@ -12,7 +12,7 @@ import (
v2session "github.com/nspcc-dev/neofs-api-go/v2/session"
cidtest "github.com/nspcc-dev/neofs-sdk-go/container/id/test"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/nspcc-dev/neofs-sdk-go/session"
sessiontest "github.com/nspcc-dev/neofs-sdk-go/session/test"
"github.com/nspcc-dev/neofs-sdk-go/user"
@ -36,7 +36,7 @@ func TestContainerProtocolV2(t *testing.T) {
restoreID()
// Owner
usr := *usertest.ID()
usr := *usertest.ID(t)
var usrV2 refs.OwnerID
usr.WriteToV2(&usrV2)
restoreUser := func() {
@ -55,8 +55,8 @@ func TestContainerProtocolV2(t *testing.T) {
restoreLifetime()
// Session key
signer := randSigner()
authKey := neofsecdsa.PublicKey(signer.PublicKey)
signer := test.RandomSignerRFC6979(t)
authKey := signer.Public()
binAuthKey := make([]byte, authKey.MaxEncodedSize())
binAuthKey = binAuthKey[:authKey.Encode(binAuthKey)]
restoreAuthKey := func() {
@ -139,7 +139,7 @@ func TestContainerProtocolV2(t *testing.T) {
},
breakSign: func(m *v2session.Token) {
id := m.GetBody().GetOwnerID().GetValue()
copy(id, usertest.ID().WalletBytes())
copy(id, usertest.ID(t).WalletBytes())
},
},
{
@ -173,7 +173,7 @@ func TestContainerProtocolV2(t *testing.T) {
},
restore: restoreAuthKey,
assert: func(val session.Container) {
require.True(t, val.AssertAuthKey(&authKey))
require.True(t, val.AssertAuthKey(authKey))
},
breakSign: func(m *v2session.Token) {
body := m.GetBody()
@ -266,12 +266,12 @@ func TestContainer_WriteToV2(t *testing.T) {
})
// Owner/Signature
signer := randSigner()
signer := test.RandomSignerRFC6979(t)
require.NoError(t, val.Sign(signer))
var usr user.ID
user.IDFromKey(&usr, signer.PublicKey)
require.NoError(t, user.IDFromSigner(&usr, signer))
var usrV2 refs.OwnerID
usr.WriteToV2(&usrV2)
@ -430,7 +430,7 @@ func TestContainer_ID(t *testing.T) {
func TestContainer_AssertAuthKey(t *testing.T) {
var x session.Container
key := randPublicKey()
key := test.RandomSignerRFC6979(t).Public()
require.False(t, x.AssertAuthKey(key))
@ -513,10 +513,10 @@ func TestIssuedBy(t *testing.T) {
var (
token session.Container
issuer user.ID
signer = randSigner()
signer = test.RandomSignerRFC6979(t)
)
user.IDFromKey(&issuer, signer.PublicKey)
require.NoError(t, user.IDFromSigner(&issuer, signer))
require.False(t, session.IssuedBy(token, issuer))
@ -526,7 +526,7 @@ func TestIssuedBy(t *testing.T) {
func TestContainer_Issuer(t *testing.T) {
var token session.Container
signer := randSigner()
signer := test.RandomSignerRFC6979(t)
require.Zero(t, token.Issuer())
@ -534,7 +534,7 @@ func TestContainer_Issuer(t *testing.T) {
var issuer user.ID
user.IDFromKey(&issuer, signer.PublicKey)
require.NoError(t, user.IDFromSigner(&issuer, signer))
require.True(t, token.Issuer().Equals(issuer))
}
@ -542,13 +542,13 @@ func TestContainer_Issuer(t *testing.T) {
func TestContainer_Sign(t *testing.T) {
val := sessiontest.Container()
require.NoError(t, val.Sign(randSigner()))
require.NoError(t, val.Sign(test.RandomSignerRFC6979(t)))
require.True(t, val.VerifySignature())
}
func TestContainer_VerifyDataSignature(t *testing.T) {
signer := randSigner()
signer := test.RandomSignerRFC6979(t)
var tok session.Container
@ -556,14 +556,14 @@ func TestContainer_VerifyDataSignature(t *testing.T) {
rand.Read(data)
var sig neofscrypto.Signature
require.NoError(t, sig.Calculate(neofsecdsa.SignerRFC6979(signer), data))
require.NoError(t, sig.Calculate(signer, data))
var sigV2 refs.Signature
sig.WriteToV2(&sigV2)
require.False(t, tok.VerifySessionDataSignature(data, sigV2.GetSign()))
tok.SetAuthKey((*neofsecdsa.PublicKeyRFC6979)(&signer.PublicKey))
tok.SetAuthKey(signer.Public())
require.True(t, tok.VerifySessionDataSignature(data, sigV2.GetSign()))
require.False(t, tok.VerifySessionDataSignature(append(data, 1), sigV2.GetSign()))
require.False(t, tok.VerifySessionDataSignature(data, append(sigV2.GetSign(), 1)))

View file

@ -1,13 +1,13 @@
package session
import (
"crypto/ecdsa"
"errors"
"fmt"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
"github.com/nspcc-dev/neofs-api-go/v2/session"
cid "github.com/nspcc-dev/neofs-sdk-go/container/id"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
)
@ -162,8 +162,8 @@ func (x *Object) UnmarshalJSON(data []byte) error {
// expected to be calculated as a final stage of Object formation.
//
// See also VerifySignature.
func (x *Object) Sign(key ecdsa.PrivateKey) error {
return x.sign(key, x.writeContext)
func (x *Object) Sign(signer neofscrypto.Signer) error {
return x.sign(signer, x.writeContext)
}
// VerifySignature checks if Object signature is presented and valid.

View file

@ -1,20 +1,17 @@
package session_test
import (
"crypto/ecdsa"
"fmt"
"math"
"math/rand"
"testing"
"github.com/google/uuid"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
v2session "github.com/nspcc-dev/neofs-api-go/v2/session"
cidtest "github.com/nspcc-dev/neofs-sdk-go/container/id/test"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
oidtest "github.com/nspcc-dev/neofs-sdk-go/object/id/test"
"github.com/nspcc-dev/neofs-sdk-go/session"
sessiontest "github.com/nspcc-dev/neofs-sdk-go/session/test"
@ -23,20 +20,6 @@ import (
"github.com/stretchr/testify/require"
)
func randSigner() ecdsa.PrivateKey {
k, err := keys.NewPrivateKey()
if err != nil {
panic(fmt.Sprintf("generate private key: %v", err))
}
return k.PrivateKey
}
func randPublicKey() neofscrypto.PublicKey {
k := randSigner().PublicKey
return (*neofsecdsa.PublicKey)(&k)
}
func TestObjectProtocolV2(t *testing.T) {
var validV2 v2session.Token
@ -53,7 +36,7 @@ func TestObjectProtocolV2(t *testing.T) {
restoreID()
// Owner
usr := *usertest.ID()
usr := *usertest.ID(t)
var usrV2 refs.OwnerID
usr.WriteToV2(&usrV2)
restoreUser := func() {
@ -72,8 +55,8 @@ func TestObjectProtocolV2(t *testing.T) {
restoreLifetime()
// Session key
signer := randSigner()
authKey := neofsecdsa.PublicKey(signer.PublicKey)
signer := test.RandomSignerRFC6979(t)
authKey := signer.Public()
binAuthKey := make([]byte, authKey.MaxEncodedSize())
binAuthKey = binAuthKey[:authKey.Encode(binAuthKey)]
restoreAuthKey := func() {
@ -161,7 +144,7 @@ func TestObjectProtocolV2(t *testing.T) {
},
breakSign: func(m *v2session.Token) {
id := m.GetBody().GetOwnerID().GetValue()
copy(id, usertest.ID().WalletBytes())
copy(id, usertest.ID(t).WalletBytes())
},
},
{
@ -195,7 +178,7 @@ func TestObjectProtocolV2(t *testing.T) {
},
restore: restoreAuthKey,
assert: func(val session.Object) {
require.True(t, val.AssertAuthKey(&authKey))
require.True(t, val.AssertAuthKey(authKey))
},
breakSign: func(m *v2session.Token) {
body := m.GetBody()
@ -293,12 +276,12 @@ func TestObject_WriteToV2(t *testing.T) {
})
// Owner/Signature
signer := randSigner()
signer := test.RandomSignerRFC6979(t)
require.NoError(t, val.Sign(signer))
var usr user.ID
user.IDFromKey(&usr, signer.PublicKey)
require.NoError(t, user.IDFromSigner(&usr, signer))
var usrV2 refs.OwnerID
usr.WriteToV2(&usrV2)
@ -540,7 +523,7 @@ func TestObject_ID(t *testing.T) {
func TestObject_AssertAuthKey(t *testing.T) {
var x session.Object
key := randPublicKey()
key := test.RandomSignerRFC6979(t).Public()
require.False(t, x.AssertAuthKey(key))
@ -626,7 +609,7 @@ func TestObject_AssertVerb(t *testing.T) {
func TestObject_Issuer(t *testing.T) {
var token session.Object
signer := randSigner()
signer := test.RandomSignerRFC6979(t)
require.Zero(t, token.Issuer())
@ -634,7 +617,7 @@ func TestObject_Issuer(t *testing.T) {
var issuer user.ID
user.IDFromKey(&issuer, signer.PublicKey)
require.NoError(t, user.IDFromSigner(&issuer, signer))
require.True(t, token.Issuer().Equals(issuer))
}
@ -642,7 +625,7 @@ func TestObject_Issuer(t *testing.T) {
func TestObject_Sign(t *testing.T) {
val := sessiontest.Object()
require.NoError(t, val.Sign(randSigner()))
require.NoError(t, val.Sign(test.RandomSignerRFC6979(t)))
require.True(t, val.VerifySignature())
}

View file

@ -6,24 +6,13 @@ import (
"crypto/rand"
"github.com/google/uuid"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
cidtest "github.com/nspcc-dev/neofs-sdk-go/container/id/test"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
neofsecdsa "github.com/nspcc-dev/neofs-sdk-go/crypto/ecdsa"
oidtest "github.com/nspcc-dev/neofs-sdk-go/object/id/test"
"github.com/nspcc-dev/neofs-sdk-go/session"
)
var p ecdsa.PrivateKey
func init() {
k, err := keys.NewPrivateKey()
if err != nil {
panic(err)
}
p = k.PrivateKey
}
// Container returns random session.Container.
//
// Resulting token is unsigned.
@ -49,10 +38,10 @@ func Container() *session.Container {
// ContainerSigned returns signed random session.Container.
//
// Panics if token could not be signed (actually unexpected).
func ContainerSigned() *session.Container {
func ContainerSigned(signer neofscrypto.Signer) *session.Container {
tok := Container()
err := tok.Sign(p)
err := tok.Sign(signer)
if err != nil {
panic(err)
}
@ -86,10 +75,10 @@ func Object() *session.Object {
// ObjectSigned returns signed random session.Object.
//
// Panics if token could not be signed (actually unexpected).
func ObjectSigned() *session.Object {
func ObjectSigned(signer neofscrypto.Signer) *session.Object {
tok := Object()
err := tok.Sign(p)
err := tok.Sign(signer)
if err != nil {
panic(err)
}

View file

@ -29,7 +29,7 @@ func TestInfo_SetID(t *testing.T) {
}
func TestInfo_SetOwner(t *testing.T) {
id := *usertest.ID()
id := *usertest.ID(t)
var info Info
info.SetOwner(id)
@ -39,7 +39,7 @@ func TestInfo_SetOwner(t *testing.T) {
}
func TestInfo_Marshal(t *testing.T) {
info := subnettest.Info()
info := subnettest.Info(t)
var info2 Info
require.NoError(t, info2.Unmarshal(info.Marshal()))

View file

@ -1,14 +1,16 @@
package subnettest
import (
"testing"
"github.com/nspcc-dev/neofs-sdk-go/subnet"
subnetidtest "github.com/nspcc-dev/neofs-sdk-go/subnet/id/test"
usertest "github.com/nspcc-dev/neofs-sdk-go/user/test"
)
// Info generates and returns random subnet.Info.
func Info() (x subnet.Info) {
func Info(t *testing.T) (x subnet.Info) {
x.SetID(subnetidtest.ID())
x.SetOwner(*usertest.ID())
x.SetOwner(*usertest.ID(t))
return
}

View file

@ -48,7 +48,7 @@ func TestID_SetScriptHash(t *testing.T) {
}
func TestV2_ID(t *testing.T) {
id := *usertest.ID()
id := *usertest.ID(t)
var m refs.OwnerID
var id2 ID
@ -91,7 +91,7 @@ func TestV2_ID(t *testing.T) {
}
func TestID_EncodeToString(t *testing.T) {
id := *usertest.ID()
id := *usertest.ID(t)
s := id.EncodeToString()
@ -110,8 +110,8 @@ func TestID_EncodeToString(t *testing.T) {
}
func TestID_Equal(t *testing.T) {
id1 := *usertest.ID()
id2 := *usertest.ID()
id1 := *usertest.ID(t)
id2 := *usertest.ID(t)
id3 := id1
require.True(t, id1.Equals(id1)) // self-equality

View file

@ -1,19 +1,18 @@
package usertest
import (
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"testing"
"github.com/nspcc-dev/neofs-sdk-go/crypto/test"
"github.com/nspcc-dev/neofs-sdk-go/user"
)
// ID returns random user.ID.
func ID() *user.ID {
key, err := keys.NewPrivateKey()
if err != nil {
panic(err)
}
func ID(tb testing.TB) *user.ID {
var x user.ID
user.IDFromKey(&x, key.PrivateKey.PublicKey)
if err := user.IDFromSigner(&x, test.RandomSigner(tb)); err != nil {
return nil
}
return &x
}

View file

@ -1,12 +1,29 @@
package user
import (
"crypto/ecdsa"
"fmt"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
neofscrypto "github.com/nspcc-dev/neofs-sdk-go/crypto"
)
// IDFromKey forms the ID using script hash calculated for the given key.
func IDFromKey(id *ID, key ecdsa.PublicKey) {
id.SetScriptHash((*keys.PublicKey)(&key).GetScriptHash())
func IDFromKey(id *ID, key []byte) error {
var pk keys.PublicKey
if err := pk.DecodeBytes(key); err != nil {
return fmt.Errorf("IDFromKey %v", err)
}
id.SetScriptHash(pk.GetScriptHash())
return nil
}
// IDFromSigner forms the ID using script hash calculated for the given key.
func IDFromSigner(id *ID, signer neofscrypto.Signer) error {
public := signer.Public()
key := make([]byte, public.MaxEncodedSize())
key = key[:public.Encode(key)]
return IDFromKey(id, key)
}

View file

@ -1,7 +1,6 @@
package user_test
import (
"crypto/ecdsa"
"crypto/elliptic"
"encoding/hex"
"testing"
@ -18,7 +17,7 @@ func TestIDFromKey(t *testing.T) {
var id user.ID
user.IDFromKey(&id, ecdsa.PublicKey{Curve: elliptic.P256(), X: x, Y: y})
require.NoError(t, user.IDFromKey(&id, rawPub))
require.Equal(t, "NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs", id.EncodeToString())
}