Skip to content

Fix(GraphQL): Add support for using auth with secret directive #6907

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

Merged
merged 4 commits into from
Nov 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
152 changes: 152 additions & 0 deletions graphql/e2e/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import (
"strings"
"testing"

"github.com/google/go-cmp/cmp/cmpopts"

"github.com/dgraph-io/dgraph/graphql/e2e/common"
"github.com/dgraph-io/dgraph/testutil"
"github.com/dgrijalva/jwt-go/v4"
Expand Down Expand Up @@ -97,6 +99,7 @@ type Log struct {
Id string `json:"id,omitempty"`
Logs string `json:"logs,omitempty"`
Random string `json:"random,omitempty"`
Pwd string `json:"pwd,omitempty"`
}

type ComplexLog struct {
Expand Down Expand Up @@ -1615,3 +1618,152 @@ func TestChildCountQueryWithOtherFields(t *testing.T) {
})
}
}

func checkLogPassword(t *testing.T, logID, pwd, role string) *common.GraphQLResponse {
// Check Log Password for given logID, pwd, role
checkLogParamsFalse := &common.GraphQLParams{
Headers: common.GetJWT(t, "SomeUser", role, metaInfo),
Query: `query checkLogPassword($name: ID!, $pwd: String!) {
checkLogPassword(id: $name, pwd: $pwd) { id }
}`,
Variables: map[string]interface{}{
"name": logID,
"pwd": pwd,
},
}

gqlResponse := checkLogParamsFalse.ExecuteAsPost(t, graphqlURL)
common.RequireNoGQLErrors(t, gqlResponse)
return gqlResponse
}

func deleteLog(t *testing.T, logID string) {
deleteLogParams := &common.GraphQLParams{
Query: `
mutation DelLog($logID: ID!) {
deleteLog(filter:{id:[$logID]}) {
numUids
}
}
`,
Variables: map[string]interface{}{"logID": logID},
Headers: common.GetJWT(t, "SomeUser", "ADMIN", metaInfo),
}
gqlResponse := deleteLogParams.ExecuteAsPost(t, graphqlURL)
require.Nil(t, gqlResponse.Errors)
}

func deleteUser(t *testing.T, username string) {
deleteUserParams := &common.GraphQLParams{
Headers: common.GetJWT(t, username, "ADMIN", metaInfo),
Query: `
mutation DelUser($username: String!) {
deleteUser(filter:{username: {eq: $username } } ) {
numUids
}
}
`,
Variables: map[string]interface{}{"username": username},
}
gqlResponse := deleteUserParams.ExecuteAsPost(t, graphqlURL)
require.Nil(t, gqlResponse.Errors)
}

func TestAuthWithSecretDirective(t *testing.T) {

// Check that no auth rule is applied to checkUserPassword query.
newUser := &common.User{
Username: "Test User",
Password: "password",
IsPublic: true,
}

addUserParams := &common.GraphQLParams{
Query: `mutation addUser($user: [AddUserInput!]!) {
addUser(input: $user) {
user {
username
}
}
}`,
Variables: map[string]interface{}{"user": []*common.User{newUser}},
}

gqlResponse := addUserParams.ExecuteAsPost(t, graphqlURL)
require.Equal(t, `{"addUser":{"user":[{"username":"Test User"}]}}`,
string(gqlResponse.Data))

checkUserParams := &common.GraphQLParams{
Query: `query checkUserPassword($name: String!, $pwd: String!) {
checkUserPassword(username: $name, password: $pwd) {
username
isPublic
}
}`,
Variables: map[string]interface{}{
"name": newUser.Username,
"pwd": newUser.Password,
},
}

gqlResponse = checkUserParams.ExecuteAsPost(t, graphqlURL)
common.RequireNoGQLErrors(t, gqlResponse)

var result struct {
CheckUserPassword *common.User `json:"checkUserPassword,omitempty"`
}

err := json.Unmarshal([]byte(gqlResponse.Data), &result)
require.Nil(t, err)

opt := cmpopts.IgnoreFields(common.User{}, "Password")
if diff := cmp.Diff(newUser, result.CheckUserPassword, opt); diff != "" {
t.Errorf("result mismatch (-want +got):\n%s", diff)
}
deleteUser(t, newUser.Username)

// Check that checkLogPassword works with RBAC rule
newLog := &Log{
Pwd: "password",
}

addLogParams := &common.GraphQLParams{
Headers: common.GetJWT(t, "Random", "ADMIN", metaInfo),
Query: `mutation addLog($log: [AddLogInput!]!) {
addLog(input: $log) {
log {
id
}
}
}`,
Variables: map[string]interface{}{"log": []*Log{newLog}},
}

gqlResponse = addLogParams.ExecuteAsPost(t, graphqlURL)
var addLogResult struct {
AddLog struct {
Log []*Log
}
}

err = json.Unmarshal([]byte(gqlResponse.Data), &addLogResult)
require.Nil(t, err)
// Id of the created log
logID := addLogResult.AddLog.Log[0].Id

// checkLogPassword with RBAC rule true should work
gqlResponse = checkLogPassword(t, logID, newLog.Pwd, "Admin")
var resultLog struct {
CheckLogPassword *Log `json:"checkLogPassword,omitempty"`
}

err = json.Unmarshal([]byte(gqlResponse.Data), &resultLog)
require.Nil(t, err)

require.Equal(t, resultLog.CheckLogPassword.Id, logID)

// checkLogPassword with RBAC rule false should not work
gqlResponse = checkLogPassword(t, logID, newLog.Pwd, "USER")
require.JSONEq(t, `{"checkLogPassword": null}`, string(gqlResponse.Data))
deleteLog(t, logID)
}
61 changes: 52 additions & 9 deletions graphql/e2e/auth/schema.graphql
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type User @auth(
type User @secret(field: "password") @auth(
delete: { and: [
{ rule: """
query($USER: String!) {
Expand Down Expand Up @@ -262,11 +262,12 @@ type Issue @auth(
random: String
}

type Log @auth(
query: { rule: "{$ROLE: { eq: \"ADMIN\" }}" },
add: { rule: "{$ROLE: { eq: \"ADMIN\" }}" },
update: { rule: "{$ROLE: { eq: \"ADMIN\" }}" },
delete: { rule: "{$ROLE: { eq: \"ADMIN\" }}" },
type Log @secret(field: "pwd") @auth(
password: { rule: "{$ROLE: { eq: \"Admin\" } }"},
query: { rule: "{$ROLE: { eq: \"ADMIN\" }}" },
add: { rule: "{$ROLE: { eq: \"ADMIN\" }}" },
update: { rule: "{$ROLE: { eq: \"ADMIN\" }}" },
delete: { rule: "{$ROLE: { eq: \"ADMIN\" }}" },
) {
id: ID!
logs: String
Expand Down Expand Up @@ -301,7 +302,19 @@ type ComplexLog @auth(
visible: Boolean @search
}

type Project @auth(
type Project @secret(field: "pwd") @auth(
password: { or: [
{ rule: """query($USER: String!) {
queryProject {
roles(filter: { permission: { eq: EDIT } }) {
assignedTo(filter: { username: { eq: $USER } }) {
__typename
}
}
}
}""" },
{ rule: "{$ROLE: { eq: \"ADMIN\" }}" }
]},
query: { or: [
{ rule: """query($USER: String!) {
queryProject {
Expand Down Expand Up @@ -401,6 +414,18 @@ enum Permission {
}

type Column @auth(
password: { rule: """
query($USER: String!) {
queryColumn {
inProject {
roles(filter: { permission: { eq: EDIT } } ) {
assignedTo(filter: { username: { eq: $USER } }) {
__typename
}
}
}
}
}"""},
query: { rule: """
query($USER: String!) {
queryColumn {
Expand Down Expand Up @@ -591,7 +616,8 @@ type Author {
posts: [Post] @hasInverse(field: author)
}

interface Post @auth(
interface Post @secret(field: "pwd") @auth(
password: { rule: "{$ROLE: { eq: \"Admin\" } }"},
query: { rule: """
query($USER: String!) {
queryPost{
Expand Down Expand Up @@ -643,6 +669,13 @@ interface MsgPost @auth(
}

type Question implements Post @auth(
password:{ rule: """
query($ANS: Boolean!) {
queryQuestion(filter: { answered: $ANS } ) {
id
text
}
}""" },
query:{ rule: """
query($ANS: Boolean!) {
queryQuestion(filter: { answered: $ANS } ) {
Expand Down Expand Up @@ -671,7 +704,17 @@ type Question implements Post @auth(
answered: Boolean @search
}

type FbPost implements Post & MsgPost {
type FbPost implements Post & MsgPost @auth(
password: { rule: """
query($USER: String!) {
queryFbPost{
author(filter: {name: {eq: $USER}}){
name
}
}
}"""
}
) {
postCount: Int
}

Expand Down
3 changes: 2 additions & 1 deletion graphql/e2e/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ type User struct {
Age uint64 `json:"age,omitempty"`
IsPublic bool `json:"isPublic,omitempty"`
Disabled bool `json:"disabled,omitempty"`
Password string `json:"password,omitempty"`
}

type country struct {
Expand Down Expand Up @@ -360,6 +361,7 @@ func RunAll(t *testing.T) {
t.Run("query count at child level", queryCountAtChildLevel)
t.Run("query count at child level with filter", queryCountAtChildLevelWithFilter)
t.Run("query count and other fields at child level", queryCountAndOtherFieldsAtChildLevel)
t.Run("checkUserPassword query", passwordTest)

// mutation tests
t.Run("add mutation", addMutation)
Expand Down Expand Up @@ -392,7 +394,6 @@ func RunAll(t *testing.T) {
addMutationWithReverseDgraphEdge)
t.Run("numUids test", testNumUids)
t.Run("empty delete", mutationEmptyDelete)
t.Run("password in mutation", passwordTest)
t.Run("duplicate xid in single mutation", deepMutationDuplicateXIDsSameObjectTest)
t.Run("query typename in mutation payload", queryTypenameInMutationPayload)
t.Run("ensure alias in mutation payload", ensureAliasInMutationPayload)
Expand Down
85 changes: 0 additions & 85 deletions graphql/e2e/common/mutation.go
Original file line number Diff line number Diff line change
Expand Up @@ -3285,95 +3285,10 @@ func testNumUids(t *testing.T) {
cleanUp(t, []*country{newCountry}, nil, nil)
}

func checkUser(t *testing.T, userObj, expectedObj *user) {
checkUserParams := &GraphQLParams{
Query: `query checkUserPassword($name: String!, $pwd: String!) {
checkUserPassword(name: $name, password: $pwd) { name }
}`,
Variables: map[string]interface{}{
"name": userObj.Name,
"pwd": userObj.Password,
},
}

gqlResponse := checkUserParams.ExecuteAsPost(t, GraphqlURL)
RequireNoGQLErrors(t, gqlResponse)

var result struct {
CheckUserPasword *user `json:"checkUserPassword,omitempty"`
}

err := json.Unmarshal([]byte(gqlResponse.Data), &result)
require.Nil(t, err)

opt := cmpopts.IgnoreFields(user{}, "Password")
if diff := cmp.Diff(expectedObj, result.CheckUserPasword, opt); diff != "" {
t.Errorf("result mismatch (-want +got):\n%s", diff)
}
}

func deleteUser(t *testing.T, userObj user) {
deleteGqlType(t, "User", getXidFilter("name", []string{userObj.Name}), 1, nil)
}

func passwordTest(t *testing.T) {
newUser := &user{
Name: "Test User",
Password: "password",
}

addUserParams := &GraphQLParams{
Query: `mutation addUser($user: [AddUserInput!]!) {
addUser(input: $user) {
user {
name
}
}
}`,
Variables: map[string]interface{}{"user": []*user{newUser}},
}

updateUserParams := &GraphQLParams{
Query: `mutation addUser($user: UpdateUserInput!) {
updateUser(input: $user) {
user {
name
}
}
}`,
Variables: map[string]interface{}{"user": map[string]interface{}{
"filter": map[string]interface{}{
"name": map[string]interface{}{
"eq": newUser.Name,
},
},
"set": map[string]interface{}{
"password": "password_new",
},
}},
}

t.Run("Test add and update user", func(t *testing.T) {
gqlResponse := postExecutor(t, GraphqlURL, addUserParams)
RequireNoGQLErrors(t, gqlResponse)
require.Equal(t, `{"addUser":{"user":[{"name":"Test User"}]}}`,
string(gqlResponse.Data))

checkUser(t, newUser, newUser)
checkUser(t, &user{Name: "Test User", Password: "Wrong Pass"}, nil)

gqlResponse = postExecutor(t, GraphqlURL, updateUserParams)
RequireNoGQLErrors(t, gqlResponse)
require.Equal(t, `{"updateUser":{"user":[{"name":"Test User"}]}}`,
string(gqlResponse.Data))
checkUser(t, newUser, nil)
updatedUser := &user{Name: newUser.Name, Password: "password_new"}
checkUser(t, updatedUser, updatedUser)
})

deleteUser(t, *newUser)
}

func threeLevelDeepMutation(t *testing.T) {
newStudent := &student{
Xid: "HS1",
Expand Down
Loading