-
Notifications
You must be signed in to change notification settings - Fork 295
/
firewall.rs
854 lines (771 loc) · 31.6 KB
/
firewall.rs
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
use crate::{
catch_up_package_provider::CatchUpPackageProvider,
error::{OrchestratorError, OrchestratorResult},
metrics::OrchestratorMetrics,
registry_helper::RegistryHelper,
};
use ic_config::firewall::{Config as FirewallConfig, FIREWALL_FILE_DEFAULT_PATH};
use ic_logger::{debug, info, warn, ReplicaLogger};
use ic_protobuf::registry::firewall::v1::{FirewallAction, FirewallRule, FirewallRuleDirection};
use ic_registry_keys::FirewallRulesScope;
use ic_sys::fs::write_string_using_tmp_file;
use ic_types::NodeId;
use ic_types::RegistryVersion;
use std::{
cmp::{max, min},
collections::BTreeSet,
convert::TryFrom,
net::IpAddr,
path::PathBuf,
sync::Arc,
};
use tokio::sync::RwLock;
#[derive(Clone, Debug, PartialEq, Eq)]
enum DataSource {
Config,
Registry,
}
/// Provides function to continuously check the Registry to determine if there
/// has been a change in the firewall config, and if so, updates the node's
/// firewall rules file accordingly.
pub(crate) struct Firewall {
registry: Arc<RegistryHelper>,
metrics: Arc<OrchestratorMetrics>,
catchup_package_provider: Arc<CatchUpPackageProvider>,
logger: ReplicaLogger,
configuration: FirewallConfig,
source: DataSource,
compiled_config: String,
last_applied_version: Arc<RwLock<RegistryVersion>>,
/// If true, write the file content even if no change was detected in registry, i.e. first time
must_write: bool,
/// If false, do not update the firewall rules (test mode)
enabled: bool,
node_id: NodeId,
}
impl Firewall {
pub(crate) fn new(
node_id: NodeId,
registry: Arc<RegistryHelper>,
metrics: Arc<OrchestratorMetrics>,
firewall_config: FirewallConfig,
catchup_package_provider: Arc<CatchUpPackageProvider>,
logger: ReplicaLogger,
) -> Self {
let config = firewall_config;
// Disable if the config is the default one (e.g if we're in a test)
let enabled = config
.config_file
.ne(&PathBuf::from(FIREWALL_FILE_DEFAULT_PATH));
if !enabled {
warn!(
logger,
"Firewall configuration not found. Orchestrator does not update firewall rules."
);
}
Self {
registry,
metrics,
catchup_package_provider,
configuration: config,
source: DataSource::Config,
logger,
compiled_config: Default::default(),
last_applied_version: Default::default(),
must_write: true,
enabled,
node_id,
}
}
fn fetch_from_registry(
&self,
registry_version: RegistryVersion,
scope: &FirewallRulesScope,
) -> Vec<FirewallRule> {
self.registry
.get_firewall_rules(registry_version, scope)
.map(|firewall_ruleset| firewall_ruleset.entries)
.unwrap_or_default()
}
/// Checks for the firewall configuration that applies to this node
async fn check_for_firewall_config(
&mut self,
registry_version: RegistryVersion,
) -> OrchestratorResult<()> {
if *self.last_applied_version.read().await == registry_version {
// No update in the registry, so no need to re-check
return Ok(());
}
// Get the subnet ID of this node, if exists
let subnet_id = self
.registry
.get_subnet_id_from_node_id(self.node_id, registry_version)
.unwrap_or(None);
// This is the eventual list of rules fetched from the registry. It is built in the order of the priority:
// Node > Subnet > Replica Nodes > Global
let mut tcp_rules = Vec::<FirewallRule>::new();
let mut udp_rules = Vec::<FirewallRule>::new();
// First, we fetch the rules that are specific for this node
tcp_rules.append(
&mut self
.fetch_from_registry(registry_version, &FirewallRulesScope::Node(self.node_id)),
);
// Then we fetch the rules that are specific for the subnet, if one is assigned
if let Some(subnet_id) = subnet_id {
tcp_rules.append(
&mut self
.fetch_from_registry(registry_version, &FirewallRulesScope::Subnet(subnet_id)),
);
}
// Then the rules that apply to all replica nodes
tcp_rules.append(
&mut self.fetch_from_registry(registry_version, &FirewallRulesScope::ReplicaNodes),
);
// Lastly, rules that apply globally to any type of node
tcp_rules
.append(&mut self.fetch_from_registry(registry_version, &FirewallRulesScope::Global));
if !tcp_rules.is_empty() {
// We found some rules in the registry, so we will not use the default rules in the config file
self.source = DataSource::Registry;
} else {
// We fetched no ruled from the registry, so we will use the default rules in the config file
warn!(
every_n_seconds => 300,
self.logger,
"Firewall configuration was not found in registry. Using config file instead. This warning should be ignored when firewall config is not expected to appear in the registry (e.g., on testnets)."
);
self.source = DataSource::Config;
tcp_rules.append(&mut self.configuration.default_rules.clone());
}
// Whitelisting for node IPs
// In addition to any explicit firewall rules we might apply, we also ALWAYS whitelist all nodes in the registry
// on the ports used by the protocol
// First, get all the registry versions between the latest CUP and the latest version in the registry inclusive.
let registry_versions: Vec<RegistryVersion> = self
.catchup_package_provider
.get_local_cup()
.map(|latest_cup| {
let cup_registry_version = latest_cup.get_oldest_registry_version_in_use();
// Iterate:
// - from min(cup_registry_version, registry_version)
// - to max(cup_registry_version, registry_version).
// The `cup_registry_version` is extracted from the latest seen catchup package.
// The `registry_version` is the latest registry version known to this node.
// In almost any case `registry_version >= cup_registry_version` but there may exist cases where this condition does not hold.
// In that case we should at least include our latest local view of the subnet.
let min_registry_version = min(cup_registry_version, registry_version);
let max_registry_version = max(cup_registry_version, registry_version);
let registry_version_range =
min_registry_version.get()..=max_registry_version.get();
registry_version_range.map(RegistryVersion::from).collect()
})
.unwrap_or_else(|| vec![registry_version]);
// Get the union of all the node IP addresses from the registry
let node_whitelist_ips: BTreeSet<IpAddr> = registry_versions
.into_iter()
.flat_map(|registry_version| {
self.registry
.get_all_nodes_ip_addresses(registry_version)
.unwrap_or_default()
})
.collect();
// Then split it to v4 and v6 separately
let node_ipv4s: Vec<String> = node_whitelist_ips
.iter()
.filter(|ip| ip.is_ipv4())
.map(|ip| ip.to_string())
.collect();
let node_ipv6s: Vec<String> = node_whitelist_ips
.iter()
.filter(|ip| ip.is_ipv6())
.map(|ip| ip.to_string())
.collect();
info!(
self.logger,
"Whitelisting {} node IP addresses ({} v4 and {} v6) on the firewall",
node_whitelist_ips.len(),
node_ipv4s.len(),
node_ipv6s.len()
);
// Build a UDP and TCP rule to whitelist all v4 and v6 IP addresses of nodes.
let tcp_node_whitelisting_rule = FirewallRule {
ipv4_prefixes: node_ipv4s.clone(),
ipv6_prefixes: node_ipv6s.clone(),
ports: self.configuration.tcp_ports_for_node_whitelist.clone(),
action: FirewallAction::Allow as i32,
comment: "Automatic node whitelisting".to_string(),
user: None,
direction: Some(FirewallRuleDirection::Inbound as i32),
};
let udp_node_whitelisting_rule = FirewallRule {
ipv4_prefixes: node_ipv4s.clone(),
ipv6_prefixes: node_ipv6s.clone(),
ports: self.configuration.udp_ports_for_node_whitelist.clone(),
action: FirewallAction::Allow as i32,
comment: "Automatic node whitelisting".to_string(),
user: None,
direction: Some(FirewallRuleDirection::Inbound as i32),
};
// Insert the whitelisting rules at the top of the list (highest priority)
tcp_rules.insert(0, tcp_node_whitelisting_rule);
udp_rules.insert(0, udp_node_whitelisting_rule);
// Blacklisting for Canister HTTP requests
// In addition to any explicit firewall rules we might apply, we also ALWAYS blacklist the ic-http-adapter used from accessing
// all nodes in the registry on specific ports defined in the config file.
// (Currently, this code does not support ranges so we cannot have 1-19999 blocked nicely)
// Build a single rule to blacklist v4 and v6 IP addresses
// that are not supposed to be used by ic-http-adapter.
let ic_http_adapter_rule = FirewallRule {
ipv4_prefixes: node_ipv4s,
ipv6_prefixes: node_ipv6s,
ports: self.configuration.ports_for_http_adapter_blacklist.clone(),
action: FirewallAction::Reject as i32,
comment: "Automatic blacklisting for ic-http-adapter".to_string(),
user: Some("ic-http-adapter".to_string()),
direction: Some(FirewallRuleDirection::Outbound as i32),
};
// Insert the ic-http-adapter rule at the top of the list (highest priority)
tcp_rules.insert(0, ic_http_adapter_rule);
// Generate the firewall file content
let content =
Self::generate_firewall_file_content_full(&self.configuration, tcp_rules, udp_rules);
let changed = content.ne(&self.compiled_config);
if changed {
// Firewall config is different - update it
info!(
self.logger,
"New firewall configuration found (source: {:?}). Updating local firewall.",
self.source
);
}
let mut update_version_metric = false;
if changed || self.must_write {
if content.is_empty() {
warn!(
self.logger,
"No firewall configuration found. Orchestrator will not write any config to a file."
);
} else {
self.write_firewall_file(&content)?;
self.compiled_config = content;
update_version_metric = true;
}
self.must_write = false;
}
if update_version_metric {
// Update registry version metric, even if there was no change, but only if not rolled back
self.metrics
.firewall_registry_version
.set(i64::try_from(registry_version.get()).unwrap_or(-1));
}
*self.last_applied_version.write().await = registry_version;
Ok(())
}
fn write_firewall_file(&self, content: &str) -> OrchestratorResult<()> {
let f = &self.configuration.config_file;
write_string_using_tmp_file(f, content)
.map_err(|e| OrchestratorError::file_write_error(f, e))?;
Ok(())
}
/// Generates a string with the content for the firewall rules file
fn generate_firewall_file_content_full(
config: &FirewallConfig,
tcp_rules: Vec<FirewallRule>,
udp_rules: Vec<FirewallRule>,
) -> String {
config
.file_template
.replace(
"<<IPv4_TCP_RULES>>",
&Self::compile_rules(
&config.ipv4_tcp_rule_template,
&tcp_rules,
vec![
FirewallRuleDirection::Inbound,
FirewallRuleDirection::Unspecified,
],
),
)
.replace(
"<<IPv4_UDP_RULES>>",
&Self::compile_rules(
&config.ipv4_udp_rule_template,
&udp_rules,
vec![
FirewallRuleDirection::Inbound,
FirewallRuleDirection::Unspecified,
],
),
)
.replace(
"<<IPv6_TCP_RULES>>",
&Self::compile_rules(
&config.ipv6_tcp_rule_template,
&tcp_rules,
vec![
FirewallRuleDirection::Inbound,
FirewallRuleDirection::Unspecified,
],
),
)
.replace(
"<<IPv6_UDP_RULES>>",
&Self::compile_rules(
&config.ipv6_udp_rule_template,
&udp_rules,
vec![
FirewallRuleDirection::Inbound,
FirewallRuleDirection::Unspecified,
],
),
)
.replace(
"<<IPv4_OUTBOUND_RULES>>",
&Self::compile_rules(
&config.ipv4_user_output_rule_template,
&tcp_rules,
vec![FirewallRuleDirection::Outbound],
),
)
.replace(
"<<IPv6_OUTBOUND_RULES>>",
&Self::compile_rules(
&config.ipv6_user_output_rule_template,
&tcp_rules,
vec![FirewallRuleDirection::Outbound],
),
)
.replace(
"<<MAX_SIMULTANEOUS_CONNECTIONS_PER_IP_ADDRESS>>",
&config
.max_simultaneous_connections_per_ip_address
.to_string(),
)
}
/// Converts a protobuf action for nftables-specific syntax action
fn action_to_nftables_action(action: Option<FirewallAction>) -> String {
let default = "drop".to_string();
if let Some(real_action) = action {
match real_action {
FirewallAction::Allow => "accept".to_string(),
FirewallAction::Reject => "reject".to_string(),
_ => default,
}
} else {
default
}
}
/// Compiles the entire list of rules using the templates
fn compile_rules(
template: &str,
rules: &[FirewallRule],
directions: Vec<FirewallRuleDirection>,
) -> String {
rules
.iter()
.filter_map(|rule| -> Option<String> {
let rule_direction = rule
.direction
.map(|v| {
FirewallRuleDirection::try_from(v)
.unwrap_or(FirewallRuleDirection::Unspecified)
})
.unwrap_or(FirewallRuleDirection::Unspecified);
if !directions.contains(&rule_direction) {
// Only produce rules with the requested direction
return None;
}
if (!template.contains("<<IPv4_PREFIXES>>") || rule.ipv4_prefixes.is_empty())
&& (!template.contains("<<IPv6_PREFIXES>>") || rule.ipv6_prefixes.is_empty())
{
// Do not produce rules with empty prefix list
return None;
}
if template.contains("<<USER>>")
&& (rule.user.is_none() || rule.user.as_ref().unwrap().is_empty())
{
// Do not produce rules with empty user
return None;
}
Some(
template
.replace(
"<<USER>>",
rule.user.as_ref().unwrap_or(&"".to_string()).as_str(),
)
.replace("<<IPv4_PREFIXES>>", rule.ipv4_prefixes.join(",").as_str())
.replace("<<IPv6_PREFIXES>>", rule.ipv6_prefixes.join(",").as_str())
.replace(
"<<PORTS>>",
rule.ports
.iter()
.map(|port| port.to_string())
.collect::<Vec<String>>()
.join(",")
.as_str(),
)
.replace(
"<<ACTION>>",
&Self::action_to_nftables_action(
FirewallAction::try_from(rule.action).ok(),
),
)
.replace("<<COMMENT>>", &rule.comment),
)
})
.collect::<Vec<String>>()
.join("\n")
}
/// Checks for new firewall config, and if found, update local firewall
/// rules
pub async fn check_and_update(&mut self) {
if !self.enabled {
return;
}
let registry_version = self.registry.get_latest_version();
debug!(
self.logger,
"Checking for firewall config registry version: {}", registry_version
);
if let Err(e) = self.check_for_firewall_config(registry_version).await {
info!(
self.logger,
"Failed to check for firewall config at version {}: {}", registry_version, e
)
}
}
pub fn get_last_applied_version(&self) -> Arc<RwLock<RegistryVersion>> {
Arc::clone(&self.last_applied_version)
}
}
#[cfg(test)]
mod tests {
use std::{io::Write, path::Path};
use ic_config::{ConfigOptional, ConfigSource};
use ic_logger::replica_logger::no_op_logger;
use ic_protobuf::registry::firewall::v1::FirewallRuleSet;
use ic_registry_client_fake::FakeRegistryClient;
use ic_registry_client_helpers::node_operator::{ConnectionEndpoint, NodeRecord};
use ic_registry_keys::{make_firewall_rules_record_key, make_node_record_key};
use ic_registry_proto_data_provider::ProtoRegistryDataProvider;
use ic_test_utilities::crypto::CryptoReturningOk;
use ic_test_utilities_registry::{add_subnet_record, SubnetRecordBuilder};
use ic_test_utilities_types::ids::{node_test_id, subnet_test_id};
use super::*;
const CFG_TEMPLATE_BYTES: &[u8] =
include_bytes!("../../../ic-os/guestos/rootfs/opt/ic/share/ic.json5.template");
const NFTABLES_GOLDEN_BYTES: &[u8] =
include_bytes!("../testdata/nftables_assigned_replica.conf.golden");
#[test]
fn test_firewall_rule_compilation() {
let max_simultaneous_connections_per_ip_address: u32 = 5;
let ipv4_rule_template = format!(
"{} {} {} {}",
"<<IPv4_PREFIXES>>", "<<PORTS>>", "<<ACTION>>", "<<COMMENT>>"
);
let ipv6_rule_template = format!(
"{} {} {} {}",
"<<IPv6_PREFIXES>>", "<<PORTS>>", "<<ACTION>>", "<<COMMENT>>"
);
let file_template = format!(
"{} {} {} {} {}",
"<<MAX_SIMULTANEOUS_CONNECTIONS_PER_IP_ADDRESS>>",
"<<IPv4_TCP_RULES>>",
"<<IPv4_UDP_RULES>>",
"<<IPv6_TCP_RULES>>",
"<<IPv6_UDP_RULES>>",
);
let tcp_rules = vec![
FirewallRule {
ipv4_prefixes: vec!["test_ipv4_1".to_string()],
ipv6_prefixes: vec!["test_ipv6_1".to_string()],
ports: vec![1, 2, 3],
action: 1,
comment: "comment1".to_string(),
user: None,
direction: Some(FirewallRuleDirection::Inbound as i32),
},
FirewallRule {
ipv4_prefixes: vec!["test_ipv4_2".to_string()],
ipv6_prefixes: vec![],
ports: vec![4, 5, 6],
action: 2,
comment: "comment2".to_string(),
user: None,
direction: Some(FirewallRuleDirection::Inbound as i32),
},
FirewallRule {
ipv4_prefixes: vec![],
ipv6_prefixes: vec!["test_ipv6_3".to_string()],
ports: vec![7, 8, 9],
action: 2,
comment: "comment3".to_string(),
user: None,
direction: Some(FirewallRuleDirection::Inbound as i32),
},
FirewallRule {
ipv4_prefixes: vec![],
ipv6_prefixes: vec![],
ports: vec![10, 11, 12],
action: 1,
comment: "comment4".to_string(),
user: None,
direction: Some(FirewallRuleDirection::Inbound as i32),
},
];
let udp_rules = vec![FirewallRule {
ipv4_prefixes: vec!["test_ipv4_5_udp".to_string()],
ipv6_prefixes: vec!["test_ipv6_5_udp".to_string()],
ports: vec![13, 14, 15],
action: 1,
comment: "comment5".to_string(),
user: None,
direction: Some(FirewallRuleDirection::Inbound as i32),
}];
let expected_tcp_rules_compiled_v4 = [
format!("{} {} {} {}", "test_ipv4_1", "1,2,3", "accept", "comment1"),
format!("{} {} {} {}", "test_ipv4_2", "4,5,6", "drop", "comment2"),
];
let expected_udp_rules_compiled_v4 = [format!(
"{} {} {} {}",
"test_ipv4_5_udp", "13,14,15", "accept", "comment5"
)];
let expected_tcp_rules_compiled_v6 = [
format!("{} {} {} {}", "test_ipv6_1", "1,2,3", "accept", "comment1"),
format!("{} {} {} {}", "test_ipv6_3", "7,8,9", "drop", "comment3"),
];
let expected_udp_rules_compiled_v6 = [format!(
"{} {} {} {}",
"test_ipv6_5_udp", "13,14,15", "accept", "comment5"
)];
let expected_file_content = format!(
"{} {} {} {} {}",
max_simultaneous_connections_per_ip_address,
expected_tcp_rules_compiled_v4.join("\n"),
expected_udp_rules_compiled_v4.join("\n"),
expected_tcp_rules_compiled_v6.join("\n"),
expected_udp_rules_compiled_v6.join("\n"),
);
let config = FirewallConfig {
config_file: PathBuf::default(),
file_template,
ipv4_tcp_rule_template: ipv4_rule_template.clone(),
ipv4_udp_rule_template: ipv4_rule_template,
ipv6_tcp_rule_template: ipv6_rule_template.clone(),
ipv6_udp_rule_template: ipv6_rule_template,
ipv4_user_output_rule_template: "".to_string(),
ipv6_user_output_rule_template: "".to_string(),
default_rules: vec![],
tcp_ports_for_node_whitelist: vec![],
udp_ports_for_node_whitelist: vec![],
ports_for_http_adapter_blacklist: vec![],
max_simultaneous_connections_per_ip_address,
};
assert_eq!(
expected_file_content,
Firewall::generate_firewall_file_content_full(&config, tcp_rules, udp_rules)
);
}
#[tokio::test]
async fn nftables_golden_test() {
golden_test(NFTABLES_GOLDEN_BYTES, "assigned_replica").await
}
/// Runs [`Firewall::check_for_firewall_config`] and compares the output against the specified
/// golden output.
async fn golden_test(golden_bytes: &[u8], label: &str) {
let tmp_dir = tempfile::tempdir().unwrap();
let nftables_config_path = tmp_dir.path().join("nftables.conf");
let config = get_config();
let mut replica_firewall_config = config.firewall.unwrap();
replica_firewall_config.config_file = nftables_config_path.clone();
let mut firewall = set_up_firewall_dependencies(replica_firewall_config, tmp_dir.path());
firewall
.check_for_firewall_config(RegistryVersion::new(1))
.await
.expect("Should successfully produce a firewall config");
let golden = String::from_utf8(golden_bytes.to_vec()).unwrap();
let nftables = std::fs::read_to_string(&nftables_config_path).unwrap();
let file_name = format!("nftables_{}.conf", label);
if nftables != golden {
maybe_write_golden(nftables, &file_name);
panic!(
"The output doesn't match the golden. \
In order to see the generated `nftables.conf` file please \
look inside `outputs.zip` file under `bazel-testlogs`"
);
}
}
/// Returns the `ic.json5` config filled with some dummy values.
fn get_config() -> ConfigOptional {
// Make the string parsable by filling the template placeholders with dummy values
let cfg = String::from_utf8(CFG_TEMPLATE_BYTES.to_vec())
.unwrap()
.replace("{{ node_index }}", "0")
.replace("{{ ipv6_address }}", "::")
.replace("{{ backup_retention_time_secs }}", "0")
.replace("{{ backup_purging_interval_secs }}", "0")
.replace("{{ replica_log_debug_overrides }}", "[]")
.replace("{{ nns_url }}", "http://www.fakeurl.com/")
.replace("{{ malicious_behavior }}", "null")
.replace("{{ query_stats_aggregation }}", "\"Enabled\"")
.replace("{{ query_stats_epoch_length }}", "600");
let config_source = ConfigSource::Literal(cfg);
let config: ConfigOptional = config_source.load().unwrap();
config
}
/// When `TEST_UNDECLARED_OUTPUTS_DIR` is set, writes the `content` to a file in the specified
/// directory. Later that file can be inspected manually, i.e. it won't be erased by the test
/// runner.
///
/// See: the `TEST_UNDECLARED_OUTPUTS_DIR` in https://bazel.build/reference/test-encyclopedia
fn maybe_write_golden(content: String, file_name: &str) {
let Ok(dir_str) = std::env::var("TEST_UNDECLARED_OUTPUTS_DIR") else {
return;
};
let dir = PathBuf::from(dir_str);
let mut file = std::fs::File::options()
.read(true)
.write(true)
.create_new(true)
.open(dir.join(file_name))
.unwrap();
file.write_all(content.as_bytes()).unwrap();
}
/// Sets up all the necessary dependencies of the [`Firewall`]
fn set_up_firewall_dependencies(config: FirewallConfig, tmp_dir: &Path) -> Firewall {
let node = node_test_id(0);
let registry = set_up_registry(node);
let registry_helper = Arc::new(RegistryHelper::new(node, registry, no_op_logger()));
let catch_up_package_provider = CatchUpPackageProvider::new(
registry_helper.clone(),
tmp_dir.join("cups"),
Arc::new(CryptoReturningOk::default()),
no_op_logger(),
node,
);
Firewall::new(
node,
registry_helper,
Arc::new(OrchestratorMetrics::new(&ic_metrics::MetricsRegistry::new())),
config,
Arc::new(catch_up_package_provider),
no_op_logger(),
)
}
/// Sets up the registry with:
/// 1) two node records - one for the specified node + another one,
/// 2) a bunch of firewall rules,
/// 3) a Subnet record,
/// and returns a registry client.
fn set_up_registry(node: NodeId) -> Arc<FakeRegistryClient> {
let registry_version = RegistryVersion::new(1);
let registry_data_provider = Arc::new(ProtoRegistryDataProvider::new());
let subnet_record = SubnetRecordBuilder::from(&[node]).build();
// add [`NodeRecord`] for the given node
add_node_record(
®istry_data_provider,
registry_version,
node,
/*ip=*/ "1.1.1.1",
);
// add [`NodeRecord`] for some other node
add_node_record(
®istry_data_provider,
registry_version,
node_test_id(123),
/*ip=*/ "2.2.2.2",
);
// Add a bunch of firewall rules for different scopes.
add_firewall_rules_record(
®istry_data_provider,
registry_version,
&FirewallRulesScope::Subnet(subnet_test_id(1)),
/*ip=*/ "3.3.3.3",
/*port=*/ 1003,
);
add_firewall_rules_record(
®istry_data_provider,
registry_version,
&FirewallRulesScope::ReplicaNodes,
/*ip=*/ "4.4.4.4",
/*port=*/ 1004,
);
add_firewall_rules_record(
®istry_data_provider,
registry_version,
&FirewallRulesScope::Node(node),
/*ip=*/ "5.5.5.5",
/*port=*/ 1005,
);
add_firewall_rules_record(
®istry_data_provider,
registry_version,
&FirewallRulesScope::Global,
/*ip=*/ "6.6.6.6",
/*port=*/ 1006,
);
add_subnet_record(
®istry_data_provider,
registry_version.get(),
subnet_test_id(1),
subnet_record,
);
let registry = Arc::new(FakeRegistryClient::new(
Arc::clone(®istry_data_provider) as Arc<_>
));
registry.update_to_latest_version();
registry
}
/// Adds a [`NodeRecord`] to the registry.
fn add_node_record(
registry_data_provider: &Arc<ProtoRegistryDataProvider>,
registry_version: RegistryVersion,
node: NodeId,
ip: &str,
) {
registry_data_provider
.add(
&make_node_record_key(node),
registry_version,
Some(NodeRecord {
http: Some(ConnectionEndpoint {
ip_addr: String::from(ip),
port: 80,
}),
xnet: None,
node_operator_id: vec![],
chip_id: None,
hostos_version_id: None,
public_ipv4_config: None,
domain: None,
}),
)
.expect("Failed to add node record.");
}
/// Adds a [`FirewallRule`] to the registry.
fn add_firewall_rules_record(
registry_data_provider: &Arc<ProtoRegistryDataProvider>,
registry_version: RegistryVersion,
scope: &FirewallRulesScope,
ip: &str,
port: u32,
) {
registry_data_provider
.add(
&make_firewall_rules_record_key(scope),
registry_version,
Some(FirewallRuleSet {
entries: vec![FirewallRule {
ipv4_prefixes: vec![String::from(ip)],
ipv6_prefixes: vec![format!("::ffff:{}", ip)],
ports: vec![port],
action: FirewallAction::Allow as i32,
comment: scope.to_string(),
user: None,
direction: Some(FirewallRuleDirection::Inbound as i32),
}],
}),
)
.unwrap();
}
}