Limit WordPress REST API route to an IP range

If you are exposing an API route for a specific service, check if they make requests or send responses from the same IP or IP range.

Especially if you are expecting payloads from webhooks or sensitive user data, it's a good security measure and easy to implement.

In WordPress, generally, the permission_callback is used for checking user's capabilities, but it's the appropriate place for doing other conditionals:

register_rest_route(
    '3rdPartyService/v1',
    '/listener',
    [
        'permission_callback' => static function (WP_REST_Request $request): bool {
            $ipRangeStart = ip2long('XXX.XXX.XXX.XX');
            $ipRangeEnd = ip2long('XXX.XXX.XX.XX');
            $requestIp = ip2long($_SERVER['REMOTE_ADDR']);

            return ($requestIp >= $ipRangeStart) && ($requestIp <= $ipRangeEnd);
        },
    ]
);