We're storing the xml communications with an external service in a text in the db and in a before_create I've got the following:

  # filter opera password
  def remove_password!
    self.request.gsub!  /UserPassword\>[^\<]*\<\//,

Is there a better, safer way of doing it?

  • \$\begingroup\$ Is the XML always the same schema? Can it be validated with a Schema or DTD? \$\endgroup\$ – JoeGeeky Dec 17 '11 at 23:04
  • \$\begingroup\$ yes the schema in the header stills but for several reasons at this point I've got only the string, and I'd avoid to re-convert it into xml \$\endgroup\$ – ecoologic Dec 18 '11 at 17:05

That depends on how confident you are that neither of these cases will be true:

  • Another tag like will be introduced that you will want to leave unfiltered
  • No nested tags will appear within the tag

An example of the last would be:

<UserPassword><for name="boy">Sue</for></UserPassword>

It seems your assumptions are safe, but if you want to be certain, go with

self.request.gsub! /\<UserPassword\>.+?\</UserPassword\>/gm, '<UserPassword>[FILTERED]</UserPassword>'

By eliminating the greediness of the regex, you can match the exact tag you mean and reduce the assumptions that will come back and bite you.

  • \$\begingroup\$ there are no sub-tags in userPassword, the reason why I hadn't included the complete close tag is because some servers respond with a tag-prefix e.g.: <n3:UserPassword> though I understand that including the close tag is definitely a must \$\endgroup\$ – ecoologic Dec 18 '11 at 17:09
  • \$\begingroup\$ If you know the form of the tag-prefix, then specify it as optional. E.g.: \<(?:[a-zA-Z]+\d+:)?UserPassword\>/gm The non-capturing group ensures you will not get it in your password (if that matters) but if you specify the form, you can be sure you aren't getting garbage from the server. \$\endgroup\$ – Steve Ross Dec 18 '11 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.