mofa-foundation 0.1.1

MoFA Foundation - Core building blocks and utilities
Documentation
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
//! Concrete event response plugin implementations
//!
//! This module contains specific plugin implementations for handling different
//! types of operational events.

use super::event::{Event, EventType};
use super::plugin::{BaseEventResponsePlugin, EventResponseConfig, EventResponsePlugin};
use async_trait::async_trait;
use mofa_kernel::plugin::{PluginPriority, PluginResult};
use std::collections::HashMap;
use std::sync::RwLock;

// ============================================================================
// Server Fault Response Plugin
// ============================================================================

/// Plugin for handling server fault events
///
/// Workflow:
/// 1. Attempt to automatically restart the server
/// 2. Notify the administrator about the fault
pub struct ServerFaultResponsePlugin {
    base: BaseEventResponsePlugin,
    config: RwLock<EventResponseConfig>,
}

impl ServerFaultResponsePlugin {
    /// Create a new server fault response plugin
    pub fn new() -> Self {
        let handled_event_types = vec![EventType::ServerFault];
        let workflow_steps = vec![
            "attempt_auto_restart".to_string(),
            "notify_administrator".to_string(),
        ];

        let base = BaseEventResponsePlugin::new(
            "server-fault-responder",
            "Server Fault Responder",
            handled_event_types.clone(), // Clone it to avoid move error
            workflow_steps,
        )
        .with_priority(PluginPriority::High) // Server faults should be handled quickly
        .with_max_impact_scope("instance");

        let config = RwLock::new(EventResponseConfig {
            handled_event_types,
            priority: PluginPriority::High,
            ..Default::default()
        });

        Self { base, config }
    }

    /// Attempt to restart the server automatically
    async fn attempt_auto_restart(&self, server: &str) -> Result<bool, String> {
        // Simulate server restart logic
        println!("Attempting to restart server: {}", server);
        // In real implementation, this would call an API or execute a command

        // Return success for now
        Ok(true)
    }

    /// Notify the administrator about the server fault
    async fn notify_administrator(&self, event: &Event) -> Result<(), String> {
        // Simulate notification logic (email, SMS, Slack, etc.)
        println!("Notifying administrator about server fault:");
        println!("  Event ID: {}", event.id);
        println!("  Source: {}", event.source);
        println!("  Description: {}", event.description);

        Ok(())
    }
}

#[async_trait]
impl EventResponsePlugin for ServerFaultResponsePlugin {
    fn config(&self) -> &EventResponseConfig {
        panic!("config() should not be called directly on this plugin");
    }

    async fn update_config(&mut self, config: EventResponseConfig) -> PluginResult<()> {
        // Update the local config
        {
            let mut current_config = self.config.write().unwrap();
            *current_config = config.clone();
        }
        // Update the base config
        self.base.update_config(config).await
    }

    fn can_handle(&self, event: &Event) -> bool {
        self.base.can_handle(event)
    }

    async fn handle_event(&mut self, event: Event) -> PluginResult<Event> {
        self.base.handle_event(event).await
    }

    async fn execute_workflow(&self, event: &Event) -> PluginResult<HashMap<String, String>> {
        let mut result = HashMap::new();

        // Step 1: Attempt to automatically restart the server
        let server_name = event
            .data
            .get("server")
            .and_then(|s| s.as_str())
            .unwrap_or("unknown");

        let restart_result = self.attempt_auto_restart(server_name).await;

        match restart_result {
            Ok(success) => {
                result.insert(
                    "auto_restart".to_string(),
                    if success {
                        "success".to_string()
                    } else {
                        "failed".to_string()
                    },
                );
            }
            Err(err) => {
                result.insert("auto_restart".to_string(), format!("error: {}", err));
            }
        }

        // Step 2: Notify the administrator
        match self.notify_administrator(event).await {
            Ok(_) => {
                result.insert("notify_admin".to_string(), "success".to_string());
            }
            Err(err) => {
                result.insert("notify_admin".to_string(), format!("error: {}", err));
            }
        }

        // Add workflow status
        result.insert(
            "workflow_status".to_string(),
            "server_fault_workflow_completed".to_string(),
        );

        Ok(result)
    }
}

#[async_trait]
impl mofa_kernel::plugin::AgentPlugin for ServerFaultResponsePlugin {
    fn metadata(&self) -> &mofa_kernel::plugin::PluginMetadata {
        self.base.metadata()
    }

    fn state(&self) -> mofa_kernel::plugin::PluginState {
        self.base.state()
    }

    async fn load(
        &mut self,
        ctx: &mofa_kernel::plugin::PluginContext,
    ) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.load(ctx).await
    }

    async fn init_plugin(&mut self) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.init_plugin().await
    }

    async fn start(&mut self) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.start().await
    }

    async fn stop(&mut self) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.stop().await
    }

    async fn unload(&mut self) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.unload().await
    }

    async fn execute(&mut self, input: String) -> mofa_kernel::plugin::PluginResult<String> {
        self.base.execute(input).await
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn into_any(self: Box<Self>) -> Box<dyn std::any::Any> {
        self
    }
}

impl From<ServerFaultResponsePlugin> for Box<dyn EventResponsePlugin> {
    fn from(plugin: ServerFaultResponsePlugin) -> Self {
        Box::new(plugin)
    }
}

impl From<ServerFaultResponsePlugin> for Box<dyn mofa_kernel::plugin::AgentPlugin> {
    fn from(plugin: ServerFaultResponsePlugin) -> Self {
        Box::new(plugin)
    }
}

// ============================================================================
// Network Attack Response Plugin
// ============================================================================

/// Plugin for handling network attack events
///
/// Workflow:
/// 1. Block the attacking IP address
/// 2. Analyze the attack pattern
/// 3. Notify the security team
pub struct NetworkAttackResponsePlugin {
    base: BaseEventResponsePlugin,
    config: RwLock<EventResponseConfig>,
}

impl NetworkAttackResponsePlugin {
    /// Create a new network attack response plugin
    pub fn new() -> Self {
        let handled_event_types = vec![EventType::NetworkAttack];
        let workflow_steps = vec![
            "block_attacking_ip".to_string(),
            "analyze_attack_pattern".to_string(),
            "notify_security_team".to_string(),
        ];

        let base = BaseEventResponsePlugin::new(
            "network-attack-responder",
            "Network Attack Responder",
            handled_event_types.clone(), // Clone it to avoid move error
            workflow_steps,
        )
        .with_priority(PluginPriority::Critical) // Network attacks require immediate action
        .with_max_impact_scope("system");

        let config = RwLock::new(EventResponseConfig {
            handled_event_types,
            priority: PluginPriority::Critical,
            ..Default::default()
        });

        Self { base, config }
    }

    /// Block the attacking IP address
    async fn block_attacking_ip(&self, ip: &str) -> Result<bool, String> {
        // Simulate IP blocking logic
        println!("Blocking attacking IP: {}", ip);
        // In real implementation, this would update firewall rules, etc.

        Ok(true)
    }

    /// Analyze the attack pattern
    async fn analyze_attack_pattern(&self, event: &Event) -> Result<String, String> {
        // Simulate attack analysis
        println!("Analyzing attack pattern for event: {}", event.id);

        Ok("ddos_attack".to_string()) // Dummy analysis result
    }

    /// Notify the security team about the attack
    async fn notify_security_team(&self, event: &Event, attack_type: &str) -> Result<(), String> {
        // Simulate security notification
        println!("Notifying security team about {} attack:", attack_type);
        println!("  Event ID: {}", event.id);
        println!("  Source IP: {:?}", event.data.get("source_ip"));

        Ok(())
    }
}

#[async_trait]
impl EventResponsePlugin for NetworkAttackResponsePlugin {
    fn config(&self) -> &EventResponseConfig {
        panic!("config() should not be called directly on this plugin");
    }

    async fn update_config(&mut self, config: EventResponseConfig) -> PluginResult<()> {
        // Update the local config
        {
            let mut current_config = self.config.write().unwrap();
            *current_config = config.clone();
        }
        // Update the base config
        self.base.update_config(config).await
    }

    fn can_handle(&self, event: &Event) -> bool {
        self.base.can_handle(event)
    }

    async fn handle_event(&mut self, event: Event) -> PluginResult<Event> {
        self.base.handle_event(event).await
    }

    async fn execute_workflow(&self, event: &Event) -> PluginResult<HashMap<String, String>> {
        let mut result = HashMap::new();

        // Step 1: Block attacking IP
        let source_ip = event
            .data
            .get("source_ip")
            .and_then(|ip| ip.as_str())
            .unwrap_or("unknown");

        let block_result = self.block_attacking_ip(source_ip).await;
        match block_result {
            Ok(success) => {
                result.insert(
                    "block_ip".to_string(),
                    if success {
                        "success".to_string()
                    } else {
                        "failed".to_string()
                    },
                );
            }
            Err(err) => {
                result.insert("block_ip".to_string(), format!("error: {}", err));
            }
        }

        // Step 2: Analyze attack pattern
        let analysis_result = self.analyze_attack_pattern(event).await;
        let attack_type = match analysis_result {
            Ok(attack) => {
                result.insert("attack_analysis".to_string(), attack.clone());
                attack
            }
            Err(err) => {
                result.insert("attack_analysis".to_string(), format!("error: {}", err));
                "unknown".to_string()
            }
        };

        // Step 3: Notify security team
        if let Err(err) = self.notify_security_team(event, &attack_type).await {
            result.insert("notify_security".to_string(), format!("error: {}", err));
        } else {
            result.insert("notify_security".to_string(), "success".to_string());
        }

        // Add workflow status
        result.insert(
            "workflow_status".to_string(),
            "network_attack_workflow_completed".to_string(),
        );

        Ok(result)
    }
}

#[async_trait]
impl mofa_kernel::plugin::AgentPlugin for NetworkAttackResponsePlugin {
    fn metadata(&self) -> &mofa_kernel::plugin::PluginMetadata {
        self.base.metadata()
    }

    fn state(&self) -> mofa_kernel::plugin::PluginState {
        self.base.state()
    }

    async fn load(
        &mut self,
        ctx: &mofa_kernel::plugin::PluginContext,
    ) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.load(ctx).await
    }

    async fn init_plugin(&mut self) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.init_plugin().await
    }

    async fn start(&mut self) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.start().await
    }

    async fn stop(&mut self) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.stop().await
    }

    async fn unload(&mut self) -> mofa_kernel::plugin::PluginResult<()> {
        self.base.unload().await
    }

    async fn execute(&mut self, input: String) -> mofa_kernel::plugin::PluginResult<String> {
        self.base.execute(input).await
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn into_any(self: Box<Self>) -> Box<dyn std::any::Any> {
        self
    }
}

impl From<NetworkAttackResponsePlugin> for Box<dyn EventResponsePlugin> {
    fn from(plugin: NetworkAttackResponsePlugin) -> Self {
        Box::new(plugin)
    }
}

impl From<NetworkAttackResponsePlugin> for Box<dyn mofa_kernel::plugin::AgentPlugin> {
    fn from(plugin: NetworkAttackResponsePlugin) -> Self {
        Box::new(plugin)
    }
}