lib/WWW/Hetzner/CLI/Cmd/Firewall/Cmd/AddRule.pm untested

filter: Statementstmt 0.0% 0 / 33 Branchbran 0.0% 0 / 4 Conditioncond 0.0% 0 / 4 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 4 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 46 CC 3 SCAR 19.5
CC
3
Cov
0%
execute
12.0
BEGIN
2.0
BEGIN
2.0
CRAP 7.0
1 package WWW::Hetzner::CLI::Cmd::Firewall::Cmd::AddRule;
2 # ABSTRACT: Add a rule to a firewall
3  
4 our $VERSION = '0.100';
5  
6 use Moo;
7 use MooX::Cmd;
8 use MooX::Options protect_argv => 0, usage_string => 'USAGE: hcloud.pl firewall add-rule <id> --direction <in|out> --protocol <tcp|udp|icmp|gre|esp> --port <port> [--source-ips <ips>]';
9  
10 option direction => (
11 is => 'ro',
12 format => 's',
13 required => 1,
14 doc => 'Direction: in or out',
15 );
16  
17 option protocol => (
18 is => 'ro',
19 format => 's',
20 required => 1,
21 doc => 'Protocol: tcp, udp, icmp, gre, esp',
22 );
23  
24 option port => (
25 is => 'ro',
26 format => 's',
27 doc => 'Port or port range (e.g. 22 or 80-443)',
28 );
29  
30 option 'source_ips' => (
31 is => 'ro',
32 format => 's@',
33 long_doc => 'source-ips',
34 doc => 'Source IPs (can specify multiple)',
35 default => sub { ['0.0.0.0/0', '::/0'] },
36 );
37  
38 sub execute {
39 my ($self, $args, $chain) = @_;
40 my $id = $args->[0] or die "Usage: hcloud.pl firewall add-rule <id> --direction <in|out> --protocol <tcp|udp|icmp> --port <port>\n";
41  
42 my $main = $chain->[0];
43 my $cloud = $main->cloud;
44  
45 # Get existing firewall
46 my $fw = $cloud->firewalls->get($id);
47 my @rules = @{ $fw->rules // [] };
48  
49 # Build new rule
50 my $rule = {
51 direction => $self->direction,
52 protocol => $self->protocol,
53 };
54 $rule->{port} = $self->port if $self->port;
55  
56 if ($self->direction eq 'in') {
57 $rule->{source_ips} = $self->source_ips;
58 } else {
59 $rule->{destination_ips} = $self->source_ips; # reuse for simplicity
60 }
61  
62 push @rules, $rule;
63  
64 print "Adding rule to firewall $id...\n";
65 $cloud->firewalls->set_rules($id, @rules);
66 print "Rule added.\n";
67 }
68  
69 1;
70  
71 __END__