2022-09-05 03:06:08 -04:00
|
|
|
/*
|
|
|
|
Copyright (c) Edgeless Systems GmbH
|
|
|
|
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2023-01-19 09:57:50 -05:00
|
|
|
// Package nodelock handles locking operations on the node.
|
2022-06-28 12:33:27 -04:00
|
|
|
package nodelock
|
|
|
|
|
2022-07-08 04:59:59 -04:00
|
|
|
import (
|
2023-07-04 10:26:37 -04:00
|
|
|
"io"
|
|
|
|
"sync/atomic"
|
2022-07-08 04:59:59 -04:00
|
|
|
|
2023-03-08 08:13:57 -05:00
|
|
|
"github.com/edgelesssys/constellation/v2/internal/attestation/initialize"
|
2022-09-21 07:47:57 -04:00
|
|
|
"github.com/edgelesssys/constellation/v2/internal/attestation/vtpm"
|
2022-07-08 04:59:59 -04:00
|
|
|
)
|
2022-06-28 12:33:27 -04:00
|
|
|
|
|
|
|
// Lock locks the node once there the join or the init is at a point
|
|
|
|
// where there is no turning back and the other operation does not need
|
|
|
|
// to continue.
|
|
|
|
//
|
|
|
|
// This can be viewed as a state machine with two states: unlocked and locked.
|
|
|
|
// There is no way to unlock, so the state changes only once from unlock to
|
|
|
|
// locked.
|
|
|
|
type Lock struct {
|
2023-07-04 10:26:37 -04:00
|
|
|
tpm vtpm.TPMOpenFunc
|
|
|
|
marker markAsBootstrapped
|
|
|
|
inner atomic.Bool
|
2022-06-28 12:33:27 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// New creates a new NodeLock, which is unlocked.
|
2022-07-08 04:59:59 -04:00
|
|
|
func New(tpm vtpm.TPMOpenFunc) *Lock {
|
|
|
|
return &Lock{
|
2023-07-04 10:26:37 -04:00
|
|
|
tpm: tpm,
|
|
|
|
marker: initialize.MarkNodeAsBootstrapped,
|
2022-07-08 04:59:59 -04:00
|
|
|
}
|
2022-06-28 12:33:27 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// TryLockOnce tries to lock the node. If the node is already locked, it
|
|
|
|
// returns false. If the node is unlocked, it locks it and returns true.
|
2022-07-26 04:58:39 -04:00
|
|
|
func (l *Lock) TryLockOnce(clusterID []byte) (bool, error) {
|
2023-07-04 10:26:37 -04:00
|
|
|
// CompareAndSwap first checks if the node is currently unlocked.
|
|
|
|
// If it was already locked, it returns early.
|
|
|
|
// If it is unlocked, it swaps the value to locked atomically and continues.
|
|
|
|
if !l.inner.CompareAndSwap(unlocked, locked) {
|
2022-07-14 09:45:04 -04:00
|
|
|
return false, nil
|
2022-07-08 04:59:59 -04:00
|
|
|
}
|
2022-07-26 04:58:39 -04:00
|
|
|
|
2023-07-04 10:26:37 -04:00
|
|
|
return true, l.marker(l.tpm, clusterID)
|
2022-06-28 12:33:27 -04:00
|
|
|
}
|
2023-07-04 10:26:37 -04:00
|
|
|
|
|
|
|
// markAsBootstrapped is a function that marks the node as bootstrapped in the TPM.
|
|
|
|
type markAsBootstrapped func(openDevice func() (io.ReadWriteCloser, error), clusterID []byte) error
|
|
|
|
|
|
|
|
const (
|
|
|
|
unlocked = false
|
|
|
|
locked = true
|
|
|
|
)
|