Rename package servers to server (#2222)

This commit is contained in:
Todd authored and GitHub committed 2022-06-20 18:20:17 -07:00
1 parent fb0e5ea1ce
commit 19b549c44a
79 files changed
+608 -604

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
package servers
import (
"context"
"reflect"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/scheduler"
)
// RegisterJobs registers the rotate roots job with the provided scheduler.
func RegisterJobs(ctx context.Context, scheduler *scheduler.Scheduler, r db.Reader, w db.Writer, kms *kms.Kms) error {
const op = "server.(Jobs).RegisterJobs"
if isNil(scheduler) {
return errors.New(ctx, errors.InvalidParameter, op, "missing scheduler")
}
if isNil(r) {
return errors.New(ctx, errors.InvalidParameter, op, "missing reader")
}
if isNil(w) {
return errors.New(ctx, errors.InvalidParameter, op, "missing writer")
}
if kms == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing kms")
}
rotateRootsJob, err := newRotateRootsJob(ctx, r, w, kms)
if err != nil {
return errors.Wrap(ctx, err, op)
}
if err = scheduler.RegisterJob(ctx, rotateRootsJob); err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
}
func isNil(i interface{}) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
return reflect.ValueOf(i).IsNil()
}
return false
}
+82
View File
@@ -0,0 +1,82 @@
package servers
import (
"context"
"time"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/scheduler"
"github.com/hashicorp/boundary/internal/server"
)
const rotateFrequency = time.Hour
// rotateRootsJob defines a periodic job that initiates root certificate rotation
// It runs every hour; the root rotation function in the library is designed to not
// do anything if it's not time to rotate (roots are within their valid ranges)
type rotateRootsJob struct {
workerAuthRepo *server.WorkerAuthRepositoryStorage
totalRotates int
}
// newRotateRootsJob instantiates the rotate roots job.
func newRotateRootsJob(ctx context.Context, r db.Reader, w db.Writer, kms *kms.Kms) (*rotateRootsJob, error) {
const op = "server.newRotateRootsJob"
switch {
case isNil(r):
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing reader")
case isNil(w):
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing writer")
case kms == nil:
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing kms")
}
workerAuthRepo, err := server.NewRepositoryStorage(ctx, r, w, kms)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return &rotateRootsJob{
workerAuthRepo: workerAuthRepo,
totalRotates: 0,
}, nil
}
// Name returns a short, unique name for the job.
func (r *rotateRootsJob) Name() string { return "rotate_roots" }
// Description returns the description for the job.
func (r *rotateRootsJob) Description() string {
return "Rotate root certificates"
}
// NextRunIn returns the next run time after a job is completed.
// This is represented by RotateFrequency
func (r *rotateRootsJob) NextRunIn(_ context.Context) (time.Duration, error) {
return rotateFrequency, nil
}
// Status returns the status of the running job.
func (r *rotateRootsJob) Status() scheduler.JobStatus {
return scheduler.JobStatus{
Completed: r.totalRotates,
Total: r.totalRotates,
}
}
// Run executes the job by calling the rotateRoots domain function
func (r *rotateRootsJob) Run(ctx context.Context) error {
const op = "server.(rotateRootsJob).Run"
err := server.RotateRoots(ctx, r.workerAuthRepo)
if err != nil {
return errors.Wrap(ctx, err, op)
}
r.totalRotates += 1
return nil
}
@@ -0,0 +1,221 @@
package servers
import (
"context"
"crypto/rand"
"testing"
"time"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/scheduler"
"github.com/hashicorp/boundary/internal/server"
"github.com/hashicorp/boundary/internal/types/scope"
"github.com/hashicorp/nodeenrollment/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRotateRootsJob(t *testing.T) {
require, assert := require.New(t), assert.New(t)
ctx := context.Background()
wrapper := db.TestWrapper(t)
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
kmsCache := kms.TestKms(t, conn, wrapper)
err := kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
require.NoError(err)
workerAuthRepo, err := server.NewRepositoryStorage(ctx, rw, rw, kmsCache)
require.NoError(err)
type args struct {
w db.Writer
r db.Reader
kms *kms.Kms
}
tests := []struct {
name string
args args
options []server.Option
wantLimit int
wantErr bool
wantErrCode errors.Code
}{
{
name: "nil writer",
args: args{
r: rw,
kms: kmsCache,
},
wantErr: true,
wantErrCode: errors.InvalidParameter,
},
{
name: "nil reader",
args: args{
w: rw,
kms: kmsCache,
},
wantErr: true,
wantErrCode: errors.InvalidParameter,
},
{
name: "nil kms",
args: args{
w: rw,
r: rw,
},
wantErr: true,
wantErrCode: errors.InvalidParameter,
},
{
name: "valid",
args: args{
w: rw,
r: rw,
kms: kmsCache,
},
wantLimit: db.DefaultLimit,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := newRotateRootsJob(ctx, tt.args.r, tt.args.w, tt.args.kms)
if tt.wantErr {
require.Error(err)
assert.Nil(got)
assert.Truef(errors.Match(errors.T(tt.wantErrCode), err), "Unexpected error %s", err)
return
}
require.NoError(err)
require.NotNil(got)
require.Equal(0, got.totalRotates)
rootIds, err := workerAuthRepo.List(ctx, (*types.RootCertificate)(nil))
require.NoError(err)
assert.Len(rootIds, 0)
assert.Equal("rotate_roots", got.Name())
assert.Equal("Rotate root certificates", got.Description())
nextRun, err := got.NextRunIn(ctx)
require.NoError(err)
assert.Equal(time.Hour, nextRun)
// Run job and ensure rotation was performed
err = got.Run(ctx)
require.NoError(err)
require.Equal(1, got.totalRotates)
rootIds, err = workerAuthRepo.List(ctx, (*types.RootCertificate)(nil))
require.NoError(err)
assert.Len(rootIds, 2)
})
}
}
func TestRotateRootsJobFailure(t *testing.T) {
require := require.New(t)
ctx := context.Background()
wrapper := db.TestWrapper(t)
conn, _ := db.TestSetup(t, "postgres")
kmsCache := kms.TestKms(t, conn, wrapper)
err := kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
require.NoError(err)
got, err := newRotateRootsJob(ctx, &db.Db{}, &db.Db{}, kmsCache)
require.NoError(err)
err = got.Run(ctx)
require.Error(err)
}
func TestRegisterRotateRootsJob(t *testing.T) {
require, assert := require.New(t), assert.New(t)
ctx := context.Background()
wrapper := db.TestWrapper(t)
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
kmsCache := kms.TestKms(t, conn, wrapper)
err := kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
require.NoError(err)
sched := scheduler.TestScheduler(t, conn, wrapper)
type args struct {
s *scheduler.Scheduler
w db.Writer
r db.Reader
kms *kms.Kms
}
tests := []struct {
name string
args args
options []server.Option
wantLimit int
wantErr bool
wantErrCode errors.Code
}{
{
name: "nil scheduler",
args: args{
w: rw,
r: rw,
kms: kmsCache,
},
wantErr: true,
wantErrCode: errors.InvalidParameter,
},
{
name: "nil writer",
args: args{
s: sched,
r: rw,
kms: kmsCache,
},
wantErr: true,
wantErrCode: errors.InvalidParameter,
},
{
name: "nil reader",
args: args{
s: sched,
w: rw,
kms: kmsCache,
},
wantErr: true,
wantErrCode: errors.InvalidParameter,
},
{
name: "nil kms",
args: args{
s: sched,
w: rw,
r: rw,
},
wantErr: true,
wantErrCode: errors.InvalidParameter,
},
{
name: "valid",
args: args{
s: sched,
w: rw,
r: rw,
kms: kmsCache,
},
wantLimit: db.DefaultLimit,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := RegisterJobs(ctx, tt.args.s, tt.args.r, tt.args.w, tt.args.kms)
if tt.wantErr {
require.Error(err)
assert.Truef(errors.Match(errors.T(tt.wantErrCode), err), "Unexpected error %s", err)
return
}
require.NoError(err)
})
}
}
+165
View File
@@ -0,0 +1,165 @@
package server
import (
"context"
"time"
"github.com/hashicorp/nodeenrollment/types"
)
// getOpts - iterate the inbound Options and return a struct
func getOpts(opt ...Option) options {
opts := getDefaultOptions()
for _, o := range opt {
o(&opts)
}
return opts
}
// Option - how Options are passed as arguments
type Option func(*options)
// options = how options are represented
type options struct {
withName string
withPublicId string
withDescription string
withAddress string
withLimit int
withLiveness time.Duration
withUpdateTags bool
withWorkerTags []*Tag
withWorkerKeyIdentifier string
withWorkerKeys WorkerKeys
withControllerEncryptionPrivateKey []byte
withKeyId string
withNonce []byte
withNewIdFunc func(context.Context) (string, error)
withFetchNodeCredentialsRequest *types.FetchNodeCredentialsRequest
withTestPkiWorkerAuthorized bool
withTestPkiWorkerKeyId *string
}
func getDefaultOptions() options {
return options{
withNewIdFunc: newWorkerId,
}
}
// WithDescription provides an optional description.
func WithDescription(desc string) Option {
return func(o *options) {
o.withDescription = desc
}
}
// WithName provides an optional name.
func WithName(name string) Option {
return func(o *options) {
o.withName = name
}
}
// WithPublicId provides an optional public Id used for skipping one db call.
func WithPublicId(id string) Option {
return func(o *options) {
o.withPublicId = id
}
}
// WithAddress provides an optional address.
func WithAddress(address string) Option {
return func(o *options) {
o.withAddress = address
}
}
// WithLimit provides an option to provide a limit. Intentionally allowing
// negative integers. If WithLimit < 0, then unlimited results are returned.
// If WithLimit == 0, then default limits are used for results.
func WithLimit(limit int) Option {
return func(o *options) {
o.withLimit = limit
}
}
// WithLiveness indicates how far back we want to search for server entries.
// Use 0 for the default liveness (15 seconds). A liveness value of -1 removes
// the liveliness condition.
func WithLiveness(liveness time.Duration) Option {
return func(o *options) {
o.withLiveness = liveness
}
}
// WithUpdateTags indicates that we should perform tag updates in the DB.
// This would happen on first sync from a worker after startup or (eventually,
// perhaps), after a SIGHUP.
func WithUpdateTags(updateTags bool) Option {
return func(o *options) {
o.withUpdateTags = updateTags
}
}
// WithWorkerTags provides worker tags.
func WithWorkerTags(tags ...*Tag) Option {
return func(o *options) {
o.withWorkerTags = tags
}
}
func WithWorkerKeyIdentifier(workerKeyIdentifier string) Option {
return func(o *options) {
o.withWorkerKeyIdentifier = workerKeyIdentifier
}
}
func WithWorkerKeys(workerKeys WorkerKeys) Option {
return func(o *options) {
o.withWorkerKeys = workerKeys
}
}
func WithControllerEncryptionPrivateKey(controllerKey []byte) Option {
return func(o *options) {
o.withControllerEncryptionPrivateKey = controllerKey
}
}
func WithKeyId(keyId string) Option {
return func(o *options) {
o.withKeyId = keyId
}
}
func WithNonce(nonce []byte) Option {
return func(o *options) {
o.withNonce = nonce
}
}
// WithNewIdFunc allows an optional factory function for new worker IDs to be
// specified (this option is likely only useful for tests).
func WithNewIdFunc(fn func(context.Context) (string, error)) Option {
return func(o *options) {
o.withNewIdFunc = fn
}
}
// WithFetchNodeCredentialsRequest allows an optional
// FetchNodeCredentialsRequest to be specified.
func WithFetchNodeCredentialsRequest(req *types.FetchNodeCredentialsRequest) Option {
return func(o *options) {
o.withFetchNodeCredentialsRequest = req
}
}
// WithTestPkiWorkerAuthorizedKeyId should only be used in tests.
// It specifies that the test worker should be authorized when returned and
// assigns the key id for that worker to the string pointer in this option.
func WithTestPkiWorkerAuthorizedKeyId(id *string) Option {
return func(o *options) {
o.withTestPkiWorkerAuthorized = true
o.withTestPkiWorkerKeyId = id
}
}
+161
View File
@@ -0,0 +1,161 @@
package server
import (
"context"
"reflect"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
// Test_GetOpts provides unit tests for GetOpts and all the options
func Test_GetOpts(t *testing.T) {
t.Parallel()
t.Run("WithName", func(t *testing.T) {
opts := getOpts(WithName("test"))
testOpts := getDefaultOptions()
testOpts.withName = "test"
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(t, opts, testOpts)
})
t.Run("WithPublicId", func(t *testing.T) {
opts := getOpts(WithPublicId("test"))
testOpts := getDefaultOptions()
testOpts.withPublicId = "test"
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(t, opts, testOpts)
})
t.Run("WithDescription", func(t *testing.T) {
opts := getOpts(WithDescription("test desc"))
testOpts := getDefaultOptions()
testOpts.withDescription = "test desc"
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(t, opts, testOpts)
})
t.Run("WithLimit", func(t *testing.T) {
opts := getOpts(WithLimit(5))
testOpts := getDefaultOptions()
testOpts.withLimit = 5
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(t, opts, testOpts)
})
t.Run("WithAddress", func(t *testing.T) {
opts := getOpts(WithAddress("test"))
testOpts := getDefaultOptions()
testOpts.withAddress = "test"
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(t, opts, testOpts)
})
t.Run("WithLiveness", func(t *testing.T) {
opts := getOpts(WithLiveness(time.Hour))
testOpts := getDefaultOptions()
testOpts.withLiveness = time.Hour
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(t, opts, testOpts)
})
t.Run("WithUpdateTags", func(t *testing.T) {
opts := getOpts(WithUpdateTags(true))
testOpts := getDefaultOptions()
testOpts.withUpdateTags = true
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(t, opts, testOpts)
})
t.Run("WithWorkerTags", func(t *testing.T) {
tags := []*Tag{
{Key: "key1", Value: "val1"},
{Key: "key2", Value: "val2"},
}
opts := getOpts(WithWorkerTags(tags...))
testOpts := getDefaultOptions()
testOpts.withWorkerTags = tags
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(t, opts, testOpts)
})
t.Run("WithWorkerKeys", func(t *testing.T) {
assert := assert.New(t)
testOpts := getDefaultOptions()
keys := WorkerKeys{
workerEncryptionPubKey: populateBytes(20),
workerSigningPubKey: populateBytes(20),
}
opts := getOpts(WithWorkerKeys(keys))
testOpts = getDefaultOptions()
testOpts.withWorkerKeys = keys
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(opts, testOpts)
})
t.Run("WithControllerEncryptionPrivateKey", func(t *testing.T) {
assert := assert.New(t)
testOpts := getDefaultOptions()
key := populateBytes(20)
opts := getOpts(WithControllerEncryptionPrivateKey(key))
testOpts = getDefaultOptions()
testOpts.withControllerEncryptionPrivateKey = key
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(opts, testOpts)
})
t.Run("WithKeyId", func(t *testing.T) {
assert := assert.New(t)
testOpts := getDefaultOptions()
opts := getOpts(WithKeyId("hi i'm another key id"))
testOpts = getDefaultOptions()
testOpts.withKeyId = "hi i'm another key id"
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(opts, testOpts)
})
t.Run("WithNonce", func(t *testing.T) {
assert := assert.New(t)
testOpts := getDefaultOptions()
nonce := populateBytes(20)
opts := getOpts(WithNonce(nonce))
testOpts = getDefaultOptions()
testOpts.withNonce = nonce
opts.withNewIdFunc = nil
testOpts.withNewIdFunc = nil
assert.Equal(opts, testOpts)
})
t.Run("WithNewIdFunc", func(t *testing.T) {
assert := assert.New(t)
testFn := func(context.Context) (string, error) { return "", nil }
opts := getOpts(WithNewIdFunc(testFn))
testOpts := getDefaultOptions()
testOpts.withNewIdFunc = testFn
assert.Equal(
runtime.FuncForPC(reflect.ValueOf(opts.withNewIdFunc).Pointer()).Name(),
runtime.FuncForPC(reflect.ValueOf(testOpts.withNewIdFunc).Pointer()).Name(),
)
})
t.Run("WithTestPkiWorkerAuthorizedKeyId", func(t *testing.T) {
assert := assert.New(t)
testOpts := getDefaultOptions()
var keyId string
opts := getOpts(WithTestPkiWorkerAuthorizedKeyId(&keyId))
testOpts = getDefaultOptions()
testOpts.withTestPkiWorkerAuthorized = true
testOpts.withTestPkiWorkerKeyId = &keyId
testOpts.withNewIdFunc = nil
opts.withNewIdFunc = nil
assert.Equal(opts, testOpts)
})
}
+33
View File
@@ -0,0 +1,33 @@
package server
import (
"context"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
)
// PublicId prefixes for the resources in the server package.
const (
WorkerPrefix = "w"
)
func newWorkerId(ctx context.Context) (string, error) {
id, err := db.NewPublicId(WorkerPrefix)
if err != nil {
return "", errors.Wrap(ctx, err, "server.newWorkerId")
}
return id, nil
}
// newWorkerIdFromScopeAndName generates a predictable public id based on the
// scope and the worker name. This should only be used on kms workers at
// upsert time.
func newWorkerIdFromScopeAndName(ctx context.Context, scope, name string) (string, error) {
const op = "server.newWorkerIdFromScopeAndName"
id, err := db.NewPublicId(WorkerPrefix, db.WithPrngValues([]string{scope, name}))
if err != nil {
return "", errors.Wrap(ctx, err, "server.newWorkerId")
}
return id, nil
}
+26
View File
@@ -0,0 +1,26 @@
package server
const (
deleteWhereCreateTimeSql = `create_time < ?`
deleteTagsByWorkerIdSql = `
delete
from server_worker_tag
where
source = ?
and
worker_id = ?`
deleteWorkerAuthQuery = `
delete from worker_auth_authorized
where worker_key_identifier = @worker_key_identifier;
`
deleteWorkerCertBundlesQuery = `
delete from worker_auth_certificate_bundle
where worker_key_identifier = @worker_key_identifier;
`
deleteRootCertificateQuery = `
delete from worker_auth_ca_certificate
where state = @state;
`
)
+69
View File
@@ -0,0 +1,69 @@
package server
import (
"reflect"
"time"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
)
const (
// DefaultLiveness is the setting that controls the server "liveness" time,
// or the maximum allowable time that a worker can't send a status update to
// the controller for. After this, the server is considered dead, and it will
// be taken out of the rotation for allowable workers for connections, and
// connections will possibly start to be terminated and marked as closed
// depending on the grace period setting (see
// base.Server.StatusGracePeriodDuration). This value serves as the default
// and minimum allowable setting for the grace period.
DefaultLiveness = 15 * time.Second
)
// Repository is the server database repository
type Repository struct {
reader db.Reader
writer db.Writer
kms *kms.Kms
// defaultLimit provides a default for limiting the number of results returned from the repo
defaultLimit int
}
// NewRepository creates a new server Repository. Supports the options: WithLimit
// which sets a default limit on results returned by repo operations.
func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repository, error) {
const op = "server.NewRepository"
if r == nil {
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "nil reader")
}
if w == nil {
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "nil writer")
}
if kms == nil {
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "nil kms")
}
opts := getOpts(opt...)
if opts.withLimit == 0 {
// zero signals the boundary defaults should be used.
opts.withLimit = db.DefaultLimit
}
return &Repository{
reader: r,
writer: w,
kms: kms,
defaultLimit: opts.withLimit,
}, nil
}
func isNil(i interface{}) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
return reflect.ValueOf(i).IsNil()
}
return false
}
+76
View File
@@ -0,0 +1,76 @@
package server
import (
"context"
"fmt"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/server/store"
)
func (r *Repository) ListControllers(ctx context.Context, opt ...Option) ([]*store.Controller, error) {
return r.listControllersWithReader(ctx, r.reader, opt...)
}
// listControllersWithReader will return a listing of resources and honor the
// WithLimit option or the repo defaultLimit. It accepts a reader, allowing it
// to be used within a transaction or without.
func (r *Repository) listControllersWithReader(ctx context.Context, reader db.Reader, opt ...Option) ([]*store.Controller, error) {
opts := getOpts(opt...)
liveness := opts.withLiveness
if liveness == 0 {
liveness = DefaultLiveness
}
var where string
if liveness > 0 {
where = fmt.Sprintf("update_time > now() - interval '%d seconds'", uint32(liveness.Seconds()))
}
var controllers []*store.Controller
if err := reader.SearchWhere(
ctx,
&controllers,
where,
[]interface{}{},
db.WithLimit(-1),
); err != nil {
return nil, errors.Wrap(ctx, err, "workers.listControllersWithReader")
}
return controllers, nil
}
func (r *Repository) UpsertController(ctx context.Context, controller *store.Controller) (int, error) {
const op = "server.UpsertController"
if controller == nil {
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "controller is nil")
}
var rowsUpdated int64
_, err := r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(read db.Reader, w db.Writer) error {
var err error
onConflict := &db.OnConflict{
Target: db.Columns{"private_id"},
Action: append(db.SetColumns([]string{"description", "address"}), db.SetColumnValues(map[string]interface{}{"update_time": "now()"})...),
}
err = w.Create(ctx, controller, db.WithOnConflict(onConflict), db.WithReturnRowsAffected(&rowsUpdated))
if err != nil {
return errors.Wrap(ctx, err, op+":Upsert")
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, err
}
return int(rowsUpdated), nil
}
+74
View File
@@ -0,0 +1,74 @@
package server
import (
"context"
"fmt"
"time"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
)
type Nonce struct {
Nonce string
Purpose string
}
// TableName returns the table name.
func (n *Nonce) TableName() string {
return "nonce"
}
const (
NoncePurposeRecovery = "recovery"
NoncePurposeWorkerAuth = "worker-auth"
)
// AddNonce adds a nonce
func (r *Repository) AddNonce(ctx context.Context, nonce, purpose string, opt ...Option) error {
const op = "server.AddNonce"
if nonce == "" {
return errors.New(ctx, errors.InvalidParameter, op, "empty nonce")
}
switch purpose {
case NoncePurposeRecovery, NoncePurposeWorkerAuth:
case "":
return errors.New(ctx, errors.InvalidParameter, op, "empty nonce purpose")
default:
return errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unknown nonce purpose %q", purpose))
}
if err := r.writer.Create(ctx, &Nonce{
Nonce: nonce,
Purpose: purpose,
}); err != nil {
return errors.Wrap(ctx, err, op+":Insertion")
}
return nil
}
// CleanupNonces removes nonces that no longer need to be stored
func (r *Repository) CleanupNonces(ctx context.Context, opt ...Option) (int, error) {
// Use the largest validity period out of the various nonces we're looking at
maxDuration := globals.RecoveryTokenValidityPeriod
if globals.WorkerAuthNonceValidityPeriod > maxDuration {
maxDuration = globals.WorkerAuthNonceValidityPeriod
}
// If something was inserted before 3x the actual validity period, clean it out
endTime := time.Now().Add(-3 * maxDuration)
rows, err := r.writer.Delete(ctx, &Nonce{}, db.WithWhere(deleteWhereCreateTimeSql, endTime))
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, "server.CleanupNonces")
}
return rows, nil
}
// ListNonces lists nonces. Used only for tests at the moment.
func (r *Repository) ListNonces(ctx context.Context, purpose string, opt ...Option) ([]*Nonce, error) {
var nonces []*Nonce
if err := r.reader.SearchWhere(ctx, &nonces, "purpose = ?", []interface{}{purpose}, db.WithLimit(-1)); err != nil {
return nil, errors.Wrap(ctx, err, "server.ListNonces")
}
return nonces, nil
}
+87
View File
@@ -0,0 +1,87 @@
package server_test
import (
"context"
"testing"
"time"
"github.com/hashicorp/boundary/api/recovery"
"github.com/hashicorp/boundary/api/roles"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/daemon/controller"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/server"
"github.com/hashicorp/boundary/internal/types/scope"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRecoveryNonces(t *testing.T) {
assert, require := assert.New(t), require.New(t)
// Set these low so that we can not have the test run forever
globals.RecoveryTokenValidityPeriod = 10 * time.Second
globals.WorkerAuthNonceValidityPeriod = 10 * time.Second
controller.NonceCleanupInterval = 20 * time.Second
wrapper := db.TestWrapper(t)
tc := controller.NewTestController(t, &controller.TestControllerOpts{
RecoveryKms: wrapper,
})
defer tc.Shutdown()
externalWrappers := tc.Kms().GetExternalWrappers(context.Background())
externalRecovery := externalWrappers.Recovery()
require.Equal(externalRecovery, wrapper)
client := tc.Client()
repo := tc.ServersRepo()
// First, validate that we can't use the same token twice. Get two tokens,
// try to use the first twice (should succeed first time, fail second), then
// ensure second token works
token1, err := recovery.GenerateRecoveryToken(tc.Context(), wrapper)
require.NoError(err)
token2, err := recovery.GenerateRecoveryToken(tc.Context(), wrapper)
require.NoError(err)
// Token 1, try 1
client.SetToken(token1)
roleClient := roles.NewClient(client)
_, err = roleClient.Create(tc.Context(), scope.Global.String())
require.NoError(err)
nonces, err := repo.ListNonces(tc.Context(), server.NoncePurposeRecovery)
require.NoError(err)
assert.Len(nonces, 1)
// Token 1, try 2
_, err = roleClient.Create(tc.Context(), scope.Global.String())
require.Error(err)
nonces, err = repo.ListNonces(tc.Context(), server.NoncePurposeRecovery)
require.NoError(err)
assert.Len(nonces, 1)
// Token 2
roleClient.ApiClient().SetToken(token2)
_, err = roleClient.Create(tc.Context(), scope.Global.String())
require.NoError(err)
nonces, err = repo.ListNonces(tc.Context(), server.NoncePurposeRecovery)
require.NoError(err)
assert.Len(nonces, 2)
// Make sure they get cleaned up
time.Sleep(2 * controller.NonceCleanupInterval)
nonces, err = repo.ListNonces(tc.Context(), server.NoncePurposeRecovery)
require.NoError(err)
assert.Len(nonces, 0)
// And finally, make sure they still can't be used
for _, token := range []string{token1, token2} {
roleClient.ApiClient().SetToken(token)
_, err = roleClient.Create(tc.Context(), scope.Global.String())
require.Error(err)
nonces, err = repo.ListNonces(tc.Context(), server.NoncePurposeRecovery)
require.NoError(err)
assert.Len(nonces, 0)
}
}
+560
View File
@@ -0,0 +1,560 @@
package server
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/boundary/internal/db"
dbcommon "github.com/hashicorp/boundary/internal/db/common"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/server/store"
"github.com/hashicorp/boundary/internal/types/scope"
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
"github.com/hashicorp/nodeenrollment"
"github.com/hashicorp/nodeenrollment/registration"
"google.golang.org/protobuf/types/known/structpb"
)
// DeleteWorker will delete a worker from the repository.
func (r *Repository) DeleteWorker(ctx context.Context, publicId string, _ ...Option) (int, error) {
const op = "server.(Repository).DeleteWorker"
if publicId == "" {
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
worker := allocWorker()
worker.Worker.PublicId = publicId
var rowsDeleted int
_, err := r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(_ db.Reader, w db.Writer) error {
deleteWorker := worker.clone()
var err error
rowsDeleted, err = w.Delete(
ctx,
deleteWorker,
)
if err != nil {
return errors.Wrap(ctx, err, op)
}
if rowsDeleted > 1 {
// return err, which will result in a rollback of the delete
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been deleted")
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", publicId)))
}
if rowsDeleted == 0 {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("delete failed for worker with workerId: %s", publicId)))
}
return rowsDeleted, nil
}
// LookupWorkerByName returns the worker with the provided name. In the event
// that no worker is found that matches then nil, nil will be returned.
func (r *Repository) LookupWorkerByName(ctx context.Context, name string) (*Worker, error) {
const op = "server.(Repository).LookupWorkerByName"
switch {
case name == "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "name is empty")
}
w, err := lookupWorkerByName(ctx, r.reader, name)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return w, nil
}
func lookupWorkerByName(ctx context.Context, reader db.Reader, name string) (*Worker, error) {
const op = "server.lookupWorkerByName"
switch {
case isNil(reader):
return nil, errors.New(ctx, errors.InvalidParameter, op, "reader is nil")
case name == "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "name is empty")
}
wAgg := &workerAggregate{}
err := reader.LookupWhere(ctx, &wAgg, "name = ?", []interface{}{name})
if err != nil {
if errors.IsNotFoundError(err) {
return nil, nil
}
return nil, errors.Wrap(ctx, err, op)
}
w, err := wAgg.toWorker(ctx)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return w, nil
}
func (r *Repository) LookupWorkerIdByKeyId(ctx context.Context, keyId string) (string, error) {
const op = "server.(Repository).LookupWorkerIdByKeyId"
switch {
case keyId == "":
return "", errors.New(ctx, errors.InvalidParameter, op, "keyId is empty")
}
// We're searching for a workerAuth record based on worker id
worker := allocWorkerAuth()
worker.WorkerKeyIdentifier = keyId
err := r.reader.LookupById(ctx, worker)
if err != nil {
if errors.IsNotFoundError(err) {
return "", nil
}
return "", errors.Wrap(ctx, err, op)
}
return worker.WorkerId, nil
}
// LookupWorker returns the worker for the provided publicId. This returns
// nil nil in the situation where no worker can be found with that public id.
func (r *Repository) LookupWorker(ctx context.Context, publicId string, _ ...Option) (*Worker, error) {
const op = "server.(Repository).LookupWorker"
switch {
case publicId == "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "publicId is empty")
}
w, err := lookupWorker(ctx, r.reader, publicId)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return w, nil
}
// lookupWorker returns the worker for the provided id. This returns
// nil nil in the situation where no worker can be found with that public id.
func lookupWorker(ctx context.Context, reader db.Reader, id string) (*Worker, error) {
const op = "server.lookupWorker"
switch {
case id == "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "id is empty")
}
wAgg := &workerAggregate{}
wAgg.PublicId = id
err := reader.LookupById(ctx, wAgg)
if err != nil {
if errors.IsNotFoundError(err) {
return nil, nil
}
return nil, errors.Wrap(ctx, err, op)
}
w, err := wAgg.toWorker(ctx)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return w, nil
}
// ListWorkers will return a listing of Workers and honor the WithLimit option.
// If WithLiveness is zero the default liveness value is used, if it is negative
// then the last status update time is ignored.
// If WithLimit < 0, then unlimited results are returned. If WithLimit == 0, then
// default limits are used for results.
func (r *Repository) ListWorkers(ctx context.Context, scopeIds []string, opt ...Option) ([]*Worker, error) {
const op = "server.(Repository).ListWorkers"
switch {
case len(scopeIds) == 0:
return nil, errors.New(ctx, errors.InvalidParameter, op, "no scope ids set")
}
opts := getOpts(opt...)
liveness := opts.withLiveness
if liveness == 0 {
liveness = DefaultLiveness
}
var where []string
var whereArgs []interface{}
if liveness > 0 {
where = append(where, fmt.Sprintf("last_status_time > now() - interval '%d seconds'", uint32(liveness.Seconds())))
}
if len(scopeIds) > 0 {
where = append(where, "scope_id in (?)")
whereArgs = append(whereArgs, scopeIds)
}
limit := r.defaultLimit
if opts.withLimit != 0 {
// non-zero signals an override of the default limit for the repo.
limit = opts.withLimit
}
var wAggs []*workerAggregate
if err := r.reader.SearchWhere(
ctx,
&wAggs,
strings.Join(where, " and "),
whereArgs,
db.WithLimit(limit),
); err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error searching for workers"))
}
workers := make([]*Worker, 0, len(wAggs))
for _, a := range wAggs {
w, err := a.toWorker(ctx)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error converting workerAggregate to Worker"))
}
workers = append(workers, w)
}
return workers, nil
}
// UpsertWorkerStatus will update the address and last status time for a worker.
// If the worker is a kms worker that hasn't been seen yet, it'll attempt to
// create a new one, but will return an error if another worker (kms or other)
// has the same name. This returns the Worker object with the changes applied.
// The WithPublicId, WithKeyId, and WithUpdateTags options are
// the only ones used. All others are ignored.
// Workers are intentionally not oplogged.
func (r *Repository) UpsertWorkerStatus(ctx context.Context, worker *Worker, opt ...Option) (*Worker, error) {
const op = "server.UpsertWorkerStatus"
opts := getOpts(opt...)
switch {
case worker == nil:
return nil, errors.New(ctx, errors.InvalidParameter, op, "worker is nil")
case worker.GetAddress() == "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "worker reported address is empty")
case worker.ScopeId == "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "scope id is empty")
case worker.PublicId != "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "worker id is not empty")
case worker.GetName() == "" && opts.withKeyId == "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "worker keyId and reported name are both empty; one is required")
case worker.GetName() != "" && opts.withKeyId != "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "worker keyId and reported name are both set; no more than one is allowed")
}
var workerId string
var err error
switch {
case opts.withPublicId != "":
workerId = opts.withPublicId
case opts.withKeyId != "":
workerId, err = r.LookupWorkerIdByKeyId(ctx, opts.withKeyId)
if err != nil || workerId == "" {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error finding worker by keyId"))
}
default:
// generating the worker id based off of the scope and name ensures
// that if 2 kms workers are making requests with the same name they
// are treated as the same worker. Allowing this only for kms workers
// also ensures that we maintain the unique name constraint between pki
// workers and kms workers.
workerId, err = newWorkerIdFromScopeAndName(ctx, worker.GetScopeId(), worker.GetName())
if err != nil || workerId == "" {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error creating a worker id"))
}
}
var ret *Worker
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
workerClone := worker.clone()
workerClone.PublicId = workerId
switch {
case opts.withKeyId != "":
// This case goes first in case we want to relax the restriction
// around both name and key ID being supplied to account for
// e.g. config processing bugs. In that case, a key ID being
// supplied should be a clear indicator that we are working with
// a PKI workerClone, and a lack of one a clear indication we are
// working with a KMS workerClone.
//
// Note: unlike in the below case, this purposefully leaves out
// "description" since we want description changes for PKI-based
// workers to come via API only. We can't really guard on this
// in the DB so we need to be sure to not include it here.
n, err := w.Update(ctx, workerClone, []string{"address"}, nil)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to update status of pki worker"))
}
switch n {
case 0:
return errors.New(ctx, errors.RecordNotFound, op, fmt.Sprintf("failed to find worker with key id %q", opts.withKeyId))
case 1:
break
default:
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("multiple records found when updating worker with id %q", workerClone.GetPublicId()))
}
case workerClone.GetName() != "":
workerClone.Type = KmsWorkerType.String()
workerCreateConflict := &db.OnConflict{
Target: db.Columns{"public_id"},
Action: append(db.SetColumns([]string{"address"}),
db.SetColumnValues(map[string]interface{}{"last_status_time": "now()"})...),
}
var withRowsAffected int64
err := w.Create(ctx, workerClone, db.WithOnConflict(workerCreateConflict), db.WithReturnRowsAffected(&withRowsAffected),
// The intent of this WithWhere option is to operate with the OnConflict such that the action
// taken by the OnConflict only applies if the conflict is on a row that is returned by this where
// statement, otherwise it should error out.
db.WithWhere("server_worker.type = 'kms'"))
if err == nil && workerClone.Description != worker.Description {
_, err = w.Update(ctx, workerClone, []string{"description"}, nil)
}
switch {
case err != nil:
return errors.Wrap(ctx, err, op, errors.WithMsg("error creating a worker"))
case withRowsAffected == 0:
return errors.New(ctx, errors.NotUnique, op, "error updating worker")
}
}
// If we've been told to update tags, we need to clean out old
// ones and add new ones. Within the current transaction, simply
// delete all tags for the given worker, then add the new ones
// we've been sent.
if opts.withUpdateTags {
if err := setWorkerTags(ctx, w, workerClone.GetPublicId(), ConfigurationTagSource, workerClone.inputTags); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("error setting worker tags"))
}
}
wAgg := &workerAggregate{PublicId: workerClone.GetPublicId()}
if err := reader.LookupById(ctx, wAgg); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("error looking up worker aggregate"))
}
ret, err = wAgg.toWorker(ctx)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("error converting worker aggregate to worker"))
}
return nil
},
)
if err != nil {
return nil, err
}
return ret, nil
}
// setWorkerTags removes all existing tags from the same source and worker id
// and creates new ones based on the ones provided. This function should be
// called from inside a db transaction.
// Workers/worker tags are intentionally not oplogged.
func setWorkerTags(ctx context.Context, w db.Writer, id string, ts TagSource, tags []*Tag) error {
const op = "server.setWorkerTags"
switch {
case !ts.isValid():
return errors.New(ctx, errors.InvalidParameter, op, "invalid tag source provided")
case id == "":
return errors.New(ctx, errors.InvalidParameter, op, "worker id is empty")
case isNil(w):
return errors.New(ctx, errors.InvalidParameter, op, "db.Writer is nil")
}
_, err := w.Exec(ctx, deleteTagsByWorkerIdSql, []interface{}{ts.String(), id})
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("couldn't delete exist tags for worker %q", id)))
}
// If tags were cleared out entirely, then we'll have nothing
// to do here, e.g., it will result in deletion of all tags.
// Otherwise, go through and stage each tuple for insertion
// below.
if len(tags) > 0 {
uTags := make([]interface{}, 0, len(tags))
for _, v := range tags {
if v == nil {
return errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("found nil tag value for worker %s", id))
}
uTags = append(uTags, &store.WorkerTag{
WorkerId: id,
Key: v.Key,
Value: v.Value,
Source: ts.String(),
})
}
if err = w.CreateItems(ctx, uTags); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("error creating tags for worker %q", id)))
}
}
return nil
}
// UpdateWorker will update a worker in the repository and return the resulting
// worker. 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, Description, and Address are the only updatable
// fields, if no updatable fields are included in the fieldMaskPaths, then an
// error is returned. If any paths besides those listed above are included in
// the path then an error is returned.
func (r *Repository) UpdateWorker(ctx context.Context, worker *Worker, version uint32, fieldMaskPaths []string, opt ...Option) (*Worker, int, error) {
const (
nameField = "name"
descField = "description"
)
const op = "server.(Repository).UpdateWorker"
switch {
case worker == nil:
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "worker is nil")
case worker.PublicId == "":
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing public id")
case version == 0:
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "version is zero")
}
for _, f := range fieldMaskPaths {
switch {
case strings.EqualFold(nameField, f):
case strings.EqualFold(descField, f):
default:
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidFieldMask, op, fmt.Sprintf("invalid field mask: %s", f))
}
}
var dbMask, nullFields []string
dbMask, nullFields = dbcommon.BuildUpdatePaths(
map[string]interface{}{
nameField: worker.Name,
descField: worker.Description,
},
fieldMaskPaths,
nil,
)
if len(dbMask) == 0 && len(nullFields) == 0 {
return nil, db.NoRowsAffected, errors.New(ctx, errors.EmptyFieldMask, op, "no fields to update")
}
var rowsUpdated int
var ret *Worker
var err error
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
worker := worker.clone()
rowsUpdated, err = w.Update(ctx, worker, dbMask, nullFields, db.WithVersion(&version),
db.WithWhere("server_worker.type = 'pki'"))
if err != nil {
return errors.Wrap(ctx, err, op)
}
if worker.Type == KmsWorkerType.String() {
return errors.New(ctx, errors.InvalidParameter, op, "cannot update a KMS worker")
}
if rowsUpdated > 1 {
// return err, which will result in a rollback of the update
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
wAgg := &workerAggregate{PublicId: worker.GetPublicId()}
if err := reader.LookupById(ctx, wAgg); err != nil {
return errors.Wrap(ctx, err, op)
}
if ret, err = wAgg.toWorker(ctx); err != nil {
return err
}
return nil
},
)
if err != nil {
if errors.IsUniqueError(err) {
return nil, db.NoRowsAffected, errors.New(ctx, errors.NotUnique, op, fmt.Sprintf("worker with name %q already exists", worker.Name))
}
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("for %s", worker.GetPublicId())))
}
return ret, rowsUpdated, nil
}
// CreateWorker will create a worker in the repository and return the written
// worker. Creating a worker is not intentionally oplogged. A worker's
// ReportedStatus and Tags are intentionally ignored when creating a worker (not
// included). Currently, a worker can only be created in the global scope
//
// Options supported: WithFetchNodeCredentialsRequest and WithNewIdFunc (this
// option is likely only useful for tests)
func (r *Repository) CreateWorker(ctx context.Context, worker *Worker, opt ...Option) (*Worker, error) {
const op = "server.CreateWorker"
switch {
case worker == nil:
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing worker")
case worker.PublicId != "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "public id is not empty")
case worker.ScopeId == "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing scope id")
case worker.ScopeId != scope.Global.String():
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("scope id must be %q", scope.Global.String()))
case worker.Address != "":
return nil, errors.New(ctx, errors.InvalidParameter, op, "address is not empty")
case worker.LastStatusTime != nil:
return nil, errors.New(ctx, errors.InvalidParameter, op, "last status time is not nil")
}
opts := getOpts(opt...)
var err error
if worker.PublicId, err = opts.withNewIdFunc(ctx); err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to generate worker id"))
}
state, err := structpb.NewStruct(map[string]any{
"worker_id": worker.PublicId,
})
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error generating state struct", err))
}
var databaseWrapper wrapping.Wrapper
var workerAuthRepo *WorkerAuthRepositoryStorage
if opts.withFetchNodeCredentialsRequest != nil {
// used to encrypt the privKey within the NodeInformation
databaseWrapper, err = r.kms.GetWrapper(ctx, scope.Global.String(), kms.KeyPurposeDatabase)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
}
var returnedWorker *Worker
if _, err := r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(read db.Reader, w db.Writer) error {
returnedWorker = worker.clone()
returnedWorker.Type = PkiWorkerType.String()
if err := w.Create(
ctx,
returnedWorker,
); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to create worker"))
}
if opts.withFetchNodeCredentialsRequest != nil {
workerAuthRepo, err = NewRepositoryStorage(ctx, read, w, r.kms)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to create worker auth repository"))
}
nodeInfo, err := registration.AuthorizeNode(ctx, workerAuthRepo, opts.withFetchNodeCredentialsRequest, nodeenrollment.WithSkipStorage(true))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to authorize node"))
}
nodeInfo.State = state
if err := StoreNodeInformationTx(ctx, w, databaseWrapper, nodeInfo); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to store node information"))
}
}
return nil
},
); err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return returnedWorker, nil
}
File diff suppressed because it is too large. Load diff
+781
View File
@@ -0,0 +1,781 @@
package server
import (
"context"
"crypto/x509"
"database/sql"
"fmt"
"strconv"
"github.com/fatih/structs"
"google.golang.org/protobuf/types/known/structpb"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/db/timestamp"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/server/store"
"github.com/hashicorp/boundary/internal/types/scope"
"github.com/hashicorp/go-dbw"
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
"github.com/hashicorp/nodeenrollment"
nodee "github.com/hashicorp/nodeenrollment"
"github.com/hashicorp/nodeenrollment/types"
"github.com/mitchellh/mapstructure"
"google.golang.org/protobuf/proto"
)
// Ensure we implement the Storage interfaces
var (
_ nodee.Storage = (*WorkerAuthRepositoryStorage)(nil)
)
type rootCertificatesVersion struct {
Version uint32 `mapstructure:"version"`
}
// WorkerAuthRepositoryStorage is the Worker Auth database repository
type WorkerAuthRepositoryStorage struct {
reader db.Reader
writer db.Writer
kms *kms.Kms
}
// NewRepositoryStorage creates a new WorkerAuthRepositoryStorage that implements the Storage interface
func NewRepositoryStorage(ctx context.Context, r db.Reader, w db.Writer, kms *kms.Kms) (*WorkerAuthRepositoryStorage, error) {
const op = "server.(WorkerAuthRepositoryStorage).NewRepositoryStorage"
switch {
case isNil(r):
return nil, errors.New(ctx, errors.InvalidParameter, op, "reader is nil")
case isNil(w):
return nil, errors.New(ctx, errors.InvalidParameter, op, "writer is nil")
case isNil(kms):
return nil, errors.New(ctx, errors.InvalidParameter, op, "kms is nil")
}
workerAuthRepoStorage := &WorkerAuthRepositoryStorage{
reader: r,
writer: w,
kms: kms,
}
return workerAuthRepoStorage, nil
}
// Store implements the Storage interface
func (r *WorkerAuthRepositoryStorage) Store(ctx context.Context, msg nodee.MessageWithId) error {
const op = "server.(WorkerAuthRepositoryStorage).Store"
if err := types.ValidateMessage(msg); err != nil {
return errors.Wrap(ctx, err, op)
}
if msg.GetId() == "" {
return errors.New(ctx, errors.InvalidParameter, op, "given message cannot be stored as it has no ID")
}
// Determine type of message to store
switch t := msg.(type) {
case *types.NodeInformation:
// Encrypt the private key
databaseWrapper, err := r.kms.GetWrapper(ctx, scope.Global.String(), kms.KeyPurposeDatabase)
if err != nil {
return errors.Wrap(ctx, err, op)
}
if _, err := r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{}, func(read db.Reader, w db.Writer) error {
return StoreNodeInformationTx(ctx, w, databaseWrapper, t)
}); err != nil {
return errors.Wrap(ctx, err, op)
}
case *types.RootCertificates:
err := r.storeRootCertificates(ctx, t)
if err != nil {
return errors.Wrap(ctx, err, op)
}
default:
return errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("message type %T not supported for Store", msg))
}
return nil
}
// StoreNodeInformationTx stores NodeInformation. No options are currently
// supported.
//
// This function encapsulates all the work required within a dbw.TxHandler and
// allows this capability to be shared with other repositories or just called
// within a transaction. To be clear, this repository function doesn't include
// its own transaction and is intended to be used within a transaction provided
// by the caller.
//
// Node information is stored in two parts:
// * the workerAuth record is stored with a reference to a worker
// * certificate bundles are stored with a reference to the workerAuth record and issuing root certificate
func StoreNodeInformationTx(ctx context.Context, writer db.Writer, databaseWrapper wrapping.Wrapper, node *types.NodeInformation, _ ...Option) error {
const op = "server.(WorkerAuthRepositoryStorage).storeNodeInformation"
if isNil(writer) {
return errors.New(ctx, errors.InvalidParameter, op, "missing writer")
}
if isNil(databaseWrapper) {
return errors.New(ctx, errors.InvalidParameter, op, "missing database wrapper")
}
if node == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing NodeInformation")
}
nodeAuth := allocWorkerAuth()
nodeAuth.WorkerKeyIdentifier = node.Id
nodeAuth.WorkerEncryptionPubKey = node.EncryptionPublicKeyBytes
nodeAuth.WorkerSigningPubKey = node.CertificatePublicKeyPkix
nodeAuth.Nonce = node.RegistrationNonce
var err error
nodeAuth.KeyId, err = databaseWrapper.KeyId(ctx)
if err != nil {
return errors.Wrap(ctx, err, op)
}
nodeAuth.ControllerEncryptionPrivKey, err = encrypt(ctx, node.ServerEncryptionPrivateKeyBytes, databaseWrapper)
if err != nil {
return errors.Wrap(ctx, err, op)
}
// Get workerId from state passed in
var result workerAuthWorkerId
err = mapstructure.Decode(node.State.AsMap(), &result)
if err != nil {
return errors.Wrap(ctx, err, op)
}
nodeAuth.WorkerId = result.WorkerId
if err := nodeAuth.ValidateNewWorkerAuth(ctx); err != nil {
return errors.Wrap(ctx, err, op)
}
// Store WorkerAuth
if err := writer.Create(ctx, &nodeAuth); err != nil {
return errors.Wrap(ctx, err, op)
}
// Then store cert bundles associated with this WorkerAuth
for _, c := range node.CertificateBundles {
if err := storeWorkerCertBundle(ctx, c, nodeAuth.WorkerKeyIdentifier, writer); err != nil {
return errors.Wrap(ctx, err, op)
}
}
return nil
}
func storeWorkerCertBundle(
ctx context.Context,
bundle *types.CertificateBundle,
workerKeyIdentifier string,
writer db.Writer,
) error {
const op = "server.(WorkerAuthRepositoryStorage).storeWorkerCertBundle"
if bundle == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing CertificateBundle")
}
if workerKeyIdentifier == "" {
return errors.New(ctx, errors.InvalidParameter, op, "empty workerKeyIdentifier")
}
if writer == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing writer")
}
workerCertBundle := allocWorkerCertBundle()
bundleBytes, err := proto.Marshal(bundle)
if err != nil {
return errors.New(ctx, errors.Encode, op, "error marshaling nodetypes.CertificateBundle", errors.WithWrap(err))
}
// Extract serial number from CA cert
caCert := bundle.CaCertificateDer
parsedCert, err := x509.ParseCertificate(caCert)
if err != nil {
return errors.Wrap(ctx, err, op)
}
workerCertBundle.RootCertificatePublicKey = parsedCert.AuthorityKeyId
workerCertBundle.CertBundle = bundleBytes
workerCertBundle.WorkerKeyIdentifier = workerKeyIdentifier
err = workerCertBundle.ValidateNewWorkerCertBundle(ctx)
if err != nil {
return errors.Wrap(ctx, err, op)
}
err = writer.Create(ctx, &workerCertBundle)
if err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
}
func (r *WorkerAuthRepositoryStorage) convertRootCertificate(ctx context.Context, cert *types.RootCertificate) (*RootCertificate, error) {
const op = "server.(WorkerAuthRepositoryStorage).convertRootCertificate"
if cert == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing RootCertificate")
}
rootCert := allocRootCertificate()
parsedCert, err := x509.ParseCertificate(cert.CertificateDer)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
rootCert.SerialNumber = parsedCert.SerialNumber.Uint64()
rootCert.Certificate = cert.CertificateDer
rootCert.NotValidAfter = timestamp.New(cert.NotAfter.AsTime())
rootCert.NotValidBefore = timestamp.New(cert.NotBefore.AsTime())
rootCert.PublicKey = cert.PublicKeyPkix
rootCert.State = cert.Id
rootCert.IssuingCa = ca_id
// Encrypt the private key
databaseWrapper, err := r.kms.GetWrapper(ctx, scope.Global.String(), kms.KeyPurposeDatabase)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
rootCert.KeyId, err = databaseWrapper.KeyId(ctx)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
rootCert.PrivateKey, err = encrypt(ctx, cert.PrivateKeyPkcs8, databaseWrapper)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
err = rootCert.ValidateNewRootCertificate(ctx)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return rootCert, nil
}
func (r *WorkerAuthRepositoryStorage) storeRootCertificates(ctx context.Context, cert *types.RootCertificates) error {
const op = "server.(WorkerAuthRepositoryStorage).storeRootCertificates"
if cert == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing RootCertificate")
}
nextCert, err := r.convertRootCertificate(ctx, cert.Next)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to convert next root certificate"))
}
currentCert, err := r.convertRootCertificate(ctx, cert.Current)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to convert current root certificate"))
}
// Use passed version
var result rootCertificatesVersion
err = mapstructure.Decode(cert.State.AsMap(), &result)
if err != nil {
return errors.Wrap(ctx, err, op)
}
version := uint32(1)
if result.Version != 0 {
version = result.Version
}
certAuthority := &CertificateAuthority{
CertificateAuthority: &store.CertificateAuthority{
PrivateId: ca_id,
Version: version + 1,
},
}
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(read db.Reader, w db.Writer) error {
// Delete the old certs
if err = r.removeRootCertificateWithWriter(ctx, string(CurrentState), w); err != nil {
return errors.Wrap(ctx, err, op)
}
if err = r.removeRootCertificateWithWriter(ctx, string(NextState), w); err != nil {
return errors.Wrap(ctx, err, op)
}
// Update the certAuthority's version column
rowsUpdated, err := w.Update(ctx, certAuthority, []string{"Version"}, nil, db.WithVersion(&version))
if err != nil {
return errors.Wrap(ctx, err, op)
}
if rowsUpdated != 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated CertificateAuthority and %d rows updated", rowsUpdated))
}
// Then insert the new certs
if nextCert != nil {
if err = w.Create(ctx, &nextCert); err != nil {
return errors.Wrap(ctx, err, op)
}
}
if currentCert != nil {
if err = w.Create(ctx, &currentCert); err != nil {
return errors.Wrap(ctx, err, op)
}
}
return nil
},
)
if err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
}
// Load implements the Storage interface.
// Load loads values into the given message. The message must be populated
// with the ID value. If not found, the returned error should be ErrNotFound.
func (r *WorkerAuthRepositoryStorage) Load(ctx context.Context, msg nodee.MessageWithId) error {
const op = "server.(WorkerAuthRepositoryStorage).Load"
if err := types.ValidateMessage(msg); err != nil {
return errors.Wrap(ctx, err, op)
}
if msg.GetId() == "" {
return errors.New(ctx, errors.InvalidParameter, op, "given message cannot be loaded as it has no ID")
}
var err error
switch t := msg.(type) {
case *types.NodeInformation:
err = r.loadNodeInformation(ctx, t)
case *types.RootCertificates:
err = r.loadRootCertificates(ctx, t)
default:
return errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("message type %T not supported for Load", t))
}
if err != nil {
if err == nodeenrollment.ErrNotFound {
// Don't wrap as this will confuse things
return err
}
return errors.Wrap(ctx, err, op)
}
return nil
}
// Node information is loaded in two parts:
// * the workerAuth record
// * its certificate bundles
func (r *WorkerAuthRepositoryStorage) loadNodeInformation(ctx context.Context, node *types.NodeInformation) error {
const op = "server.(WorkerAuthRepositoryStorage).loadNodeInformation"
if node == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing NodeInformation")
}
authorizedWorker, err := r.findWorkerAuth(ctx, node)
if err != nil {
return errors.Wrap(ctx, err, op)
}
if authorizedWorker == nil {
return nodee.ErrNotFound
}
node.EncryptionPublicKeyBytes = authorizedWorker.WorkerEncryptionPubKey
node.CertificatePublicKeyPkix = authorizedWorker.WorkerSigningPubKey
node.RegistrationNonce = authorizedWorker.Nonce
// Default values are used for key types
node.EncryptionPublicKeyType = types.KEYTYPE_X25519
node.CertificatePublicKeyType = types.KEYTYPE_ED25519
node.ServerEncryptionPrivateKeyType = types.KEYTYPE_X25519
// Decrypt private key
databaseWrapper, err := r.kms.GetWrapper(ctx, scope.Global.String(), kms.KeyPurposeDatabase, kms.WithKeyId(authorizedWorker.KeyId))
if err != nil {
return errors.Wrap(ctx, err, op)
}
node.ServerEncryptionPrivateKeyBytes, err = decrypt(ctx, authorizedWorker.ControllerEncryptionPrivKey, databaseWrapper)
if err != nil {
return errors.Wrap(ctx, err, op)
}
workerIdInfo := workerAuthWorkerId{WorkerId: authorizedWorker.GetWorkerId()}
s := structs.New(workerIdInfo)
s.TagName = "mapstructure"
state, err := structpb.NewStruct(s.Map())
if err != nil {
return errors.Wrap(ctx, err, op)
}
node.State = state
// Get cert bundles from the other table
certBundles, err := r.findCertBundles(ctx, node.Id)
if err != nil {
return errors.Wrap(ctx, err, op)
}
node.CertificateBundles = certBundles
return nil
}
func (r *WorkerAuthRepositoryStorage) findCertBundles(ctx context.Context, workerKeyId string) ([]*types.CertificateBundle, error) {
const op = "server.(WorkerAuthRepositoryStorage).findCertBundles"
if workerKeyId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "empty workerKeyId")
}
var bundles []*WorkerCertBundle
err := r.reader.SearchWhere(ctx, &bundles, "worker_key_identifier = ?", []interface{}{workerKeyId}, db.WithLimit(-1))
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
certBundle := []*types.CertificateBundle{}
for _, bundle := range bundles {
thisBundle := &types.CertificateBundle{}
if err := proto.Unmarshal(bundle.WorkerCertBundle.CertBundle, thisBundle); err != nil {
return nil, errors.New(ctx, errors.Decode, op, "error unmarshaling message", errors.WithWrap(err))
}
certBundle = append(certBundle, thisBundle)
}
return certBundle, nil
}
func (r *WorkerAuthRepositoryStorage) findWorkerAuth(ctx context.Context, node *types.NodeInformation) (*WorkerAuth, error) {
const op = "server.(WorkerAuthRepositoryStorage).findWorkerAuth"
if node == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "node is nil")
}
worker := allocWorkerAuth()
worker.WorkerKeyIdentifier = node.Id
err := r.reader.LookupById(ctx, worker)
if err != nil {
if errors.Is(err, dbw.ErrRecordNotFound) {
return nil, nil
}
return nil, errors.Wrap(ctx, err, op)
}
return worker, nil
}
func (r *WorkerAuthRepositoryStorage) loadRootCertificates(ctx context.Context, cert *types.RootCertificates) error {
const op = "server.(WorkerAuthRepositoryStorage).loadRootCertificates"
if cert == nil {
return errors.New(ctx, errors.InvalidParameter, op, "cert is nil")
}
// See if we have the CertificateAuthority first
certAuthority := &CertificateAuthority{
CertificateAuthority: &store.CertificateAuthority{
PrivateId: cert.Id,
},
}
err := r.reader.LookupById(ctx, certAuthority)
if err != nil {
return nodee.ErrNotFound
}
// Add version to state field of cert
versionMap := &rootCertificatesVersion{Version: certAuthority.Version}
stateOpt := structs.Map(versionMap)
state, err := structpb.NewStruct(stateOpt)
if err != nil {
return errors.Wrap(ctx, err, op)
}
cert.State = state
// Load current and next certificates
certsToFind := []string{string(NextState), string(CurrentState)}
for _, c := range certsToFind {
rootCertificate := allocRootCertificate()
rootCert := &types.RootCertificate{}
if err := r.reader.SearchWhere(ctx, &rootCertificate, "state = ?", []interface{}{c}, db.WithLimit(-1)); err != nil {
return errors.Wrap(ctx, err, op)
}
if rootCertificate.Certificate == nil {
return nodee.ErrNotFound
}
rootCert.CertificateDer = rootCertificate.Certificate
rootCert.NotAfter = rootCertificate.NotValidAfter.Timestamp
rootCert.NotBefore = rootCertificate.NotValidBefore.Timestamp
rootCert.PublicKeyPkix = rootCertificate.PublicKey
rootCert.PrivateKeyType = types.KEYTYPE_ED25519
// decrypt private key
databaseWrapper, err := r.kms.GetWrapper(ctx, scope.Global.String(), kms.KeyPurposeDatabase, kms.WithKeyId(rootCertificate.KeyId))
if err != nil {
return errors.Wrap(ctx, err, op)
}
rootCert.PrivateKeyPkcs8, err = decrypt(ctx, rootCertificate.PrivateKey, databaseWrapper)
if err != nil {
return errors.Wrap(ctx, err, op)
}
if c == string(NextState) {
cert.Next = rootCert
}
if c == string(CurrentState) {
cert.Current = rootCert
}
}
return nil
}
// Remove implements the Storage interface.
// Remove removes the given message. Only the ID field of the message is considered.
func (r *WorkerAuthRepositoryStorage) Remove(ctx context.Context, msg nodee.MessageWithId) error {
const op = "server.(WorkerAuthRepositoryStorage).Remove"
if err := types.ValidateMessage(msg); err != nil {
return errors.New(ctx, errors.InvalidParameter, op, "given message cannot be removed as it has no ID")
}
// Determine type of message to remove
switch msg.(type) {
case *types.NodeInformation:
err := r.removeNodeInformation(ctx, msg.GetId())
if err != nil {
return errors.Wrap(ctx, err, op)
}
case *types.RootCertificates:
err := r.removeCertificateAuthority(ctx, msg.(*types.RootCertificates))
if err != nil {
return errors.Wrap(ctx, err, op)
}
default:
return errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("message type %T not supported for Remove", msg))
}
return nil
}
func (r *WorkerAuthRepositoryStorage) removeNodeInformation(ctx context.Context, id string) error {
const op = "server.(WorkerAuthRepositoryStorage).removeNodeInformation"
if id == "" {
return errors.New(ctx, errors.InvalidParameter, op, "empty id")
}
_, err := r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
var err error
_, err = w.Exec(ctx, deleteWorkerAuthQuery, []interface{}{sql.Named("worker_key_identifier", id)})
if err != nil {
return errors.Wrap(ctx, err, op)
}
_, err = w.Exec(ctx, deleteWorkerCertBundlesQuery, []interface{}{sql.Named("worker_key_identifier", id)})
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to delete workerAuth"))
}
return nil
},
)
if err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
}
func (r *WorkerAuthRepositoryStorage) removeCertificateAuthority(ctx context.Context, cert *types.RootCertificates) error {
const op = "server.(WorkerAuthRepositoryStorage).removeCertificateAuthority"
var result rootCertificatesVersion
err := mapstructure.Decode(cert.State.AsMap(), &result)
if err != nil {
return errors.Wrap(ctx, err, op)
}
version := uint32(1)
if result.Version != 0 {
version = result.Version
}
certAuthority := &CertificateAuthority{
CertificateAuthority: &store.CertificateAuthority{
PrivateId: ca_id,
Version: version + 1,
},
}
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(read db.Reader, w db.Writer) error {
// Update the certAuthority's version column first
rowsUpdated, err := w.Update(ctx, certAuthority, []string{"Version"}, nil, db.WithVersion(&version))
if err != nil {
return errors.Wrap(ctx, err, op)
}
if rowsUpdated != 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated CertificateAuthority and %d rows updated", rowsUpdated))
}
if err := r.removeRootCertificateWithWriter(ctx, string(CurrentState), w); err != nil {
return errors.Wrap(ctx, err, op)
}
if err := r.removeRootCertificateWithWriter(ctx, string(NextState), w); err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
},
)
if err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
}
func (r *WorkerAuthRepositoryStorage) removeRootCertificateWithWriter(ctx context.Context, id string, writer db.Writer) error {
const op = "server.(WorkerAuthRepositoryStorage).removeRootCertificateWithWriter"
if id == "" {
return errors.New(ctx, errors.InvalidParameter, op, "empty id")
}
if writer == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing writer")
}
rows, err := writer.Exec(ctx, deleteRootCertificateQuery, []interface{}{
sql.Named("state", id),
})
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to delete root certificate"))
}
if rows > 1 {
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 root certificate would have been deleted")
}
return nil
}
// List implements the Storage interface.
// List returns a list of IDs; the type of the message is used to disambiguate what to list.
func (r *WorkerAuthRepositoryStorage) List(ctx context.Context, msg proto.Message) ([]string, error) {
const op = "server.(WorkerAuthRepositoryStorage).List"
var err error
var ids []string
// Determine type of message to store
switch msg.(type) {
case *types.NodeInformation:
ids, err = r.listNodeInformation(ctx)
case *types.RootCertificate:
ids, err = r.listRootCertificates(ctx)
case *types.RootCertificates:
ids, err = r.listCertificateAuthority(ctx)
default:
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("message type %T not supported for List", msg))
}
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return ids, nil
}
// Returns a list of node auth IDs
func (r *WorkerAuthRepositoryStorage) listNodeInformation(ctx context.Context) ([]string, error) {
const op = "server.(WorkerAuthRepositoryStorage).listNodeCertificates"
var where string
var nodeAuths []*WorkerAuth
err := r.reader.SearchWhere(ctx, &nodeAuths, where, []interface{}{}, db.WithLimit(-1))
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
var nodeIds []string
for _, auth := range nodeAuths {
nodeIds = append(nodeIds, auth.WorkerKeyIdentifier)
}
return nodeIds, nil
}
// Returns a list of root certificates
func (r *WorkerAuthRepositoryStorage) listRootCertificates(ctx context.Context) ([]string, error) {
const op = "server.(WorkerAuthRepositoryStorage).listRootCertificates"
var where string
var rootCertificates []*RootCertificate
err := r.reader.SearchWhere(ctx, &rootCertificates, where, []interface{}{}, db.WithLimit(-1))
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
var certIds []string
for _, cert := range rootCertificates {
certIds = append(certIds, strconv.FormatUint(cert.SerialNumber, 10))
}
return certIds, nil
}
// Returns a list of certificate authorities
func (r *WorkerAuthRepositoryStorage) listCertificateAuthority(ctx context.Context) ([]string, error) {
const op = "server.(WorkerAuthRepositoryStorage).listCertificateAuthority"
var where string
var rootCertificates []*CertificateAuthority
err := r.reader.SearchWhere(ctx, &rootCertificates, where, []interface{}{}, db.WithLimit(-1))
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
var certIds []string
for _, cert := range rootCertificates {
certIds = append(certIds, cert.PrivateId)
}
return certIds, nil
}
// encrypt value before writing it to the db
func encrypt(ctx context.Context, value []byte, wrapper wrapping.Wrapper) ([]byte, error) {
const op = "server.(WorkerAuthRepositoryStorage).encrypt"
if value == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing value")
}
if wrapper == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing wrapper")
}
blobInfo, err := wrapper.Encrypt(ctx, value)
if err != nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "error encrypting recovery info", errors.WithWrap(err))
}
marshaledBlob, err := proto.Marshal(blobInfo)
if err != nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "error marshaling encrypted blob", errors.WithWrap(err))
}
return marshaledBlob, nil
}
func decrypt(ctx context.Context, value []byte, wrapper wrapping.Wrapper) ([]byte, error) {
const op = "server.(WorkerAuthRepositoryStorage).decrypt"
if value == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing value")
}
if wrapper == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing wrapper")
}
blobInfo := new(wrapping.BlobInfo)
if err := proto.Unmarshal(value, blobInfo); err != nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "error decoding encrypted blob", errors.WithWrap(err))
}
marshaledInfo, err := wrapper.Decrypt(ctx, blobInfo)
if err != nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "error decrypting recovery info", errors.WithWrap(err))
}
return marshaledInfo, nil
}
@@ -0,0 +1,424 @@
package server
import (
"context"
"crypto/rand"
"testing"
"github.com/fatih/structs"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/types/scope"
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
"github.com/hashicorp/nodeenrollment"
"github.com/hashicorp/nodeenrollment/registration"
"github.com/hashicorp/nodeenrollment/rotation"
"github.com/hashicorp/nodeenrollment/storage/file"
"github.com/hashicorp/nodeenrollment/types"
"github.com/mitchellh/mapstructure"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/curve25519"
"google.golang.org/protobuf/types/known/structpb"
)
// Test RootCertificate storage
func TestStoreRootCertificates(t *testing.T) {
require, assert := require.New(t), assert.New(t)
ctx := context.Background()
wrapper := db.TestWrapper(t)
conn, _ := db.TestSetup(t, "postgres")
kmsCache := kms.TestKms(t, conn, wrapper)
// Ensures the global scope contains a valid root key
err := kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
require.NoError(err)
wrapper, err = kmsCache.GetWrapper(context.Background(), scope.Global.String(), kms.KeyPurposeDatabase)
require.NoError(err)
require.NotNil(wrapper)
rw := db.New(conn)
workerAuthRepo, err := NewRepositoryStorage(ctx, rw, rw, kmsCache)
require.NoError(err)
// Fail to find root certificates prior to rotation/ creation
noCertAuth := &types.RootCertificates{Id: ca_id}
err = workerAuthRepo.Load(ctx, noCertAuth)
require.Error(err)
rootIds, err := workerAuthRepo.List(ctx, (*types.RootCertificate)(nil))
require.NoError(err)
assert.Len(rootIds, 0)
// Rotate will generate and store next and current, as we have none
roots, err := rotation.RotateRootCertificates(ctx, workerAuthRepo)
require.NoError(err)
rootIds, err = workerAuthRepo.List(ctx, (*types.RootCertificate)(nil))
require.NoError(err)
assert.Len(rootIds, 2)
// Load stored roots
certAuthority := &types.RootCertificates{Id: ca_id}
err = workerAuthRepo.Load(ctx, certAuthority)
require.NoError(err)
require.NotNil(certAuthority.GetNext())
require.NotNil(certAuthority.GetCurrent())
// Read the next cert and validate the stored values are valid after encrypt and decrypt
assert.Equal(roots.Next.PrivateKeyPkcs8, certAuthority.Next.PrivateKeyPkcs8)
// Read the current cert and validate the stored values are valid after encrypt and decrypt
assert.Equal(roots.Current.PrivateKeyPkcs8, certAuthority.Current.PrivateKeyPkcs8)
// Fail to find root certificates under bogus id
bogusCertAuth := &types.RootCertificates{Id: "bogus"}
err = workerAuthRepo.Load(ctx, bogusCertAuth)
require.Error(err)
}
func TestStoreCertAuthorityVersioning(t *testing.T) {
require, assert := require.New(t), assert.New(t)
ctx := context.Background()
wrapper := db.TestWrapper(t)
conn, _ := db.TestSetup(t, "postgres")
kmsCache := kms.TestKms(t, conn, wrapper)
// Ensures the global scope contains a valid root key
err := kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
require.NoError(err)
wrapper, err = kmsCache.GetWrapper(context.Background(), scope.Global.String(), kms.KeyPurposeDatabase)
require.NoError(err)
require.NotNil(wrapper)
rw := db.New(conn)
workerAuthRepo, err := NewRepositoryStorage(ctx, rw, rw, kmsCache)
require.NoError(err)
// Store CA and check that initial version updates
roots, err := rotation.RotateRootCertificates(ctx, workerAuthRepo)
require.NoError(err)
cAuth2 := &types.RootCertificates{Id: ca_id}
err = workerAuthRepo.Load(ctx, cAuth2)
require.NoError(err)
var result2 rootCertificatesVersion
err = mapstructure.Decode(cAuth2.State.AsMap(), &result2)
require.NoError(err)
assert.Equal(uint32(2), result2.Version)
// Store CA with old version, expect error
badVersion := &rootCertificatesVersion{Version: uint32(1)}
s := structs.New(badVersion)
s.TagName = "mapstructure"
badState, err := structpb.NewStruct(s.Map())
require.NoError(err)
newRoots2 := &types.RootCertificates{
Id: ca_id,
Next: roots.Next,
Current: roots.Current,
}
newRoots2.State = badState
err = workerAuthRepo.Store(ctx, newRoots2)
require.Error(err)
// Remove CA, expect updated version
cAuthRemove := &types.RootCertificates{Id: ca_id}
removeVersion := &rootCertificatesVersion{Version: uint32(2)}
s = structs.New(removeVersion)
s.TagName = "mapstructure"
removeState, err := structpb.NewStruct(s.Map())
require.NoError(err)
cAuthRemove.State = removeState
err = workerAuthRepo.Remove(ctx, cAuthRemove)
require.NoError(err)
}
// Test WorkerAuth storage
func TestStoreWorkerAuth(t *testing.T) {
require, assert := require.New(t), assert.New(t)
ctx := context.Background()
wrapper := db.TestWrapper(t)
conn, _ := db.TestSetup(t, "postgres")
kmsCache := kms.TestKms(t, conn, wrapper)
// Ensures the global scope contains a valid root key
err := kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
require.NoError(err)
wrapper, err = kmsCache.GetWrapper(context.Background(), scope.Global.String(), kms.KeyPurposeDatabase)
require.NoError(err)
require.NotNil(wrapper)
worker := TestPkiWorker(t, conn, wrapper)
rw := db.New(conn)
rootStorage, err := NewRepositoryStorage(ctx, rw, rw, kmsCache)
require.NoError(err)
_, err = rotation.RotateRootCertificates(ctx, rootStorage)
require.NoError(err)
// Create struct to pass in with workerId that will be passed along to storage
state, err := AttachWorkerIdToState(ctx, worker.PublicId)
require.NoError(err)
// This happens on the worker
fileStorage, err := file.New(ctx)
require.NoError(err)
nodeCreds, err := types.NewNodeCredentials(ctx, fileStorage)
require.NoError(err)
// Create request using worker id
fetchReq, err := nodeCreds.CreateFetchNodeCredentialsRequest(ctx)
require.NoError(err)
keyId, err := nodeenrollment.KeyIdFromPkix(nodeCreds.CertificatePublicKeyPkix)
require.NoError(err)
nodePubKey, err := curve25519.X25519(nodeCreds.EncryptionPrivateKeyBytes, curve25519.Basepoint)
require.NoError(err)
// Add in node information to storage so we have a key to use
nodeInfo := &types.NodeInformation{
Id: keyId,
CertificatePublicKeyPkix: nodeCreds.CertificatePublicKeyPkix,
CertificatePublicKeyType: nodeCreds.CertificatePrivateKeyType,
EncryptionPublicKeyBytes: nodePubKey,
EncryptionPublicKeyType: nodeCreds.EncryptionPrivateKeyType,
RegistrationNonce: nodeCreds.RegistrationNonce,
State: state,
}
// Create storage for authentication and pass it the worker
storage, err := NewRepositoryStorage(ctx, rw, rw, kmsCache)
require.NoError(err)
// The AuthorizeNode request will result in a WorkerAuth record being stored
_, err = registration.AuthorizeNode(ctx, storage, fetchReq, nodeenrollment.WithState(state))
require.NoError(err)
// We should now look for a node information value in storage and validate that it's populated
nodeInfos, err := storage.List(ctx, (*types.NodeInformation)(nil))
require.NoError(err)
require.NotEmpty(nodeInfos)
assert.Len(nodeInfos, 1)
// Validate the stored fields match those from the worker
nodeLookup := &types.NodeInformation{
Id: keyId,
}
err = storage.Load(ctx, nodeLookup)
require.NoError(err)
assert.NotEmpty(nodeLookup)
assert.Equal(nodeInfo.EncryptionPublicKeyBytes, nodeLookup.EncryptionPublicKeyBytes)
assert.Equal(nodeInfo.RegistrationNonce, nodeLookup.RegistrationNonce)
assert.Equal(nodeInfo.CertificatePublicKeyPkix, nodeLookup.CertificatePublicKeyPkix)
assert.Equal(nodeInfo.State.AsMap(), nodeLookup.State.AsMap())
// Remove node
err = storage.Remove(ctx, nodeLookup)
require.NoError(err)
err = storage.Load(ctx, nodeLookup)
require.Error(err)
}
func TestUnsupportedMessages(t *testing.T) {
require := require.New(t)
ctx := context.Background()
wrapper := db.TestWrapper(t)
conn, _ := db.TestSetup(t, "postgres")
kmsCache := kms.TestKms(t, conn, wrapper)
rw := db.New(conn)
storage, err := NewRepositoryStorage(ctx, rw, rw, kmsCache)
require.NoError(err)
err = storage.Store(ctx, &types.NodeCredentials{})
require.Error(err)
err = storage.Load(ctx, &types.NodeCredentials{Id: "bogus"})
require.Error(err)
_, err = storage.List(ctx, (*types.NodeCredentials)(nil))
require.Error(err)
err = storage.Remove(ctx, &types.NodeCredentials{Id: "bogus"})
require.Error(err)
}
func TestStoreNodeInformationTx(t *testing.T) {
t.Parallel()
testCtx := context.Background()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
testWrapper := db.TestWrapper(t)
testKeyId, err := testWrapper.KeyId(testCtx)
require.NoError(t, err)
kmsCache := kms.TestKms(t, conn, testWrapper)
// Ensures the global scope contains a valid root key
err = kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
require.NoError(t, err)
databaseWrapper, err := kmsCache.GetWrapper(context.Background(), scope.Global.String(), kms.KeyPurposeDatabase)
require.NoError(t, err)
testRootStorage, err := NewRepositoryStorage(testCtx, rw, rw, kmsCache)
require.NoError(t, err)
_, err = rotation.RotateRootCertificates(testCtx, testRootStorage)
require.NoError(t, err)
// Create struct to pass in with workerId that will be passed along to
// storage
testWorker := TestPkiWorker(t, conn, testWrapper)
testState, err := AttachWorkerIdToState(testCtx, testWorker.PublicId)
require.NoError(t, err)
testNodeInfoFn := func() *types.NodeInformation {
// This happens on the worker
fileStorage, err := file.New(testCtx)
require.NoError(t, err)
nodeCreds, err := types.NewNodeCredentials(testCtx, fileStorage)
require.NoError(t, err)
nodePubKey, err := curve25519.X25519(nodeCreds.EncryptionPrivateKeyBytes, curve25519.Basepoint)
require.NoError(t, err)
// Add in node information to storage so we have a key to use
nodeInfo := &types.NodeInformation{
Id: testKeyId,
CertificatePublicKeyPkix: nodeCreds.CertificatePublicKeyPkix,
CertificatePublicKeyType: nodeCreds.CertificatePrivateKeyType,
EncryptionPublicKeyBytes: nodePubKey,
EncryptionPublicKeyType: nodeCreds.EncryptionPrivateKeyType,
ServerEncryptionPrivateKeyBytes: []byte("whatever"),
RegistrationNonce: nodeCreds.RegistrationNonce,
State: testState,
}
return nodeInfo
}
tests := []struct {
name string
writer db.Writer
databaseWrapper wrapping.Wrapper
node *types.NodeInformation
wantErr bool
wantErrIs errors.Code
wantErrContains string
}{
{
name: "missing-writer",
databaseWrapper: databaseWrapper,
node: testNodeInfoFn(),
wantErr: true,
wantErrIs: errors.InvalidParameter,
wantErrContains: "missing writer",
},
{
name: "missing-wrapper",
writer: rw,
node: testNodeInfoFn(),
wantErr: true,
wantErrIs: errors.InvalidParameter,
wantErrContains: "missing database wrapper",
},
{
name: "missing-node",
writer: rw,
databaseWrapper: databaseWrapper,
wantErr: true,
wantErrIs: errors.InvalidParameter,
wantErrContains: "missing NodeInformation",
},
{
name: "key-id-error",
writer: rw,
databaseWrapper: &mockTestWrapper{err: errors.New(testCtx, errors.Internal, "testing", "key-id-error")},
node: testNodeInfoFn(),
wantErr: true,
wantErrIs: errors.Internal,
wantErrContains: "key-id-error",
},
{
name: "encrypt-error",
writer: rw,
databaseWrapper: &mockTestWrapper{
encryptError: true,
err: errors.New(testCtx, errors.Encrypt, "testing", "encrypt-error"),
},
node: testNodeInfoFn(),
wantErr: true,
wantErrIs: errors.Encrypt,
wantErrContains: "encrypt-error",
},
{
name: "create-error-no-db",
writer: &db.Db{},
databaseWrapper: databaseWrapper,
node: testNodeInfoFn(),
wantErr: true,
wantErrContains: "db.Create",
},
{
name: "create-error-validation",
writer: rw,
databaseWrapper: databaseWrapper,
node: func() *types.NodeInformation {
ni := testNodeInfoFn()
ni.State = nil
return ni
}(),
wantErr: true,
wantErrContains: "missing WorkerId",
},
{
name: "success",
writer: rw,
databaseWrapper: databaseWrapper,
node: testNodeInfoFn(),
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
err := StoreNodeInformationTx(testCtx, tc.writer, tc.databaseWrapper, tc.node)
if tc.wantErr {
require.Error(err)
if tc.wantErrIs != errors.Unknown {
assert.True(errors.Match(errors.T(tc.wantErrIs), err))
}
if tc.wantErrContains != "" {
assert.Contains(err.Error(), tc.wantErrContains)
}
return
}
require.NoError(err)
})
}
}
type mockTestWrapper struct {
wrapping.Wrapper
decryptError bool
encryptError bool
err error
keyId string
}
func (m *mockTestWrapper) KeyId(context.Context) (string, error) {
if m.err != nil {
return "", m.err
}
return m.keyId, nil
}
func (m *mockTestWrapper) Encrypt(ctx context.Context, plaintext []byte, options ...wrapping.Option) (*wrapping.BlobInfo, error) {
if m.err != nil && m.encryptError {
return nil, m.err
}
panic("todo")
}
func (m *mockTestWrapper) Decrypt(ctx context.Context, ciphertext *wrapping.BlobInfo, options ...wrapping.Option) ([]byte, error) {
if m.err != nil && m.decryptError {
return nil, m.err
}
return []byte("decrypted"), nil
}
+160
View File
@@ -0,0 +1,160 @@
package server
import (
"context"
"fmt"
"github.com/hashicorp/boundary/internal/errors"
timestamp "github.com/hashicorp/boundary/internal/db/timestamp"
"github.com/hashicorp/boundary/internal/server/store"
"google.golang.org/protobuf/proto"
)
// The CertificateAuthority id will always be set to "roots".
// The const ca_id contains this value
const ca_id = "roots"
// CertificateAuthority is a versioned entity used to lock the database when rotation RootCertificates
type CertificateAuthority struct {
*store.CertificateAuthority
tableName string `gorm:"-"`
}
func newCertificateAuthority() *CertificateAuthority {
ca := &CertificateAuthority{
CertificateAuthority: &store.CertificateAuthority{
PrivateId: ca_id,
},
}
return ca
}
// TableName returns the table name.
func (r *CertificateAuthority) TableName() string {
if r.tableName != "" {
return r.tableName
}
return "worker_auth_ca"
}
// SetTableName sets the table name.
func (r *CertificateAuthority) SetTableName(n string) {
r.tableName = n
}
// RootCertificate contains fields related to a RootCertificate resource
// This includes public/ private keys, the PEM encoded certificate, and the certificate validity period
type RootCertificate struct {
*store.RootCertificate
tableName string `gorm:"-"`
}
// RootCertificateKeys contains the public and private keys for use in constructing a RootCertificate
type RootCertificateKeys struct {
publicKey []byte
privateKey []byte
}
func newRootCertificate(ctx context.Context, serialNumber uint64, certificate []byte, notValidBefore, notValidAfter *timestamp.Timestamp,
rootCertificateKeys RootCertificateKeys, keyId string, state CertificateState,
) (*RootCertificate, error) {
const op = "server.newRootCertificate"
if &serialNumber == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no serialNumber")
}
if certificate == nil || len(certificate) == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "empty certificate")
}
if notValidAfter == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no notValidAfter")
}
if notValidBefore == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no notValidBefore")
}
if rootCertificateKeys.publicKey == nil || len(rootCertificateKeys.publicKey) == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "empty publicKey")
}
if rootCertificateKeys.privateKey == nil || len(rootCertificateKeys.privateKey) == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "empty privateKey")
}
if keyId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no keyId")
}
if !validState(state) {
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("%s is not a valid certificate state", state))
}
l := &RootCertificate{
RootCertificate: &store.RootCertificate{
SerialNumber: serialNumber,
Certificate: certificate,
NotValidAfter: notValidAfter,
NotValidBefore: notValidBefore,
PublicKey: rootCertificateKeys.publicKey,
PrivateKey: rootCertificateKeys.privateKey,
KeyId: keyId,
State: string(state),
IssuingCa: ca_id,
},
}
return l, nil
}
func allocRootCertificate() *RootCertificate {
return &RootCertificate{
RootCertificate: &store.RootCertificate{},
}
}
func (r *RootCertificate) clone() *RootCertificate {
cp := proto.Clone(r.RootCertificate)
return &RootCertificate{
RootCertificate: cp.(*store.RootCertificate),
}
}
// Validate the RootCertificate. On success, return nil
func (r *RootCertificate) ValidateNewRootCertificate(ctx context.Context) error {
const op = "server.(RootCertificate).ValidateNewRootCertificate"
if &r.SerialNumber == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing SerialNumber")
}
if r.Certificate == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing Certificate")
}
if r.NotValidBefore.GetTimestamp().AsTime().IsZero() {
return errors.New(ctx, errors.InvalidParameter, op, "missing not valid before timestamp")
}
if r.NotValidAfter.GetTimestamp().AsTime().IsZero() {
return errors.New(ctx, errors.InvalidParameter, op, "missing not valid after timestamp")
}
if r.PublicKey == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing public key")
}
if r.PrivateKey == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing private key")
}
if r.KeyId == "" {
return errors.New(ctx, errors.InvalidParameter, op, "missing key id")
}
if r.State == "" {
return errors.New(ctx, errors.InvalidParameter, op, "missing state")
}
return nil
}
// TableName returns the table name.
func (r *RootCertificate) TableName() string {
if r.tableName != "" {
return r.tableName
}
return "worker_auth_ca_certificate"
}
// SetTableName sets the table name.
func (r *RootCertificate) SetTableName(n string) {
r.tableName = n
}
+277
View File
@@ -0,0 +1,277 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc (unknown)
// source: controller/servers/v1/servers.proto
package server
import (
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)
)
// TagPair matches a key to a value.
type TagPair struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty" class:"public"` // @gotags: `class:"public"`
Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty" class:"public"` // @gotags: `class:"public"`
}
func (x *TagPair) Reset() {
*x = TagPair{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_servers_v1_servers_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *TagPair) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*TagPair) ProtoMessage() {}
func (x *TagPair) ProtoReflect() protoreflect.Message {
mi := &file_controller_servers_v1_servers_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 TagPair.ProtoReflect.Descriptor instead.
func (*TagPair) Descriptor() ([]byte, []int) {
return file_controller_servers_v1_servers_proto_rawDescGZIP(), []int{0}
}
func (x *TagPair) GetKey() string {
if x != nil {
return x.Key
}
return ""
}
func (x *TagPair) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
// ServerWorkerStatus is the new message used in place of Server to relay status request info.
type ServerWorkerStatus struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Id of the worker.
PublicId string `protobuf:"bytes,10,opt,name=public_id,json=publicId,proto3" json:"public_id,omitempty" class:"public"` // @gotags: `class:"public"`
// Name of the resource (optional)
Name string `protobuf:"bytes,20,opt,name=name,proto3" json:"name,omitempty" class:"public"` // @gotags: `class:"public"`
// Description of the resource (optional)
Description string `protobuf:"bytes,25,opt,name=description,proto3" json:"description,omitempty" class:"public"` // @gotags: `class:"public"`
// Address for the worker. This must be set.
Address string `protobuf:"bytes,30,opt,name=address,proto3" json:"address,omitempty" class:"public"` // @gotags: `class:"public"`
// Tags for workers
Tags []*TagPair `protobuf:"bytes,40,rep,name=tags,proto3" json:"tags,omitempty"`
// The key id for this worker, if applicable (optional)
KeyId string `protobuf:"bytes,50,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty" class:"public"` // @gotags: `class:"public"`
}
func (x *ServerWorkerStatus) Reset() {
*x = ServerWorkerStatus{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_servers_v1_servers_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ServerWorkerStatus) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerWorkerStatus) ProtoMessage() {}
func (x *ServerWorkerStatus) ProtoReflect() protoreflect.Message {
mi := &file_controller_servers_v1_servers_proto_msgTypes[1]
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 ServerWorkerStatus.ProtoReflect.Descriptor instead.
func (*ServerWorkerStatus) Descriptor() ([]byte, []int) {
return file_controller_servers_v1_servers_proto_rawDescGZIP(), []int{1}
}
func (x *ServerWorkerStatus) GetPublicId() string {
if x != nil {
return x.PublicId
}
return ""
}
func (x *ServerWorkerStatus) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *ServerWorkerStatus) GetDescription() string {
if x != nil {
return x.Description
}
return ""
}
func (x *ServerWorkerStatus) GetAddress() string {
if x != nil {
return x.Address
}
return ""
}
func (x *ServerWorkerStatus) GetTags() []*TagPair {
if x != nil {
return x.Tags
}
return nil
}
func (x *ServerWorkerStatus) GetKeyId() string {
if x != nil {
return x.KeyId
}
return ""
}
var File_controller_servers_v1_servers_proto protoreflect.FileDescriptor
var file_controller_servers_v1_servers_proto_rawDesc = []byte{
0x0a, 0x23, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x65, 0x72,
0x76, 0x65, 0x72, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65,
0x72, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x2e, 0x76, 0x31, 0x22, 0x31, 0x0a, 0x07,
0x54, 0x61, 0x67, 0x50, 0x61, 0x69, 0x72, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01,
0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c,
0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22,
0xcc, 0x01, 0x0a, 0x12, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x57, 0x6f, 0x72, 0x6b, 0x65, 0x72,
0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63,
0x5f, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x75, 0x62, 0x6c, 0x69,
0x63, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x14, 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, 0x19, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65,
0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64,
0x72, 0x65, 0x73, 0x73, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72,
0x65, 0x73, 0x73, 0x12, 0x32, 0x0a, 0x04, 0x74, 0x61, 0x67, 0x73, 0x18, 0x28, 0x20, 0x03, 0x28,
0x0b, 0x32, 0x1e, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73,
0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x61, 0x67, 0x50, 0x61, 0x69,
0x72, 0x52, 0x04, 0x74, 0x61, 0x67, 0x73, 0x12, 0x15, 0x0a, 0x06, 0x6b, 0x65, 0x79, 0x5f, 0x69,
0x64, 0x18, 0x32, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6b, 0x65, 0x79, 0x49, 0x64, 0x42, 0x36,
0x5a, 0x34, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73,
0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f,
0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x3b,
0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_controller_servers_v1_servers_proto_rawDescOnce sync.Once
file_controller_servers_v1_servers_proto_rawDescData = file_controller_servers_v1_servers_proto_rawDesc
)
func file_controller_servers_v1_servers_proto_rawDescGZIP() []byte {
file_controller_servers_v1_servers_proto_rawDescOnce.Do(func() {
file_controller_servers_v1_servers_proto_rawDescData = protoimpl.X.CompressGZIP(file_controller_servers_v1_servers_proto_rawDescData)
})
return file_controller_servers_v1_servers_proto_rawDescData
}
var file_controller_servers_v1_servers_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_controller_servers_v1_servers_proto_goTypes = []interface{}{
(*TagPair)(nil), // 0: controller.servers.v1.TagPair
(*ServerWorkerStatus)(nil), // 1: controller.servers.v1.ServerWorkerStatus
}
var file_controller_servers_v1_servers_proto_depIdxs = []int32{
0, // 0: controller.servers.v1.ServerWorkerStatus.tags:type_name -> controller.servers.v1.TagPair
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_controller_servers_v1_servers_proto_init() }
func file_controller_servers_v1_servers_proto_init() {
if File_controller_servers_v1_servers_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_controller_servers_v1_servers_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*TagPair); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_controller_servers_v1_servers_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ServerWorkerStatus); 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_servers_v1_servers_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_controller_servers_v1_servers_proto_goTypes,
DependencyIndexes: file_controller_servers_v1_servers_proto_depIdxs,
MessageInfos: file_controller_servers_v1_servers_proto_msgTypes,
}.Build()
File_controller_servers_v1_servers_proto = out.File
file_controller_servers_v1_servers_proto_rawDesc = nil
file_controller_servers_v1_servers_proto_goTypes = nil
file_controller_servers_v1_servers_proto_depIdxs = nil
}
+27
View File
@@ -0,0 +1,27 @@
package server
import (
"context"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/nodeenrollment"
"github.com/hashicorp/nodeenrollment/rotation"
)
// RotateRoots is a domain service function that initiates a rotation of root certificates
// via a call to the nodenenrollment RotateRootCertificates function
// Accepts the nodeenrollment option, WithCertificateLifetime(time.Duration) to specify the lifetime
// of the generated cert(s)
func RotateRoots(ctx context.Context, workerAuthRepo *WorkerAuthRepositoryStorage, opt ...nodeenrollment.Option) error {
const op = "server.RotateRoots"
if workerAuthRepo == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing workerAuthRepo")
}
_, err := rotation.RotateRootCertificates(ctx, workerAuthRepo, opt...)
if err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -0,0 +1,88 @@
package server
import (
"context"
"crypto/rand"
"testing"
"time"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/types/scope"
"github.com/hashicorp/nodeenrollment"
"github.com/hashicorp/nodeenrollment/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRotateRoots(t *testing.T) {
require, assert := require.New(t), assert.New(t)
ctx := context.Background()
wrapper := db.TestWrapper(t)
conn, _ := db.TestSetup(t, "postgres")
kmsCache := kms.TestKms(t, conn, wrapper)
err := kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
require.NoError(err)
rw := db.New(conn)
workerAuthRepo, err := NewRepositoryStorage(ctx, rw, rw, kmsCache)
require.NoError(err)
// Check that we have no roots first
rootIds, err := workerAuthRepo.List(ctx, (*types.RootCertificate)(nil))
require.NoError(err)
assert.Len(rootIds, 0)
// Generate roots
err = RotateRoots(ctx, workerAuthRepo, nodeenrollment.WithCertificateLifetime(time.Second*5))
require.NoError(err)
// Check that we have roots now
rootIds, err = workerAuthRepo.List(ctx, (*types.RootCertificate)(nil))
require.NoError(err)
assert.Len(rootIds, 2)
certAuthority := &types.RootCertificates{Id: ca_id}
err = workerAuthRepo.Load(ctx, certAuthority)
require.NoError(err)
require.NotNil(certAuthority.GetNext())
require.NotNil(certAuthority.GetCurrent())
initialNext := certAuthority.GetNext()
initialCurrent := certAuthority.GetCurrent()
// Rotate roots and assert that they've rotated
err = RotateRoots(ctx, workerAuthRepo, nodeenrollment.WithCertificateLifetime(time.Second*5))
require.NoError(err)
certAuthority2 := &types.RootCertificates{Id: ca_id}
err = workerAuthRepo.Load(ctx, certAuthority2)
require.NoError(err)
require.NotNil(certAuthority2.GetNext())
require.NotNil(certAuthority2.GetCurrent())
rotatedNext := certAuthority2.GetNext()
rotatedCurrent := certAuthority2.GetCurrent()
// Next and current should have changed
assert.NotEqual(initialNext, rotatedNext)
assert.NotEqual(initialCurrent, rotatedCurrent)
// And the old next root should now be current
assert.Equal(initialNext, rotatedCurrent)
}
func TestRotateRootsFailure(t *testing.T) {
require := require.New(t)
ctx := context.Background()
wrapper := db.TestWrapper(t)
conn, _ := db.TestSetup(t, "postgres")
kmsCache := kms.TestKms(t, conn, wrapper)
err := kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
require.NoError(err)
workerAuthRepo, err := NewRepositoryStorage(ctx, &db.Db{}, &db.Db{}, kmsCache)
require.NoError(err)
err = RotateRoots(ctx, workerAuthRepo)
require.Error(err)
}
+20
View File
@@ -0,0 +1,20 @@
package server
// CertificateState defines the possible states for a workerauth certificate
type CertificateState string
const (
UnknownState CertificateState = "unknown"
CurrentState CertificateState = "current"
NextState CertificateState = "next"
)
func validState(s CertificateState) bool {
st := CertificateState(s)
switch st {
case CurrentState, NextState:
return true
default:
return false
}
}
+209
View File
@@ -0,0 +1,209 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc (unknown)
// source: controller/storage/servers/store/v1/controller.proto
package store
import (
timestamp "github.com/hashicorp/boundary/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)
)
// Controller contains all fields related to a Controller resource
type Controller struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Private ID of the resource
PrivateId string `protobuf:"bytes,10,opt,name=private_id,json=privateId,proto3" json:"private_id,omitempty"`
// Address for the controller
Address string `protobuf:"bytes,20,opt,name=address,proto3" json:"address,omitempty"`
// Description of the resource (optional)
// @inject_tag: `gorm:"default:null"`
Description string `protobuf:"bytes,30,opt,name=description,proto3" json:"description,omitempty" gorm:"default:null"`
// First seen time from the RDBMS
CreateTime *timestamp.Timestamp `protobuf:"bytes,40,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"`
// Last time there was an update
UpdateTime *timestamp.Timestamp `protobuf:"bytes,50,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty"`
}
func (x *Controller) Reset() {
*x = Controller{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_storage_servers_store_v1_controller_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Controller) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Controller) ProtoMessage() {}
func (x *Controller) ProtoReflect() protoreflect.Message {
mi := &file_controller_storage_servers_store_v1_controller_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 Controller.ProtoReflect.Descriptor instead.
func (*Controller) Descriptor() ([]byte, []int) {
return file_controller_storage_servers_store_v1_controller_proto_rawDescGZIP(), []int{0}
}
func (x *Controller) GetPrivateId() string {
if x != nil {
return x.PrivateId
}
return ""
}
func (x *Controller) GetAddress() string {
if x != nil {
return x.Address
}
return ""
}
func (x *Controller) GetDescription() string {
if x != nil {
return x.Description
}
return ""
}
func (x *Controller) GetCreateTime() *timestamp.Timestamp {
if x != nil {
return x.CreateTime
}
return nil
}
func (x *Controller) GetUpdateTime() *timestamp.Timestamp {
if x != nil {
return x.UpdateTime
}
return nil
}
var File_controller_storage_servers_store_v1_controller_proto protoreflect.FileDescriptor
var file_controller_storage_servers_store_v1_controller_proto_rawDesc = []byte{
0x0a, 0x34, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f,
0x72, 0x61, 0x67, 0x65, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x2f, 0x73, 0x74, 0x6f,
0x72, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x23, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c,
0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x65,
0x72, 0x73, 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, 0x22, 0x81, 0x02, 0x0a,
0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x12, 0x1d, 0x0a, 0x0a, 0x70,
0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52,
0x09, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64,
0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x14, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64,
0x72, 0x65, 0x73, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74,
0x69, 0x6f, 0x6e, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72,
0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x4b, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65,
0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x28, 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, 0x32, 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,
0x42, 0x3b, 0x5a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68,
0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x61, 0x72,
0x79, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65,
0x72, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x3b, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_controller_storage_servers_store_v1_controller_proto_rawDescOnce sync.Once
file_controller_storage_servers_store_v1_controller_proto_rawDescData = file_controller_storage_servers_store_v1_controller_proto_rawDesc
)
func file_controller_storage_servers_store_v1_controller_proto_rawDescGZIP() []byte {
file_controller_storage_servers_store_v1_controller_proto_rawDescOnce.Do(func() {
file_controller_storage_servers_store_v1_controller_proto_rawDescData = protoimpl.X.CompressGZIP(file_controller_storage_servers_store_v1_controller_proto_rawDescData)
})
return file_controller_storage_servers_store_v1_controller_proto_rawDescData
}
var file_controller_storage_servers_store_v1_controller_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_controller_storage_servers_store_v1_controller_proto_goTypes = []interface{}{
(*Controller)(nil), // 0: controller.storage.servers.store.v1.Controller
(*timestamp.Timestamp)(nil), // 1: controller.storage.timestamp.v1.Timestamp
}
var file_controller_storage_servers_store_v1_controller_proto_depIdxs = []int32{
1, // 0: controller.storage.servers.store.v1.Controller.create_time:type_name -> controller.storage.timestamp.v1.Timestamp
1, // 1: controller.storage.servers.store.v1.Controller.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_servers_store_v1_controller_proto_init() }
func file_controller_storage_servers_store_v1_controller_proto_init() {
if File_controller_storage_servers_store_v1_controller_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_controller_storage_servers_store_v1_controller_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Controller); 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_servers_store_v1_controller_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_controller_storage_servers_store_v1_controller_proto_goTypes,
DependencyIndexes: file_controller_storage_servers_store_v1_controller_proto_depIdxs,
MessageInfos: file_controller_storage_servers_store_v1_controller_proto_msgTypes,
}.Build()
File_controller_storage_servers_store_v1_controller_proto = out.File
file_controller_storage_servers_store_v1_controller_proto_rawDesc = nil
file_controller_storage_servers_store_v1_controller_proto_goTypes = nil
file_controller_storage_servers_store_v1_controller_proto_depIdxs = nil
}
+11
View File
@@ -0,0 +1,11 @@
package store
// TableName overrides the table name used by Controller to `server_controller`
func (Controller) TableName() string {
return "server_controller"
}
// TableName overrides the table name used by WorkerTag to `worker_tag`
func (WorkerTag) TableName() string {
return "server_worker_tag"
}
@@ -0,0 +1,340 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc (unknown)
// source: controller/storage/servers/store/v1/root_certificate.proto
// Package store provides protobufs for storing types in the pki package.
package store
import (
timestamp "github.com/hashicorp/boundary/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)
)
// CertificateAuthority is a versioned entity used to lock the database when rotation RootCertificates
type CertificateAuthority struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// @inject_tag: `gorm:"primary_key"`
PrivateId string `protobuf:"bytes,10,opt,name=private_id,json=privateId,proto3" json:"private_id,omitempty" gorm:"primary_key"`
// version allows optimistic locking of the resource.
// @inject_tag: `gorm:"default:null"`
Version uint32 `protobuf:"varint,20,opt,name=version,proto3" json:"version,omitempty" gorm:"default:null"`
}
func (x *CertificateAuthority) Reset() {
*x = CertificateAuthority{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_storage_servers_store_v1_root_certificate_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *CertificateAuthority) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CertificateAuthority) ProtoMessage() {}
func (x *CertificateAuthority) ProtoReflect() protoreflect.Message {
mi := &file_controller_storage_servers_store_v1_root_certificate_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 CertificateAuthority.ProtoReflect.Descriptor instead.
func (*CertificateAuthority) Descriptor() ([]byte, []int) {
return file_controller_storage_servers_store_v1_root_certificate_proto_rawDescGZIP(), []int{0}
}
func (x *CertificateAuthority) GetPrivateId() string {
if x != nil {
return x.PrivateId
}
return ""
}
func (x *CertificateAuthority) GetVersion() uint32 {
if x != nil {
return x.Version
}
return 0
}
// RootCertificate contains all fields related to a RootCertificate resource
type RootCertificate struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The serial number of the root certificate
// @inject_tag: `gorm:"not_null"`
SerialNumber uint64 `protobuf:"varint,10,opt,name=serial_number,json=serialNumber,proto3" json:"serial_number,omitempty" gorm:"not_null"`
// Certificate is the PEM encoded certificate.
// @inject_tag: `gorm:"not_null"`
Certificate []byte `protobuf:"bytes,20,opt,name=certificate,proto3" json:"certificate,omitempty" gorm:"not_null"`
// Not valid before is the timestamp at which this certificate's validity period starts
NotValidBefore *timestamp.Timestamp `protobuf:"bytes,30,opt,name=not_valid_before,json=notValidBefore,proto3" json:"not_valid_before,omitempty"`
// Not valid after is the timestamp at which this certificate's validity period ends
NotValidAfter *timestamp.Timestamp `protobuf:"bytes,40,opt,name=not_valid_after,json=notValidAfter,proto3" json:"not_valid_after,omitempty"`
// The public key associated with this certificate
// @inject_tag: `gorm:"not_null"`
PublicKey []byte `protobuf:"bytes,50,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty" gorm:"not_null"`
// The private key associated with this certificate
// This is a ciphertext field
// @inject_tag: `gorm:"not_null"`
PrivateKey []byte `protobuf:"bytes,60,opt,name=private_key,json=privateKey,proto3" json:"private_key,omitempty" gorm:"not_null"`
// The id of the kms database key used for encrypting this entry.
// @inject_tag: `gorm:"not_null"`
KeyId string `protobuf:"bytes,70,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty" gorm:"not_null"`
// State is an enum value indicating if this is the next or current root cert
// @inject_tag: `gorm:"not_null"`
State string `protobuf:"bytes,80,opt,name=state,proto3" json:"state,omitempty" gorm:"not_null"`
// A reference to the CertificateAuthority
// @inject_tag: `gorm:"not_null"`
IssuingCa string `protobuf:"bytes,90,opt,name=issuing_ca,json=issuingCa,proto3" json:"issuing_ca,omitempty" gorm:"not_null"`
}
func (x *RootCertificate) Reset() {
*x = RootCertificate{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_storage_servers_store_v1_root_certificate_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RootCertificate) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RootCertificate) ProtoMessage() {}
func (x *RootCertificate) ProtoReflect() protoreflect.Message {
mi := &file_controller_storage_servers_store_v1_root_certificate_proto_msgTypes[1]
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 RootCertificate.ProtoReflect.Descriptor instead.
func (*RootCertificate) Descriptor() ([]byte, []int) {
return file_controller_storage_servers_store_v1_root_certificate_proto_rawDescGZIP(), []int{1}
}
func (x *RootCertificate) GetSerialNumber() uint64 {
if x != nil {
return x.SerialNumber
}
return 0
}
func (x *RootCertificate) GetCertificate() []byte {
if x != nil {
return x.Certificate
}
return nil
}
func (x *RootCertificate) GetNotValidBefore() *timestamp.Timestamp {
if x != nil {
return x.NotValidBefore
}
return nil
}
func (x *RootCertificate) GetNotValidAfter() *timestamp.Timestamp {
if x != nil {
return x.NotValidAfter
}
return nil
}
func (x *RootCertificate) GetPublicKey() []byte {
if x != nil {
return x.PublicKey
}
return nil
}
func (x *RootCertificate) GetPrivateKey() []byte {
if x != nil {
return x.PrivateKey
}
return nil
}
func (x *RootCertificate) GetKeyId() string {
if x != nil {
return x.KeyId
}
return ""
}
func (x *RootCertificate) GetState() string {
if x != nil {
return x.State
}
return ""
}
func (x *RootCertificate) GetIssuingCa() string {
if x != nil {
return x.IssuingCa
}
return ""
}
var File_controller_storage_servers_store_v1_root_certificate_proto protoreflect.FileDescriptor
var file_controller_storage_servers_store_v1_root_certificate_proto_rawDesc = []byte{
0x0a, 0x3a, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f,
0x72, 0x61, 0x67, 0x65, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x2f, 0x73, 0x74, 0x6f,
0x72, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x72, 0x6f, 0x6f, 0x74, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x69,
0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x23, 0x63, 0x6f,
0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65,
0x2e, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 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, 0x22, 0x4f, 0x0a, 0x14, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74,
0x65, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x72,
0x69, 0x76, 0x61, 0x74, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09,
0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72,
0x73, 0x69, 0x6f, 0x6e, 0x18, 0x14, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73,
0x69, 0x6f, 0x6e, 0x22, 0x8e, 0x03, 0x0a, 0x0f, 0x52, 0x6f, 0x6f, 0x74, 0x43, 0x65, 0x72, 0x74,
0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x73, 0x65, 0x72, 0x69, 0x61,
0x6c, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0c,
0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x20, 0x0a, 0x0b,
0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x18, 0x14, 0x20, 0x01, 0x28,
0x0c, 0x52, 0x0b, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x12, 0x54,
0x0a, 0x10, 0x6e, 0x6f, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x5f, 0x62, 0x65, 0x66, 0x6f,
0x72, 0x65, 0x18, 0x1e, 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, 0x0e, 0x6e, 0x6f, 0x74, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x42, 0x65,
0x66, 0x6f, 0x72, 0x65, 0x12, 0x52, 0x0a, 0x0f, 0x6e, 0x6f, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x69,
0x64, 0x5f, 0x61, 0x66, 0x74, 0x65, 0x72, 0x18, 0x28, 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, 0x0d, 0x6e, 0x6f, 0x74, 0x56, 0x61,
0x6c, 0x69, 0x64, 0x41, 0x66, 0x74, 0x65, 0x72, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x75, 0x62, 0x6c,
0x69, 0x63, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x32, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x70, 0x75,
0x62, 0x6c, 0x69, 0x63, 0x4b, 0x65, 0x79, 0x12, 0x1f, 0x0a, 0x0b, 0x70, 0x72, 0x69, 0x76, 0x61,
0x74, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x3c, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x70, 0x72,
0x69, 0x76, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x12, 0x15, 0x0a, 0x06, 0x6b, 0x65, 0x79, 0x5f,
0x69, 0x64, 0x18, 0x46, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6b, 0x65, 0x79, 0x49, 0x64, 0x12,
0x14, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x50, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05,
0x73, 0x74, 0x61, 0x74, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x69, 0x73, 0x73, 0x75, 0x69, 0x6e, 0x67,
0x5f, 0x63, 0x61, 0x18, 0x5a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x69, 0x73, 0x73, 0x75, 0x69,
0x6e, 0x67, 0x43, 0x61, 0x42, 0x3b, 0x5a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,
0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75,
0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x73,
0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x3b, 0x73, 0x74, 0x6f, 0x72,
0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_controller_storage_servers_store_v1_root_certificate_proto_rawDescOnce sync.Once
file_controller_storage_servers_store_v1_root_certificate_proto_rawDescData = file_controller_storage_servers_store_v1_root_certificate_proto_rawDesc
)
func file_controller_storage_servers_store_v1_root_certificate_proto_rawDescGZIP() []byte {
file_controller_storage_servers_store_v1_root_certificate_proto_rawDescOnce.Do(func() {
file_controller_storage_servers_store_v1_root_certificate_proto_rawDescData = protoimpl.X.CompressGZIP(file_controller_storage_servers_store_v1_root_certificate_proto_rawDescData)
})
return file_controller_storage_servers_store_v1_root_certificate_proto_rawDescData
}
var file_controller_storage_servers_store_v1_root_certificate_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_controller_storage_servers_store_v1_root_certificate_proto_goTypes = []interface{}{
(*CertificateAuthority)(nil), // 0: controller.storage.servers.store.v1.CertificateAuthority
(*RootCertificate)(nil), // 1: controller.storage.servers.store.v1.RootCertificate
(*timestamp.Timestamp)(nil), // 2: controller.storage.timestamp.v1.Timestamp
}
var file_controller_storage_servers_store_v1_root_certificate_proto_depIdxs = []int32{
2, // 0: controller.storage.servers.store.v1.RootCertificate.not_valid_before:type_name -> controller.storage.timestamp.v1.Timestamp
2, // 1: controller.storage.servers.store.v1.RootCertificate.not_valid_after: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_servers_store_v1_root_certificate_proto_init() }
func file_controller_storage_servers_store_v1_root_certificate_proto_init() {
if File_controller_storage_servers_store_v1_root_certificate_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_controller_storage_servers_store_v1_root_certificate_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*CertificateAuthority); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_controller_storage_servers_store_v1_root_certificate_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RootCertificate); 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_servers_store_v1_root_certificate_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_controller_storage_servers_store_v1_root_certificate_proto_goTypes,
DependencyIndexes: file_controller_storage_servers_store_v1_root_certificate_proto_depIdxs,
MessageInfos: file_controller_storage_servers_store_v1_root_certificate_proto_msgTypes,
}.Build()
File_controller_storage_servers_store_v1_root_certificate_proto = out.File
file_controller_storage_servers_store_v1_root_certificate_proto_rawDesc = nil
file_controller_storage_servers_store_v1_root_certificate_proto_goTypes = nil
file_controller_storage_servers_store_v1_root_certificate_proto_depIdxs = nil
}
+382
View File
@@ -0,0 +1,382 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc (unknown)
// source: controller/storage/servers/store/v1/worker.proto
package store
import (
timestamp "github.com/hashicorp/boundary/internal/db/timestamp"
_ "github.com/hashicorp/boundary/sdk/pbs/controller/protooptions"
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)
)
// Worker contains all fields related to a Worker resource
type Worker struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// public_id is a surrogate key suitable for use in a public API
// @inject_tag: `gorm:"primary_key"`
PublicId string `protobuf:"bytes,10,opt,name=public_id,json=publicId,proto3" json:"public_id,omitempty" gorm:"primary_key"`
// Name of the resource (optional)
// @inject_tag: `gorm:"default:null"`
Name string `protobuf:"bytes,20,opt,name=name,proto3" json:"name,omitempty" gorm:"default:null"`
// Description of the resource (optional)
// @inject_tag: `gorm:"default:null"`
Description string `protobuf:"bytes,30,opt,name=description,proto3" json:"description,omitempty" gorm:"default:null"`
// Address for the worker. This is optional.
// @inject_tag: `gorm:"default:null"`
Address string `protobuf:"bytes,40,opt,name=address,proto3" json:"address,omitempty" gorm:"default:null"`
// The create_time is set by the database.
// @inject_tag: `gorm:"default:current_timestamp"`
CreateTime *timestamp.Timestamp `protobuf:"bytes,50,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty" gorm:"default:current_timestamp"`
// The update_time is set by the database.
// @inject_tag: `gorm:"default:current_timestamp"`
UpdateTime *timestamp.Timestamp `protobuf:"bytes,60,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty" gorm:"default:current_timestamp"`
// The scope_id of the owning scope and must be set.
// @inject_tag: `gorm:"not_null"`
ScopeId string `protobuf:"bytes,70,opt,name=scope_id,json=scopeId,proto3" json:"scope_id,omitempty" gorm:"not_null"`
// version allows optimistic locking of the resource.
// @inject_tag: `gorm:"default:null"`
Version uint32 `protobuf:"varint,80,opt,name=version,proto3" json:"version,omitempty" gorm:"default:null"`
// The last_status_time is the last time a worker daemon sent a status update.
// @inject_tag: `gorm:"default:null"`
LastStatusTime *timestamp.Timestamp `protobuf:"bytes,110,opt,name=last_status_time,json=lastStatusTime,proto3" json:"last_status_time,omitempty" gorm:"default:null"`
// The type of the worker, denoted by how it authenticates: pki or kms.
// @inject_tag: `gorm:"not_null"`
Type string `protobuf:"bytes,130,opt,name=type,proto3" json:"type,omitempty" gorm:"not_null"`
}
func (x *Worker) Reset() {
*x = Worker{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_storage_servers_store_v1_worker_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Worker) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Worker) ProtoMessage() {}
func (x *Worker) ProtoReflect() protoreflect.Message {
mi := &file_controller_storage_servers_store_v1_worker_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 Worker.ProtoReflect.Descriptor instead.
func (*Worker) Descriptor() ([]byte, []int) {
return file_controller_storage_servers_store_v1_worker_proto_rawDescGZIP(), []int{0}
}
func (x *Worker) GetPublicId() string {
if x != nil {
return x.PublicId
}
return ""
}
func (x *Worker) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *Worker) GetDescription() string {
if x != nil {
return x.Description
}
return ""
}
func (x *Worker) GetAddress() string {
if x != nil {
return x.Address
}
return ""
}
func (x *Worker) GetCreateTime() *timestamp.Timestamp {
if x != nil {
return x.CreateTime
}
return nil
}
func (x *Worker) GetUpdateTime() *timestamp.Timestamp {
if x != nil {
return x.UpdateTime
}
return nil
}
func (x *Worker) GetScopeId() string {
if x != nil {
return x.ScopeId
}
return ""
}
func (x *Worker) GetVersion() uint32 {
if x != nil {
return x.Version
}
return 0
}
func (x *Worker) GetLastStatusTime() *timestamp.Timestamp {
if x != nil {
return x.LastStatusTime
}
return nil
}
func (x *Worker) GetType() string {
if x != nil {
return x.Type
}
return ""
}
// WorkerTag is a tag for a worker. The primary key is comprised of the
// worker_id, key, value, and source.
type WorkerTag struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// worker_id is the public key that key of the worker this tag is for.
// @inject_tag: `gorm:"primary_key"`
WorkerId string `protobuf:"bytes,10,opt,name=worker_id,json=workerId,proto3" json:"worker_id,omitempty" gorm:"primary_key"`
// key is the key of the tag. This must be set.
// @inject_tag: `gorm:"primary_key"`
Key string `protobuf:"bytes,20,opt,name=key,proto3" json:"key,omitempty" gorm:"primary_key"`
// value is the value
// @inject_tag: `gorm:"primary_key"`
Value string `protobuf:"bytes,30,opt,name=value,proto3" json:"value,omitempty" gorm:"primary_key"`
// source is the source of the tag. Either 'configuration' or 'api'.
// @inject_tag: `gorm:"default:not_null"`
Source string `protobuf:"bytes,40,opt,name=source,proto3" json:"source,omitempty" gorm:"default:not_null"`
}
func (x *WorkerTag) Reset() {
*x = WorkerTag{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_storage_servers_store_v1_worker_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *WorkerTag) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*WorkerTag) ProtoMessage() {}
func (x *WorkerTag) ProtoReflect() protoreflect.Message {
mi := &file_controller_storage_servers_store_v1_worker_proto_msgTypes[1]
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 WorkerTag.ProtoReflect.Descriptor instead.
func (*WorkerTag) Descriptor() ([]byte, []int) {
return file_controller_storage_servers_store_v1_worker_proto_rawDescGZIP(), []int{1}
}
func (x *WorkerTag) GetWorkerId() string {
if x != nil {
return x.WorkerId
}
return ""
}
func (x *WorkerTag) GetKey() string {
if x != nil {
return x.Key
}
return ""
}
func (x *WorkerTag) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
func (x *WorkerTag) GetSource() string {
if x != nil {
return x.Source
}
return ""
}
var File_controller_storage_servers_store_v1_worker_proto protoreflect.FileDescriptor
var file_controller_storage_servers_store_v1_worker_proto_rawDesc = []byte{
0x0a, 0x30, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f,
0x72, 0x61, 0x67, 0x65, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x2f, 0x73, 0x74, 0x6f,
0x72, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x12, 0x23, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73,
0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x2e, 0x73,
0x74, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x2a, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c,
0x6c, 0x65, 0x72, 0x2f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f,
0x6e, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 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, 0x22, 0xe1, 0x03, 0x0a, 0x06, 0x57, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x12,
0x1b, 0x0a, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01,
0x28, 0x09, 0x52, 0x08, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x49, 0x64, 0x12, 0x24, 0x0a, 0x04,
0x6e, 0x61, 0x6d, 0x65, 0x18, 0x14, 0x20, 0x01, 0x28, 0x09, 0x42, 0x10, 0xc2, 0xdd, 0x29, 0x0c,
0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x52, 0x04, 0x6e, 0x61,
0x6d, 0x65, 0x12, 0x40, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f,
0x6e, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x09, 0x42, 0x1e, 0xc2, 0xdd, 0x29, 0x1a, 0x0a, 0x0b, 0x64,
0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x0b, 0x64, 0x65, 0x73, 0x63,
0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70,
0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18,
0x28, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x4b,
0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x32, 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, 0x3c, 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, 0x19, 0x0a, 0x08, 0x73, 0x63, 0x6f, 0x70,
0x65, 0x5f, 0x69, 0x64, 0x18, 0x46, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x63, 0x6f, 0x70,
0x65, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x50,
0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x54, 0x0a,
0x10, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x5f, 0x74, 0x69, 0x6d,
0x65, 0x18, 0x6e, 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, 0x0e, 0x6c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x54,
0x69, 0x6d, 0x65, 0x12, 0x13, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x82, 0x01, 0x20, 0x01,
0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x22, 0x68, 0x0a, 0x09, 0x57, 0x6f, 0x72, 0x6b,
0x65, 0x72, 0x54, 0x61, 0x67, 0x12, 0x1b, 0x0a, 0x09, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x5f,
0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72,
0x49, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x14, 0x20, 0x01, 0x28, 0x09, 0x52,
0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x1e, 0x20,
0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x6f,
0x75, 0x72, 0x63, 0x65, 0x18, 0x28, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x6f, 0x75, 0x72,
0x63, 0x65, 0x42, 0x3b, 0x5a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d,
0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f, 0x62, 0x6f, 0x75, 0x6e, 0x64,
0x61, 0x72, 0x79, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x73, 0x65, 0x72,
0x76, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x3b, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x62,
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_controller_storage_servers_store_v1_worker_proto_rawDescOnce sync.Once
file_controller_storage_servers_store_v1_worker_proto_rawDescData = file_controller_storage_servers_store_v1_worker_proto_rawDesc
)
func file_controller_storage_servers_store_v1_worker_proto_rawDescGZIP() []byte {
file_controller_storage_servers_store_v1_worker_proto_rawDescOnce.Do(func() {
file_controller_storage_servers_store_v1_worker_proto_rawDescData = protoimpl.X.CompressGZIP(file_controller_storage_servers_store_v1_worker_proto_rawDescData)
})
return file_controller_storage_servers_store_v1_worker_proto_rawDescData
}
var file_controller_storage_servers_store_v1_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_controller_storage_servers_store_v1_worker_proto_goTypes = []interface{}{
(*Worker)(nil), // 0: controller.storage.servers.store.v1.Worker
(*WorkerTag)(nil), // 1: controller.storage.servers.store.v1.WorkerTag
(*timestamp.Timestamp)(nil), // 2: controller.storage.timestamp.v1.Timestamp
}
var file_controller_storage_servers_store_v1_worker_proto_depIdxs = []int32{
2, // 0: controller.storage.servers.store.v1.Worker.create_time:type_name -> controller.storage.timestamp.v1.Timestamp
2, // 1: controller.storage.servers.store.v1.Worker.update_time:type_name -> controller.storage.timestamp.v1.Timestamp
2, // 2: controller.storage.servers.store.v1.Worker.last_status_time:type_name -> controller.storage.timestamp.v1.Timestamp
3, // [3:3] is the sub-list for method output_type
3, // [3:3] is the sub-list for method input_type
3, // [3:3] is the sub-list for extension type_name
3, // [3:3] is the sub-list for extension extendee
0, // [0:3] is the sub-list for field type_name
}
func init() { file_controller_storage_servers_store_v1_worker_proto_init() }
func file_controller_storage_servers_store_v1_worker_proto_init() {
if File_controller_storage_servers_store_v1_worker_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_controller_storage_servers_store_v1_worker_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Worker); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_controller_storage_servers_store_v1_worker_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*WorkerTag); 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_servers_store_v1_worker_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_controller_storage_servers_store_v1_worker_proto_goTypes,
DependencyIndexes: file_controller_storage_servers_store_v1_worker_proto_depIdxs,
MessageInfos: file_controller_storage_servers_store_v1_worker_proto_msgTypes,
}.Build()
File_controller_storage_servers_store_v1_worker_proto = out.File
file_controller_storage_servers_store_v1_worker_proto_rawDesc = nil
file_controller_storage_servers_store_v1_worker_proto_goTypes = nil
file_controller_storage_servers_store_v1_worker_proto_depIdxs = nil
}
+326
View File
@@ -0,0 +1,326 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc (unknown)
// source: controller/storage/servers/store/v1/worker_auth.proto
// Package store provides protobufs for storing types in the pki package.
package store
import (
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)
)
// WorkerAuth contains all fields related to an authorized Worker resource
type WorkerAuth struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The key id for this worker auth record, generated from the signing pub key
// @inject_tag: `gorm:"primary_key"`
WorkerKeyIdentifier string `protobuf:"bytes,10,opt,name=worker_key_identifier,json=workerKeyIdentifier,proto3" json:"worker_key_identifier,omitempty" gorm:"primary_key"`
// The worker id this worker authentication record is for
// @inject_tag: `gorm:"not_null"`
WorkerId string `protobuf:"bytes,20,opt,name=worker_id,json=workerId,proto3" json:"worker_id,omitempty" gorm:"not_null"`
// The worker's public signing key
// @inject_tag: `gorm:"not_null"`
WorkerSigningPubKey []byte `protobuf:"bytes,30,opt,name=worker_signing_pub_key,json=workerSigningPubKey,proto3" json:"worker_signing_pub_key,omitempty" gorm:"not_null"`
// The worker's public encryption key
// @inject_tag: `gorm:"not_null"`
WorkerEncryptionPubKey []byte `protobuf:"bytes,40,opt,name=worker_encryption_pub_key,json=workerEncryptionPubKey,proto3" json:"worker_encryption_pub_key,omitempty" gorm:"not_null"`
// The private key associated with this certificate
// This is a ciphertext field
// @inject_tag: `gorm:"not_null"`
ControllerEncryptionPrivKey []byte `protobuf:"bytes,50,opt,name=controller_encryption_priv_key,json=controllerEncryptionPrivKey,proto3" json:"controller_encryption_priv_key,omitempty" gorm:"not_null"`
// The id of the kms database key used for encrypting this entry.
// @inject_tag: `gorm:"not_null"`
KeyId string `protobuf:"bytes,60,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty" gorm:"not_null"`
// Nonce used by a worker in authenticating
// @inject_tag: `gorm:"default:null"`
Nonce []byte `protobuf:"bytes,70,opt,name=nonce,proto3" json:"nonce,omitempty" gorm:"default:null"`
}
func (x *WorkerAuth) Reset() {
*x = WorkerAuth{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_storage_servers_store_v1_worker_auth_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *WorkerAuth) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*WorkerAuth) ProtoMessage() {}
func (x *WorkerAuth) ProtoReflect() protoreflect.Message {
mi := &file_controller_storage_servers_store_v1_worker_auth_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 WorkerAuth.ProtoReflect.Descriptor instead.
func (*WorkerAuth) Descriptor() ([]byte, []int) {
return file_controller_storage_servers_store_v1_worker_auth_proto_rawDescGZIP(), []int{0}
}
func (x *WorkerAuth) GetWorkerKeyIdentifier() string {
if x != nil {
return x.WorkerKeyIdentifier
}
return ""
}
func (x *WorkerAuth) GetWorkerId() string {
if x != nil {
return x.WorkerId
}
return ""
}
func (x *WorkerAuth) GetWorkerSigningPubKey() []byte {
if x != nil {
return x.WorkerSigningPubKey
}
return nil
}
func (x *WorkerAuth) GetWorkerEncryptionPubKey() []byte {
if x != nil {
return x.WorkerEncryptionPubKey
}
return nil
}
func (x *WorkerAuth) GetControllerEncryptionPrivKey() []byte {
if x != nil {
return x.ControllerEncryptionPrivKey
}
return nil
}
func (x *WorkerAuth) GetKeyId() string {
if x != nil {
return x.KeyId
}
return ""
}
func (x *WorkerAuth) GetNonce() []byte {
if x != nil {
return x.Nonce
}
return nil
}
// WorkerCertBundle contains all fields related to a WorkerCertBundle resource
type WorkerCertBundle struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The public key of the issuing root certificate
// @inject_tag: `gorm:"primary_key"`
RootCertificatePublicKey []byte `protobuf:"bytes,10,opt,name=root_certificate_public_key,json=rootCertificatePublicKey,proto3" json:"root_certificate_public_key,omitempty" gorm:"primary_key"`
// The WorkerAuth worker_key_identifier this cert bundle record is for
// @inject_tag: `gorm:"primary_key"`
WorkerKeyIdentifier string `protobuf:"bytes,20,opt,name=worker_key_identifier,json=workerKeyIdentifier,proto3" json:"worker_key_identifier,omitempty" gorm:"primary_key"`
// CertBundle is the marshaled protobuf certificate bundle for a WorkerAuth
// @inject_tag: `gorm:"not_null"`
CertBundle []byte `protobuf:"bytes,30,opt,name=cert_bundle,json=certBundle,proto3" json:"cert_bundle,omitempty" gorm:"not_null"`
}
func (x *WorkerCertBundle) Reset() {
*x = WorkerCertBundle{}
if protoimpl.UnsafeEnabled {
mi := &file_controller_storage_servers_store_v1_worker_auth_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *WorkerCertBundle) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*WorkerCertBundle) ProtoMessage() {}
func (x *WorkerCertBundle) ProtoReflect() protoreflect.Message {
mi := &file_controller_storage_servers_store_v1_worker_auth_proto_msgTypes[1]
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 WorkerCertBundle.ProtoReflect.Descriptor instead.
func (*WorkerCertBundle) Descriptor() ([]byte, []int) {
return file_controller_storage_servers_store_v1_worker_auth_proto_rawDescGZIP(), []int{1}
}
func (x *WorkerCertBundle) GetRootCertificatePublicKey() []byte {
if x != nil {
return x.RootCertificatePublicKey
}
return nil
}
func (x *WorkerCertBundle) GetWorkerKeyIdentifier() string {
if x != nil {
return x.WorkerKeyIdentifier
}
return ""
}
func (x *WorkerCertBundle) GetCertBundle() []byte {
if x != nil {
return x.CertBundle
}
return nil
}
var File_controller_storage_servers_store_v1_worker_auth_proto protoreflect.FileDescriptor
var file_controller_storage_servers_store_v1_worker_auth_proto_rawDesc = []byte{
0x0a, 0x35, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f,
0x72, 0x61, 0x67, 0x65, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x2f, 0x73, 0x74, 0x6f,
0x72, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x5f, 0x61, 0x75, 0x74,
0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x23, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c,
0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x73, 0x65, 0x72, 0x76,
0x65, 0x72, 0x73, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x31, 0x22, 0xbf, 0x02, 0x0a,
0x0a, 0x57, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x41, 0x75, 0x74, 0x68, 0x12, 0x32, 0x0a, 0x15, 0x77,
0x6f, 0x72, 0x6b, 0x65, 0x72, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69,
0x66, 0x69, 0x65, 0x72, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x13, 0x77, 0x6f, 0x72, 0x6b,
0x65, 0x72, 0x4b, 0x65, 0x79, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12,
0x1b, 0x0a, 0x09, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x14, 0x20, 0x01,
0x28, 0x09, 0x52, 0x08, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x49, 0x64, 0x12, 0x33, 0x0a, 0x16,
0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x70,
0x75, 0x62, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x13, 0x77, 0x6f,
0x72, 0x6b, 0x65, 0x72, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x50, 0x75, 0x62, 0x4b, 0x65,
0x79, 0x12, 0x39, 0x0a, 0x19, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x5f, 0x65, 0x6e, 0x63, 0x72,
0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x75, 0x62, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x28,
0x20, 0x01, 0x28, 0x0c, 0x52, 0x16, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x45, 0x6e, 0x63, 0x72,
0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x12, 0x43, 0x0a, 0x1e,
0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x5f, 0x65, 0x6e, 0x63, 0x72, 0x79,
0x70, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x72, 0x69, 0x76, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x32,
0x20, 0x01, 0x28, 0x0c, 0x52, 0x1b, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72,
0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72, 0x69, 0x76, 0x4b, 0x65,
0x79, 0x12, 0x15, 0x0a, 0x06, 0x6b, 0x65, 0x79, 0x5f, 0x69, 0x64, 0x18, 0x3c, 0x20, 0x01, 0x28,
0x09, 0x52, 0x05, 0x6b, 0x65, 0x79, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x6e, 0x6f, 0x6e, 0x63,
0x65, 0x18, 0x46, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x6e, 0x6f, 0x6e, 0x63, 0x65, 0x22, 0xa6,
0x01, 0x0a, 0x10, 0x57, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x43, 0x65, 0x72, 0x74, 0x42, 0x75, 0x6e,
0x64, 0x6c, 0x65, 0x12, 0x3d, 0x0a, 0x1b, 0x72, 0x6f, 0x6f, 0x74, 0x5f, 0x63, 0x65, 0x72, 0x74,
0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x5f, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x5f, 0x6b,
0x65, 0x79, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x18, 0x72, 0x6f, 0x6f, 0x74, 0x43, 0x65,
0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x4b,
0x65, 0x79, 0x12, 0x32, 0x0a, 0x15, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x5f, 0x6b, 0x65, 0x79,
0x5f, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x18, 0x14, 0x20, 0x01, 0x28,
0x09, 0x52, 0x13, 0x77, 0x6f, 0x72, 0x6b, 0x65, 0x72, 0x4b, 0x65, 0x79, 0x49, 0x64, 0x65, 0x6e,
0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x65, 0x72, 0x74, 0x5f, 0x62,
0x75, 0x6e, 0x64, 0x6c, 0x65, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x63, 0x65, 0x72,
0x74, 0x42, 0x75, 0x6e, 0x64, 0x6c, 0x65, 0x42, 0x3b, 0x5a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75,
0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, 0x72, 0x70, 0x2f,
0x62, 0x6f, 0x75, 0x6e, 0x64, 0x61, 0x72, 0x79, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61,
0x6c, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x3b, 0x73,
0x74, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_controller_storage_servers_store_v1_worker_auth_proto_rawDescOnce sync.Once
file_controller_storage_servers_store_v1_worker_auth_proto_rawDescData = file_controller_storage_servers_store_v1_worker_auth_proto_rawDesc
)
func file_controller_storage_servers_store_v1_worker_auth_proto_rawDescGZIP() []byte {
file_controller_storage_servers_store_v1_worker_auth_proto_rawDescOnce.Do(func() {
file_controller_storage_servers_store_v1_worker_auth_proto_rawDescData = protoimpl.X.CompressGZIP(file_controller_storage_servers_store_v1_worker_auth_proto_rawDescData)
})
return file_controller_storage_servers_store_v1_worker_auth_proto_rawDescData
}
var file_controller_storage_servers_store_v1_worker_auth_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_controller_storage_servers_store_v1_worker_auth_proto_goTypes = []interface{}{
(*WorkerAuth)(nil), // 0: controller.storage.servers.store.v1.WorkerAuth
(*WorkerCertBundle)(nil), // 1: controller.storage.servers.store.v1.WorkerCertBundle
}
var file_controller_storage_servers_store_v1_worker_auth_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_controller_storage_servers_store_v1_worker_auth_proto_init() }
func file_controller_storage_servers_store_v1_worker_auth_proto_init() {
if File_controller_storage_servers_store_v1_worker_auth_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_controller_storage_servers_store_v1_worker_auth_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*WorkerAuth); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_controller_storage_servers_store_v1_worker_auth_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*WorkerCertBundle); 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_servers_store_v1_worker_auth_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_controller_storage_servers_store_v1_worker_auth_proto_goTypes,
DependencyIndexes: file_controller_storage_servers_store_v1_worker_auth_proto_depIdxs,
MessageInfos: file_controller_storage_servers_store_v1_worker_auth_proto_msgTypes,
}.Build()
File_controller_storage_servers_store_v1_worker_auth_proto = out.File
file_controller_storage_servers_store_v1_worker_auth_proto_rawDesc = nil
file_controller_storage_servers_store_v1_worker_auth_proto_goTypes = nil
file_controller_storage_servers_store_v1_worker_auth_proto_depIdxs = nil
}
+204
View File
@@ -0,0 +1,204 @@
package server
import (
"context"
"crypto/rand"
mathRand "math/rand"
"strings"
"testing"
"time"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/db/timestamp"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/iam"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/server/store"
"github.com/hashicorp/boundary/internal/types/scope"
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
"github.com/hashicorp/nodeenrollment"
"github.com/hashicorp/nodeenrollment/registration"
"github.com/hashicorp/nodeenrollment/rotation"
"github.com/hashicorp/nodeenrollment/storage/file"
"github.com/hashicorp/nodeenrollment/types"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
)
const defaultLength = 20
// Generate random bytes for byte fields
func populateBytes(length int) []byte {
fieldBytes := make([]byte, length)
rand.Read(fieldBytes)
return fieldBytes
}
func TestKmsKey(ctx context.Context, t *testing.T, conn *db.DB, wrapper wrapping.Wrapper) string {
t.Helper()
org, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
kmsCache := kms.TestKms(t, conn, wrapper)
databaseWrapper, err := kmsCache.GetWrapper(context.Background(), org.PublicId, kms.KeyPurposeDatabase)
require.NoError(t, err)
testKey, err := databaseWrapper.KeyId(ctx)
require.NoError(t, err)
return testKey
}
func TestRootCertificate(ctx context.Context, t *testing.T, conn *db.DB, kmsKey string) *RootCertificate {
t.Helper()
rw := db.New(conn)
beforeTimestamp := &timestamp.Timestamp{Timestamp: timestamppb.New(time.Now().Add(-1 * time.Hour))}
afterTimestamp := &timestamp.Timestamp{Timestamp: timestamppb.New(time.Now().Add(1 * time.Hour))}
rootCertKeys := RootCertificateKeys{
publicKey: populateBytes(defaultLength),
privateKey: populateBytes(defaultLength),
}
cert, err := newRootCertificate(ctx, mathRand.Uint64(), populateBytes(defaultLength), beforeTimestamp, afterTimestamp,
rootCertKeys, kmsKey, CurrentState)
err = rw.Create(ctx, cert)
require.NoError(t, err)
return cert
}
func TestWorkerAuth(t *testing.T, conn *db.DB, worker *Worker, kmsKey string) *WorkerAuth {
t.Helper()
ctx := context.Background()
rw := db.New(conn)
wSignPubKey := populateBytes(defaultLength)
wEncPubKey := populateBytes(defaultLength)
workerKeys := WorkerKeys{workerSigningPubKey: wSignPubKey, workerEncryptionPubKey: wEncPubKey}
controllerKey := populateBytes(defaultLength)
nonce := populateBytes(defaultLength)
opt := []Option{
WithKeyId(kmsKey),
WithWorkerKeys(workerKeys),
WithControllerEncryptionPrivateKey(controllerKey),
WithNonce(nonce),
}
workerAuth, err := newWorkerAuth(ctx, "worker-key-identifier", worker.PublicId, opt...)
require.NoError(t, err)
err = rw.Create(ctx, workerAuth)
require.NoError(t, err)
return workerAuth
}
// TestKmsWorker inserts a worker into the db to satisfy foreign key constraints.
// The worker provided fields are auto generated. if WithName is not present a
// random name will be generated and assigned to the worker.
func TestKmsWorker(t *testing.T, conn *db.DB, wrapper wrapping.Wrapper, opt ...Option) *Worker {
t.Helper()
rw := db.New(conn)
kms := kms.TestKms(t, conn, wrapper)
serversRepo, err := NewRepository(rw, rw, kms)
require.NoError(t, err)
ctx := context.Background()
opts := getOpts(opt...)
namePart, err := newWorkerId(ctx)
require.NoError(t, err)
name := "test-worker-" + strings.ToLower(namePart)
if opts.withName != "" {
name = opts.withName
}
address := "127.0.0.1"
if opts.withAddress != "" {
address = opts.withAddress
}
wrk := NewWorker(scope.Global.String(),
WithName(name),
WithAddress(address),
WithDescription(opts.withDescription))
wrk, err = serversRepo.UpsertWorkerStatus(ctx, wrk)
require.NoError(t, err)
require.NotNil(t, wrk)
require.Equal(t, "kms", wrk.Type)
if len(opts.withWorkerTags) > 0 {
var tags []interface{}
for _, t := range opts.withWorkerTags {
tags = append(tags, &store.WorkerTag{
WorkerId: wrk.GetPublicId(),
Key: t.Key,
Value: t.Value,
Source: "configuration",
})
}
require.NoError(t, rw.CreateItems(ctx, tags))
}
wrk, err = serversRepo.LookupWorker(ctx, wrk.GetPublicId())
require.NoError(t, err)
return wrk
}
// TestPkiWorker inserts a worker into the db to satisfy foreign key constraints.
// The worker provided fields are auto generated. WithName and WithDescription,
// are applied to the resource name, description if present. WithTestPkiWorkerAuthorizedKeyId
// can be used to make the PkiWorker authorized in which case the string pointer
// passed to WithTestPkiWorkerAuthorizedKeyId is set to the key id.
func TestPkiWorker(t *testing.T, conn *db.DB, wrapper wrapping.Wrapper, opt ...Option) *Worker {
t.Helper()
rw := db.New(conn)
kmsCache := kms.TestKms(t, conn, wrapper)
serversRepo, err := NewRepository(rw, rw, kmsCache)
require.NoError(t, err)
ctx := context.Background()
opts := getOpts(opt...)
require.NoError(t, err)
wrk := NewWorker(scope.Global.String(),
opt...)
wrk, err = serversRepo.CreateWorker(ctx, wrk, opt...)
require.NoError(t, err)
require.NotNil(t, wrk)
if len(opts.withWorkerTags) > 0 {
var tags []interface{}
for _, t := range opts.withWorkerTags {
tags = append(tags, &store.WorkerTag{
WorkerId: wrk.GetPublicId(),
Key: t.Key,
Value: t.Value,
Source: "configuration",
})
}
require.NoError(t, rw.CreateItems(ctx, tags))
}
if opts.withTestPkiWorkerAuthorized {
err = kmsCache.CreateKeys(context.Background(), scope.Global.String(), kms.WithRandomReader(rand.Reader))
// We always try to create root global scope keys, but if it already exists, just continue...
require.True(t, err == nil || errors.IsUniqueError(err), err)
rootStorage, err := NewRepositoryStorage(ctx, rw, rw, kmsCache)
require.NoError(t, err)
_, err = rotation.RotateRootCertificates(ctx, rootStorage)
require.NoError(t, err)
// Create struct to pass in with workerId that will be passed along to storage
state, err := AttachWorkerIdToState(ctx, wrk.PublicId)
require.NoError(t, err)
// This happens on the worker
fileStorage, err := file.New(ctx)
require.NoError(t, err)
nodeCreds, err := types.NewNodeCredentials(ctx, fileStorage)
require.NoError(t, err)
// Create request using worker id
fetchReq, err := nodeCreds.CreateFetchNodeCredentialsRequest(ctx)
require.NoError(t, err)
registeredNode, err := registration.AuthorizeNode(ctx, rootStorage, fetchReq, nodeenrollment.WithState(state))
require.NoError(t, err)
if opts.withTestPkiWorkerKeyId != nil {
*opts.withTestPkiWorkerKeyId = registeredNode.Id
}
}
wrk, err = serversRepo.LookupWorker(ctx, wrk.GetPublicId())
require.NoError(t, err)
return wrk
}
+64
View File
@@ -0,0 +1,64 @@
package server
import (
"context"
"strings"
"testing"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/types/scope"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTestKmsWorker(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
wrapper := db.TestWrapper(t)
const (
name = "test name"
description = "test description"
address = "test address"
)
tWorker := TestKmsWorker(t, conn, wrapper, WithName(name), WithDescription(description), WithAddress(address))
assert.NotNil(t, tWorker)
assert.True(t, strings.HasPrefix(tWorker.GetPublicId(), WorkerPrefix))
lkpWorker := NewWorker(scope.Global.String())
lkpWorker.PublicId = tWorker.GetPublicId()
rw := db.New(conn)
require.NoError(t, rw.LookupById(context.Background(), lkpWorker))
assert.NotNil(t, lkpWorker)
assert.NotNil(t, lkpWorker.GetLastStatusTime())
assert.Equal(t, KmsWorkerType.String(), lkpWorker.GetType())
assert.Equal(t, name, lkpWorker.GetName())
assert.Equal(t, description, lkpWorker.GetDescription())
assert.Equal(t, address, lkpWorker.GetAddress())
}
func TestTestPkiWorker(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
wrapper := db.TestWrapper(t)
const (
name = "test name"
description = "test description"
)
tWorker := TestPkiWorker(t, conn, wrapper, WithName(name), WithDescription(description))
assert.NotNil(t, tWorker)
assert.True(t, strings.HasPrefix(tWorker.GetPublicId(), WorkerPrefix))
lkpWorker := NewWorker(scope.Global.String())
lkpWorker.PublicId = tWorker.GetPublicId()
rw := db.New(conn)
require.NoError(t, rw.LookupById(context.Background(), lkpWorker))
assert.NotNil(t, lkpWorker)
assert.Equal(t, PkiWorkerType.String(), lkpWorker.GetType())
assert.Equal(t, name, lkpWorker.GetName())
assert.Equal(t, description, lkpWorker.GetDescription())
assert.Nil(t, lkpWorker.GetLastStatusTime())
var keyId string
authorizedWorker := TestPkiWorker(t, conn, wrapper, WithTestPkiWorkerAuthorizedKeyId(&keyId))
assert.NotNil(t, authorizedWorker)
assert.True(t, strings.HasPrefix(authorizedWorker.GetPublicId(), WorkerPrefix))
assert.NotEmpty(t, keyId)
}
+253
View File
@@ -0,0 +1,253 @@
package server
import (
"context"
"strings"
"github.com/fatih/structs"
"github.com/hashicorp/boundary/internal/db/timestamp"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/server/store"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/structpb"
)
type WorkerType string
const (
UnknownWorkerType WorkerType = "unknown"
KmsWorkerType WorkerType = "kms"
PkiWorkerType WorkerType = "pki"
)
func (t WorkerType) Valid() bool {
switch t {
case KmsWorkerType, PkiWorkerType:
return true
}
return false
}
func (t WorkerType) String() string {
return string(t)
}
type workerAuthWorkerId struct {
WorkerId string `mapstructure:"worker_id"`
}
// AttachWorkerIdToState accepts a workerId and creates a struct for use with the Nodeenrollment lib
// This is intended for use in worker authorization; AuthorizeNode in the lib accepts the option WithState
// so that the workerId is passed through to storage and associated with a WorkerAuth record
func AttachWorkerIdToState(ctx context.Context, workerId string) (*structpb.Struct, error) {
const op = "server.(Worker).AttachWorkerIdToState"
if workerId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing workerId")
}
workerMap := &workerAuthWorkerId{WorkerId: workerId}
s := structs.New(workerMap)
s.TagName = "mapstructure"
return structpb.NewStruct(s.Map())
}
// A Worker is a server that provides an address which can be used to proxy
// session connections. It can be tagged with custom tags and is used when
// authorizing and establishing a session. It is owned by a scope.
type Worker struct {
*store.Worker
activeConnectionCount uint32 `gorm:"-"`
apiTags []*Tag `gorm:"-"`
configTags []*Tag `gorm:"-"`
// inputTags is not specified to be api or config tags and is not intended
// to be read by clients. Since config tags and api tags are applied in
// mutually exclusive contexts, inputTags is interpreted to be one or the
// other based on the context in which the worker is passed. As such
// inputTags should only be read when performing mutations on the database.
inputTags []*Tag `gorm:"-"`
}
// NewWorker returns a new Worker. Valid options are WithName, WithDescription
// WithAddress, and WithWorkerTags. All other options are ignored. This does
// not set any of the worker reported values.
func NewWorker(scopeId string, opt ...Option) *Worker {
opts := getOpts(opt...)
return &Worker{
Worker: &store.Worker{
ScopeId: scopeId,
Name: opts.withName,
Description: opts.withDescription,
Address: opts.withAddress,
},
inputTags: opts.withWorkerTags,
}
}
// allocWorker will allocate a Worker
func allocWorker() Worker {
return Worker{Worker: &store.Worker{}}
}
func (w *Worker) clone() *Worker {
if w == nil {
return nil
}
cw := proto.Clone(w.Worker)
cWorker := &Worker{
Worker: cw.(*store.Worker),
}
if w.apiTags != nil {
cWorker.apiTags = make([]*Tag, 0, len(w.apiTags))
for _, t := range w.apiTags {
cWorker.apiTags = append(cWorker.apiTags, &Tag{Key: t.Key, Value: t.Value})
}
}
if w.configTags != nil {
cWorker.configTags = make([]*Tag, 0, len(w.configTags))
for _, t := range w.configTags {
cWorker.configTags = append(cWorker.configTags, &Tag{Key: t.Key, Value: t.Value})
}
}
if w.inputTags != nil {
cWorker.inputTags = make([]*Tag, 0, len(w.inputTags))
for _, t := range w.inputTags {
cWorker.inputTags = append(cWorker.inputTags, &Tag{Key: t.Key, Value: t.Value})
}
}
return cWorker
}
// ActiveConnectionCount is the current number of sessions this worker is handling
// according to the controllers.
func (w *Worker) ActiveConnectionCount() uint32 {
return w.activeConnectionCount
}
// CanonicalTags is the deduplicated set of tags contained on both the resource
// set over the API as well as the tags reported by the worker itself.
func (w *Worker) CanonicalTags() map[string][]string {
dedupedTags := make(map[Tag]struct{})
for _, t := range w.apiTags {
dedupedTags[*t] = struct{}{}
}
for _, t := range w.configTags {
dedupedTags[*t] = struct{}{}
}
tags := make(map[string][]string)
for t := range dedupedTags {
tags[t.Key] = append(tags[t.Key], t.Value)
}
return tags
}
// GetConfigTags returns the tags for this worker which has been set through
// the worker daemon's configuration file.
func (w *Worker) GetConfigTags() map[string][]string {
tags := make(map[string][]string)
for _, t := range w.configTags {
tags[t.Key] = append(tags[t.Key], t.Value)
}
return tags
}
// GetLastStatusTime contains the last time the worker has reported to the
// controller its connection status. If the worker has never reported to a
// controller then nil is returned.
func (w *Worker) GetLastStatusTime() *timestamp.Timestamp {
if w == nil || w.Worker == nil || w.Worker.GetLastStatusTime().AsTime() == timestamp.NegativeInfinityTS {
return nil
}
return w.Worker.GetLastStatusTime()
}
// TableName overrides the table name used by Worker to `server_worker`
func (Worker) TableName() string {
return "server_worker"
}
// workerAggregate contains an aggregated view of the values associated with
// a single worker.
type workerAggregate struct {
PublicId string `gorm:"primary_key"`
ScopeId string
Name string
Description string
CreateTime *timestamp.Timestamp
UpdateTime *timestamp.Timestamp
Address string
Version uint32
Type string
ApiTags string
ActiveConnectionCount uint32
// Config Fields
LastStatusTime *timestamp.Timestamp
WorkerConfigTags string
}
func (a *workerAggregate) toWorker(ctx context.Context) (*Worker, error) {
const op = "server.(workerAggregate).toWorker"
worker := &Worker{
Worker: &store.Worker{
PublicId: a.PublicId,
Name: a.Name,
Description: a.Description,
Address: a.Address,
CreateTime: a.CreateTime,
UpdateTime: a.UpdateTime,
ScopeId: a.ScopeId,
Version: a.Version,
LastStatusTime: a.LastStatusTime,
Type: a.Type,
},
activeConnectionCount: a.ActiveConnectionCount,
}
tags, err := tagsFromAggregatedTagString(ctx, a.ApiTags)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error parsing config tag string"))
}
worker.apiTags = tags
tags, err = tagsFromAggregatedTagString(ctx, a.WorkerConfigTags)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error parsing config tag string"))
}
worker.configTags = tags
return worker, nil
}
// tagsForAggregatedTagString parses a deliminated string in the format returned
// by the database for the server_worker_aggregate view and returns []*Tag.
// The string is in the format of key1Yvalue1Zkey2Yvalue2Zkey3Yvalue3. Y and Z
// ares chosen for deliminators since tag keys and values are restricted from
// having capitalized letters in them.
func tagsFromAggregatedTagString(ctx context.Context, s string) ([]*Tag, error) {
if s == "" {
return nil, nil
}
const op = "server.tagsFromAggregatedTagString"
const aggregateDelimiter = "Z"
const pairDelimiter = "Y"
var tags []*Tag
for _, kv := range strings.Split(s, aggregateDelimiter) {
res := strings.SplitN(kv, pairDelimiter, 3)
if len(res) != 2 {
return nil, errors.New(ctx, errors.Internal, op, "invalid aggregated tag pairs")
}
tags = append(tags, &Tag{
Key: res[0],
Value: res[1],
})
}
return tags, nil
}
func (a *workerAggregate) GetPublicId() string {
return a.PublicId
}
func (workerAggregate) TableName() string {
return "server_worker_aggregate"
}
+183
View File
@@ -0,0 +1,183 @@
package server
import (
"context"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/server/store"
"google.golang.org/protobuf/proto"
)
// WorkerAuth contains all fields related to an authorized Worker resource
// This includes worker public keys, the controller encryption key,
// and certificate bundles issued by the Boundary CA
type WorkerAuth struct {
*store.WorkerAuth
tableName string `gorm:"-"`
}
// WorkerKeys contain the signing and encryption keys for a WorkerAuth resource
type WorkerKeys struct {
workerSigningPubKey []byte
workerEncryptionPubKey []byte
}
func newWorkerAuth(ctx context.Context, workerKeyIdentifier, workerId string, opt ...Option) (*WorkerAuth, error) {
const op = "server.newWorkerAuth"
opts := getOpts(opt...)
if workerKeyIdentifier == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no workerKeyIdentifier")
}
if workerId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no workerId")
}
l := &WorkerAuth{
WorkerAuth: &store.WorkerAuth{
WorkerKeyIdentifier: workerKeyIdentifier,
WorkerId: workerId,
},
}
if &opts.withWorkerKeys != nil {
l.WorkerSigningPubKey = opts.withWorkerKeys.workerSigningPubKey
l.WorkerEncryptionPubKey = opts.withWorkerKeys.workerEncryptionPubKey
}
if &opts.withControllerEncryptionPrivateKey != nil {
l.ControllerEncryptionPrivKey = opts.withControllerEncryptionPrivateKey
}
if opts.withKeyId != "" {
l.KeyId = opts.withKeyId
}
if opts.withNonce != nil {
l.Nonce = opts.withNonce
}
return l, nil
}
func allocWorkerAuth() *WorkerAuth {
return &WorkerAuth{
WorkerAuth: &store.WorkerAuth{},
}
}
func (w *WorkerAuth) clone() *WorkerAuth {
cp := proto.Clone(w.WorkerAuth)
return &WorkerAuth{
WorkerAuth: cp.(*store.WorkerAuth),
}
}
// Validate is called before storing a WorkerAuth in the db
func (w *WorkerAuth) ValidateNewWorkerAuth(ctx context.Context) error {
const op = "server.(WorkerAuth).validateNewWorkerAuth"
if w.WorkerKeyIdentifier == "" {
return errors.New(ctx, errors.InvalidParameter, op, "missing WorkerKeyIdentifier")
}
if w.WorkerId == "" {
return errors.New(ctx, errors.InvalidParameter, op, "missing WorkerId")
}
if w.WorkerSigningPubKey == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing WorkerSigningPubKey")
}
if w.WorkerEncryptionPubKey == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing WorkerEncryptionPubKey")
}
if w.ControllerEncryptionPrivKey == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing ControllerEncryptionPrivKey")
}
if w.KeyId == "" {
return errors.New(ctx, errors.InvalidParameter, op, "missing KeyId")
}
if w.Nonce == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing Nonce")
}
return nil
}
// TableName returns the table name.
func (w *WorkerAuth) TableName() string {
if w.tableName != "" {
return w.tableName
}
return "worker_auth_authorized"
}
// SetTableName sets the table name.
func (w *WorkerAuth) SetTableName(n string) {
w.tableName = n
}
// WorkerCertBundle contains all fields related to a WorkerCertBundle resource
// This includes the serial number of the issuing CA, the worker id, and the certificate bundles issued by the CA
type WorkerCertBundle struct {
*store.WorkerCertBundle
tableName string `gorm:"-"`
}
func newWorkerCertBundle(ctx context.Context, certificatePublicKey []byte, workerKeyIdentifier string, certBundle []byte) (*WorkerCertBundle, error) {
const op = "server.newWorkerCertBundle"
if certificatePublicKey == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no certificatePublicKey")
}
if workerKeyIdentifier == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no workerKeyIdentifier")
}
if certBundle == nil || len(certBundle) == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "empty certBundle")
}
l := &WorkerCertBundle{
WorkerCertBundle: &store.WorkerCertBundle{
RootCertificatePublicKey: certificatePublicKey,
WorkerKeyIdentifier: workerKeyIdentifier,
CertBundle: certBundle,
},
}
return l, nil
}
func allocWorkerCertBundle() *WorkerCertBundle {
return &WorkerCertBundle{
WorkerCertBundle: &store.WorkerCertBundle{},
}
}
func (w *WorkerCertBundle) clone() *WorkerCertBundle {
cp := proto.Clone(w.WorkerCertBundle)
return &WorkerCertBundle{
WorkerCertBundle: cp.(*store.WorkerCertBundle),
}
}
// Validate is called before storing a WorkerCertBundle in the db
func (w *WorkerCertBundle) ValidateNewWorkerCertBundle(ctx context.Context) error {
const op = "server.(WorkerAuth).validateNewWorkerCertBundle"
if w.RootCertificatePublicKey == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing CertificatePublicKey")
}
if w.WorkerKeyIdentifier == "" {
return errors.New(ctx, errors.InvalidParameter, op, "missing WorkerKeyIdentifier")
}
if w.CertBundle == nil {
return errors.New(ctx, errors.InvalidParameter, op, "missing certificate bundle")
}
return nil
}
// TableName returns the table name.
func (w *WorkerCertBundle) TableName() string {
if w.tableName != "" {
return w.tableName
}
return "worker_auth_certificate_bundle"
}
// SetTableName sets the table name.
func (w *WorkerCertBundle) SetTableName(n string) {
w.tableName = n
}
+26
View File
@@ -0,0 +1,26 @@
package server
// A Tag is a custom key/value pair which can be attached to a Worker.
// Multiple Tags may contain the same key and different values in which
// case both key/value pairs are valid. Tags can be sourced from either the
// worker's configuration or the api. key/value pairs can be the same from
// different sources.
type Tag struct {
Key string
Value string
}
type TagSource string
const (
ConfigurationTagSource TagSource = "configuration"
ApiTagSource TagSource = "api"
)
func (t TagSource) isValid() bool {
return t == ConfigurationTagSource || t == ApiTagSource
}
func (t TagSource) String() string {
return string(t)
}
+108
View File
@@ -0,0 +1,108 @@
package server
import (
"context"
"testing"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/server/store"
"github.com/stretchr/testify/assert"
)
func TestWorkerTags_Create(t *testing.T) {
t.Parallel()
conn, _ := db.TestSetup(t, "postgres")
wrapper := db.TestWrapper(t)
rw := db.New(conn)
worker := TestKmsWorker(t, conn, wrapper)
tests := []struct {
name string
want *store.WorkerTag
wantCreateErr bool
}{
{
name: "success api source",
want: &store.WorkerTag{
WorkerId: worker.GetPublicId(),
Key: "key",
Value: "value",
Source: ApiTagSource.String(),
},
},
{
name: "success config source",
want: &store.WorkerTag{
WorkerId: worker.GetPublicId(),
Key: "key",
Value: "value",
Source: ConfigurationTagSource.String(),
},
},
{
name: "unknown source",
want: &store.WorkerTag{
WorkerId: worker.GetPublicId(),
Key: "key",
Value: "value",
Source: "unknown",
},
wantCreateErr: true,
},
{
name: "no source",
want: &store.WorkerTag{
WorkerId: worker.GetPublicId(),
Key: "key",
Value: "value",
},
wantCreateErr: true,
},
{
name: "bad worker id",
want: &store.WorkerTag{
WorkerId: "w_badworkeridthatdoesntexist",
Key: "key",
Value: "value",
},
wantCreateErr: true,
},
{
name: "missing worker id",
want: &store.WorkerTag{
Key: "key",
Value: "value",
},
wantCreateErr: true,
},
{
name: "missing key",
want: &store.WorkerTag{
WorkerId: worker.GetPublicId(),
Value: "value",
},
wantCreateErr: true,
},
{
name: "missing value",
want: &store.WorkerTag{
WorkerId: worker.GetPublicId(),
Key: "key",
},
wantCreateErr: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
err := rw.Create(context.Background(), tt.want)
if tt.wantCreateErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
+785
View File
@@ -0,0 +1,785 @@
package server
import (
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/db/timestamp"
"github.com/hashicorp/boundary/internal/iam"
"github.com/hashicorp/boundary/internal/server/store"
"github.com/hashicorp/boundary/internal/types/scope"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/timestamppb"
)
func TestWorkerCanonicalTags(t *testing.T) {
w := NewWorker(scope.Global.String())
w.apiTags = []*Tag{
{Key: "key", Value: "apis unique"},
{Key: "key", Value: "shared"},
{Key: "key2", Value: "apis key2 unique"},
}
w.configTags = []*Tag{
{Key: "key", Value: "configs unique"},
{Key: "key", Value: "shared"},
{Key: "key3", Value: "configs key3 unique"},
}
got := w.CanonicalTags()
assert.Len(t, got, 3, "2 keys expected, 'key' and 'key2'")
assert.ElementsMatch(t, got["key"], []string{"shared", "apis unique", "configs unique"})
assert.ElementsMatch(t, got["key2"], []string{"apis key2 unique"})
assert.ElementsMatch(t, got["key3"], []string{"configs key3 unique"})
}
func TestWorkerAggregate(t *testing.T) {
t.Parallel()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
ctx := context.Background()
getAggWorker := func(id string) *Worker {
agg := &workerAggregate{PublicId: id}
require.NoError(t, rw.LookupById(ctx, agg))
got, err := agg.toWorker(ctx)
assert.NoError(t, err)
return got
}
t.Run("kms worker", func(t *testing.T) {
id, err := newWorkerId(ctx)
require.NoError(t, err)
id = strings.ToLower(id)
w := NewWorker(scope.Global.String(),
WithName(id),
WithAddress("address"))
w.Type = KmsWorkerType.String()
w.PublicId = id
require.NoError(t, rw.Create(ctx, w))
got := getAggWorker(id)
assert.Equal(t, KmsWorkerType.String(), got.GetType())
assert.Equal(t, id, got.GetPublicId())
assert.Equal(t, scope.Global.String(), got.GetScopeId())
assert.Equal(t, id, got.GetName())
assert.Equal(t, "address", got.GetAddress())
assert.Equal(t, uint32(1), got.GetVersion())
assert.NotNil(t, got.GetLastStatusTime())
assert.Empty(t, got.CanonicalTags())
})
// Worker with status
t.Run("Worker with status", func(t *testing.T) {
id, err := newWorkerId(ctx)
require.NoError(t, err)
w := NewWorker(scope.Global.String(),
WithAddress("address"),
WithName(strings.ToLower(id)))
w.Type = KmsWorkerType.String()
w.PublicId = id
require.NoError(t, rw.Create(ctx, w))
got := getAggWorker(id)
assert.Equal(t, id, got.GetPublicId())
assert.Equal(t, uint32(1), got.GetVersion())
assert.NotNil(t, got.GetLastStatusTime())
assert.Equal(t, strings.ToLower(id), got.GetName())
assert.Equal(t, "address", got.GetAddress())
})
t.Run("Worker with a config tag", func(t *testing.T) {
id, err := newWorkerId(ctx)
require.NoError(t, err)
w := NewWorker(scope.Global.String(),
WithAddress("address"),
WithName(strings.ToLower(id)))
w.Type = KmsWorkerType.String()
w.PublicId = id
require.NoError(t, rw.Create(ctx, w))
require.NoError(t, rw.Create(ctx,
&store.WorkerTag{
WorkerId: id,
Key: "key",
Value: "val",
Source: ConfigurationTagSource.String(),
}))
got := getAggWorker(id)
assert.Equal(t, id, got.GetPublicId())
assert.Equal(t, uint32(1), got.GetVersion())
assert.NotNil(t, got.GetLastStatusTime())
assert.Empty(t, got.apiTags)
assert.Equal(t, got.configTags, []*Tag{{Key: "key", Value: "val"}})
})
t.Run("Worker with many config tag", func(t *testing.T) {
id, err := newWorkerId(ctx)
require.NoError(t, err)
w := NewWorker(scope.Global.String(),
WithAddress("address"),
WithName(strings.ToLower(id)))
w.Type = KmsWorkerType.String()
w.PublicId = id
require.NoError(t, rw.Create(ctx, w))
require.NoError(t, rw.Create(ctx, &store.WorkerTag{
WorkerId: id,
Key: "key",
Value: "val",
Source: ConfigurationTagSource.String(),
}))
require.NoError(t, rw.Create(ctx, &store.WorkerTag{
WorkerId: id,
Key: "key",
Value: "val2",
Source: ConfigurationTagSource.String(),
}))
require.NoError(t, rw.Create(ctx, &store.WorkerTag{
WorkerId: id,
Key: "key2",
Value: "val2",
Source: ConfigurationTagSource.String(),
}))
got := getAggWorker(id)
require.NotNil(t, got.GetLastStatusTime())
assert.Empty(t, got.apiTags)
assert.ElementsMatch(t, got.configTags, []*Tag{
{Key: "key", Value: "val"},
{Key: "key", Value: "val2"},
{Key: "key2", Value: "val2"},
})
})
t.Run("Worker with an api tag", func(t *testing.T) {
id, err := newWorkerId(ctx)
require.NoError(t, err)
w := NewWorker(scope.Global.String(),
WithAddress("address"),
WithName(strings.ToLower(id)))
w.Type = KmsWorkerType.String()
w.PublicId = id
require.NoError(t, rw.Create(ctx, w))
require.NoError(t, rw.Create(ctx,
&store.WorkerTag{
WorkerId: id,
Key: "key",
Value: "val",
Source: ApiTagSource.String(),
}))
got := getAggWorker(id)
assert.Equal(t, id, got.GetPublicId())
assert.Equal(t, uint32(1), got.GetVersion())
assert.NotNil(t, got.GetLastStatusTime())
assert.Empty(t, got.GetConfigTags())
assert.Equal(t, got.apiTags, []*Tag{{Key: "key", Value: "val"}})
})
// Worker with mix of tag sources
t.Run("Worker with mix of tag sources", func(t *testing.T) {
id, err := newWorkerId(ctx)
require.NoError(t, err)
w := NewWorker(scope.Global.String(),
WithAddress("address"),
WithName(strings.ToLower(id)))
w.Type = KmsWorkerType.String()
w.PublicId = id
require.NoError(t, rw.Create(ctx, w))
require.NoError(t, rw.Create(ctx, &store.WorkerTag{
WorkerId: id,
Key: "key",
Value: "val",
Source: ConfigurationTagSource.String(),
}))
require.NoError(t, rw.Create(ctx, &store.WorkerTag{
WorkerId: id,
Key: "key",
Value: "val2",
Source: ApiTagSource.String(),
}))
require.NoError(t, rw.Create(ctx, &store.WorkerTag{
WorkerId: id,
Key: "key2",
Value: "val2",
Source: ApiTagSource.String(),
}))
got := getAggWorker(id)
require.NotNil(t, got.GetLastStatusTime())
assert.ElementsMatch(t, got.apiTags, []*Tag{
{Key: "key", Value: "val2"},
{Key: "key2", Value: "val2"},
})
assert.ElementsMatch(t, got.configTags, []*Tag{
{Key: "key", Value: "val"},
})
})
}
func TestWorker_Update(t *testing.T) {
t.Parallel()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
ctx := context.Background()
newId := func() string {
id, err := newWorkerId(ctx)
require.NoError(t, err)
return id
}
cases := []struct {
name string
initial Worker
update Worker
mask []string
nullMask []string
assert func(t *testing.T, init, up *Worker)
wantUpdateError bool
}{
{
name: "kms update address",
initial: Worker{
Worker: &store.Worker{
Type: KmsWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "kms update address",
Address: "kms update address",
},
},
update: Worker{
Worker: &store.Worker{
Address: "updated kms update address",
},
},
mask: []string{"Address"},
assert: func(t *testing.T, init, up *Worker) {
t.Helper()
assert.Equal(t, "kms update address", up.Name)
assert.Equal(t, "updated kms update address", up.Address)
assert.Greater(t, up.GetUpdateTime().AsTime(), up.GetCreateTime().AsTime())
assert.Equal(t, up.GetLastStatusTime().AsTime(), up.GetUpdateTime().AsTime())
},
},
{
name: "kms update name",
initial: Worker{
Worker: &store.Worker{
Type: KmsWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "kms update name",
Address: "kms update name",
},
},
update: Worker{
Worker: &store.Worker{
Name: "updated kms update name",
},
},
mask: []string{"Name"},
wantUpdateError: true,
},
{
name: "kms clear name",
initial: Worker{
Worker: &store.Worker{
Type: KmsWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "kms clear name",
Address: "kms clear name",
},
},
update: Worker{
Worker: &store.Worker{},
},
nullMask: []string{"Name"},
wantUpdateError: true,
},
{
name: "pki update address",
initial: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "pki update address",
},
},
update: Worker{
Worker: &store.Worker{
Address: "updated pki update address",
},
},
mask: []string{"Address"},
assert: func(t *testing.T, init, up *Worker) {
t.Helper()
assert.Equal(t, "pki update address", up.Name)
assert.Equal(t, "updated pki update address", up.Address)
assert.Greater(t, up.GetUpdateTime().AsTime(), up.GetCreateTime().AsTime())
assert.Equal(t, up.GetLastStatusTime().AsTime(), up.GetUpdateTime().AsTime())
},
},
{
name: "pki update name",
initial: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "pki update name",
},
},
update: Worker{
Worker: &store.Worker{
Name: "updated pki update name",
},
},
mask: []string{"Name"},
assert: func(t *testing.T, init, up *Worker) {
t.Helper()
assert.Equal(t, "updated pki update name", up.Name)
assert.Greater(t, up.GetUpdateTime().AsTime(), up.GetCreateTime().AsTime())
assert.Nil(t, up.GetLastStatusTime())
},
},
{
name: "pki update description",
initial: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "pki update description",
},
},
update: Worker{
Worker: &store.Worker{
Description: "updated pki update description",
},
},
mask: []string{"Description"},
assert: func(t *testing.T, init, up *Worker) {
t.Helper()
assert.Equal(t, "pki update description", up.Name)
assert.Equal(t, "updated pki update description", up.Description)
assert.Greater(t, up.GetUpdateTime().AsTime(), up.GetCreateTime().AsTime())
assert.Nil(t, up.GetLastStatusTime())
},
},
{
name: "pki clear address",
initial: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "pki clear address",
Address: "pki clear address",
LastStatusTime: &timestamp.Timestamp{Timestamp: timestamppb.New(time.Now().Add(time.Hour))},
},
},
update: Worker{
Worker: &store.Worker{},
},
nullMask: []string{"Address"},
wantUpdateError: true,
},
{
name: "pki clear name",
initial: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "pki clear name",
Address: "pki clear name",
LastStatusTime: &timestamp.Timestamp{Timestamp: timestamppb.New(time.Now().Add(time.Hour))},
},
},
update: Worker{
Worker: &store.Worker{},
},
nullMask: []string{"Name"},
assert: func(t *testing.T, init, up *Worker) {
t.Helper()
assert.Empty(t, up.Name)
assert.Greater(t, up.GetUpdateTime().AsTime(), up.GetCreateTime().AsTime())
assert.Greater(t, up.GetLastStatusTime().AsTime(), up.GetUpdateTime().AsTime())
assert.Less(t, up.GetLastStatusTime().AsTime(), time.Now().Add(time.Hour))
},
},
{
name: "pki update name to capital",
initial: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "pki update name to capital",
},
},
update: Worker{
Worker: &store.Worker{
Name: "PKI Update Name To Capital",
},
},
mask: []string{"Name"},
wantUpdateError: true,
},
{
name: "pki update name to unprintable",
initial: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "worker reported update name to unprintable",
},
},
update: Worker{
Worker: &store.Worker{
Name: "unprintable \u0008 name",
},
},
mask: []string{"Name"},
wantUpdateError: true,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
init := tc.initial.clone()
require.NoError(t, rw.Create(ctx, init))
up := tc.update.clone()
up.PublicId = init.PublicId
_, err := rw.Update(ctx, up, tc.mask, tc.nullMask)
if tc.wantUpdateError {
fmt.Println(err)
assert.Error(t, err)
return
} else {
require.NoError(t, err)
}
tc.assert(t, init.clone(), up.clone())
})
}
}
func TestWorker_Create(t *testing.T) {
t.Parallel()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
ctx := context.Background()
newId := func() string {
id, err := newWorkerId(ctx)
require.NoError(t, err)
return id
}
type wanted struct {
lastStatusUpdated bool
createError bool
}
cases := []struct {
name string
in Worker
want wanted
}{
{
name: "kms base",
in: Worker{
Worker: &store.Worker{
Type: KmsWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Address: "address",
Name: "kms base",
Description: "kms base",
},
},
want: wanted{lastStatusUpdated: true},
},
{
name: "kms with no name field",
in: Worker{
Worker: &store.Worker{
Type: KmsWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Address: "address",
},
},
want: wanted{createError: true},
},
{
name: "kms with no address field",
in: Worker{
Worker: &store.Worker{
Type: KmsWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "kms with no address field",
},
},
want: wanted{createError: true},
},
{
name: "kms with upper case name",
in: Worker{
Worker: &store.Worker{
Type: KmsWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "With Upper Case Worker Reported Name",
Address: "address",
},
},
want: wanted{createError: true},
},
{
name: "kms with unprintable worker reported name",
in: Worker{
Worker: &store.Worker{
Type: KmsWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "unprintable \u0008 worker reported name",
Address: "address",
},
},
want: wanted{createError: true},
},
// PKI workers are not created in a way that should set the address
// or the last_status_time.
{
name: "pki base",
in: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "pki base",
},
},
want: wanted{},
},
{
name: "pki with no name field",
in: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
},
},
want: wanted{},
},
{
name: "pki with address field",
in: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Address: "address",
},
},
want: wanted{createError: true},
},
{
name: "pki with upper case name",
in: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "PKI With Upper Case Worker Reported Name",
Address: "address",
},
},
want: wanted{createError: true},
},
{
name: "pki with unprintable worker reported name",
in: Worker{
Worker: &store.Worker{
Type: PkiWorkerType.String(),
ScopeId: scope.Global.String(),
PublicId: newId(),
Name: "unprintable \u0008 worker reported name",
Address: "address",
},
},
want: wanted{createError: true},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
w := tc.in.clone()
err := rw.Create(ctx, w)
if tc.want.createError {
assert.Error(t, err)
return
} else {
assert.NoError(t, err)
}
if tc.want.lastStatusUpdated {
assert.NotNil(t, w.GetLastStatusTime())
} else {
assert.Nil(t, w.GetLastStatusTime())
}
assert.NotNil(t, w.GetCreateTime())
assert.Equal(t, w.GetCreateTime(), w.GetUpdateTime())
})
}
}
func TestWorker_New(t *testing.T) {
t.Parallel()
conn, _ := db.TestSetup(t, "postgres")
wrapper := db.TestWrapper(t)
org, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
type args struct {
scopeId string
opts []Option
}
tests := []struct {
name string
args args
want *Worker
}{
{
name: "missing-scope-id",
args: args{},
want: &Worker{
Worker: &store.Worker{},
},
},
{
name: "global-scope-id",
args: args{
scopeId: scope.Global.String(),
},
want: &Worker{
Worker: &store.Worker{
ScopeId: scope.Global.String(),
},
},
},
{
name: "org-scope-id",
args: args{
scopeId: org.GetPublicId(),
},
want: &Worker{
Worker: &store.Worker{
ScopeId: org.GetPublicId(),
},
},
},
{
name: "project-scope-id",
args: args{
scopeId: prj.GetPublicId(),
},
want: &Worker{
Worker: &store.Worker{
ScopeId: prj.GetPublicId(),
},
},
},
{
name: "with name",
args: args{
scopeId: scope.Global.String(),
opts: []Option{
WithName("foo"),
},
},
want: &Worker{
Worker: &store.Worker{
ScopeId: scope.Global.String(),
Name: "foo",
},
},
},
{
name: "with description",
args: args{
scopeId: scope.Global.String(),
opts: []Option{
WithDescription("foo"),
},
},
want: &Worker{
Worker: &store.Worker{
ScopeId: scope.Global.String(),
Description: "foo",
},
},
},
{
name: "with address",
args: args{
scopeId: scope.Global.String(),
opts: []Option{
WithAddress("foo"),
},
},
want: &Worker{
Worker: &store.Worker{
ScopeId: scope.Global.String(),
Address: "foo",
},
},
},
{
name: "with Tags",
args: args{
scopeId: scope.Global.String(),
opts: []Option{
WithWorkerTags(&Tag{
Key: "key",
Value: "val",
}),
},
},
want: &Worker{
Worker: &store.Worker{
ScopeId: scope.Global.String(),
},
inputTags: []*Tag{
{
Key: "key",
Value: "val",
},
},
},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
assert := assert.New(t)
got := NewWorker(tt.args.scopeId, tt.args.opts...)
assert.Empty(cmp.Diff(tt.want, got.clone(), protocmp.Transform()))
})
}
}
+532
View File
@@ -0,0 +1,532 @@
package server
import (
"context"
"math/rand"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"google.golang.org/protobuf/testing/protocmp"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/db/timestamp"
"github.com/hashicorp/boundary/internal/iam"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/server/store"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
)
func TestRootCertStore(t *testing.T) {
t.Parallel()
ctx := context.Background()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
org, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
kmsCache := kms.TestKms(t, conn, wrapper)
databaseWrapper, err := kmsCache.GetWrapper(context.Background(), org.PublicId, kms.KeyPurposeDatabase)
require.NoError(t, err)
testKey, err := databaseWrapper.KeyId(ctx)
require.NoError(t, err)
beforeTimestamp := &timestamp.Timestamp{Timestamp: timestamppb.New(time.Now().Add(-1 * time.Hour))}
afterTimestamp := &timestamp.Timestamp{Timestamp: timestamppb.New(time.Now().Add(1 * time.Hour))}
publicKey := populateBytes(defaultLength)
privateKey := populateBytes(defaultLength)
certificate := populateBytes(defaultLength)
type args struct {
serialNumber uint64
certificate []byte
rootCertKeys RootCertificateKeys
notValidBefore *timestamp.Timestamp
notValidAfter *timestamp.Timestamp
keyId string
state CertificateState
}
tests := []struct {
name string
args args
expectedRootCert *store.RootCertificate
wantErr bool
wantCreateErr bool
}{
{
name: "rootcert-store-next",
args: args{
serialNumber: 1234567890,
rootCertKeys: RootCertificateKeys{publicKey: publicKey, privateKey: privateKey},
certificate: certificate,
notValidBefore: beforeTimestamp,
notValidAfter: afterTimestamp,
keyId: testKey,
state: NextState,
},
expectedRootCert: &store.RootCertificate{
SerialNumber: 1234567890,
PublicKey: publicKey,
PrivateKey: privateKey,
Certificate: certificate,
NotValidBefore: beforeTimestamp,
NotValidAfter: afterTimestamp,
KeyId: testKey,
State: "next",
IssuingCa: ca_id,
},
wantErr: false,
},
{
name: "rootcert-store-current",
args: args{
serialNumber: 9876543210,
rootCertKeys: RootCertificateKeys{publicKey: publicKey, privateKey: privateKey},
certificate: certificate,
notValidBefore: beforeTimestamp,
notValidAfter: afterTimestamp,
keyId: testKey,
state: CurrentState,
},
expectedRootCert: &store.RootCertificate{
SerialNumber: 9876543210,
PublicKey: publicKey,
PrivateKey: privateKey,
Certificate: certificate,
NotValidBefore: beforeTimestamp,
NotValidAfter: afterTimestamp,
KeyId: testKey,
State: "current",
IssuingCa: ca_id,
},
wantErr: false,
},
{
name: "rootcert-store-empty-key",
args: args{
serialNumber: 9876543210,
rootCertKeys: RootCertificateKeys{publicKey: populateBytes(0), privateKey: privateKey},
certificate: certificate,
notValidBefore: beforeTimestamp,
notValidAfter: afterTimestamp,
keyId: testKey,
state: NextState,
},
wantErr: true,
},
{
name: "rootcert-no-keys",
args: args{
serialNumber: 1011121314,
certificate: certificate,
notValidBefore: beforeTimestamp,
notValidAfter: afterTimestamp,
keyId: testKey,
state: NextState,
},
wantErr: true,
},
{
name: "rootcert-no-cert",
args: args{
serialNumber: 15161718,
rootCertKeys: RootCertificateKeys{publicKey: publicKey, privateKey: privateKey},
notValidBefore: beforeTimestamp,
notValidAfter: afterTimestamp,
keyId: testKey,
state: NextState,
},
wantErr: true,
},
{
name: "rootcert-invalid-timestamps",
args: args{
serialNumber: 1920212223,
rootCertKeys: RootCertificateKeys{publicKey: publicKey, privateKey: privateKey},
certificate: certificate,
notValidBefore: afterTimestamp,
notValidAfter: beforeTimestamp,
keyId: testKey,
state: NextState,
},
wantCreateErr: true,
},
{
name: "rootcert-invalid-timestamps-2",
args: args{
serialNumber: 2425262728,
rootCertKeys: RootCertificateKeys{publicKey: publicKey, privateKey: privateKey},
certificate: certificate,
notValidBefore: afterTimestamp,
notValidAfter: afterTimestamp,
keyId: testKey,
state: NextState,
},
wantCreateErr: true,
},
{
name: "rootcert-invalid-state",
args: args{
serialNumber: 3031323334,
rootCertKeys: RootCertificateKeys{publicKey: publicKey, privateKey: privateKey},
certificate: certificate,
notValidBefore: beforeTimestamp,
notValidAfter: afterTimestamp,
keyId: testKey,
state: UnknownState,
},
wantErr: true,
},
{
name: "rootcert-no-key-id",
args: args{
serialNumber: 4041424344,
rootCertKeys: RootCertificateKeys{publicKey: publicKey, privateKey: privateKey},
certificate: certificate,
notValidBefore: beforeTimestamp,
notValidAfter: afterTimestamp,
state: NextState,
},
wantErr: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
cert, err := newRootCertificate(ctx, tt.args.serialNumber, tt.args.certificate, tt.args.notValidBefore, tt.args.notValidAfter,
tt.args.rootCertKeys, tt.args.keyId, tt.args.state)
if tt.wantErr {
assert.Error(err)
return
}
require.NoError(err)
require.NotNil(cert)
err = rw.Create(ctx, cert)
if tt.wantCreateErr {
assert.Error(err)
return
} else {
assert.NoError(err)
assert.Equal(tt.expectedRootCert, cert.RootCertificate)
assert.Empty(cmp.Diff(tt.expectedRootCert, cert, protocmp.Transform()))
}
deleteWhere := `state = ?`
deleted, err := rw.Delete(ctx, &RootCertificate{}, db.WithWhere(deleteWhere, cert.State))
assert.NoError(err)
assert.Equal(1, deleted)
})
}
}
func TestDuplicateRootCert(t *testing.T) {
t.Parallel()
ctx := context.Background()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
org, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
kmsCache := kms.TestKms(t, conn, wrapper)
databaseWrapper, err := kmsCache.GetWrapper(context.Background(), org.PublicId, kms.KeyPurposeDatabase)
require.NoError(t, err)
testKey, err := databaseWrapper.KeyId(ctx)
require.NoError(t, err)
beforeTimestamp := &timestamp.Timestamp{Timestamp: timestamppb.New(time.Now().Add(-1 * time.Hour))}
afterTimestamp := &timestamp.Timestamp{Timestamp: timestamppb.New(time.Now().Add(1 * time.Hour))}
// Attempt to create a duplicate CA and expect a failure
certAuthority := newCertificateAuthority()
err = rw.Create(ctx, certAuthority)
require.Error(t, err)
// Make two current and next root certs
current1, err := newRootCertificate(ctx, rand.Uint64(), populateBytes(defaultLength), beforeTimestamp, afterTimestamp,
RootCertificateKeys{publicKey: populateBytes(defaultLength), privateKey: populateBytes(defaultLength)},
testKey, CurrentState)
require.NoError(t, err)
current2, err := newRootCertificate(ctx, rand.Uint64(), populateBytes(defaultLength), beforeTimestamp, afterTimestamp,
RootCertificateKeys{publicKey: populateBytes(defaultLength), privateKey: populateBytes(defaultLength)},
testKey, CurrentState)
require.NoError(t, err)
next1, err := newRootCertificate(ctx, rand.Uint64(), populateBytes(defaultLength), beforeTimestamp, afterTimestamp,
RootCertificateKeys{publicKey: populateBytes(defaultLength), privateKey: populateBytes(defaultLength)},
testKey, NextState)
require.NoError(t, err)
next2, err := newRootCertificate(ctx, rand.Uint64(), populateBytes(defaultLength), beforeTimestamp, afterTimestamp,
RootCertificateKeys{publicKey: populateBytes(defaultLength), privateKey: populateBytes(defaultLength)},
testKey, NextState)
require.NoError(t, err)
// Insert first set of certs
err = rw.Create(ctx, current1)
require.NoError(t, err)
err = rw.Create(ctx, next1)
require.NoError(t, err)
// Insert second current cert and expect an error
err = rw.Create(ctx, current2)
require.Error(t, err)
err = rw.Create(ctx, next2)
require.Error(t, err)
}
func TestWorkerAuthStore(t *testing.T) {
t.Parallel()
ctx := context.Background()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
org, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
kmsCache := kms.TestKms(t, conn, wrapper)
databaseWrapper, err := kmsCache.GetWrapper(context.Background(), org.PublicId, kms.KeyPurposeDatabase)
require.NoError(t, err)
testKey, err := databaseWrapper.KeyId(ctx)
require.NoError(t, err)
worker := TestPkiWorker(t, conn, wrapper)
wSignPubKey := populateBytes(defaultLength)
wEncPubKey := populateBytes(defaultLength)
workerKeys := WorkerKeys{workerSigningPubKey: wSignPubKey, workerEncryptionPubKey: wEncPubKey}
controllerKey := populateBytes(defaultLength)
nonce := populateBytes(defaultLength)
type args struct {
workerKeyIdentifier string
workerId string
}
tests := []struct {
name string
args args
expectedWorkerAuth *store.WorkerAuth
opt []Option
wantErr bool
wantCreateErr bool
}{
{
name: "workerauth-store",
args: args{
workerKeyIdentifier: "worker-auth-id-123",
workerId: worker.PublicId,
},
opt: []Option{
WithWorkerKeys(workerKeys),
WithControllerEncryptionPrivateKey(controllerKey),
WithNonce(nonce),
WithKeyId(testKey),
},
expectedWorkerAuth: &store.WorkerAuth{
WorkerKeyIdentifier: "worker-auth-id-123",
WorkerId: worker.PublicId,
WorkerSigningPubKey: wSignPubKey,
WorkerEncryptionPubKey: wEncPubKey,
ControllerEncryptionPrivKey: controllerKey,
KeyId: testKey,
Nonce: nonce,
},
wantErr: false,
},
{
name: "workerauth-store-invalid-key-id",
args: args{
workerKeyIdentifier: "worker-auth-id-456",
workerId: worker.PublicId,
},
opt: []Option{
WithWorkerKeys(workerKeys),
WithControllerEncryptionPrivateKey(controllerKey),
WithNonce(nonce),
WithKeyId("fakeyityfake"),
},
wantCreateErr: true,
},
{
name: "workerauth-no-pkey",
args: args{
workerId: worker.PublicId,
},
opt: []Option{
WithWorkerKeys(workerKeys),
WithControllerEncryptionPrivateKey(controllerKey),
WithNonce(nonce),
WithKeyId(testKey),
},
wantErr: true,
},
{
name: "workerauth-empty-pkey",
args: args{
workerKeyIdentifier: "",
workerId: worker.PublicId,
},
opt: []Option{
WithWorkerKeys(workerKeys),
WithControllerEncryptionPrivateKey(controllerKey),
WithNonce(nonce),
WithKeyId(testKey),
},
wantErr: true,
},
{
name: "workerauth-invalid-workerid",
args: args{
workerKeyIdentifier: "worker-auth-id-101",
workerId: "bogus-worker",
},
opt: []Option{
WithWorkerKeys(workerKeys),
WithControllerEncryptionPrivateKey(controllerKey),
WithNonce(nonce),
WithKeyId(testKey),
},
wantCreateErr: true,
},
{
name: "empty-workerauth",
args: args{},
wantErr: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
wAuth, err := newWorkerAuth(ctx, tt.args.workerKeyIdentifier, tt.args.workerId, tt.opt...)
if tt.wantErr {
assert.Error(err)
return
}
require.NoError(err)
require.NotNil(wAuth)
err = rw.Create(ctx, wAuth)
if tt.wantCreateErr {
assert.Error(err)
} else {
assert.NoError(err)
assert.Equal(tt.expectedWorkerAuth, wAuth.WorkerAuth)
assert.Empty(cmp.Diff(tt.expectedWorkerAuth, wAuth, protocmp.Transform()))
}
})
}
}
func TestWorkerCertBundle(t *testing.T) {
t.Parallel()
ctx := context.Background()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
testKey := TestKmsKey(ctx, t, conn, wrapper)
worker := TestPkiWorker(t, conn, wrapper)
workerAuth := TestWorkerAuth(t, conn, worker, testKey)
rootCA := TestRootCertificate(ctx, t, conn, testKey)
certBundle := populateBytes(defaultLength)
type args struct {
certificatePubKey []byte
workerAuthId string
certificateBundle []byte
}
tests := []struct {
name string
args args
expected *store.WorkerCertBundle
wantErr bool
wantCreateErr bool
}{
{
name: "workercertbundle-store",
args: args{
certificatePubKey: rootCA.PublicKey,
workerAuthId: workerAuth.WorkerKeyIdentifier,
certificateBundle: certBundle,
},
expected: &store.WorkerCertBundle{
RootCertificatePublicKey: rootCA.PublicKey,
WorkerKeyIdentifier: workerAuth.WorkerKeyIdentifier,
CertBundle: certBundle,
},
wantErr: false,
},
{
name: "workercertbundle-empty-cert-bundle",
args: args{
certificatePubKey: rootCA.PublicKey,
workerAuthId: workerAuth.WorkerKeyIdentifier,
},
wantErr: true,
},
{
name: "workercertbundle-no-worker-id",
args: args{
certificatePubKey: rootCA.PublicKey,
certificateBundle: certBundle,
},
wantErr: true,
},
{
name: "workercertbundle-invalid-worker-id",
args: args{
certificatePubKey: rootCA.PublicKey,
workerAuthId: "bogus-worker",
certificateBundle: certBundle,
},
wantCreateErr: true,
},
{
name: "workercertbundle-empty-publickey",
args: args{
workerAuthId: workerAuth.WorkerKeyIdentifier,
certificateBundle: certBundle,
},
wantErr: true,
},
{
name: "workercertbundle-invalid-publickey",
args: args{
certificatePubKey: populateBytes(defaultLength),
workerAuthId: workerAuth.WorkerKeyIdentifier,
certificateBundle: certBundle,
},
wantCreateErr: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
workerCertBundle, err := newWorkerCertBundle(ctx, tt.args.certificatePubKey, tt.args.workerAuthId, tt.args.certificateBundle)
if tt.wantErr {
assert.Error(err)
return
}
require.NoError(err)
require.NotNil(workerCertBundle)
err = rw.Create(ctx, workerCertBundle)
if tt.wantCreateErr {
assert.Error(err)
} else {
assert.NoError(err)
assert.Equal(tt.expected, workerCertBundle.WorkerCertBundle)
assert.Empty(cmp.Diff(tt.expected, workerCertBundle, protocmp.Transform()))
}
})
}
}