[key-manager] move initialization to Instance::AfterInit (#12476)

Currently, `KeyManager` generates and stores a random `NetworkKey` in its
constructor when `OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE` is
enabled. This invokes `StoreNetworkKey()`, which interacts with
`KeyRefManager`. Accessing other components during construction can be
unsafe if they are not yet fully initialized.

This commit introduces a `KeyManager::Init()` method to handle this
initialization. This method is called from `Instance::AfterInit()`,
ensuring that the `Instance` and all dependencies, such as
`KeyRefManager`, are fully constructed before the `KeyManager` attempts
to access them.
This commit is contained in:
Abtin Keshavarzian
2026-02-23 11:00:53 -08:00
committed by GitHub
parent e20bfbc591
commit c28002707d
3 changed files with 23 additions and 9 deletions
+2
View File
@@ -432,6 +432,8 @@ void Instance::AfterInit(void)
mIsInitialized = true;
#if OPENTHREAD_MTD || OPENTHREAD_FTD
Get<KeyManager>().Init();
// Restore datasets and network information
Get<Settings>().Init();
+12 -9
View File
@@ -179,15 +179,8 @@ KeyManager::KeyManager(Instance &aInstance)
otPlatCryptoInit();
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
{
NetworkKey networkKey;
mNetworkKeyRef = Crypto::Storage::kInvalidKeyRef;
mPskcRef = Crypto::Storage::kInvalidKeyRef;
IgnoreError(networkKey.GenerateRandom());
StoreNetworkKey(networkKey, /* aOverWriteExisting */ false);
}
mNetworkKeyRef = Crypto::Storage::kInvalidKeyRef;
mPskcRef = Crypto::Storage::kInvalidKeyRef;
#else
IgnoreError(mNetworkKey.GenerateRandom());
mPskc.Clear();
@@ -196,6 +189,16 @@ KeyManager::KeyManager(Instance &aInstance)
mMacFrameCounters.Reset();
}
void KeyManager::Init(void)
{
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
NetworkKey networkKey;
IgnoreError(networkKey.GenerateRandom());
StoreNetworkKey(networkKey, /* aOverWriteExisting */ false);
#endif
}
void KeyManager::Start(void)
{
mKeySwitchGuardTimer = 0;
+9
View File
@@ -228,6 +228,15 @@ public:
*/
explicit KeyManager(Instance &aInstance);
/**
* Initializes the `KeyManager`.
*
* This method is called after OpenThread `Instance` is fully initialized (from `Instance::AfterInit()`). This
* ensures that all `Instance` components (including `KeyManager`) have been constructed and are safe to interact
* with (e.g., to save a default key in `Crypto::Storage::KeyRefManager`).
*/
void Init(void);
/**
* Starts KeyManager rotation timer and sets guard timer to initial value.
*/