Skip to content

Commit d45c3e5

Browse files
committed
[FAB-1822] - parse strings into cauthdsl policies
This change set provides code to parse expressions like AND('org0.member', 'org1.admin') into cauthdsl policy objects. This can then be used for the golang client reference implementation to specify endorsement policies for newly created chaincodes. Change-Id: Idb00ff0547ac489438a5023d76970f898d11dca2 Signed-off-by: Alessandro Sorniotti <[email protected]>
1 parent 6ad68d5 commit d45c3e5

23 files changed

+3707
-0
lines changed

common/cauthdsl/policyparser.go

+253
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
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 cauthdsl
18+
19+
import (
20+
"fmt"
21+
"reflect"
22+
"regexp"
23+
"strconv"
24+
25+
"github.com/Knetic/govaluate"
26+
"github.com/hyperledger/fabric/protos/common"
27+
"github.com/hyperledger/fabric/protos/utils"
28+
)
29+
30+
var regex *regexp.Regexp = regexp.MustCompile("^([[:alnum:]]+)([.])(member|admin)$")
31+
32+
func and(args ...interface{}) (interface{}, error) {
33+
toret := "outof(" + strconv.Itoa(len(args))
34+
for _, arg := range args {
35+
toret += ", "
36+
switch t := arg.(type) {
37+
case string:
38+
if regex.MatchString(t) {
39+
toret += "'" + t + "'"
40+
} else {
41+
toret += t
42+
}
43+
default:
44+
return nil, fmt.Errorf("Unexpected type %s", reflect.TypeOf(arg))
45+
}
46+
}
47+
48+
return toret + ")", nil
49+
}
50+
51+
func or(args ...interface{}) (interface{}, error) {
52+
toret := "outof(" + strconv.Itoa(1)
53+
for _, arg := range args {
54+
toret += ", "
55+
switch t := arg.(type) {
56+
case string:
57+
if regex.MatchString(t) {
58+
toret += "'" + t + "'"
59+
} else {
60+
toret += t
61+
}
62+
default:
63+
return nil, fmt.Errorf("Unexpected type %s", reflect.TypeOf(arg))
64+
}
65+
}
66+
67+
return toret + ")", nil
68+
}
69+
70+
func firstPass(args ...interface{}) (interface{}, error) {
71+
toret := "outof(ID"
72+
for _, arg := range args {
73+
toret += ", "
74+
switch t := arg.(type) {
75+
case string:
76+
if regex.MatchString(t) {
77+
toret += "'" + t + "'"
78+
} else {
79+
toret += t
80+
}
81+
case float32:
82+
case float64:
83+
toret += strconv.Itoa(int(t))
84+
default:
85+
return nil, fmt.Errorf("Unexpected type %s", reflect.TypeOf(arg))
86+
}
87+
}
88+
89+
return toret + ")", nil
90+
}
91+
92+
func secondPass(args ...interface{}) (interface{}, error) {
93+
/* general sanity check, we expect at least 3 args */
94+
if len(args) < 3 {
95+
return nil, fmt.Errorf("At least 3 arguments expected, got %d", len(args))
96+
}
97+
98+
/* get the first argument, we expect it to be the context */
99+
var ctx *context
100+
switch v := args[0].(type) {
101+
case *context:
102+
ctx = v
103+
default:
104+
return nil, fmt.Errorf("Unrecognized type, expected the context, got %s", reflect.TypeOf(args[0]))
105+
}
106+
107+
/* get the second argument, we expect an integer telling us
108+
how many of the remaining we expect to have*/
109+
var t int
110+
switch arg := args[1].(type) {
111+
case float64:
112+
t = int(arg)
113+
default:
114+
return nil, fmt.Errorf("Unrecognized type, expected a number, got %s", reflect.TypeOf(args[1]))
115+
}
116+
117+
/* get the n in the t out of n */
118+
var n int = len(args) - 1
119+
120+
/* sanity check - t better be <= n */
121+
if t > n {
122+
return nil, fmt.Errorf("Invalid t-out-of-n predicate, t %d, n %d", t, n)
123+
}
124+
125+
policies := make([]*common.SignaturePolicy, 0)
126+
127+
/* handle the rest of the arguments */
128+
for _, principal := range args[2:] {
129+
switch t := principal.(type) {
130+
/* if it's a string, we expect it to be formed as
131+
<MSP_ID> . <ROLE>, where MSP_ID is the MSP identifier
132+
and ROLE is either a member of an admin*/
133+
case string:
134+
/* split the string */
135+
subm := regex.FindAllStringSubmatch(t, -1)
136+
if subm == nil || len(subm) != 1 || len(subm[0]) != 4 {
137+
return nil, fmt.Errorf("Error parsing principal %s", t)
138+
}
139+
140+
/* get the right role */
141+
var r common.MSPRole_MSPRoleType
142+
if subm[0][3] == "member" {
143+
r = common.MSPRole_Member
144+
} else {
145+
r = common.MSPRole_Admin
146+
}
147+
148+
/* build the principal we've been told */
149+
p := &common.MSPPrincipal{
150+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
151+
Principal: utils.MarshalOrPanic(&common.MSPRole{MSPIdentifier: subm[0][1], Role: r})}
152+
ctx.principals = append(ctx.principals, p)
153+
154+
/* create a SignaturePolicy that requires a signature from
155+
the principal we've just built*/
156+
dapolicy := SignedBy(int32(ctx.IDNum))
157+
policies = append(policies, dapolicy)
158+
159+
/* increment the identity counter. Note that this is
160+
suboptimal as we are not reusing identities. We
161+
can deduplicate them easily and make this puppy
162+
smaller. For now it's fine though */
163+
// TODO: deduplicate principals
164+
ctx.IDNum++
165+
166+
/* if we've already got a policy we're good, just append it */
167+
case *common.SignaturePolicy:
168+
policies = append(policies, t)
169+
170+
default:
171+
return nil, fmt.Errorf("Unrecognized type, expected a principal or a policy, got %s", reflect.TypeOf(principal))
172+
}
173+
}
174+
175+
return NOutOf(int32(t), policies), nil
176+
}
177+
178+
type context struct {
179+
IDNum int
180+
principals []*common.MSPPrincipal
181+
}
182+
183+
func newContext() *context {
184+
return &context{IDNum: 0, principals: make([]*common.MSPPrincipal, 0)}
185+
}
186+
187+
// FromString takes a string representation of the policy,
188+
// parses it and returns a SignaturePolicyEnvelope that
189+
// implements that policy. The supported language is as follows
190+
//
191+
// GATE(P[, P])
192+
//
193+
// where
194+
// - GATE is either "and" or "or"
195+
// - P is either a principal or another nested call to GATE
196+
//
197+
// a principal is defined as
198+
//
199+
// ORG.ROLE
200+
//
201+
// where
202+
// - ORG is a string (representing the MSP identifier)
203+
// - ROLE is either the string "member" or the string "admin" representing the required role
204+
func FromString(policy string) (*common.SignaturePolicyEnvelope, error) {
205+
// first we translate the and/or business into outof gates
206+
intermediate, err := govaluate.NewEvaluableExpressionWithFunctions(policy, map[string]govaluate.ExpressionFunction{"AND": and, "and": and, "OR": or, "or": or})
207+
if err != nil {
208+
return nil, err
209+
}
210+
211+
intermediateRes, err := intermediate.Evaluate(nil)
212+
if err != nil {
213+
return nil, err
214+
}
215+
216+
// we still need two passes. The first pass just adds an extra
217+
// argument ID to each of the outof calls. This is
218+
// required because govaluate has no means of giving context
219+
// to user-implemented functions other than via arguments.
220+
// We need this argument because we need a global place where
221+
// we put the identities that the policy requires
222+
exp, err := govaluate.NewEvaluableExpressionWithFunctions(intermediateRes.(string), map[string]govaluate.ExpressionFunction{"outof": firstPass})
223+
if err != nil {
224+
return nil, err
225+
}
226+
227+
res, err := exp.Evaluate(nil)
228+
if err != nil {
229+
return nil, err
230+
}
231+
232+
ctx := newContext()
233+
parameters := make(map[string]interface{}, 1)
234+
parameters["ID"] = ctx
235+
236+
exp, err = govaluate.NewEvaluableExpressionWithFunctions(res.(string), map[string]govaluate.ExpressionFunction{"outof": secondPass})
237+
if err != nil {
238+
return nil, err
239+
}
240+
241+
res, err = exp.Evaluate(parameters)
242+
if err != nil {
243+
return nil, err
244+
}
245+
246+
p := &common.SignaturePolicyEnvelope{
247+
Identities: ctx.principals,
248+
Version: 0,
249+
Policy: res.(*common.SignaturePolicy),
250+
}
251+
252+
return p, nil
253+
}

common/cauthdsl/policyparser_test.go

+130
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
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 cauthdsl
18+
19+
import (
20+
"reflect"
21+
"testing"
22+
23+
"github.com/hyperledger/fabric/protos/common"
24+
"github.com/hyperledger/fabric/protos/utils"
25+
"github.com/stretchr/testify/assert"
26+
)
27+
28+
func TestAnd(t *testing.T) {
29+
p1, err := FromString("AND('A.member', 'B.member')")
30+
assert.NoError(t, err)
31+
32+
principals := make([]*common.MSPPrincipal, 0)
33+
34+
principals = append(principals, &common.MSPPrincipal{
35+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
36+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "A"})})
37+
38+
principals = append(principals, &common.MSPPrincipal{
39+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
40+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "B"})})
41+
42+
p2 := &common.SignaturePolicyEnvelope{
43+
Version: 0,
44+
Policy: And(SignedBy(0), SignedBy(1)),
45+
Identities: principals,
46+
}
47+
48+
assert.True(t, reflect.DeepEqual(p1, p2))
49+
}
50+
51+
func TestOr(t *testing.T) {
52+
p1, err := FromString("OR('A.member', 'B.member')")
53+
assert.NoError(t, err)
54+
55+
principals := make([]*common.MSPPrincipal, 0)
56+
57+
principals = append(principals, &common.MSPPrincipal{
58+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
59+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "A"})})
60+
61+
principals = append(principals, &common.MSPPrincipal{
62+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
63+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "B"})})
64+
65+
p2 := &common.SignaturePolicyEnvelope{
66+
Version: 0,
67+
Policy: Or(SignedBy(0), SignedBy(1)),
68+
Identities: principals,
69+
}
70+
71+
assert.True(t, reflect.DeepEqual(p1, p2))
72+
}
73+
74+
func TestComplex1(t *testing.T) {
75+
p1, err := FromString("OR('A.member', AND('B.member', 'C.member'))")
76+
assert.NoError(t, err)
77+
78+
principals := make([]*common.MSPPrincipal, 0)
79+
80+
principals = append(principals, &common.MSPPrincipal{
81+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
82+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "B"})})
83+
84+
principals = append(principals, &common.MSPPrincipal{
85+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
86+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "C"})})
87+
88+
principals = append(principals, &common.MSPPrincipal{
89+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
90+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "A"})})
91+
92+
p2 := &common.SignaturePolicyEnvelope{
93+
Version: 0,
94+
Policy: Or(SignedBy(2), And(SignedBy(0), SignedBy(1))),
95+
Identities: principals,
96+
}
97+
98+
assert.True(t, reflect.DeepEqual(p1, p2))
99+
}
100+
101+
func TestComplex2(t *testing.T) {
102+
p1, err := FromString("OR(AND('A.member', 'B.member'), OR('C.admin', 'D.member'))")
103+
assert.NoError(t, err)
104+
105+
principals := make([]*common.MSPPrincipal, 0)
106+
107+
principals = append(principals, &common.MSPPrincipal{
108+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
109+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "A"})})
110+
111+
principals = append(principals, &common.MSPPrincipal{
112+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
113+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "B"})})
114+
115+
principals = append(principals, &common.MSPPrincipal{
116+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
117+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Admin, MSPIdentifier: "C"})})
118+
119+
principals = append(principals, &common.MSPPrincipal{
120+
PrincipalClassification: common.MSPPrincipal_ByMSPRole,
121+
Principal: utils.MarshalOrPanic(&common.MSPRole{Role: common.MSPRole_Member, MSPIdentifier: "D"})})
122+
123+
p2 := &common.SignaturePolicyEnvelope{
124+
Version: 0,
125+
Policy: Or(And(SignedBy(0), SignedBy(1)), Or(SignedBy(2), SignedBy(3))),
126+
Identities: principals,
127+
}
128+
129+
assert.True(t, reflect.DeepEqual(p1, p2))
130+
}

vendor/github.com/Knetic/govaluate/CONTRIBUTORS

+8
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)