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

plan, privilege: add role support for SHOW GRANT #10016

Merged
merged 10 commits into from
Apr 21, 2019
Merged
Show file tree
Hide file tree
Changes from 9 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
3 changes: 2 additions & 1 deletion executor/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,7 @@ func (b *executorBuilder) buildShow(v *plannercore.Show) Executor {
Table: v.Table,
Column: v.Column,
User: v.User,
Roles: v.Roles,
IfNotExists: v.IfNotExists,
Flag: v.Flag,
Full: v.Full,
Expand Down Expand Up @@ -1253,7 +1254,7 @@ func (b *executorBuilder) buildUpdate(v *plannercore.Update) Executor {

// cols2Handle represents an mapper from column index to handle index.
type cols2Handle struct {
// start/end represent the ordinal range [start, end) of the consecutive columns.
// start and end represent the ordinal range [start, end) of the consecutive columns.
start, end int32
// handleOrdinal represents the ordinal of the handle column.
handleOrdinal int32
Expand Down
15 changes: 12 additions & 3 deletions executor/show.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ type ShowExec struct {
Column *ast.ColumnName // Used for `desc table column`.
Flag int // Some flag parsed from sql, such as FULL.
Full bool
User *auth.UserIdentity // Used for show grants.
IfNotExists bool // Used for `show create database if not exists`
User *auth.UserIdentity // Used for show grants.
Roles []*auth.RoleIdentity // Used for show grants.
IfNotExists bool // Used for `show create database if not exists`

// GlobalScope is used by show variables
GlobalScope bool
Expand Down Expand Up @@ -908,7 +909,15 @@ func (e *ShowExec) fetchShowGrants() error {
if checker == nil {
return errors.New("miss privilege checker")
}
gs, err := checker.ShowGrants(e.ctx, e.User)
for _, r := range e.Roles {
if r.Hostname == "" {
r.Hostname = "%"
}
if !checker.FindEdge(e.ctx, r, e.User) {
return ErrRoleNotGranted.GenWithStackByArgs(r.String(), e.User.String())
}
}
gs, err := checker.ShowGrants(e.ctx, e.User, e.Roles)
if err != nil {
return errors.Trace(err)
}
Expand Down
8 changes: 4 additions & 4 deletions planner/core/common_plans.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,13 +318,13 @@ type Show struct {
Column *ast.ColumnName // Used for `desc table column`.
Flag int // Some flag parsed from sql, such as FULL.
Full bool
User *auth.UserIdentity // Used for show grants.
IfNotExists bool // Used for `show create database if not exists`
User *auth.UserIdentity // Used for show grants.
Roles []*auth.RoleIdentity // Used for show grants.
IfNotExists bool // Used for `show create database if not exists`

Conditions []expression.Expression

// Used by show variables
GlobalScope bool
GlobalScope bool // Used by show variables
}

// Set represents a plan for set stmt.
Expand Down
1 change: 1 addition & 0 deletions planner/core/planbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -1026,6 +1026,7 @@ func (b *PlanBuilder) buildShow(show *ast.ShowStmt) (Plan, error) {
Flag: show.Flag,
Full: show.Full,
User: show.User,
Roles: show.Roles,
IfNotExists: show.IfNotExists,
GlobalScope: show.GlobalScope,
}.Init(b.ctx)
Expand Down
2 changes: 1 addition & 1 deletion privilege/privilege.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (k keyType) String() string {
// Manager is the interface for providing privilege related operations.
type Manager interface {
// ShowGrants shows granted privileges for user.
ShowGrants(ctx sessionctx.Context, user *auth.UserIdentity) ([]string, error)
ShowGrants(ctx sessionctx.Context, user *auth.UserIdentity, roles []*auth.RoleIdentity) ([]string, error)

// GetEncodedPassword shows the encoded password for user.
GetEncodedPassword(user, host string) string
Expand Down
132 changes: 112 additions & 20 deletions privilege/privileges/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ type defaultRoleRecord struct {

// roleGraphEdgesTable is used to cache relationship between and role.
type roleGraphEdgesTable struct {
roleList map[string]bool
roleList map[string]*auth.RoleIdentity
}

// Find method is used to find role from table
Expand All @@ -145,6 +145,33 @@ type MySQLPrivilege struct {
RoleGraph map[string]roleGraphEdgesTable
}

// FindAllRole is used to find all roles grant to this user.
func (p *MySQLPrivilege) FindAllRole(activeRoles []*auth.RoleIdentity) []*auth.RoleIdentity {
queue, head := make([]*auth.RoleIdentity, 0, len(activeRoles)), 0
for _, r := range activeRoles {
queue = append(queue, r)
}
// Using breadth first search to find all roles grant to this user.
visited, ret := make(map[string]bool), make([]*auth.RoleIdentity, 0)
for head < len(queue) {
role := queue[head]
if _, ok := visited[role.String()]; !ok {
visited[role.String()] = true
ret = append(ret, role)
key := role.Username + "@" + role.Hostname
if edgeTable, ok := p.RoleGraph[key]; ok {
for _, v := range edgeTable.roleList {
if _, ok := visited[v.String()]; !ok {
queue = append(queue, v)
}
}
}
}
head += 1
}
return ret
}

// FindRole is used to detect whether there is edges between users and roles.
func (p *MySQLPrivilege) FindRole(user string, host string, role *auth.RoleIdentity) bool {
rec := p.matchUser(user, host)
Expand Down Expand Up @@ -474,10 +501,10 @@ func (p *MySQLPrivilege) decodeRoleEdgesTable(row chunk.Row, fs []*ast.ResultFie
toKey := toUser + "@" + toHost
roleGraph, ok := p.RoleGraph[toKey]
if !ok {
roleGraph = roleGraphEdgesTable{roleList: make(map[string]bool)}
roleGraph = roleGraphEdgesTable{roleList: make(map[string]*auth.RoleIdentity)}
p.RoleGraph[toKey] = roleGraph
}
roleGraph.roleList[fromKey] = true
roleGraph.roleList[fromKey] = &auth.RoleIdentity{Username: fromUser, Hostname: fromHost}
return nil
}

Expand Down Expand Up @@ -700,50 +727,115 @@ func (p *MySQLPrivilege) DBIsVisible(user, host, db string) bool {
return false
}

func (p *MySQLPrivilege) showGrants(user, host string) []string {
func (p *MySQLPrivilege) showGrants(user, host string, roles []*auth.RoleIdentity) []string {
var gs []string
var hasGlobalGrant bool = false
// Show global grants
// Some privileges may granted from role inheritance.
// We should find these inheritance relationship.
allRoles := p.FindAllRole(roles)
// Show global grants.
var currentPriv mysql.PrivilegeType
var g string
for _, record := range p.User {
if record.User == user && record.Host == host {
hasGlobalGrant = true
g := userPrivToString(record.Privileges)
if len(g) > 0 {
s := fmt.Sprintf(`GRANT %s ON *.* TO '%s'@'%s'`, g, record.User, record.Host)
gs = append(gs, s)
currentPriv |= record.Privileges
} else {
for _, r := range allRoles {
if record.User == r.Username && record.Host == r.Hostname {
hasGlobalGrant = true
currentPriv |= record.Privileges
}
}
break // it's unique
}
}
g = userPrivToString(currentPriv)
if len(g) > 0 {
s := fmt.Sprintf(`GRANT %s ON *.* TO '%s'@'%s'`, g, user, host)
gs = append(gs, s)
}

// This is a mysql convention.
if len(gs) == 0 && hasGlobalGrant {
s := fmt.Sprintf("GRANT USAGE ON *.* TO '%s'@'%s'", user, host)
gs = append(gs, s)
}

// Show db scope grants
// Show db scope grants.
dbPrivTable := make(map[string]mysql.PrivilegeType)
for _, record := range p.DB {
if record.User == user && record.Host == host {
g := dbPrivToString(record.Privileges)
if len(g) > 0 {
s := fmt.Sprintf(`GRANT %s ON %s.* TO '%s'@'%s'`, g, record.DB, record.User, record.Host)
gs = append(gs, s)
if _, ok := dbPrivTable[record.DB]; ok {
dbPrivTable[record.DB] |= record.Privileges
} else {
tiancaiamao marked this conversation as resolved.
Show resolved Hide resolved
dbPrivTable[record.DB] = record.Privileges
}
} else {
for _, r := range allRoles {
if record.User == r.Username && record.Host == r.Hostname {
if _, ok := dbPrivTable[record.DB]; ok {
dbPrivTable[record.DB] |= record.Privileges
} else {
dbPrivTable[record.DB] = record.Privileges
tiancaiamao marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
}
}
for dbName, priv := range dbPrivTable {
g := dbPrivToString(priv)
if len(g) > 0 {
s := fmt.Sprintf(`GRANT %s ON %s.* TO '%s'@'%s'`, g, dbName, user, host)
gs = append(gs, s)
}
}

// Show table scope grants
// Show table scope grants.
tablePrivTable := make(map[string]mysql.PrivilegeType)
for _, record := range p.TablesPriv {
recordKey := record.DB + "." + record.TableName
if record.User == user && record.Host == host {
g := tablePrivToString(record.TablePriv)
if len(g) > 0 {
s := fmt.Sprintf(`GRANT %s ON %s.%s TO '%s'@'%s'`, g, record.DB, record.TableName, record.User, record.Host)
gs = append(gs, s)
if _, ok := dbPrivTable[record.DB]; ok {
tablePrivTable[recordKey] |= record.TablePriv
} else {
tablePrivTable[recordKey] = record.TablePriv
}
} else {
for _, r := range allRoles {
if record.User == r.Username && record.Host == r.Hostname {
if _, ok := dbPrivTable[record.DB]; ok {
tablePrivTable[recordKey] |= record.TablePriv
} else {
tablePrivTable[recordKey] = record.TablePriv
}
}
}
}
}
for k, priv := range tablePrivTable {
g := tablePrivToString(priv)
if len(g) > 0 {
s := fmt.Sprintf(`GRANT %s ON %s TO '%s'@'%s'`, g, k, user, host)
gs = append(gs, s)
}
}

// Show role grants.
graphKey := user + "@" + host
edgeTable, ok := p.RoleGraph[graphKey]
g = ""
if ok {
for k := range edgeTable.roleList {
role := strings.Split(k, "@")
roleName, roleHost := role[0], role[1]
if g != "" {
g += ", "
}
g += fmt.Sprintf("'%s'@'%s'", roleName, roleHost)
}
s := fmt.Sprintf(`GRANT %s TO '%s'@'%s'`, g, user, host)
gs = append(gs, s)
}
return gs
}

Expand Down
4 changes: 2 additions & 2 deletions privilege/privileges/privileges.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,15 +175,15 @@ func (p *UserPrivileges) UserPrivilegesTable() [][]types.Datum {
}

// ShowGrants implements privilege.Manager ShowGrants interface.
func (p *UserPrivileges) ShowGrants(ctx sessionctx.Context, user *auth.UserIdentity) (grants []string, err error) {
func (p *UserPrivileges) ShowGrants(ctx sessionctx.Context, user *auth.UserIdentity, roles []*auth.RoleIdentity) (grants []string, err error) {
mysqlPrivilege := p.Handle.Get()
u := user.Username
h := user.Hostname
if len(user.AuthUsername) > 0 && len(user.AuthHostname) > 0 {
u = user.AuthUsername
h = user.AuthHostname
}
grants = mysqlPrivilege.showGrants(u, h)
grants = mysqlPrivilege.showGrants(u, h, roles)
tiancaiamao marked this conversation as resolved.
Show resolved Hide resolved
if len(grants) == 0 {
err = errNonexistingGrant.GenWithStackByArgs(u, h)
}
Expand Down
Loading