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(multi-tenancy): Add mutation for guardian of galaxy to reset password of users of any namespaces #7418

Merged
merged 5 commits into from
Feb 11, 2021
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
1 change: 1 addition & 0 deletions edgraph/access.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ func AuthorizeGuardians(ctx context.Context) error {
}

func AuthGuardianOfTheGalaxy(ctx context.Context) error {
// always allow access
return nil
}

Expand Down
3 changes: 3 additions & 0 deletions edgraph/access_ee.go
Original file line number Diff line number Diff line change
Expand Up @@ -1039,6 +1039,9 @@ func authorizeSchemaQuery(ctx context.Context, er *query.ExecutionResult) error
return nil
}

// AuthGuardianOfTheGalaxy authorizes the operations for the users who belong to the guardians
// group in the galaxy namespace. This authorization is used for admin usages like creation and
// deletion of a namespace, resetting passwords across namespaces etc.
func AuthGuardianOfTheGalaxy(ctx context.Context) error {
if !x.WorkerConfig.AclEnabled {
return nil
Expand Down
43 changes: 43 additions & 0 deletions edgraph/multi_tenancy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// +build oss

/*
* Copyright 2021 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package edgraph

import "context"

type ResetPasswordInput struct {
UserID string
Password string
Namespace uint64
}

func (s *Server) CreateNamespace(ctx context.Context) (uint64, error) {
return 0, nil
}

func (s *Server) DeleteNamespace(ctx context.Context, namespace uint64) error {
return nil
}

func (s *Server) ResetPassword(ctx context.Context, ns *ResetPasswordInput) error {
return nil
}

func createGuardianAndGroot(ctx context.Context, namespace uint64) error {
return nil
}
151 changes: 151 additions & 0 deletions edgraph/multi_tenancy_ee.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// +build !oss

/*
* Copyright 2021 Dgraph Labs, Inc. All rights reserved.
*
* Licensed under the Dgraph Community License (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* https://github.com/dgraph-io/dgraph/blob/master/licenses/DCL.txt
*/

package edgraph

import (
"context"
"encoding/json"
"fmt"

"github.com/dgraph-io/dgo/v200/protos/api"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/query"
"github.com/dgraph-io/dgraph/schema"
"github.com/dgraph-io/dgraph/worker"
"github.com/dgraph-io/dgraph/x"
"github.com/golang/glog"
"github.com/pkg/errors"
)

type ResetPasswordInput struct {
UserID string
Password string
Namespace uint64
}

func (s *Server) ResetPassword(ctx context.Context, inp *ResetPasswordInput) error {
if err := AuthGuardianOfTheGalaxy(ctx); err != nil {
return errors.Wrapf(err, "Reset password got error:")
}

query := fmt.Sprintf(`{
x as updateUser(func: eq(dgraph.xid, "%s")) @filter(type(dgraph.type.User)) {
uid
}
}`, inp.UserID)

userNQuads := []*api.NQuad{
{
Subject: "uid(x)",
Predicate: "dgraph.password",
ObjectValue: &api.Value{Val: &api.Value_StrVal{StrVal: inp.Password}},
},
}
req := &Request{
req: &api.Request{
CommitNow: true,
Query: query,
Mutations: []*api.Mutation{
{
Set: userNQuads,
Cond: "@if(gt(len(x), 0))",
},
},
},
doAuth: NoAuthorize,
}
ctx = x.AttachNamespace(ctx, inp.Namespace)
resp, err := (&Server{}).doQuery(ctx, req)
if err != nil {
return errors.Wrapf(err, "Reset password for user %s in namespace %d, got error:",
inp.UserID, inp.Namespace)
}

type userNode struct {
Uid string `json:"uid"`
}

type userQryResp struct {
User []userNode `json:"updateUser"`
}
var userResp userQryResp
if err := json.Unmarshal(resp.GetJson(), &userResp); err != nil {
return errors.Wrap(err, "Reset password failed with error")
}

if len(userResp.User) == 0 {
return errors.New("Failed to reset password, user doesn't exist")
}
return nil
}

func (s *Server) CreateNamespace(ctx context.Context) (uint64, error) {
ctx = x.AttachJWTNamespace(ctx)
glog.V(2).Info("Got create namespace request from namespace: ", x.ExtractNamespace(ctx))

// Namespace creation is only allowed by the guardians of the galaxy group.
if err := AuthGuardianOfTheGalaxy(ctx); err != nil {
return 0, errors.Wrapf(err, "Creating namespace, got error:")
}

num := &pb.Num{Val: 1, Type: pb.Num_NS_ID}
ids, err := worker.AssignNsIdsOverNetwork(ctx, num)
if err != nil {
return 0, errors.Wrapf(err, "Creating namespace, got error:")
}

ns := ids.StartId
glog.V(2).Infof("Got a lease for NsID: %d", ns)

// Attach the newly leased NsID in the context in order to create guardians/groot for it.
ctx = x.AttachNamespace(ctx, ns)
m := &pb.Mutations{StartTs: worker.State.GetTimestamp(false)}
m.Schema = schema.InitialSchema(ns)
m.Types = schema.InitialTypes(ns)
_, err = query.ApplyMutations(ctx, m)
if err != nil {
return 0, err
}

if err = worker.WaitForIndexing(ctx, true); err != nil {
return 0, errors.Wrap(err, "Creating namespace, got error: ")
}
if err := createGuardianAndGroot(ctx, ids.StartId); err != nil {
return 0, errors.Wrapf(err, "Failed to create guardian and groot: ")
}
glog.V(2).Infof("Created namespace: %d", ns)
return ns, nil
}

// This function is used while creating new namespace. New namespace creation is only allowed
// by the guardians of the galaxy group.
func createGuardianAndGroot(ctx context.Context, namespace uint64) error {
if err := upsertGuardian(ctx); err != nil {
return errors.Wrap(err, "While creating Guardian")
}
if err := upsertGroot(ctx); err != nil {
return errors.Wrap(err, "While creating Groot")
}
return nil
}

func (s *Server) DeleteNamespace(ctx context.Context, namespace uint64) error {
glog.Info("Deleting namespace", namespace)
ctx = x.AttachJWTNamespace(ctx)
if err := AuthGuardianOfTheGalaxy(ctx); err != nil {
return errors.Wrapf(err, "Creating namespace, got error: ")
}
// TODO(Ahsan): We have to ban the pstore for all the groups.
ps := worker.State.Pstore
return ps.BanNamespace(namespace)
}
59 changes: 0 additions & 59 deletions edgraph/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,65 +109,6 @@ type existingGQLSchemaQryResp struct {
ExistingGQLSchema []graphQLSchemaNode `json:"ExistingGQLSchema"`
}

func (s *Server) CreateNamespace(ctx context.Context) (uint64, error) {
ctx = x.AttachJWTNamespace(ctx)
glog.V(2).Info("Got create namespace request from namespace: ", x.ExtractNamespace(ctx))

// Namespace creation is only allowed by the guardians of the galaxy group.
if err := AuthGuardianOfTheGalaxy(ctx); err != nil {
return 0, errors.Wrapf(err, "Creating namespace, got error:")
}

num := &pb.Num{Val: 1, Type: pb.Num_NS_ID}
ids, err := worker.AssignNsIdsOverNetwork(ctx, num)
if err != nil {
return 0, errors.Wrapf(err, "Creating namespace, got error:")
}

ns := ids.StartId
glog.V(2).Infof("Got a lease for NsID: %d", ns)

// Attach the newly leased NsID in the context in order to create guardians/groot for it.
ctx = x.AttachNamespace(ctx, ns)
m := &pb.Mutations{StartTs: worker.State.GetTimestamp(false)}
m.Schema = schema.InitialSchema(ns)
m.Types = schema.InitialTypes(ns)
_, err = query.ApplyMutations(ctx, m)
if err != nil {
return 0, err
}

if err = worker.WaitForIndexing(ctx, true); err != nil {
return 0, errors.Wrap(err, "Creating namespace, got error: ")
}
if err := createGuardianAndGroot(ctx, ids.StartId); err != nil {
return 0, errors.Wrapf(err, "Failed to create guardian and groot: ")
}
glog.V(2).Infof("Created namespace: %d", ns)
return ns, nil
}

// This function is used while creating new namespace. New namespace creation is only allowed
// by the guardians of the galaxy group.
func createGuardianAndGroot(ctx context.Context, namespace uint64) error {
if err := upsertGuardian(ctx); err != nil {
return errors.Wrap(err, "While creating Guardian")
}
if err := upsertGroot(ctx); err != nil {
return errors.Wrap(err, "While creating Groot")
}
return nil
}

func (s *Server) DeleteNamespace(ctx context.Context, namespace uint64) error {
glog.Info("Deleting namespace", namespace)
ctx = x.AttachJWTNamespace(ctx)
if err := AuthGuardianOfTheGalaxy(ctx); err != nil {
return errors.Wrapf(err, "Deleting namespace, got error: ")
}
return worker.ProcessDeleteNsRequest(ctx, namespace)
}

// PeriodicallyPostTelemetry periodically reports telemetry data for alpha.
func PeriodicallyPostTelemetry() {
glog.V(2).Infof("Starting telemetry data collection for alpha...")
Expand Down
1 change: 1 addition & 0 deletions graphql/admin/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,7 @@ func newAdminResolverFactory() resolve.ResolverFactory {
"draining": resolveDraining,
"export": resolveExport,
"login": resolveLogin,
"resetPassword": resolveResetPassword,
"restore": resolveRestore,
"shutdown": resolveShutdown,
}
Expand Down
18 changes: 18 additions & 0 deletions graphql/admin/endpoints_ee.go
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,18 @@ const adminTypes = `
namespaceId: Int
message: String
}

input ResetPasswordInput {
userId: String!
password: String!
namespace: Int!
}

type ResetPasswordPayload {
userId: String
message: String
namespace: Int
}
`

const adminMutations = `
Expand Down Expand Up @@ -483,6 +495,12 @@ const adminMutations = `
Delete a namespace.
"""
deleteNamespace(input: NamespaceInput!): NamespacePayload

"""
Reset password can only be used by the Guardians of the galaxy to reset password of
any user in any namespace.
"""
resetPassword(input: ResetPasswordInput!): ResetPasswordPayload
`

const adminQueries = `
Expand Down
68 changes: 68 additions & 0 deletions graphql/admin/reset_password.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright 2020 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package admin

import (
"context"
"encoding/json"
"strconv"

"github.com/dgraph-io/dgraph/edgraph"
"github.com/dgraph-io/dgraph/graphql/resolve"
"github.com/dgraph-io/dgraph/graphql/schema"
"github.com/golang/glog"
)

func resolveResetPassword(ctx context.Context, m schema.Mutation) (*resolve.Resolved, bool) {
inp, err := getPasswordInput(m)
if err != nil {
glog.Error("Failed to parse the reset password input")
}
if err = (&edgraph.Server{}).ResetPassword(ctx, inp); err != nil {
return resolve.EmptyResult(m, err), false
}

return resolve.DataResult(
m,
map[string]interface{}{
m.Name(): map[string]interface{}{
"userId": inp.UserID,
"message": "Reset password is successful",
"namespace": json.Number(strconv.Itoa(int(inp.Namespace))),
},
},
nil,
), true

}

func getPasswordInput(m schema.Mutation) (*edgraph.ResetPasswordInput, error) {
var input edgraph.ResetPasswordInput

inputArg := m.ArgValue(schema.InputArgName)
inputByts, err := json.Marshal(inputArg)

if err != nil {
return nil, schema.GQLWrapf(err, "couldn't get input argument")
}

if err := json.Unmarshal(inputByts, &input); err != nil {
return nil, schema.GQLWrapf(err, "couldn't get input argument")
}

return &input, nil
}