# filter out password in xml string

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
end


Is there a better, safer way of doing it?

• Is the XML always the same schema? Can it be validated with a Schema or DTD? – JoeGeeky Dec 17 '11 at 23:04
• 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 – 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.

• 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 – ecoologic Dec 18 '11 at 17:09
• 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. – Steve Ross Dec 18 '11 at 21:55