Add read:self and delete:self to auth tokens and add logout command (#1162)

This commit is contained in:
Jeff Mitchell authored and GitHub committed 2021-04-23 13:45:08 -04:00
1 parent 3fe94335d4
commit e6af51943d
20 files changed
+966 -223

No files matched your search

@@ -24,7 +24,9 @@ var (
IdActions = action.ActionSet{
action.NoOp,
action.Read,
action.ReadSelf,
action.Delete,
action.DeleteSelf,
}
// CollectionActions contains the set of actions that can be performed on
@@ -99,10 +101,17 @@ func (s Service) ListAuthTokens(ctx context.Context, req *pbs.ListAuthTokensRequ
for _, item := range ul {
item.Scope = scopeInfoMap[item.GetScopeId()]
res.ScopeId = item.Scope.Id
item.AuthorizedActions = authResults.FetchActionSetForId(ctx, item.Id, IdActions, auth.WithResource(res)).Strings()
if len(item.AuthorizedActions) == 0 {
authorizedActions := authResults.FetchActionSetForId(ctx, item.Id, IdActions, auth.WithResource(res))
if len(authorizedActions) == 0 {
continue
}
if authorizedActions.OnlySelf() && item.GetUserId() != authResults.UserId {
continue
}
item.AuthorizedActions = authorizedActions.Strings()
if filter.Match(item) {
finalItems = append(finalItems, item)
}
@@ -115,7 +124,7 @@ func (s Service) GetAuthToken(ctx context.Context, req *pbs.GetAuthTokenRequest)
if err := validateGetRequest(req); err != nil {
return nil, err
}
authResults := s.authResult(ctx, req.GetId(), action.Read)
authResults := s.authResult(ctx, req.GetId(), action.ReadSelf)
if authResults.Error != nil {
return nil, authResults.Error
}
@@ -123,6 +132,15 @@ func (s Service) GetAuthToken(ctx context.Context, req *pbs.GetAuthTokenRequest)
if err != nil {
return nil, err
}
authzdActions := authResults.FetchActionSetForId(ctx, u.Id, IdActions)
// Check to see if we need to verify Read vs. just ReadSelf
if u.GetUserId() != authResults.UserId {
if !authzdActions.HasAction(action.Read) {
return nil, handlers.ForbiddenError()
}
}
u.Scope = authResults.Scope
u.AuthorizedActions = authResults.FetchActionSetForId(ctx, u.Id, IdActions).Strings()
return &pbs.GetAuthTokenResponse{Item: u}, nil
@@ -133,11 +151,24 @@ func (s Service) DeleteAuthToken(ctx context.Context, req *pbs.DeleteAuthTokenRe
if err := validateDeleteRequest(req); err != nil {
return nil, err
}
authResults := s.authResult(ctx, req.GetId(), action.Delete)
authResults := s.authResult(ctx, req.GetId(), action.DeleteSelf)
if authResults.Error != nil {
return nil, authResults.Error
}
_, err := s.deleteFromRepo(ctx, req.GetId())
at, err := s.getFromRepo(ctx, req.GetId())
if err != nil {
return nil, err
}
authzdActions := authResults.FetchActionSetForId(ctx, at.Id, IdActions)
// Check to see if we need to verify Delete vs. just DeleteSelf
if at.GetUserId() != authResults.UserId {
if !authzdActions.HasAction(action.Delete) {
return nil, handlers.ForbiddenError()
}
}
_, err = s.deleteFromRepo(ctx, req.GetId())
if err != nil {
return nil, err
}
@@ -1,8 +1,10 @@
package authtokens_test
import (
"context"
"errors"
"fmt"
"net/http/httptest"
"testing"
"github.com/google/go-cmp/cmp"
@@ -14,9 +16,11 @@ import (
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
"github.com/hashicorp/boundary/internal/iam"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/servers"
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
"github.com/hashicorp/boundary/internal/servers/controller/handlers/authtokens"
"github.com/hashicorp/boundary/internal/types/scope"
"github.com/hashicorp/go-hclog"
"google.golang.org/grpc/codes"
"google.golang.org/protobuf/testing/protocmp"
@@ -24,7 +28,89 @@ import (
"github.com/stretchr/testify/require"
)
var testAuthorizedActions = []string{"no-op", "read", "delete"}
var testAuthorizedActions = []string{"no-op", "read", "read:self", "delete", "delete:self"}
func TestGetSelf(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrap := db.TestWrapper(t)
logger := hclog.New(nil)
kms := kms.TestKms(t, conn, wrap)
iamRepoFn := func() (*iam.Repository, error) {
return iam.TestRepo(t, conn, wrap), nil
}
tokenRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
}
serversRepoFn := func() (*servers.Repository, error) {
return servers.NewRepository(rw, rw, kms)
}
a, err := authtokens.NewService(tokenRepoFn, iamRepoFn)
require.NoError(t, err, "Couldn't create new auth token service.")
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
at1 := authtoken.TestAuthToken(t, conn, kms, o.GetPublicId())
at2 := authtoken.TestAuthToken(t, conn, kms, o.GetPublicId())
cases := []struct {
name string
token *authtoken.AuthToken
readId string
err error
}{
{
name: "at1 read self",
token: at1,
readId: at1.GetPublicId(),
},
{
name: "at1 read at2",
token: at1,
readId: at2.GetPublicId(),
err: handlers.ApiErrorWithCodeAndMessage(codes.PermissionDenied, "Forbidden."),
},
{
name: "at2 read self",
token: at2,
readId: at2.GetPublicId(),
},
{
name: "at2 read at1",
token: at2,
readId: at1.GetPublicId(),
err: handlers.ApiErrorWithCodeAndMessage(codes.PermissionDenied, "Forbidden."),
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require, assert := require.New(t), assert.New(t)
// Setup the auth request information
req := httptest.NewRequest("GET", fmt.Sprintf("http://127.0.0.1/v1/auth-tokens/%s", tc.readId), nil)
requestInfo := auth.RequestInfo{
Path: req.URL.Path,
Method: req.Method,
TokenFormat: auth.AuthTokenTypeBearer,
PublicId: tc.token.GetPublicId(),
Token: tc.token.GetToken(),
}
ctx := auth.NewVerifierContext(context.Background(), logger, iamRepoFn, tokenRepoFn, serversRepoFn, kms, requestInfo)
got, err := a.GetAuthToken(ctx, &pbs.GetAuthTokenRequest{Id: tc.readId})
if tc.err != nil {
require.EqualError(err, tc.err.Error())
require.Nil(got)
return
}
require.NoError(err)
require.NotNil(got)
assert.Equal(got.GetItem().GetId(), tc.token.GetPublicId())
// Ensure we didn't simply have e.g. read on all tokens
assert.Equal(got.Item.GetAuthorizedActions(), []string{"read:self", "delete:self"})
})
}
}
func TestGet(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
@@ -101,6 +187,75 @@ func TestGet(t *testing.T) {
}
}
func TestList_Self(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrap := db.TestWrapper(t)
logger := hclog.New(nil)
kms := kms.TestKms(t, conn, wrap)
iamRepo := iam.TestRepo(t, conn, wrap)
iamRepoFn := func() (*iam.Repository, error) {
return iamRepo, nil
}
tokenRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
}
serversRepoFn := func() (*servers.Repository, error) {
return servers.NewRepository(rw, rw, kms)
}
// This will result in the scope having default permissions, which now
// includes list on auth tokens
o, _ := iam.TestScopes(t, iamRepo)
// Each of these should only end up being able to list themselves
at := authtoken.TestAuthToken(t, conn, kms, o.GetPublicId())
otherAt := authtoken.TestAuthToken(t, conn, kms, o.GetPublicId())
cases := []struct {
name string
requester *authtoken.AuthToken
count int
}{
{
name: "First token sees only self",
requester: at,
},
{
name: "Second token sees only self",
requester: otherAt,
},
}
a, err := authtokens.NewService(tokenRepoFn, iamRepoFn)
require.NoError(t, err)
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require, assert := require.New(t), assert.New(t)
// Setup the auth request information
req := httptest.NewRequest("GET", fmt.Sprintf("http://127.0.0.1/v1/auth-tokens?scope_id=%s", o.GetPublicId()), nil)
requestInfo := auth.RequestInfo{
Path: req.URL.Path,
Method: req.Method,
TokenFormat: auth.AuthTokenTypeBearer,
PublicId: tc.requester.GetPublicId(),
Token: tc.requester.GetToken(),
}
ctx := auth.NewVerifierContext(context.Background(), logger, iamRepoFn, tokenRepoFn, serversRepoFn, kms, requestInfo)
got, err := a.ListAuthTokens(ctx, &pbs.ListAuthTokensRequest{ScopeId: o.GetPublicId()})
require.NoError(err)
require.Len(got.Items, 1)
assert.Equal(got.Items[0].GetId(), tc.requester.GetPublicId())
// Ensure we didn't simply have e.g. read on all tokens
assert.Equal(got.Items[0].GetAuthorizedActions(), []string{"read:self", "delete:self"})
})
}
}
func TestList(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
@@ -243,6 +398,98 @@ func TestList(t *testing.T) {
}
}
func TestDeleteSelf(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrap := db.TestWrapper(t)
logger := hclog.New(nil)
kms := kms.TestKms(t, conn, wrap)
iamRepo := iam.TestRepo(t, conn, wrap)
iamRepoFn := func() (*iam.Repository, error) {
return iamRepo, nil
}
tokenRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
}
serversRepoFn := func() (*servers.Repository, error) {
return servers.NewRepository(rw, rw, kms)
}
a, err := authtokens.NewService(tokenRepoFn, iamRepoFn)
require.NoError(t, err, "Couldn't create new auth token service.")
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrap))
at1 := authtoken.TestAuthToken(t, conn, kms, o.GetPublicId())
at2 := authtoken.TestAuthToken(t, conn, kms, o.GetPublicId())
cases := []struct {
name string
token *authtoken.AuthToken
deleteId string
err error
}{
{
name: "at1 delete at2",
token: at1,
deleteId: at2.GetPublicId(),
err: handlers.ApiErrorWithCodeAndMessage(codes.PermissionDenied, "Forbidden."),
},
{
name: "at2 delete at1",
token: at2,
deleteId: at1.GetPublicId(),
err: handlers.ApiErrorWithCodeAndMessage(codes.PermissionDenied, "Forbidden."),
},
{
name: "at1 delete self",
token: at1,
deleteId: at1.GetPublicId(),
},
{
name: "at2 delete self",
token: at2,
deleteId: at2.GetPublicId(),
},
{
name: "at1 not found",
token: at1,
deleteId: at1.GetPublicId(),
err: handlers.ApiErrorWithCodeAndMessage(codes.NotFound, "Resource not found."),
},
{
name: "at2 not found",
token: at2,
deleteId: at2.GetPublicId(),
err: handlers.ApiErrorWithCodeAndMessage(codes.NotFound, "Resource not found."),
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
// Setup the auth request information
req := httptest.NewRequest("DELETE", fmt.Sprintf("http://127.0.0.1/v1/auth-tokens/%s", tc.deleteId), nil)
requestInfo := auth.RequestInfo{
Path: req.URL.Path,
Method: req.Method,
TokenFormat: auth.AuthTokenTypeBearer,
PublicId: tc.token.GetPublicId(),
Token: tc.token.GetToken(),
}
ctx := auth.NewVerifierContext(context.Background(), logger, iamRepoFn, tokenRepoFn, serversRepoFn, kms, requestInfo)
got, err := a.DeleteAuthToken(ctx, &pbs.DeleteAuthTokenRequest{Id: tc.deleteId})
if tc.err != nil {
require.EqualError(err, tc.err.Error())
require.Nil(got)
return
}
require.NoError(err)
})
}
}
func TestDelete(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
@@ -77,14 +77,7 @@ func (s Service) GetSession(ctx context.Context, req *pbs.GetSessionRequest) (*p
authzdActions := authResults.FetchActionSetForId(ctx, ses.Id, IdActions)
// Check to see if we need to verify Read vs. just ReadSelf
if ses.GetUserId() != authResults.UserId {
var found bool
for _, v := range authzdActions {
if v == action.Read {
found = true
break
}
}
if !found {
if !authzdActions.HasAction(action.Read) {
return nil, handlers.ForbiddenError()
}
}
@@ -143,14 +136,8 @@ func (s Service) ListSessions(ctx context.Context, req *pbs.ListSessionsRequest)
if len(authorizedActions) == 0 {
continue
}
onlySelf := true
for _, v := range authorizedActions {
if v != action.ReadSelf && v != action.CancelSelf {
onlySelf = false
break
}
}
if onlySelf && item.GetUserId() != authResults.UserId {
if authorizedActions.OnlySelf() && item.GetUserId() != authResults.UserId {
continue
}
@@ -179,16 +166,9 @@ func (s Service) CancelSession(ctx context.Context, req *pbs.CancelSessionReques
return nil, err
}
authzdActions := authResults.FetchActionSetForId(ctx, ses.Id, IdActions)
// Check to see if we need to verify Read vs. just ReadSelf
// Check to see if we need to verify Cancel vs. just CancelSelf
if ses.GetUserId() != authResults.UserId {
var found bool
for _, v := range authzdActions {
if v == action.Cancel {
found = true
break
}
}
if !found {
if !authzdActions.HasAction(action.Cancel) {
return nil, handlers.ForbiddenError()
}
}