Skip to content
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

Add Validating Directives #583

Merged
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
5 changes: 5 additions & 0 deletions directives/visitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,8 @@ type Resolver interface {
type ResolverInterceptor interface {
Resolve(ctx context.Context, args interface{}, next Resolver) (output interface{}, err error)
}

// Validator directive which executes before anything is resolved, allowing the request to be rejected.
type Validator interface {
Validate(ctx context.Context, args interface{}) error
}
8 changes: 4 additions & 4 deletions example/directives/authorization/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,16 +80,16 @@ $ curl 'http://localhost:8080/query' \
return "hasRole"
}

func (h *HasRoleDirective) Resolve(ctx context.Context, args interface{}, next directives.Resolver) (output interface{}, err error) {
func (h *HasRoleDirective) Validate(ctx context.Context, _ interface{}) error {
u, ok := user.FromContext(ctx)
if !ok {
return nil, fmt.Errorf("user not provided in context")
return fmt.Errorf("user not provided in context")
}
role := strings.ToLower(h.Role)
if !u.HasRole(role) {
return nil, fmt.Errorf("access denied, %q role required", role)
return fmt.Errorf("access denied, %q role required", role)
}
return next.Resolve(ctx, args)
return nil
}
```

Expand Down
9 changes: 4 additions & 5 deletions example/directives/authorization/authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"fmt"
"strings"

"github.com/graph-gophers/graphql-go/directives"
"github.com/graph-gophers/graphql-go/example/directives/authorization/user"
)

Expand Down Expand Up @@ -36,17 +35,17 @@ func (h *HasRoleDirective) ImplementsDirective() string {
return "hasRole"
}

func (h *HasRoleDirective) Resolve(ctx context.Context, args interface{}, next directives.Resolver) (output interface{}, err error) {
func (h *HasRoleDirective) Validate(ctx context.Context, _ interface{}) error {
u, ok := user.FromContext(ctx)
if !ok {
return nil, fmt.Errorf("user not provided in cotext")
return fmt.Errorf("user not provided in cotext")
}
role := strings.ToLower(h.Role)
if !u.HasRole(role) {
return nil, fmt.Errorf("access denied, %q role required", role)
return fmt.Errorf("access denied, %q role required", role)
}

return next.Resolve(ctx, args)
return nil
}

type Resolver struct{}
Expand Down
42 changes: 35 additions & 7 deletions example_directives_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"os"
"strings"

"github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/directives"
Expand All @@ -22,11 +23,31 @@ func (h *HasRoleDirective) ImplementsDirective() string {
return "hasRole"
}

func (h *HasRoleDirective) Resolve(ctx context.Context, in interface{}, next directives.Resolver) (interface{}, error) {
func (h *HasRoleDirective) Validate(ctx context.Context, _ interface{}) error {
if ctx.Value(RoleKey) != h.Role {
return nil, fmt.Errorf("access deinied, role %q required", h.Role)
return fmt.Errorf("access denied, role %q required", h.Role)
}
return next.Resolve(ctx, in)
return nil
}

type UpperDirective struct{}

func (d *UpperDirective) ImplementsDirective() string {
return "upper"
}

func (d *UpperDirective) Resolve(ctx context.Context, args interface{}, next directives.Resolver) (interface{}, error) {
out, err := next.Resolve(ctx, args)
if err != nil {
return out, err
}

s, ok := out.(string)
if !ok {
return out, nil
}

return strings.ToUpper(s), nil
}

type authResolver struct{}
Expand All @@ -43,13 +64,14 @@ func ExampleDirectives() {
}

directive @hasRole(role: String!) on FIELD_DEFINITION
directive @upper on FIELD_DEFINITION

type Query {
greet(name: String!): String! @hasRole(role: "admin")
greet(name: String!): String! @hasRole(role: "admin") @upper
}
`
opts := []graphql.SchemaOpt{
graphql.Directives(&HasRoleDirective{}),
graphql.Directives(&HasRoleDirective{}, &UpperDirective{}),
// other options go here
}
schema := graphql.MustParseSchema(s, &authResolver{}, opts...)
Expand Down Expand Up @@ -86,7 +108,13 @@ func ExampleDirectives() {
// {
// "errors": [
// {
// "message": "access deinied, role \"admin\" required",
// "message": "access denied, role \"admin\" required",
// "locations": [
// {
// "line": 10,
// "column": 4
// }
// ],
// "path": [
// "greet"
// ]
Expand All @@ -97,7 +125,7 @@ func ExampleDirectives() {
// Admin user result:
// {
// "data": {
// "greet": "Hello, GraphQL!"
// "greet": "HELLO, GRAPHQL!"
// }
// }
}
201 changes: 201 additions & 0 deletions graphql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"

"github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/directives"
gqlerrors "github.com/graph-gophers/graphql-go/errors"
"github.com/graph-gophers/graphql-go/example/social"
"github.com/graph-gophers/graphql-go/example/starwars"
"github.com/graph-gophers/graphql-go/gqltesting"
"github.com/graph-gophers/graphql-go/introspection"
Expand Down Expand Up @@ -477,6 +479,205 @@ func TestCustomDirective(t *testing.T) {
})
}

func TestCustomValidatingDirective(t *testing.T) {
t.Parallel()

gqltesting.RunTests(t, []*gqltesting.Test{
{
Schema: graphql.MustParseSchema(`
directive @hasRole(role: String!) on FIELD_DEFINITION

schema {
query: Query
}

type Query {
hello: String! @hasRole(role: "ADMIN")
}`,
&helloResolver{},
graphql.Directives(&HasRoleDirective{}),
),
Context: context.WithValue(context.Background(), RoleKey, "USER"),
Query: `
{
hello
}
`,
ExpectedResult: "null",
ExpectedErrors: []*gqlerrors.QueryError{
{Message: `access denied, role "ADMIN" required`, Locations: []gqlerrors.Location{{Line: 9, Column: 6}}, Path: []interface{}{"hello"}},
},
},
{
Schema: graphql.MustParseSchema(`
directive @hasRole(role: String!) on FIELD_DEFINITION

schema {
query: Query
}

type Query {
hello: String! @hasRole(role: "ADMIN")
}`,
&helloResolver{},
graphql.Directives(&HasRoleDirective{}),
),
Context: context.WithValue(context.Background(), RoleKey, "ADMIN"),
Query: `
{
hello
}
`,
ExpectedResult: `
{
"hello": "Hello world!"
}
`,
},
{
Schema: graphql.MustParseSchema(
`directive @hasRole(role: String!) on FIELD_DEFINITION

`+strings.ReplaceAll(
social.Schema,
"role: Role!",
`role: Role! @hasRole(role: "ADMIN")`,
),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(nitpick) You could have used schema extension here : )

I'll add examples how to do that soon.

&social.Resolver{},
graphql.Directives(&HasRoleDirective{}),
graphql.UseFieldResolvers(),
),
Context: context.WithValue(context.Background(), RoleKey, "ADMIN"),
Query: `
query {
user(id: "0x01") {
role
... on User {
email
}
... on Person {
name
}
}
}
`,
ExpectedResult: `
{
"user": {
"role": "ADMIN",
"email": "[email protected]",
"name": "Albus Dumbledore"
}
}
`,
},
{
Schema: graphql.MustParseSchema(
`directive @hasRole(role: String!) on FIELD_DEFINITION

`+strings.ReplaceAll(
starwars.Schema,
"hero(episode: Episode = NEWHOPE): Character",
`hero(episode: Episode = NEWHOPE): Character @hasRole(role: "REBELLION")`,
),
&starwars.Resolver{},
graphql.Directives(&HasRoleDirective{}),
),
Context: context.WithValue(context.Background(), RoleKey, "EMPIRE"),
Query: `
query HeroesOfTheRebellion($episode: Episode!) {
hero(episode: $episode) {
id name
... on Human { starships { id name } }
... on Droid { primaryFunction }
}
}
`,
Variables: map[string]interface{}{"episode": "NEWHOPE"},
ExpectedResult: "null",
ExpectedErrors: []*gqlerrors.QueryError{
{Message: `access denied, role "REBELLION" required`, Locations: []gqlerrors.Location{{Line: 10, Column: 3}}, Path: []interface{}{"hero"}},
},
},
{
Schema: graphql.MustParseSchema(
`directive @hasRole(role: String!) on FIELD_DEFINITION

`+strings.ReplaceAll(
starwars.Schema,
"starships: [Starship]",
`starships: [Starship] @hasRole(role: "REBELLION")`,
),
&starwars.Resolver{},
graphql.Directives(&HasRoleDirective{}),
),
Context: context.WithValue(context.Background(), RoleKey, "EMPIRE"),
Query: `
query HeroesOfTheRebellion($episode: Episode!) {
hero(episode: $episode) {
id name
... on Human { starships { id name } }
... on Droid { primaryFunction }
}
}
`,
Variables: map[string]interface{}{"episode": "NEWHOPE"},
ExpectedResult: "null",
ExpectedErrors: []*gqlerrors.QueryError{
{Message: `access denied, role "REBELLION" required`, Locations: []gqlerrors.Location{{Line: 68, Column: 3}}, Path: []interface{}{"hero", "starships"}},
},
},
{
Schema: graphql.MustParseSchema(
`directive @restrictImperialUnits on FIELD_DEFINITION

`+strings.ReplaceAll(
starwars.Schema,
"height(unit: LengthUnit = METER): Float!",
`height(unit: LengthUnit = METER): Float! @restrictImperialUnits`,
),
&starwars.Resolver{},
graphql.Directives(&restrictImperialUnitsDirective{}),
),
Context: context.WithValue(context.Background(), RoleKey, "REBELLION"),
Query: `
query HeroesOfTheRebellion($episode: Episode!) {
hero(episode: $episode) {
id name
... on Human { height(unit: FOOT) }
}
}
`,
Variables: map[string]interface{}{"episode": "NEWHOPE"},
ExpectedResult: "null",
ExpectedErrors: []*gqlerrors.QueryError{
{Message: `rebels cannot request imperial units`, Locations: []gqlerrors.Location{{Line: 58, Column: 3}}, Path: []interface{}{"hero", "height"}},
},
},
})
}

type restrictImperialUnitsDirective struct{}

func (d *restrictImperialUnitsDirective) ImplementsDirective() string {
return "restrictImperialUnits"
}

func (d *restrictImperialUnitsDirective) Validate(ctx context.Context, args interface{}) error {
if ctx.Value(RoleKey) == "EMPIRE" {
return nil
}

v, ok := args.(struct {
Unit string
})
if ok && v.Unit == "FOOT" {
return fmt.Errorf("rebels cannot request imperial units")
}

return nil
}

func TestCustomDirectiveStructFieldResolver(t *testing.T) {
t.Parallel()

Expand Down
12 changes: 12 additions & 0 deletions internal/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ func (r *Request) Execute(ctx context.Context, s *resolvable.Schema, op *ast.Ope
default:
panic("unknown query operation")
}

if errs := validateSelections(ctx, sels, nil, s); errs != nil {
r.Errs = errs
out.Write([]byte("null"))
return
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can add a global short circuit here. If the schema doesn't have any validation directives, then this entire block can be skipped.


r.execSelections(ctx, sels, nil, s, resolver, &out, op.Type == query.Mutation)
}()

Expand All @@ -64,6 +71,11 @@ func (r *Request) Execute(ctx context.Context, s *resolvable.Schema, op *ast.Ope
return out.Bytes(), r.Errs
}

type fieldToValidate struct {
field *selected.SchemaField
sels []selected.Selection
}

type fieldToExec struct {
field *selected.SchemaField
sels []selected.Selection
Expand Down
Loading