From def242214d3194c45cf63b32f146b1400f9991da Mon Sep 17 00:00:00 2001 From: zhangxiangnan <1194256997@qq.com> Date: Tue, 1 Dec 2026 10:47:03 +0800 Subject: [PATCH] fix(skills): discover resources in executable JAR classpaths Supplement Guava scanning with JarURLConnection roots without adding a Spring runtime dependency. Preserve ordinary classpath behavior, per-loader deduplication, canonical archive/root deduplication across loaders and java.class.path, and cover JAR subdirectories, parent loaders, malformed roots, and multi-release URLs. Fixes #1895 --- .../adk/skills/ClassPathSkillSource.java | 662 ++++++++++--- .../adk/skills/ClassPathSkillSourceTest.java | 884 ++++++++++++++++++ 2 files changed, 1422 insertions(+), 124 deletions(-) diff --git a/core/src/main/java/com/google/adk/skills/ClassPathSkillSource.java b/core/src/main/java/com/google/adk/skills/ClassPathSkillSource.java index 8cb5458fe9..5da7df30d5 100644 --- a/core/src/main/java/com/google/adk/skills/ClassPathSkillSource.java +++ b/core/src/main/java/com/google/adk/skills/ClassPathSkillSource.java @@ -25,28 +25,43 @@ import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.io.ByteSource; import com.google.common.reflect.ClassPath; import com.google.common.reflect.ClassPath.ResourceInfo; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; +import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.net.JarURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLClassLoader; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; +import java.util.ArrayList; +import java.util.Enumeration; import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.Manifest; -/** Loads skills from the classpath. */ +/** Loads skills from file-based classpaths and {@code jar:} roots exposed by URL class loaders. */ public final class ClassPathSkillSource extends AbstractSkillSource { private static final Splitter PATH_SPLITTER = Splitter.on('/'); - private final String baseResourcePath; - private final ClassLoader classLoader; - private final Single> skillMdsSingle; - private final Single> allResourcesSingle; + private final ResourceSource legacySource; + private final ResourceSource delegate; /** * Creates a new {@link ClassPathSkillSource} that loads skills from the given base resource path @@ -70,13 +85,68 @@ public ClassPathSkillSource(String baseResourcePath) { * @param classLoader the class loader to use for scanning resources */ public ClassPathSkillSource(String baseResourcePath, ClassLoader classLoader) { - this.baseResourcePath = normalizePath(baseResourcePath); - this.classLoader = classLoader; + String normalizedPath = normalizePath(baseResourcePath); + Single> nativeResources = + Single.fromCallable(() -> scanNativeResources(normalizedPath, classLoader)).cache(); + this.legacySource = + new ResourceSource<>( + normalizedPath, + nativeResources, + ResourceInfo::getResourceName, + ResourceInfo::asByteSource); + this.delegate = + new ResourceSource<>( + normalizedPath, + nativeResources + .map(resources -> supplementJarResources(normalizedPath, classLoader, resources)) + .cache(), + ResourceHandle::name, + ResourceHandle::content); + } + + @Override + public Single> listFrontmatters() { + return delegate.listFrontmatters(); + } + + @Override + public Single loadFrontmatter(String skillName) { + return delegate.loadFrontmatter(skillName); + } + + @Override + public Single loadInstructions(String skillName) { + return delegate.loadInstructions(skillName); + } + + @Override + public Single loadResource(String skillName, String resourcePath) { + return delegate.loadResource(skillName, resourcePath); + } + + @Override + public Single> listResources(String skillName, String resourceDirectory) { + return delegate.listResources(skillName, resourceDirectory); + } + + @Override + protected Flowable> listSkills() { + return legacySource.listSkills(); + } - // Scan classpath once (lazily) - Single> scanned = Single.fromCallable(this::scanClassPath).cache(); - this.allResourcesSingle = scanned; - this.skillMdsSingle = scanned.map(this::extractSkillMds).cache(); + @Override + protected Single findSkillMdPath(String skillName) { + return legacySource.findSkillMdPath(skillName); + } + + @Override + protected Single findResourcePath(String skillName, String resourcePath) { + return legacySource.findResourcePath(skillName, resourcePath); + } + + @Override + protected ReadableByteChannel openChannel(ResourceInfo path) throws IOException { + return legacySource.openChannel(path); } private static String normalizePath(String path) { @@ -89,10 +159,10 @@ private static String normalizePath(String path) { return path + "/"; } - private ImmutableList scanClassPath() throws SkillSourceException { + private static ImmutableList scanNativeResources( + String baseResourcePath, ClassLoader classLoader) throws SkillSourceException { try { - ClassPath classPath = ClassPath.from(classLoader); - return classPath.getResources().stream() + return ClassPath.from(classLoader).getResources().stream() .filter(info -> info.getResourceName().startsWith(baseResourcePath)) .collect(toImmutableList()); } catch (IOException e) { @@ -101,128 +171,472 @@ private ImmutableList scanClassPath() throws SkillSourceException } } - private ImmutableMap extractSkillMds(ImmutableList resources) - throws SkillSourceException { - Map skillMdMap = new HashMap<>(); - for (ResourceInfo info : resources) { - String relPath = info.getResourceName().substring(baseResourcePath.length()); - List parts = PATH_SPLITTER.splitToList(relPath); - // Check if the path format matches exactly {skillName}/SKILL.md (or skill.md - // case-insensitively). - if (parts.size() == 2 && Ascii.equalsIgnoreCase(parts.get(1), "SKILL.md")) { - String skillName = parts.get(0); - String logicalName = skillName.replace('_', '-'); - if (skillMdMap.containsKey(logicalName)) { - ResourceInfo existing = skillMdMap.get(logicalName); - throw new SkillSourceException( - "Conflicting SKILL.md files found for skill '" - + logicalName - + "': " - + existing.getResourceName() - + " and " - + info.getResourceName(), - SKILL_LOAD_ERROR); + private static ImmutableList supplementJarResources( + String baseResourcePath, + ClassLoader classLoader, + ImmutableList nativeResources) { + List resources = new ArrayList<>(); + for (ResourceInfo info : nativeResources) { + // Preserve Guava's resource identity and lazy reads, including duplicate-name conflicts. + resources.add( + new ResourceHandle( + info.getResourceName(), + new ByteSource() { + @Override + public InputStream openStream() throws IOException { + return info.asByteSource().openStream(); + } + })); + } + for (String name : scanJarUrls(baseResourcePath, classLoader, !nativeResources.isEmpty())) { + // Match the supplied loader's resource lookup order; never retain an enumeration JarFile. + resources.add( + new ResourceHandle( + name, + new ByteSource() { + @Override + public InputStream openStream() throws IOException { + InputStream stream = classLoader.getResourceAsStream(name); + if (stream == null) { + throw new IOException("Classpath resource not found: " + name); + } + return stream; + } + })); + } + return ImmutableList.copyOf(resources); + } + + private static List scanJarUrls( + String baseResourcePath, ClassLoader classLoader, boolean hasNativeResources) { + List resources = new ArrayList<>(); + // Guava only scans file: classpath entries. Executable JAR classloaders also expose jar: + // roots, whose URL handlers provide JarURLConnection even for nested archives. + Set scannedRoots = new HashSet<>(); + // Without matching native resources, there are no file/JAR duplicates to reconcile. + FileClassPath fileClassPath = + hasNativeResources ? null : new FileClassPath(new HashSet<>(), new HashMap<>()); + for (ClassLoader loader = classLoader; loader != null; loader = loader.getParent()) { + if (!(loader instanceof URLClassLoader urlLoader)) { + continue; + } + // Same-loader classpath order wins. Cross-loader duplicates stay so they still conflict. + Set namesInLoader = null; + for (URL url : urlLoader.getURLs()) { + if (!url.getProtocol().equals("jar") || hasNetworkInnerProtocol(url)) { + continue; + } + try { + URL rootUrl = normalizeJarRootUrl(url); + if (!(rootUrl.openConnection() instanceof JarURLConnection connection)) { + continue; + } + URL jarFileUrl = connection.getJarFileURL(); + if (isNetworkProtocol(jarFileUrl.getProtocol())) { + continue; + } + String root = Objects.requireNonNullElse(connection.getEntryName(), ""); + if (!root.isEmpty() && !root.endsWith("/")) { + root += "/"; + } + String archiveIdentity = jarFileIdentity(jarFileUrl); + JarRoot jarRoot = new JarRoot(archiveIdentity, root); + if (scannedRoots.contains(jarRoot)) { + continue; + } + // A root-level file: URL is already covered by Guava. Subdirectory roots remain + // distinct because they remap archive entries to different classpath resource names. + if (fileClassPath == null) { + fileClassPath = fileClassPath(baseResourcePath, classLoader); + } + if (root.isEmpty() && fileClassPath.archiveRoots().contains(archiveIdentity)) { + continue; + } + connection = archiveRootConnection(rootUrl, connection, root); + connection.setUseCaches(false); + try (JarFile jar = connection.getJarFile()) { + if (namesInLoader == null) { + namesInLoader = + fileClassPath.namesByLoader().computeIfAbsent(loader, unused -> new HashSet<>()); + } + scannedRoots.add(jarRoot); + Enumeration entries = jar.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + if (!entry.isDirectory() && entry.getName().startsWith(root)) { + String name = entry.getName().substring(root.length()); + if (name.startsWith(baseResourcePath) && namesInLoader.add(name)) { + resources.add(name); + } + } + } + } + } catch (IOException | SecurityException ignored) { + // Match Guava ClassPath: an unreadable classpath root must not hide valid roots. } - skillMdMap.put(logicalName, info); } } - return ImmutableMap.copyOf(skillMdMap); + return resources; } - @Override - public Single> listResources(String skillName, String resourceDirectory) { - String logicalSkillName = skillName.replace('_', '-'); - String prefix = - resourceDirectory.isEmpty() - ? "" - : (resourceDirectory.endsWith("/") ? resourceDirectory : resourceDirectory + "/"); - - // Support both standard ADK hyphenated directories and legacy underscore directories. - String hyphenatedDir = logicalSkillName; - String underscoredDir = logicalSkillName.replace('-', '_'); - - return findSkillMdPath(skillName) - .flatMap( - ignored -> - allResourcesSingle.map( - resources -> - resources.stream() - .map( - info -> info.getResourceName().substring(baseResourcePath.length())) - .filter( - relPath -> - relPath.startsWith(hyphenatedDir + "/" + prefix) - || relPath.startsWith(underscoredDir + "/" + prefix)) - .map( - relPath -> { - if (relPath.startsWith(hyphenatedDir + "/")) { - return relPath.substring(hyphenatedDir.length() + 1); - } else { - return relPath.substring(underscoredDir.length() + 1); - } - }) - .filter(path -> !Ascii.equalsIgnoreCase(path, "SKILL.md")) - .collect(toImmutableList()))) - .flatMap( - list -> - (!resourceDirectory.isEmpty() && list.isEmpty()) - ? Single.error( - new SkillSourceException( - "Resource directory '" - + resourceDirectory - + "' not found for skill '" - + logicalSkillName - + "'", - RESOURCE_NOT_FOUND)) - : Single.just(list)); + private static FileClassPath fileClassPath(String baseResourcePath, ClassLoader classLoader) { + Map entries = new LinkedHashMap<>(); + ImmutableList.Builder hierarchy = ImmutableList.builder(); + for (ClassLoader loader = classLoader; loader != null; loader = loader.getParent()) { + hierarchy.add(loader); + } + for (ClassLoader loader : hierarchy.build().reverse()) { + if (loader instanceof URLClassLoader urlLoader) { + for (URL url : urlLoader.getURLs()) { + if (url.getProtocol().equals("file")) { + entries.putIfAbsent(fileFromUrl(url), loader); + } + } + } else if (loader.equals(ClassLoader.getSystemClassLoader())) { + addJavaClassPath(entries, loader); + } + } + // Guava reserves all explicit paths before following manifests, then scans them parent-first. + // Keep these paths separate from canonical archive identities: aliases can resolve relative + // manifest entries to different directories. + Set visited = new HashSet<>(entries.keySet()); + Set roots = new HashSet<>(); + Map> namesByLoader = new HashMap<>(); + for (Map.Entry entry : entries.entrySet()) { + Set names = + namesByLoader.computeIfAbsent(entry.getValue(), unused -> new HashSet<>()); + addFileClassPathRoot(baseResourcePath, entry.getKey(), visited, roots, names); + } + return new FileClassPath(roots, namesByLoader); } - @Override - protected Flowable> listSkills() { - return skillMdsSingle - .flattenAsFlowable(ImmutableMap::entrySet) - .map(entry -> new SkillMdPath<>(entry.getKey(), entry.getValue())); + private static void addFileClassPathRoot( + String baseResourcePath, File file, Set visited, Set roots, Set names) { + try { + if (!file.exists()) { + return; + } + } catch (SecurityException ignored) { + // Guava skips classpath entries whose existence cannot be checked. + return; + } + if (file.isDirectory()) { + try { + Set ancestors = new HashSet<>(); + ancestors.add(file.getCanonicalFile()); + addDirectoryResources(file, "", baseResourcePath, ancestors, names); + } catch (IOException ignored) { + // An unreadable directory must not hide other roots. + } + return; + } + try (JarFile jar = new JarFile(file)) { + roots.add(file.getCanonicalPath()); + Manifest manifest = jar.getManifest(); + String classPath = + manifest == null ? null : manifest.getMainAttributes().getValue("Class-Path"); + if (classPath != null) { + for (String entry : Splitter.on(' ').omitEmptyStrings().split(classPath)) { + try { + URL dependency = new URL(file.toURI().toURL(), entry); + if (dependency.getProtocol().equals("file")) { + File dependencyFile = fileFromUrl(dependency); + // Guava checks canonical paths for recursive edges, but resolves from the original. + if (visited.add(dependencyFile.getCanonicalFile())) { + addFileClassPathRoot(baseResourcePath, dependencyFile, visited, roots, names); + } + } + } catch (IllegalArgumentException | IOException ignored) { + // A malformed manifest entry must not hide the remaining roots. + } + } + } + Enumeration jarEntries = jar.entries(); + while (jarEntries.hasMoreElements()) { + JarEntry entry = jarEntries.nextElement(); + if (!entry.isDirectory() + && !entry.getName().equals(JarFile.MANIFEST_NAME) + && entry.getName().startsWith(baseResourcePath)) { + names.add(entry.getName()); + } + } + } catch (IOException ignored) { + // Missing, unreadable, and non-JAR entries are also skipped by Guava. + } } - @Override - protected Single findSkillMdPath(String skillName) { - String logicalSkillName = skillName.replace('_', '-'); - return skillMdsSingle - .mapOptional(map -> Optional.ofNullable(map.get(logicalSkillName))) - .switchIfEmpty( - Single.error( - new SkillSourceException( - "SKILL.md not found for skill: " + logicalSkillName, SKILL_NOT_FOUND))); + private static void addDirectoryResources( + File directory, + String prefix, + String baseResourcePath, + Set ancestors, + Set names) + throws IOException { + File[] files = directory.listFiles(); + if (files == null) { + return; + } + for (File file : files) { + String name = prefix + file.getName(); + if (file.isDirectory()) { + File canonical = file.getCanonicalFile(); + // Match Guava: stop cycles in the current path, but retain distinct symlink aliases. + if (ancestors.add(canonical)) { + addDirectoryResources(canonical, name + "/", baseResourcePath, ancestors, names); + ancestors.remove(canonical); + } + } else if (!name.equals(JarFile.MANIFEST_NAME) && name.startsWith(baseResourcePath)) { + names.add(name); + } + } } - @Override - protected Single findResourcePath(String skillName, String resourcePath) { - String logicalSkillName = skillName.replace('_', '-'); - // Support both standard ADK hyphenated directories and legacy underscore directories. - String hyphenatedDir = logicalSkillName; - String underscoredDir = logicalSkillName.replace('-', '_'); - - String hyphenatedPath = baseResourcePath + hyphenatedDir + "/" + resourcePath; - String underscoredPath = baseResourcePath + underscoredDir + "/" + resourcePath; - - return allResourcesSingle - .mapOptional( - resources -> - resources.stream() - .filter( - info -> - info.getResourceName().equals(hyphenatedPath) - || info.getResourceName().equals(underscoredPath)) - .findFirst()) - .switchIfEmpty( - Single.error( - new SkillSourceException( - "Resource not found: " + resourcePath + " for skill: " + logicalSkillName, - RESOURCE_NOT_FOUND))); + private static void addJavaClassPath(Map entries, ClassLoader loader) { + String classPath = System.getProperty("java.class.path"); + if (classPath == null) { + return; + } + for (String entry : Splitter.on(File.pathSeparatorChar).split(classPath)) { + entries.putIfAbsent(new File(entry).getAbsoluteFile(), loader); + } } - @Override - protected ReadableByteChannel openChannel(ResourceInfo path) throws IOException { - return Channels.newChannel(path.asByteSource().openStream()); + private record FileClassPath( + Set archiveRoots, Map> namesByLoader) {} + + private static String jarFileIdentity(URL url) { + if (!url.getProtocol().equals("file")) { + return withoutFragment(url); + } + try { + return fileFromUrl(url).getCanonicalPath(); + } catch (IOException e) { + return withoutFragment(url); + } + } + + private static File fileFromUrl(URL url) { + try { + URI uri = url.toURI(); + return new File(new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, null)); + } catch (IllegalArgumentException | URISyntaxException e) { + return new File(url.getPath()); + } + } + + private static String withoutFragment(URL url) { + String value = url.toExternalForm(); + int fragment = value.indexOf('#'); + return fragment < 0 ? value : value.substring(0, fragment); + } + + private static boolean hasNetworkInnerProtocol(URL url) { + String spec = url.getFile(); + while (true) { + int separator = spec.indexOf(':'); + if (separator <= 0) { + return false; + } + String protocol = spec.substring(0, separator); + if (isNetworkProtocol(protocol)) { + return true; + } + if (!protocol.equalsIgnoreCase("jar")) { + return false; + } + spec = spec.substring(separator + 1); + } + } + + private static boolean isNetworkProtocol(String protocol) { + return protocol.equalsIgnoreCase("http") + || protocol.equalsIgnoreCase("https") + || protocol.equalsIgnoreCase("ftp"); + } + + private static URL normalizeJarRootUrl(URL url) throws IOException { + String file = url.getFile(); + int separator = file.lastIndexOf("!/"); + if (separator < 0) { + return url; + } + List parts = PATH_SPLITTER.splitToList(file.substring(separator + 2)); + if (!parts.contains(".") && !parts.contains("..")) { + return url; + } + String fragment = url.getRef() == null ? "" : "#" + url.getRef(); + String directory = file.endsWith("/") ? file : file + "/"; + // Resolve through the original handler, before decoding escaped entry names such as %2e. + return new URL(new URL(url, "jar:" + directory + fragment), "." + fragment); + } + + private static JarURLConnection archiveRootConnection( + URL url, JarURLConnection connection, String root) throws IOException { + if (root.isEmpty()) { + return connection; + } + String file = url.getFile(); + int separator = file.lastIndexOf("!/"); + if (separator < 0) { + throw new IOException("Malformed JAR URL without !/: " + url); + } + String fragment = url.getRef() == null ? "" : "#" + url.getRef(); + URL archiveRoot = new URL(url, "jar:" + file.substring(0, separator + 2) + fragment); + if (!(archiveRoot.openConnection() instanceof JarURLConnection archiveConnection)) { + throw new IOException("JAR URL did not provide a JarURLConnection: " + archiveRoot); + } + return archiveConnection; + } + + private record JarRoot(String archiveIdentity, String root) {} + + private record ResourceHandle(String name, ByteSource content) {} + + /** Shares lookup and parsing behavior between the legacy and supplemented resource catalogs. */ + private static final class ResourceSource

extends AbstractSkillSource

{ + private final String baseResourcePath; + private final Single> allResourcesSingle; + private final Single> skillMdsSingle; + private final Function resourceName; + private final Function content; + + ResourceSource( + String baseResourcePath, + Single> resources, + Function resourceName, + Function content) { + this.baseResourcePath = baseResourcePath; + this.allResourcesSingle = resources; + this.resourceName = resourceName; + this.content = content; + this.skillMdsSingle = resources.map(this::extractSkillMds).cache(); + } + + private ImmutableMap extractSkillMds(ImmutableList

resources) + throws SkillSourceException { + Map skillMdMap = new HashMap<>(); + for (P info : resources) { + String relPath = resourceName.apply(info).substring(baseResourcePath.length()); + List parts = PATH_SPLITTER.splitToList(relPath); + // Check if the path format matches exactly {skillName}/SKILL.md (or skill.md + // case-insensitively). + if (parts.size() == 2 && Ascii.equalsIgnoreCase(parts.get(1), "SKILL.md")) { + String skillName = parts.get(0); + String logicalName = skillName.replace('_', '-'); + if (skillMdMap.containsKey(logicalName)) { + P existing = skillMdMap.get(logicalName); + throw new SkillSourceException( + "Conflicting SKILL.md files found for skill '" + + logicalName + + "': " + + resourceName.apply(existing) + + " and " + + resourceName.apply(info), + SKILL_LOAD_ERROR); + } + skillMdMap.put(logicalName, info); + } + } + return ImmutableMap.copyOf(skillMdMap); + } + + @Override + public Single> listResources(String skillName, String resourceDirectory) { + String logicalSkillName = skillName.replace('_', '-'); + String prefix = + resourceDirectory.isEmpty() + ? "" + : (resourceDirectory.endsWith("/") ? resourceDirectory : resourceDirectory + "/"); + + // Support both standard ADK hyphenated directories and legacy underscore directories. + String hyphenatedDir = logicalSkillName; + String underscoredDir = logicalSkillName.replace('-', '_'); + + return findSkillMdPath(skillName) + .flatMap( + ignored -> + allResourcesSingle.map( + resources -> + resources.stream() + .map( + info -> + resourceName.apply(info).substring(baseResourcePath.length())) + .filter( + relPath -> + relPath.startsWith(hyphenatedDir + "/" + prefix) + || relPath.startsWith(underscoredDir + "/" + prefix)) + .map( + relPath -> { + if (relPath.startsWith(hyphenatedDir + "/")) { + return relPath.substring(hyphenatedDir.length() + 1); + } else { + return relPath.substring(underscoredDir.length() + 1); + } + }) + .filter(path -> !Ascii.equalsIgnoreCase(path, "SKILL.md")) + .distinct() + .collect(toImmutableList()))) + .flatMap( + list -> + (!resourceDirectory.isEmpty() && list.isEmpty()) + ? Single.error( + new SkillSourceException( + "Resource directory '" + + resourceDirectory + + "' not found for skill '" + + logicalSkillName + + "'", + RESOURCE_NOT_FOUND)) + : Single.just(list)); + } + + @Override + protected Flowable> listSkills() { + return skillMdsSingle + .flattenAsFlowable(ImmutableMap::entrySet) + .map(entry -> new SkillMdPath<>(entry.getKey(), entry.getValue())); + } + + @Override + protected Single

findSkillMdPath(String skillName) { + String logicalSkillName = skillName.replace('_', '-'); + return skillMdsSingle + .mapOptional(map -> Optional.ofNullable(map.get(logicalSkillName))) + .switchIfEmpty( + Single.error( + new SkillSourceException( + "SKILL.md not found for skill: " + logicalSkillName, SKILL_NOT_FOUND))); + } + + @Override + protected Single

findResourcePath(String skillName, String resourcePath) { + String logicalSkillName = skillName.replace('_', '-'); + // Support both standard ADK hyphenated directories and legacy underscore directories. + String hyphenatedDir = logicalSkillName; + String underscoredDir = logicalSkillName.replace('-', '_'); + + String hyphenatedPath = baseResourcePath + hyphenatedDir + "/" + resourcePath; + String underscoredPath = baseResourcePath + underscoredDir + "/" + resourcePath; + + return allResourcesSingle + .mapOptional( + resources -> + resources.stream() + .filter( + info -> + resourceName.apply(info).equals(hyphenatedPath) + || resourceName.apply(info).equals(underscoredPath)) + .findFirst()) + .switchIfEmpty( + Single.error( + new SkillSourceException( + "Resource not found: " + resourcePath + " for skill: " + logicalSkillName, + RESOURCE_NOT_FOUND))); + } + + @Override + protected ReadableByteChannel openChannel(P path) throws IOException { + return Channels.newChannel(content.apply(path).openStream()); + } } } diff --git a/core/src/test/java/com/google/adk/skills/ClassPathSkillSourceTest.java b/core/src/test/java/com/google/adk/skills/ClassPathSkillSourceTest.java index 3db9f668f5..36ff89db07 100644 --- a/core/src/test/java/com/google/adk/skills/ClassPathSkillSourceTest.java +++ b/core/src/test/java/com/google/adk/skills/ClassPathSkillSourceTest.java @@ -17,13 +17,38 @@ package com.google.adk.skills; import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertThrows; +import static org.junit.Assume.assumeTrue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.io.ByteSource; +import com.google.common.reflect.ClassPath.ResourceInfo; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.JarURLConnection; +import java.net.URI; +import java.net.URL; +import java.net.URLClassLoader; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.nio.channels.Channels; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.Permission; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -32,6 +57,8 @@ public final class ClassPathSkillSourceTest { private static final String BASE_PATH = "skills/"; + @Rule public final TemporaryFolder temporary = new TemporaryFolder(); + // ========================================================================= // Constructor & Base Path Normalization // ========================================================================= @@ -202,4 +229,861 @@ public void testConflictingSkillMds() { assertThat(cause.getErrorCode()).isEqualTo(SkillSourceException.SKILL_LOAD_ERROR); assertThat(cause).hasMessageThat().contains("Conflicting SKILL.md files found for skill 'a-b'"); } + + // ========================================================================= + // Packaged Resources & ClassLoader Compatibility + // ========================================================================= + + @Test + public void testOrdinaryJar_withoutDirectoryEntries() throws Exception { + Path jar = skillJar("ordinary.jar", "", "ordinary-skill"); + try (URLClassLoader loader = new URLClassLoader(new URL[] {jar.toUri().toURL()}, null)) { + assertSkill(new ClassPathSkillSource("skills/", loader), "ordinary-skill"); + } + } + + @Test + public void testJarUrl_withoutDirectoryEntries() throws Exception { + Path jar = skillJar("jar-url.jar", "", "jar-skill"); + try (URLClassLoader loader = new URLClassLoader(new URL[] {jarRoot(jar, "")}, null)) { + assertThat(loader.getResource("skills/jar-skill/SKILL.md")).isNotNull(); + assertSkill(new ClassPathSkillSource("skills/", loader), "jar-skill"); + } + } + + @Test + public void testJarSubdirectory_isRelativeToClassLoaderRoot() throws Exception { + Path jar = skillJar("application with spaces.jar", "BOOT-INF/classes/", "app-skill"); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {jarRoot(jar, "BOOT-INF/classes/")}, null)) { + assertSkill(new ClassPathSkillSource("skills", loader), "app-skill"); + assertThat(new ClassPathSkillSource("", loader).listFrontmatters().blockingGet().keySet()) + .containsExactly("root-skill"); + } + } + + @Test + public void testScanJarUrls_alongsideFileUrlsAndParentLoaders() throws Exception { + Path parentJar = skillJar("parent.jar", "", "parent-skill"); + Path childJar = skillJar("child.jar", "", "child-skill"); + try (URLClassLoader parent = new URLClassLoader(new URL[] {jarRoot(parentJar, "")}, null); + URLClassLoader child = new URLClassLoader(new URL[] {childJar.toUri().toURL()}, parent)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", child); + assertThat(source.listFrontmatters().blockingGet().keySet()) + .containsExactly("parent-skill", "child-skill"); + assertThat(source.loadInstructions("parent-skill").blockingGet()).isEqualTo("Instructions."); + assertThat(source.loadInstructions("child-skill").blockingGet()).isEqualTo("Instructions."); + } + } + + @Test + public void testCompatibility_retainsGenericSuperclassAndProtectedMethods() throws Exception { + Path jar = skillJar("legacy.jar", "", "legacy-skill"); + try (URLClassLoader loader = new URLClassLoader(new URL[] {jar.toUri().toURL()}, null)) { + AbstractSkillSource source = new ClassPathSkillSource("skills/", loader); + ResourceInfo skill = source.findSkillMdPath("legacy-skill").blockingGet(); + assertThat(skill.getResourceName()).isEqualTo("skills/legacy-skill/SKILL.md"); + assertThat(source.listSkills().count().blockingGet()).isEqualTo(1); + ResourceInfo resource = + source.findResourcePath("legacy-skill", "references/nested/guide.txt").blockingGet(); + try (var stream = Channels.newInputStream(source.openChannel(resource))) { + assertThat(new String(stream.readAllBytes(), UTF_8)).isEqualTo("Reference text."); + } + assertThat(source.loadInstructions("legacy-skill").blockingGet()).isEqualTo("Instructions."); + } + } + + @Test + public void testScan_isLazyAndSharedWithProtectedMethods() throws Exception { + Path jar = skillJar("cached.jar", "", "cached-skill"); + AtomicInteger scans = new AtomicInteger(); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {jar.toUri().toURL()}, null) { + @Override + public URL[] getURLs() { + scans.incrementAndGet(); + return super.getURLs(); + } + }) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", loader); + assertThat(scans.get()).isEqualTo(0); + source.listFrontmatters().blockingGet(); + int scansAfterDiscovery = scans.get(); + assertThat(scansAfterDiscovery).isGreaterThan(0); + + // Public and protected lookups reuse discovery, regardless of its scan phases. + assertSkill(source, "cached-skill"); + source.findSkillMdPath("cached-skill").blockingGet(); + source.findResourcePath("cached-skill", "references/nested/guide.txt").blockingGet(); + source.listSkills().toList().blockingGet(); + assertThat(scans.get()).isEqualTo(scansAfterDiscovery); + } + } + + @Test + public void testScan_sameArchiveExposedAsFileAndJarDoesNotDuplicateSkills() throws Exception { + Path jar = skillJar("duplicate-url.jar", "", "single-skill"); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {jar.toUri().toURL(), jarRoot(jar, "")}, null)) { + assertSkill(new ClassPathSkillSource("skills/", loader), "single-skill"); + } + } + + @Test + public void testScan_retainsNativeDuplicateNameConflictsAcrossLoaders() throws Exception { + Path parentJar = skillJar("native-parent.jar", "", "conflicting-skill"); + Path childJar = skillJar("native-child.jar", "", "conflicting-skill"); + try (URLClassLoader parent = new URLClassLoader(new URL[] {parentJar.toUri().toURL()}, null); + URLClassLoader child = new URLClassLoader(new URL[] {childJar.toUri().toURL()}, parent)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", child); + assertSkillLoadError(() -> source.listFrontmatters().blockingGet(), "Conflicting SKILL.md"); + assertSkillLoadError( + () -> source.findSkillMdPath("conflicting-skill").blockingGet(), "Conflicting SKILL.md"); + } + } + + @Test + public void testNativeReads_retainTheDiscoveringLoader() throws Exception { + Path jar = skillJar("native-origin.jar", "", "parent-skill"); + URL replacement = temporary.newFile("replacement.txt").toURI().toURL(); + try (URLClassLoader parent = new URLClassLoader(new URL[] {jar.toUri().toURL()}, null); + URLClassLoader child = + new URLClassLoader(new URL[0], parent) { + @Override + public URL getResource(String name) { + return name.startsWith("skills/") ? replacement : super.getResource(name); + } + }) { + assertSkill(new ClassPathSkillSource("skills/", child), "parent-skill"); + } + } + + @Test + public void testScan_duplicateJarResourcesConflictAcrossLoaders() throws Exception { + Path parentJar = skillJar("jar-parent.jar", "", "shared-skill", "Parent instructions."); + Path childJar = skillJar("jar-child.jar", "", "shared-skill", "Child instructions."); + try (URLClassLoader parent = new URLClassLoader(new URL[] {jarRoot(parentJar, "")}, null); + URLClassLoader child = new URLClassLoader(new URL[] {jarRoot(childJar, "")}, parent)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", child); + assertSkillLoadError(() -> source.listFrontmatters().blockingGet(), "Conflicting SKILL.md"); + } + } + + @Test + public void testScan_differentFileAndJarRootsWithSameResourceConflict() throws Exception { + Path parentJar = skillJar("mixed-parent.jar", "", "shared-skill"); + Path childJar = skillJar("mixed-child.jar", "", "shared-skill"); + for (boolean parentUsesJarUrl : ImmutableList.of(false, true)) { + URL parentUrl = parentUsesJarUrl ? jarRoot(parentJar, "") : parentJar.toUri().toURL(); + URL childUrl = parentUsesJarUrl ? childJar.toUri().toURL() : jarRoot(childJar, ""); + try (URLClassLoader parent = new URLClassLoader(new URL[] {parentUrl}, null); + URLClassLoader child = new URLClassLoader(new URL[] {childUrl}, parent)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", child); + assertSkillLoadError(() -> source.listFrontmatters().blockingGet(), "Conflicting SKILL.md"); + } + } + } + + @Test + public void testScan_sameJarRootAcrossLoadersIsScannedOnce() throws Exception { + Path jar = skillJar("shared-root.jar", "", "shared-skill"); + URL root = jarRoot(jar, ""); + try (URLClassLoader parent = new URLClassLoader(new URL[] {root}, null); + URLClassLoader child = new URLClassLoader(new URL[] {root}, parent)) { + assertSkill(new ClassPathSkillSource("skills/", child), "shared-skill"); + } + } + + @Test + public void testScan_sameLoaderJarRootsKeepFirstSkillAndResource() throws Exception { + Path classes = skillJar("classes.jar", "", "app-skill", "From classes."); + Path dependency = skillJar("dependency.jar", "", "app-skill", "From dependency."); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {jarRoot(classes, ""), jarRoot(dependency, "")}, null)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", loader); + assertThat(source.listFrontmatters().blockingGet().keySet()).containsExactly("app-skill"); + assertThat(source.loadInstructions("app-skill").blockingGet()).isEqualTo("From classes."); + assertThat(source.listResources("app-skill", "references").blockingGet()) + .containsExactly("references/nested/guide.txt"); + } + } + + @Test + public void testScan_sameLoaderMixedRootsKeepFirstSkill() throws Exception { + Path first = skillJar("mixed-first.jar", "", "mixed-skill", "First instructions."); + Path second = skillJar("mixed-second.jar", "", "mixed-skill", "Second instructions."); + for (boolean jarFirst : ImmutableList.of(false, true)) { + URL firstUrl = jarFirst ? jarRoot(first, "") : first.toUri().toURL(); + URL secondUrl = jarFirst ? second.toUri().toURL() : jarRoot(second, ""); + try (URLClassLoader loader = new URLClassLoader(new URL[] {firstUrl, secondUrl}, null)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", loader); + assertThat(source.listFrontmatters().blockingGet().keySet()).containsExactly("mixed-skill"); + assertThat(source.loadInstructions("mixed-skill").blockingGet()) + .isEqualTo("First instructions."); + assertThat(source.listResources("mixed-skill", "references").blockingGet()) + .containsExactly("references/nested/guide.txt"); + } + } + } + + @Test + public void testScan_directoryDoesNotRequireCreatingClassLoader() throws Exception { + // Run the permission check in a subprocess; Java 24+ disables SecurityManager. + assumeTrue(Runtime.version().feature() < 24); + Path directory = skillDirectory("restricted-classes", "shared-skill"); + Path jar = skillJar("restricted.jar", "", "shared-skill"); + Path deniedDirectory = temporary.newFolder("denied-directory").toPath(); + Path deniedJar = skillJar("denied.jar", "", "denied-skill"); + String java = Path.of(System.getProperty("java.home"), "bin", "java").toString(); + File log = temporary.newFile("restricted-loader.log"); + Process process = + new ProcessBuilder( + java, + "-Djava.security.manager=allow", + "-cp", + System.getProperty("java.class.path"), + RestrictedClassLoaderProbe.class.getName(), + directory.toString(), + jar.toString(), + deniedDirectory.toString(), + deniedJar.toString()) + .redirectErrorStream(true) + .redirectOutput(log) + .start(); + boolean finished = process.waitFor(30, TimeUnit.SECONDS); + if (!finished) { + process.destroyForcibly(); + } + String output = Files.readString(log.toPath(), UTF_8); + assertWithMessage(output).that(finished).isTrue(); + assertWithMessage(output).that(process.exitValue()).isEqualTo(0); + } + + @Test + public void testScan_sameLoaderDirectoryAndJarKeepFirstSkill() throws Exception { + Path directory = skillDirectory("classes", "mixed-skill"); + Path jar = skillJar("directory-mixed.jar", "", "mixed-skill", "JAR instructions."); + for (boolean jarFirst : ImmutableList.of(false, true)) { + URL[] urls = + jarFirst + ? new URL[] {jarRoot(jar, ""), directory.toUri().toURL()} + : new URL[] {directory.toUri().toURL(), jarRoot(jar, "")}; + try (URLClassLoader loader = new URLClassLoader(urls, null)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", loader); + assertThat(source.listFrontmatters().blockingGet().keySet()).containsExactly("mixed-skill"); + assertThat(source.loadInstructions("mixed-skill").blockingGet()) + .isEqualTo(jarFirst ? "JAR instructions." : "Directory instructions."); + } + } + } + + @Test + public void testScan_directoryAliasesRemainDistinctWhileCyclesAreSkipped() throws Exception { + Path directory = skillDirectory("symlink-classes", "mixed-skill"); + Path skill = directory.resolve("skills/mixed-skill"); + Path references = Files.createDirectories(skill.resolve("references")); + Path assets = temporary.newFolder("assets").toPath(); + Files.writeString(assets.resolve("guide.txt"), "Shared reference.", UTF_8); + Files.createSymbolicLink(assets.resolve("loop"), assets); + Files.createSymbolicLink(references.resolve("first"), assets); + Files.createSymbolicLink(references.resolve("second"), assets); + Path jar = skillJar("symlink-mixed.jar", "", "mixed-skill"); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {directory.toUri().toURL(), jarRoot(jar, "")}, null)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", loader); + assertThat(source.listFrontmatters().blockingGet().keySet()).containsExactly("mixed-skill"); + assertThat(source.listResources("mixed-skill", "references").blockingGet()) + .containsExactly( + "references/first/guide.txt", + "references/second/guide.txt", + "references/nested/guide.txt"); + assertThat( + source + .loadResource("mixed-skill", "references/second/guide.txt") + .blockingGet() + .read()) + .isEqualTo("Shared reference.".getBytes(UTF_8)); + } + } + + @Test + public void testScan_childExplicitRootRetainsParentManifestOwnership() throws Exception { + temporary.newFolder("real"); + temporary.newFolder("alias"); + Path launcher = manifestJar("real/launcher.jar", "dep.jar").toRealPath(); + skillJar("real/dep.jar", "", "real-skill"); + Path aliasDependency = skillJar("alias/dep.jar", "", "alias-skill"); + Files.createSymbolicLink(aliasDependency.resolveSibling("launcher.jar"), launcher); + Path bridge = manifestJar("real/bridge.jar", "launcher.jar").toRealPath(); + Path realEntry = manifestJar("real/entry.jar", "bridge.jar").toRealPath(); + Path aliasEntry = manifestJar("alias/entry.jar", "launcher.jar").toRealPath(); + Path other = skillJar("other-alias.jar", "", "alias-skill", "Other instructions."); + for (boolean parentUsesJarUrl : ImmutableList.of(false, true)) { + URL otherUrl = parentUsesJarUrl ? jarRoot(other, "") : other.toUri().toURL(); + try (URLClassLoader parent = + new URLClassLoader( + new URL[] {realEntry.toUri().toURL(), aliasEntry.toUri().toURL(), otherUrl}, + null); + URLClassLoader child = new URLClassLoader(new URL[] {bridge.toUri().toURL()}, parent)) { + assertSkill(new ClassPathSkillSource("skills/", child), "alias-skill"); + } + } + } + + @Test + public void testScan_childExplicitManifestDependencyRetainsCrossLoaderConflict() + throws Exception { + Path dependency = skillJar("reserved-dependency.jar", "", "shared").toRealPath(); + Path other = skillJar("other-reserved.jar", "", "shared"); + Path launcher = manifestJar("reserved-launcher.jar", "reserved-dependency.jar").toRealPath(); + for (boolean parentUsesJarUrl : ImmutableList.of(false, true)) { + URL otherUrl = parentUsesJarUrl ? jarRoot(other, "") : other.toUri().toURL(); + try (URLClassLoader parent = + new URLClassLoader(new URL[] {launcher.toUri().toURL(), otherUrl}, null); + URLClassLoader child = + new URLClassLoader(new URL[] {dependency.toUri().toURL()}, parent)) { + assertSkillLoadError( + () -> new ClassPathSkillSource("skills/", child).listFrontmatters().blockingGet(), + "Conflicting SKILL.md files found for skill 'shared'"); + } + } + } + + @Test + public void testScan_manifestDependencyAndJarAliasDoNotDuplicate() throws Exception { + Path dependency = skillJar("manifest-dependency.jar", "", "manifest-skill"); + Path bridge = manifestJar("bridge.jar", "manifest-dependency.jar launcher.jar"); + Path launcher = manifestJar("launcher.jar", bridge.getFileName().toString()); + for (boolean acrossLoaders : ImmutableList.of(false, true)) { + URL[] parentUrls = acrossLoaders ? new URL[] {launcher.toUri().toURL()} : new URL[0]; + URL[] childUrls = + acrossLoaders + ? new URL[] {jarRoot(dependency, "")} + : new URL[] {launcher.toUri().toURL(), jarRoot(dependency, "")}; + try (URLClassLoader parent = new URLClassLoader(parentUrls, null); + URLClassLoader child = new URLClassLoader(childUrls, parent)) { + assertSkill(new ClassPathSkillSource("skills/", child), "manifest-skill"); + } + } + } + + @Test + public void testScan_manifestDependenciesAreRelativeToSymlinkLocation() throws Exception { + temporary.newFolder("real path"); + temporary.newFolder("alias path"); + Path launcher = manifestJar("real path/launcher.jar", "dep.jar"); + Path realDependency = skillJar("real path/dep.jar", "", "real-skill"); + Path aliasDependency = skillJar("alias path/dep.jar", "", "alias-skill"); + Path link = Files.createSymbolicLink(aliasDependency.resolveSibling("launcher.jar"), launcher); + for (boolean exposeAlias : ImmutableList.of(false, true)) { + URL[] urls = + exposeAlias + ? new URL[] { + link.toUri().toURL(), jarRoot(aliasDependency, ""), jarRoot(realDependency, "") + } + : new URL[] {link.toUri().toURL(), jarRoot(realDependency, "")}; + try (URLClassLoader loader = new URLClassLoader(urls, null)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", loader); + assertThat(source.listFrontmatters().blockingGet().keySet()) + .containsExactly("alias-skill", "real-skill"); + for (String name : ImmutableList.of("alias-skill", "real-skill")) { + assertThat(source.loadInstructions(name).blockingGet()).isEqualTo("Instructions."); + assertThat(source.loadResource(name, "references/nested/guide.txt").blockingGet().read()) + .isEqualTo("Reference text.".getBytes(UTF_8)); + } + } + } + } + + @Test + public void testScan_manifestAliasesAcrossLoadersRetainBothDependencyRoots() throws Exception { + Path real = temporary.newFolder("real").toPath(); + temporary.newFolder("alias"); + Path launcher = manifestJar("real/launcher.jar", "dep.jar loop/launcher.jar"); + Path realDependency = skillJar("real/dep.jar", "", "real-skill"); + Path aliasDependency = skillJar("alias/dep.jar", "", "alias-skill"); + Path link = Files.createSymbolicLink(aliasDependency.resolveSibling("launcher.jar"), launcher); + Files.createSymbolicLink(real.resolve("loop"), real); + for (boolean parentUsesAlias : ImmutableList.of(true, false)) { + URL parentUrl = (parentUsesAlias ? link : launcher).toUri().toURL(); + URL childUrl = (parentUsesAlias ? launcher : link).toUri().toURL(); + try (URLClassLoader parent = new URLClassLoader(new URL[] {parentUrl}, null); + URLClassLoader child = + new URLClassLoader( + new URL[] {childUrl, jarRoot(aliasDependency, ""), jarRoot(realDependency, "")}, + parent)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", child); + assertThat(source.listFrontmatters().blockingGet().keySet()) + .containsExactly("alias-skill", "real-skill"); + for (String name : ImmutableList.of("alias-skill", "real-skill")) { + assertThat(source.loadInstructions(name).blockingGet()).isEqualTo("Instructions."); + assertThat(source.listResources(name, "references").blockingGet()) + .containsExactly("references/nested/guide.txt"); + } + } + } + } + + @Test + public void testScan_indirectManifestAliasesFollowParentFirstOrder() throws Exception { + temporary.newFolder("real"); + temporary.newFolder("alias"); + Path launcher = manifestJar("real/launcher.jar", "dep.jar"); + Path realDependency = skillJar("real/dep.jar", "", "real-skill"); + Path aliasDependency = skillJar("alias/dep.jar", "", "alias-skill"); + Files.createSymbolicLink(aliasDependency.resolveSibling("launcher.jar"), launcher); + Path realEntry = manifestJar("real/entry.jar", "launcher.jar"); + Path aliasEntry = manifestJar("alias/entry.jar", "launcher.jar"); + for (boolean parentUsesAlias : ImmutableList.of(true, false)) { + URL parentUrl = (parentUsesAlias ? aliasEntry : realEntry).toUri().toURL(); + URL childUrl = (parentUsesAlias ? realEntry : aliasEntry).toUri().toURL(); + Path childDependency = parentUsesAlias ? realDependency : aliasDependency; + try (URLClassLoader parent = new URLClassLoader(new URL[] {parentUrl}, null); + URLClassLoader child = + new URLClassLoader(new URL[] {childUrl, jarRoot(childDependency, "")}, parent)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", child); + assertThat(source.listFrontmatters().blockingGet().keySet()) + .containsExactly("alias-skill", "real-skill"); + for (String name : ImmutableList.of("alias-skill", "real-skill")) { + assertThat(source.loadInstructions(name).blockingGet()).isEqualTo("Instructions."); + assertThat(source.loadResource(name, "references/nested/guide.txt").blockingGet().read()) + .isEqualTo("Reference text.".getBytes(UTF_8)); + } + } + } + } + + @Test + public void testScan_explicitManifestAliasDoesNotSkipIndirectRoot() throws Exception { + temporary.newFolder("real"); + temporary.newFolder("alias"); + Path launcher = manifestJar("real/launcher.jar", "dep.jar"); + Path realDependency = skillJar("real/dep.jar", "", "real-skill"); + Path aliasDependency = skillJar("alias/dep.jar", "", "alias-skill"); + Path link = Files.createSymbolicLink(aliasDependency.resolveSibling("launcher.jar"), launcher); + Path entry = manifestJar("real/entry.jar", "launcher.jar"); + try (URLClassLoader parent = + new URLClassLoader(new URL[] {link.toUri().toURL(), entry.toUri().toURL()}, null); + URLClassLoader child = + new URLClassLoader( + new URL[] {jarRoot(realDependency, ""), jarRoot(aliasDependency, "")}, parent)) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", child); + assertThat(source.listFrontmatters().blockingGet().keySet()) + .containsExactly("alias-skill", "real-skill"); + for (String name : ImmutableList.of("alias-skill", "real-skill")) { + assertThat(source.loadInstructions(name).blockingGet()).isEqualTo("Instructions."); + assertThat(source.loadResource(name, "references/nested/guide.txt").blockingGet().read()) + .isEqualTo("Reference text.".getBytes(UTF_8)); + } + } + } + + @Test + public void testScan_invalidManifestEntriesDoNotHideValidDependency() throws Exception { + Path dependency = skillJar("valid-manifest-dependency.jar", "", "manifest-skill"); + Files.writeString(temporary.newFile("not-a-jar.txt").toPath(), "not a JAR", UTF_8); + Path launcher = + manifestJar( + "invalid-entries.jar", + "missing.jar not-a-jar.txt http://[invalid https://invalid.example/ignored.jar " + + dependency.getFileName()); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {launcher.toUri().toURL(), jarRoot(dependency, "")}, null)) { + assertSkill(new ClassPathSkillSource("skills/", loader), "manifest-skill"); + } + } + + @Test + public void testScan_fileUrlAndJarUrlFormsDoNotDuplicate() throws Exception { + Path jar = skillJar("url form.jar", "", "url-form-skill"); + URL fileUrl = jar.getParent().resolve(".").resolve(jar.getFileName()).toUri().toURL(); + URL jarUrl = jarRoot(jar, ""); + assertThat(fileUrl.toExternalForm()) + .isNotEqualTo( + ((JarURLConnection) jarUrl.openConnection()).getJarFileURL().toExternalForm()); + try (URLClassLoader loader = new URLClassLoader(new URL[] {fileUrl, jarUrl}, null)) { + assertSkill(new ClassPathSkillSource("skills/", loader), "url-form-skill"); + } + } + + @Test + public void testScan_systemClassPathAndChildJarRootDoNotDuplicate() throws Exception { + Path jar = skillJar("system-classpath.jar", "", "system-classpath-skill"); + String java = + ProcessHandle.current() + .info() + .command() + .orElse(Path.of(System.getProperty("java.home"), "bin", "java").toString()); + String classPath = System.getProperty("java.class.path") + File.pathSeparator + jar; + File logFile = temporary.newFile("system-classpath-probe.log"); + Process process = + new ProcessBuilder( + java, "-cp", classPath, SystemClassPathProbe.class.getName(), jar.toString()) + .redirectOutput(logFile) + .redirectErrorStream(true) + .start(); + boolean finished = process.waitFor(30, TimeUnit.SECONDS); + if (!finished) { + process.destroyForcibly(); + } + String output = Files.readString(logFile.toPath(), UTF_8); + assertThat(finished).isTrue(); + assertWithMessage(output).that(process.exitValue()).isEqualTo(0); + assertThat(output).contains("system-classpath-skill"); + } + + @Test + public void testScan_runtimeFragmentAndPlainJarRootAcrossLoadersDoNotConflict() throws Exception { + Path jar = skillJar("runtime-once.jar", "BOOT-INF/classes/", "runtime-once-skill"); + URL plain = jarRoot(jar, "BOOT-INF/classes"); + URL runtime = URI.create("jar:" + jar.toUri() + "!/BOOT-INF/classes/#runtime").toURL(); + try (URLClassLoader parent = new URLClassLoader(new URL[] {plain}, null); + URLClassLoader child = + new URLClassLoader(new URL[] {runtime}, parent) { + @Override + public InputStream getResourceAsStream(String name) { + try { + return jarRoot(jar, "BOOT-INF/classes/" + name).openStream(); + } catch (IOException e) { + return null; + } + } + }) { + assertSkill(new ClassPathSkillSource("skills/", child), "runtime-once-skill"); + } + } + + @Test + public void testScan_failedAliasDoesNotHideEquivalentValidRoot() throws Exception { + Path jar = skillJar("failed-alias.jar", "", "valid-alias-skill"); + URL validRoot = jarRoot(jar, ""); + URL failedRoot = + new URL( + null, + validRoot.toExternalForm(), + new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL url) throws IOException { + return new JarURLConnection(url) { + @Override + public void connect() {} + + @Override + public JarFile getJarFile() throws IOException { + throw new IOException("Simulated unreadable alias"); + } + }; + } + }); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {failedRoot, validRoot}, null) { + @Override + public InputStream getResourceAsStream(String name) { + try { + return jarRoot(jar, name).openStream(); + } catch (IOException e) { + return null; + } + } + }) { + assertSkill(new ClassPathSkillSource("skills/", loader), "valid-alias-skill"); + } + } + + @Test + public void testScan_doesNotOpenUnsupportedProtocolRoots() throws Exception { + URL root = + new URL( + null, + "custom:/skills/", + new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL url) { + throw new AssertionError("Unsupported root must not be opened"); + } + }); + try (URLClassLoader loader = new URLClassLoader(new URL[] {root}, null)) { + assertThat(new ClassPathSkillSource("skills/", loader).listFrontmatters().blockingGet()) + .isEmpty(); + } + } + + @Test + public void testScan_skipsMissingJarRootAlongsideValidFileRoot() throws Exception { + Path validJar = skillJar("valid.jar", "", "valid-skill"); + Path missingJar = temporary.getRoot().toPath().resolve("missing.jar"); + URL missingRoot = URI.create("jar:" + missingJar.toUri() + "!/").toURL(); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {missingRoot, validJar.toUri().toURL()}, null)) { + assertSkill(new ClassPathSkillSource("skills/", loader), "valid-skill"); + } + } + + @Test + public void testScan_skipsRemoteJarRoots() throws Exception { + URL remoteRoot = + new URL( + null, + "jar:https://example.invalid/remote.jar!/", + new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL url) { + throw new AssertionError("Remote JAR URL handler must not be opened"); + } + }); + try (URLClassLoader loader = new URLClassLoader(new URL[] {remoteRoot}, null)) { + assertThat(new ClassPathSkillSource("skills/", loader).listFrontmatters().blockingGet()) + .isEmpty(); + } + } + + @Test + public void testScan_supportsMultiReleaseJarUrlFragment() throws Exception { + Path jar = skillJar("multi-release.jar", "BOOT-INF/classes/", "runtime-skill"); + URL runtimeRoot = URI.create("jar:" + jar.toUri() + "!/BOOT-INF/classes/#runtime").toURL(); + try (URLClassLoader loader = new URLClassLoader(new URL[] {runtimeRoot}, null)) { + assertSkill(new ClassPathSkillSource("skills/", loader), "runtime-skill"); + } + } + + @Test + public void testScan_nonUrlClassLoaderDelegatesToJarParent() throws Exception { + Path jar = skillJar("parent-only.jar", "", "parent-skill"); + try (URLClassLoader parent = new URLClassLoader(new URL[] {jarRoot(jar, "")}, null)) { + ClassLoader child = new ClassLoader(parent) {}; + assertSkill(new ClassPathSkillSource("skills/", child), "parent-skill"); + } + } + + @Test + public void testLoadFrontmatter_jarResourceStreamMissing() throws Exception { + Path jar = skillJar("missing-stream.jar", "", "missing-stream-skill"); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {jarRoot(jar, "")}, null) { + @Override + public InputStream getResourceAsStream(String name) { + return null; + } + }) { + assertSkillLoadError( + () -> new ClassPathSkillSource("skills/", loader).listFrontmatters().blockingGet(), + "Cannot load frontmatter"); + } + } + + @Test + public void testScan_jarProtocolWithoutJarUrlConnectionIsIgnored() throws Exception { + URL root = + new URL( + null, + "jar:custom:/skills.jar!/", + new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL url) { + return new URLConnection(url) { + @Override + public void connect() {} + }; + } + }); + try (URLClassLoader loader = new URLClassLoader(new URL[] {root}, null)) { + assertThat(new ClassPathSkillSource("skills/", loader).listFrontmatters().blockingGet()) + .isEmpty(); + } + } + + @Test + public void testScan_jarRootsNormalizeDotSegments() throws Exception { + Path rootJar = skillJar("dot-root.jar", "", "dot-skill"); + Path subdirectoryJar = skillJar("dot-subdirectory.jar", "BOOT-INF/classes/", "dot-skill"); + for (String prefix : ImmutableList.of("./", "other/../", "././")) { + try (URLClassLoader loader = new URLClassLoader(new URL[] {jarRoot(rootJar, prefix)}, null)) { + assertSkill(new ClassPathSkillSource("skills/", loader), "dot-skill"); + } + } + for (String prefix : ImmutableList.of("BOOT-INF/./classes/", "BOOT-INF/other/../classes/")) { + for (String fragment : ImmutableList.of("", "#runtime")) { + URL root = jarRoot(subdirectoryJar, prefix + fragment); + try (URLClassLoader loader = new URLClassLoader(new URL[] {root}, null)) { + assertSkill(new ClassPathSkillSource("skills/", loader), "dot-skill"); + } + } + } + } + + @Test + public void testScan_dotSegmentJarAliasesAcrossLoadersDoNotConflict() throws Exception { + Path jar = skillJar("dot-alias.jar", "BOOT-INF/classes/", "dot-skill"); + try (URLClassLoader parent = + new URLClassLoader(new URL[] {jarRoot(jar, "BOOT-INF/classes/")}, null); + URLClassLoader child = + new URLClassLoader( + new URL[] {jarRoot(jar, "BOOT-INF/other/../classes/#runtime")}, parent)) { + assertSkill(new ClassPathSkillSource("skills/", child), "dot-skill"); + } + } + + @Test + public void testScan_encodedDotsRemainLiteralEntryNames() throws Exception { + Path jar = skillJar("literal-dots.jar", "BOOT-INF/./classes/", "literal-skill"); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {jarRoot(jar, "BOOT-INF/%2e/classes/")}, null)) { + assertSkill(new ClassPathSkillSource("skills/", loader), "literal-skill"); + } + } + + @Test + public void testScan_jarSubdirectoryWithoutTrailingSlash() throws Exception { + Path jar = skillJar("subdirectory-no-slash.jar", "BOOT-INF/classes/", "app-skill"); + try (URLClassLoader loader = + new URLClassLoader(new URL[] {jarRoot(jar, "BOOT-INF/classes")}, null) { + @Override + public InputStream getResourceAsStream(String name) { + try { + return jarRoot(jar, "BOOT-INF/classes/" + name).openStream(); + } catch (IOException e) { + return null; + } + } + }) { + assertSkill(new ClassPathSkillSource("skills/", loader), "app-skill"); + } + } + + private static void assertSkillLoadError(Runnable action, String message) { + RuntimeException error = assertThrows(RuntimeException.class, action::run); + assertThat(error).hasCauseThat().isInstanceOf(SkillSourceException.class); + SkillSourceException cause = (SkillSourceException) error.getCause(); + assertThat(cause.getErrorCode()).isEqualTo(SkillSourceException.SKILL_LOAD_ERROR); + assertThat(cause).hasMessageThat().contains(message); + } + + private void assertSkill(ClassPathSkillSource source, String name) throws IOException { + assertThat(source.listFrontmatters().blockingGet().keySet()).containsExactly(name); + assertThat(source.loadFrontmatter(name).blockingGet().name()).isEqualTo(name); + assertThat(source.loadInstructions(name).blockingGet()).isEqualTo("Instructions."); + assertThat(source.listResources(name, "references").blockingGet()) + .containsExactly("references/nested/guide.txt"); + assertThat(source.loadResource(name, "references/nested/guide.txt").blockingGet().read()) + .isEqualTo("Reference text.".getBytes(UTF_8)); + } + + private Path skillDirectory(String directoryName, String name) throws IOException { + Path directory = temporary.newFolder(directoryName).toPath(); + Path skill = Files.createDirectories(directory.resolve("skills/" + name)); + Files.writeString( + skill.resolve("SKILL.md"), + "---\nname: " + name + "\ndescription: Directory skill\n---\nDirectory instructions.", + UTF_8); + return directory; + } + + private Path skillJar(String filename, String prefix, String name) throws IOException { + return skillJar(filename, prefix, name, "Instructions."); + } + + private Path skillJar(String filename, String prefix, String name, String instructions) + throws IOException { + Path path = temporary.newFile(filename).toPath(); + Map files = + ImmutableMap.of( + prefix + "skills/" + name + "/SKILL.md", + "---\nname: " + name + "\ndescription: A packaged skill\n---\n" + instructions, + prefix + "skills/" + name + "/references/nested/guide.txt", + "Reference text.", + prefix + "root-skill/SKILL.md", + "---\nname: root-skill\ndescription: At the classpath root\n---\nInstructions.", + "outside/hidden-skill/SKILL.md", + "---\nname: hidden-skill\ndescription: Not in the classpath root\n---\nHidden."); + try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(path))) { + for (Map.Entry file : files.entrySet()) { + output.putNextEntry(new JarEntry(file.getKey())); + output.write(file.getValue().getBytes(UTF_8)); + output.closeEntry(); + } + } + return path; + } + + private Path manifestJar(String filename, String classPath) throws IOException { + Path path = temporary.newFile(filename).toPath(); + Manifest manifest = new Manifest(); + manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); + manifest.getMainAttributes().putValue("Class-Path", classPath); + try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(path), manifest)) { + // Only the manifest is needed to expose the dependency through the class loader. + } + return path; + } + + private static URL jarRoot(Path jar, String prefix) throws IOException { + return URI.create("jar:" + jar.toUri() + "!/" + prefix).toURL(); + } + + @SuppressWarnings("removal") + public static final class RestrictedClassLoaderProbe { + public static void main(String[] args) throws Exception { + URL directory = Path.of(args[0]).toUri().toURL(); + URL jar = jarRoot(Path.of(args[1]), ""); + Path deniedDirectory = Path.of(args[2]); + Path deniedJar = Path.of(args[3]); + try (URLClassLoader loader = + new URLClassLoader( + new URL[] { + directory, + jar, + deniedDirectory.toUri().toURL(), + deniedJar.toUri().toURL(), + jarRoot(deniedJar, "") + }, + null)) { + System.setSecurityManager( + new SecurityManager() { + @Override + public void checkPermission(Permission permission) {} + + @Override + public void checkRead(String file) { + if (file.equals(deniedDirectory.toString()) || file.equals(deniedJar.toString())) { + throw new SecurityException("Reading this classpath root is not allowed"); + } + } + + @Override + public void checkCreateClassLoader() { + throw new SecurityException("Creating a class loader is not allowed"); + } + }); + try { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", loader); + assertThat(source.listFrontmatters().blockingGet().keySet()) + .containsExactly("shared-skill"); + assertThat(source.loadInstructions("shared-skill").blockingGet()) + .isEqualTo("Directory instructions."); + } finally { + System.setSecurityManager(null); + } + } + } + } + + public static final class SystemClassPathProbe { + public static void main(String[] args) throws Exception { + Path jar = Path.of(args[0]); + try (URLClassLoader child = + new URLClassLoader(new URL[] {jarRoot(jar, "")}, ClassLoader.getSystemClassLoader())) { + ClassPathSkillSource source = new ClassPathSkillSource("skills/", child); + String name = "system-classpath-skill"; + if (!source.listFrontmatters().blockingGet().containsKey(name) + || !source.loadInstructions(name).blockingGet().equals("Instructions.") + || !source + .listResources(name, "references") + .blockingGet() + .equals(ImmutableList.of("references/nested/guide.txt"))) { + throw new AssertionError("Unexpected system classpath skill result"); + } + System.out.println(name); + } + } + } }