Skip to content
This repository has been archived by the owner on Nov 25, 2020. It is now read-only.

Testing invocation permissions based on certificate attributes #39

Open
cayblood opened this issue May 19, 2020 · 0 comments
Open

Testing invocation permissions based on certificate attributes #39

cayblood opened this issue May 19, 2020 · 0 comments

Comments

@cayblood
Copy link

I'd like to be able to test access control to chaincode invocations based on whether or not the fabric client's certificate has the required attributes. Here is some example chaincode. I don't see any built-in functionality for mocking the cert coming from stub. Am I missing something? Thanks in advance.

/////////////////////////////////////////////////////////
// ROLE-BASED ACCESS CONTROL EXAMPLE
// 
// The following chaincode demonstrates how to prevent
// unauthorized clients from invoking chaincode methods.
/////////////////////////////////////////////////////////

'use strict';
const shim = require('fabric-shim');

/////////////////////////////////////////////////////////
// requireRole
//
// This method will throw an error if the calling client
// does not have the specified role.
/////////////////////////////////////////////////////////
async function requireRole(stub, role) {
  const ClientIdentity = shim.ClientIdentity;
  let cid = new ClientIdentity(stub);
  if (!cid.assertAttributeValue('role', role))
    throw new Error(`Unauthorized access: ${role} required`);
}

let Chaincode = class {
  async Init(stub) {
    console.info('============= Init called =============');
    return shim.success();
  }

  async Invoke(stub) {
    console.info('============= Invoke called =============');
    
    // ensure client has admin role before proceeding
    try {
      await requireRole(stub, 'admin');
    } catch(err) {
      // log failed access attempt and return
      console.error("Error during Invoke: ", err);
      return shim.error(err.message || err);
    }
    
    // client has the expected role, so continue
    console.info('SUCCESS!')
    return shim.success();
  }
}

shim.start(new Chaincode());
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant