- enabled reflective access to `java.io.ByteArrayInputStream` and `sun.misc.security.KeyUtil` on JDK 17+
- Minor refactor to ServicesTest to avoid the need for PowerMock
This commit is contained in:
lhazlewood 2023-10-04 19:39:39 -07:00 committed by GitHub
parent 44cd5523e8
commit 1625067b85
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 243 additions and 184 deletions

View File

@ -1,5 +1,10 @@
## Release Notes
### JJWT_RELEASE_VERSION
Enabled reflective access on JDK 17+ to `java.io.ByteArrayInputStream` and `sun.security.util.KeyUtil` for
`jjwt-impl.jar`
### 0.12.0
This is a big release! JJWT now fully supports Encrypted JSON Web Tokens (JWE), JSON Web Keys (JWK) and more! See the

View File

@ -15,6 +15,7 @@
*/
package io.jsonwebtoken.impl.io;
import io.jsonwebtoken.impl.lang.AddOpens;
import io.jsonwebtoken.impl.lang.Bytes;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.lang.Classes;
@ -42,6 +43,11 @@ public class Streams {
*/
public static final int EOF = -1;
static {
// For reflective access to ByteArrayInputStream via the 'bytes' static method on >= JDK 9:
AddOpens.open("java.base", "java.io");
}
public static byte[] bytes(final InputStream in, String exmsg) {
if (in instanceof ByteArrayInputStream) {
return Classes.getFieldValue(in, "buf", byte[].class);

View File

@ -0,0 +1,128 @@
/*
* Copyright 2021 Stefan Zobel
* Copyright © 2023 jsonwebtoken.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jsonwebtoken.impl.lang;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* A utility class that allows to open arbitrary packages to the calling module
* at runtime, so it is a kind of dynamic device for "--add-opens" that could be
* used inside libraries instead of forcing the application to be run with
* command line parameters like "--add-opens java.base/java.util=ALL-UNNAMED" or
* having the "Add-Opens:" entries supplied in the application Jar manifest.
* Note that this still works in the Java 17 GA release, dated 2021-09-14 but it
* may break at any time in the future (theoretically even for a minor
* release!).
*
* @since JJWT_RELEASE_VERSION, gratefully copied from <a href="https://github.com/stefan-zobel/wip/blob/b74e927edddf19a5dce7c8610835f620c0b6f557/src/main/java/misc/AddOpens.java">https://github.com/stefan-zobel/wip/blob/b74e927edddf19a5dce7c8610835f620c0b6f557/src/main/java/misc/AddOpens.java</a>
* under the terms of the Apache 2 open source license (same as the JJWT license).
*/
public final class AddOpens {
// field offset of the override field (Warning: this may change at any time!)
private static final long OVERRIDE_OFFSET = 12;
private static final sun.misc.Unsafe U = getUnsafe();
private AddOpens() {
throw new AssertionError();
}
/**
* Open one or more packages in the given module to the current module. Example
* usage:
*
* <pre>{@code
* boolean success = AddOpens.open("java.base", "java.util", "java.net");
* }</pre>
*
* @param moduleName the module you want to open
* @param packageNames packages in that module you want to be opened
* @return {@code true} if the open operation has succeeded for all packages,
* otherwise {@code false}
*/
public static boolean open(String moduleName, String... packageNames) {
// Use reflection so that this code can run on Java 8
Class<?> javaLangModule;
try {
javaLangModule = Class.forName("java.lang.Module");
} catch (Throwable t) {
// we must be < Java 9
return true;
}
try {
// the module we are currently running in (either named or unnamed)
Object thisModule = getCurrentModule();
// find the module to open
Object targetModule = findModule(moduleName);
// get the method that is also used by "--add-opens"
Method m = javaLangModule.getDeclaredMethod("implAddOpens", String.class, javaLangModule);
// override language-level access checks
setAccessible(m);
// open given packages in the target module to this module
for (String package_ : packageNames) {
m.invoke(targetModule, package_, thisModule);
}
return true;
} catch (Throwable ignore) {
return false;
}
}
private static Object findModule(String moduleName) {
// Use reflection so that this code can run on Java 8
try {
Class<?> moduleLayerClass = Class.forName("java.lang.ModuleLayer");
Method bootMethod = moduleLayerClass.getDeclaredMethod("boot");
Object bootLayer = bootMethod.invoke(null);
Method findModuleMethod = moduleLayerClass.getDeclaredMethod("findModule", String.class);
Object optionalModule = findModuleMethod.invoke(bootLayer, moduleName);
Class<?> optionalClass = Class.forName("java.util.Optional");
Method getMethod = optionalClass.getDeclaredMethod("get");
return getMethod.invoke(optionalModule);
} catch (Throwable t) {
return null;
}
}
private static Object getCurrentModule() {
// Use reflection so that this code can run on Java 8
try {
Method m = Class.class.getDeclaredMethod("getModule");
setAccessible(m);
return m.invoke(AddOpens.class);
} catch (Throwable t) {
return null;
}
}
private static void setAccessible(Method method) {
if (U != null) {
U.putBoolean(method, OVERRIDE_OFFSET, true);
}
}
private static sun.misc.Unsafe getUnsafe() {
try {
Field unsafe = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
unsafe.setAccessible(true);
return (sun.misc.Unsafe) unsafe.get(null);
} catch (Throwable ignore) {
return null;
}
}
}

View File

@ -18,7 +18,6 @@ package io.jsonwebtoken.impl.lang;
import io.jsonwebtoken.lang.Assert;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

View File

@ -15,6 +15,7 @@
*/
package io.jsonwebtoken.impl.security;
import io.jsonwebtoken.impl.lang.AddOpens;
import io.jsonwebtoken.impl.lang.Bytes;
import io.jsonwebtoken.impl.lang.OptionalMethodInvoker;
import io.jsonwebtoken.lang.Assert;
@ -41,6 +42,11 @@ public final class KeysBridge {
new OptionalMethodInvoker<>(SUN_KEYUTIL_CLASSNAME, "getKeySize", Key.class, true);
private static final String SUN_KEYUTIL_ERR = "Unexpected " + SUN_KEYUTIL_CLASSNAME + " invocation error.";
static {
// For reflective access to KeyUtil on >= JDK 9:
AddOpens.open("java.base", "sun.security.util");
}
// prevent instantiation
private KeysBridge() {
}

View File

@ -1,46 +0,0 @@
/*
* Copyright (C) 2019 jsonwebtoken.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jsonwebtoken.impl.io
class FakeServiceDescriptorClassLoader extends ClassLoader {
private String serviceDescriptor
FakeServiceDescriptorClassLoader(ClassLoader parent, String serviceDescriptor) {
super(parent)
this.serviceDescriptor = serviceDescriptor
}
@Override
Enumeration<URL> getResources(String name) throws IOException {
if (name.startsWith("META-INF/services/")) {
return super.getResources(serviceDescriptor)
} else {
return super.getResources(name)
}
}
static void runWithFake(String fakeDescriptor, Closure closure) {
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader()
try {
Thread.currentThread().setContextClassLoader(new FakeServiceDescriptorClassLoader(originalClassLoader, fakeDescriptor))
closure.run()
} finally {
if(originalClassLoader != null) {
Thread.currentThread().setContextClassLoader(originalClassLoader)
}
}
}
}

View File

@ -1,43 +0,0 @@
/*
* Copyright (C) 2019 jsonwebtoken.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jsonwebtoken.impl.io
class NoServiceDescriptorClassLoader extends ClassLoader {
NoServiceDescriptorClassLoader(ClassLoader parent) {
super(parent)
}
@Override
Enumeration<URL> getResources(String name) throws IOException {
if (name.startsWith("META-INF/services/")) {
return Collections.emptyEnumeration()
} else {
return super.getResources(name)
}
}
static void runWith(Closure closure) {
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader()
try {
Thread.currentThread().setContextClassLoader(new NoServiceDescriptorClassLoader(originalClassLoader))
closure.run()
} finally {
if(originalClassLoader != null) {
Thread.currentThread().setContextClassLoader(originalClassLoader)
}
}
}
}

View File

@ -76,6 +76,6 @@ class DefaultRegistryTest {
@Test
void testToString() {
assertEquals reg.@DELEGATE.toString(), reg.toString()
assertEquals '{a=a, b=b, c=c, d=d}', reg.toString()
}
}

View File

@ -19,17 +19,9 @@ import io.jsonwebtoken.StubService
import io.jsonwebtoken.impl.DefaultStubService
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.api.easymock.PowerMock
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.lang.reflect.Field
import static org.junit.Assert.*
@RunWith(PowerMockRunner.class)
@PrepareForTest([Services])
class ServicesTest {
@Test
@ -41,9 +33,7 @@ class ServicesTest {
@Test(expected = UnavailableImplementationException)
void testLoadFirstUnavailable() {
NoServicesClassLoader.runWith {
Services.loadFirst(StubService.class)
}
Services.loadFirst(NoService.class)
}
@Test
@ -55,9 +45,7 @@ class ServicesTest {
@Test(expected = UnavailableImplementationException)
void testLoadAllUnavailable() {
NoServicesClassLoader.runWith {
Services.loadAll(StubService.class)
}
Services.loadAll(NoService.class)
}
@Test
@ -79,38 +67,5 @@ class ServicesTest {
Services.reload();
}
static class NoServicesClassLoader extends ClassLoader {
private NoServicesClassLoader(ClassLoader parent) {
super(parent)
}
@Override
Enumeration<URL> getResources(String name) throws IOException {
if (name.startsWith("META-INF/services/")) {
return Collections.emptyEnumeration()
} else {
return super.getResources(name)
}
}
static void runWith(Closure closure) {
Field field = PowerMock.field(Services.class, "CLASS_LOADER_ACCESSORS")
def originalValue = field.get(Services.class)
try {
// use powermock to change the list of the classloaders we are using
List<Services.ClassLoaderAccessor> classLoaderAccessors = [
new Services.ClassLoaderAccessor() {
@Override
ClassLoader getClassLoader() {
return new NoServicesClassLoader(Thread.currentThread().getContextClassLoader())
}
}
]
field.set(Services.class, classLoaderAccessors)
closure.run()
} finally {
field.set(Services.class, originalValue)
}
}
}
interface NoService {} // no implementations
}

139
pom.xml
View File

@ -14,7 +14,8 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.jsonwebtoken</groupId>
@ -90,13 +91,13 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<arguments />
<arguments/>
<jjwt.root>${basedir}</jjwt.root>
<jjwt.previousVersion>0.11.2</jjwt.previousVersion>
<maven.jar.version>3.2.2</maven.jar.version>
<maven.compiler.version>3.8.1</maven.compiler.version> <!-- max version allowed for JDK 7 builds -->
<maven.jar.version>3.3.0</maven.jar.version>
<maven.compiler.version>3.11.0</maven.compiler.version>
<maven.javadoc.version>3.1.1</maven.javadoc.version> <!-- max version allowed for JDK 7 builds -->
<maven.source.version>3.2.1</maven.source.version>
<maven.resources.version>3.1.0</maven.resources.version>
@ -106,14 +107,14 @@
<maven.license.version>4.2.rc3</maven.license.version>
<maven.license.skipExistingHeaders>true</maven.license.skipExistingHeaders>
<jdk.version>1.7</jdk.version>
<jdk.version>7</jdk.version>
<buildNumber>${user.name}-${maven.build.timestamp}</buildNumber>
<jackson.version>2.12.7.1</jackson.version>
<orgjson.version>20230618</orgjson.version>
<gson.version>2.9.0</gson.version>
<maven.javadoc.additionalOptions />
<maven.javadoc.additionalOptions/>
<!-- Optional Runtime Dependencies: -->
<bouncycastle.version>1.76</bouncycastle.version>
@ -129,31 +130,11 @@
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
<clover.version>4.3.1</clover.version> <!-- max version allowed for JDK 7 builds -->
<clover.db>${jjwt.root}/target/clover/clover.db</clover.db>
<surefire.argLine />
<surefire.argLine/>
<test.addOpens>
--add-opens java.base/java.time.zone=ALL-UNNAMED,
--add-opens java.base/java.lang.ref=ALL-UNNAMED,
--add-opens java.base/java.lang=ALL-UNNAMED,
--add-opens java.base/java.lang.reflect=ALL-UNNAMED,
--add-opens java.base/java.net=ALL-UNNAMED,
--add-opens java.base/java.nio.charset=ALL-UNNAMED,
--add-opens java.base/java.nio.file=ALL-UNNAMED,
--add-opens java.base/java.security.cert=ALL-UNNAMED,
--add-opens java.base/java.text=ALL-UNNAMED,
--add-opens java.base/java.util.regex=ALL-UNNAMED,
--add-opens java.base/java.util.stream=ALL-UNNAMED,
--add-opens java.base/java.util.concurrent=ALL-UNNAMED,
--add-opens java.base/java.util.concurrent.atomic=ALL-UNNAMED,
--add-opens java.base/java.util.concurrent.locks=ALL-UNNAMED,
--add-opens java.base/java.time=ALL-UNNAMED,
--add-opens java.base/java.util=ALL-UNNAMED,
--add-opens java.base/java.io=ALL-UNNAMED,
--add-opens java.base/java.security=ALL-UNNAMED,
--add-opens java.base/jdk.internal.loader=ALL-UNNAMED,
--add-opens java.base/sun.nio.fs=ALL-UNNAMED,
--add-opens java.base/sun.security.x509=ALL-UNNAMED,
--add-opens java.base/sun.security.util=ALL-UNNAMED,
--add-opens java.logging/java.util.logging=ALL-UNNAMED
--add-opens java.base/java.lang=ALL-UNNAMED, <!-- Needed by EasyMock/cglib -->
--add-opens java.desktop/java.beans=ALL-UNNAMED, <!-- Needed by EasyMock/cglib -->
--add-opens java.base/java.lang.ref=ALL-UNNAMED <!-- Needed by PowerMock -->
</test.addOpens>
</properties>
@ -309,6 +290,7 @@
<exclude>io/jsonwebtoken/impl/io/FilteredInputStream.java</exclude>
<exclude>io/jsonwebtoken/impl/io/FilteredOutputStream.java</exclude>
<exclude>io/jsonwebtoken/impl/io/CharSequenceReader.java</exclude>
<exclude>io/jsonwebtoken/impl/lang/AddOpens.java</exclude>
</excludes>
<methodPercentage>100.000000%</methodPercentage>
<statementPercentage>100.000000%</statementPercentage>
@ -387,6 +369,20 @@
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven.jar.version}</version>
<configuration>
<archive>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
@ -478,7 +474,8 @@
</includes>
</artifactSet>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
<executions>
@ -517,6 +514,40 @@
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-compiler-plugin</artifactId>-->
<!-- <version>${maven.compiler.version}</version>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>default-compile</id>-->
<!-- <configuration>-->
<!-- <release>9</release>-->
<!-- &lt;!&ndash; no excludes: compile everything to ensure module-info contains right entries &ndash;&gt;-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- <execution>-->
<!-- <id>base-compile</id>-->
<!-- <goals>-->
<!-- <goal>compile</goal>-->
<!-- </goals>-->
<!-- <configuration>-->
<!-- &lt;!&ndash; recompile everything for target VM except the module-info.java &ndash;&gt;-->
<!-- <excludes>-->
<!-- <exclude>module-info.java</exclude>-->
<!-- </excludes>-->
<!-- </configuration>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- &lt;!&ndash; defaults for compile and testCompile &ndash;&gt;-->
<!-- <configuration>-->
<!-- <release>${jdk.version}</release>-->
<!--&lt;!&ndash; &lt;!&ndash; Only required when Maven runtime JAVA_HOME isn't at least Java 9 and when haven't configured the maven-toolchains-plugin &ndash;&gt;&ndash;&gt;-->
<!--&lt;!&ndash; <jdkToolchain>&ndash;&gt;-->
<!--&lt;!&ndash; <version>9</version>&ndash;&gt;-->
<!--&lt;!&ndash; </jdkToolchain>&ndash;&gt;-->
<!-- </configuration>-->
<!-- </plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@ -609,7 +640,7 @@
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.3.0</version>
<version>3.5.0</version>
<executions>
<execution>
<id>bundle-manifest</id>
@ -628,18 +659,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven.jar.version}</version>
<configuration>
<archive>
<manifest>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestFile>
${project.build.outputDirectory}/META-INF/MANIFEST.MF
</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>io.jsonwebtoken.coveralls</groupId>
@ -655,6 +674,8 @@
<jdk>1.7</jdk>
</activation>
<properties>
<maven.jar.version>3.2.2</maven.jar.version>
<maven.compiler.version>3.8.1</maven.compiler.version>
<bcprov.artifactId>bcprov-jdk15to18</bcprov.artifactId>
<bcpkix.artifactId>bcpkix-jdk15to18</bcpkix.artifactId>
</properties>
@ -665,13 +686,39 @@
<jdk>[1.8,)</jdk>
</activation>
<properties>
<gmavenplus.version>1.13.1</gmavenplus.version>
<gmavenplus.version>3.0.2</gmavenplus.version>
<groovy.version>3.0.19</groovy.version>
<easymock.version>4.2</easymock.version>
<powermock.version>2.0.7</powermock.version>
<maven.japicmp.version>0.15.6</maven.japicmp.version>
<failsafe.plugin.version>3.1.2</failsafe.plugin.version>
<surefire.plugin.version>3.1.2</surefire.plugin.version>
</properties>
</profile>
<!-- <profile>-->
<!-- <id>jdk7And8</id>-->
<!-- <activation>-->
<!-- <jdk>[1.7,9)</jdk>-->
<!-- </activation>-->
<!-- <build>-->
<!-- <plugins>-->
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-compiler-plugin</artifactId>-->
<!-- <version>${maven.compiler.version}</version>-->
<!-- <configuration>-->
<!-- <source>${jdk.version}</source>-->
<!-- <target>${jdk.version}</target>-->
<!-- <release/>-->
<!-- <encoding>${project.build.sourceEncoding}</encoding>-->
<!-- <excludes>-->
<!-- <exclude>module-info.java</exclude>-->
<!-- </excludes>-->
<!-- </configuration>-->
<!-- </plugin>-->
<!-- </plugins>-->
<!-- </build>-->
<!-- </profile>-->
<profile>
<!-- Added profile to address https://github.com/jwtk/jjwt/issues/364 -->
<id>jdk9AndLater</id>
@ -679,6 +726,8 @@
<jdk>[1.9,)</jdk>
</activation>
<properties>
<maven.compiler.version>3.11.0</maven.compiler.version>
<surefire.useModulePath>false</surefire.useModulePath>
<maven.javadoc.additionalOptions>-html5</maven.javadoc.additionalOptions>
<surefire.argLine>${test.addOpens}, --illegal-access=debug</surefire.argLine>
</properties>