iam roles (#116)

This commit is contained in:
Jim authored and GitHub committed 2020-06-15 12:42:08 -04:00
1 parent 1637403624
commit ffddf24f86
14 files changed
+1671 -2

No files matched your search

+1
View File
@@ -54,6 +54,7 @@ protobuild:
@protoc --proto_path=internal/proto/local --proto_path=internal/proto/third_party --swagger_out=logtostderr=true,disable_default_errors=true,include_package_in_tags=true,fqn_for_swagger_name=true,allow_merge,merge_file_name=controller:internal/gen/. internal/proto/local/controller/api/services/v1/*.proto
@protoc-go-inject-tag -input=./internal/oplog/store/oplog.pb.go
@protoc-go-inject-tag -input=./internal/oplog/oplog_test/oplog_test.pb.go
@protoc-go-inject-tag -input=./internal/iam/store/role.pb.go
@protoc-go-inject-tag -input=./internal/iam/store/user.pb.go
@protoc-go-inject-tag -input=./internal/iam/store/scope.pb.go
@protoc-go-inject-tag -input=./internal/iam/store/group.pb.go
+30
View File
@@ -343,6 +343,8 @@ drop table iam_scope_project cascade;
drop table iam_scope_organization cascade;
drop table iam_scope cascade;
drop table iam_scope_type_enm cascade;
drop table iam_role cascade;
drop function iam_sub_names cascade;
drop function iam_immutable_scope_type_func cascade;
@@ -526,6 +528,33 @@ before
insert on iam_user
for each row execute procedure default_create_time();
create table iam_role (
public_id wt_public_id not null primary key,
create_time wt_timestamp,
update_time wt_timestamp,
name text,
description text,
scope_id wt_public_id not null references iam_scope(public_id) on delete cascade on update cascade,
unique(name, scope_id),
disabled boolean not null default false
);
create trigger
update_time_column
before update on iam_role
for each row execute procedure update_time_column();
create trigger
immutable_create_time
before
update on iam_role
for each row execute procedure immutable_create_time_func();
create trigger
default_create_time_column
before
insert on iam_role
for each row execute procedure default_create_time();
create table iam_group (
public_id wt_public_id not null primary key,
@@ -554,6 +583,7 @@ create trigger
before
insert on iam_group
for each row execute procedure default_create_time();
commit;
`),
@@ -6,6 +6,8 @@ drop table iam_scope_project cascade;
drop table iam_scope_organization cascade;
drop table iam_scope cascade;
drop table iam_scope_type_enm cascade;
drop table iam_role cascade;
drop function iam_sub_names cascade;
drop function iam_immutable_scope_type_func cascade;
@@ -169,6 +169,33 @@ before
insert on iam_user
for each row execute procedure default_create_time();
create table iam_role (
public_id wt_public_id not null primary key,
create_time wt_timestamp,
update_time wt_timestamp,
name text,
description text,
scope_id wt_public_id not null references iam_scope(public_id) on delete cascade on update cascade,
unique(name, scope_id),
disabled boolean not null default false
);
create trigger
update_time_column
before update on iam_role
for each row execute procedure update_time_column();
create trigger
immutable_create_time
before
update on iam_role
for each row execute procedure immutable_create_time_func();
create trigger
default_create_time_column
before
insert on iam_role
for each row execute procedure default_create_time();
create table iam_group (
public_id wt_public_id not null primary key,
@@ -197,4 +224,5 @@ create trigger
before
insert on iam_group
for each row execute procedure default_create_time();
commit;
+9
View File
@@ -9,8 +9,17 @@ import (
const (
UserPrefix = "u"
GroupPrefix = "g"
RolePrefix = "r"
)
func newRoleId() (string, error) {
id, err := db.NewPublicId(RolePrefix)
if err != nil {
return "", fmt.Errorf("new role id: %w", err)
}
return id, nil
}
func newUserId() (string, error) {
id, err := db.NewPublicId(UserPrefix)
if err != nil {
+7 -1
View File
@@ -1,16 +1,22 @@
package iam
import (
"errors"
"strings"
"testing"
"errors"
"github.com/hashicorp/watchtower/internal/db"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_PublicIds(t *testing.T) {
t.Run("role", func(t *testing.T) {
id, err := newRoleId()
require.NoError(t, err)
assert.True(t, strings.HasPrefix(id, RolePrefix+"_"))
})
t.Run("user", func(t *testing.T) {
id, err := newUserId()
require.NoError(t, err)
+116
View File
@@ -0,0 +1,116 @@
package iam
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/watchtower/internal/db"
)
// CreateRole will create a role in the repository and return the written
// role. No options are currently supported.
func (r *Repository) CreateRole(ctx context.Context, role *Role, opt ...Option) (*Role, error) {
if role == nil {
return nil, fmt.Errorf("create role: missing role %w", db.ErrNilParameter)
}
if role.Role == nil {
return nil, fmt.Errorf("create role: missing role store %w", db.ErrNilParameter)
}
if role.PublicId != "" {
return nil, fmt.Errorf("create role: public id not empty: %w", db.ErrInvalidParameter)
}
if role.ScopeId == "" {
return nil, fmt.Errorf("create role: missing role scope id: %w", db.ErrInvalidParameter)
}
id, err := newRoleId()
if err != nil {
return nil, fmt.Errorf("create role: %w", err)
}
c := role.Clone().(*Role)
c.PublicId = id
resource, err := r.create(ctx, c)
if err != nil {
if db.IsUniqueError(err) {
return nil, fmt.Errorf("create role: role %s already exists in scope %s: %w", role.Name, role.ScopeId, db.ErrNotUnique)
}
return nil, fmt.Errorf("create role: %w for %s", err, c.PublicId)
}
return resource.(*Role), err
}
// UpdateRole will update a role in the repository and return the written
// role. fieldMaskPaths provides field_mask.proto paths for fields that should
// be updated. Fields will be set to NULL if the field is a zero value and
// included in fieldMask. Name and Description are the only updatable fields,
// If no updatable fields are included in the fieldMaskPaths, then an error is returned.
func (r *Repository) UpdateRole(ctx context.Context, role *Role, fieldMaskPaths []string, opt ...Option) (*Role, int, error) {
if role == nil {
return nil, db.NoRowsAffected, fmt.Errorf("update role: missing role %w", db.ErrNilParameter)
}
if role.Role == nil {
return nil, db.NoRowsAffected, fmt.Errorf("update role: missing role store %w", db.ErrNilParameter)
}
if role.PublicId == "" {
return nil, db.NoRowsAffected, fmt.Errorf("update role: missing role public id %w", db.ErrInvalidParameter)
}
for _, f := range fieldMaskPaths {
switch {
case strings.EqualFold("name", f):
case strings.EqualFold("description", f):
default:
return nil, db.NoRowsAffected, fmt.Errorf("update role: field: %s: %w", f, db.ErrInvalidFieldMask)
}
}
var dbMask, nullFields []string
dbMask, nullFields = buildUpdatePaths(
map[string]interface{}{
"name": role.Name,
"description": role.Description,
},
fieldMaskPaths,
)
if len(dbMask) == 0 && len(nullFields) == 0 {
return nil, db.NoRowsAffected, fmt.Errorf("update role: %w", db.ErrEmptyFieldMask)
}
c := role.Clone().(*Role)
resource, rowsUpdated, err := r.update(ctx, c, dbMask, nullFields)
if err != nil {
if db.IsUniqueError(err) {
return nil, db.NoRowsAffected, fmt.Errorf("update role: role %s already exists in organization %s: %w", role.Name, role.ScopeId, db.ErrNotUnique)
}
return nil, db.NoRowsAffected, fmt.Errorf("update role: %w for %s", err, c.PublicId)
}
return resource.(*Role), rowsUpdated, err
}
// LookupRole will look up a role in the repository. If the role is not
// found, it will return nil, nil.
func (r *Repository) LookupRole(ctx context.Context, withPublicId string, opt ...Option) (*Role, error) {
if withPublicId == "" {
return nil, fmt.Errorf("lookup role: missing public id %w", db.ErrNilParameter)
}
role := allocRole()
role.PublicId = withPublicId
if err := r.reader.LookupByPublicId(ctx, &role); err != nil {
return nil, fmt.Errorf("lookup role: failed %w for %s", err, withPublicId)
}
return &role, nil
}
// DeleteRole will delete a role from the repository.
func (r *Repository) DeleteRole(ctx context.Context, withPublicId string, opt ...Option) (int, error) {
if withPublicId == "" {
return db.NoRowsAffected, fmt.Errorf("delete role: missing public id %w", db.ErrNilParameter)
}
role := allocRole()
role.PublicId = withPublicId
if err := r.reader.LookupByPublicId(ctx, &role); err != nil {
return db.NoRowsAffected, fmt.Errorf("delete role: failed %w for %s", err, withPublicId)
}
rowsDeleted, err := r.delete(ctx, &role)
if err != nil {
return db.NoRowsAffected, fmt.Errorf("delete role: failed %w for %s", err, withPublicId)
}
return rowsDeleted, nil
}
+541
View File
@@ -0,0 +1,541 @@
package iam
import (
"context"
"errors"
"testing"
"time"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/watchtower/internal/db"
dbassert "github.com/hashicorp/watchtower/internal/db/assert"
"github.com/hashicorp/watchtower/internal/oplog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
func TestRepository_CreateRole(t *testing.T) {
t.Parallel()
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(t, err)
err = conn.Close()
assert.NoError(t, err)
}()
rw := db.New(conn)
wrapper := db.TestWrapper(t)
repo, err := NewRepository(rw, rw, wrapper)
require.NoError(t, err)
id := testId(t)
org, proj := TestScopes(t, conn)
type args struct {
role *Role
opt []Option
}
tests := []struct {
name string
args args
wantDup bool
wantErr bool
wantErrMsg string
wantIsError error
}{
{
name: "valid-org",
args: args{
role: func() *Role {
r, err := NewRole(org.PublicId, WithName("valid-org"+id), WithDescription(id))
assert.NoError(t, err)
return r
}(),
},
wantErr: false,
},
{
name: "valid-proj",
args: args{
role: func() *Role {
r, err := NewRole(proj.PublicId, WithName("valid-proj"+id), WithDescription(id))
assert.NoError(t, err)
return r
}(),
},
wantErr: false,
},
{
name: "bad-public-id",
args: args{
role: func() *Role {
r, err := NewRole(proj.PublicId, WithName("valid-proj"+id), WithDescription(id))
assert.NoError(t, err)
r.PublicId = id
return r
}(),
},
wantErrMsg: "create role: public id not empty: invalid parameter",
wantIsError: db.ErrInvalidParameter,
wantErr: true,
},
{
name: "nil-role",
args: args{
role: nil,
},
wantErr: true,
wantErrMsg: "create role: missing role nil parameter",
wantIsError: db.ErrNilParameter,
},
{
name: "nil-store",
args: args{
role: func() *Role {
return &Role{
Role: nil,
}
}(),
},
wantErr: true,
wantErrMsg: "create role: missing role store nil parameter",
wantIsError: db.ErrNilParameter,
},
{
name: "bad-scope-id",
args: args{
role: func() *Role {
r, err := NewRole(id)
assert.NoError(t, err)
return r
}(),
},
wantErr: true,
wantErrMsg: "create role: error getting metadata for create: unable to get scope for standard metadata: record not found for",
wantIsError: db.ErrInvalidParameter,
},
{
name: "dup-name",
args: args{
role: func() *Role {
r, err := NewRole(org.PublicId, WithName("dup-name"+id), WithDescription(id))
assert.NoError(t, err)
return r
}(),
opt: []Option{WithName("dup-name" + id)},
},
wantDup: true,
wantErr: true,
wantErrMsg: "already exists in scope ",
wantIsError: db.ErrNotUnique,
},
{
name: "dup-name-but-diff-scope",
args: args{
role: func() *Role {
r, err := NewRole(proj.PublicId, WithName("dup-name-but-diff-scope"+id), WithDescription(id))
assert.NoError(t, err)
return r
}(),
opt: []Option{WithName("dup-name-but-diff-scope" + id)},
},
wantDup: true,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert := assert.New(t)
if tt.wantDup {
dup, err := NewRole(org.PublicId, tt.args.opt...)
assert.NoError(err)
dup, err = repo.CreateRole(context.Background(), dup, tt.args.opt...)
assert.NoError(err)
assert.NotNil(dup)
}
grp, err := repo.CreateRole(context.Background(), tt.args.role, tt.args.opt...)
if tt.wantErr {
assert.Error(err)
assert.Nil(grp)
assert.Contains(err.Error(), tt.wantErrMsg)
return
}
assert.NoError(err)
assert.NotNil(grp.CreateTime)
assert.NotNil(grp.UpdateTime)
foundGrp, err := repo.LookupRole(context.Background(), grp.PublicId)
assert.NoError(err)
assert.True(proto.Equal(foundGrp, grp))
err = db.TestVerifyOplog(t, rw, grp.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second))
assert.NoError(err)
})
}
}
func TestRepository_UpdateRole(t *testing.T) {
t.Parallel()
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(t, err)
err = conn.Close()
assert.NoError(t, err)
}()
rw := db.New(conn)
wrapper := db.TestWrapper(t)
repo, err := NewRepository(rw, rw, wrapper)
require.NoError(t, err)
id, err := uuid.GenerateUUID()
require.NoError(t, err)
org, proj := TestScopes(t, conn)
pubId := func(s string) *string { return &s }
type args struct {
name string
description string
fieldMaskPaths []string
opt []Option
ScopeId string
PublicId *string
}
tests := []struct {
name string
newScopeId string
newGrpOpts []Option
args args
wantRowsUpdate int
wantErr bool
wantErrMsg string
wantIsError error
wantDup bool
}{
{
name: "valid",
args: args{
name: "valid" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: org.PublicId,
},
newScopeId: org.PublicId,
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "valid-no-op",
args: args{
name: "valid-no-op" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: org.PublicId,
},
newScopeId: org.PublicId,
newGrpOpts: []Option{WithName("valid-no-op" + id)},
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "not-found",
args: args{
name: "not-found" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: org.PublicId,
PublicId: func() *string { s := "1"; return &s }(),
},
newScopeId: org.PublicId,
wantErr: true,
wantRowsUpdate: 0,
wantErrMsg: "update role: update: lookup error lookup after write: failed record not found for 1",
wantIsError: db.ErrRecordNotFound,
},
{
name: "null-name",
args: args{
name: "",
fieldMaskPaths: []string{"Name"},
ScopeId: org.PublicId,
},
newScopeId: org.PublicId,
newGrpOpts: []Option{WithName("null-name" + id)},
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "null-description",
args: args{
name: "",
fieldMaskPaths: []string{"Description"},
ScopeId: org.PublicId,
},
newScopeId: org.PublicId,
newGrpOpts: []Option{WithDescription("null-description" + id)},
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "empty-field-mask",
args: args{
name: "valid" + id,
fieldMaskPaths: []string{},
ScopeId: org.PublicId,
},
newScopeId: org.PublicId,
wantErr: true,
wantRowsUpdate: 0,
wantErrMsg: "update role: empty field mask",
wantIsError: db.ErrEmptyFieldMask,
},
{
name: "nil-fieldmask",
args: args{
name: "valid" + id,
fieldMaskPaths: nil,
ScopeId: org.PublicId,
},
newScopeId: org.PublicId,
wantErr: true,
wantRowsUpdate: 0,
wantErrMsg: "update role: empty field mask",
wantIsError: db.ErrEmptyFieldMask,
},
{
name: "read-only-fields",
args: args{
name: "valid" + id,
fieldMaskPaths: []string{"CreateTime"},
ScopeId: org.PublicId,
},
newScopeId: org.PublicId,
wantErr: true,
wantRowsUpdate: 0,
wantErrMsg: "update role: field: CreateTime: invalid field mask",
wantIsError: db.ErrInvalidFieldMask,
},
{
name: "unknown-fields",
args: args{
name: "valid" + id,
fieldMaskPaths: []string{"Alice"},
ScopeId: org.PublicId,
},
newScopeId: org.PublicId,
wantErr: true,
wantRowsUpdate: 0,
wantErrMsg: "update role: field: Alice: invalid field mask",
wantIsError: db.ErrInvalidFieldMask,
},
{
name: "no-public-id",
args: args{
name: "valid" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: org.PublicId,
PublicId: pubId(""),
},
newScopeId: org.PublicId,
wantErr: true,
wantErrMsg: "update role: missing role public id invalid parameter",
wantIsError: db.ErrInvalidParameter,
wantRowsUpdate: 0,
},
{
name: "proj-scope-id-no-mask",
args: args{
name: "proj-scope-id" + id,
ScopeId: proj.PublicId,
},
newScopeId: org.PublicId,
wantErr: true,
wantErrMsg: "update role: empty field mask",
wantIsError: db.ErrEmptyFieldMask,
},
{
name: "empty-scope-id-with-name-mask",
args: args{
name: "empty-scope-id" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: "",
},
newScopeId: org.PublicId,
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "dup-name-in-diff-scope",
args: args{
name: "dup-name-in-diff-scope" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: proj.PublicId,
},
newScopeId: proj.PublicId,
newGrpOpts: []Option{WithName("dup-name-in-diff-scope-pre-update" + id)},
wantErr: false,
wantRowsUpdate: 1,
wantDup: true,
},
{
name: "dup-name",
args: args{
name: "dup-name" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: org.PublicId,
},
newScopeId: org.PublicId,
wantErr: true,
wantDup: true,
wantErrMsg: " already exists in organization " + org.PublicId,
wantIsError: db.ErrNotUnique,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert := assert.New(t)
if tt.wantDup {
r := TestRole(t, conn, org.PublicId)
r.Name = tt.args.name
_, _, err := repo.UpdateRole(context.Background(), r, tt.args.fieldMaskPaths, tt.args.opt...)
assert.NoError(err)
}
r := TestRole(t, conn, tt.newScopeId, tt.newGrpOpts...)
updateRole := allocRole()
updateRole.PublicId = r.PublicId
if tt.args.PublicId != nil {
updateRole.PublicId = *tt.args.PublicId
}
updateRole.ScopeId = tt.args.ScopeId
updateRole.Name = tt.args.name
updateRole.Description = tt.args.description
roleAfterUpdate, updatedRows, err := repo.UpdateRole(context.Background(), &updateRole, tt.args.fieldMaskPaths, tt.args.opt...)
if tt.wantErr {
assert.Error(err)
if tt.wantIsError != nil {
assert.True(errors.Is(err, tt.wantIsError))
}
assert.Nil(roleAfterUpdate)
assert.Equal(0, updatedRows)
assert.Contains(err.Error(), tt.wantErrMsg)
err = db.TestVerifyOplog(t, rw, r.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second))
assert.Error(err)
assert.True(errors.Is(db.ErrRecordNotFound, err))
return
}
assert.NoError(err)
assert.Equal(tt.wantRowsUpdate, updatedRows)
switch tt.name {
case "valid-no-op":
assert.Equal(r.UpdateTime, roleAfterUpdate.UpdateTime)
default:
assert.NotEqual(r.UpdateTime, roleAfterUpdate.UpdateTime)
}
foundRole, err := repo.LookupRole(context.Background(), r.PublicId)
assert.NoError(err)
assert.True(proto.Equal(roleAfterUpdate, foundRole))
dbassert := dbassert.New(t, rw)
if tt.args.name == "" {
assert.Equal(foundRole.Name, "")
dbassert.IsNull(foundRole, "name")
}
if tt.args.description == "" {
assert.Equal(foundRole.Description, "")
dbassert.IsNull(foundRole, "description")
}
err = db.TestVerifyOplog(t, rw, r.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second))
assert.NoError(err)
})
}
}
func TestRepository_DeleteRole(t *testing.T) {
t.Parallel()
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(t, err)
err = conn.Close()
assert.NoError(t, err)
}()
rw := db.New(conn)
wrapper := db.TestWrapper(t)
repo, err := NewRepository(rw, rw, wrapper)
require.NoError(t, err)
org, _ := TestScopes(t, conn)
type args struct {
role *Role
opt []Option
}
tests := []struct {
name string
args args
wantRowsDeleted int
wantErr bool
wantErrMsg string
}{
{
name: "valid",
args: args{
role: TestRole(t, conn, org.PublicId),
},
wantRowsDeleted: 1,
wantErr: false,
},
{
name: "no-public-id",
args: args{
role: func() *Role {
g := allocRole()
return &g
}(),
},
wantRowsDeleted: 0,
wantErr: true,
wantErrMsg: "delete role: missing public id nil parameter",
},
{
name: "not-found",
args: args{
role: func() *Role {
id, err := newRoleId()
require.NoError(t, err)
r, err := NewRole(org.PublicId)
r.PublicId = id
require.NoError(t, err)
return r
}(),
},
wantRowsDeleted: 0,
wantErr: true,
wantErrMsg: "delete role: failed record not found for ",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert := assert.New(t)
deletedRows, err := repo.DeleteRole(context.Background(), tt.args.role.PublicId, tt.args.opt...)
if tt.wantErr {
assert.Error(err)
assert.Equal(0, deletedRows)
assert.Contains(err.Error(), tt.wantErrMsg)
err = db.TestVerifyOplog(t, rw, tt.args.role.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second))
assert.Error(err)
assert.True(errors.Is(db.ErrRecordNotFound, err))
return
}
assert.NoError(err)
assert.Equal(tt.wantRowsDeleted, deletedRows)
foundRole, err := repo.LookupRole(context.Background(), tt.args.role.PublicId)
assert.Error(err)
assert.Nil(foundRole)
assert.True(errors.Is(err, db.ErrRecordNotFound))
err = db.TestVerifyOplog(t, rw, tt.args.role.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second))
assert.NoError(err)
})
}
}
+96
View File
@@ -0,0 +1,96 @@
package iam
import (
"context"
"errors"
"fmt"
"github.com/hashicorp/watchtower/internal/db"
"github.com/hashicorp/watchtower/internal/iam/store"
"google.golang.org/protobuf/proto"
)
// Roles are granted permissions and assignable to Users and Groups.
type Role struct {
*store.Role
tableName string `gorm:"-"`
}
// ensure that Role implements the interfaces of: Resource, Clonable, and db.VetForWriter.
var _ Resource = (*Role)(nil)
var _ Clonable = (*Role)(nil)
var _ db.VetForWriter = (*Role)(nil)
// NewRole creates a new in memory role with a scope (project/organization)
// allowed options include: withDescripion, WithName.
func NewRole(scopeId string, opt ...Option) (*Role, error) {
if scopeId == "" {
return nil, fmt.Errorf("new role: missing scope id %w", db.ErrInvalidParameter)
}
opts := getOpts(opt...)
r := &Role{
Role: &store.Role{
ScopeId: scopeId,
Name: opts.withName,
Description: opts.withDescription,
},
}
return r, nil
}
func allocRole() Role {
return Role{
Role: &store.Role{},
}
}
// Clone creates a clone of the Role.
func (r *Role) Clone() interface{} {
cp := proto.Clone(r.Role)
return &Role{
Role: cp.(*store.Role),
}
}
// VetForWrite implements db.VetForWrite() interface.
func (role *Role) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error {
if role.PublicId == "" {
return errors.New("error public id is empty string for role write")
}
if err := validateScopeForWrite(ctx, r, role, opType, opt...); err != nil {
return err
}
return nil
}
func (u *Role) validScopeTypes() []ScopeType {
return []ScopeType{OrganizationScope, ProjectScope}
}
// Getscope returns the scope for the Role.
func (role *Role) GetScope(ctx context.Context, r db.Reader) (*Scope, error) {
return LookupScope(ctx, r, role)
}
// ResourceType returns the type of the Role.
func (*Role) ResourceType() ResourceType { return ResourceTypeRole }
// Actions returns the available actions for Role.
func (*Role) Actions() map[string]Action {
return CrudActions()
}
// TableName returns the tablename to override the default gorm table name.
func (r *Role) TableName() string {
if r.tableName != "" {
return r.tableName
}
return "iam_role"
}
// SetTableName sets the tablename and satisfies the ReplayableMessage interface.
func (r *Role) SetTableName(n string) {
if n != "" {
r.tableName = n
}
}
+516
View File
@@ -0,0 +1,516 @@
package iam
import (
"context"
"errors"
"testing"
"time"
"github.com/hashicorp/watchtower/internal/db"
dbassert "github.com/hashicorp/watchtower/internal/db/assert"
"github.com/hashicorp/watchtower/internal/oplog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
func TestNewRole(t *testing.T) {
t.Parallel()
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(t, err)
err = conn.Close()
assert.NoError(t, err)
}()
org, proj := TestScopes(t, conn)
id := testId(t)
type args struct {
scopePublicId string
opt []Option
}
tests := []struct {
name string
args args
wantErr bool
wantErrMsg string
wantIsErr error
wantName string
wantDescription string
}{
{
name: "valid",
args: args{
scopePublicId: org.PublicId,
opt: []Option{WithName(id), WithDescription("description-" + id)},
},
wantErr: false,
wantName: id,
wantDescription: "description-" + id,
},
{
name: "valid-proj",
args: args{
scopePublicId: proj.PublicId,
opt: []Option{WithName(id), WithDescription("description-" + id)},
},
wantErr: false,
wantName: id,
wantDescription: "description-" + id,
},
{
name: "valid-with-no-options" + id,
args: args{
scopePublicId: org.PublicId,
},
wantErr: false,
},
{
name: "no-scope",
args: args{
opt: []Option{WithName(id)},
},
wantErr: true,
wantErrMsg: "new role: missing scope id invalid parameter",
wantIsErr: db.ErrInvalidParameter,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
got, err := NewRole(tt.args.scopePublicId, tt.args.opt...)
if tt.wantErr {
require.Error(err)
assert.Equal(tt.wantErrMsg, err.Error())
if tt.wantIsErr != nil {
assert.True(errors.Is(err, tt.wantIsErr))
}
return
}
require.NoError(err)
assert.Equal(tt.wantName, got.Name)
assert.Equal(tt.wantDescription, got.Description)
assert.Empty(got.PublicId)
})
}
}
func Test_RoleCreate(t *testing.T) {
t.Parallel()
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(t, err)
err = conn.Close()
assert.NoError(t, err)
}()
org, proj := TestScopes(t, conn)
type args struct {
role *Role
}
tests := []struct {
name string
args args
wantDup bool
wantErr bool
wantErrMsg string
wantIsError error
}{
{
name: "valid-with-org",
args: args{
role: func() *Role {
id := testId(t)
role, err := NewRole(org.PublicId, WithName(id), WithDescription("description-"+id))
require.NoError(t, err)
grpId, err := newRoleId()
require.NoError(t, err)
role.PublicId = grpId
return role
}(),
},
wantErr: false,
},
{
name: "valid-with-proj",
args: args{
role: func() *Role {
id := testId(t)
role, err := NewRole(proj.PublicId, WithName(id), WithDescription("description-"+id))
require.NoError(t, err)
grpId, err := newRoleId()
require.NoError(t, err)
role.PublicId = grpId
return role
}(),
},
wantErr: false,
},
{
name: "valid-with-dup-null-names-and-descriptions",
args: args{
role: func() *Role {
role, err := NewRole(org.PublicId)
require.NoError(t, err)
roleId, err := newRoleId()
require.NoError(t, err)
role.PublicId = roleId
return role
}(),
},
wantDup: true,
wantErr: false,
},
{
name: "bad-scope-id",
args: args{
role: func() *Role {
id := testId(t)
role, err := NewRole(id)
require.NoError(t, err)
roleId, err := newRoleId()
require.NoError(t, err)
role.PublicId = roleId
return role
}(),
},
wantErr: true,
wantErrMsg: "create: vet for write failed scope is not found",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
w := db.New(conn)
if tt.wantDup {
r := tt.args.role.Clone().(*Role)
roleId, err := newRoleId()
require.NoError(err)
r.PublicId = roleId
err = w.Create(context.Background(), r)
require.NoError(err)
}
r := tt.args.role.Clone().(*Role)
err := w.Create(context.Background(), r)
if tt.wantErr {
require.Error(err)
assert.Equal(tt.wantErrMsg, err.Error())
return
}
assert.NoError(err)
assert.NotEmpty(tt.args.role.PublicId)
foundGrp := allocRole()
foundGrp.PublicId = tt.args.role.PublicId
err = w.LookupByPublicId(context.Background(), &foundGrp)
require.NoError(err)
assert.Equal(r, &foundGrp)
})
}
}
func Test_RoleUpdate(t *testing.T) {
t.Parallel()
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(t, err)
err = conn.Close()
assert.NoError(t, err)
}()
id := testId(t)
org, proj := TestScopes(t, conn)
rw := db.New(conn)
type args struct {
name string
description string
fieldMaskPaths []string
nullPaths []string
ScopeId string
}
tests := []struct {
name string
args args
wantRowsUpdate int
wantErr bool
wantErrMsg string
wantDup bool
}{
{
name: "valid",
args: args{
name: "valid" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: org.PublicId,
},
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "proj-scope-id",
args: args{
name: "proj-scope-id" + id,
fieldMaskPaths: []string{"ScopeId"},
ScopeId: proj.PublicId,
},
wantErr: true,
wantErrMsg: "update: vet for write failed not allowed to change a resource's scope",
},
{
name: "proj-scope-id-not-in-mask",
args: args{
name: "proj-scope-id" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: proj.PublicId,
},
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "empty-scope-id",
args: args{
name: "empty-scope-id" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: "",
},
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "dup-name",
args: args{
name: "dup-name" + id,
fieldMaskPaths: []string{"Name"},
ScopeId: org.PublicId,
},
wantErr: true,
wantDup: true,
wantErrMsg: `update: failed pq: duplicate key value violates unique constraint "iam_role_name_scope_id_key"`,
},
{
name: "set description null",
args: args{
name: "set description null" + id,
fieldMaskPaths: []string{"Name"},
nullPaths: []string{"Description"},
ScopeId: org.PublicId,
},
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "set name null",
args: args{
description: "set description null" + id,
fieldMaskPaths: []string{"Description"},
nullPaths: []string{"Name"},
ScopeId: org.PublicId,
},
wantDup: true,
wantErr: false,
wantRowsUpdate: 1,
},
{
name: "set description null",
args: args{
name: "set name null" + id,
fieldMaskPaths: []string{"Name"},
nullPaths: []string{"Description"},
ScopeId: org.PublicId,
},
wantErr: false,
wantRowsUpdate: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
if tt.wantDup {
r := TestRole(t, conn, org.PublicId, WithName(tt.args.name))
_, err := rw.Update(context.Background(), r, tt.args.fieldMaskPaths, tt.args.nullPaths)
require.NoError(err)
}
id := testId(t)
role := TestRole(t, conn, org.PublicId, WithDescription(id), WithName(id))
updateRole := allocRole()
updateRole.PublicId = role.PublicId
updateRole.ScopeId = tt.args.ScopeId
updateRole.Name = tt.args.name
updateRole.Description = tt.args.description
updatedRows, err := rw.Update(context.Background(), &updateRole, tt.args.fieldMaskPaths, tt.args.nullPaths)
if tt.wantErr {
require.Error(err)
assert.Equal(0, updatedRows)
assert.Equal(tt.wantErrMsg, err.Error())
err = db.TestVerifyOplog(t, rw, role.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second))
require.Error(err)
assert.Equal("record not found", err.Error())
return
}
require.NoError(err)
assert.Equal(tt.wantRowsUpdate, updatedRows)
assert.NotEqual(role.UpdateTime, updateRole.UpdateTime)
foundRole := allocRole()
foundRole.PublicId = role.GetPublicId()
err = rw.LookupByPublicId(context.Background(), &foundRole)
require.NoError(err)
assert.True(proto.Equal(updateRole, foundRole))
if len(tt.args.nullPaths) != 0 {
dbassert := dbassert.New(t, rw)
for _, f := range tt.args.nullPaths {
dbassert.IsNull(&foundRole, f)
}
}
})
}
t.Run("update dup names in diff scopes", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
id := testId(t)
_ = TestRole(t, conn, org.PublicId, WithDescription(id), WithName(id))
projRole := TestRole(t, conn, proj.PublicId, WithName(id))
updatedRows, err := rw.Update(context.Background(), projRole, []string{"Name"}, nil)
require.NoError(err)
assert.Equal(1, updatedRows)
foundRole := allocRole()
foundRole.PublicId = projRole.GetPublicId()
err = rw.LookupByPublicId(context.Background(), &foundRole)
require.NoError(err)
assert.Equal(id, projRole.Name)
})
}
func Test_RoleDelete(t *testing.T) {
t.Parallel()
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(t, err)
err = conn.Close()
assert.NoError(t, err)
}()
rw := db.New(conn)
id := testId(t)
org, _ := TestScopes(t, conn)
tests := []struct {
name string
role *Role
wantRowsDeleted int
wantErr bool
wantErrMsg string
}{
{
name: "valid",
role: TestRole(t, conn, org.PublicId),
wantErr: false,
wantRowsDeleted: 1,
},
{
name: "bad-id",
role: func() *Role { r := allocRole(); r.PublicId = id; return &r }(),
wantErr: false,
wantRowsDeleted: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
deleteRole := allocRole()
deleteRole.PublicId = tt.role.GetPublicId()
deletedRows, err := rw.Delete(context.Background(), &deleteRole)
if tt.wantErr {
require.Error(err)
return
}
require.NoError(err)
if tt.wantRowsDeleted == 0 {
assert.Equal(tt.wantRowsDeleted, deletedRows)
return
}
assert.Equal(tt.wantRowsDeleted, deletedRows)
foundRole := allocRole()
foundRole.PublicId = tt.role.GetPublicId()
err = rw.LookupByPublicId(context.Background(), &foundRole)
require.Error(err)
assert.True(errors.Is(db.ErrRecordNotFound, err))
})
}
}
func TestRole_Actions(t *testing.T) {
assert := assert.New(t)
r := &Role{}
a := r.Actions()
assert.Equal(a[ActionCreate.String()], ActionCreate)
assert.Equal(a[ActionUpdate.String()], ActionUpdate)
assert.Equal(a[ActionRead.String()], ActionRead)
assert.Equal(a[ActionDelete.String()], ActionDelete)
}
func TestRole_ResourceType(t *testing.T) {
assert := assert.New(t)
r := &Role{}
ty := r.ResourceType()
assert.Equal(ty, ResourceTypeRole)
}
func TestRole_GetScope(t *testing.T) {
t.Parallel()
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(t, err)
err = conn.Close()
assert.NoError(t, err)
}()
org, proj := TestScopes(t, conn)
t.Run("valid-org", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
w := db.New(conn)
role := TestRole(t, conn, org.PublicId)
scope, err := role.GetScope(context.Background(), w)
require.NoError(err)
assert.True(proto.Equal(org, scope))
})
t.Run("valid-proj", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
w := db.New(conn)
role := TestRole(t, conn, proj.PublicId)
scope, err := role.GetScope(context.Background(), w)
require.NoError(err)
assert.True(proto.Equal(proj, scope))
})
}
func TestRole_Clone(t *testing.T) {
t.Parallel()
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(t, err)
err = conn.Close()
assert.NoError(t, err)
}()
org, _ := TestScopes(t, conn)
t.Run("valid", func(t *testing.T) {
assert := assert.New(t)
role := TestRole(t, conn, org.PublicId, WithDescription("this is a test role"))
cp := role.Clone()
assert.True(proto.Equal(cp.(*Role).Role, role.Role))
})
t.Run("not-equal", func(t *testing.T) {
assert := assert.New(t)
role := TestRole(t, conn, org.PublicId)
role2 := TestRole(t, conn, org.PublicId)
cp := role.Clone()
assert.True(!proto.Equal(cp.(*Role).Role, role2.Role))
})
}
+243
View File
@@ -0,0 +1,243 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.24.0
// protoc v3.12.3
// source: controller/storage/iam/store/v1/role.proto
package store
import (
proto "github.com/golang/protobuf/proto"
timestamp "github.com/hashicorp/watchtower/internal/db/timestamp"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
type Role struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// public_id is used to access the Role via an API
// @inject_tag: gorm:"primary_key"
PublicId string `protobuf:"bytes,1,opt,name=public_id,json=publicId,proto3" json:"public_id,omitempty" gorm:"primary_key"`
// create_time from the RDBMS
// @inject_tag: `gorm:"default:current_timestamp"`
CreateTime *timestamp.Timestamp `protobuf:"bytes,2,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty" gorm:"default:current_timestamp"`
// update_time from the RDBMS
// @inject_tag: `gorm:"default:current_timestamp"`
UpdateTime *timestamp.Timestamp `protobuf:"bytes,3,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty" gorm:"default:current_timestamp"`
// name is the optional friendly name used to
// access the Role via an API
// @inject_tag: `gorm:"default:null"`
Name string `protobuf:"bytes,5,opt,name=name,proto3" json:"name,omitempty" gorm:"default:null"`
// description of the role
// @inject_tag: `gorm:"default:null"`
Description string `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty" gorm:"default:null"`
// scope id for the role
// @inject_tag: `gorm:"default:null"`
ScopeId string `protobuf:"bytes,7,opt,name=scope_id,json=scopeId,proto3" json:"scope_id,omitempty" gorm:"default:null"`
// disabled is by default false and allows a Role to be marked disabled.
// @inject_tag: `gorm:"default:null"`
Disabled bool `protobuf:"varint,9,opt,name=disabled,proto3" json:"disabled,omitempty" gorm:"default:null"`
}
func (x *Role) Reset() {
*x = Role{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_storage_iam_store_v1_role_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Role) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Role) ProtoMessage() {}
func (x *Role) ProtoReflect() protoreflect.Message {
mi := &file_controller_storage_iam_store_v1_role_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Role.ProtoReflect.Descriptor instead.
func (*Role) Descriptor() ([]byte, []int) {
return file_controller_storage_iam_store_v1_role_proto_rawDescGZIP(), []int{0}
}
func (x *Role) GetPublicId() string {
if x != nil {
return x.PublicId
}
return ""
}
func (x *Role) GetCreateTime() *timestamp.Timestamp {
if x != nil {
return x.CreateTime
}
return nil
}
func (x *Role) GetUpdateTime() *timestamp.Timestamp {
if x != nil {
return x.UpdateTime
}
return nil
}
func (x *Role) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *Role) GetDescription() string {
if x != nil {
return x.Description
}
return ""
}
func (x *Role) GetScopeId() string {
if x != nil {
return x.ScopeId
}
return ""
}
func (x *Role) GetDisabled() bool {
if x != nil {
return x.Disabled
}
return false
}
var File_controller_storage_iam_store_v1_role_proto protoreflect.FileDescriptor
var file_controller_storage_iam_store_v1_role_proto_rawDesc = []byte{
0x0a, 0x2a, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f,
0x72, 0x61, 0x67, 0x65, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x76,
0x31, 0x2f, 0x72, 0x6f, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1f, 0x63, 0x6f,
0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65,
0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x2f, 0x63,
0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67,
0x65, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2f, 0x76, 0x31, 0x2f, 0x74,
0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2b,
0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x61,
0x67, 0x65, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x31, 0x2f,
0x73, 0x63, 0x6f, 0x70, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xaa, 0x02, 0x0a, 0x04,
0x52, 0x6f, 0x6c, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x69,
0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x49,
0x64, 0x12, 0x4b, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65,
0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c,
0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65,
0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61,
0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x4b,
0x0a, 0x0b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20,
0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72,
0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61,
0x6d, 0x70, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52,
0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e,
0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12,
0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x06,
0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f,
0x6e, 0x12, 0x19, 0x0a, 0x08, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x07, 0x20,
0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08,
0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x09, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08,
0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x42, 0x3a, 0x5a, 0x38, 0x67, 0x69, 0x74, 0x68,
0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70,
0x2f, 0x77, 0x61, 0x74, 0x63, 0x68, 0x74, 0x6f, 0x77, 0x65, 0x72, 0x2f, 0x69, 0x6e, 0x74, 0x65,
0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x3b, 0x73,
0x74, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_controller_storage_iam_store_v1_role_proto_rawDescOnce sync.Once
file_controller_storage_iam_store_v1_role_proto_rawDescData = file_controller_storage_iam_store_v1_role_proto_rawDesc
)
func file_controller_storage_iam_store_v1_role_proto_rawDescGZIP() []byte {
file_controller_storage_iam_store_v1_role_proto_rawDescOnce.Do(func() {
file_controller_storage_iam_store_v1_role_proto_rawDescData = protoimpl.X.CompressGZIP(file_controller_storage_iam_store_v1_role_proto_rawDescData)
})
return file_controller_storage_iam_store_v1_role_proto_rawDescData
}
var file_controller_storage_iam_store_v1_role_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_controller_storage_iam_store_v1_role_proto_goTypes = []interface{}{
(*Role)(nil), // 0: controller.storage.iam.store.v1.Role
(*timestamp.Timestamp)(nil), // 1: controller.storage.timestamp.v1.Timestamp
}
var file_controller_storage_iam_store_v1_role_proto_depIdxs = []int32{
1, // 0: controller.storage.iam.store.v1.Role.create_time:type_name -> controller.storage.timestamp.v1.Timestamp
1, // 1: controller.storage.iam.store.v1.Role.update_time:type_name -> controller.storage.timestamp.v1.Timestamp
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_controller_storage_iam_store_v1_role_proto_init() }
func file_controller_storage_iam_store_v1_role_proto_init() {
if File_controller_storage_iam_store_v1_role_proto != nil {
return
}
file_controller_storage_iam_store_v1_scope_proto_init()
if !protoimpl.UnsafeEnabled {
file_controller_storage_iam_store_v1_role_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Role); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_controller_storage_iam_store_v1_role_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_controller_storage_iam_store_v1_role_proto_goTypes,
DependencyIndexes: file_controller_storage_iam_store_v1_role_proto_depIdxs,
MessageInfos: file_controller_storage_iam_store_v1_role_proto_msgTypes,
}.Build()
File_controller_storage_iam_store_v1_role_proto = out.File
file_controller_storage_iam_store_v1_role_proto_rawDesc = nil
file_controller_storage_iam_store_v1_role_proto_goTypes = nil
file_controller_storage_iam_store_v1_role_proto_depIdxs = nil
}
+21
View File
@@ -85,6 +85,27 @@ func TestUser(t *testing.T, conn *gorm.DB, orgId string, opt ...Option) *User {
return user
}
// TestRole creates a role suitable for testing.
func TestRole(t *testing.T, conn *gorm.DB, scopeId string, opt ...Option) *Role {
t.Helper()
require := require.New(t)
rw := db.New(conn)
role, err := NewRole(scopeId, opt...)
require.NoError(err)
id, err := newRoleId()
require.NoError(err)
role.PublicId = id
err = rw.Create(context.Background(), role)
require.NoError(err)
require.NotEmpty(role.PublicId)
opts := getOpts(opt...)
require.Equal(opts.withDescription, role.Description)
require.Equal(opts.withName, role.Name)
return role
}
// TestGroup creates a group suitable for testing.
func TestGroup(t *testing.T, conn *gorm.DB, orgId string, opt ...Option) *Group {
t.Helper()
+23 -1
View File
@@ -67,7 +67,6 @@ func Test_TestUser(t *testing.T) {
err = conn.Close()
assert.NoError(err)
}()
org, _ := TestScopes(t, conn)
require.NotNil(org)
@@ -77,3 +76,26 @@ func Test_TestUser(t *testing.T) {
require.NotNil(user)
assert.NotEmpty(user.PublicId)
}
func Test_TestRole(t *testing.T) {
t.Helper()
assert, require := assert.New(t), require.New(t)
cleanup, conn, _ := db.TestSetup(t, "postgres")
defer func() {
err := cleanup()
assert.NoError(err)
err = conn.Close()
assert.NoError(err)
}()
id := testId(t)
org, proj := TestScopes(t, conn)
role := TestRole(t, conn, org.PublicId, WithDescription(id), WithName(id))
require.NotNil(role)
assert.Equal(id, role.Description)
assert.Equal(id, role.Name)
assert.NotEmpty(role.PublicId)
projRole := TestRole(t, conn, proj.PublicId)
require.NotNil(projRole)
assert.NotEmpty(projRole.PublicId)
}
@@ -0,0 +1,38 @@
syntax = "proto3";
package controller.storage.iam.store.v1;
option go_package = "github.com/hashicorp/watchtower/internal/iam/store;store";
import "controller/storage/timestamp/v1/timestamp.proto";
import "controller/storage/iam/store/v1/scope.proto";
message Role {
// public_id is used to access the Role via an API
// @inject_tag: gorm:"primary_key"
string public_id = 1;
// create_time from the RDBMS
// @inject_tag: `gorm:"default:current_timestamp"`
timestamp.v1.Timestamp create_time = 2;
// update_time from the RDBMS
// @inject_tag: `gorm:"default:current_timestamp"`
timestamp.v1.Timestamp update_time = 3;
// name is the optional friendly name used to
// access the Role via an API
// @inject_tag: `gorm:"default:null"`
string name = 5;
// description of the role
// @inject_tag: `gorm:"default:null"`
string description = 6;
// scope id for the role
// @inject_tag: `gorm:"default:null"`
string scope_id = 7;
// disabled is by default false and allows a Role to be marked disabled.
// @inject_tag: `gorm:"default:null"`
bool disabled = 9;
}