aboutsummaryrefslogtreecommitdiff
path: root/gson/src/test/java/com/google/gson/functional/ReflectionAccessFilterTest.java
blob: 775baf9f901ab9af2822a84b6837d262c7189e60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package com.google.gson.functional;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.ReflectionAccessFilter;
import com.google.gson.ReflectionAccessFilter.FilterResult;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;

public class ReflectionAccessFilterTest {
  // Reader has protected `lock` field which cannot be accessed
  private static class ClassExtendingJdkClass extends Reader {
    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
      return 0;
    }

    @Override
    public void close() throws IOException {
    }
  }

  @Test
  public void testBlockInaccessibleJava() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_INACCESSIBLE_JAVA)
      .create();

    // Serialization should fail for classes with non-public fields
    try {
      gson.toJson(new File("a"));
      fail("Expected exception; test needs to be run with Java >= 9");
    } catch (JsonIOException expected) {
      // Note: This test is rather brittle and depends on the JDK implementation
      assertEquals(
        "Field 'java.io.File#path' is not accessible and ReflectionAccessFilter does not permit "
        + "making it accessible. Register a TypeAdapter for the declaring type or adjust the access filter.",
        expected.getMessage()
      );
    }

    // But serialization should succeed for classes with only public fields
    String json = gson.toJson(new Point(1, 2));
    assertEquals("{\"x\":1,\"y\":2}", json);
  }

  @Test
  public void testBlockInaccessibleJavaExtendingJdkClass() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_INACCESSIBLE_JAVA)
      .create();

    try {
      gson.toJson(new ClassExtendingJdkClass());
      fail("Expected exception; test needs to be run with Java >= 9");
    } catch (JsonIOException expected) {
      assertEquals(
        "Field 'java.io.Reader#lock' is not accessible and ReflectionAccessFilter does not permit "
        + "making it accessible. Register a TypeAdapter for the declaring type or adjust the access filter.",
        expected.getMessage()
      );
    }
  }

  @Test
  public void testBlockAllJava() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_ALL_JAVA)
      .create();

    // Serialization should fail for any Java class
    try {
      gson.toJson(Thread.currentThread());
      fail();
    } catch (JsonIOException expected) {
      assertEquals(
        "ReflectionAccessFilter does not permit using reflection for class java.lang.Thread. "
        + "Register a TypeAdapter for this type or adjust the access filter.",
        expected.getMessage()
      );
    }
  }

  @Test
  public void testBlockAllJavaExtendingJdkClass() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(ReflectionAccessFilter.BLOCK_ALL_JAVA)
      .create();

    try {
      gson.toJson(new ClassExtendingJdkClass());
      fail();
    } catch (JsonIOException expected) {
      assertEquals(
        "ReflectionAccessFilter does not permit using reflection for class java.io.Reader "
        + "(supertype of class com.google.gson.functional.ReflectionAccessFilterTest$ClassExtendingJdkClass). "
        + "Register a TypeAdapter for this type or adjust the access filter.",
        expected.getMessage()
      );
    }
  }

  private static class ClassWithStaticField {
    @SuppressWarnings("unused")
    private static int i = 1;
  }

  @Test
  public void testBlockInaccessibleStaticField() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          return FilterResult.BLOCK_INACCESSIBLE;
        }
      })
      // Include static fields
      .excludeFieldsWithModifiers(0)
      .create();

      try {
        gson.toJson(new ClassWithStaticField());
        fail("Expected exception; test needs to be run with Java >= 9");
      } catch (JsonIOException expected) {
        assertEquals(
          "Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithStaticField#i' "
          + "is not accessible and ReflectionAccessFilter does not permit making it accessible. "
          + "Register a TypeAdapter for the declaring type or adjust the access filter.",
          expected.getMessage()
        );
      }
  }

  private static class SuperTestClass {
  }
  private static class SubTestClass extends SuperTestClass {
    @SuppressWarnings("unused")
    public int i = 1;
  }
  private static class OtherClass {
    @SuppressWarnings("unused")
    public int i = 2;
  }

  @Test
  public void testDelegation() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          // INDECISIVE in last filter should act like ALLOW
          return SuperTestClass.class.isAssignableFrom(rawClass) ? FilterResult.BLOCK_ALL : FilterResult.INDECISIVE;
        }
      })
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          // INDECISIVE should delegate to previous filter
          return rawClass == SubTestClass.class ? FilterResult.ALLOW : FilterResult.INDECISIVE;
        }
      })
      .create();

    // Filter disallows SuperTestClass
    try {
      gson.toJson(new SuperTestClass());
      fail();
    } catch (JsonIOException expected) {
      assertEquals(
        "ReflectionAccessFilter does not permit using reflection for class "
        + "com.google.gson.functional.ReflectionAccessFilterTest$SuperTestClass. "
        + "Register a TypeAdapter for this type or adjust the access filter.",
        expected.getMessage()
      );
    }

    // But registration order is reversed, so filter for SubTestClass allows reflection
    String json = gson.toJson(new SubTestClass());
    assertEquals("{\"i\":1}", json);

    // And unrelated class should not be affected
    json = gson.toJson(new OtherClass());
    assertEquals("{\"i\":2}", json);
  }

  private static class ClassWithPrivateField {
    @SuppressWarnings("unused")
    private int i = 1;
  }
  private static class ExtendingClassWithPrivateField extends ClassWithPrivateField {
  }

  @Test
  public void testAllowForSupertype() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          return FilterResult.BLOCK_INACCESSIBLE;
        }
      })
      .create();

    // First make sure test is implemented correctly and access is blocked
    try {
      gson.toJson(new ExtendingClassWithPrivateField());
      fail("Expected exception; test needs to be run with Java >= 9");
    } catch (JsonIOException expected) {
      assertEquals(
        "Field 'com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateField#i' "
        + "is not accessible and ReflectionAccessFilter does not permit making it accessible. "
        + "Register a TypeAdapter for the declaring type or adjust the access filter.",
        expected.getMessage()
      );
    }

    gson = gson.newBuilder()
      // Allow reflective access for supertype
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          return rawClass == ClassWithPrivateField.class ? FilterResult.ALLOW : FilterResult.INDECISIVE;
        }
      })
      .create();

    // Inherited (inaccessible) private field should have been made accessible
    String json = gson.toJson(new ExtendingClassWithPrivateField());
    assertEquals("{\"i\":1}", json);
  }

  private static class ClassWithPrivateNoArgsConstructor {
    private ClassWithPrivateNoArgsConstructor() {
    }
  }

  @Test
  public void testInaccessibleNoArgsConstructor() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          return FilterResult.BLOCK_INACCESSIBLE;
        }
      })
      .create();

    try {
      gson.fromJson("{}", ClassWithPrivateNoArgsConstructor.class);
      fail("Expected exception; test needs to be run with Java >= 9");
    } catch (JsonIOException expected) {
      assertEquals(
        "Unable to invoke no-args constructor of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithPrivateNoArgsConstructor; "
        + "constructor is not accessible and ReflectionAccessFilter does not permit making it accessible. Register an "
        + "InstanceCreator or a TypeAdapter for this type, change the visibility of the constructor or adjust the access filter.",
        expected.getMessage()
      );
    }
  }

  private static class ClassWithoutNoArgsConstructor {
    public String s;

    public ClassWithoutNoArgsConstructor(String s) {
      this.s = s;
    }
  }

  @Test
  public void testClassWithoutNoArgsConstructor() {
    GsonBuilder gsonBuilder = new GsonBuilder()
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          // Even BLOCK_INACCESSIBLE should prevent usage of Unsafe for object creation
          return FilterResult.BLOCK_INACCESSIBLE;
        }
      });
    Gson gson = gsonBuilder.create();

    try {
      gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
      fail();
    } catch (JsonIOException expected) {
      assertEquals(
        "Unable to create instance of class com.google.gson.functional.ReflectionAccessFilterTest$ClassWithoutNoArgsConstructor; "
        + "ReflectionAccessFilter does not permit using reflection or Unsafe. Register an InstanceCreator "
        + "or a TypeAdapter for this type or adjust the access filter to allow using reflection.",
        expected.getMessage()
      );
    }

    // But should not fail when custom TypeAdapter is specified
    gson = gson.newBuilder()
      .registerTypeAdapter(ClassWithoutNoArgsConstructor.class, new TypeAdapter<ClassWithoutNoArgsConstructor>() {
        @Override public ClassWithoutNoArgsConstructor read(JsonReader in) throws IOException {
          in.skipValue();
          return new ClassWithoutNoArgsConstructor("TypeAdapter");
        }
        @Override public void write(JsonWriter out, ClassWithoutNoArgsConstructor value) throws IOException {
          throw new AssertionError("Not needed for test");
        };
      })
      .create();
    ClassWithoutNoArgsConstructor deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
    assertEquals("TypeAdapter", deserialized.s);

    // But should not fail when custom InstanceCreator is specified
    gson = gsonBuilder
      .registerTypeAdapter(ClassWithoutNoArgsConstructor.class, new InstanceCreator<ClassWithoutNoArgsConstructor>() {
        @Override public ClassWithoutNoArgsConstructor createInstance(Type type) {
          return new ClassWithoutNoArgsConstructor("InstanceCreator");
        }
      })
      .create();
    deserialized = gson.fromJson("{}", ClassWithoutNoArgsConstructor.class);
    assertEquals("InstanceCreator", deserialized.s);
  }

  /**
   * When using {@link FilterResult#BLOCK_ALL}, registering only a {@link JsonSerializer}
   * but not performing any deserialization should not throw any exception.
   */
  @Test
  public void testBlockAllPartial() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          return FilterResult.BLOCK_ALL;
        }
      })
      .registerTypeAdapter(OtherClass.class, new JsonSerializer<OtherClass>() {
        @Override public JsonElement serialize(OtherClass src, Type typeOfSrc, JsonSerializationContext context) {
          return new JsonPrimitive(123);
        }
      })
      .create();

    String json = gson.toJson(new OtherClass());
    assertEquals("123", json);

    // But deserialization should fail
    try {
      gson.fromJson("{}", OtherClass.class);
      fail();
    } catch (JsonIOException expected) {
      assertEquals(
        "ReflectionAccessFilter does not permit using reflection for class com.google.gson.functional.ReflectionAccessFilterTest$OtherClass. "
        + "Register a TypeAdapter for this type or adjust the access filter.",
        expected.getMessage()
      );
    }
  }

  /**
   * Should not fail when deserializing collection interface
   * (Even though this goes through {@link ConstructorConstructor} as well)
   */
  @Test
  public void testBlockAllCollectionInterface() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          return FilterResult.BLOCK_ALL;
        }
      })
      .create();
    List<?> deserialized = gson.fromJson("[1.0]", List.class);
    assertEquals(1.0, deserialized.get(0));
  }

  /**
   * Should not fail when deserializing specific collection implementation
   * (Even though this goes through {@link ConstructorConstructor} as well)
   */
  @Test
  public void testBlockAllCollectionImplementation() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          return FilterResult.BLOCK_ALL;
        }
      })
      .create();
    List<?> deserialized = gson.fromJson("[1.0]", LinkedList.class);
    assertEquals(1.0, deserialized.get(0));
  }

  /**
   * When trying to deserialize interface an exception for that should
   * be thrown, even if {@link FilterResult#BLOCK_INACCESSIBLE} is used
   */
  @Test
  public void testBlockInaccessibleInterface() {
    Gson gson = new GsonBuilder()
      .addReflectionAccessFilter(new ReflectionAccessFilter() {
        @Override public FilterResult check(Class<?> rawClass) {
          return FilterResult.BLOCK_INACCESSIBLE;
        }
      })
      .create();

    try {
      gson.fromJson("{}", Runnable.class);
      fail();
    } catch (JsonIOException expected) {
      assertEquals(
        "Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for "
        + "this type. Interface name: java.lang.Runnable",
        expected.getMessage()
      );
    }
  }
}