<commit_before>/*
Copyright IBM Corp All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package e2e

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	"github.com/gogo/protobuf/proto"
	"github.com/hyperledger/fabric/common/tools/configtxlator/update"
	"github.com/hyperledger/fabric/core/aclmgmt/resources"
	"github.com/hyperledger/fabric/integration/helpers"
	"github.com/hyperledger/fabric/integration/runner"
	"github.com/hyperledger/fabric/integration/world"
	"github.com/hyperledger/fabric/protos/common"
	pb "github.com/hyperledger/fabric/protos/peer"
	"github.com/hyperledger/fabric/protos/utils"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
)

var _ = Describe("EndToEndACL", func() {
	var (
		testDir    string
		w          *world.World
		deployment world.Deployment
		org1Peer0  *runner.Peer
		org2Peer0  *runner.Peer
	)

	BeforeEach(func() {
		var err error
		testDir, err = ioutil.TempDir("", "acl-e2e")
		Expect(err).NotTo(HaveOccurred())

		w = world.GenerateBasicConfig("solo", 2, 2, testDir, components)

		// sets up the world for all tests
		deployment = world.Deployment{
			Channel: "testchannel",
			Chaincode: world.Chaincode{
				Name:     "mycc",
				Version:  "0.0",
				Path:     "github.com/hyperledger/fabric/integration/chaincode/simple/cmd",
				ExecPath: os.Getenv("PATH"),
			},
			InitArgs: `{"Args":["init","a","100","b","200"]}`,
			Policy:   `OR ('Org1MSP.member','Org2MSP.member')`,
			Orderer:  "127.0.0.1:7050",
		}
		w.BootstrapNetwork(deployment.Channel)
		helpers.CopyFile(filepath.Join("testdata", "orderer.yaml"), filepath.Join(w.Rootpath, "orderer.yaml"))
		w.CopyPeerConfigs("testdata")
		w.BuildNetwork()
		w.SetupChannel(deployment, []string{"peer0.org1.example.com", "peer0.org2.example.com"})

		org1Peer0 = components.Peer()
		org1Peer0.ConfigDir = filepath.Join(w.Rootpath, "peer0.org1.example.com")
		org1Peer0.MSPConfigPath = filepath.Join(w.Rootpath, "crypto", "peerOrganizations", "org1.example.com", "users", "<EMAIL>", "msp")

		org2Peer0 = components.Peer()
		org2Peer0.ConfigDir = filepath.Join(w.Rootpath, "peer0.org2.example.com")
		org2Peer0.MSPConfigPath = filepath.Join(w.Rootpath, "crypto", "peerOrganizations", "org2.example.com", "users", "<EMAIL>", "msp")
	})

	AfterEach(func() {
		w.Close(deployment)
		os.RemoveAll(testDir)
	})

	It("enforces access control list policies", func() {
		//
		// when the ACL policy for DeliverFiltered is satisified
		//
		By("setting the filtered block event ACL policy to Org1/Admins")
		policyName := resources.Event_FilteredBlock
		policy := "/Channel/Application/Org1/Admins"
		SetACLPolicy(w, deployment, policyName, policy)

		By("invoking chaincode as a permitted Org1 Admin identity")
		adminRunner := org1Peer0.InvokeChaincode(deployment.Chaincode.Name, deployment.Channel, `{"Args":["invoke","a","b","10"]}`, deployment.Orderer, "--waitForEvent")
		execute(adminRunner)
		Expect(adminRunner.Err()).To(gbytes.Say("Chaincode invoke successful. result: status:200"))

		//
		// when the ACL policy for DeliverFiltered is not satisifed
		//
		By("setting the filtered block event ACL policy to Org2/Admins")
		policyName = resources.Event_FilteredBlock
		policy = "/Channel/Application/Org2/Admins"
		SetACLPolicy(w, deployment, policyName, policy)

		By("invoking chaincode as a forbidden Org2 Admin identity")
		adminRunner = org1Peer0.InvokeChaincode(deployment.Chaincode.Name, deployment.Channel, `{"Args":["invoke","a","b","10"]}`, deployment.Orderer, "--waitForEvent")
		execute(adminRunner)
		Expect(adminRunner.Err()).To(gbytes.Say(`\Qdeliver completed with status (FORBIDDEN)\E`))

		//
		// when the ACL policy for Deliver is satisfied
		//
		By("setting the block event ACL policy to Org1/Admins")
		policyName = resources.Event_Block
		policy = "/Channel/Application/Org1/Admins"
		SetACLPolicy(w, deployment, policyName, policy)

		By("setting the log level for deliver to debug for org1Peer0")
		lRunner := org1Peer0.SetLogLevel("common/deliver", "debug")
		execute(lRunner)
		Expect(lRunner.Err()).To(gbytes.Say("Log level set for peer modules matching regular expression 'common/deliver': DEBUG"))

		By("fetching the latest block from the peer as a permitted Org1 Admin identity")
		outputBlock := filepath.Join(w.Rootpath, "newest_block.pb")
		fRunner := org1Peer0.FetchChannel(deployment.Channel, outputBlock, "newest", "")
		execute(fRunner)
		Expect(fRunner.Err()).To(gbytes.Say("Received block: "))
		// TODO - enable this once the peer's logs are available here
		// Expect(peerRunner.Err()).To(gbytes.Say(`\Q[channel: testchannel] Done delivering \E`))

		//
		// when the ACL policy for Deliver is not satisifed
		//
		By("setting the block event ACL policy to Org2/Admins")
		policyName = resources.Event_Block
		policy = "/Channel/Application/Org2/Admins"
		SetACLPolicy(w, deployment, policyName, policy)

		By("fetching the latest block from the peer as a forbidden Org1 Admin identity")
		fRunner = org1Peer0.FetchChannel(deployment.Channel, filepath.Join(w.Rootpath, "newest_block.pb"), "newest", "")
		execute(fRunner)
		Expect(fRunner.Err()).To(gbytes.Say("can't read the block: &{FORBIDDEN}"))
		// TODO - enable this once the peer's logs are available here
		// Expect(peerRunner.Err()).To(gbytes.Say(`\Q[channel: testchannel] Done delivering \Q`))

		By("setting the log level for deliver back to info for org1Peer0")
		lRunner = org1Peer0.SetLogLevel("common/deliver", "info")
		execute(lRunner)
		Expect(lRunner.Err()).To(gbytes.Say("Log level set for peer modules matching regular expression 'common/deliver': INFO"))

		//
		// when a system chaincode ACL policy is set and a query is performed
		//

		// getting a transaction id from a block in the ledger
		txID := GetTxIDFromBlockFile(outputBlock)

		ItEnforcesPolicy := func(scc, operation string, args ...string) {
			policyName := fmt.Sprintf("%s/%s", scc, operation)
			policy := "/Channel/Application/Org1/Admins"
			By("setting " + policyName + " to Org1 Admins")
			SetACLPolicy(w, deployment, policyName, policy)

			By("evaluating " + policyName + " for a permitted subject")
			args = append([]string{operation}, args...)
			cliArgs := ToCLIChaincodeArgs(args...)
			adminRunner := org1Peer0.QueryChaincode(scc, deployment.Channel, string(cliArgs))
			err := execute(adminRunner)
			Expect(err).NotTo(HaveOccurred())

			By("evaluating " + policyName + " for a forbidden subject")
			adminRunner = org2Peer0.QueryChaincode(scc, deployment.Channel, string(cliArgs))
			err = execute(adminRunner)
			Expect(err).To(HaveOccurred())
			Expect(adminRunner.Err()).To(gbytes.Say(fmt.Sprintf(`access denied for \[%s\]\[%s\](.*)signature set did not satisfy policy`, operation, deployment.Channel)))<commit_msg>[FAB-9655] Function test for LSCC GetInstantiatedCCs<commit_after>/*
Copyright IBM Corp All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package e2e

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	"github.com/gogo/protobuf/proto"
	"github.com/hyperledger/fabric/common/tools/configtxlator/update"
	"github.com/hyperledger/fabric/core/aclmgmt/resources"
	"github.com/hyperledger/fabric/integration/helpers"
	"github.com/hyperledger/fabric/integration/runner"
	"github.com/hyperledger/fabric/integration/world"
	"github.com/hyperledger/fabric/protos/common"
	pb "github.com/hyperledger/fabric/protos/peer"
	"github.com/hyperledger/fabric/protos/utils"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
)

var _ = Describe("EndToEndACL", func() {
	var (
		testDir    string
		w          *world.World
		deployment world.Deployment
		org1Peer0  *runner.Peer
		org2Peer0  *runner.Peer
	)

	BeforeEach(func() {
		var err error
		testDir, err = ioutil.TempDir("", "acl-e2e")
		Expect(err).NotTo(HaveOccurred())

		w = world.GenerateBasicConfig("solo", 2, 2, testDir, components)

		// sets up the world for all tests
		deployment = world.Deployment{
			Channel: "testchannel",
			Chaincode: world.Chaincode{
				Name:     "mycc",
				Version:  "0.0",
				Path:     "github.com/hyperledger/fabric/integration/chaincode/simple/cmd",
				ExecPath: os.Getenv("PATH"),
			},
			InitArgs: `{"Args":["init","a","100","b","200"]}`,
			Policy:   `OR ('Org1MSP.member','Org2MSP.member')`,
			Orderer:  "127.0.0.1:7050",
		}
		w.BootstrapNetwork(deployment.Channel)
		helpers.CopyFile(filepath.Join("testdata", "orderer.yaml"), filepath.Join(w.Rootpath, "orderer.yaml"))
		w.CopyPeerConfigs("testdata")
		w.BuildNetwork()
		w.SetupChannel(deployment, []string{"peer0.org1.example.com", "peer0.org2.example.com"})

		org1Peer0 = components.Peer()
		org1Peer0.ConfigDir = filepath.Join(w.Rootpath, "peer0.org1.example.com")
		org1Peer0.MSPConfigPath = filepath.Join(w.Rootpath, "crypto", "peerOrganizations", "org1.example.com", "users", "<EMAIL>", "msp")

		org2Peer0 = components.Peer()
		org2Peer0.ConfigDir = filepath.Join(w.Rootpath, "peer0.org2.example.com")
		org2Peer0.MSPConfigPath = filepath.Join(w.Rootpath, "crypto", "peerOrganizations", "org2.example.com", "users", "<EMAIL>", "msp")
	})

	AfterEach(func() {
		w.Close(deployment)
		os.RemoveAll(testDir)
	})

	It("enforces access control list policies", func() {
		//
		// when the ACL policy for DeliverFiltered is satisified
		//
		By("setting the filtered block event ACL policy to Org1/Admins")
		policyName := resources.Event_FilteredBlock
		policy := "/Channel/Application/Org1/Admins"
		SetACLPolicy(w, deployment, policyName, policy)

		By("invoking chaincode as a permitted Org1 Admin identity")
		adminRunner := org1Peer0.InvokeChaincode(deployment.Chaincode.Name, deployment.Channel, `{"Args":["invoke","a","b","10"]}`, deployment.Orderer, "--waitForEvent")
		execute(adminRunner)
		Expect(adminRunner.Err()).To(gbytes.Say("Chaincode invoke successful. result: status:200"))

		//
		// when the ACL policy for DeliverFiltered is not satisifed
		//
		By("setting the filtered block event ACL policy to Org2/Admins")
		policyName = resources.Event_FilteredBlock
		policy = "/Channel/Application/Org2/Admins"
		SetACLPolicy(w, deployment, policyName, policy)

		By("invoking chaincode as a forbidden Org2 Admin identity")
		adminRunner = org1Peer0.InvokeChaincode(deployment.Chaincode.Name, deployment.Channel, `{"Args":["invoke","a","b","10"]}`, deployment.Orderer, "--waitForEvent")
		execute(adminRunner)
		Expect(adminRunner.Err()).To(gbytes.Say(`\Qdeliver completed with status (FORBIDDEN)\E`))

		//
		// when the ACL policy for Deliver is satisfied
		//
		By("setting the block event ACL policy to Org1/Admins")
		policyName = resources.Event_Block
		policy = "/Channel/Application/Org1/Admins"
		SetACLPolicy(w, deployment, policyName, policy)

		By("setting the log level for deliver to debug for org1Peer0")
		lRunner := org1Peer0.SetLogLevel("common/deliver", "debug")
		execute(lRunner)
		Expect(lRunner.Err()).To(gbytes.Say("Log level set for peer modules matching regular expression 'common/deliver': DEBUG"))

		By("fetching the latest block from the peer as a permitted Org1 Admin identity")
		outputBlock := filepath.Join(w.Rootpath, "newest_block.pb")
		fRunner := org1Peer0.FetchChannel(deployment.Channel, outputBlock, "newest", "")
		execute(fRunner)
		Expect(fRunner.Err()).To(gbytes.Say("Received block: "))
		// TODO - enable this once the peer's logs are available here
		// Expect(peerRunner.Err()).To(gbytes.Say(`\Q[channel: testchannel] Done delivering \E`))

		//
		// when the ACL policy for Deliver is not satisifed
		//
		By("setting the block event ACL policy to Org2/Admins")
		policyName = resources.Event_Block
		policy = "/Channel/Application/Org2/Admins"
		SetACLPolicy(w, deployment, policyName, policy)

		By("fetching the latest block from the peer as a forbidden Org1 Admin identity")
		fRunner = org1Peer0.FetchChannel(deployment.Channel, filepath.Join(w.Rootpath, "newest_block.pb"), "newest", "")
		execute(fRunner)
		Expect(fRunner.Err()).To(gbytes.Say("can't read the block: &{FORBIDDEN}"))
		// TODO - enable this once the peer's logs are available here
		// Expect(peerRunner.Err()).To(gbytes.Say(`\Q[channel: testchannel] Done delivering \Q`))

		By("setting the log level for deliver back to info for org1Peer0")
		lRunner = org1Peer0.SetLogLevel("common/deliver", "info")
		execute(lRunner)
		Expect(lRunner.Err()).To(gbytes.Say("Log level set for peer modules matching regular expression 'common/deliver': INFO"))

		//
		// when the ACL policy for lscc/GetInstantiatedChaincodes is satisfied
		//
		By("setting the lscc/GetInstantiatedChaincodes ACL policy to Org1/Admins")
		policyName = resources.Lscc_GetInstantiatedChaincodes
		policy = "/Channel/Application/Org1/Admins"
		SetACLPolicy(w, deployment, policyName, policy)

		By("listing the instantiated chaincodes as a permitted Org1 Admin identity")
		adminRunner = org1Peer0.ChaincodeListInstantiated(deployment.Channel)
		execute(adminRunner)
		Expect(adminRunner.Buffer()).To(gbytes.Say("Name: mycc, Version: 0.0, Path: github.com/hyperledger/fabric/integration/chaincode/simple/cmd, Escc: escc, Vscc: vscc"))

		//
		// when the ACL policy for lscc/GetInstantiatedChaincodes is not satisfied
		//
		By("listing the instantiated chaincodes as a forbidden Org2 Admin identity")
		adminRunner = org2Peer0.ChaincodeListInstantiated(deployment.Channel)
		execute(adminRunner)
		Expect(adminRunner.Buffer()).NotTo(gbytes.Say("Name: mycc, Version: 0.0, Path: github.com/hyperledger/fabric/integration/chaincode/simple/cmd, Escc: escc, Vscc: vscc"))
		Expect(adminRunner.Err()).To(gbytes.Say(`access denied for \[getchaincodes\]\[testchannel\](.*)signature set did not satisfy policy`))

		//
		// when a system chaincode ACL policy is set and a query is performed
		//

		// getting a transaction id from a block in the ledger
		txID := GetTxIDFromBlockFile(outputBlock)

		ItEnforcesPolicy := func(scc, operation string, args ...string) {
			policyName := fmt.Sprintf("%s/%s", scc, operation)
			policy := "/Channel/Application/Org1/Admins"
			By("setting " + policyName + " to Org1 Admins")
			SetACLPolicy(w, deployment, policyName, policy)

			By("evaluating " + policyName + " for a permitted subject")
			args = append([]string{operation}, args...)
			cliArgs := ToCLIChaincodeArgs(args...)
			adminRunner := org1Peer0.QueryChaincode(scc, deployment.Channel, string(cliArgs))
			err := execute(adminRunner)
			Expect(err).NotTo(HaveOccurred())

			By("evaluating " + policyName + " for a forbidden subject")
			adminRunner = org2Peer0.QueryChaincode(scc, deployment.Channel, string(cliArgs))
			err = execute(adminRunner)
			Expect(err).To(HaveOccurred())
			Expect(adminRunner.Err()).To(gbytes.Say(fmt.Sprintf(`access denied for \[%s\]\[%s\](.*)signature set did not satisfy policy`, operation, deployment.Channel)))
{'fraction_non_alphanumeric': 0.1437470694621207, 'fraction_numerical': 0.013530712036975015, 'mean_word_length': 4.689786585365853, 'pattern_counts': {'":': 6, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2822427', 'n_tokens_mistral': 5479, 'n_tokens_neox': 4952, 'n_words': 1071}