strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
4.03k stars 536 forks source link

Add utilities for preventing malicious queries #960

Open patrick91 opened 3 years ago

patrick91 commented 3 years ago

Some ideas here: https://www.apollographql.com/blog/graphql/security/securing-your-graphql-api-from-malicious-queries/

We can definitely implement some of those :)

Upvote & Fund

Fund with Polar

jkimbo commented 3 years ago

Because graphql-core is a direct port of graphql-js I think https://github.com/stems/graphql-depth-limit can be directly ported to Python.

jkimbo commented 3 years ago

@MeRuslan points out a another useful library to implement cost analysis: https://github.com/pa-bru/graphql-cost-analysis (ref: https://github.com/strawberry-graphql/strawberry/issues/902#issuecomment-873305453). We could probably port that library to python as well.

Note that graphql-js has decided not to support adding directives through code definitions: https://github.com/graphql/graphql-js/issues/1343

jkimbo commented 3 years ago

Another simple thing would be to add an extension that prevents introspection queries. That way you can add/enable it on production only to prevent people from introspecting your schema.

Speedy1991 commented 3 years ago

Maybe this is also a thing to note: https://www.apollographql.com/docs/react/api/link/persisted-queries/

Obviousy only useful for closed API's - it makes a gql scheme more "static" with the precalculated hashes

As far i know you can limit the server to only respond to known hashes

jkimbo commented 3 years ago

Maybe this is also a thing to note: https://www.apollographql.com/docs/react/api/link/persisted-queries/

Persisted queries is the ultimate way to protect against malicious queries because it means you can’t execute a query that isn’t trusted. It’s very powerful but requires some effort with tooling to make it work well.

We should provide an extension that lets you implement persisted queries like envelop has: https://www.envelop.dev/plugins/use-persisted-operations

erikwrede commented 1 year ago

For reference from strawberry discord on cost calculation (will refine later)

Roadmap could be the following

M1: basic cost calc

Example from stellate for reference:

query {
  # Total: 18
  todos(limit: 2) {
    # (Nested: 2 + 1 + 1 + 1 + (author: 2 + 1 + 1)) * limit: 2 = 18
    id # Scalar: 1
    text # Scalar: 1
    completed # Scalar: 1
    author {
      ## Nested: 4 (2 + 1 + 1)
      id ## Scalar: 1
      name ## Scalar: 1
    }
  }
}