Skip to content
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
46 changes: 31 additions & 15 deletions src/common/security/robot/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package robot

import (
"context"
"fmt"
rbac_project "github.com/goharbor/harbor/src/common/rbac/project"
"github.com/goharbor/harbor/src/common/rbac/system"
"github.com/goharbor/harbor/src/controller/robot"
Expand All @@ -27,26 +28,21 @@ import (
"github.com/goharbor/harbor/src/pkg/permission/evaluator"
"github.com/goharbor/harbor/src/pkg/permission/types"
"github.com/goharbor/harbor/src/pkg/project/models"
"github.com/goharbor/harbor/src/pkg/robot/model"
)

// SecurityContext implements security.Context interface based on database
type SecurityContext struct {
robot *model.Robot
isSystemLevel bool
ctl project.Controller
policies []*types.Policy
evaluator evaluator.Evaluator
once sync.Once
robot *robot.Robot
ctl project.Controller
evaluator evaluator.Evaluator
once sync.Once
}

// NewSecurityContext ...
func NewSecurityContext(robot *model.Robot, isSystemLevel bool, policy []*types.Policy) *SecurityContext {
func NewSecurityContext(r *robot.Robot) *SecurityContext {
return &SecurityContext{
ctl: project.Ctl,
robot: robot,
policies: policy,
isSystemLevel: isSystemLevel,
ctl: project.Ctl,
robot: r,
}
}

Expand All @@ -69,6 +65,11 @@ func (s *SecurityContext) GetUsername() string {
return s.robot.Name
}

// User get the current user
func (s *SecurityContext) User() *robot.Robot {
return s.robot
}

// IsSysAdmin robot cannot be a system admin
func (s *SecurityContext) IsSysAdmin() bool {
return false
Expand All @@ -81,12 +82,27 @@ func (s *SecurityContext) IsSolutionUser() bool {

// Can returns whether the robot can do action on resource
func (s *SecurityContext) Can(ctx context.Context, action types.Action, resource types.Resource) bool {
if s.robot == nil {
return false
}

s.once.Do(func() {
if s.isSystemLevel {
var accesses []*types.Policy
for _, p := range s.robot.Permissions {
for _, a := range p.Access {
accesses = append(accesses, &types.Policy{
Action: a.Action,
Effect: a.Effect,
Resource: types.Resource(fmt.Sprintf("%s/%s", p.Scope, a.Resource)),
})
}
}

if s.robot.Level == robot.LEVELSYSTEM {
var proPolicies []*types.Policy
var sysPolicies []*types.Policy
var evaluators evaluator.Evaluators
for _, p := range s.policies {
for _, p := range accesses {
if strings.HasPrefix(p.Resource.String(), robot.SCOPESYSTEM) {
sysPolicies = append(sysPolicies, p)
} else if strings.HasPrefix(p.Resource.String(), robot.SCOPEPROJECT) {
Expand All @@ -101,7 +117,7 @@ func (s *SecurityContext) Can(ctx context.Context, action types.Action, resource
s.evaluator = evaluators

} else {
s.evaluator = rbac_project.NewEvaluator(s.ctl, rbac_project.NewBuilderForPolicies(s.GetUsername(), s.policies, filterRobotPolicies))
s.evaluator = rbac_project.NewEvaluator(s.ctl, rbac_project.NewBuilderForPolicies(s.GetUsername(), accesses, filterRobotPolicies))
}
})

Expand Down
145 changes: 97 additions & 48 deletions src/common/security/robot/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"context"
"fmt"
"github.com/goharbor/harbor/src/common/rbac/project"
"github.com/goharbor/harbor/src/controller/robot"
"reflect"
"testing"

Expand All @@ -32,117 +33,165 @@ import (

var (
private = &proModels.Project{
Name: "testrobot",
OwnerID: 1,
ProjectID: 1,
Name: "testrobot",
OwnerID: 1,
}
)

func TestIsAuthenticated(t *testing.T) {
// unauthenticated
ctx := NewSecurityContext(nil, false, nil)
ctx := NewSecurityContext(nil)
assert.False(t, ctx.IsAuthenticated())

// authenticated
ctx = NewSecurityContext(&model.Robot{
Name: "test",
Disabled: false,
}, false, nil)
ctx = NewSecurityContext(&robot.Robot{
Robot: model.Robot{
Name: "test",
Disabled: false,
},
})
assert.True(t, ctx.IsAuthenticated())
}

func TestGetUsername(t *testing.T) {
// unauthenticated
ctx := NewSecurityContext(nil, false, nil)
ctx := NewSecurityContext(nil)
assert.Equal(t, "", ctx.GetUsername())

// authenticated
ctx = NewSecurityContext(&model.Robot{
Name: "test",
Disabled: false,
}, false, nil)
ctx = NewSecurityContext(&robot.Robot{
Robot: model.Robot{
Name: "test",
Disabled: false,
},
})
assert.Equal(t, "test", ctx.GetUsername())
}

func TestGetUser(t *testing.T) {
// unauthenticated
ctx := NewSecurityContext(nil)
assert.Equal(t, "", ctx.GetUsername())

// authenticated
ctx = NewSecurityContext(&robot.Robot{
Robot: model.Robot{
ID: 123,
Name: "test",
Disabled: false,
},
})
assert.Equal(t, "test", ctx.User().Name)
assert.Equal(t, int64(123), ctx.User().ID)
}

func TestIsSysAdmin(t *testing.T) {
// unauthenticated
ctx := NewSecurityContext(nil, false, nil)
ctx := NewSecurityContext(nil)
assert.False(t, ctx.IsSysAdmin())

// authenticated, non admin
ctx = NewSecurityContext(&model.Robot{
Name: "test",
Disabled: false,
}, false, nil)
ctx = NewSecurityContext(&robot.Robot{
Robot: model.Robot{
Name: "test",
Disabled: false,
},
})
assert.False(t, ctx.IsSysAdmin())
}

func TestIsSolutionUser(t *testing.T) {
ctx := NewSecurityContext(nil, false, nil)
ctx := NewSecurityContext(nil)
assert.False(t, ctx.IsSolutionUser())
}

func TestHasPullPerm(t *testing.T) {
policies := []*types.Policy{
{
Resource: rbac.Resource(fmt.Sprintf("/project/%d/repository", private.ProjectID)),
Action: rbac.ActionPull,
robot := &robot.Robot{
Robot: model.Robot{
Name: "test_robot_1",
Description: "desc",
},
Permissions: []*robot.Permission{
{
Kind: "project",
Namespace: "library",
Access: []*types.Policy{
{
Resource: rbac.Resource(fmt.Sprintf("project/%d/repository", private.ProjectID)),
Action: rbac.ActionPull,
},
},
},
},
}
robot := &model.Robot{
Name: "test_robot_1",
Description: "desc",
}

ctl := &projecttesting.Controller{}
mock.OnAnything(ctl, "Get").Return(private, nil)

ctx := NewSecurityContext(robot, false, policies)
ctx := NewSecurityContext(robot)
ctx.ctl = ctl
resource := project.NewNamespace(private.ProjectID).Resource(rbac.ResourceRepository)
assert.True(t, ctx.Can(context.TODO(), rbac.ActionPull, resource))
}

func TestHasPushPerm(t *testing.T) {
policies := []*types.Policy{
{
Resource: rbac.Resource(fmt.Sprintf("/project/%d/repository", private.ProjectID)),
Action: rbac.ActionPush,
robot := &robot.Robot{
Robot: model.Robot{
Name: "test",
Disabled: false,
},
Permissions: []*robot.Permission{
{
Kind: "project",
Namespace: "library",
Access: []*types.Policy{
{
Resource: rbac.Resource(fmt.Sprintf("project/%d/repository", private.ProjectID)),
Action: rbac.ActionPush,
},
},
},
},
}
robot := &model.Robot{
Name: "test_robot_2",
Description: "desc",
}

ctl := &projecttesting.Controller{}
mock.OnAnything(ctl, "Get").Return(private, nil)

ctx := NewSecurityContext(robot, false, policies)
ctx := NewSecurityContext(robot)
ctx.ctl = ctl
resource := project.NewNamespace(private.ProjectID).Resource(rbac.ResourceRepository)
assert.True(t, ctx.Can(context.TODO(), rbac.ActionPush, resource))
}

func TestHasPushPullPerm(t *testing.T) {
policies := []*types.Policy{
{
Resource: rbac.Resource(fmt.Sprintf("/project/%d/repository", private.ProjectID)),
Action: rbac.ActionPush,
robot := &robot.Robot{
Robot: model.Robot{
Name: "test_robot_3",
Description: "desc",
},
{
Resource: rbac.Resource(fmt.Sprintf("/project/%d/repository", private.ProjectID)),
Action: rbac.ActionPull,
Permissions: []*robot.Permission{
{
Kind: "project",
Namespace: "library",
Access: []*types.Policy{
{
Resource: rbac.Resource(fmt.Sprintf("project/%d/repository", private.ProjectID)),
Action: rbac.ActionPush,
},
{
Resource: rbac.Resource(fmt.Sprintf("project/%d/repository", private.ProjectID)),
Action: rbac.ActionPull,
},
},
},
},
}
robot := &model.Robot{
Name: "test_robot_3",
Description: "desc",
}

ctl := &projecttesting.Controller{}
mock.OnAnything(ctl, "Get").Return(private, nil)

ctx := NewSecurityContext(robot, false, policies)
ctx := NewSecurityContext(robot)
ctx.ctl = ctl
resource := project.NewNamespace(private.ProjectID).Resource(rbac.ResourceRepository)
assert.True(t, ctx.Can(context.TODO(), rbac.ActionPush, resource) && ctx.Can(context.TODO(), rbac.ActionPull, resource))
Expand Down
30 changes: 30 additions & 0 deletions src/pkg/project/models/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ type Project struct {
RegistryID int64 `orm:"column(registry_id)" json:"registry_id"`
}

// NamesQuery ...
type NamesQuery struct {
Names []string // the names of project
WithPublic bool // include the public projects
}

// GetMetadata ...
func (p *Project) GetMetadata(key string) (string, bool) {
if len(p.Metadata) == 0 {
Expand Down Expand Up @@ -182,6 +188,30 @@ func (p *Project) FilterByMember(ctx context.Context, qs orm.QuerySeter, key str
return qs.FilterRaw("project_id", fmt.Sprintf("IN (%s)", subQuery))
}

// FilterByNames returns orm.QuerySeter with name filter
func (p *Project) FilterByNames(ctx context.Context, qs orm.QuerySeter, key string, value interface{}) orm.QuerySeter {
query, ok := value.(*NamesQuery)
if !ok {
return qs
}

if len(query.Names) == 0 {
return qs
}

var names []string
for _, v := range query.Names {
names = append(names, `'`+v+`'`)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggest using the lib/pg.QuoteLiteral here

}
subQuery := fmt.Sprintf("SELECT project_id FROM project where name IN (%s)", strings.Join(names, ","))

if query.WithPublic {
subQuery = fmt.Sprintf("(%s) UNION (SELECT project_id FROM project_metadata WHERE name = 'public' AND value = 'true')", subQuery)
}

return qs.FilterRaw("project_id", fmt.Sprintf("IN (%s)", subQuery))
}

func isTrue(i interface{}) bool {
switch value := i.(type) {
case bool:
Expand Down
Loading