← Back to Demos & Examples

06_policy_firewall_compiler.vk

Raw .vk
// Example 06: Declarative Firewall Policy DSL Compiler & Stateful Rate-Limiter
// Track A (ORO VM) : veko run examples/06_policy_firewall_compiler.vk
// Track A (.vko)   : veko compile --vko examples/06_policy_firewall_compiler.vk -o dist/06.vko ; veko run dist/06.vko
// Track B (Wasm 3) : veko run --wasm examples/06_policy_firewall_compiler.vk
// Track C (Native) : veko compile --native examples/06_policy_firewall_compiler.vk -o dist/06.exe ; ./dist/06.exe
use [str]

// Helper invoked by the parse-block dialect to construct typed rule records
make-rule = fn [proto cidr port auth limit] [
	{
		proto = proto
		cidr  = cidr
		port  = port
		auth  = auth
		limit = limit
	}
]

// 1. Parse declarative policy rules from homoiconic [ ... ] data
mut rules = []
mut default-action = .deny

policy-spec = quote [
	default .deny
	route .tcp '10.10.' 8443 .mtls 2
	route .udp '192.168.' 51820 .open 5
	route .tcp '0.0.0.' 80 .deny 0
]

ok = parse-block policy-spec [
	any [
		['default' act = enum!] [
			default-action = act
		]
		['route' p = enum! c = str! pt = int! a = enum! lim = int!] [
			push mut rules (make-rule p c pt a lim)
		]
	]
]

println (str/append 'compiled-rules=' (mold rules.len))

// 2. Build a stateful evaluator closure with per-rule hit counters (ORO map)
make-evaluator = fn [rule-list fallback] [
	mut hits = {}
	fn [pkt] [
		matched = filter rule-list fn [r] [
			(r.proto == pkt.proto) and (r.port == pkt.port) and (str/contains? pkt.ip r.cidr)
		]
		if empty? matched [return fallback]

		rule = first matched
		if rule.auth == .deny [return .blocked]
		if (rule.auth == .mtls) and (not pkt.has-cert) [return .unauthenticated]

		key = str/append pkt.ip (mold pkt.port)
		cur = if map/has? hits key [map/get hits key] else [0]
		if cur >= rule.limit [return .rate-limited]

		hits = map/set hits key (cur + 1)
		.allowed
	]
]

eval-pkt = make-evaluator rules default-action

// 3. Simulate traffic stream against the compiled policy
traffic = [
	{ proto = .tcp, ip = '10.10.4.20',   port = 8443,  has-cert = false }
	{ proto = .tcp, ip = '10.10.4.20',   port = 8443,  has-cert = true  }
	{ proto = .tcp, ip = '10.10.4.20',   port = 8443,  has-cert = true  }
	{ proto = .tcp, ip = '10.10.4.20',   port = 8443,  has-cert = true  }
	{ proto = .udp, ip = '192.168.1.9',  port = 51820, has-cert = false }
	{ proto = .tcp, ip = '0.0.0.5',      port = 80,    has-cert = true  }
	{ proto = .tcp, ip = '172.16.0.1',   port = 9999,  has-cert = true  }
]

each traffic fn [pkt] [
	verdict = (eval-pkt pkt)
	label = match verdict [
		.allowed         ['ALLOW']
		.rate-limited    ['LIMIT']
		.unauthenticated ['NO_MTLS']
		.blocked         ['BLOCK']
		_                ['DENY_DEFAULT']
	]
	println (str/join [label pkt.ip pkt.port] ' ')
]