Skip to content

Commit

Permalink
added e2e test for grpc api for stream and non-stream for transaction
Browse files Browse the repository at this point in the history
Signed-off-by: Harshit Gangal <[email protected]>
  • Loading branch information
harshit-gangal committed May 25, 2023
1 parent 6c004b3 commit 5203b73
Show file tree
Hide file tree
Showing 7 changed files with 251 additions and 305 deletions.
15 changes: 15 additions & 0 deletions go/test/endtoend/cluster/cluster_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ import (
"testing"
"time"

"google.golang.org/grpc"

"vitess.io/vitess/go/vt/grpcclient"
"vitess.io/vitess/go/vt/vtgate/grpcvtgateconn"

"github.com/buger/jsonparser"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -446,3 +451,13 @@ func WaitForHealthyShard(vtctldclient *VtctldClientProcess, keyspace, shard stri
time.Sleep(defaultRetryDelay)
}
}

// DialVTGate returns a VTGate grpc connection.
func DialVTGate(ctx context.Context, name, addr, username, password string) (*vtgateconn.VTGateConn, error) {
clientCreds := &grpcclient.StaticAuthClientCreds{Username: username, Password: password}
creds := grpc.WithPerRPCCredentials(clientCreds)
dialerFunc := grpcvtgateconn.Dial(creds)
dialerName := name
vtgateconn.RegisterDialer(dialerName, dialerFunc)
return vtgateconn.DialProtocol(ctx, dialerName, addr)
}
110 changes: 110 additions & 0 deletions go/test/endtoend/vtgate/grpc_api/acl_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
Copyright 2023 The Vitess 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 grpc_api

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"vitess.io/vitess/go/test/endtoend/cluster"
"vitess.io/vitess/go/vt/callerid"
)

// TestEffectiveCallerIDWithAccess verifies that an authenticated gRPC static user with an effectiveCallerID that has ACL access can execute queries
func TestEffectiveCallerIDWithAccess(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

vtgateConn, err := cluster.DialVTGate(ctx, t.Name(), vtgateGrpcAddress, "some_other_user", "test_password")
require.NoError(t, err)
defer vtgateConn.Close()

session := vtgateConn.Session(keyspaceName+"@primary", nil)
query := "SELECT id FROM test_table"
ctx = callerid.NewContext(ctx, callerid.NewEffectiveCallerID("user_with_access", "", ""), nil)
_, err = session.Execute(ctx, query, nil)
assert.NoError(t, err)
}

// TestEffectiveCallerIDWithNoAccess verifies that an authenticated gRPC static user without an effectiveCallerID that has ACL access cannot execute queries
func TestEffectiveCallerIDWithNoAccess(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

vtgateConn, err := cluster.DialVTGate(ctx, t.Name(), vtgateGrpcAddress, "another_unrelated_user", "test_password")
require.NoError(t, err)
defer vtgateConn.Close()

session := vtgateConn.Session(keyspaceName+"@primary", nil)
query := "SELECT id FROM test_table"
ctx = callerid.NewContext(ctx, callerid.NewEffectiveCallerID("user_no_access", "", ""), nil)
_, err = session.Execute(ctx, query, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "Select command denied to user")
assert.Contains(t, err.Error(), "for table 'test_table' (ACL check error)")
}

// TestAuthenticatedUserWithAccess verifies that an authenticated gRPC static user with ACL access can execute queries
func TestAuthenticatedUserWithAccess(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

vtgateConn, err := cluster.DialVTGate(ctx, t.Name(), vtgateGrpcAddress, "user_with_access", "test_password")
require.NoError(t, err)
defer vtgateConn.Close()

session := vtgateConn.Session(keyspaceName+"@primary", nil)
query := "SELECT id FROM test_table"
_, err = session.Execute(ctx, query, nil)
assert.NoError(t, err)
}

// TestAuthenticatedUserNoAccess verifies that an authenticated gRPC static user with no ACL access cannot execute queries
func TestAuthenticatedUserNoAccess(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

vtgateConn, err := cluster.DialVTGate(ctx, t.Name(), vtgateGrpcAddress, "user_no_access", "test_password")
require.NoError(t, err)
defer vtgateConn.Close()

session := vtgateConn.Session(keyspaceName+"@primary", nil)
query := "SELECT id FROM test_table"
_, err = session.Execute(ctx, query, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "Select command denied to user")
assert.Contains(t, err.Error(), "for table 'test_table' (ACL check error)")
}

// TestUnauthenticatedUser verifies that an unauthenticated gRPC user cannot execute queries
func TestUnauthenticatedUser(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

vtgateConn, err := cluster.DialVTGate(ctx, t.Name(), vtgateGrpcAddress, "", "")
require.NoError(t, err)
defer vtgateConn.Close()

session := vtgateConn.Session(keyspaceName+"@primary", nil)
query := "SELECT id FROM test_table"
_, err = session.Execute(ctx, query, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid credentials")
}
114 changes: 114 additions & 0 deletions go/test/endtoend/vtgate/grpc_api/execute_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package grpc_api

import (
"context"
"fmt"
"io"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/test/endtoend/cluster"
querypb "vitess.io/vitess/go/vt/proto/query"
vtgatepb "vitess.io/vitess/go/vt/proto/vtgate"
"vitess.io/vitess/go/vt/vtgate/vtgateconn"
)

func TestTransctionsWithGRPCAPI(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

vtgateConn, err := cluster.DialVTGate(ctx, t.Name(), vtgateGrpcAddress, "user_with_access", "test_password")
require.NoError(t, err)
defer vtgateConn.Close()

vtSession := vtgateConn.Session(keyspaceName, nil)
workload := []string{"OLTP", "OLAP"}
for i := 0; i < 4; i++ { // running all switch combinations.
index := i % len(workload)
_, session, err := exec(ctx, vtSession, fmt.Sprintf("set workload = %s", workload[index]), nil)
require.NoError(t, err)

require.Equal(t, workload[index], session.Options.Workload.String())
execTest(ctx, t, workload[index], vtSession)
}

}

func execTest(ctx context.Context, t *testing.T, workload string, vtSession *vtgateconn.VTGateSession) {
tcases := []struct {
query string

expRowCount int
expRowAffected int
expInTransaction bool
}{{
query: "select id, val from test_table",
}, {
query: "begin",
expInTransaction: true,
}, {
query: "insert into test_table(id, val) values (1, 'A')",
expRowAffected: 1,
expInTransaction: true,
}, {
query: "select id, val from test_table",
expRowCount: 1,
expInTransaction: true,
}, {
query: "commit",
}, {
query: "select id, val from test_table",
expRowCount: 1,
}, {
query: "delete from test_table",
expRowAffected: 1,
}}

for _, tc := range tcases {
t.Run(workload+":"+tc.query, func(t *testing.T) {
qr, session, err := exec(ctx, vtSession, tc.query, nil)
require.NoError(t, err)

assert.Len(t, qr.Rows, tc.expRowCount)
assert.EqualValues(t, tc.expRowAffected, qr.RowsAffected)
assert.EqualValues(t, tc.expInTransaction, session.InTransaction)
})
}
}

func exec(ctx context.Context, conn *vtgateconn.VTGateSession, sql string, bv map[string]*querypb.BindVariable) (*sqltypes.Result, *vtgatepb.Session, error) {
options := conn.SessionPb().GetOptions()
if options != nil && options.Workload == querypb.ExecuteOptions_OLAP {
return streamExec(ctx, conn, sql, bv)
}
res, err := conn.Execute(ctx, sql, bv)
return res, conn.SessionPb(), err
}

func streamExec(ctx context.Context, conn *vtgateconn.VTGateSession, sql string, bv map[string]*querypb.BindVariable) (*sqltypes.Result, *vtgatepb.Session, error) {
stream, err := conn.StreamExecute(ctx, sql, bv)
if err != nil {
return nil, conn.SessionPb(), err
}
result := &sqltypes.Result{}
for {
res, err := stream.Recv()
if err != nil {
if err == io.EOF {
return result, conn.SessionPb(), nil
}
return nil, conn.SessionPb(), err
}
result.Rows = append(result.Rows, res.Rows...)
result.RowsAffected += res.RowsAffected
if res.InsertID != 0 {
result.InsertID = res.InsertID
}
if res.Fields != nil {
result.Fields = res.Fields
}
}
}
Original file line number Diff line number Diff line change
@@ -1,39 +1,13 @@
/*
Copyright 2023 The Vitess 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 grpc_server_acls
package grpc_api

import (
"context"
"flag"
"fmt"
"os"
"path"
"testing"

"vitess.io/vitess/go/vt/callerid"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"

"vitess.io/vitess/go/test/endtoend/cluster"
"vitess.io/vitess/go/vt/grpcclient"
"vitess.io/vitess/go/vt/vtgate/grpcvtgateconn"
"vitess.io/vitess/go/vt/vtgate/vtgateconn"
)

var (
Expand All @@ -58,6 +32,14 @@ var (
{
"Username": "another_unrelated_user",
"Password": "test_password"
},
{
"Username": "user_with_access",
"Password": "test_password"
},
{
"Username": "user_no_access",
"Password": "test_password"
}
]
`
Expand All @@ -77,7 +59,6 @@ var (
)

func TestMain(m *testing.M) {

defer cluster.PanicHandler(nil)
flag.Parse()

Expand Down Expand Up @@ -144,53 +125,6 @@ func TestMain(m *testing.M) {
os.Exit(exitcode)
}

// TestEffectiveCallerIDWithAccess verifies that an authenticated gRPC static user with an effectiveCallerID that has ACL access can execute queries
func TestEffectiveCallerIDWithAccess(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

vtgateConn, err := dialVTGate(ctx, t, "some_other_user", "test_password")
if err != nil {
t.Fatal(err)
}
defer vtgateConn.Close()

session := vtgateConn.Session(keyspaceName+"@primary", nil)
query := "SELECT id FROM test_table"
ctx = callerid.NewContext(ctx, callerid.NewEffectiveCallerID("user_with_access", "", ""), nil)
_, err = session.Execute(ctx, query, nil)
assert.NoError(t, err)
}

// TestEffectiveCallerIDWithNoAccess verifies that an authenticated gRPC static user without an effectiveCallerID that has ACL access cannot execute queries
func TestEffectiveCallerIDWithNoAccess(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

vtgateConn, err := dialVTGate(ctx, t, "another_unrelated_user", "test_password")
if err != nil {
t.Fatal(err)
}
defer vtgateConn.Close()

session := vtgateConn.Session(keyspaceName+"@primary", nil)
query := "SELECT id FROM test_table"
ctx = callerid.NewContext(ctx, callerid.NewEffectiveCallerID("user_no_access", "", ""), nil)
_, err = session.Execute(ctx, query, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "Select command denied to user")
assert.Contains(t, err.Error(), "for table 'test_table' (ACL check error)")
}

func dialVTGate(ctx context.Context, t *testing.T, username string, password string) (*vtgateconn.VTGateConn, error) {
clientCreds := &grpcclient.StaticAuthClientCreds{Username: username, Password: password}
creds := grpc.WithPerRPCCredentials(clientCreds)
dialerFunc := grpcvtgateconn.Dial(creds)
dialerName := t.Name()
vtgateconn.RegisterDialer(dialerName, dialerFunc)
return vtgateconn.DialProtocol(ctx, dialerName, vtgateGrpcAddress)
}

func createFile(path string, contents string) error {
f, err := os.Create(path)
if err != nil {
Expand Down
Loading

0 comments on commit 5203b73

Please sign in to comment.