* Key Rotation/Destruction (#2477) * fix: Correct kms.CreateKeys comment This method does not return anything. * feat(kms): Add new ListKeys method The new ListKeys method wraps the underlying KMS wrapper, returning all the keys in the scope specified. * feat(scopes): Add new scope actions for key management Adds list-keys, rotate-keys and revoke-keys actions for scopes. * feat(scopes): Add ListKeys API endpoint This new endpoint lists all keys in a scope * feat(api): Add ListKeys to Scopes client This has to be a custom function because it is a custom action and doesn't map well to any of the existing templates, or generalises well in a way that would make it reasonable to create a new template. * feat(cli): Add new scopes list-keys command * add RotateKeys function to the kms repository * Add Rotate Keys Endpoint to Scopes Api (#2360) * add rotate keys endpoint * add tests for RotateKeys endpoint * remove that one comment I forgot about * addressing more PR comments * Add Rotate Keys CLI Command (#2395) * add cli command and client * add bats tests * fix some info text and pr comments * write a new rotate keys description * Add Missing DEK Foreign Keys (#2408) * add missing fks * mark key as nullable in gorm * update tests to use a new wrapper with a real key_id * fix formatting in test and add keys for auth_token test * replace key values * revert postgres_40_01_test.go * style: reformat sql for readability * refactor: change type of key_id columns to kms_private_id * Store key_id and scope_id with oplog entries, re-type columns referencing data key version (#2431) * fix(db): Correct types of data key version referencers * fix(oplog): Fix missing error handling * feat(oplog): Store key_id and scope_id with oplog entries This migration truncates all existing oplog entries, as migrating existing data would have been complex and likely unnecessary. * Update view references * Always delete oplog entries when dropping keys * Fix rebase issues * Fix sql tests * Add schema for new kms destruction jobs (#2479) * feat: Add schema for new kms destruction jobs The schema lets us manage destruction jobs per-table while providing a guarantee that only one run is running at a time. * Apply suggestions from code review Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com> * Fix table reference and tests Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com> * update domain, api, and cli to all include key versions in outputs (#2472) * update domain, api, and cli to all include key versions in outputs * fix go sum * add migration to fix immutable error * fix final test issue as well as make gen issue * rebase and fix * address johan pr comments * make gen, didn't realize comments were included * update migrations based on new migration 55 file 03 * Move migrations to 56 * feat: Add key version rewrapping function registry (#2478) The new RegisterTableRewrapFn can be used by a domain to register a callback to use when rewrapping data in a specific table name. * feat(kms): Add scopeId to RewrapFn (#2539) This makes it much easier for rewrap functions to look up the correct wrapper and limit the number of rows searched. * Update Root Cert Proto Definition (#2542) * update root cert proto definition to properly identify public_key as the table primary key * add the test fix as well * Rewrap Functions for Encrypted Tables (#2532) * add oidc rewrap * add argon2 config rewrap * add auth token rewrapping * add worker auth cert rewrapping * check the err * add username password credential rewrapping * add ssh private key credential rewrapping * add vault client certificate rewrap function * add host catalog secret rewrap function * cleanup a little * add host vault token rewrap function * add session credential rewrap function * add session rewrap function * add worker auth rewrap function * update test to include full assert gamut * add session rewrap function TEST * bring all tests up to current standards, make more readable, and include full assert gamut * rework all rewrap functions to utilize scope id * update comments, queries, sql refs, etc, in response to PR comments * forgot a comment * remove hmac updates and fix a couple comments again * Rewrapping Registered Tables Test (#2555) * add the registered table test as well as the two missing rewrap functions * address pr comments, add db r/w conversions, cmp.diff, sql comment, remove (now) faulty immutable test * Add ability to list key version destruction jobs, recurring jobs and destroying key versions (#2498) * feat(kms): Add ability to list data key version destruction jobs * feat(scopes): Add ListKeyVersionDestructionJobs * feat(cli): Add list-key-version-destruction-jobs * feat(kms): Add recurring job that performs table rewrapping The new recurring job runs for each job table with a registered rewrapping callback. It attempts to become the running run and start its rewrapping, gracefully handling sudden interruptions by resuming it's work if it finds evidence of sudden interruption. * feat(kms): Add recurring job for destroying key versions The new job monitors the database for data key version destruction jobs that have finished rewrapping all its data, performing the final data key version revocation. * feat(kms): Add DestroyKeyVersion DestroyKeyVersion immediately destroys a key version if it is a root key version or a data key version which encrypts no data. If the data key version encrypts data which needs to be rewrapped, it queues an asynchronous job to complete the rewrapping operation. * feat(scopes): Add DestroyKeyVersion API endpoint * feat(cli): Add scopes destroy-key-version CLI command * Ensure all secret updates include key ID (#2556) * feat(all): Ensure all secret updates include key ID When updating a secret, it is paramount that the key ID is also updated, as it is the only means we have of ensuring that we only destroy keys once there is no more data associated with the key. * Remove fix to session repository for now This breaks the current private key derivation method * add new encrypt/decrypt funcs and made necessary proto changes (#2557) * add new encrypt/decrypt funcs and made necessary proto changes * address all PR comments * fix test panic * add param checking to rewraps * fix(schema): Correctly organize migrations again * Review comments part 1 * Review comments part 2 * Review comments part 3 * Store cert private key, encrypt tofu token (#2583) * fix(session): store cert private key, encrypt tofu token Previously, we would derive a session certificate private key from the session key used in each project, and not store the key. We would also encrypt the tofu token with the database key but not store a reference to this key in the database. This change fixes this by replacing our key derivation with a key generation step, and instead store the generated key, encrypted, in the database. We also ensure that any new tofu tokens are encrypted with the same key. To handle existing sessions, we lazily rewrite the sessions whenever a user lists them. There is a minor risk that a user could end up destroying the database key that encrypts the tofu token before that session has been rewrapped, but this is going to be rare and temporary. * feat(session): Allow the random source for secrets to be configured * Review comments * Minor fixes * More minor fixes * More small fixes Co-authored-by: Danielle Miu <dani.miu@hashicorp.com> Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com> Co-authored-by: Michael Gaffney <mike@gaffney.cc> Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com> * fix(session): Unset session key ID when scope is deleted Unsetting the key ID allows the session to live beyond the lifetime of the scope, while allowing the scope to cascade delete its keys. * fix(migrations): Rewrite migration 56 tests These tests can no longer use the normal test helpers as they try to use the new oplog table structure, so we have to manually write all the interactions. * fix(migrations): Rename migration 58 file name This was the name used in the release branch, update it to the new migration number. * fix(e2e): Add some comments and debug to kms tests * fix(session): Handle empty project and user IDs in read When a project or user is deleted, the session is automatically canceled and the respective field on the session is unset. LookupSession did not handle this case gracefully, and would error on decryption in this state. Skip decrypting sessions that do not have either a user or project to avoid this error. The decrypted values are not used for a canceled session. * Fix worker test * Increase test timeout Co-authored-by: Danielle Miu <dani.miu@hashicorp.com> Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com> Co-authored-by: Michael Gaffney <mike@gaffney.cc> Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
484 lines
16 KiB
Go
484 lines
16 KiB
Go
package oplog
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
|
|
"github.com/golang/protobuf/ptypes/wrappers"
|
|
"github.com/hashicorp/boundary/internal/errors"
|
|
"github.com/hashicorp/boundary/internal/oplog/store"
|
|
"github.com/hashicorp/boundary/internal/util"
|
|
"github.com/hashicorp/go-dbw"
|
|
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
|
|
"github.com/hashicorp/go-kms-wrapping/v2/extras/structwrapping"
|
|
"google.golang.org/protobuf/proto"
|
|
"google.golang.org/protobuf/types/known/structpb"
|
|
)
|
|
|
|
// Version of oplog entries (among other things, it's used to manage upgrade
|
|
// compatibility when replicating)
|
|
//
|
|
// v1: initial version
|
|
// v2: adds the new Message.Opts
|
|
const Version = "v2"
|
|
|
|
// Message wraps a proto.Message with some other bits like operation type,
|
|
// paths and options.
|
|
type Message struct {
|
|
proto.Message
|
|
TypeName string
|
|
OpType OpType
|
|
FieldMaskPaths []string
|
|
SetToNullPaths []string
|
|
Opts []dbw.Option
|
|
}
|
|
|
|
// Entry represents an oplog entry
|
|
type Entry struct {
|
|
*store.Entry
|
|
Wrapper wrapping.Wrapper `gorm:"-"`
|
|
Ticketer Ticketer `gorm:"-"`
|
|
}
|
|
|
|
// Metadata provides meta information about the Entry
|
|
type Metadata map[string][]string
|
|
|
|
// NewEntry creates a new Entry
|
|
func NewEntry(ctx context.Context, aggregateName string, metadata Metadata, wrapper wrapping.Wrapper, ticketer Ticketer) (*Entry, error) {
|
|
const op = "oplog.NewEntry"
|
|
if util.IsNil(wrapper) {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "nil wrapper")
|
|
}
|
|
keyId, err := wrapper.KeyId(ctx)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
entry := Entry{
|
|
Entry: &store.Entry{
|
|
AggregateName: aggregateName,
|
|
Version: Version,
|
|
KeyId: keyId,
|
|
},
|
|
Wrapper: wrapper,
|
|
Ticketer: ticketer,
|
|
}
|
|
if len(metadata) > 0 {
|
|
storeMD := []*store.Metadata{}
|
|
for k, v := range metadata {
|
|
if len(v) > 0 {
|
|
for _, vv := range v {
|
|
storeMD = append(storeMD, &store.Metadata{Key: k, Value: vv})
|
|
}
|
|
continue
|
|
}
|
|
// this metadata just has a key with no values
|
|
storeMD = append(storeMD, &store.Metadata{Key: k})
|
|
}
|
|
entry.Metadata = storeMD
|
|
}
|
|
if err := entry.validate(ctx); err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
return &entry, nil
|
|
}
|
|
|
|
func (e *Entry) validate(ctx context.Context) error {
|
|
const op = "oplog.(Entry).validate"
|
|
if util.IsNil(e.Wrapper) {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "nil wrapper")
|
|
}
|
|
if util.IsNil(e.Ticketer) {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "nil ticketer")
|
|
}
|
|
if e.Entry == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "nil entry")
|
|
}
|
|
if e.Entry.Version == "" {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing entry version")
|
|
}
|
|
if e.Entry.AggregateName == "" {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing entry aggregate name")
|
|
}
|
|
if e.Entry.KeyId == "" {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing entry key id")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UnmarshalData the data attribute from []byte (treated as a FIFO QueueBuffer) to a []proto.Message
|
|
func (e *Entry) UnmarshalData(ctx context.Context, types *TypeCatalog) ([]Message, error) {
|
|
const op = "oplog.(Entry).UnmarshalData"
|
|
if types == nil {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "nil type catalog")
|
|
}
|
|
if len(e.Data) == 0 {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing data")
|
|
}
|
|
msgs := []Message{}
|
|
queue := Queue{
|
|
Buffer: *bytes.NewBuffer(e.Data),
|
|
Catalog: types,
|
|
}
|
|
for {
|
|
item, err := queue.remove(ctx)
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error removing item from queue"))
|
|
}
|
|
name, err := types.GetTypeName(ctx, item.msg)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
dbwOpts, err := convertToDbwOpts(ctx, item.operationOptions)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
msgs = append(msgs, Message{
|
|
Message: item.msg,
|
|
TypeName: name,
|
|
OpType: item.opType,
|
|
FieldMaskPaths: item.fieldMask,
|
|
SetToNullPaths: item.setToNullPaths,
|
|
Opts: dbwOpts,
|
|
})
|
|
}
|
|
return msgs, nil
|
|
}
|
|
|
|
func convertToDbwOpts(ctx context.Context, opts *OperationOptions) ([]dbw.Option, error) {
|
|
const op = "oplog.convertToDbwOpts"
|
|
if opts == nil {
|
|
return []dbw.Option{}, nil
|
|
}
|
|
dbwOpts := []dbw.Option{
|
|
dbw.WithSkipVetForWrite(opts.GetWithSkipVetForWrite()),
|
|
}
|
|
if opts.GetWithVersion() != nil {
|
|
dbwOpts = append(dbwOpts, dbw.WithVersion(&opts.GetWithVersion().Value))
|
|
}
|
|
if opts.GetWithOnConflict() != nil {
|
|
c := &dbw.OnConflict{}
|
|
|
|
switch targetType := opts.GetWithOnConflict().GetTarget().(type) {
|
|
case *WithOnConflict_Columns:
|
|
c.Target = dbw.Columns(opts.GetWithOnConflict().GetColumns().GetNames())
|
|
case *WithOnConflict_Constraint:
|
|
c.Target = dbw.Constraint(opts.GetWithOnConflict().GetConstraint())
|
|
default:
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("not a supported target type: %T", targetType))
|
|
}
|
|
|
|
switch actionType := opts.GetWithOnConflict().GetAction().(type) {
|
|
case *WithOnConflict_DoNothing:
|
|
c.Action = dbw.DoNothing(opts.GetWithOnConflict().GetDoNothing())
|
|
case *WithOnConflict_UpdateAll:
|
|
c.Action = dbw.UpdateAll(opts.GetWithOnConflict().GetUpdateAll())
|
|
case *WithOnConflict_ColumnValues:
|
|
cvAction := make([]dbw.ColumnValue, 0, len(actionType.ColumnValues.GetValues()))
|
|
for _, cv := range actionType.ColumnValues.GetValues() {
|
|
newColVal := dbw.ColumnValue{
|
|
Column: cv.GetName(),
|
|
}
|
|
switch pbVal := cv.Value.(type) {
|
|
case *ColumnValue_Raw:
|
|
newColVal.Value = pbVal.Raw.AsInterface()
|
|
case *ColumnValue_ExprValue:
|
|
expr := dbw.ExprValue{
|
|
Sql: pbVal.ExprValue.GetSql(),
|
|
}
|
|
args := make([]any, 0, len(pbVal.ExprValue.GetArgs()))
|
|
for _, a := range pbVal.ExprValue.GetArgs() {
|
|
args = append(args, a.AsInterface())
|
|
}
|
|
newColVal.Value = expr
|
|
case *ColumnValue_Column:
|
|
newColVal.Value = dbw.Column{
|
|
Name: pbVal.Column.GetName(),
|
|
Table: pbVal.Column.GetTable(),
|
|
}
|
|
default:
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("not a supported column value type: %T", pbVal))
|
|
}
|
|
cvAction = append(cvAction, newColVal)
|
|
}
|
|
c.Action = cvAction
|
|
default:
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("not a supported action type: %T", actionType))
|
|
}
|
|
dbwOpts = append(dbwOpts, dbw.WithOnConflict(c))
|
|
}
|
|
if opts.GetWithWhereClause() != "" {
|
|
sql := opts.GetWithWhereClause()
|
|
args := make([]any, 0, len(opts.GetWithWhereClauseArgs()))
|
|
for _, a := range opts.GetWithWhereClauseArgs() {
|
|
args = append(args, a.AsInterface())
|
|
}
|
|
dbwOpts = append(dbwOpts, dbw.WithWhere(sql, args...))
|
|
|
|
}
|
|
return dbwOpts, nil
|
|
}
|
|
|
|
// convertFromDbwOpts converts dbw options to an OperationalOptions for an Entry
|
|
func convertFromDbwOpts(ctx context.Context, opts dbw.Options) (*OperationOptions, error) {
|
|
const op = "oplog.convertFromDbwOptions"
|
|
pbOpts := &OperationOptions{
|
|
WithSkipVetForWrite: opts.WithSkipVetForWrite,
|
|
WithWhereClause: opts.WithWhereClause,
|
|
}
|
|
if opts.WithVersion != nil {
|
|
pbOpts.WithVersion = &wrappers.UInt32Value{Value: *opts.WithVersion}
|
|
}
|
|
|
|
clauseValues := make([]*structpb.Value, 0, len(opts.WithWhereClauseArgs))
|
|
for _, arg := range opts.WithWhereClauseArgs {
|
|
v, err := structpb.NewValue(arg)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
clauseValues = append(clauseValues, v)
|
|
}
|
|
pbOpts.WithWhereClauseArgs = clauseValues
|
|
|
|
if opts.WithOnConflict != nil {
|
|
c := &WithOnConflict{}
|
|
switch target := opts.WithOnConflict.Target.(type) {
|
|
case dbw.Constraint:
|
|
c.Target = &WithOnConflict_Constraint{string(target)}
|
|
case dbw.Columns:
|
|
c.Target = &WithOnConflict_Columns{
|
|
&Columns{
|
|
Names: []string(target),
|
|
},
|
|
}
|
|
default:
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("not a supported target type: %T", target))
|
|
}
|
|
switch action := opts.WithOnConflict.Action.(type) {
|
|
case dbw.DoNothing:
|
|
c.Action = &WithOnConflict_DoNothing{bool(action)}
|
|
case dbw.UpdateAll:
|
|
c.Action = &WithOnConflict_UpdateAll{bool(action)}
|
|
case []dbw.ColumnValue:
|
|
colVals := make([]*ColumnValue, 0, len(action))
|
|
for _, cv := range action {
|
|
pbColVal := &ColumnValue{
|
|
Name: cv.Column,
|
|
}
|
|
switch cvVal := cv.Value.(type) {
|
|
case dbw.ExprValue:
|
|
args := make([]*structpb.Value, 0, len(cvVal.Vars))
|
|
for _, vv := range cvVal.Vars {
|
|
pbVar, err := structpb.NewValue(vv)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create expr arg"))
|
|
}
|
|
args = append(args, pbVar)
|
|
}
|
|
pbColVal.Value = &ColumnValue_ExprValue{&ExprValue{
|
|
Sql: cvVal.Sql,
|
|
Args: args,
|
|
}}
|
|
case dbw.Column:
|
|
pbColVal.Value = &ColumnValue_Column{
|
|
&Column{
|
|
Name: cvVal.Name,
|
|
Table: cvVal.Table,
|
|
},
|
|
}
|
|
default:
|
|
exprVal, err := structpb.NewValue(cv.Value)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create column value"))
|
|
}
|
|
pbColVal.Value = &ColumnValue_Raw{exprVal}
|
|
}
|
|
colVals = append(colVals, pbColVal)
|
|
}
|
|
c.Action = &WithOnConflict_ColumnValues{ColumnValues: &ColumnValues{Values: colVals}}
|
|
default:
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("not a valid supported action: %T", action))
|
|
}
|
|
|
|
pbOpts.WithOnConflict = c
|
|
}
|
|
return pbOpts, nil
|
|
}
|
|
|
|
// WriteEntryWith the []proto.Message marshaled into the entry data as a FIFO QueueBuffer
|
|
// if Wrapper != nil then the data is authentication encrypted
|
|
func (e *Entry) WriteEntryWith(ctx context.Context, tx *Writer, ticket *store.Ticket, msgs ...*Message) error {
|
|
const op = "oplog.(Entry).WriteEntryWith"
|
|
if tx == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "nil writer")
|
|
}
|
|
if err := e.validate(ctx); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
if ticket == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "nil ticket")
|
|
}
|
|
if ticket.Version == 0 {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing ticket version")
|
|
}
|
|
queue := Queue{}
|
|
for _, m := range msgs {
|
|
if m == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "nil message")
|
|
}
|
|
if err := queue.add(ctx, m.Message, m.TypeName, m.OpType, WithOperationOptions(m.Opts...), WithFieldMaskPaths(m.FieldMaskPaths), WithSetToNullPaths(m.SetToNullPaths)); err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithMsg("error adding message to queue"))
|
|
}
|
|
}
|
|
e.Data = append(e.Data, queue.Bytes()...)
|
|
|
|
if e.Wrapper != nil {
|
|
if err := e.encryptData(ctx); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
}
|
|
rw := dbw.New(tx.DB)
|
|
if err := rw.Create(ctx, e); err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithMsg("error writing data to storage"))
|
|
}
|
|
if err := e.Ticketer.Redeem(ctx, ticket); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Write the entry as is with whatever it has for e.Data marshaled into a FIFO QueueBuffer
|
|
// If Wrapper != nil then the data is authentication encrypted
|
|
func (e *Entry) Write(ctx context.Context, tx *Writer, ticket *store.Ticket) error {
|
|
const op = "oplog.(Entry).Write"
|
|
if err := e.validate(ctx); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
if ticket == nil {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "nil ticket")
|
|
}
|
|
if ticket.Version == 0 {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing ticket version")
|
|
}
|
|
if e.Wrapper != nil {
|
|
if err := e.encryptData(ctx); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
}
|
|
rw := dbw.New(tx.DB)
|
|
if err := rw.Create(ctx, e); err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithMsg("error writing data to storage"))
|
|
}
|
|
if err := e.Ticketer.Redeem(ctx, ticket); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// encryptData the entry's data using its Wrapper (wrapping.Wrapper)
|
|
func (e *Entry) encryptData(ctx context.Context) error {
|
|
const op = "oplog.(Entry).EncryptData"
|
|
// structwrapping doesn't support embedding, so we'll pass in the store.Entry directly
|
|
if err := structwrapping.WrapStruct(ctx, e.Wrapper, e.Entry, nil); err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithCode(errors.Encrypt))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DecryptData will decrypt the entry's data using its Wrapper (wrapping.Wrapper)
|
|
func (e *Entry) DecryptData(ctx context.Context) error {
|
|
const op = "oplog.(Entry).DecryptData"
|
|
// structwrapping doesn't support embedding, so we'll pass in the store.Entry directly
|
|
if err := structwrapping.UnwrapStruct(ctx, e.Wrapper, e.Entry, nil); err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithCode(errors.Decrypt))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Replay provides the ability to replay an entry. you must initialize any new tables ending with the tableSuffix before
|
|
// calling Replay, otherwise you'll get "a table doesn't exist" error.
|
|
func (e *Entry) Replay(ctx context.Context, tx *Writer, types *TypeCatalog, tableSuffix string) error {
|
|
const op = "oplog.(Entry).Replay"
|
|
msgs, err := e.UnmarshalData(ctx, types)
|
|
if err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
for _, m := range msgs {
|
|
em, ok := m.Message.(ReplayableMessage)
|
|
if !ok {
|
|
return errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("%T is not a replayable message", m.Message))
|
|
}
|
|
origTableName := em.TableName()
|
|
defer em.SetTableName(origTableName)
|
|
|
|
/*
|
|
how replay will be implemented for snapshots is still very much under discussion.
|
|
when we go to implement snapshots we may very well need to refactor
|
|
this create table choice... there are many issues with doing the
|
|
"create" in this manner:
|
|
* the perms needed to create a table and possible security issues
|
|
* the fk references would be to the original tables, not the new
|
|
replay tables.
|
|
* we need a way to create a replay table that contains the existing
|
|
named constraints. Currently, on conflicts using a constraint
|
|
target won't work.
|
|
It may be a better choice to just create separate schemas for replay
|
|
named blue and green since we need at min of two replay tables
|
|
definitions. if we went with separate schemas they could be create
|
|
with a boundary cli cmd that had appropriate privs (reducing
|
|
security issues) and the separate schemas wouldn't have the fk
|
|
reference issues mentioned above.
|
|
|
|
|
|
*/
|
|
replayTable := origTableName + tableSuffix
|
|
hasTable, err := tx.hasTable(ctx, replayTable)
|
|
if err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
if !hasTable {
|
|
if err := tx.createTableLike(ctx, origTableName, replayTable); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
}
|
|
rw := dbw.New(tx.DB)
|
|
|
|
m.Opts = append(m.Opts, dbw.WithTable(replayTable))
|
|
switch m.OpType {
|
|
case OpType_OP_TYPE_CREATE:
|
|
if err := rw.Create(ctx, m.Message, m.Opts...); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
case OpType_OP_TYPE_CREATE_ITEMS:
|
|
// TODO: jimlambrt 12/2021 -> while this will work for
|
|
// CreateItems(...) it's hardly efficient. We'll need to refactor
|
|
// oplog quite a bit to support a multi-message operation.
|
|
if err := rw.CreateItems(ctx, []any{m.Message}, m.Opts...); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
case OpType_OP_TYPE_UPDATE:
|
|
if _, err := rw.Update(ctx, m.Message, m.FieldMaskPaths, m.SetToNullPaths, m.Opts...); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
case OpType_OP_TYPE_DELETE:
|
|
if _, err := rw.Delete(ctx, m.Message, m.Opts...); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
case OpType_OP_TYPE_DELETE_ITEMS:
|
|
// TODO: jimlambrt 12/2021 -> while this will work for
|
|
// DeleteItems(...) it's hardly efficient. We'll need to refactor
|
|
// oplog quite a bit to support a multi-message operation.
|
|
if _, err := rw.DeleteItems(ctx, []any{m.Message}, m.Opts...); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
default:
|
|
return errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("invalid operation %T", m.OpType))
|
|
}
|
|
}
|
|
return nil
|
|
}
|