At the Google I/O conference at the end of May I asked this question.
The answer was that GWT's client-side JSON library eventually calls
eval() when it converts a string to a JSON value. The underlying
assumption, therefore, is that you're consuming JSON strings from a
trusted source. I expressed some concern at that because not everyone
is consuming trusted strings and I wasn't aware of any advance notice
that parsing JSON is a trusted code path in GWT. There was some talk
about changing the parse() method to be safe and introducing an
unsafeParse() that you could invoke on trusted strings to gain some
speed benefits. I don't know if any of that talk turned into code.
Ian
There are two kinds of strings under discussion here: the overall JSON
data payload that is a "string", and then the string values embedded
within the data payload. If the payload is coming from a trusted
server, I don't think it matters if the embedded strings contain
user-controlled input, but someone else should check me here. My
logic is that the trusted server should be generating valid JSON, so
the embedded strings should be valid Javascript strings with properly
escaped quotes and newlines, and no illegal characters. Also, because
the server is trusted, it won't be generating object literals that
contain function definitions or invocations. I think, so long as you
don't try to interpret user-controlled strings as HTML, Javascript,
SQL, or anything else and remember that it's "just a string", you
should be OK. As far as I know, all the official GWT widgets will
sanitize incoming strings before displaying them *unless* you tell the
widget to interpret the string as HTML. So, for example, I _think_
the following is safe:
String userString = Window.prompt("Do your worst", "");
RootPanel.get().add(new Label(userString));
On the other hand, the following is dangerous:
String userString = Window.prompt("Do your worst", "");
RootPanel.get().add(new HTML(userString));
So, in summary, if the server generating the JSON can be trusted to
generate well-formed JSON, I think it's safe to pass that JSON to
eval() to convert the string into an object, regardless of the source
of the values within the JSON data. Once you've got an object on your
hands, though, then you need to be careful what you do with the data
within it.
Ian