1 /* 2 * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 import java.nio.file.Files; 25 import java.nio.file.Path; 26 import java.nio.file.Paths; 27 import java.nio.file.StandardCopyOption; 28 import java.security.Security; 29 import java.util.Collections; 30 import java.util.HashMap; 31 import java.util.LinkedList; 32 import java.util.List; 33 import java.util.Map; 34 import java.util.Arrays; 35 import java.util.stream.Stream; 36 import java.io.File; 37 import java.io.IOException; 38 import java.io.OutputStream; 39 import java.lang.module.ModuleDescriptor; 40 import java.lang.module.ModuleDescriptor.Builder; 41 import jdk.test.lib.process.ProcessTools; 42 import jdk.test.lib.util.JarUtils; 43 import jdk.test.lib.util.ModuleInfoWriter; 44 45 /* 46 * @test 47 * @bug 8130360 8183310 48 * @summary Test security provider in different combination of modular option 49 * defined with(out) service description. 50 * @enablePreview 51 * @modules java.base/jdk.internal.module 52 * @library /test/lib 53 * @build jdk.test.lib.util.JarUtils 54 * TestProvider TestClient 55 * @run main SecurityProviderModularTest CL true 56 * @run main SecurityProviderModularTest CL false 57 * @run main SecurityProviderModularTest SL true 58 * @run main SecurityProviderModularTest SL false 59 * @run main SecurityProviderModularTest SPN true 60 * @run main SecurityProviderModularTest SPN false 61 * @run main SecurityProviderModularTest SPT true 62 * @run main SecurityProviderModularTest SPT false 63 */ 64 public class SecurityProviderModularTest { 65 66 private static final Path TEST_CLASSES 67 = Paths.get(System.getProperty("test.classes")); 68 private static final Path ARTIFACT_DIR = Paths.get("jars"); 69 private static final Path SEC_FILE = Paths.get("java.extn.security"); 70 private static final String PS = File.pathSeparator; 71 private static final String P_TYPE = "p.TestProvider"; 72 private static final String C_TYPE = "c.TestClient"; 73 74 /** 75 * Here is the naming convention followed. 76 * Test runtime arguments, 77 * CL - Provider class loaded through ClassLoader 78 * SL - Provider class to be discovered by ServiceLoader 79 * SPN - Provider name defined through "java.extn.security" file which 80 * referred through system property "java.security.properties". 81 * SPT - Provider type defined through "java.extn.security" file which 82 * referred through system property "java.security.properties". 83 * 84 * For each jar file name, 85 * p.jar - Unnamed provider jar. 86 * pd.jar - Unnamed provider jar with META-INF provider descriptor. 87 * mp.jar - Modular provider jar. 88 * mpd.jar - Modular provider jar with META-INF provider descriptor. 89 * msp.jar - Modular provider jar provides service through module-info.java 90 * mspd.jar - Modular provider jar with META-INF provider descriptor and 91 * provides service through module-info.java. 92 * c.jar - Unnamed client jar. 93 * mc.jar - Modular client jar. 94 * mcs.jar - Modular client jar uses service through module-info.java. 95 * amc.jar - Modular client used for automatic provider jar. 96 * amcs.jar - Modular client used for automatic provider jar uses service 97 * through module-info.java. 98 */ 99 private static final Path P_JAR = artifact("p.jar"); 100 private static final Path PD_JAR = artifact("pd.jar"); 101 private static final Path MP_JAR = artifact("mp.jar"); 102 private static final Path MPD_JAR = artifact("mpd.jar"); 103 private static final Path MSP_JAR = artifact("msp.jar"); 104 private static final Path MSPD_JAR = artifact("mspd.jar"); 105 private static final Path C_JAR = artifact("c.jar"); 106 private static final Path MC_JAR = artifact("mc.jar"); 107 private static final Path MCS_JAR = artifact("mcs.jar"); 108 private static final Path AMC_JAR = artifact("amc.jar"); 109 private static final Path AMCS_JAR = artifact("amcs.jar"); 110 private static final Map<String, String> MSG_MAP = new HashMap<>(); 111 112 static { 113 /* 114 * This mapping help process finding expected message based 115 * on the key passed as argument while executing java command. 116 */ 117 MSG_MAP.put("NoAccess", "cannot access class p.TestProvider"); 118 MSG_MAP.put("Success", "Client: found provider TestProvider"); 119 MSG_MAP.put("NoProvider", "Provider TestProvider not found"); 120 } 121 122 private final String addUNArg; 123 private final String addNMArg; 124 private final String cArg; 125 private final String unnP; 126 private final String modP; 127 private final String unnC; 128 private final String modC; 129 private final String autoMC; 130 private final String expModRes; 131 private final String expAModRes; 132 // Common set of VM arguments used in all test cases 133 private final List<String> commonArgs; 134 135 public SecurityProviderModularTest(String use, boolean metaDesc) { 136 137 List<String> argList = new LinkedList<>(); 138 argList.add("-Duser.language=en"); 139 argList.add("-Duser.region=US"); 140 final boolean useSL = "SL".equals(use) || "SPN".equals(use); 141 final boolean useCL = "CL".equals(use); 142 final boolean useSPT = "SPT".equals(use); 143 final boolean useSP = use.startsWith("SP"); 144 /* Use Security property file when the provider expected to 145 * loaded through Security property file. */ 146 if (useSP) { 147 /* Create a java.security file to specify the new provider. 148 * java.security file extension can be provided using 149 * "-Djava.security.properties" VM argument at runtime.*/ 150 createJavaSecurityFileExtn("SPN".equals(use)); 151 argList.add("-Djava.security.properties=" + toAbsPath(SEC_FILE)); 152 } 153 commonArgs = Collections.unmodifiableList(argList); 154 cArg = (useCL) ? P_TYPE : "TestProvider"; 155 addUNArg = (useSL) ? "" : ("--add-modules=" 156 + ((metaDesc) ? "pd" : "p")); 157 addNMArg = (useSL) ? "" : "--add-modules=mp"; 158 159 // Based on Testcase, select unnamed/modular jar files to use. 160 unnP = toAbsPath((metaDesc) ? PD_JAR : P_JAR); 161 modP = toAbsPath(useSL ? (metaDesc ? MSPD_JAR : MSP_JAR) 162 : (metaDesc ? MPD_JAR : MP_JAR)); 163 unnC = toAbsPath(C_JAR); 164 modC = toAbsPath(useSL ? MCS_JAR : MC_JAR); 165 autoMC = toAbsPath(useSL ? AMCS_JAR : AMC_JAR); 166 167 expModRes = "Success"; 168 expAModRes = (useSPT | useCL) ? "Success" 169 : (metaDesc) ? "Success" : "NoProvider"; 170 String loadByMsg = useSP ? "SecurityPropertyFile" 171 : ((useCL) ? "ClassLoader" : "ServiceLoader"); 172 System.out.printf("%n*** Providers loaded through %s and includes" 173 + " META Descriptor: %s ***%n%n", loadByMsg, metaDesc); 174 } 175 176 /* 177 * Test cases are based on the following logic, 178 * for (ProviderLoadedThrough : {"ServiceLoader", "ClassLoader", 179 * "SecurityPropertyFile"}) { 180 * for (definedWith : {"METAINFService", "WithoutMETAINFService"}) { 181 * for (clientType : {"NAMED", "AUTOMATIC", "UNNAMED"}) { 182 * for (providerType : {"NAMED", "AUTOMATIC", "UNNAMED"}) { 183 * Create and run java command for each possible case 184 * } 185 * } 186 * } 187 * } 188 */ 189 public static void main(String[] args) throws Exception { 190 191 // Generates unnamed and modular jars. 192 setUp(); 193 boolean metaDesc = Boolean.valueOf(args[1]); 194 SecurityProviderModularTest test 195 = new SecurityProviderModularTest(args[0], metaDesc); 196 test.process(args[0]); 197 } 198 199 private void process(String use) throws Exception { 200 201 // Case: NAMED-NAMED, NAMED-AUTOMATIC, NAMED-UNNAMED 202 System.out.printf("Case: Modular Client and Modular Provider"); 203 execute(String.format("--module-path %s%s%s -m mc/%s %s %s", 204 modC, PS, modP, C_TYPE, use, cArg), expModRes); 205 System.out.printf("Case: Modular Client and automatic Provider"); 206 execute(String.format("--module-path %s%s%s %s -m mc/%s %s %s", autoMC, 207 PS, unnP, addUNArg, C_TYPE, use, cArg), expAModRes); 208 System.out.printf("Case: Modular Client and unnamed Provider"); 209 execute(String.format("--module-path %s -cp %s -m mc/%s %s %s", autoMC, 210 unnP, C_TYPE, use, cArg), expAModRes); 211 212 // Case: AUTOMATIC-NAMED, AUTOMATIC-AUTOMATIC, AUTOMATIC-UNNAMED 213 System.out.printf("Case: Automatic Client and modular Provider"); 214 execute(String.format("--module-path %s%s%s %s -m c/%s %s %s", unnC, 215 PS, modP, addNMArg, C_TYPE, use, cArg), expModRes); 216 System.out.printf("Case: Automatic Client and automatic Provider"); 217 execute(String.format("--module-path %s%s%s %s -m c/%s %s %s", unnC, 218 PS, unnP, addUNArg, C_TYPE, use, cArg), expAModRes); 219 System.out.printf("Case: Automatic Client and unnamed Provider"); 220 execute(String.format("--module-path %s -cp %s -m c/%s %s %s", unnC, 221 unnP, C_TYPE, use, cArg), expAModRes); 222 223 // Case: UNNAMED-NAMED, UNNAMED-AUTOMATIC, UNNAMED-UNNAMED 224 System.out.printf("Case: Unnamed Client and modular Provider"); 225 execute(String.format("-cp %s --module-path %s %s %s %s %s", unnC, 226 modP, addNMArg, C_TYPE, use, cArg), expModRes); 227 System.out.printf("Case: Unnamed Client and automatic Provider"); 228 execute(String.format("-cp %s --module-path %s %s %s %s %s", unnC, 229 unnP, addUNArg, C_TYPE, use, cArg), expAModRes); 230 System.out.printf("Case: Unnamed Client and unnamed Provider"); 231 execute(String.format("-cp %s%s%s %s %s %s", unnC, PS, unnP, C_TYPE, 232 use, cArg), expAModRes); 233 234 // Case: unnamed jars in --module-path and modular jars in -cp. 235 System.out.printf( 236 "Case: Unnamed Client and Unnamed Provider in modulepath"); 237 execute(String.format("--module-path %s%s%s %s -m c/%s %s %s", unnC, 238 PS, unnP, addUNArg, C_TYPE, use, cArg), expAModRes); 239 System.out.printf( 240 "Case: Modular Client and Modular Provider in classpath"); 241 execute(String.format("-cp %s%s%s %s %s %s", modC, PS, modP, C_TYPE, 242 use, cArg), expAModRes); 243 } 244 245 /** 246 * Execute with command arguments and process the result. 247 */ 248 private void execute(String args, String msgKey) throws Exception { 249 250 String[] safeArgs = Stream.concat(commonArgs.stream(), 251 Stream.of(args.split("\\s+"))).filter(s -> { 252 if (s.contains(" ")) { 253 throw new RuntimeException("No spaces in args"); 254 } 255 return !s.isEmpty(); 256 }).toArray(String[]::new); 257 String out = ProcessTools.executeTestJava(safeArgs).getOutput(); 258 // Handle response. 259 if ((msgKey != null && out.contains(MSG_MAP.get(msgKey)))) { 260 System.out.printf("PASS: Expected Result: %s.%n", 261 MSG_MAP.get(msgKey)); 262 } else if (out.contains("Exception") || out.contains("Error")) { 263 System.out.printf("OUTPUT: %s", out); 264 throw new RuntimeException("FAIL: Unknown Exception occured. " 265 + "Expected: " + MSG_MAP.get(msgKey)); 266 } else { 267 System.out.printf("OUTPUT: %s", out); 268 throw new RuntimeException("FAIL: Unknown Test case found"); 269 } 270 } 271 272 /** 273 * Creates Unnamed/modular jar files for TestClient and TestClassLoader. 274 */ 275 private static void setUp() throws Exception { 276 277 if (ARTIFACT_DIR.toFile().exists()) { 278 System.out.println("Skipping setup: Artifacts already exists."); 279 return; 280 } 281 // Generate unnamed provider jar file. 282 JarUtils.createJarFile(P_JAR, TEST_CLASSES, "p/TestProvider.class"); 283 // Generate unnamed client jar file. 284 JarUtils.createJarFile(C_JAR, TEST_CLASSES, "c/TestClient.class"); 285 // Generate unnamed provider jar files with META-INF descriptor. 286 generateJar(P_JAR, PD_JAR, null, true); 287 288 Builder mBuilder = ModuleDescriptor.newModule("mp").exports("p"); 289 // Modular provider defined as META-INF service. 290 generateJar(P_JAR, MPD_JAR, mBuilder.build(), true); 291 // Modular jar exports package to let the provider type accessible. 292 generateJar(P_JAR, MP_JAR, mBuilder.build(), false); 293 294 mBuilder = ModuleDescriptor.newModule("mp") 295 .provides("java.security.Provider", Arrays.asList(P_TYPE)); 296 // Modular provider Service in module-info does not need to export 297 // its package. 298 generateJar(P_JAR, MSP_JAR, mBuilder.build(), false); 299 // Modular provider Service in module-info also have META-INF descriptor 300 generateJar(P_JAR, MSPD_JAR, mBuilder.build(), true); 301 302 mBuilder = ModuleDescriptor.newModule("mc").exports("c"); 303 // Generate modular client jar file to use automatic provider jar. 304 generateJar(C_JAR, AMC_JAR, mBuilder.build(), false); 305 // Generate modular client jar file to use modular provider jar. 306 generateJar(C_JAR, MC_JAR, mBuilder.requires("mp").build(), false); 307 308 mBuilder = ModuleDescriptor.newModule("mc").exports("c") 309 .uses("java.security.Provider"); 310 // Generate modular client jar file to use automatic provider service. 311 generateJar(C_JAR, AMCS_JAR, mBuilder.build(), false); 312 // Generate modular client jar file using modular provider service. 313 generateJar(C_JAR, MCS_JAR, mBuilder.requires("mp").build(), false); 314 } 315 316 /** 317 * Update Unnamed jars and include descriptor files. 318 */ 319 private static void generateJar(Path sjar, Path djar, 320 ModuleDescriptor mDesc, boolean metaDesc) throws Exception { 321 322 Files.copy(sjar, djar, StandardCopyOption.REPLACE_EXISTING); 323 Path dir = Files.createTempDirectory("tmp"); 324 if (metaDesc) { 325 write(dir.resolve(Paths.get("META-INF", "services", 326 "java.security.Provider")), P_TYPE); 327 } 328 if (mDesc != null) { 329 Path mi = dir.resolve("module-info.class"); 330 try (OutputStream out = Files.newOutputStream(mi)) { 331 ModuleInfoWriter.write(mDesc, out); 332 } 333 System.out.format("Added 'module-info.class' in '%s'%n", djar); 334 } 335 JarUtils.updateJarFile(djar, dir); 336 } 337 338 /** 339 * Look for file path in generated jars. 340 */ 341 private static Path artifact(String file) { 342 return ARTIFACT_DIR.resolve(file); 343 } 344 345 /** 346 * Convert to absolute file path. 347 */ 348 private static String toAbsPath(Path path) { 349 return path.toFile().getAbsolutePath(); 350 } 351 352 /** 353 * Create the parent directories if missing to ensure the path exist. 354 */ 355 private static Path ensurePath(Path at) throws IOException { 356 Path parent = at.getParent(); 357 if (parent != null && !parent.toFile().exists()) { 358 ensurePath(parent); 359 } 360 return Files.createDirectories(parent); 361 } 362 363 /** 364 * Generates service descriptor inside META-INF folder. 365 */ 366 private static void write(Path at, String content) throws IOException { 367 ensurePath(at); 368 Files.write(at, content.getBytes("UTF-8")); 369 } 370 371 /** 372 * Create new provider entry through java.security file extension. 373 * New provider entry will be the last entry inside the JRE. 374 */ 375 private static void createJavaSecurityFileExtn(boolean useName) { 376 int insertAt = Security.getProviders().length + 1; 377 String provider = (useName ? "TestProvider" : P_TYPE); 378 try { 379 Files.write(SEC_FILE, String.format("security.provider.%s=%s", 380 insertAt, provider).getBytes("UTF-8")); 381 } catch (IOException e) { 382 throw new RuntimeException(e); 383 } 384 System.out.printf("Security property file created at: %s with value:" 385 + " %s%n", SEC_FILE, provider); 386 } 387 }