Authenticate Handler API and SDK, and much more (#183)

This commit is contained in:
Todd Knight authored and GitHub committed 2020-07-14 17:32:47 -04:00
1 parent acce195dcb
commit 28dbcd84bd
89 files changed
+5296 -1943

No files matched your search

+29 -15
View File
@@ -7,16 +7,17 @@ import (
"github.com/hashicorp/watchtower/api"
)
func (s Role) AddPrincipals(ctx context.Context, groups, users []string) (*Role, *api.Error, error) {
func (s Role) AddPrincipals(ctx context.Context, principalIds []string) (*Role, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in AddPrincipals request")
}
// We assume that the client provided has the org and optionally the project id of the request.
body := map[string]interface{}{
"group_ids": groups,
"user_ids": users,
"version": s.Version,
"version": s.Version,
}
if len(principalIds) > 0 {
body["principal_ids"] = principalIds
}
req, err := s.Client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:add-principals", s.Id), body)
@@ -40,16 +41,20 @@ func (s Role) AddPrincipals(ctx context.Context, groups, users []string) (*Role,
return target, apiErr, nil
}
func (s Role) SetPrincipals(ctx context.Context, groups, users []string) (*Role, *api.Error, error) {
func (s Role) SetPrincipals(ctx context.Context, principalIds []string) (*Role, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in SetPrincipals request")
}
// We assume that the client provided has the org and optionally the project id of the request.
body := map[string]interface{}{
"group_ids": groups,
"user_ids": users,
"version": s.Version,
"version": s.Version,
}
if len(principalIds) > 0 {
body["principal_ids"] = principalIds
} else if principalIds != nil {
// In this function, a non-nil but empty list means clear out
body["principal_ids"] = nil
}
req, err := s.Client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:set-principals", s.Id), body)
@@ -73,16 +78,17 @@ func (s Role) SetPrincipals(ctx context.Context, groups, users []string) (*Role,
return target, apiErr, nil
}
func (s Role) RemovePrincipals(ctx context.Context, groups, users []string) (*Role, *api.Error, error) {
func (s Role) RemovePrincipals(ctx context.Context, principalIds []string) (*Role, *api.Error, error) {
if s.Client == nil {
return nil, nil, fmt.Errorf("nil client in RemovePrincipals request")
}
// We assume that the client provided has the org and optionally the project id of the request.
body := map[string]interface{}{
"group_ids": groups,
"user_ids": users,
"version": s.Version,
"version": s.Version,
}
if len(principalIds) > 0 {
body["principal_ids"] = principalIds
}
req, err := s.Client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:remove-principals", s.Id), body)
@@ -113,9 +119,11 @@ func (s Role) AddGrants(ctx context.Context, grants []string) (*Role, *api.Error
// We assume that the client provided has the org and optionally the project id of the request.
body := map[string]interface{}{
"grants": grants,
"version": s.Version,
}
if len(grants) > 0 {
body["grants"] = grants
}
req, err := s.Client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:add-grants", s.Id), body)
if err != nil {
@@ -145,9 +153,13 @@ func (s Role) SetGrants(ctx context.Context, grants []string) (*Role, *api.Error
// We assume that the client provided has the org and optionally the project id of the request.
body := map[string]interface{}{
"grants": grants,
"version": s.Version,
}
if len(grants) > 0 {
body["grants"] = grants
} else if grants != nil {
body["grants"] = nil
}
req, err := s.Client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:set-grants", s.Id), body)
if err != nil {
@@ -177,9 +189,11 @@ func (s Role) RemoveGrants(ctx context.Context, grants []string) (*Role, *api.Er
// We assume that the client provided has the org and optionally the project id of the request.
body := map[string]interface{}{
"grants": grants,
"version": s.Version,
}
if len(grants) > 0 {
body["grants"] = grants
}
req, err := s.Client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:remove-grants", s.Id), body)
if err != nil {
+61
View File
@@ -0,0 +1,61 @@
// Code generated by "make api"; DO NOT EDIT.
package roles
import (
"encoding/json"
"strings"
"github.com/fatih/structs"
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/internal/strutil"
)
type Principal struct {
Client *api.Client `json:"-"`
defaultFields []string
// The ID of the principal.
// Output only.
Id string `json:"id,omitempty"`
// The type of the principal.
// Output only.
Type string `json:"type,omitempty"`
// The scope ID of the principal.
// Output only.
ScopeId string `json:"scope_id,omitempty"`
}
func (s *Principal) SetDefault(key string) {
lowerKey := strings.ToLower(key)
validMap := map[string]string{"id": "id", "scopeid": "scope_id", "type": "type"}
for k, v := range validMap {
if k == lowerKey || v == lowerKey {
s.defaultFields = strutil.AppendIfMissing(s.defaultFields, v)
return
}
}
}
func (s *Principal) UnsetDefault(key string) {
lowerKey := strings.ToLower(key)
validMap := map[string]string{"id": "id", "scopeid": "scope_id", "type": "type"}
for k, v := range validMap {
if k == lowerKey || v == lowerKey {
s.defaultFields = strutil.StrListDelete(s.defaultFields, v)
return
}
}
}
func (s Principal) MarshalJSON() ([]byte, error) {
m := structs.Map(s)
if m == nil {
m = make(map[string]interface{})
}
for _, k := range s.defaultFields {
m[k] = nil
}
return json.Marshal(m)
}
+23 -7
View File
@@ -3,6 +3,7 @@ package roles
import (
"encoding/json"
"strings"
"time"
"github.com/fatih/structs"
@@ -40,13 +41,14 @@ type Role struct {
// The version can be used in subsiquent write requests to ensure this resource
// has not changed and to fail the write if it has.
// Output only.
Version *uint32 `json:"version,omitempty"`
// The principals that are assigned this role.
Version uint32 `json:"version,omitempty"`
// The IDs (only) of principals that are assigned to this role.
// Output only.
UserIds []string `json:"user_ids,omitempty"`
PrincipalIds []string `json:"principal_ids,omitempty"`
// The principals that are assigned to this role.
// Output only.
GroupIds []string `json:"group_ids,omitempty"`
// The grants that this role provides for it's principals.
Principals []*Principal `json:"principals,omitempty"`
// The grants that this role provides for its principals.
// Output only.
Grants []string `json:"grants,omitempty"`
// The canonical version of the grants in the grants field with the same index.
@@ -58,11 +60,25 @@ type Role struct {
}
func (s *Role) SetDefault(key string) {
s.defaultFields = strutil.AppendIfMissing(s.defaultFields, key)
lowerKey := strings.ToLower(key)
validMap := map[string]string{"createdtime": "created_time", "description": "description", "disabled": "disabled", "grants": "grants", "grantscanonical": "grants_canonical", "grantscopeid": "grant_scope_id", "grantsjson": "grants_json", "id": "id", "name": "name", "principalids": "principal_ids", "principals": "principals", "updatedtime": "updated_time", "version": "version"}
for k, v := range validMap {
if k == lowerKey || v == lowerKey {
s.defaultFields = strutil.AppendIfMissing(s.defaultFields, v)
return
}
}
}
func (s *Role) UnsetDefault(key string) {
s.defaultFields = strutil.StrListDelete(s.defaultFields, key)
lowerKey := strings.ToLower(key)
validMap := map[string]string{"createdtime": "created_time", "description": "description", "disabled": "disabled", "grants": "grants", "grantscanonical": "grants_canonical", "grantscopeid": "grant_scope_id", "grantsjson": "grants_json", "id": "id", "name": "name", "principalids": "principal_ids", "principals": "principals", "updatedtime": "updated_time", "version": "version"}
for k, v := range validMap {
if k == lowerKey || v == lowerKey {
s.defaultFields = strutil.StrListDelete(s.defaultFields, v)
return
}
}
}
func (s Role) MarshalJSON() ([]byte, error) {
+86 -56
View File
@@ -6,6 +6,7 @@ import (
"net/http"
"testing"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/groups"
"github.com/hashicorp/watchtower/api/roles"
@@ -27,7 +28,7 @@ type roleCrud interface {
}
func TestCustom(t *testing.T) {
tc := controller.NewTestController(t, nil)
tc := controller.NewTestController(t, &controller.TestControllerOpts{DisableAuthorizationFailures: true})
defer tc.Shutdown()
client := tc.Client()
@@ -56,6 +57,22 @@ func TestCustom(t *testing.T) {
},
}
hasPrincipal := func(role *roles.Role, principalId string) bool {
var foundInPrincipals bool
var foundInPrincipalIds bool
for _, v := range role.Principals {
if v.Id == principalId {
foundInPrincipals = true
}
}
for _, v := range role.PrincipalIds {
if v == principalId {
foundInPrincipalIds = true
}
}
return foundInPrincipals && foundInPrincipalIds
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
@@ -70,63 +87,52 @@ func TestCustom(t *testing.T) {
require.Nil(apiErr)
require.NotNil(r)
updatedRole, apiErr, err := r.AddPrincipals(ctx, []string{g.Id}, nil)
updatedRole, apiErr, err := r.AddPrincipals(ctx, []string{g.Id})
require.NoError(err)
require.Nil(apiErr, "Got error ", errorMessage(apiErr))
assert.Equal(t, *updatedRole.Version, (*r.Version)+1)
assert.Contains(t, updatedRole.GroupIds, g.Id)
assert.Empty(t, updatedRole.UserIds)
require.Nil(apiErr, "Got error ", apiErr)
assert.Equal(t, updatedRole.Version, r.Version+1)
assert.True(t, hasPrincipal(updatedRole, g.Id))
r = updatedRole
updatedRole, apiErr, err = r.SetPrincipals(ctx, nil, []string{user.Id})
updatedRole, apiErr, err = r.SetPrincipals(ctx, []string{user.Id})
require.NoError(err)
require.Nil(apiErr, "Got error ", errorMessage(apiErr))
assert.Equal(t, *updatedRole.Version, (*r.Version)+1)
assert.Empty(t, updatedRole.GroupIds)
assert.Contains(t, updatedRole.UserIds, user.Id)
require.Nil(apiErr, "Got error ", apiErr)
assert.Equal(t, updatedRole.Version, r.Version+1)
assert.True(t, hasPrincipal(updatedRole, user.Id))
r = updatedRole
updatedRole, apiErr, err = r.RemovePrincipals(ctx, nil, []string{user.Id})
updatedRole, apiErr, err = r.RemovePrincipals(ctx, []string{user.Id})
require.NoError(err)
require.Nil(apiErr, "Got error ", errorMessage(apiErr))
assert.Equal(t, *updatedRole.Version, (*r.Version)+1)
assert.Empty(t, updatedRole.GroupIds)
assert.Empty(t, updatedRole.UserIds)
require.Nil(apiErr, "Got error ", apiErr)
assert.Equal(t, updatedRole.Version, r.Version+1)
assert.Empty(t, updatedRole.Principals)
r = updatedRole
updatedRole, apiErr, err = r.AddGrants(ctx, []string{"id=*;actions=read"})
require.NoError(err)
require.Nil(apiErr, "Got error ", errorMessage(apiErr))
assert.Equal(t, *updatedRole.Version, (*r.Version)+1)
require.Nil(apiErr, "Got error ", apiErr)
assert.Equal(t, updatedRole.Version, r.Version+1)
assert.Contains(t, updatedRole.Grants, "id=*;actions=read")
r = updatedRole
updatedRole, apiErr, err = r.SetGrants(ctx, []string{"id=*;actions=*"})
require.NoError(err)
require.Nil(apiErr, "Got error ", errorMessage(apiErr))
assert.Equal(t, *updatedRole.Version, (*r.Version)+1)
require.Nil(apiErr, "Got error ", apiErr)
assert.Equal(t, updatedRole.Version, r.Version+1)
assert.Contains(t, updatedRole.Grants, "id=*;actions=*")
r = updatedRole
updatedRole, apiErr, err = r.RemoveGrants(ctx, []string{"id=*;actions=*"})
require.NoError(err)
require.Nil(apiErr, "Got error ", errorMessage(apiErr))
assert.Equal(t, *updatedRole.Version, (*r.Version)+1)
require.Nil(apiErr, "Got error ", apiErr)
assert.Equal(t, updatedRole.Version, r.Version+1)
assert.Empty(t, updatedRole.Grants)
})
}
}
func errorMessage(in *api.Error) string {
if in == nil {
return ""
}
return *in.Message
}
func TestRole_List(t *testing.T) {
assert := assert.New(t)
tc := controller.NewTestController(t, nil)
tc := controller.NewTestController(t, &controller.TestControllerOpts{DisableAuthorizationFailures: true})
defer tc.Shutdown()
client := tc.Client()
@@ -153,12 +159,19 @@ func TestRole_List(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
ctx := context.Background()
pl, apiErr, err := tc.scope.ListRoles(ctx)
assert.NoError(err)
p1, apiErr, err := tc.scope.ListRoles(ctx)
require.NoError(err)
assert.Nil(apiErr)
assert.Empty(pl)
var defaultRoleIds []string
if tc.name == "org" {
require.True(2 == len(p1))
defaultRoleIds = []string{p1[0].Id, p1[1].Id}
} else {
require.Empty(p1)
}
var expected []*roles.Role
for i := 0; i < 10; i++ {
@@ -166,21 +179,35 @@ func TestRole_List(t *testing.T) {
}
expected[0], apiErr, err = tc.scope.CreateRole(ctx, expected[0])
assert.NoError(err)
require.NoError(err)
assert.Nil(apiErr)
pl, apiErr, err = tc.scope.ListRoles(ctx)
p2, apiErr, err := tc.scope.ListRoles(ctx)
assert.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected[:1]), comparableSlice(pl))
var p2ForComparison []*roles.Role
for _, v := range p2 {
if !strutil.StrListContains(defaultRoleIds, v.Id) {
p2ForComparison = append(p2ForComparison, v)
}
}
assert.ElementsMatch(comparableSlice(expected[:1]), comparableSlice(p2ForComparison))
for i := 1; i < 10; i++ {
expected[i], apiErr, err = tc.scope.CreateRole(ctx, expected[i])
assert.NoError(err)
assert.Nil(apiErr)
}
pl, apiErr, err = tc.scope.ListRoles(ctx)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(pl))
p3, apiErr, err := tc.scope.ListRoles(ctx)
require.NoError(err)
assert.Nil(apiErr)
var p3ForComparison []*roles.Role
for _, v := range p3 {
if !strutil.StrListContains(defaultRoleIds, v.Id) {
p3ForComparison = append(p3ForComparison, v)
}
}
assert.ElementsMatch(comparableSlice(expected), comparableSlice(p3ForComparison))
})
}
}
@@ -202,7 +229,7 @@ func comparableSlice(in []*roles.Role) []roles.Role {
}
func TestRole_Crud(t *testing.T) {
tc := controller.NewTestController(t, nil)
tc := controller.NewTestController(t, &controller.TestControllerOpts{DisableAuthorizationFailures: true})
defer tc.Shutdown()
client := tc.Client()
@@ -217,8 +244,8 @@ func TestRole_Crud(t *testing.T) {
checkRole := func(step string, g *roles.Role, apiErr *api.Error, err error, wantedName string) {
assert := assert.New(t)
assert.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != nil {
t.Errorf("ApiError message: %q", *apiErr.Message)
if !assert.Nil(apiErr, step) && apiErr.Message != "" {
t.Errorf("ApiError message: %q", apiErr.Message)
}
assert.NotNil(g, "returned no resource", step)
gotName := ""
@@ -244,6 +271,7 @@ func TestRole_Crud(t *testing.T) {
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
g, apiErr, err := tt.scope.CreateRole(tc.Context(), &roles.Role{Name: api.String("foo")})
checkRole("create", g, apiErr, err, "foo")
@@ -261,19 +289,20 @@ func TestRole_Crud(t *testing.T) {
checkRole("update", g, apiErr, err, "")
existed, apiErr, err := tt.scope.DeleteRole(tc.Context(), g)
assert.NoError(t, err)
assert.True(t, existed, "Expected existing user when deleted, but it wasn't.")
require.NoError(err)
assert.Nil(apiErr)
assert.True(existed, "Expected existing user when deleted, but it wasn't.")
existed, apiErr, err = tt.scope.DeleteRole(tc.Context(), g)
assert.NoError(t, err)
assert.False(t, existed, "Expected user to not exist when deleted, but it did.")
require.NoError(err)
assert.Nil(apiErr)
assert.False(existed, "Expected user to not exist when deleted, but it did.")
})
}
}
func TestRole_Errors(t *testing.T) {
assert := assert.New(t)
tc := controller.NewTestController(t, nil)
tc := controller.NewTestController(t, &controller.TestControllerOpts{DisableAuthorizationFailures: true})
defer tc.Shutdown()
ctx := tc.Context()
@@ -302,30 +331,31 @@ func TestRole_Errors(t *testing.T) {
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
u, apiErr, err := tt.scope.CreateRole(ctx, &roles.Role{Name: api.String("first")})
assert.NoError(err)
require.NoError(err)
assert.Nil(apiErr)
assert.NotNil(u)
// Create another resource with the same name.
_, apiErr, err = tt.scope.CreateRole(ctx, &roles.Role{Name: api.String("first")})
assert.NoError(err)
require.NoError(err)
assert.NotNil(apiErr)
_, apiErr, err = tt.scope.ReadRole(ctx, &roles.Role{Id: iam.RolePrefix + "_doesntexis"})
assert.NoError(err)
require.NoError(err)
assert.NotNil(apiErr)
assert.EqualValues(*apiErr.Status, http.StatusNotFound)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = tt.scope.ReadRole(ctx, &roles.Role{Id: "invalid id"})
assert.NoError(err)
require.NoError(err)
assert.NotNil(apiErr)
assert.EqualValues(*apiErr.Status, http.StatusBadRequest)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
_, apiErr, err = tt.scope.UpdateRole(ctx, &roles.Role{Id: u.Id})
assert.NoError(err)
require.NoError(err)
assert.NotNil(apiErr)
assert.EqualValues(*apiErr.Status, http.StatusBadRequest)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
})
}
}