How can we secure the GraphQL API from malicious queries in Dgraph?

Hi guys,

We are trying to migrate from MySQL to dgraph and we want to use GraphQL API by implementing our schema after the migration, but we do not know how we can limit and prevent malicious queries.

for example what is the solution to prevent user or attacker from requesting 1000000 results(by setting first: 100000) in a query?

This article suggests some solutions when we are using GraphQL

What are the solutions when we use dgraph GraphQL?

Thanks in advance

2 Likes

Welcome to the forms @pshaddel !

Dgraph has an @auth directive that I believe you can use to do what you’re asking.

For example:

type Todo @auth(
    query: { rule: """
        query { 
            queryTodo(first: 100) { 
                id 
            } 
        }"""
    }
){
    id: ID!
    text: String! @search(by: [term])
    owner: String! @search(by: [hash])
}

This would only allow you to query up to 100 items, and you could use first in your actual code to get only the first 10 for example. These query rules, similar to policies in SQL or RLC (Row Level Security) can be quite powerful.

Basically, it filters your results before you get your actual results. You can do a lot with queries, but I believe the biggest caveat is the missing update-after rules in mutations. There seems to be an internal debate at Dgraph on the importance of validation and verification on the backend, but luckily most people realize its importance and we should hopefully see more security features in the future.

J

2 Likes

Thank you Jonathan. I just checked the query and it is working fine with filters and all the other stuff.
Good luck

1 Like

@jdgamble555 Hi Jonathan,
When I was testing this in Jun 12 it was working fine but right now it is not working and I cannot limit number of results. I created a backend with only one type exactly like what you noted down here:

type Todo
  @auth(
    query: {
      rule: """
      query {
          queryTodo(first: 2) {
              id
          }
      }
      """
    }
  ) {
  id: ID!
  text: String! @search(by: [term])
  owner: String! @search(by: [hash])
}

would you please checkout this endpoint: https://green-pine.us-east-1.aws.cloud.dgraph.io/graphql

I expect only 2 results but it returns 4 results.

I was able to reproduce this same error. I am wondering if you were recently upgraded from 20.11, and if the upgrade caused the bug? Do you know by chance?

If so, then it may be a bug that needs to be reported in 21.03.

J

I was testing it in dgraph cloud so I think this is because of the upgrade.

@MichelDiz - This is a Bug, should I create a new thread for this?

J

I created this after I realized this is a bug: