Skip to content

Commit

Permalink
coordinator: make history thread-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
burgerdev committed Jun 14, 2024
1 parent c1f0432 commit a1c91b3
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions coordinator/history/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"fmt"
"hash"
"os"
"sync/atomic"

"github.com/spf13/afero"
)
Expand All @@ -28,7 +29,7 @@ const (
type History struct {
store Store
hashFun func() hash.Hash
signingKey *ecdsa.PrivateKey
signingKey atomic.Pointer[ecdsa.PrivateKey]
}

// New creates a new History backed by the default filesystem store.
Expand All @@ -55,7 +56,7 @@ func NewWithStore(store Store) *History {

// ConfigureSigningKey sets the signing key for validation and signing of the protected history parts.
func (h *History) ConfigureSigningKey(signingKey *ecdsa.PrivateKey) {
h.signingKey = signingKey
h.signingKey.Store(signingKey)
}

// GetManifest returns the manifest for the given hash.
Expand Down Expand Up @@ -98,7 +99,8 @@ func (h *History) SetTransition(transition *Transition) ([HashSize]byte, error)

// GetLatest returns the verified transition for the given hash.
func (h *History) GetLatest() (*LatestTransition, error) {
if h.signingKey == nil {
signingKey := h.signingKey.Load()
if signingKey == nil {
return nil, errors.New("signing key not configured")
}
transitionBytes, err := h.store.Get("transitions/latest")
Expand All @@ -109,7 +111,7 @@ func (h *History) GetLatest() (*LatestTransition, error) {
if err := latestTransition.unmarshalBinary(transitionBytes); err != nil {
return nil, fmt.Errorf("unmarshaling latest transition: %w", err)
}
if err := latestTransition.verify(&h.signingKey.PublicKey); err != nil {
if err := latestTransition.verify(&signingKey.PublicKey); err != nil {
return nil, fmt.Errorf("verifying latest transition: %w", err)
}
return &latestTransition, nil
Expand All @@ -129,10 +131,11 @@ func (h *History) HasLatest() (bool, error) {

// SetLatest signs and sets the latest transition if the current latest is equal to oldT.
func (h *History) SetLatest(oldT, newT *LatestTransition) error {
if h.signingKey == nil {
signingKey := h.signingKey.Load()
if signingKey == nil {
return errors.New("signing key not configured")
}
if err := newT.sign(h.signingKey); err != nil {
if err := newT.sign(signingKey); err != nil {
return fmt.Errorf("signing latest transition: %w", err)
}
if err := h.store.CompareAndSwap("transitions/latest", oldT.marshalBinary(), newT.marshalBinary()); err != nil {
Expand Down

0 comments on commit a1c91b3

Please sign in to comment.