Module: Microsandbox::Rule

Defined in:
lib/microsandbox/network.rb

Overview

Factory for a single network-policy rule. A rule pairs an action (allow/deny) with a direction, a destination, and optional protocol/port filters; rules are evaluated first-match-wins per direction.

‘destination:` accepts a Destination Hash, a shorthand String (“*”, “public”, “1.1.1.1”, “10.0.0.0/8”, “.internal”, “api.example.com”), or nil (any). Mirrors the `Rule` factory in the official SDKs.

Examples:

Microsandbox::Rule.allow(destination: "1.1.1.1", protocol: :tcp, port: "443")
Microsandbox::Rule.deny(destination: Microsandbox::Destination.group(:metadata))
Microsandbox::Rule.allow(direction: :ingress, destination: "10.0.0.0/8", port: "8000-9000")

Class Method Summary collapse

Class Method Details

.allow(destination: nil, direction: :egress, protocol: nil, protocols: nil, port: nil, ports: nil) ⇒ Hash

Build an allow rule. See Microsandbox::Rule for argument semantics.

Returns:

  • (Hash)


55
56
57
# File 'lib/microsandbox/network.rb', line 55

def allow(destination: nil, direction: :egress, protocol: nil, protocols: nil, port: nil, ports: nil)
  build("allow", destination, direction, protocol, protocols, port, ports)
end

.build(action, destination, direction, protocol, protocols, port, ports) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



66
67
68
69
70
71
72
73
74
# File 'lib/microsandbox/network.rb', line 66

def build(action, destination, direction, protocol, protocols, port, ports)
  rule = { "action" => action, "direction" => direction.to_s }
  rule.merge!(normalize_destination(destination))
  protos = (Array(protocols) + Array(protocol)).compact.map(&:to_s)
  rule["protocols"] = protos unless protos.empty?
  prts = (Array(ports) + Array(port)).compact.map(&:to_s)
  rule["ports"] = prts unless prts.empty?
  rule
end

.deny(destination: nil, direction: :egress, protocol: nil, protocols: nil, port: nil, ports: nil) ⇒ Hash

Build a deny rule.

Returns:

  • (Hash)


61
62
63
# File 'lib/microsandbox/network.rb', line 61

def deny(destination: nil, direction: :egress, protocol: nil, protocols: nil, port: nil, ports: nil)
  build("deny", destination, direction, protocol, protocols, port, ports)
end

.normalize_destination(dest) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



77
78
79
80
81
82
83
84
# File 'lib/microsandbox/network.rb', line 77

def normalize_destination(dest)
  case dest
  when nil then {}
  when Hash then dest.each_with_object({}) { |(k, v), a| a[k.to_s] = v }
  when String, Symbol then { "destination" => dest.to_s }
  else raise ArgumentError, "invalid rule destination: #{dest.inspect}"
  end
end