Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a firestore key migration to Teleport 17 #46472

Open
wants to merge 7 commits into
base: master
Choose a base branch
from

Conversation

tigrato
Copy link
Contributor

@tigrato tigrato commented Sep 11, 2024

Throughout the lifespan of the Firestore backend, the type of the key parameter has evolved from string, to []byte, to backend.Key, and eventually back to []byte. With each new type, documents were added without migrating the existing ones. As a result, every time a new key type was introduced, an additional step was required during key iteration because Firestore maps each of these key types to a distinct database type.

  • backend.Key is mapped to an Array in Firestore.
  • []byte is mapped to Bytes in Firestore.
  • string is mapped to a String in Firestore.

When searching for a specific key, the Go type is converted into a proto type and encoded in a particular way. During the database's range query, all keys with a different type than the requested one are ignored. This allows us to retrieve only the relevant keys and convert them to []byte by updating the database.

Throughout the lifespan of the Firestore backend, the type of the key parameter has evolved from `string`, to `[]byte`, to `backend.Key`, and eventually back to `[]byte`. With each new type, documents were added without migrating the existing ones. As a result, every time a new key type was introduced, an additional step was required during key iteration because Firestore maps each of these key types to a distinct database type.

- `backend.Key` is mapped to an Array in Firestore.
- `[]byte` is mapped to Bytes in Firestore.
- `string` is mapped to a String in Firestore.

When searching for a specific key, the Go type is converted into a proto type and encoded in a particular way. During the database's range query, all keys with a different type than the requested one are ignored. This allows us to retrieve only the relevant keys and convert them to `[]byte` by updating the database.

Signed-off-by: Tiago Silva <tiago.silva@goteleport.com>
@tigrato tigrato marked this pull request as ready for review September 12, 2024 09:59
Copy link

The PR changelog entry failed validation: Changelog entry not found in the PR body. Please add a "no-changelog" label to the PR, or changelog lines starting with changelog: followed by the changelog entries for the PR.

@tigrato tigrato added the no-changelog Indicates that a PR does not require a changelog entry label Sep 12, 2024
Comment on lines 35 to 66
type migrateFirestoreKeys struct {
}

func (d migrateFirestoreKeys) Version() int64 {
return 2
}

func (d migrateFirestoreKeys) Name() string {
return "migrate_firestore_keys"
}

// Up scans the backend for keys that are stored as strings or backend.Key types
// and converts them to the correct type (bytes).
func (d migrateFirestoreKeys) Up(ctx context.Context, b backend.Backend) error {
ctx, span := tracer.Start(ctx, "migrateFirestoreKeys/Up")
defer span.End()

// if the backend is not firestore, skip this migration
if b.GetName() != firestore.GetName() {
return nil
}

// migrate firestore keys
return trace.Wrap(firestore.MigrateIncorrectKeyTypes(ctx, b))
}

// Down is a no-op for this migration.
func (d migrateFirestoreKeys) Down(ctx context.Context, _ backend.Backend) error {
_, span := tracer.Start(ctx, "migrateFirestoreKeys/Down")
defer span.End()
return nil
}
Copy link
Contributor

@rosstimothy rosstimothy Sep 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know that a one-shot migration will work. If we assume that a new Firestore cluster was created on v16.2.0, the release the introduced the latest broken key, and stays on that version until upgrading to v17, then there is a chance the upgrade isn't performed according to our guidelines and an auth at 16.2.0 and 17 are running simultaneously. In that case, the migration may complete successfully, however, it may also be immediately undone by the old auth instance.

If we are to proceed with a one-shot migration I don't know that we can safely do it until v18. I think the safest migration strategy might be to have the firestore backend always spin up a background goroutine that performs MigrateIncorrectKeyTypes. In that case though, I think we need to rate limit the migration in order to prevent having any impact on cluster reads and writes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thinking is that during a migration, the older version will simply upsert the heartbeats, which will reset once authentication restarts. However, there’s a possibility that someone might try to modify static objects during the migration process.

I don’t believe we can handle everything in a background goroutine as well, at least not without optimistic locking. There’s nothing stopping a role from being altered between the read and put operations, especially since authentication will remain fully functional. We also can’t enforce this during startup because it could take a long time, and backend creation might fail.

We’d need to restart the conversion loop whenever a conditional update issue occurs if we use bulk writing.

Given this, I think we should postpone it to v18 and treat it as part of the migration but this is becoming terrible as read range operations take tons of time.

What are your thoughts?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The older version of Auth may still be processing and handling traffic from users, which means any tctl create operation could land on the wrong Auth server during a migration.

As you mentioned, the background migration is a perpetual clean up operation. However, since in v17 all Auth servers are capable of reading the correct, legacy, and broken key types, if a v16 Auth server undoes a migration it's not the end of the world. By the time the migration was removed in v19, there would be no possibility of any new keys being stored in the wrong format.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rosstimothy c2f93ec applied the changes. I also start the migration after a few minutes to avoid interfering with cache loads

@@ -190,6 +190,7 @@ func newRecord(from backend.Item, clock clockwork.Clock) record {
return r
}

// TODO(tigrato|rosstimothy): Simplify this function by removing the brokenRecord and legacyRecord struct
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a note indicating which version that it's safe to do this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in f74a94d

Copy link
Contributor

@fspmarshall fspmarshall left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO it would be preferable to make this an infrequent periodic rather than only run once on startup in order to be absolutely certain that we eventually migrate everything even if a bugged auth server is accidentally kept live longer than intended and auths with the migration aren't restarted.

My suggestion would be to set this up to run on an infrequent jittered interval with a short first duration. Ex:

migrationInterval := interval.New(interval.Config{
    Duration:      time.Hour * 12,
    FirstDuration: utils.FullJitter(time.Minute *5),
    Jitter:        retryutils.NewSeventhJitter(),
})
defer migrationInterval.Stop()
for {
    select {
    case <-migrationInterval.Next():
        doMigration()
    case <-ctx.Done():
        return
    }
}

@@ -413,6 +414,10 @@ func New(ctx context.Context, params backend.Params, options Options) (*Backend,
go RetryingAsyncFunctionRunner(b.clientContext, linearConfig, b.Logger, b.purgeExpiredDocuments, "purgeExpiredDocuments")
}

// Migrate incorrect key types to the correct type.
// Start the migration after a delay to allow the backend to start up and won't be affected by the migration.
_ = b.clock.AfterFunc(5*time.Minute, b.migrateIncorrectKeyTypes)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably worth using a FullJitter on this delay to ensure that it still eventually gets run even if auth is being frequently restarted. That will mean that some small portion of the time it'll interfere a bit with startup, but IMO it's worth it in order to be confident that it'll eventually get run in the context of frequent restarts.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched to interval.

lib/backend/firestore/migration.go Outdated Show resolved Hide resolved
Copy link
Contributor

@rosstimothy rosstimothy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Tiago!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-changelog Indicates that a PR does not require a changelog entry size/md
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants