Article 4VMH9 CodeSOD: A Very Personal Role

CodeSOD: A Very Personal Role

by
Remy Porter
from The Daily WTF on (#4VMH9)

Nohemi has a program which needs to apply role-based security. Due to their organizational needs, the rules for role names are a bit unusual. Some roles have to be a case-insensitive match. But some roles have a more flexible pattern they need to have. This is how her co-worker implemented this:

 public static String decodeRole(String role) { String decodedRole = ""; if (role != null && !role.trim().equals("")) { if (role.trim().equalsIgnoreCase(ROLE_1_STRING)) decodedRole = CODE_ROLE_1; else if (role.trim().equalsIgnoreCase(ROLE_2_STRING)) decodedRole = CODE_ROLE_2; else if (role.trim().equalsIgnoreCase(ROLE_3_STRING)) decodedRole = CODE_ROLE_3; else if (personalContains(role.trim(), ROLE_4_STRING)) decodedRole = CODE_ROLE_4; } return decodedRole; }

Here's the key method which does this translation. Roles 1, 2 and 3 must be an exact match. Role 4, on the other hand, has to apply their special rule, a rule so complicated it can only be evaluated via a regular expression:

 private static final String REGEXP_SUFFIX = ").*$"; private static final String REGEXP_PREFIX = "^.*("; public static boolean personalContains(String fatherString, String toSearchString) { Pattern p = Pattern.compile(REGEXP_PREFIX + toSearchString.toLowerCase() + REGEXP_SUFFIX); Matcher m = p.matcher(fatherString.toLowerCase()); boolean matchFound = m.matches(); if (matchFound) return true; else return false; }

It's a contains check. If your search string were, say, ROLE_4, the constructed regex would be ^.*(ROLE_4).*$, which is "the start of the string, followed by zero or more of any character, followed by ROLE_4, followed by zero or more of any character, followed by the end of the string.

It's a contains check. This isn't even the right way to do this is regular expressions, since ROLE_4 would be a regex which matches if any substring is ROLE_4, but regexes aren't the right way to do this in the first place, since Java has a lovely String.contains method already. The entire personalContains method could be removed.

The real WTF, though, is that instead of returning m.matches(), they have to do this:

 if (matchFound) return true; else return false;
proget-icon.png [Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how! TheDailyWtf?d=yIl2AUoC8zAouyn6P_sG1s
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments