Your observation doesn't contradict the use of firewall rules to accomplish this.
Binding with port 0 as argument for AF_INET binds a random available port, not port 0. This is documented behavior of Linux and likely every other OS implementing a BSD-style socket interface.
Also note that ufw is just a tiny, non-standard wrapper for the much more powerful nftables/iptables interfaces