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

feat(GraphQL): Adds auth for subscriptions (#5984) #6165

Merged
merged 4 commits into from
Aug 13, 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
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ require (
github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd
github.com/dgraph-io/badger/v2 v2.0.1-rc1.0.20200718033852-37ee16d8ad1c
github.com/dgraph-io/dgo/v200 v200.0.0-20200401175452-e463f9234453
github.com/dgraph-io/graphql-transport-ws v0.0.0-20200715131837-c0460019ead2
github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1
Expand All @@ -36,7 +37,7 @@ require (
github.com/google/uuid v1.0.0
github.com/gorilla/websocket v1.4.1
github.com/graph-gophers/graphql-go v0.0.0-20200309224638-dae41bde9ef9
github.com/graph-gophers/graphql-transport-ws v0.0.0-20190611222414-40c048432299
github.com/graph-gophers/graphql-transport-ws v0.0.0-20190611222414-40c048432299 // indirect
github.com/hashicorp/vault/api v1.0.4
github.com/minio/minio-go/v6 v6.0.55
github.com/mitchellh/panicwrap v1.0.0
Expand All @@ -62,7 +63,7 @@ require (
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e
golang.org/x/sync v0.0.0-20190423024810-112230192c58
golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f
golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9
golang.org/x/text v0.3.2
google.golang.org/genproto v0.0.0-20190516172635-bb713bdc0e52 // indirect
google.golang.org/grpc v1.23.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ github.com/dgraph-io/badger/v2 v2.0.1-rc1.0.20200718033852-37ee16d8ad1c h1:LoEZf
github.com/dgraph-io/badger/v2 v2.0.1-rc1.0.20200718033852-37ee16d8ad1c/go.mod h1:26P/7fbL4kUZVEVKLAKXkBXKOydDmM2p1e+NhhnBCAE=
github.com/dgraph-io/dgo/v200 v200.0.0-20200401175452-e463f9234453 h1:DTgOrw91nMIukDm/WEvdobPLl0LgeDd/JE66+24jBks=
github.com/dgraph-io/dgo/v200 v200.0.0-20200401175452-e463f9234453/go.mod h1:Co+FwJrnndSrPORO8Gdn20dR7FPTfmXr0W/su0Ve/Ig=
github.com/dgraph-io/graphql-transport-ws v0.0.0-20200715131837-c0460019ead2 h1:NSl3XXyON9bgmBJSAvr5FPrgILAovtoTs7FwdtaZZq0=
github.com/dgraph-io/graphql-transport-ws v0.0.0-20200715131837-c0460019ead2/go.mod h1:7z3c/5w0sMYYZF5bHsrh8IH4fKwG5O5Y70cPH1ZLLRQ=
github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de h1:t0UHb5vdojIDUqktM6+xJAfScFBsVpXZmqC9dsgJmeA=
github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
Expand Down
39 changes: 20 additions & 19 deletions graphql/authorization/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,11 @@ import (
)

type ctxKey string
type authVariablekey string

const (
AuthJwtCtxKey = ctxKey("authorizationJwt")
AuthVariables = authVariablekey("authVariable")
RSA256 = "RS256"
HMAC256 = "HS256"
AuthMetaHeader = "# Dgraph.Authorization "
Expand Down Expand Up @@ -208,22 +210,6 @@ func (c *CustomClaims) UnmarshalJSON(data []byte) error {
return nil
}

func ExtractAuthVariables(ctx context.Context) (map[string]interface{}, error) {
// Extract the jwt and unmarshal the jwt to get the auth variables.
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, nil
}

jwtToken := md.Get(string(AuthJwtCtxKey))
if len(jwtToken) == 0 {
return nil, nil
} else if len(jwtToken) > 1 {
return nil, fmt.Errorf("invalid jwt auth token")
}
return validateToken(jwtToken[0])
}

func (c *CustomClaims) validateAudience() error {
// If there's no audience claim, ignore
if c.Audience == nil || len(c.Audience) == 0 {
Expand All @@ -250,7 +236,23 @@ func (c *CustomClaims) validateAudience() error {
return nil
}

func validateToken(jwtStr string) (map[string]interface{}, error) {
func ExtractCustomClaims(ctx context.Context) (*CustomClaims, error) {
// return CustomClaims containing jwt and authvariables.
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return &CustomClaims{}, nil
}

jwtToken := md.Get(string(AuthJwtCtxKey))
if len(jwtToken) == 0 {
return &CustomClaims{}, nil
} else if len(jwtToken) > 1 {
return nil, fmt.Errorf("invalid jwt auth token")
}
return validateJWTCustomClaims(jwtToken[0])
}

func validateJWTCustomClaims(jwtStr string) (*CustomClaims, error) {
if metainfo.Algo == "" {
return nil, fmt.Errorf(
"jwt token cannot be validated because verification algorithm is not set")
Expand Down Expand Up @@ -290,6 +292,5 @@ func validateToken(jwtStr string) (map[string]interface{}, error) {
if err := claims.validateAudience(); err != nil {
return nil, err
}

return claims.AuthVariables, nil
return claims, nil
}
3 changes: 2 additions & 1 deletion graphql/e2e/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"os"
"strings"
"testing"
"time"

"github.com/dgraph-io/dgraph/graphql/authorization"
"github.com/dgraph-io/dgraph/graphql/e2e/common"
Expand Down Expand Up @@ -177,7 +178,7 @@ func getJWT(t *testing.T, user, role string) http.Header {
metaInfo.AuthVars["ROLE"] = role
}

jwtToken, err := metaInfo.GetSignedToken("./sample_private_key.pem")
jwtToken, err := metaInfo.GetSignedToken("./sample_private_key.pem", 300*time.Second)
require.NoError(t, err)

h := make(http.Header)
Expand Down
10 changes: 5 additions & 5 deletions graphql/e2e/common/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -1284,9 +1284,9 @@ func querynestedOnlyTypename(t *testing.T) {
},
{
"__typename": "Post"
},
},
{

"__typename": "Post"
}
]
Expand All @@ -1312,8 +1312,8 @@ func onlytypenameForInterface(t *testing.T) {
eq: [EMPIRE]
}
}) {


... on Human {
__typename
}
Expand All @@ -1327,7 +1327,7 @@ func onlytypenameForInterface(t *testing.T) {
expected := `{
"queryCharacter": [
{
"__typename": "Human"
"__typename": "Human"
},
{
"__typename": "Droid"
Expand Down
5 changes: 2 additions & 3 deletions graphql/e2e/common/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,18 @@ type GraphQLSubscriptionClient struct {
}

// NewGraphQLSubscription returns graphql subscription client.
func NewGraphQLSubscription(url string, req *schema.Request) (*GraphQLSubscriptionClient, error) {
func NewGraphQLSubscription(url string, req *schema.Request, subscriptionPayload string) (*GraphQLSubscriptionClient, error) {
header := http.Header{
"Sec-WebSocket-Protocol": []string{protocolGraphQLWS},
}
conn, _, err := websocket.DefaultDialer.Dial(url, header)
if err != nil {
return nil, err
}

// Initialize subscription.
init := operationMessage{
Type: initMsg,
Payload: []byte(`{}`),
Payload: []byte(subscriptionPayload),
}

// Send Intialization message to the graphql server.
Expand Down
22 changes: 11 additions & 11 deletions graphql/e2e/custom_logic/custom_logic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ func TestCustomQueryShouldForwardHeaders(t *testing.T) {
secretHeaders: ["Github-Api-Token"]
})
}

# Dgraph.Secret Github-Api-Token "random-fake-token"
# Dgraph.Secret app "should-be-overriden"
`
Expand Down Expand Up @@ -247,7 +247,7 @@ func TestSchemaIntrospectionForCustomQueryShouldForwardHeaders(t *testing.T) {
code: String!
name: String!
}

type Query {
myCustom(yo: CountryInput!): [Country!]!
@custom(
Expand Down Expand Up @@ -331,7 +331,7 @@ func TestCustomFieldsInSubscription(t *testing.T) {
name
}
}`,
})
}, `{}`)
require.NoError(t, err)
_, err = client.RecvMsg()
require.Contains(t, err.Error(), "Custom field `name` is not supported in graphql subscription")
Expand Down Expand Up @@ -370,7 +370,7 @@ func TestSubscriptionInNestedCustomField(t *testing.T) {
}
}
}`,
})
}, `{}`)
require.NoError(t, err)
_, err = client.RecvMsg()
require.Contains(t, err.Error(), "Custom field `anotherName` is not supported in graphql subscription")
Expand Down Expand Up @@ -1257,7 +1257,7 @@ func TestCustomLogicGraphql(t *testing.T) {
code: String
name: String
}

type Query {
getCountry1(id: ID!): Country!
@custom(
Expand Down Expand Up @@ -1292,7 +1292,7 @@ func TestCustomLogicGraphqlWithArgumentsOnFields(t *testing.T) {
code(size: Int!): String
name: String
}

type Query {
getCountry2(id: ID!): Country!
@custom(
Expand Down Expand Up @@ -1378,7 +1378,7 @@ func TestCustomLogicGraphQLValidArrayResponse(t *testing.T) {
code: String
name: String
}

type Query {
getCountries(id: ID!): [Country]
@custom(
Expand Down Expand Up @@ -2071,7 +2071,7 @@ func TestCustomGraphqlMissingRequiredArgument(t *testing.T) {
code: String!
name: String!
}

type Mutation {
addCountry1(input: CountryInput!): Country! @custom(http: {
url: "http://mock:8888/setCountry",
Expand Down Expand Up @@ -2134,7 +2134,7 @@ func TestCustomGraphqlMutation1(t *testing.T) {
code: String!
name: String!
}

type Mutation {
addCountry1(input: CountryInput!): Country! @custom(http: {
url: "http://mock:8888/setCountry"
Expand Down Expand Up @@ -2224,7 +2224,7 @@ func TestCustomGraphqlMutation2(t *testing.T) {
code: String!
name: String!
}

type Mutation {
updateCountries(name: String, std: Int): [Country!]! @custom(http: {
url: "http://mock:8888/updateCountries",
Expand Down Expand Up @@ -2279,7 +2279,7 @@ func TestForValidInputArgument(t *testing.T) {
code: String!
name: String!
}

type Query {
myCustom(yo: CountryInput!): [Country!]!
@custom(
Expand Down
Loading