Skip to content

Commit

Permalink
fix(acl): fix duplicate groot user creation (#51)
Browse files Browse the repository at this point in the history
This PR adds the unique directive to the 'dgraph.xid' predicate. Prior to this change, users could
create duplicate users leading to misconfiguration of ACL.
  • Loading branch information
shivaji-dgraph committed Mar 27, 2024
1 parent ec08d12 commit 6b76bc6
Show file tree
Hide file tree
Showing 12 changed files with 618 additions and 145 deletions.
207 changes: 207 additions & 0 deletions check_upgrade/check_upgrade.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
/*
* Copyright 2024 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 checkupgrade

import (
"context"
"encoding/json"
"fmt"
"os"
"slices"
"strings"

"github.com/pkg/errors"
"github.com/spf13/cobra"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"

"github.com/dgraph-io/dgo/v230"
"github.com/dgraph-io/dgo/v230/protos/api"
"github.com/dgraph-io/dgraph/dgraphtest"
"github.com/dgraph-io/dgraph/x"
)

var (
CheckUpgrade x.SubCommand
)

const (
alphaGrpc = "grpc_port"
alphaHttp = "http_port"
)

type commandInput struct {
alphaGrpc string
alphaHttp string
}

type ACLNode struct {
UID string `json:"uid"`
DgraphXID string `json:"dgraph.xid"`
DgraphType []string `json:"dgraph.type"`
}

func setupClients(alphaGrpc, alphaHttp string) (*dgo.Dgraph, *dgraphtest.HTTPClient, error) {
d, err := grpc.Dial(alphaGrpc, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, nil, errors.Wrapf(err, "while dialing gRPC server")
}

return dgo.NewDgraphClient(api.NewDgraphClient(d)), dgraphtest.GetHttpClient(alphaHttp), nil
}

func findDuplicateNodes(aclNode []ACLNode) []ACLNode {
duplicateAclNodes := make([]ACLNode, 0)
for _, i := range aclNode {
for _, j := range aclNode {
if i.DgraphXID == j.DgraphXID && i.UID != j.UID {
duplicateAclNodes = append(duplicateAclNodes, i)
}
}
}

return duplicateAclNodes
}

func getDuplicateNodes(ctx context.Context, dg *dgo.Dgraph) ([]ACLNode, error) {
query := `{
nodes(func: has(dgraph.xid)) {
uid
dgraph.xid
dgraph.type
}
}`

resp, err := dg.NewTxn().Query(ctx, query)
if err != nil {
return nil, errors.Wrapf(err, "while querying dgraph for duplicate nodes")
}

type Nodes struct {
Nodes []ACLNode `json:"nodes"`
}
var result Nodes
if err := json.Unmarshal([]byte(resp.Json), &result); err != nil {
return nil, errors.Wrapf(err, "while unmarshalling response: %v", string(resp.Json))

}

return findDuplicateNodes(result.Nodes), nil
}

func printDuplicates(entityType string, ns uint64, nodes []ACLNode) {
if len(nodes) > 0 {
fmt.Printf("Found duplicate %ss in namespace: #%v\n", entityType, ns)
for _, node := range nodes {
fmt.Printf("dgraph.xid %v , Uid: %v\n", node.DgraphXID, node.UID)
}
}
}

func init() {
CheckUpgrade.Cmd = &cobra.Command{
Use: "checkupgrade",
Short: "Run the checkupgrade tool",
Long: "The checkupgrade tool is used to check for duplicate dgraph.xid's in the Dgraph database before upgrade.",
Run: func(cmd *cobra.Command, args []string) {
run()
},
Annotations: map[string]string{"group": "tool"},
}
CheckUpgrade.Cmd.SetHelpTemplate(x.NonRootTemplate)
flag := CheckUpgrade.Cmd.Flags()
flag.String(alphaGrpc, "127.0.0.1:9080",
"Dgraph Alpha gRPC server address")

flag.String(alphaHttp, "http://127.0.0.1:8080", "Draph Alpha HTTP(S) endpoint.")
}

func printDupDeleteMutation(nodes []ACLNode) {
if len(nodes) == 0 {
return
}
var deleteMutation strings.Builder
deleteMutation.WriteString("{\n")
deleteMutation.WriteString(" delete {\n")
for _, node := range nodes {
deleteMutation.WriteString(fmt.Sprintf("<%v> <%v> \"%v\" .\n", node.UID, "dgraph.xid", node.DgraphXID))
}
deleteMutation.WriteString(" }\n")
deleteMutation.WriteString(" }\n")

fmt.Printf("\ndelete duplicate nodes using following mutation : \n%v", deleteMutation.String())
}

func run() {
if err := checkUpgrade(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}

func checkUpgrade() error {
fmt.Println("Running check-upgrade tool")

cmdInput := parseInput()

gc, hc, err := setupClients(cmdInput.alphaGrpc, cmdInput.alphaHttp)
if err != nil {
return errors.Wrapf(err, "while setting up clients")
}

hc.LoginIntoNamespace(dgraphtest.DefaultUser, dgraphtest.DefaultPassword, x.GalaxyNamespace)
if err != nil {
return errors.Wrapf(err, "while logging into namespace: %v", x.GalaxyNamespace)
}

namespaces, err := hc.ListNamespaces()
if err != nil {
return err
}

ctx := context.Background()
for _, ns := range namespaces {
if err := gc.LoginIntoNamespace(ctx, dgraphtest.DefaultUser, dgraphtest.DefaultPassword, ns); err != nil {
return errors.Wrapf(err, "while logging into namespace: %v", ns)
}

duplicates, err := getDuplicateNodes(ctx, gc)
if err != nil {
return err
}

var duplicateUsers []ACLNode
var duplicateGroups []ACLNode

for _, node := range duplicates {
if slices.Contains(node.DgraphType, "dgraph.type.User") {
duplicateUsers = append(duplicateUsers, node)
} else if slices.Contains(node.DgraphType, "dgraph.type.Group") {
duplicateGroups = append(duplicateGroups, node)
}
}

printDuplicates("user", ns, duplicateUsers)
printDuplicates("group", ns, duplicateGroups)
printDupDeleteMutation(duplicateUsers)
printDupDeleteMutation(duplicateGroups)
}

return nil
}
func parseInput() *commandInput {
return &commandInput{alphaGrpc: CheckUpgrade.Conf.GetString(alphaGrpc), alphaHttp: CheckUpgrade.Conf.GetString(alphaHttp)}
}
2 changes: 2 additions & 0 deletions dgraph/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/viper"

checkupgrade "github.com/dgraph-io/dgraph/check_upgrade"
"github.com/dgraph-io/dgraph/dgraph/cmd/alpha"
"github.com/dgraph-io/dgraph/dgraph/cmd/bulk"
"github.com/dgraph-io/dgraph/dgraph/cmd/cert"
Expand Down Expand Up @@ -84,6 +85,7 @@ var rootConf = viper.New()
var subcommands = []*x.SubCommand{
&bulk.Bulk, &cert.Cert, &conv.Conv, &live.Live, &alpha.Alpha, &zero.Zero, &version.Version,
&debug.Debug, &migrate.Migrate, &debuginfo.DebugInfo, &upgrade.Upgrade, &decrypt.Decrypt, &increment.Increment,
&checkupgrade.CheckUpgrade,
}

func initCmds() {
Expand Down
9 changes: 9 additions & 0 deletions dgraphtest/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -751,3 +751,12 @@ func IsHigherVersion(higher, lower string) (bool, error) {

return true, nil
}

func GetHttpClient(alphaUrl string) *HTTPClient {
return &HTTPClient{
adminURL: alphaUrl + "/admin",
graphqlURL: alphaUrl + "/graphql",
dqlURL: alphaUrl + "/query",
HttpToken: &HttpToken{},
}
}
26 changes: 25 additions & 1 deletion dgraphtest/ee.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func (hc *HTTPClient) CreateGroup(name string) (string, error) {
}
resp, err := hc.RunGraphqlQuery(params, true)
if err != nil {
return "", nil
return "", err
}
type Response struct {
AddGroup struct {
Expand Down Expand Up @@ -453,3 +453,27 @@ func (hc *HTTPClient) DeleteNamespace(nsID uint64) (uint64, error) {
}
return 0, errors.New(result.DeleteNamespace.Message)
}

func (hc *HTTPClient) ListNamespaces() ([]uint64, error) {
const listNss = `{ state {
namespaces
}
}`

params := GraphQLParams{Query: listNss}
resp, err := hc.RunGraphqlQuery(params, true)
if err != nil {
return nil, err
}

var result struct {
State struct {
Namespaces []uint64 `json:"namespaces"`
} `json:"state"`
}
if err := json.Unmarshal(resp, &result); err != nil {
return nil, errors.Wrap(err, "error unmarshalling response")
}

return result.State.Namespaces, nil
}
6 changes: 3 additions & 3 deletions dgraphtest/paths.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func init() {
panic(err)
}

log.Printf("[INFO] baseRepoDir: %v", baseRepoDir)
log.Printf("[INFO] repoDir: %v", repoDir)
log.Printf("[INFO] binariesPath: %v", binariesPath)
// log.Printf("[INFO] baseRepoDir: %v", baseRepoDir)
// log.Printf("[INFO] repoDir: %v", repoDir)
// log.Printf("[INFO] binariesPath: %v", binariesPath)
}
18 changes: 18 additions & 0 deletions ee/acl/acl_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,7 @@ func (asuite *AclTestSuite) TestWrongPermission() {
defer cleanup()
require.NoError(t, gc.LoginIntoNamespace(ctx, dgraphtest.DefaultUser,
dgraphtest.DefaultPassword, x.GalaxyNamespace))
require.NoError(t, gc.DropAll())

mu := &api.Mutation{SetNquads: []byte(`
_:dev <dgraph.type> "dgraph.type.Group" .
Expand All @@ -437,3 +438,20 @@ func (asuite *AclTestSuite) TestWrongPermission() {
require.Error(t, err, "Setting permission to -1 should have returned error")
require.Contains(t, err.Error(), "Value for this predicate should be between 0 and 7")
}

func (asuite *AclTestSuite) TestACLDuplicateGrootUser() {
t := asuite.T()
gc, cleanup, err := asuite.dc.Client()
require.NoError(t, err)
defer cleanup()
require.NoError(t, gc.LoginIntoNamespace(context.Background(),
dgraphtest.DefaultUser, dgraphtest.DefaultPassword, x.GalaxyNamespace))

rdfs := `_:a <dgraph.xid> "groot" .
_:a <dgraph.type> "dgraph.type.User" .`

mu := &api.Mutation{SetNquads: []byte(rdfs), CommitNow: true}
_, err = gc.Mutate(mu)
require.Error(t, err)
require.ErrorContains(t, err, "could not insert duplicate value [groot] for predicate [dgraph.xid]")
}
Loading

0 comments on commit 6b76bc6

Please sign in to comment.