Skip to content

Commit 8a11a4e

Browse files
committed
Adds handling for common JSON parsing exceptions and wraps them in a JwtException
Move the parser error handling logic out of DefaultJwtParser into the new JwtDeserializer and wraps them with developer freiendly exceptions Add check for common JSON parsing exceptions like stack overflow when parsing deeply nested (or malformed) JSON
1 parent d9da0e3 commit 8a11a4e

File tree

8 files changed

+146
-13
lines changed

8 files changed

+146
-13
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
## Release Notes
22

3+
### 0.11.3
4+
5+
This patch release:
6+
7+
* Adds handling for common JSON parsing exceptions and wraps them in a `JwtException`.
8+
39
### 0.11.2
410

511
This patch release:

impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
import io.jsonwebtoken.impl.lang.LegacyServices;
4343
import io.jsonwebtoken.io.Decoder;
4444
import io.jsonwebtoken.io.Decoders;
45-
import io.jsonwebtoken.io.DeserializationException;
4645
import io.jsonwebtoken.io.Deserializer;
4746
import io.jsonwebtoken.lang.Assert;
4847
import io.jsonwebtoken.lang.DateFormats;
@@ -111,7 +110,7 @@ public DefaultJwtParser() { }
111110
@Override
112111
public JwtParser deserializeJsonWith(Deserializer<Map<String, ?>> deserializer) {
113112
Assert.notNull(deserializer, "deserializer cannot be null.");
114-
this.deserializer = deserializer;
113+
this.deserializer = new JwtDeserializer<>(deserializer);
115114
return this;
116115
}
117116

@@ -253,7 +252,7 @@ public Jwt parse(String jwt) throws ExpiredJwtException, MalformedJwtException,
253252
if (this.deserializer == null) {
254253
// try to find one based on the services available
255254
// TODO: This util class will throw a UnavailableImplementationException here to retain behavior of previous version, remove in v1.0
256-
this.deserializer = LegacyServices.loadFirst(Deserializer.class);
255+
this.deserializeJsonWith(LegacyServices.loadFirst(Deserializer.class));
257256
}
258257

259258
Assert.hasText(jwt, "JWT String argument cannot be null or empty.");
@@ -617,11 +616,7 @@ public Jws<Claims> onClaimsJws(Jws<Claims> jws) {
617616

618617
@SuppressWarnings("unchecked")
619618
protected Map<String, ?> readValue(String val) {
620-
try {
621-
byte[] bytes = val.getBytes(Strings.UTF_8);
622-
return deserializer.deserialize(bytes);
623-
} catch (DeserializationException e) {
624-
throw new MalformedJwtException("Unable to read JSON value: " + val, e);
625-
}
619+
byte[] bytes = val.getBytes(Strings.UTF_8);
620+
return deserializer.deserialize(bytes);
626621
}
627622
}

impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParserBuilder.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ public JwtParser build() {
204204
allowedClockSkewMillis,
205205
expectedClaims,
206206
base64UrlDecoder,
207-
deserializer,
207+
new JwtDeserializer<>(deserializer),
208208
compressionCodecResolver));
209209
}
210210
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
* Copyright (C) 2021 jsonwebtoken.io
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.jsonwebtoken.impl;
17+
18+
import io.jsonwebtoken.MalformedJwtException;
19+
import io.jsonwebtoken.io.DeserializationException;
20+
import io.jsonwebtoken.io.Deserializer;
21+
import io.jsonwebtoken.io.IOException;
22+
import io.jsonwebtoken.lang.Assert;
23+
24+
import java.nio.charset.StandardCharsets;
25+
26+
/**
27+
* A {@link Deserializer} implementation that wraps another Deserializer implementation to adds common JWT related
28+
* error handling.
29+
* @param <T> type of object to deserialize.
30+
* @since 0.11.3
31+
*/
32+
class JwtDeserializer<T> implements Deserializer<T> {
33+
34+
static final String MALFORMED_ERROR = "Malformed JWT JSON: ";
35+
static final String MALFORMED_COMPLEX_ERROR = "Malformed or excessively complex JWT JSON. This could reflect a potential malicious JWT, please investigate the JWT source further. JSON: ";
36+
37+
private final Deserializer<T> deserializer;
38+
39+
JwtDeserializer(Deserializer<T> deserializer) {
40+
Assert.notNull(deserializer, "deserializer cannot be null.");
41+
this.deserializer = deserializer;
42+
}
43+
44+
@Override
45+
public T deserialize(byte[] bytes) throws DeserializationException {
46+
try {
47+
return deserializer.deserialize(bytes);
48+
} catch (DeserializationException e) {
49+
throw new MalformedJwtException(MALFORMED_ERROR + new String(bytes, StandardCharsets.UTF_8), e);
50+
} catch (StackOverflowError e) {
51+
throw new IOException(MALFORMED_COMPLEX_ERROR + new String(bytes, StandardCharsets.UTF_8), e);
52+
}
53+
}
54+
}

impl/src/test/groovy/io/jsonwebtoken/DeprecatedJwtParserTest.groovy

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class DeprecatedJwtParserTest {
8383
Jwts.parser().parse(bad)
8484
fail()
8585
} catch (MalformedJwtException expected) {
86-
assertEquals expected.getMessage(), 'Unable to read JSON value: ' + junkPayload
86+
assertEquals expected.getMessage(), 'Malformed JWT JSON: ' + junkPayload
8787
}
8888
}
8989

impl/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ class JwtParserTest {
8686
Jwts.parserBuilder().build().parse(bad)
8787
fail()
8888
} catch (MalformedJwtException expected) {
89-
assertEquals expected.getMessage(), 'Unable to read JSON value: ' + junkPayload
89+
assertEquals expected.getMessage(), 'Malformed JWT JSON: ' + junkPayload
9090
}
9191
}
9292

impl/src/test/groovy/io/jsonwebtoken/impl/DefaultJwtParserTest.groovy

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import javax.crypto.SecretKey
2929

3030
import static org.junit.Assert.assertEquals
3131
import static org.junit.Assert.assertSame
32+
import static org.junit.Assert.assertTrue
3233

3334
// NOTE to the casual reader: even though this test class appears mostly empty, the DefaultJwtParser
3435
// implementation is tested to 100% coverage. The vast majority of its tests are in the JwtsTest class. This class
@@ -69,7 +70,8 @@ class DefaultJwtParserTest {
6970
}
7071
}
7172
def p = new DefaultJwtParser().deserializeJsonWith(deserializer)
72-
assertSame deserializer, p.deserializer
73+
assertTrue("Expected wrapping deserializer to be instance of JwtDeserializer", p.deserializer instanceof JwtDeserializer )
74+
assertSame deserializer, p.deserializer.deserializer
7375

7476
def key = Keys.secretKeyFor(SignatureAlgorithm.HS256)
7577

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* Copyright (C) 2021 jsonwebtoken.io
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.jsonwebtoken.impl
17+
18+
import io.jsonwebtoken.MalformedJwtException
19+
import io.jsonwebtoken.io.DeserializationException
20+
import io.jsonwebtoken.io.Deserializer
21+
import io.jsonwebtoken.io.IOException
22+
import org.junit.Assert
23+
import org.junit.Test
24+
25+
import java.nio.charset.StandardCharsets
26+
27+
import static org.easymock.EasyMock.expect
28+
import static org.easymock.EasyMock.mock
29+
import static org.easymock.EasyMock.replay
30+
import static org.junit.Assert.assertEquals
31+
32+
class JwtDeserializerTest {
33+
34+
/**
35+
* It's common for JSON parser's to throw a StackOverflowError when body is deeply nested. Since it's common
36+
* across multiple parsers, JJWT handles the exception when parsing.
37+
*/
38+
@Test
39+
void testParserStackOverflowError() {
40+
41+
byte[] jsonBytes = '{"test": "testParserStackOverflowError"}'.getBytes(StandardCharsets.UTF_8)
42+
43+
// create a Deserializer that will throw a StackOverflowError
44+
Deserializer<Map<String,?>> deserializer = mock(Deserializer)
45+
expect(deserializer.deserialize(jsonBytes)).andThrow(new StackOverflowError("Test exception: testParserStackOverflowError" ))
46+
replay(deserializer)
47+
48+
try {
49+
new JwtDeserializer<>(deserializer).deserialize(jsonBytes)
50+
Assert.fail("Expected IOException")
51+
} catch (IOException e) {
52+
assertEquals JwtDeserializer.MALFORMED_COMPLEX_ERROR + new String(jsonBytes), e.message
53+
}
54+
}
55+
56+
/**
57+
* Check that a DeserializationException, is wrapped and rethrown as a MalformedJwtException with a developer friendly message.
58+
*/
59+
@Test
60+
void testDeserializationExceptionMessage() {
61+
62+
byte[] jsonBytes = '{"test": "testDeserializationExceptionMessage"}'.getBytes(StandardCharsets.UTF_8)
63+
64+
// create a Deserializer that will throw a DeserializationException
65+
Deserializer<Map<String,?>> deserializer = mock(Deserializer)
66+
expect(deserializer.deserialize(jsonBytes)).andThrow(new DeserializationException("Test exception: testDeserializationExceptionMessage" ))
67+
replay(deserializer)
68+
69+
try {
70+
new JwtDeserializer<>(deserializer).deserialize(jsonBytes)
71+
Assert.fail("Expected MalformedJwtException")
72+
} catch (MalformedJwtException e) {
73+
assertEquals JwtDeserializer.MALFORMED_ERROR + new String(jsonBytes), e.message
74+
}
75+
}
76+
}

0 commit comments

Comments
 (0)