Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

security/authorization: util function for converting CEL expression string #3822

Merged
merged 2 commits into from
Aug 19, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion security/authorization/engine/engine.go
Original file line number Diff line number Diff line change
@@ -33,7 +33,7 @@ import (
"google.golang.org/protobuf/proto"
)

var logger = grpclog.Component("channelz")
var logger = grpclog.Component("authorization")

var stringAttributeMap = map[string]func(*AuthorizationArgs) (string, error){
"request.url_path": (*AuthorizationArgs).getRequestURLPath,
63 changes: 63 additions & 0 deletions security/authorization/util/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
*
* Copyright 2020 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package engine

import (
"errors"

expr "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
"google.golang.org/protobuf/proto"

"github.com/google/cel-go/cel"
"github.com/google/cel-go/checker/decls"
)

func compileCel(env *cel.Env, expr string) (*cel.Ast, error) {
ast, iss := env.Parse(expr)
// Report syntactic errors, if present.
if iss.Err() != nil {
return nil, iss.Err()
}
// Type-check the expression for correctness.
checked, iss := env.Check(ast)
if iss.Err() != nil {
return nil, iss.Err()
}
// Check the result type is a Boolean.
if !proto.Equal(checked.ResultType(), decls.Bool) {
return nil, errors.New("failed to compile CEL string: get non-bool value")
}
return checked, nil
}

func compileStringToCheckedExpr(expr string, declarations []*expr.Decl) (*expr.CheckedExpr, error) {
env, err := cel.NewEnv(cel.Declarations(declarations...))
if err != nil {
return nil, err
}
checked, err := compileCel(env, expr)
if err != nil {
return nil, err
}
checkedExpr, err := cel.AstToCheckedExpr(checked)
if err != nil {
return nil, err
}
return checkedExpr, nil
}
123 changes: 123 additions & 0 deletions security/authorization/util/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
*
* Copyright 2020 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package engine

import (
"testing"

expr "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
"google.golang.org/grpc/internal/grpctest"

"github.com/google/cel-go/cel"
"github.com/google/cel-go/checker/decls"
)

type s struct {
grpctest.Tester
}

func Test(t *testing.T) {
grpctest.RunSubTests(t, s{})
}

func (s) TestStringConvert(t *testing.T) {
declarations := []*expr.Decl{
decls.NewIdent("request.url_path", decls.String, nil),
decls.NewIdent("request.host", decls.String, nil),
decls.NewIdent("connection.uri_san_peer_certificate", decls.String, nil)}
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
env, err := cel.NewEnv()
if err != nil {
t.Fatalf("Failed to create the CEL environment")
}
for _, test := range []struct {
desc string
wantEvalOutcome bool
wantParsingError bool
wantEvalError bool
expr string
authzArgs map[string]interface{}
}{
{
desc: "Test 1 single primitive match",
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
wantEvalOutcome: true,
expr: "request.url_path.startsWith('/pkg.service/test')",
authzArgs: map[string]interface{}{"request.url_path": "/pkg.service/test"},
},
{
desc: "Test 2 single compare match",
wantEvalOutcome: true,
expr: "connection.uri_san_peer_certificate == 'cluster/ns/default/sa/admin'",
authzArgs: map[string]interface{}{"connection.uri_san_peer_certificate": "cluster/ns/default/sa/admin"},
},
{
desc: "Test 3 single primitive no match",
wantEvalOutcome: false,
expr: "request.url_path.startsWith('/pkg.service/test')",
authzArgs: map[string]interface{}{"request.url_path": "/source/pkg.service/test"},
},
{
desc: "Test 4 primitive and compare match",
wantEvalOutcome: true,
expr: "request.url_path == '/pkg.service/test' && connection.uri_san_peer_certificate == 'cluster/ns/default/sa/admin'",
authzArgs: map[string]interface{}{"request.url_path": "/pkg.service/test",
"connection.uri_san_peer_certificate": "cluster/ns/default/sa/admin"},
},
{
desc: "Test 5 parse error field not present in environment",
wantParsingError: true,
expr: "request.source_path.startsWith('/pkg.service/test')",
authzArgs: map[string]interface{}{"request.url_path": "/pkg.service/test"},
},
{
desc: "Test 6 eval error argument not included in environment",
wantEvalError: true,
expr: "request.url_path.startsWith('/pkg.service/test')",
authzArgs: map[string]interface{}{"request.source_path": "/pkg.service/test"},
},
} {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any specific reason to run these tests in parallel?
Do they run for long? Do they block on something, therefore running in parallel makes sense?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I just saw the usage of t.Parallel somewhere, and thought it might help speed up the tests.
I'll remove it since this is a small test.

checked, err := compileStringToCheckedExpr(test.expr, declarations)
want, got := test.wantParsingError, err != nil
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
if got != want {
t.Fatalf("Error mismatch in conversion, test.wantParsingError =%v, got %v", want, got)
}
if test.wantParsingError {
return
}
ast := cel.CheckedExprToAst(checked)
program, err := env.Program(ast)
if err != nil {
t.Fatalf("Failed to create CEL Program: %v", err)
}
eval, _, err := program.Eval(test.authzArgs)
want, got = test.wantEvalError, err != nil
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
if got != want {
t.Fatalf("Error mismatch in evaluation, test.wantEvalError =%v, got %v", want, got)
}
if test.wantEvalError {
return
}
if eval.Value() != test.wantEvalOutcome {
t.Fatalf("Error in evaluating converted CheckedExpr: want %v, got %v", test.wantEvalOutcome, eval.Value())
}
})
}
}