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?
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.
@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])
}
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.