Late Escaping in WordPress

Late escaping is often seen as unnecessary. I remember when I used to think this:

“Why should I late escape something that I know is safe?”

Let’s examine the various parts of that statement.  The “I” really means not just me — the developer currently writing the code — but me at this current moment in time. While debugging old code, how often have you asked yourself who the “genius” who thought up some “clever” solution was only to realize you were the one who’d written it 6 months ago?

Late escaping future-proofs your code by making it easy to spot escaping. Otherwise, to check the security of it, you’d probably need to re-read all of the code surrounding it, check which functions are called, where the inputs come from, etc. It’s easier and less time-consuming to rely on late escaping instead.

The second part of this statement I want to examine is the “is safe” part. Safe in this context really means, “is not currently known to be insecure” with currently being the key word. The statement “the code is safe” is probably accurate at the point in time when you originally commit it. The problem is, code has a tendency to change. The function you’re calling that returns the “currently safe” code might change in the future. Or, the inputs to that function will change and be from a source you didn’t initially anticipate. That change could introduce user-provided data in a way you didn’t expect and end up being insecure. It’s safest to rely on late-escaping because it’s more resilient to unanticipated changes in the future.

I sometimes hear from developers who are worried that late escaping will hurt the performance of their site. Escaping — even with functions traditionally thought of as slow such as wp_kses_post() — is a drop in the bucket compared to one additional MySQL query on a site. If you take a look at this great post by Zack Tollman on the performance of wp_kses, you can see that older versions of PHP were a bit slow on long content. However, running wp_kses on longer content in PHP 7 and above* shows performance improvements similar to those of HHVM.

So you can rest easy — adding late escaping won’t slow down your site, and it offers many benefits:

  1. It’s easier to scan the code using PHPCS
  2. It’s easier to read during peer code review
  3. It’s more resilient to changes in other parts of the codebase
  4. Removes ambiguity and adds clarity for future code maintainers (including yourself!)
  5. Negligible performance impact

 

*For reference, WordPress VIP runs PHP 7 at a minimum