harbor/src/common/security/v2token/context_test.go
Daniel Jiang 08f9ffa000 Reenable token auth for cli
Docker CLI fails if it's not logged in upon seeing "basic" realm challenging while pinging the "/v2" endpoint. (#11266)
Some CLI will send HEAD to artifact endpoint before pushing (#11188)(#11271)

To fix such problems, this commit re-introduce the token auth flow to the CLIs.

For a HEAD request to "/v2/xxx" with no "Authoirzation" header, the v2_auth middleware populates the
"Www-Authenticate" header to redirect it to token endpoint with proper
requested scope.

It also adds security context to based on the content of the JWT which has the claims of the registry.
So a request from CLI carrying a token signed by the "/service/token" will have proper permissions.

Signed-off-by: Daniel Jiang <jiangd@vmware.com>
2020-04-04 00:05:58 +08:00

98 lines
2.2 KiB
Go

package v2token
import (
"testing"
"github.com/docker/distribution/registry/auth/token"
"github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/rbac"
"github.com/goharbor/harbor/src/pkg/permission/types"
"github.com/goharbor/harbor/src/testing/pkg/project"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
)
func TestAll(t *testing.T) {
mgr := &project.FakeManager{}
mgr.On("Get", int64(1)).Return(&models.Project{ProjectID: 1, Name: "library"}, nil)
mgr.On("Get", int64(2)).Return(&models.Project{ProjectID: 2, Name: "test"}, nil)
mgr.On("Get", int64(3)).Return(&models.Project{ProjectID: 3, Name: "development"}, nil)
access := []*token.ResourceActions{
{
Type: "repository",
Name: "library/ubuntu",
Actions: []string{
"pull",
"push",
"scanner-pull",
},
},
{
Type: "repository",
Name: "test/golang",
Actions: []string{
"pull",
"*",
},
},
{
Type: "cnab",
Name: "development/cnab",
Actions: []string{
"pull",
"push",
},
},
}
sc := New(context.Background(), "jack", access)
tsc := sc.(*tokenSecurityCtx)
tsc.pm = mgr
cases := []struct {
resource types.Resource
action types.Action
expect bool
}{
{
resource: rbac.NewProjectNamespace(1).Resource(rbac.ResourceRepository),
action: rbac.ActionPush,
expect: true,
},
{
resource: rbac.NewProjectNamespace(1).Resource(rbac.ResourceRepository),
action: rbac.ActionScannerPull,
expect: true,
},
{
resource: rbac.NewProjectNamespace(2).Resource(rbac.ResourceRepository),
action: rbac.ActionPush,
expect: true,
},
{
resource: rbac.NewProjectNamespace(2).Resource(rbac.ResourceRepository),
action: rbac.ActionScannerPull,
expect: false,
},
{
resource: rbac.NewProjectNamespace(3).Resource(rbac.ResourceRepository),
action: rbac.ActionPush,
expect: false,
},
{
resource: rbac.NewProjectNamespace(2).Resource(rbac.ResourceArtifact),
action: rbac.ActionPush,
expect: false,
},
{
resource: rbac.NewProjectNamespace(1).Resource(rbac.ResourceRepository),
action: rbac.ActionCreate,
expect: false,
},
}
for _, c := range cases {
assert.Equal(t, c.expect, sc.Can(c.action, c.resource))
}
}