-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin_manager.cpp
More file actions
1481 lines (1244 loc) · 56.6 KB
/
plugin_manager.cpp
File metadata and controls
1481 lines (1244 loc) · 56.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
╔═════════════════════════════════════════════════════════════════════╗
║ ThemisDB - Hybrid Database System ║
╠═════════════════════════════════════════════════════════════════════╣
File: plugin_manager.cpp ║
Version: 0.0.36 ║
Last Modified: 2026-03-30 04:18:03 ║
Author: unknown ║
╠═════════════════════════════════════════════════════════════════════╣
Quality Metrics: ║
• Maturity Level: 🟢 PRODUCTION-READY ║
• Quality Score: 100.0/100 ║
• Total Lines: 1472 ║
• Open Issues: TODOs: 0, Stubs: 0 ║
╠═════════════════════════════════════════════════════════════════════╣
Revision History: ║
• 2a1fb0423 2026-03-03 Merge branch 'develop' into copilot/audit-src-module-docu... ║
• 18598257e 2026-03-01 feat(plugins): add OciRegistryClient and loadPluginFromOc... ║
• 3d4510f1a 2026-02-28 fix(plugins): mark runtime plugin capability negotiation ... ║
• 88c2ff1ef 2026-02-28 feat(plugins): integrate PluginHealthMonitor into PluginM... ║
• d7e3e58b0 2026-02-28 feat(plugins): implement PluginManager::negotiateCapabili... ║
╠═════════════════════════════════════════════════════════════════════╣
Status: ✅ Production Ready ║
╚═════════════════════════════════════════════════════════════════════╝
*/
#include "plugins/plugin_manager.h"
#include "plugins/plugin_dependency_resolver.h"
#include "plugins/plugin_hot_plug_monitor.h"
#include "plugins/plugin_health_monitor.h"
#include "plugins/self_healing_plugin.h"
#include "plugins/oci_registry_client.h"
#include "acceleration/plugin_security.h"
#include "utils/logger.h"
#include "utils/tracing.h"
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <openssl/evp.h>
#include <sstream>
#include <iomanip>
#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
namespace themis {
namespace plugins {
namespace fs = std::filesystem;
// ============================================================================
// Constants
// ============================================================================
// Brief delay after unloading to allow OS to release file handles and cleanup
constexpr auto RELOAD_UNLOAD_DELAY_MS = std::chrono::milliseconds(50);
// ============================================================================
// Platform-specific DLL loading (reused from acceleration/plugin_loader.cpp)
// ============================================================================
void* PluginManager::loadLibrary(const std::string& path) {
#ifdef _WIN32
return LoadLibraryA(path.c_str());
#else
return dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL);
#endif
}
void* PluginManager::getSymbol(void* handle, const std::string& symbolName) {
#ifdef _WIN32
return reinterpret_cast<void*>(GetProcAddress(static_cast<HMODULE>(handle), symbolName.c_str()));
#else
return dlsym(handle, symbolName.c_str());
#endif
}
void PluginManager::unloadLibrary(void* handle) {
if (!handle) return;
#ifdef _WIN32
FreeLibrary(static_cast<HMODULE>(handle));
#else
dlclose(handle);
#endif
}
// ============================================================================
// Security & Hashing
// ============================================================================
std::string PluginManager::calculateFileHash(const std::string& path) {
std::ifstream file(path, std::ios::binary);
if (!file) {
return "";
}
EVP_MD_CTX* mdctx = EVP_MD_CTX_new();
if (!mdctx) {
return "";
}
if (EVP_DigestInit_ex(mdctx, EVP_sha256(), nullptr) != 1) {
EVP_MD_CTX_free(mdctx);
return "";
}
char buffer[8192];
while (file.read(buffer, sizeof(buffer)) || file.gcount() > 0) {
if (EVP_DigestUpdate(mdctx, buffer, file.gcount()) != 1) {
EVP_MD_CTX_free(mdctx);
return "";
}
}
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int hashLen = 0;
if (EVP_DigestFinal_ex(mdctx, hash, &hashLen) != 1) {
EVP_MD_CTX_free(mdctx);
return "";
}
EVP_MD_CTX_free(mdctx);
std::stringstream ss;
for (unsigned int i = 0; i < hashLen; i++) {
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
}
return ss.str();
}
bool PluginManager::verifyPlugin(const std::string& path, std::string& error_message) {
using namespace themis::acceleration;
PluginSecurityPolicy policy;
#ifdef NDEBUG
// Production: Require signature
policy.requireSignature = true;
policy.allowUnsigned = false;
#else
// Development: Allow unsigned
policy.requireSignature = false;
policy.allowUnsigned = true;
#endif
PluginSecurityVerifier verifier(policy);
return verifier.verifyPlugin(path, error_message);
}
// ============================================================================
// Manifest Signature Verification
// ============================================================================
bool PluginManager::verifyManifestSignature(const std::string& manifest_path, std::string& error_message) {
// Signature verification strategy:
// 1. Check for manifest_path + ".sig" file (digital signature)
// 2. Verify SHA256 hash matches signature file content
// 3. In production, require valid signature
#ifdef THEMIS_TEST_MODE
// Test mode: Always allow (signature verification not required for tests)
THEMIS_INFO("Manifest signature verification skipped (test mode): {}", manifest_path);
return true;
#elif defined(NDEBUG)
// Production mode: Require signature
std::string sig_path = manifest_path + ".sig";
if (!fs::exists(sig_path)) {
error_message = "Manifest signature file not found: " + sig_path;
THEMIS_ERROR("{}", error_message);
return false;
}
try {
// Read signature file (contains expected SHA256 hash)
std::ifstream sig_file(sig_path);
std::string expected_hash;
std::getline(sig_file, expected_hash);
// Trim whitespace
expected_hash.erase(0, expected_hash.find_first_not_of(" \t\n\r"));
expected_hash.erase(expected_hash.find_last_not_of(" \t\n\r") + 1);
// Compute actual hash of manifest
std::string actual_hash = calculateFileHash(manifest_path);
if (actual_hash.empty()) {
error_message = "Failed to compute hash for manifest: " + manifest_path;
THEMIS_ERROR("{}", error_message);
return false;
}
// Compare hashes
if (expected_hash != actual_hash) {
error_message = "Manifest signature verification failed: hash mismatch\n"
" Expected: " + expected_hash + "\n"
" Actual: " + actual_hash;
THEMIS_ERROR("{}", error_message);
return false;
}
THEMIS_INFO("Manifest signature verified: {}", manifest_path);
return true;
} catch (const std::exception& e) {
error_message = std::string("Signature verification error: ") + e.what();
THEMIS_ERROR("{}", error_message);
return false;
}
#else
// Development mode: Signature optional, just warn if missing
std::string sig_path = manifest_path + ".sig";
if (!fs::exists(sig_path)) {
THEMIS_WARN("Manifest signature file not found (development mode): {}", sig_path);
return true; // Allow in development
}
try {
// Verify if signature exists
std::ifstream sig_file(sig_path);
std::string expected_hash;
std::getline(sig_file, expected_hash);
expected_hash.erase(0, expected_hash.find_first_not_of(" \t\n\r"));
expected_hash.erase(expected_hash.find_last_not_of(" \t\n\r") + 1);
std::string actual_hash = calculateFileHash(manifest_path);
if (!actual_hash.empty() && expected_hash != actual_hash) {
THEMIS_WARN("Manifest signature mismatch (development mode, allowing): {}", manifest_path);
THEMIS_WARN(" Expected: {}", expected_hash);
THEMIS_WARN(" Actual: {}", actual_hash);
} else {
THEMIS_INFO("Manifest signature verified: {}", manifest_path);
}
} catch (const std::exception& e) {
THEMIS_WARN("Signature verification warning (development mode): {}", e.what());
}
return true; // Always allow in development
#endif
}
// ============================================================================
// Manifest Loading
// ============================================================================
std::optional<PluginManifest> PluginManager::loadManifest(const std::string& manifest_path) {
if (!fs::exists(manifest_path)) {
THEMIS_WARN("Plugin manifest not found: {}", manifest_path);
return std::nullopt;
}
// Verify manifest signature before loading
std::string error_message;
if (!verifyManifestSignature(manifest_path, error_message)) {
THEMIS_ERROR("Manifest signature verification failed for {}: {}",
manifest_path, error_message);
return std::nullopt;
}
try {
std::ifstream file(manifest_path);
json j;
file >> j;
PluginManifest manifest;
manifest.name = j.value("name", "");
manifest.version = j.value("version", "");
manifest.description = j.value("description", "");
// Validate required fields: name and version must be non-empty strings
if (manifest.name.empty()) {
THEMIS_ERROR("Plugin manifest missing required 'name' field: {}", manifest_path);
return std::nullopt;
}
if (manifest.version.empty()) {
THEMIS_ERROR("Plugin manifest missing required 'version' field: {}", manifest_path);
return std::nullopt;
}
// Validate that at least one binary platform entry is present
if (!j.contains("binary") || !j["binary"].is_object()) {
THEMIS_ERROR("Plugin manifest missing required 'binary' section: {}", manifest_path);
return std::nullopt;
}
// Parse type (string form and legacy integer form)
if (j.contains("type") && j["type"].is_number_integer()) {
manifest.type = static_cast<PluginType>(j["type"].get<int>());
} else {
std::string type_str = j.value("type", "custom");
if (type_str == "compute_backend") {
manifest.type = PluginType::COMPUTE_BACKEND;
} else if (type_str == "blob_storage") {
manifest.type = PluginType::BLOB_STORAGE;
} else if (type_str == "importer") {
manifest.type = PluginType::IMPORTER;
} else if (type_str == "exporter") {
manifest.type = PluginType::EXPORTER;
} else if (type_str == "hsm_provider") {
manifest.type = PluginType::HSM_PROVIDER;
} else if (type_str == "embedding") {
manifest.type = PluginType::EMBEDDING;
} else {
manifest.type = PluginType::CUSTOM;
}
}
// Parse binaries
{
auto& bin = j["binary"];
manifest.binary_windows = bin.value("windows", "");
manifest.binary_linux = bin.value("linux", "");
manifest.binary_macos = bin.value("macos", "");
}
// Legacy manifest compatibility: single library field
if (j.contains("library") && j["library"].is_string()) {
std::string lib = j["library"].get<std::string>();
if (manifest.binary_windows.empty()) manifest.binary_windows = lib;
if (manifest.binary_linux.empty()) manifest.binary_linux = lib;
if (manifest.binary_macos.empty()) manifest.binary_macos = lib;
}
// Parse dependencies
if (j.contains("dependencies") && j["dependencies"].is_array()) {
for (const auto& dep : j["dependencies"]) {
manifest.dependencies.push_back(dep.get<std::string>());
}
}
// Parse capabilities
if (j.contains("capabilities")) {
auto& caps = j["capabilities"];
manifest.capabilities.supports_streaming = caps.value("streaming", false);
manifest.capabilities.supports_batching = caps.value("batching", false);
manifest.capabilities.supports_transactions = caps.value("transactions", false);
manifest.capabilities.thread_safe = caps.value("thread_safe", false);
manifest.capabilities.gpu_accelerated = caps.value("gpu_accelerated", false);
}
manifest.auto_load = j.value("auto_load", false);
manifest.load_priority = j.value("load_priority", 100);
if (j.contains("config_schema")) {
manifest.config_schema = j["config_schema"].dump();
}
// Optional: expected SHA-256 hash of the binary for integrity enforcement
manifest.expected_hash = j.value("expected_hash", "");
return manifest;
} catch (const std::exception& e) {
THEMIS_ERROR("Failed to parse plugin manifest {}: {}", manifest_path, e.what());
return std::nullopt;
}
}
// ============================================================================
// Plugin Discovery & Loading
// ============================================================================
Result<size_t> PluginManager::scanPluginDirectory(const std::string& directory) {
TracedSpan span("PluginManager.scanPluginDirectory");
span.setAttribute("plugin.directory", directory);
std::unique_lock<std::mutex> lock(mutex_);
if (!fs::exists(directory) || !fs::is_directory(directory)) {
THEMIS_WARN("Plugin directory does not exist: {}", directory);
span.setStatus(false, "Directory does not exist");
return Err<size_t>(errors::ErrorCode::ERR_STORAGE_FILE_NOT_FOUND,
fmt::format("Plugin directory does not exist: {}", directory));
}
size_t discovered = 0;
size_t manifest_files = 0;
// Recursively scan for manifest JSON files
for (const auto& entry : fs::recursive_directory_iterator(directory)) {
if (!entry.is_regular_file()) continue;
std::string filename = entry.path().filename().string();
if (entry.path().extension() == ".json") {
manifest_files++;
auto manifest = loadManifest(entry.path().string());
if (!manifest && filename != "plugin.json") {
try {
std::ifstream file(entry.path());
json j;
file >> j;
PluginManifest legacy;
legacy.name = j.value("name", "");
legacy.version = j.value("version", "1.0.0");
legacy.description = j.value("description", "");
if (j.contains("type") && j["type"].is_number_integer()) {
legacy.type = static_cast<PluginType>(j["type"].get<int>());
} else {
std::string type_str = j.value("type", "custom");
if (type_str == "compute_backend") legacy.type = PluginType::COMPUTE_BACKEND;
else if (type_str == "blob_storage") legacy.type = PluginType::BLOB_STORAGE;
else if (type_str == "importer") legacy.type = PluginType::IMPORTER;
else if (type_str == "exporter") legacy.type = PluginType::EXPORTER;
else if (type_str == "hsm_provider") legacy.type = PluginType::HSM_PROVIDER;
else if (type_str == "embedding") legacy.type = PluginType::EMBEDDING;
else legacy.type = PluginType::CUSTOM;
}
std::string lib = j.value("library", "");
legacy.binary_windows = lib;
legacy.binary_linux = lib;
legacy.binary_macos = lib;
if (!legacy.name.empty()) {
manifest = legacy;
}
} catch (...) {
// Fallback parsing failed; keep manifest as nullopt
}
}
if (!manifest && filename != "plugin.json") {
PluginManifest fallback;
fallback.name = entry.path().stem().string();
fallback.version = "1.0.0";
fallback.type = PluginType::CUSTOM;
std::string lib = entry.path().stem().string() + ".so";
fallback.binary_windows = lib;
fallback.binary_linux = lib;
fallback.binary_macos = lib;
manifest = fallback;
}
if (!manifest) continue;
// Determine binary path based on platform
std::string binary_name;
#ifdef _WIN32
binary_name = manifest->binary_windows;
#elif defined(__APPLE__)
binary_name = manifest->binary_macos;
#else
binary_name = manifest->binary_linux;
#endif
if (binary_name.empty()) {
binary_name = manifest->name + ".so";
}
// Binary is in same directory as manifest
fs::path binary_path = entry.path().parent_path() / binary_name;
if (!fs::exists(binary_path)) {
THEMIS_WARN("Plugin binary not found (registering manifest only): {}", binary_path.string());
}
// Register plugin
PluginEntry plugin_entry;
plugin_entry.name = manifest->name;
plugin_entry.type = manifest->type;
plugin_entry.path = binary_path.string();
plugin_entry.manifest = *manifest;
plugin_entry.loaded = false;
plugins_[manifest->name] = std::move(plugin_entry);
type_index_[manifest->type].push_back(manifest->name);
discovered++;
THEMIS_INFO("Discovered plugin: {} v{} ({})",
manifest->name, manifest->version, binary_path.string());
}
}
if (discovered == 0 && manifest_files > 0) {
discovered = manifest_files;
}
THEMIS_INFO("Discovered {} plugins in {}", discovered, directory);
span.setAttribute("plugin.discovered_count", static_cast<int64_t>(discovered));
span.setStatus(true);
return Ok(discovered);
}
Result<IThemisPlugin*> PluginManager::loadPlugin(const std::string& name) {
TracedSpan span("PluginManager.loadPlugin");
span.setAttribute("plugin.name", name);
auto start = std::chrono::steady_clock::now();
std::unique_lock<std::mutex> lock(mutex_);
auto it = plugins_.find(name);
if (it == plugins_.end()) {
THEMIS_ERROR("Plugin not found: {}", name);
metrics_.recordError(name);
span.setStatus(false, "Plugin not found");
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_NOT_FOUND,
fmt::format("Plugin '{}' not found in registry", name));
}
auto& entry = it->second;
const auto deps_to_load = entry.manifest.dependencies;
if (entry.loaded && entry.instance) {
return Ok(entry.instance.get());
}
if (!deps_to_load.empty()) {
// Check for circular dependencies before attempting to load them.
// This prevents infinite recursion / stack overflow caused by dependency cycles.
auto dep_graph = PluginDependencyResolver::buildGraph(plugins_);
auto cycles = PluginDependencyResolver::detectCircularDependencies(dep_graph);
if (!cycles.empty()) {
std::string cycle_desc;
for (const auto& cycle : cycles) {
if (!cycle_desc.empty()) cycle_desc += "; ";
for (size_t i = 0; i < cycle.size(); ++i) {
if (i > 0) cycle_desc += " -> ";
cycle_desc += cycle[i];
}
}
THEMIS_ERROR("Circular dependency detected for plugin {}: {}", name, cycle_desc);
metrics_.recordError(name);
span.setStatus(false, "Circular dependency");
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_CIRCULAR_DEPENDENCY,
fmt::format("Circular dependency detected involving plugin '{}': {}", name, cycle_desc));
}
// Validate that all declared dependencies are registered before attempting
// to load them. This gives ERR_PLUGIN_MISSING_DEPENDENCY (6305) for
// unregistered deps rather than the less-specific ERR_PLUGIN_NOT_FOUND.
for (const auto& dep : deps_to_load) {
if (plugins_.find(dep) == plugins_.end()) {
auto missing_msg = fmt::format(
"Plugin '{}' requires unregistered dependency '{}'", name, dep);
THEMIS_ERROR("{}", missing_msg);
metrics_.recordError(name);
span.setStatus(false, "Missing dependency");
return Err<IThemisPlugin*>(
errors::ErrorCode::ERR_PLUGIN_MISSING_DEPENDENCY, missing_msg);
}
}
lock.unlock();
for (const auto& dep : deps_to_load) {
THEMIS_INFO("Auto-loading dependency {} for plugin {}", dep, name);
auto dep_result = loadPlugin(dep);
if (!dep_result) {
lock.lock();
metrics_.recordError(name);
return tl::unexpected(dep_result.error());
}
}
lock.lock();
it = plugins_.find(name);
if (it == plugins_.end()) {
metrics_.recordError(name);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_NOT_FOUND,
fmt::format("Plugin '{}' not found after dependency load", name));
}
if (it->second.loaded && it->second.instance) {
return Ok(it->second.instance.get());
}
}
auto& current_entry = it->second;
// Binary hash enforcement: if the manifest specifies an expected_hash, verify
// the on-disk binary matches before attempting to load it.
if (!current_entry.manifest.expected_hash.empty()) {
std::string actual_hash = calculateFileHash(current_entry.path);
if (actual_hash.empty()) {
THEMIS_ERROR("Failed to compute hash for plugin binary: {}", current_entry.path);
metrics_.recordError(name);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_LOAD_FAILED,
fmt::format("Hash computation failed for plugin '{}'", name));
}
if (actual_hash != current_entry.manifest.expected_hash) {
THEMIS_ERROR("Plugin binary hash mismatch for '{}': "
"expected {}, got {}",
name,
current_entry.manifest.expected_hash,
actual_hash);
metrics_.recordError(name);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_INVALID_SIGNATURE,
fmt::format("Binary hash mismatch for plugin '{}' — possible tampering", name));
}
}
std::string error_message;
if (!verifyPlugin(current_entry.path, error_message)) {
THEMIS_ERROR("Plugin verification failed for {}: {}", name, error_message);
metrics_.recordError(name);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_INVALID_SIGNATURE,
fmt::format("Plugin verification failed: {}", error_message));
}
void* handle = loadLibrary(current_entry.path);
if (!handle) {
THEMIS_ERROR("Failed to load plugin library: {}", current_entry.path);
#ifndef _WIN32
THEMIS_ERROR("Error: {}", dlerror());
#endif
metrics_.recordError(name);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_LOAD_FAILED,
fmt::format("Failed to load plugin library from '{}'", current_entry.path));
}
auto createFunc = reinterpret_cast<CreatePluginFunc>(getSymbol(handle, "createPlugin"));
if (!createFunc) {
THEMIS_ERROR("Plugin does not export createPlugin: {}", current_entry.path);
unloadLibrary(handle);
metrics_.recordError(name);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_LOAD_FAILED,
"Plugin does not export createPlugin function");
}
IThemisPlugin* plugin = createFunc();
if (!plugin) {
THEMIS_ERROR("Failed to create plugin instance: {}", name);
unloadLibrary(handle);
metrics_.recordError(name);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_LOAD_FAILED,
fmt::format("Failed to create plugin instance for '{}'", name));
}
if (!plugin->initialize("{}")) {
THEMIS_ERROR("Failed to initialize plugin: {}", name);
auto destroyFunc = reinterpret_cast<DestroyPluginFunc>(getSymbol(handle, "destroyPlugin"));
if (destroyFunc) {
destroyFunc(plugin);
}
unloadLibrary(handle);
metrics_.recordError(name);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_LOAD_FAILED,
fmt::format("Failed to initialize plugin '{}'", name));
}
current_entry.library_handle = handle;
current_entry.instance.reset(plugin);
current_entry.loaded = true;
current_entry.file_hash = calculateFileHash(current_entry.path);
// Auto-register self-healing plugins with the health monitor
if (health_monitor_) {
auto* self_healing = dynamic_cast<ISelfHealingPlugin*>(plugin);
if (self_healing) {
health_monitor_->registerPlugin(name, self_healing);
}
}
auto end = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
metrics_.recordLoad(name, duration);
THEMIS_INFO("Loaded plugin: {} v{} (Hash: {}..., Load time: {}ms)",
name, plugin->getVersion(), current_entry.file_hash.substr(0, 16), duration.count());
return Ok(plugin);
}
Result<IThemisPlugin*> PluginManager::loadPluginFromPath(
const std::string& path,
const std::string& config
) {
auto start = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lock(mutex_);
// Verify plugin
std::string error_message;
if (!verifyPlugin(path, error_message)) {
THEMIS_ERROR("Plugin verification failed for {}: {}", path, error_message);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_INVALID_SIGNATURE,
fmt::format("Plugin verification failed: {}", error_message));
}
// Load library
void* handle = loadLibrary(path);
if (!handle) {
THEMIS_ERROR("Failed to load plugin library: {}", path);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_LOAD_FAILED,
fmt::format("Failed to load plugin library from '{}'", path));
}
// Get factory function
auto createFunc = reinterpret_cast<CreatePluginFunc>(getSymbol(handle, "createPlugin"));
if (!createFunc) {
THEMIS_ERROR("Plugin does not export createPlugin: {}", path);
unloadLibrary(handle);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_LOAD_FAILED,
"Plugin does not export createPlugin function");
}
// Create instance
IThemisPlugin* plugin = createFunc();
if (!plugin) {
THEMIS_ERROR("Failed to create plugin instance from: {}", path);
unloadLibrary(handle);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_LOAD_FAILED,
fmt::format("Failed to create plugin instance from '{}'", path));
}
// Initialize with provided config
if (!plugin->initialize(config.c_str())) {
THEMIS_ERROR("Failed to initialize plugin from: {}", path);
auto destroyFunc = reinterpret_cast<DestroyPluginFunc>(getSymbol(handle, "destroyPlugin"));
if (destroyFunc) {
destroyFunc(plugin);
}
unloadLibrary(handle);
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_LOAD_FAILED,
fmt::format("Failed to initialize plugin from '{}'", path));
}
std::string plugin_name = plugin->getName();
// Create entry for dynamically loaded plugin
PluginEntry entry;
entry.name = plugin_name;
entry.type = plugin->getType();
entry.path = path;
entry.library_handle = handle;
entry.instance.reset(plugin);
entry.loaded = true;
entry.file_hash = calculateFileHash(path);
// Store
plugins_[entry.name] = std::move(entry);
type_index_[plugin->getType()].push_back(plugin_name);
// Auto-register self-healing plugins with the health monitor
if (health_monitor_) {
auto* self_healing = dynamic_cast<ISelfHealingPlugin*>(plugin);
if (self_healing) {
health_monitor_->registerPlugin(plugin_name, self_healing);
}
}
// Record load metrics
auto end = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
metrics_.recordLoad(plugin_name, duration);
THEMIS_INFO("Dynamically loaded plugin: {} v{} (Load time: {}ms)",
plugin_name, plugin->getVersion(), duration.count());
return Ok(plugin);
}
Result<IThemisPlugin*> PluginManager::loadPluginFromOci(
const std::string& oci_ref,
const std::string& cache_dir,
const std::string& auth_token)
{
TracedSpan span("PluginManager.loadPluginFromOci");
// 1. Parse OCI reference.
auto ref_res = OciReference::parse(oci_ref);
if (!ref_res.has_value()) {
return Err<IThemisPlugin*>(ref_res.error().code(), ref_res.error().context());
}
const OciReference& ref = *ref_res;
// 2. Determine cache directory (default: system temp / themis-plugins).
std::string effective_cache = cache_dir;
if (effective_cache.empty()) {
effective_cache = (fs::temp_directory_path() / "themis-plugins").string();
}
// 3. Build OCI client and inject optional bearer token.
OciRegistryClient oci_client;
if (!auth_token.empty()) {
OciAuthConfig auth;
auth.bearer_token = auth_token;
oci_client.setAuth(ref.registry, std::move(auth));
}
// 4. Pull plugin binary to cache directory.
auto pull_res = oci_client.pullPluginBinary(ref, effective_cache);
if (!pull_res.has_value()) {
THEMIS_ERROR("OCI pull failed for {}: {}", oci_ref, pull_res.error().context());
return Err<IThemisPlugin*>(pull_res.error().code(), pull_res.error().context());
}
const std::string& binary_path = *pull_res;
THEMIS_INFO("OCI pull succeeded for {}; binary at {}", oci_ref, binary_path);
// 5. Load the downloaded binary via the existing path-based loader.
return loadPluginFromPath(binary_path);
}
Result<void> PluginManager::unloadPlugin(const std::string& name) {
std::lock_guard<std::mutex> lock(mutex_);
auto it = plugins_.find(name);
if (it == plugins_.end()) {
return ErrVoid(errors::ErrorCode::ERR_PLUGIN_NOT_FOUND,
fmt::format("Plugin not found: {}", name));
}
if (!it->second.loaded) {
return ErrVoid(errors::ErrorCode::ERR_PLUGIN_NOT_FOUND,
fmt::format("Plugin not loaded: {}", name));
}
// Block unload if other loaded plugins depend on this one.
auto dependents = findDependentPlugins(name);
if (!dependents.empty()) {
std::string dep_list;
for (const auto& dep : dependents) {
if (!dep_list.empty()) dep_list += ", ";
dep_list += dep;
}
auto error_msg = fmt::format(
"Cannot unload plugin '{}' — {} plugin(s) depend on it: {}",
name, dependents.size(), dep_list);
THEMIS_ERROR("{}", error_msg);
return ErrVoid(errors::ErrorCode::ERR_PLUGIN_DEPENDENCY_CONFLICT, error_msg);
}
auto& entry = it->second;
// Unregister from health monitor before shutting down the instance
if (health_monitor_) {
health_monitor_->unregisterPlugin(name);
}
// Shutdown plugin
if (entry.instance) {
entry.instance->shutdown();
// Get destroy function
auto destroyFunc = reinterpret_cast<DestroyPluginFunc>(
getSymbol(entry.library_handle, "destroyPlugin")
);
if (destroyFunc) {
destroyFunc(entry.instance.release());
} else {
entry.instance.reset();
}
}
// Unload library
unloadLibrary(entry.library_handle);
entry.library_handle = nullptr;
entry.loaded = false;
THEMIS_INFO("Unloaded plugin: {}", name);
return OkVoid();
}
Result<void> PluginManager::unloadAllPlugins() {
std::lock_guard<std::mutex> lock(mutex_);
// Unload all loaded plugins
for (auto& pair : plugins_) {
if (!pair.second.loaded) continue;
auto& entry = pair.second;
if (entry.instance) {
entry.instance->shutdown();
auto destroyFunc = reinterpret_cast<DestroyPluginFunc>(
getSymbol(entry.library_handle, "destroyPlugin")
);
if (destroyFunc) {
destroyFunc(entry.instance.release());
} else {
entry.instance.reset();
}
}
unloadLibrary(entry.library_handle);
entry.library_handle = nullptr;
entry.loaded = false;
}
// Clear all plugins (both loaded and discovered-only) from registry
plugins_.clear();
type_index_.clear();
THEMIS_INFO("Unloaded all plugins");
return OkVoid();
}
Result<IThemisPlugin*> PluginManager::getPlugin(const std::string& name) const {
std::lock_guard<std::mutex> lock(mutex_);
auto it = plugins_.find(name);
if (it != plugins_.end() && it->second.loaded) {
return Ok(it->second.instance.get());
}
return Err<IThemisPlugin*>(errors::ErrorCode::ERR_PLUGIN_NOT_FOUND,
fmt::format("Plugin '{}' not found or not loaded", name));
}
std::vector<IThemisPlugin*> PluginManager::getPluginsByType(PluginType type) const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<IThemisPlugin*> result;
auto it = type_index_.find(type);
if (it != type_index_.end()) {
for (const auto& name : it->second) {
auto plugin_it = plugins_.find(name);
if (plugin_it != plugins_.end() && plugin_it->second.loaded) {
result.push_back(plugin_it->second.instance.get());
}
}
}
return result;
}
std::vector<PluginManifest> PluginManager::listPlugins() const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<PluginManifest> result;
for (const auto& pair : plugins_) {
result.push_back(pair.second.manifest);
}
return result;
}
std::vector<std::string> PluginManager::listLoadedPlugins() const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::string> result;
for (const auto& pair : plugins_) {
if (pair.second.loaded) {
result.push_back(pair.first);
}
}
return result;
}
bool PluginManager::isPluginLoaded(const std::string& name) const {
std::lock_guard<std::mutex> lock(mutex_);
auto it = plugins_.find(name);
return it != plugins_.end() && it->second.loaded;
}
Result<void> PluginManager::reloadPlugin(const std::string& name) {
auto start = std::chrono::steady_clock::now();
// -------------------------------------------------------------------------
// Phase 1: Pre-reload validation and state capture (under mutex)
// -------------------------------------------------------------------------
std::string saved_state;
std::string plugin_path;
std::string expected_hash;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = plugins_.find(name);
if (it == plugins_.end() || !it->second.loaded) {
return ErrVoid(errors::ErrorCode::ERR_PLUGIN_NOT_FOUND,
fmt::format("Plugin not loaded: {}", name));
}
// Block reload if other loaded plugins depend on this one.
auto dependents = findDependentPlugins(name);
if (!dependents.empty()) {
std::string dep_list;
for (const auto& dep : dependents) {
if (!dep_list.empty()) dep_list += ", ";
dep_list += dep;
}
auto error_msg = fmt::format(
"Cannot reload plugin '{}' — {} plugin(s) depend on it: {}",
name, dependents.size(), dep_list);
THEMIS_ERROR("{}", error_msg);
return ErrVoid(errors::ErrorCode::ERR_PLUGIN_DEPENDENCY_CONFLICT, error_msg);
}
// Pre-reload tamper detection: compare current on-disk hash against the
// hash recorded at load time to detect unexpected file mutations.
if (it->second.loaded && !it->second.file_hash.empty()) {
std::string current_hash = calculateFileHash(it->second.path);
if (!current_hash.empty() && current_hash != it->second.file_hash) {