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

keyring: fixes for keyring replication on cluster join #14987

Merged
merged 4 commits into from
Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 32 additions & 7 deletions nomad/encrypter.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,33 @@ const keyIDHeader = "kid"
// SignClaims signs the identity claim for the task and returns an
// encoded JWT with both the claim and its signature
func (e *Encrypter) SignClaims(claim *structs.IdentityClaims) (string, error) {
e.lock.RLock()
defer e.lock.RUnlock()

keyset, err := e.activeKeySetLocked()
getActiveKeyset := func() (*keyset, error) {
e.lock.RLock()
defer e.lock.RUnlock()
keyset, err := e.activeKeySetLocked()
return keyset, err
}
Comment on lines +159 to +164
Copy link
Member

Choose a reason for hiding this comment

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

Sorry for the after-the-fact drive-by review:

Looks like we could replace activeKeySetLocked with this func as the only other place the key is read is Encrypt and it similarly only needs the lock for the duration of fetching the key.

The fact neither reader of this field need the lock other than for this field signals to me that the lock should be encapsulated in the getter and not the caller's concern.

Not a big deal though.

Copy link
Member Author

Choose a reason for hiding this comment

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

That's a good catch. activeKeySetLocked ends up holding onto the lock longer than it needs to as well -- it doesn't need to hold the lock while querying the state store. I'll open another quickie PR for that.

Copy link
Member Author

Choose a reason for hiding this comment

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

Follow-up PR: #15026


// If a key is rotated immediately following a leader election, plans that
// are in-flight may get signed before the new leader has the key. Allow for
// a short timeout-and-retry to avoid rejecting plans
keyset, err := getActiveKeyset()
if err != nil {
return "", err
ctx, cancel := context.WithTimeout(e.srv.shutdownCtx, 5*time.Second)
defer cancel()
for {
select {
case <-ctx.Done():
return "", err
default:
time.Sleep(50 * time.Millisecond)
keyset, err = getActiveKeyset()
if keyset != nil {
break
}
}
}
}

token := jwt.NewWithClaims(&jwt.SigningMethodEd25519{}, claim)
Expand Down Expand Up @@ -435,7 +456,10 @@ START:
return
default:
// Rate limit how often we attempt replication
limiter.Wait(ctx)
err := limiter.Wait(ctx)
if err != nil {
goto ERR_WAIT // rate limit exceeded
}
Comment on lines 458 to +462
Copy link
Member

@shoenig shoenig Oct 21, 2022

Choose a reason for hiding this comment

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

Seems like if we have our own blocking mechanism, we should be using Allow instead? Otherwise we are kind of double-waiting, which is fine but awkward given the error. (no need to change anything now)

https://pkg.go.dev/golang.org/x/time/rate#Limiter

edit: actually no, Wait has the nice property of waiting a minimal amount of time, unblocking once a resource becomes free

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah this API is weirdly hard to use correctly and the error case is only for exceeding the burst. I first thought we probably wanted to use Reserve but that has the same double-waiting problem. Maybe we should just remove the burst (set it to Inf) so that we guarantee we'll wait and not have to handle this error so awkwardly?

Copy link
Member Author

Choose a reason for hiding this comment

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

I misread the API again 😊 . Only when the rate is set to rate.Inf is the burst-limit ignored. So this is good as-is, awkward as it seems.


ws := store.NewWatchSet()
iter, err := store.RootKeyMetas(ws)
Expand All @@ -461,7 +485,8 @@ START:
getReq := &structs.KeyringGetRootKeyRequest{
KeyID: keyID,
QueryOptions: structs.QueryOptions{
Region: krr.srv.config.Region,
Region: krr.srv.config.Region,
MinQueryIndex: keyMeta.ModifyIndex - 1,
},
}
getResp := &structs.KeyringGetRootKeyResponse{}
Expand All @@ -479,7 +504,7 @@ START:
getReq.AllowStale = true
for _, peer := range krr.getAllPeers() {
err = krr.srv.forwardServer(peer, "Keyring.Get", getReq, getResp)
if err == nil {
if err == nil && getResp.Key != nil {
break
}
}
Expand Down
29 changes: 27 additions & 2 deletions nomad/encrypter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ func TestEncrypter_Restore(t *testing.T) {
}
}

// TestKeyringReplicator exercises key replication between servers
func TestKeyringReplicator(t *testing.T) {
// TestEncrypter_KeyringReplication exercises key replication between servers
func TestEncrypter_KeyringReplication(t *testing.T) {

ci.Parallel(t)

Expand Down Expand Up @@ -267,6 +267,31 @@ func TestKeyringReplicator(t *testing.T) {
require.Eventually(t, checkReplicationFn(keyID3),
time.Second*5, time.Second,
"expected keys to be replicated to followers after election")

// Scenario: new members join the cluster

srv4, cleanupSRV4 := TestServer(t, func(c *Config) {
c.BootstrapExpect = 0
c.NumSchedulers = 0
})
defer cleanupSRV4()
srv5, cleanupSRV5 := TestServer(t, func(c *Config) {
c.BootstrapExpect = 0
c.NumSchedulers = 0
})
defer cleanupSRV5()

TestJoin(t, srv4, srv5)
TestJoin(t, srv5, srv1)
servers = []*Server{srv1, srv2, srv3, srv4, srv5}

testutil.WaitForLeader(t, srv4.RPC)
testutil.WaitForLeader(t, srv5.RPC)

require.Eventually(t, checkReplicationFn(keyID3),
time.Second*5, time.Second,
"expected new servers to get replicated keys")

}

func TestEncrypter_EncryptDecrypt(t *testing.T) {
Expand Down
15 changes: 14 additions & 1 deletion nomad/keyring_endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,20 @@ func (k *Keyring) Get(args *structs.KeyringGetRootKeyRequest, reply *structs.Key
Key: key,
}
reply.Key = rootKey
reply.Index = keyMeta.ModifyIndex

// Use the last index that affected the policy table
index, err := s.Index(state.TableRootKeyMeta)
if err != nil {
return err
}

// Ensure we never set the index to zero, otherwise a blocking query
// cannot be used. We floor the index at one, since realistically
// the first write must have a higher index.
if index == 0 {
index = 1
}
reply.Index = index
return nil
},
}
Expand Down
8 changes: 4 additions & 4 deletions nomad/leader.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,6 @@ func (s *Server) establishLeadership(stopCh chan struct{}) error {
// Initialize scheduler configuration.
schedulerConfig := s.getOrCreateSchedulerConfig()

// Create the first root key if it doesn't already exist
go s.initializeKeyring(stopCh)

// Initialize the ClusterID
_, _ = s.ClusterID()
// todo: use cluster ID for stuff, later!
Expand Down Expand Up @@ -350,6 +347,9 @@ func (s *Server) establishLeadership(stopCh chan struct{}) error {

// Further clean ups and follow up that don't block RPC consistency

// Create the first root key if it doesn't already exist
go s.initializeKeyring(stopCh)

// Restore the periodic dispatcher state
if err := s.restorePeriodicDispatcher(); err != nil {
return err
Expand Down Expand Up @@ -2005,7 +2005,7 @@ func (s *Server) initializeKeyring(stopCh <-chan struct{}) {
break
}
}
// we might have lost leadershuip during the version check
// we might have lost leadership during the version check
if !s.IsLeader() {
return
}
Expand Down