4
\$\begingroup\$

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\>[^\<]*\<\//, 'UserPassword>[FILTERED]</' end 

Is there a better, safer way of doing it?

\$\endgroup\$
2
  • \$\begingroup\$Is the XML always the same schema? Can it be validated with a Schema or DTD?\$\endgroup\$
    – JoeGeeky
    CommentedDec 17, 2011 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
    CommentedDec 18, 2011 at 17:05

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\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
    CommentedDec 18, 2011 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\$CommentedDec 18, 2011 at 21:55

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.