github.com/tenywen/fabric@v1.0.0-beta.0.20170620030522-a5b1ed380643/msp/msp_test.go (about)

     1  /*
     2  Copyright IBM Corp. 2017 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package msp
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"os"
    23  	"path/filepath"
    24  	"reflect"
    25  	"testing"
    26  
    27  	"github.com/golang/protobuf/proto"
    28  	"github.com/hyperledger/fabric/bccsp"
    29  	"github.com/hyperledger/fabric/bccsp/sw"
    30  	"github.com/hyperledger/fabric/core/config"
    31  	"github.com/hyperledger/fabric/protos/msp"
    32  	"github.com/stretchr/testify/assert"
    33  )
    34  
    35  var notACert = `-----BEGIN X509 CRL-----
    36  MIIBYzCCAQgCAQEwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMCVVMxEzARBgNVBAgT
    37  CkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xHzAdBgNVBAoTFklu
    38  dGVybmV0IFdpZGdldHMsIEluYy4xDDAKBgNVBAsTA1dXVzEUMBIGA1UEAxMLZXhh
    39  bXBsZS5jb20XDTE3MDEyMzIwNTYyMFoXDTE3MDEyNjIwNTYyMFowJzAlAhQERXCx
    40  LHROap1vM3CV40EHOghPTBcNMTcwMTIzMjA0NzMxWqAvMC0wHwYDVR0jBBgwFoAU
    41  F2dCPaqegj/ExR2fW8OZ0bWcSBAwCgYDVR0UBAMCAQgwCgYIKoZIzj0EAwIDSQAw
    42  RgIhAOTTpQYkGO+gwVe1LQOcNMD5fzFViOwBUraMrk6dRMlmAiEA8z2dpXKGwHrj
    43  FRBbKkDnSpaVcZgjns+mLdHV2JkF0gk=
    44  -----END X509 CRL-----`
    45  
    46  func TestMSPParsers(t *testing.T) {
    47  	_, _, err := localMsp.(*bccspmsp).getIdentityFromConf(nil)
    48  	assert.Error(t, err)
    49  	_, _, err = localMsp.(*bccspmsp).getIdentityFromConf([]byte("barf"))
    50  	assert.Error(t, err)
    51  	_, _, err = localMsp.(*bccspmsp).getIdentityFromConf([]byte(notACert))
    52  	assert.Error(t, err)
    53  
    54  	_, err = localMsp.(*bccspmsp).getSigningIdentityFromConf(nil)
    55  	assert.Error(t, err)
    56  
    57  	sigid := &msp.SigningIdentityInfo{PublicSigner: []byte("barf"), PrivateSigner: nil}
    58  	_, err = localMsp.(*bccspmsp).getSigningIdentityFromConf(sigid)
    59  
    60  	keyinfo := &msp.KeyInfo{KeyIdentifier: "PEER", KeyMaterial: nil}
    61  	sigid = &msp.SigningIdentityInfo{PublicSigner: []byte("barf"), PrivateSigner: keyinfo}
    62  	_, err = localMsp.(*bccspmsp).getSigningIdentityFromConf(sigid)
    63  	assert.Error(t, err)
    64  }
    65  
    66  func TestMSPSetupNoCryptoConf(t *testing.T) {
    67  	mspDir, err := config.GetDevMspDir()
    68  	if err != nil {
    69  		fmt.Printf("Errog getting DevMspDir: %s", err)
    70  		os.Exit(-1)
    71  	}
    72  
    73  	conf, err := GetLocalMspConfig(mspDir, nil, "DEFAULT")
    74  	if err != nil {
    75  		fmt.Printf("Setup should have succeeded, got err %s instead", err)
    76  		os.Exit(-1)
    77  	}
    78  
    79  	mspconf := &msp.FabricMSPConfig{}
    80  	err = proto.Unmarshal(conf.Config, mspconf)
    81  	assert.NoError(t, err)
    82  
    83  	// here we test the case of an MSP configuration
    84  	// where the hash function to be used to obtain
    85  	// the identity identifier is unspecified - a
    86  	// sane default should be picked
    87  	mspconf.CryptoConfig.IdentityIdentifierHashFunction = ""
    88  	b, err := proto.Marshal(mspconf)
    89  	assert.NoError(t, err)
    90  	conf.Config = b
    91  	newmsp, err := NewBccspMsp()
    92  	assert.NoError(t, err)
    93  	err = newmsp.Setup(conf)
    94  	assert.NoError(t, err)
    95  
    96  	// here we test the case of an MSP configuration
    97  	// where the hash function to be used to compute
    98  	// signatures is unspecified - a sane default
    99  	// should be picked
   100  	mspconf.CryptoConfig.SignatureHashFamily = ""
   101  	b, err = proto.Marshal(mspconf)
   102  	assert.NoError(t, err)
   103  	conf.Config = b
   104  	newmsp, err = NewBccspMsp()
   105  	assert.NoError(t, err)
   106  	err = newmsp.Setup(conf)
   107  	assert.NoError(t, err)
   108  
   109  	// here we test the case of an MSP configuration
   110  	// that has NO crypto configuration specified;
   111  	// the code will use appropriate defaults
   112  	mspconf.CryptoConfig = nil
   113  	b, err = proto.Marshal(mspconf)
   114  	assert.NoError(t, err)
   115  	conf.Config = b
   116  	newmsp, err = NewBccspMsp()
   117  	assert.NoError(t, err)
   118  	err = newmsp.Setup(conf)
   119  	assert.NoError(t, err)
   120  }
   121  
   122  func TestGetters(t *testing.T) {
   123  	typ := localMsp.GetType()
   124  	assert.Equal(t, typ, FABRIC)
   125  	assert.NotNil(t, localMsp.GetRootCerts())
   126  	assert.NotNil(t, localMsp.GetIntermediateCerts())
   127  }
   128  
   129  func TestMSPSetupBad(t *testing.T) {
   130  	_, err := GetLocalMspConfig("barf", nil, "DEFAULT")
   131  	if err == nil {
   132  		t.Fatalf("Setup should have failed on an invalid config file")
   133  		return
   134  	}
   135  
   136  	mgr := NewMSPManager()
   137  	err = mgr.Setup(nil)
   138  	assert.Error(t, err)
   139  	err = mgr.Setup([]MSP{})
   140  	assert.Error(t, err)
   141  }
   142  
   143  func TestDoubleSetup(t *testing.T) {
   144  	// note that we've already called setup once on this
   145  	err := mspMgr.Setup(nil)
   146  	assert.NoError(t, err)
   147  }
   148  
   149  type bccspNoKeyLookupKS struct {
   150  	bccsp.BCCSP
   151  }
   152  
   153  func (*bccspNoKeyLookupKS) GetKey(ski []byte) (k bccsp.Key, err error) {
   154  	return nil, errors.New("not found")
   155  }
   156  
   157  func TestNotFoundInBCCSP(t *testing.T) {
   158  	dir, err := config.GetDevMspDir()
   159  	assert.NoError(t, err)
   160  	conf, err := GetLocalMspConfig(dir, nil, "DEFAULT")
   161  
   162  	assert.NoError(t, err)
   163  
   164  	thisMSP, err := NewBccspMsp()
   165  	assert.NoError(t, err)
   166  	ks, err := sw.NewFileBasedKeyStore(nil, filepath.Join(dir, "keystore"), true)
   167  	assert.NoError(t, err)
   168  	csp, err := sw.New(256, "SHA2", ks)
   169  	assert.NoError(t, err)
   170  	thisMSP.(*bccspmsp).bccsp = &bccspNoKeyLookupKS{csp}
   171  
   172  	err = thisMSP.Setup(conf)
   173  	assert.Error(t, err)
   174  	assert.Contains(t, "KeyMaterial not found in SigningIdentityInfo", err.Error())
   175  }
   176  
   177  func TestGetIdentities(t *testing.T) {
   178  	_, err := localMsp.GetDefaultSigningIdentity()
   179  	if err != nil {
   180  		t.Fatalf("GetDefaultSigningIdentity failed with err %s", err)
   181  		return
   182  	}
   183  }
   184  
   185  func TestDeserializeIdentityFails(t *testing.T) {
   186  	_, err := localMsp.DeserializeIdentity([]byte("barf"))
   187  	assert.Error(t, err)
   188  
   189  	id := &msp.SerializedIdentity{Mspid: "DEFAULT", IdBytes: []byte("barfr")}
   190  	b, err := proto.Marshal(id)
   191  	assert.NoError(t, err)
   192  	_, err = localMsp.DeserializeIdentity(b)
   193  	assert.Error(t, err)
   194  
   195  	id = &msp.SerializedIdentity{Mspid: "DEFAULT", IdBytes: []byte(notACert)}
   196  	b, err = proto.Marshal(id)
   197  	assert.NoError(t, err)
   198  	_, err = localMsp.DeserializeIdentity(b)
   199  	assert.Error(t, err)
   200  }
   201  
   202  func TestGetSigningIdentityFromVerifyingMSP(t *testing.T) {
   203  	mspDir, err := config.GetDevMspDir()
   204  	if err != nil {
   205  		fmt.Printf("Errog getting DevMspDir: %s", err)
   206  		os.Exit(-1)
   207  	}
   208  
   209  	conf, err = GetVerifyingMspConfig(mspDir, "DEFAULT")
   210  	if err != nil {
   211  		fmt.Printf("Setup should have succeeded, got err %s instead", err)
   212  		os.Exit(-1)
   213  	}
   214  
   215  	newmsp, err := NewBccspMsp()
   216  	assert.NoError(t, err)
   217  	err = newmsp.Setup(conf)
   218  	assert.NoError(t, err)
   219  
   220  	_, err = newmsp.GetDefaultSigningIdentity()
   221  	assert.Error(t, err)
   222  	_, err = newmsp.GetSigningIdentity(nil)
   223  	assert.Error(t, err)
   224  }
   225  
   226  func TestValidateDefaultSigningIdentity(t *testing.T) {
   227  	id, err := localMsp.GetDefaultSigningIdentity()
   228  	assert.NoError(t, err)
   229  
   230  	err = localMsp.Validate(id.GetPublicVersion())
   231  	assert.NoError(t, err)
   232  }
   233  
   234  func TestSerializeIdentities(t *testing.T) {
   235  	id, err := localMsp.GetDefaultSigningIdentity()
   236  	if err != nil {
   237  		t.Fatalf("GetSigningIdentity should have succeeded, got err %s", err)
   238  		return
   239  	}
   240  
   241  	serializedID, err := id.Serialize()
   242  	if err != nil {
   243  		t.Fatalf("Serialize should have succeeded, got err %s", err)
   244  		return
   245  	}
   246  
   247  	idBack, err := localMsp.DeserializeIdentity(serializedID)
   248  	if err != nil {
   249  		t.Fatalf("DeserializeIdentity should have succeeded, got err %s", err)
   250  		return
   251  	}
   252  
   253  	err = localMsp.Validate(idBack)
   254  	if err != nil {
   255  		t.Fatalf("The identity should be valid, got err %s", err)
   256  		return
   257  	}
   258  
   259  	if !reflect.DeepEqual(id.GetPublicVersion(), idBack) {
   260  		t.Fatalf("Identities should be equal (%s) (%s)", id, idBack)
   261  		return
   262  	}
   263  }
   264  
   265  func TestValidateCAIdentity(t *testing.T) {
   266  	caID := getIdentity(t, cacerts)
   267  
   268  	err := localMsp.Validate(caID)
   269  	assert.Error(t, err)
   270  }
   271  
   272  func TestValidateAdminIdentity(t *testing.T) {
   273  	caID := getIdentity(t, admincerts)
   274  
   275  	err := localMsp.Validate(caID)
   276  	assert.NoError(t, err)
   277  }
   278  
   279  func TestSerializeIdentitiesWithWrongMSP(t *testing.T) {
   280  	id, err := localMsp.GetDefaultSigningIdentity()
   281  	if err != nil {
   282  		t.Fatalf("GetSigningIdentity should have succeeded, got err %s", err)
   283  		return
   284  	}
   285  
   286  	serializedID, err := id.Serialize()
   287  	if err != nil {
   288  		t.Fatalf("Serialize should have succeeded, got err %s", err)
   289  		return
   290  	}
   291  
   292  	sid := &msp.SerializedIdentity{}
   293  	err = proto.Unmarshal(serializedID, sid)
   294  	assert.NoError(t, err)
   295  
   296  	sid.Mspid += "BARF"
   297  
   298  	serializedID, err = proto.Marshal(sid)
   299  	assert.NoError(t, err)
   300  
   301  	_, err = localMsp.DeserializeIdentity(serializedID)
   302  	assert.Error(t, err)
   303  }
   304  
   305  func TestSerializeIdentitiesWithMSPManager(t *testing.T) {
   306  	id, err := localMsp.GetDefaultSigningIdentity()
   307  	if err != nil {
   308  		t.Fatalf("GetSigningIdentity should have succeeded, got err %s", err)
   309  		return
   310  	}
   311  
   312  	serializedID, err := id.Serialize()
   313  	if err != nil {
   314  		t.Fatalf("Serialize should have succeeded, got err %s", err)
   315  		return
   316  	}
   317  
   318  	_, err = mspMgr.DeserializeIdentity(serializedID)
   319  	assert.NoError(t, err)
   320  
   321  	sid := &msp.SerializedIdentity{}
   322  	err = proto.Unmarshal(serializedID, sid)
   323  	assert.NoError(t, err)
   324  
   325  	sid.Mspid += "BARF"
   326  
   327  	serializedID, err = proto.Marshal(sid)
   328  	assert.NoError(t, err)
   329  
   330  	_, err = mspMgr.DeserializeIdentity(serializedID)
   331  	assert.Error(t, err)
   332  }
   333  
   334  func TestIdentitiesGetters(t *testing.T) {
   335  	id, err := localMsp.GetDefaultSigningIdentity()
   336  	if err != nil {
   337  		t.Fatalf("GetSigningIdentity should have succeeded, got err %s", err)
   338  		return
   339  	}
   340  
   341  	idid := id.GetIdentifier()
   342  	assert.NotNil(t, idid)
   343  	mspid := id.GetMSPIdentifier()
   344  	assert.NotNil(t, mspid)
   345  }
   346  
   347  func TestSignAndVerify(t *testing.T) {
   348  	id, err := localMsp.GetDefaultSigningIdentity()
   349  	if err != nil {
   350  		t.Fatalf("GetSigningIdentity should have succeeded")
   351  		return
   352  	}
   353  
   354  	serializedID, err := id.Serialize()
   355  	if err != nil {
   356  		t.Fatalf("Serialize should have succeeded")
   357  		return
   358  	}
   359  
   360  	idBack, err := localMsp.DeserializeIdentity(serializedID)
   361  	if err != nil {
   362  		t.Fatalf("DeserializeIdentity should have succeeded")
   363  		return
   364  	}
   365  
   366  	msg := []byte("foo")
   367  	sig, err := id.Sign(msg)
   368  	if err != nil {
   369  		t.Fatalf("Sign should have succeeded")
   370  		return
   371  	}
   372  
   373  	err = id.Verify(msg, sig)
   374  	if err != nil {
   375  		t.Fatalf("The signature should be valid")
   376  		return
   377  	}
   378  
   379  	err = idBack.Verify(msg, sig)
   380  	if err != nil {
   381  		t.Fatalf("The signature should be valid")
   382  		return
   383  	}
   384  
   385  	err = id.Verify(msg[1:], sig)
   386  	assert.Error(t, err)
   387  	err = id.Verify(msg, sig[1:])
   388  	assert.Error(t, err)
   389  }
   390  
   391  func TestSignAndVerifyFailures(t *testing.T) {
   392  	msg := []byte("foo")
   393  
   394  	id, err := localMspBad.GetDefaultSigningIdentity()
   395  	if err != nil {
   396  		t.Fatalf("GetSigningIdentity should have succeeded")
   397  		return
   398  	}
   399  
   400  	hash := id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily
   401  	id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = "barf"
   402  
   403  	sig, err := id.Sign(msg)
   404  	assert.Error(t, err)
   405  
   406  	id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = hash
   407  
   408  	sig, err = id.Sign(msg)
   409  	if err != nil {
   410  		t.Fatalf("Sign should have succeeded")
   411  		return
   412  	}
   413  
   414  	id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = "barf"
   415  
   416  	err = id.Verify(msg, sig)
   417  	assert.Error(t, err)
   418  
   419  	id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = hash
   420  }
   421  
   422  func TestSignAndVerifyOtherHash(t *testing.T) {
   423  	id, err := localMsp.GetDefaultSigningIdentity()
   424  	if err != nil {
   425  		t.Fatalf("GetSigningIdentity should have succeeded")
   426  		return
   427  	}
   428  
   429  	hash := id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily
   430  	id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = bccsp.SHA3
   431  
   432  	msg := []byte("foo")
   433  	sig, err := id.Sign(msg)
   434  	if err != nil {
   435  		t.Fatalf("Sign should have succeeded")
   436  		return
   437  	}
   438  
   439  	err = id.Verify(msg, sig)
   440  	assert.NoError(t, err)
   441  
   442  	id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = hash
   443  }
   444  
   445  func TestSignAndVerify_longMessage(t *testing.T) {
   446  	id, err := localMsp.GetDefaultSigningIdentity()
   447  	if err != nil {
   448  		t.Fatalf("GetSigningIdentity should have succeeded")
   449  		return
   450  	}
   451  
   452  	serializedID, err := id.Serialize()
   453  	if err != nil {
   454  		t.Fatalf("Serialize should have succeeded")
   455  		return
   456  	}
   457  
   458  	idBack, err := localMsp.DeserializeIdentity(serializedID)
   459  	if err != nil {
   460  		t.Fatalf("DeserializeIdentity should have succeeded")
   461  		return
   462  	}
   463  
   464  	msg := []byte("ABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFG")
   465  	sig, err := id.Sign(msg)
   466  	if err != nil {
   467  		t.Fatalf("Sign should have succeeded")
   468  		return
   469  	}
   470  
   471  	err = id.Verify(msg, sig)
   472  	if err != nil {
   473  		t.Fatalf("The signature should be valid")
   474  		return
   475  	}
   476  
   477  	err = idBack.Verify(msg, sig)
   478  	if err != nil {
   479  		t.Fatalf("The signature should be valid")
   480  		return
   481  	}
   482  }
   483  
   484  func TestGetOU(t *testing.T) {
   485  	id, err := localMsp.GetDefaultSigningIdentity()
   486  	if err != nil {
   487  		t.Fatalf("GetSigningIdentity should have succeeded")
   488  		return
   489  	}
   490  
   491  	assert.Equal(t, "COP", id.GetOrganizationalUnits()[0].OrganizationalUnitIdentifier)
   492  }
   493  
   494  func TestGetOUFail(t *testing.T) {
   495  	id, err := localMspBad.GetDefaultSigningIdentity()
   496  	if err != nil {
   497  		t.Fatalf("GetSigningIdentity should have succeeded")
   498  		return
   499  	}
   500  
   501  	certTmp := id.(*signingidentity).cert
   502  	id.(*signingidentity).cert = nil
   503  	ou := id.GetOrganizationalUnits()
   504  	assert.Nil(t, ou)
   505  
   506  	id.(*signingidentity).cert = certTmp
   507  
   508  	opts := id.(*signingidentity).msp.opts
   509  	id.(*signingidentity).msp.opts = nil
   510  	ou = id.GetOrganizationalUnits()
   511  	assert.Nil(t, ou)
   512  
   513  	id.(*signingidentity).msp.opts = opts
   514  }
   515  
   516  func TestCertificationIdentifierComputation(t *testing.T) {
   517  	id, err := localMsp.GetDefaultSigningIdentity()
   518  	assert.NoError(t, err)
   519  
   520  	chain, err := localMsp.(*bccspmsp).getCertificationChain(id.GetPublicVersion())
   521  	assert.NoError(t, err)
   522  
   523  	// Hash the chain
   524  	// Use the hash of the identity's certificate as id in the IdentityIdentifier
   525  	hashOpt, err := bccsp.GetHashOpt(localMsp.(*bccspmsp).cryptoConfig.IdentityIdentifierHashFunction)
   526  	assert.NoError(t, err)
   527  
   528  	hf, err := localMsp.(*bccspmsp).bccsp.GetHash(hashOpt)
   529  	assert.NoError(t, err)
   530  	// Skipping first cert because it belongs to the identity
   531  	for i := 1; i < len(chain); i++ {
   532  		hf.Write(chain[i].Raw)
   533  	}
   534  	sum := hf.Sum(nil)
   535  
   536  	assert.Equal(t, sum, id.GetOrganizationalUnits()[0].CertifiersIdentifier)
   537  }
   538  
   539  func TestOUPolicyPrincipal(t *testing.T) {
   540  	id, err := localMsp.GetDefaultSigningIdentity()
   541  	assert.NoError(t, err)
   542  
   543  	cid, err := localMsp.(*bccspmsp).getCertificationChainIdentifier(id.GetPublicVersion())
   544  	assert.NoError(t, err)
   545  
   546  	ou := &msp.OrganizationUnit{
   547  		OrganizationalUnitIdentifier: "COP",
   548  		MspIdentifier:                "DEFAULT",
   549  		CertifiersIdentifier:         cid,
   550  	}
   551  	bytes, err := proto.Marshal(ou)
   552  	assert.NoError(t, err)
   553  
   554  	principal := &msp.MSPPrincipal{
   555  		PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
   556  		Principal:               bytes,
   557  	}
   558  
   559  	err = id.SatisfiesPrincipal(principal)
   560  	assert.NoError(t, err)
   561  }
   562  
   563  func TestOUPolicyPrincipalBadPrincipal(t *testing.T) {
   564  	id, err := localMsp.GetDefaultSigningIdentity()
   565  	assert.NoError(t, err)
   566  
   567  	principal := &msp.MSPPrincipal{
   568  		PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
   569  		Principal:               []byte("barf"),
   570  	}
   571  
   572  	err = id.SatisfiesPrincipal(principal)
   573  	assert.Error(t, err)
   574  }
   575  
   576  func TestOUPolicyPrincipalBadMSPID(t *testing.T) {
   577  	id, err := localMsp.GetDefaultSigningIdentity()
   578  	assert.NoError(t, err)
   579  
   580  	cid, err := localMsp.(*bccspmsp).getCertificationChainIdentifier(id.GetPublicVersion())
   581  	assert.NoError(t, err)
   582  
   583  	ou := &msp.OrganizationUnit{
   584  		OrganizationalUnitIdentifier: "COP",
   585  		MspIdentifier:                "DEFAULTbarfbarf",
   586  		CertifiersIdentifier:         cid,
   587  	}
   588  	bytes, err := proto.Marshal(ou)
   589  	assert.NoError(t, err)
   590  
   591  	principal := &msp.MSPPrincipal{
   592  		PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
   593  		Principal:               bytes,
   594  	}
   595  
   596  	err = id.SatisfiesPrincipal(principal)
   597  	assert.Error(t, err)
   598  }
   599  
   600  func TestOUPolicyPrincipalBadPath(t *testing.T) {
   601  	id, err := localMsp.GetDefaultSigningIdentity()
   602  	assert.NoError(t, err)
   603  
   604  	ou := &msp.OrganizationUnit{
   605  		OrganizationalUnitIdentifier: "COP",
   606  		MspIdentifier:                "DEFAULT",
   607  		CertifiersIdentifier:         nil,
   608  	}
   609  	bytes, err := proto.Marshal(ou)
   610  	assert.NoError(t, err)
   611  
   612  	principal := &msp.MSPPrincipal{
   613  		PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
   614  		Principal:               bytes,
   615  	}
   616  
   617  	err = id.SatisfiesPrincipal(principal)
   618  	assert.Error(t, err)
   619  
   620  	ou = &msp.OrganizationUnit{
   621  		OrganizationalUnitIdentifier: "COP",
   622  		MspIdentifier:                "DEFAULT",
   623  		CertifiersIdentifier:         []byte{0, 1, 2, 3, 4},
   624  	}
   625  	bytes, err = proto.Marshal(ou)
   626  	assert.NoError(t, err)
   627  
   628  	principal = &msp.MSPPrincipal{
   629  		PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
   630  		Principal:               bytes,
   631  	}
   632  
   633  	err = id.SatisfiesPrincipal(principal)
   634  	assert.Error(t, err)
   635  }
   636  
   637  func TestPolicyPrincipalBogusType(t *testing.T) {
   638  	id, err := localMsp.GetDefaultSigningIdentity()
   639  	assert.NoError(t, err)
   640  
   641  	principalBytes, err := proto.Marshal(&msp.MSPRole{Role: 35, MspIdentifier: "DEFAULT"})
   642  	assert.NoError(t, err)
   643  
   644  	principal := &msp.MSPPrincipal{
   645  		PrincipalClassification: 35,
   646  		Principal:               principalBytes}
   647  
   648  	err = id.SatisfiesPrincipal(principal)
   649  	assert.Error(t, err)
   650  }
   651  
   652  func TestPolicyPrincipalBogusRole(t *testing.T) {
   653  	id, err := localMsp.GetDefaultSigningIdentity()
   654  	assert.NoError(t, err)
   655  
   656  	principalBytes, err := proto.Marshal(&msp.MSPRole{Role: 35, MspIdentifier: "DEFAULT"})
   657  	assert.NoError(t, err)
   658  
   659  	principal := &msp.MSPPrincipal{
   660  		PrincipalClassification: msp.MSPPrincipal_ROLE,
   661  		Principal:               principalBytes}
   662  
   663  	err = id.SatisfiesPrincipal(principal)
   664  	assert.Error(t, err)
   665  }
   666  
   667  func TestPolicyPrincipalWrongMSPID(t *testing.T) {
   668  	id, err := localMsp.GetDefaultSigningIdentity()
   669  	assert.NoError(t, err)
   670  
   671  	principalBytes, err := proto.Marshal(&msp.MSPRole{Role: msp.MSPRole_MEMBER, MspIdentifier: "DEFAULTBARFBARF"})
   672  	assert.NoError(t, err)
   673  
   674  	principal := &msp.MSPPrincipal{
   675  		PrincipalClassification: msp.MSPPrincipal_ROLE,
   676  		Principal:               principalBytes}
   677  
   678  	err = id.SatisfiesPrincipal(principal)
   679  	assert.Error(t, err)
   680  }
   681  
   682  func TestMemberPolicyPrincipal(t *testing.T) {
   683  	id, err := localMsp.GetDefaultSigningIdentity()
   684  	assert.NoError(t, err)
   685  
   686  	principalBytes, err := proto.Marshal(&msp.MSPRole{Role: msp.MSPRole_MEMBER, MspIdentifier: "DEFAULT"})
   687  	assert.NoError(t, err)
   688  
   689  	principal := &msp.MSPPrincipal{
   690  		PrincipalClassification: msp.MSPPrincipal_ROLE,
   691  		Principal:               principalBytes}
   692  
   693  	err = id.SatisfiesPrincipal(principal)
   694  	assert.NoError(t, err)
   695  }
   696  
   697  func TestAdminPolicyPrincipal(t *testing.T) {
   698  	id, err := localMsp.GetDefaultSigningIdentity()
   699  	assert.NoError(t, err)
   700  
   701  	principalBytes, err := proto.Marshal(&msp.MSPRole{Role: msp.MSPRole_ADMIN, MspIdentifier: "DEFAULT"})
   702  	assert.NoError(t, err)
   703  
   704  	principal := &msp.MSPPrincipal{
   705  		PrincipalClassification: msp.MSPPrincipal_ROLE,
   706  		Principal:               principalBytes}
   707  
   708  	err = id.SatisfiesPrincipal(principal)
   709  	assert.NoError(t, err)
   710  }
   711  
   712  func TestAdminPolicyPrincipalFails(t *testing.T) {
   713  	id, err := localMsp.GetDefaultSigningIdentity()
   714  	assert.NoError(t, err)
   715  
   716  	principalBytes, err := proto.Marshal(&msp.MSPRole{Role: msp.MSPRole_ADMIN, MspIdentifier: "DEFAULT"})
   717  	assert.NoError(t, err)
   718  
   719  	principal := &msp.MSPPrincipal{
   720  		PrincipalClassification: msp.MSPPrincipal_ROLE,
   721  		Principal:               principalBytes}
   722  
   723  	// remove the admin so validation will fail
   724  	localMsp.(*bccspmsp).admins = make([]Identity, 0)
   725  
   726  	err = id.SatisfiesPrincipal(principal)
   727  	assert.Error(t, err)
   728  }
   729  
   730  func TestIdentityPolicyPrincipal(t *testing.T) {
   731  	id, err := localMsp.GetDefaultSigningIdentity()
   732  	assert.NoError(t, err)
   733  
   734  	idSerialized, err := id.Serialize()
   735  	assert.NoError(t, err)
   736  
   737  	principal := &msp.MSPPrincipal{
   738  		PrincipalClassification: msp.MSPPrincipal_IDENTITY,
   739  		Principal:               idSerialized}
   740  
   741  	err = id.SatisfiesPrincipal(principal)
   742  	assert.NoError(t, err)
   743  }
   744  
   745  func TestIdentityPolicyPrincipalBadBytes(t *testing.T) {
   746  	id, err := localMsp.GetDefaultSigningIdentity()
   747  	assert.NoError(t, err)
   748  
   749  	principal := &msp.MSPPrincipal{
   750  		PrincipalClassification: msp.MSPPrincipal_IDENTITY,
   751  		Principal:               []byte("barf")}
   752  
   753  	err = id.SatisfiesPrincipal(principal)
   754  	assert.Error(t, err)
   755  }
   756  
   757  func TestMSPOus(t *testing.T) {
   758  	// Set the OUIdentifiers
   759  	backup := localMsp.(*bccspmsp).ouIdentifiers
   760  	defer func() { localMsp.(*bccspmsp).ouIdentifiers = backup }()
   761  
   762  	id, err := localMsp.GetDefaultSigningIdentity()
   763  	assert.NoError(t, err)
   764  
   765  	localMsp.(*bccspmsp).ouIdentifiers = map[string][][]byte{
   766  		"COP": {id.GetOrganizationalUnits()[0].CertifiersIdentifier},
   767  	}
   768  	assert.NoError(t, localMsp.Validate(id.GetPublicVersion()))
   769  
   770  	localMsp.(*bccspmsp).ouIdentifiers = map[string][][]byte{
   771  		"COP2": {id.GetOrganizationalUnits()[0].CertifiersIdentifier},
   772  	}
   773  	assert.Error(t, localMsp.Validate(id.GetPublicVersion()))
   774  
   775  	localMsp.(*bccspmsp).ouIdentifiers = map[string][][]byte{
   776  		"COP": {{0, 1, 2, 3, 4}},
   777  	}
   778  	assert.Error(t, localMsp.Validate(id.GetPublicVersion()))
   779  }
   780  
   781  const othercert = `-----BEGIN CERTIFICATE-----
   782  MIIDAzCCAqigAwIBAgIBAjAKBggqhkjOPQQDAjBsMQswCQYDVQQGEwJHQjEQMA4G
   783  A1UECAwHRW5nbGFuZDEOMAwGA1UECgwFQmFyMTkxDjAMBgNVBAsMBUJhcjE5MQ4w
   784  DAYDVQQDDAVCYXIxOTEbMBkGCSqGSIb3DQEJARYMQmFyMTktY2xpZW50MB4XDTE3
   785  MDIwOTE2MDcxMFoXDTE4MDIxOTE2MDcxMFowfDELMAkGA1UEBhMCR0IxEDAOBgNV
   786  BAgMB0VuZ2xhbmQxEDAOBgNVBAcMB0lwc3dpY2gxDjAMBgNVBAoMBUJhcjE5MQ4w
   787  DAYDVQQLDAVCYXIxOTEOMAwGA1UEAwwFQmFyMTkxGTAXBgkqhkiG9w0BCQEWCkJh
   788  cjE5LXBlZXIwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQlRSnAyD+ND6qmaRV7
   789  AS/BPJKX5dZt3gBe1v/RewOpc1zJeXQNWACAk0ae3mv5u9l0HxI6TXJIAQSwJACu
   790  Rqsyo4IBKTCCASUwCQYDVR0TBAIwADARBglghkgBhvhCAQEEBAMCBkAwMwYJYIZI
   791  AYb4QgENBCYWJE9wZW5TU0wgR2VuZXJhdGVkIFNlcnZlciBDZXJ0aWZpY2F0ZTAd
   792  BgNVHQ4EFgQUwHzbLJQMaWd1cpHdkSaEFxdKB1owgYsGA1UdIwSBgzCBgIAUYxFe
   793  +cXOD5iQ223bZNdOuKCRiTKhZaRjMGExCzAJBgNVBAYTAkdCMRAwDgYDVQQIDAdF
   794  bmdsYW5kMRAwDgYDVQQHDAdJcHN3aWNoMQ4wDAYDVQQKDAVCYXIxOTEOMAwGA1UE
   795  CwwFQmFyMTkxDjAMBgNVBAMMBUJhcjE5ggEBMA4GA1UdDwEB/wQEAwIFoDATBgNV
   796  HSUEDDAKBggrBgEFBQcDATAKBggqhkjOPQQDAgNJADBGAiEAuMq65lOaie4705Ol
   797  Ow52DjbaO2YuIxK2auBCqNIu0gECIQCDoKdUQ/sa+9Ah1mzneE6iz/f/YFVWo4EP
   798  HeamPGiDTQ==
   799  -----END CERTIFICATE-----
   800  `
   801  
   802  func TestIdentityPolicyPrincipalFails(t *testing.T) {
   803  	id, err := localMsp.GetDefaultSigningIdentity()
   804  	assert.NoError(t, err)
   805  
   806  	sid, err := NewSerializedIdentity("DEFAULT", []byte(othercert))
   807  	assert.NoError(t, err)
   808  
   809  	principal := &msp.MSPPrincipal{
   810  		PrincipalClassification: msp.MSPPrincipal_IDENTITY,
   811  		Principal:               sid}
   812  
   813  	err = id.SatisfiesPrincipal(principal)
   814  	assert.Error(t, err)
   815  }
   816  
   817  var conf *msp.MSPConfig
   818  var localMsp MSP
   819  
   820  // Required because deleting the cert or msp options from localMsp causes parallel tests to fail
   821  var localMspBad MSP
   822  var mspMgr MSPManager
   823  
   824  func TestMain(m *testing.M) {
   825  	var err error
   826  	mspDir, err := config.GetDevMspDir()
   827  	if err != nil {
   828  		fmt.Printf("Errog getting DevMspDir: %s", err)
   829  		os.Exit(-1)
   830  	}
   831  
   832  	conf, err = GetLocalMspConfig(mspDir, nil, "DEFAULT")
   833  	if err != nil {
   834  		fmt.Printf("Setup should have succeeded, got err %s instead", err)
   835  		os.Exit(-1)
   836  	}
   837  
   838  	localMsp, err = NewBccspMsp()
   839  	if err != nil {
   840  		fmt.Printf("Constructor for msp should have succeeded, got err %s instead", err)
   841  		os.Exit(-1)
   842  	}
   843  
   844  	localMspBad, err = NewBccspMsp()
   845  	if err != nil {
   846  		fmt.Printf("Constructor for msp should have succeeded, got err %s instead", err)
   847  		os.Exit(-1)
   848  	}
   849  
   850  	err = localMsp.Setup(conf)
   851  	if err != nil {
   852  		fmt.Printf("Setup for msp should have succeeded, got err %s instead", err)
   853  		os.Exit(-1)
   854  	}
   855  
   856  	err = localMspBad.Setup(conf)
   857  	if err != nil {
   858  		fmt.Printf("Setup for msp should have succeeded, got err %s instead", err)
   859  		os.Exit(-1)
   860  	}
   861  
   862  	mspMgr = NewMSPManager()
   863  	err = mspMgr.Setup([]MSP{localMsp})
   864  	if err != nil {
   865  		fmt.Printf("Setup for msp manager should have succeeded, got err %s instead", err)
   866  		os.Exit(-1)
   867  	}
   868  
   869  	id, err := localMsp.GetIdentifier()
   870  	if err != nil {
   871  		fmt.Println("Failed obtaining identifier for localMSP")
   872  		os.Exit(-1)
   873  	}
   874  
   875  	msps, err := mspMgr.GetMSPs()
   876  	if err != nil {
   877  		fmt.Println("Failed obtaining MSPs from MSP manager")
   878  		os.Exit(-1)
   879  	}
   880  
   881  	if msps[id] == nil {
   882  		fmt.Println("Couldn't find localMSP in MSP manager")
   883  		os.Exit(-1)
   884  	}
   885  
   886  	retVal := m.Run()
   887  	os.Exit(retVal)
   888  }
   889  
   890  func getIdentity(t *testing.T, path string) Identity {
   891  	mspDir, err := config.GetDevMspDir()
   892  	assert.NoError(t, err)
   893  
   894  	pems, err := getPemMaterialFromDir(filepath.Join(mspDir, path))
   895  	assert.NoError(t, err)
   896  
   897  	id, _, err := localMsp.(*bccspmsp).getIdentityFromConf(pems[0])
   898  	assert.NoError(t, err)
   899  
   900  	return id
   901  }
   902  
   903  func getLocalMSP(t *testing.T, dir string) MSP {
   904  	conf, err := GetLocalMspConfig(dir, nil, "DEFAULT")
   905  	assert.NoError(t, err)
   906  
   907  	thisMSP, err := NewBccspMsp()
   908  	assert.NoError(t, err)
   909  	ks, err := sw.NewFileBasedKeyStore(nil, filepath.Join(dir, "keystore"), true)
   910  	assert.NoError(t, err)
   911  	csp, err := sw.New(256, "SHA2", ks)
   912  	assert.NoError(t, err)
   913  	thisMSP.(*bccspmsp).bccsp = csp
   914  
   915  	err = thisMSP.Setup(conf)
   916  	assert.NoError(t, err)
   917  
   918  	return thisMSP
   919  }