implement schema, store and repository for IAM scopes of organization and project

This commit is contained in:
Jim authored and GitHub committed 2020-05-08 11:36:28 -04:00
1 parent 8824a6f7f9
commit 8a5197e39e
27 files changed
+2007 -38

No files matched your search

+2 -2
View File
@@ -9,7 +9,7 @@ import (
func TestPublicIdDomain(t *testing.T) {
const (
createTable = `
create table test_table (
create table if not exists test_table (
id bigint generated always as identity primary key,
public_id wt_public_id
);
@@ -33,7 +33,7 @@ returning id;
failTests := []string{
" ",
"bar",
"0000000001000000000200000000031",
"00000009",
}
for _, tt := range failTests {
value := tt
+20
View File
@@ -0,0 +1,20 @@
package db
import (
"errors"
"fmt"
"github.com/hashicorp/vault/sdk/helper/base62"
)
// NewPublicId creates a new public id with the prefix
func NewPublicId(prefix string) (string, error) {
if prefix == "" {
return "", errors.New("error no prefix for new public id")
}
publicId, err := base62.Random(10)
if err != nil {
return "", fmt.Errorf("unable to generate public id: %w", err)
}
return fmt.Sprintf("%s_%s", prefix, publicId), nil
}
+51
View File
@@ -0,0 +1,51 @@
package db
import (
"strings"
"testing"
)
func TestNewPublicId(t *testing.T) {
type args struct {
prefix string
}
tests := []struct {
name string
args args
wantErr bool
wantLen int
}{
{
name: "valid",
args: args{
prefix: "id",
},
wantErr: false,
wantLen: 10 + len("id_"),
},
{
name: "bad-prefix",
args: args{
prefix: "",
},
wantErr: true,
wantLen: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NewPublicId(tt.args.prefix)
if (err != nil) != tt.wantErr {
t.Errorf("NewPublicId() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && !strings.HasPrefix(got, tt.args.prefix+"_") {
t.Errorf("NewPublicId() = %v, wanted it to start with %v", got, tt.args.prefix)
}
if len(got) != tt.wantLen {
t.Errorf("NewPublicId() = %v, with len of %d and wanted len of %v", got, len(got), tt.wantLen)
}
})
}
}
@@ -2,7 +2,7 @@ begin;
create domain wt_public_id as text
check(
length(trim(value)) > 31
length(trim(value)) > 10
);
comment on domain wt_public_id is
'Random ID generated with github.com/hashicorp/vault/sdk/helper/base62';
@@ -0,0 +1,7 @@
BEGIN;
drop table if exists iam_scope CASCADE;
drop trigger if exists iam_scope_insert;
drop function if exists iam_sub_scopes_func;
COMMIT;
@@ -0,0 +1,86 @@
BEGIN;
CREATE TABLE if not exists iam_scope_type_enm (
string text NOT NULL primary key CHECK(string IN ('unknown', 'organization', 'project'))
);
INSERT INTO iam_scope_type_enm (string)
values
('unknown'),
('organization'),
('project');
CREATE TABLE if not exists iam_scope (
public_id wt_public_id primary key,
create_time timestamp with time zone default current_timestamp,
update_time timestamp with time zone default current_timestamp,
name text,
type text NOT NULL REFERENCES iam_scope_type_enm(string) CHECK(
(
type = 'organization'
and parent_id = NULL
)
or (
type = 'project'
and parent_id IS NOT NULL
)
),
description text,
parent_id text REFERENCES iam_scope(public_id) ON DELETE CASCADE ON UPDATE CASCADE
);
create table if not exists iam_scope_organization (
scope_id wt_public_id NOT NULL UNIQUE REFERENCES iam_scope(public_id) ON DELETE CASCADE ON UPDATE CASCADE,
name text UNIQUE,
primary key(scope_id)
);
create table if not exists iam_scope_project (
scope_id wt_public_id NOT NULL REFERENCES iam_scope(public_id) ON DELETE CASCADE ON UPDATE CASCADE,
parent_id wt_public_id NOT NULL REFERENCES iam_scope_organization(scope_id) ON DELETE CASCADE ON UPDATE CASCADE,
name text,
unique(parent_id, name),
primary key(scope_id, parent_id)
);
CREATE
OR REPLACE FUNCTION iam_sub_scopes_func() RETURNS TRIGGER
SET SCHEMA
'public' LANGUAGE plpgsql AS $$ DECLARE parent_type INT;
BEGIN IF new.type = 'organization' THEN
insert into iam_scope_organization (scope_id, name)
values
(new.public_id, new.name);
return NEW;
END IF;
IF new.type = 'project' THEN
insert into iam_scope_project (scope_id, parent_id, name)
values
(new.public_id, new.parent_id, new.name);
return NEW;
END IF;
RAISE EXCEPTION 'unknown scope type';
END;
$$;
CREATE TRIGGER iam_scope_insert
AFTER
insert ON iam_scope FOR EACH ROW EXECUTE PROCEDURE iam_sub_scopes_func();
CREATE
OR REPLACE FUNCTION iam_immutable_scope_type_func() RETURNS TRIGGER
SET SCHEMA
'public' LANGUAGE plpgsql AS $$ DECLARE parent_type INT;
BEGIN IF new.type != old.type THEN
RAISE EXCEPTION 'scope type cannot be updated';
END IF;
return NEW;
END;
$$;
CREATE TRIGGER iam_scope_update
BEFORE
update ON iam_scope FOR EACH ROW EXECUTE PROCEDURE iam_immutable_scope_type_func();
COMMIT;
+22 -12
View File
@@ -5,8 +5,8 @@ import (
"github.com/hashicorp/watchtower/internal/oplog"
)
// getOpts - iterate the inbound Options and return a struct
func getOpts(opt ...Option) options {
// GetOpts - iterate the inbound Options and return a struct
func GetOpts(opt ...Option) Options {
opts := getDefaultOptions()
for _, o := range opt {
o(&opts)
@@ -15,14 +15,16 @@ func getOpts(opt ...Option) options {
}
// Option - how Options are passed as arguments
type Option func(*options)
type Option func(*Options)
// options = how options are represented
type options struct {
// Options = how Options are represented
type Options struct {
withOplog bool
oplogOpts oplogOpts
withDebug bool
withLookup bool
// WithFieldMaskPaths must be accessible from other packages
WithFieldMaskPaths []string
}
type oplogOpts struct {
@@ -30,35 +32,36 @@ type oplogOpts struct {
metadata oplog.Metadata
}
func getDefaultOptions() options {
return options{
func getDefaultOptions() Options {
return Options{
withOplog: false,
oplogOpts: oplogOpts{
wrapper: nil,
metadata: oplog.Metadata{},
},
withDebug: false,
withLookup: false,
withDebug: false,
withLookup: false,
WithFieldMaskPaths: []string{},
}
}
// WithLookup enables a lookup
func WithLookup(enable bool) Option {
return func(o *options) {
return func(o *Options) {
o.withLookup = enable
}
}
// WithDebug enables debug
func WithDebug(enable bool) Option {
return func(o *options) {
return func(o *Options) {
o.withDebug = enable
}
}
// WithOplog provides an option to write an oplog entry
func WithOplog(wrapper wrapping.Wrapper, md oplog.Metadata) Option {
return func(o *options) {
return func(o *Options) {
o.withOplog = true
o.oplogOpts = oplogOpts{
wrapper: wrapper,
@@ -66,3 +69,10 @@ func WithOplog(wrapper wrapping.Wrapper, md oplog.Metadata) Option {
}
}
}
// WithOplog provides an option to provide field mask paths
func WithFieldMaskPaths(paths []string) Option {
return func(o *Options) {
o.WithFieldMaskPaths = paths
}
}
+6 -6
View File
@@ -14,7 +14,7 @@ func Test_getOpts(t *testing.T) {
t.Parallel()
t.Run("WithOplog", func(t *testing.T) {
// test default of false
opts := getOpts()
opts := GetOpts()
testOpts := getDefaultOptions()
testOpts.withOplog = false
assert.True(reflect.DeepEqual(opts, testOpts))
@@ -26,7 +26,7 @@ func Test_getOpts(t *testing.T) {
"project": []string{"central-info-systems", "local-info-systems"},
}
// try setting to true
opts = getOpts(WithOplog(wrapper, md))
opts = GetOpts(WithOplog(wrapper, md))
testOpts = getDefaultOptions()
testOpts.withOplog = true
testOpts.oplogOpts = oplogOpts{
@@ -37,13 +37,13 @@ func Test_getOpts(t *testing.T) {
})
t.Run("WithLookup", func(t *testing.T) {
// test default of true
opts := getOpts()
opts := GetOpts()
testOpts := getDefaultOptions()
testOpts.withLookup = false
assert.True(reflect.DeepEqual(opts, testOpts))
// try setting to false
opts = getOpts(WithLookup(true))
opts = GetOpts(WithLookup(true))
testOpts = getDefaultOptions()
testOpts.withLookup = true
assert.True(reflect.DeepEqual(opts, testOpts))
@@ -51,13 +51,13 @@ func Test_getOpts(t *testing.T) {
})
t.Run("WithDebug", func(t *testing.T) {
// test default of false
opts := getOpts()
opts := GetOpts()
testOpts := getDefaultOptions()
testOpts.withDebug = false
assert.True(reflect.DeepEqual(opts, testOpts))
// try setting to true
opts = getOpts(WithDebug(true))
opts = GetOpts(WithDebug(true))
testOpts = getDefaultOptions()
testOpts.withDebug = true
assert.True(reflect.DeepEqual(opts, testOpts))
+18 -16
View File
@@ -63,6 +63,10 @@ type Writer interface {
DB() (*sql.DB, error)
}
const (
StdRetryCnt = 20
)
// RetryInfo provides information on the retries of a transaction
type RetryInfo struct {
Retries int
@@ -93,7 +97,7 @@ const (
// VetForWriter provides an interface that Create and Update can use to vet the resource before sending it to the db
type VetForWriter interface {
VetForWrite(ctx context.Context, r Reader, opType OpType) error
VetForWrite(ctx context.Context, r Reader, opType OpType, opt ...Option) error
}
// GormReadWriter uses a gorm DB connection for read/write
@@ -118,15 +122,10 @@ func (rw *GormReadWriter) ScanRows(rows *sql.Rows, result interface{}) error {
return rw.Tx.ScanRows(rows, result)
}
// CreateConstraint will create a db constraint if it doesn't already exist
func (w *GormReadWriter) CreateConstraint(tableName string, constraintName string, constraint string) error {
return w.Tx.Exec("create_constraint_if_not_exists(?, ?, ?)", tableName, constraintName, constraint).Error
}
var ErrNotResourceWithId = errors.New("not a resource with an id")
func (rw *GormReadWriter) lookupAfterWrite(ctx context.Context, i interface{}, opt ...Option) error {
opts := getOpts(opt...)
opts := GetOpts(opt...)
withLookup := opts.withLookup
if !withLookup {
@@ -146,7 +145,7 @@ func (rw *GormReadWriter) Create(ctx context.Context, i interface{}, opt ...Opti
if rw.Tx == nil {
return errors.New("create tx is nil")
}
opts := getOpts(opt...)
opts := GetOpts(opt...)
withOplog := opts.withOplog
withDebug := opts.withDebug
if withDebug {
@@ -158,7 +157,7 @@ func (rw *GormReadWriter) Create(ctx context.Context, i interface{}, opt ...Opti
}
if vetter, ok := i.(VetForWriter); ok {
if err := vetter.VetForWrite(ctx, rw, CreateOp); err != nil {
return fmt.Errorf("error on Create %w", err)
return fmt.Errorf("error on create %w", err)
}
}
if err := rw.Tx.Create(i).Error; err != nil {
@@ -181,7 +180,7 @@ func (rw *GormReadWriter) Update(ctx context.Context, i interface{}, fieldMaskPa
if rw.Tx == nil {
return errors.New("update tx is nil")
}
opts := getOpts(opt...)
opts := GetOpts(opt...)
withDebug := opts.withDebug
withOplog := opts.withOplog
if withDebug {
@@ -192,8 +191,8 @@ func (rw *GormReadWriter) Update(ctx context.Context, i interface{}, fieldMaskPa
return errors.New("update interface is nil")
}
if vetter, ok := i.(VetForWriter); ok {
if err := vetter.VetForWrite(ctx, rw, UpdateOp); err != nil {
return fmt.Errorf("error on Create %w", err)
if err := vetter.VetForWrite(ctx, rw, UpdateOp, WithFieldMaskPaths(fieldMaskPaths)); err != nil {
return fmt.Errorf("error on update %w", err)
}
}
if len(fieldMaskPaths) == 0 {
@@ -246,6 +245,9 @@ func (rw *GormReadWriter) Update(ctx context.Context, i interface{}, fieldMaskPa
return err
}
}
// we need to force a lookupAfterWrite so the resource returned is correctly initialized
// from the db
opt = append(opt, WithLookup(true))
if err := rw.lookupAfterWrite(ctx, i, opt...); err != nil {
return fmt.Errorf("lookup error after update: %w", err)
}
@@ -260,7 +262,7 @@ func (rw *GormReadWriter) Delete(ctx context.Context, i interface{}, opt ...Opti
if i == nil {
return errors.New("delete interface is nil")
}
opts := getOpts(opt...)
opts := GetOpts(opt...)
withDebug := opts.withDebug
withOplog := opts.withOplog
if withDebug {
@@ -278,7 +280,7 @@ func (rw *GormReadWriter) Delete(ctx context.Context, i interface{}, opt ...Opti
return nil
}
func (rw *GormReadWriter) addOplog(ctx context.Context, opType OpType, opts options, i interface{}) error {
func (rw *GormReadWriter) addOplog(ctx context.Context, opType OpType, opts Options, i interface{}) error {
oplogArgs := opts.oplogOpts
if oplogArgs.wrapper == nil {
return errors.New("error wrapper is nil for WithWrapper")
@@ -386,7 +388,7 @@ func (rw *GormReadWriter) LookupByName(ctx context.Context, resource ResourceNam
if rw.Tx == nil {
return errors.New("error tx nil for lookup by name")
}
opts := getOpts(opt...)
opts := GetOpts(opt...)
withDebug := opts.withDebug
if withDebug {
rw.Tx.LogMode(true)
@@ -406,7 +408,7 @@ func (rw *GormReadWriter) LookupByPublicId(ctx context.Context, resource Resourc
if rw.Tx == nil {
return errors.New("error tx nil for lookup by public id")
}
opts := getOpts(opt...)
opts := GetOpts(opt...)
withDebug := opts.withDebug
if withDebug {
rw.Tx.LogMode(true)