- 
                Notifications
    You must be signed in to change notification settings 
- Fork 25.6k
[Entitlements] Add test entitlement bootstrap and initialization classes #127814
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Closed
      
      
            ldematte
  wants to merge
  14
  commits into
  elastic:main
from
ldematte:entitlements/test-entitlements-bootstrap-2
  
      
      
   
      
    
  
     Closed
                    Changes from 8 commits
      Commits
    
    
            Show all changes
          
          
            14 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      24199aa
              
                Initialization class as argument to EntitlementAgent
              
              
                ldematte 0289a2a
              
                visibility changes
              
              
                ldematte e166e3d
              
                WIP: test entitlement bootstrap and initialization classes
              
              
                ldematte 36479fc
              
                Simplify
              
              
                ldematte 53336dd
              
                Moving packages to reduce visibility
              
              
                ldematte c955eed
              
                Merge remote-tracking branch 'upstream/main' into entitlements/test-e…
              
              
                ldematte 24d9709
              
                adjust visibility
              
              
                ldematte fc40a30
              
                add plugins descriptor + policy parsing
              
              
                ldematte 714fbda
              
                Merge remote-tracking branch 'upstream/main' into entitlements/test-e…
              
              
                ldematte 9b1e178
              
                PR comments
              
              
                ldematte e0eee89
              
                Merge remote-tracking branch 'upstream/main' into entitlements/test-e…
              
              
                ldematte e4221b0
              
                Merge remote-tracking branch 'upstream/main' into entitlements/test-e…
              
              
                ldematte 2eb56fb
              
                update visibility, uncomment TestBuildInfoParser usage
              
              
                ldematte d47a5ed
              
                [CI] Auto commit changes from spotless
              
              
                 File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
          
            49 changes: 49 additions & 0 deletions
          
          49 
        
  ...ework/src/main/java/org/elasticsearch/entitlement/bootstrap/TestEntitlementBootstrap.java
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the "Elastic License | ||
| * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side | ||
| * Public License v 1"; you may not use this file except in compliance with, at | ||
| * your election, the "Elastic License 2.0", the "GNU Affero General Public | ||
| * License v3.0 only", or the "Server Side Public License, v 1". | ||
| */ | ||
|  | ||
| package org.elasticsearch.entitlement.bootstrap; | ||
|  | ||
| import com.sun.tools.attach.AgentInitializationException; | ||
| import com.sun.tools.attach.AgentLoadException; | ||
| import com.sun.tools.attach.AttachNotSupportedException; | ||
| import com.sun.tools.attach.VirtualMachine; | ||
|  | ||
| import org.elasticsearch.core.SuppressForbidden; | ||
| import org.elasticsearch.entitlement.initialization.TestEntitlementInitialization; | ||
| import org.elasticsearch.logging.LogManager; | ||
| import org.elasticsearch.logging.Logger; | ||
|  | ||
| import java.io.IOException; | ||
|  | ||
| class TestEntitlementBootstrap { | ||
|  | ||
| private static final Logger logger = LogManager.getLogger(TestEntitlementBootstrap.class); | ||
|  | ||
| /** | ||
| * Activates entitlement checking in tests. | ||
| */ | ||
| public static void bootstrap() { | ||
| logger.debug("Loading entitlement agent"); | ||
| loadAgent(EntitlementBootstrap.findAgentJar()); | ||
| } | ||
|  | ||
| @SuppressForbidden(reason = "The VirtualMachine API is the only way to attach a java agent dynamically") | ||
| private static void loadAgent(String agentPath) { | ||
| try { | ||
| VirtualMachine vm = VirtualMachine.attach(Long.toString(ProcessHandle.current().pid())); | ||
| try { | ||
| vm.loadAgent(agentPath, TestEntitlementInitialization.class.getName()); | ||
| } finally { | ||
| vm.detach(); | ||
| } | ||
| } catch (AttachNotSupportedException | IOException | AgentLoadException | AgentInitializationException e) { | ||
| throw new IllegalStateException("Unable to attach entitlement agent", e); | ||
| } | ||
| } | ||
| } | ||
        
          
          
            149 changes: 149 additions & 0 deletions
          
          149 
        
  ...main/java/org/elasticsearch/entitlement/initialization/TestEntitlementInitialization.java
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the "Elastic License | ||
| * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side | ||
| * Public License v 1"; you may not use this file except in compliance with, at | ||
| * your election, the "Elastic License 2.0", the "GNU Affero General Public | ||
| * License v3.0 only", or the "Server Side Public License, v 1". | ||
| */ | ||
|  | ||
| package org.elasticsearch.entitlement.initialization; | ||
|  | ||
| import org.elasticsearch.core.Strings; | ||
| import org.elasticsearch.core.SuppressForbidden; | ||
| import org.elasticsearch.entitlement.bridge.EntitlementChecker; | ||
| import org.elasticsearch.entitlement.runtime.api.ElasticsearchEntitlementChecker; | ||
| import org.elasticsearch.entitlement.runtime.policy.PathLookup; | ||
| import org.elasticsearch.entitlement.runtime.policy.Policy; | ||
| import org.elasticsearch.entitlement.runtime.policy.PolicyManager; | ||
| import org.elasticsearch.entitlement.runtime.policy.PolicyParser; | ||
| import org.elasticsearch.plugins.PluginDescriptor; | ||
|  | ||
| import java.io.IOException; | ||
| import java.io.InputStream; | ||
| import java.lang.instrument.Instrumentation; | ||
| import java.lang.reflect.Constructor; | ||
| import java.lang.reflect.InvocationTargetException; | ||
| import java.net.URL; | ||
| import java.util.ArrayList; | ||
| import java.util.HashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
| import java.util.function.Function; | ||
|  | ||
| /** | ||
| * Test-only version of {@code EntitlementInitialization} | ||
| */ | ||
| public class TestEntitlementInitialization { | ||
|  | ||
| private static ElasticsearchEntitlementChecker manager; | ||
|  | ||
| // Note: referenced by bridge reflectively | ||
| public static EntitlementChecker checker() { | ||
| return manager; | ||
| } | ||
|  | ||
| public static void initialize(Instrumentation inst) throws Exception { | ||
| manager = initChecker(); | ||
| DynamicInstrumentation.initialize( | ||
|         
                  ldematte marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| inst, | ||
| EntitlementCheckerUtils.getVersionSpecificCheckerClass(EntitlementChecker.class, Runtime.version().feature()), | ||
| false | ||
| ); | ||
| } | ||
|  | ||
| private record TestPluginData(String pluginName, boolean isModular, boolean isExternalPlugin) {} | ||
|  | ||
| private static Map<String, Policy> parsePluginsPolicies(List<TestPluginData> pluginsData) { | ||
| Map<String, Policy> policies = new HashMap<>(); | ||
| for (var pluginData : pluginsData) { | ||
| String pluginName = pluginData.pluginName(); | ||
| var resourceName = Strings.format("META-INF/es-plugins/%s/entitlement-policy.yaml", pluginName); | ||
|  | ||
| var resource = TestEntitlementInitialization.class.getClassLoader().getResource(resourceName); | ||
| if (resource != null) { | ||
| try (var inputStream = getStream(resource)) { | ||
| policies.put(pluginName, new PolicyParser(inputStream, pluginName, pluginData.isExternalPlugin()).parsePolicy()); | ||
| } catch (IOException e) { | ||
| throw new IllegalArgumentException(Strings.format("Cannot read policy for plugin [%s]", pluginName), e); | ||
| } | ||
| } | ||
| } | ||
| return policies; | ||
| } | ||
|  | ||
| private static List<PluginDescriptor> parsePluginsDescriptors(List<String> pluginNames) { | ||
| List<PluginDescriptor> descriptors = new ArrayList<>(); | ||
| for (var pluginName : pluginNames) { | ||
| var resourceName = Strings.format("META-INF/es-plugins/%s/plugin-descriptor.properties", pluginName); | ||
| var resource = TestEntitlementInitialization.class.getClassLoader().getResource(resourceName); | ||
| if (resource != null) { | ||
| try (var inputStream = getStream(resource)) { | ||
| descriptors.add(PluginDescriptor.readInternalDescriptor(inputStream)); | ||
| } catch (IOException e) { | ||
| throw new IllegalArgumentException(Strings.format("Cannot read descriptor for plugin [%s]", pluginName), e); | ||
| } | ||
| } | ||
| } | ||
| return descriptors; | ||
| } | ||
|  | ||
| @SuppressForbidden(reason = "URLs from class loader") | ||
| private static InputStream getStream(URL resource) throws IOException { | ||
| return resource.openStream(); | ||
| } | ||
|  | ||
| private static PolicyManager createPolicyManager() { | ||
|  | ||
| // TODO: uncomment after merging https://github.com/elastic/elasticsearch/pull/127719 | ||
| // var pluginsTestBuildInfo = TestBuildInfoParser.parseAllPluginTestBuildInfo(); | ||
| // var serverTestBuildInfo = TestBuildInfoParser.parseServerTestBuildInfo(); | ||
| Function<Class<?>, PolicyManager.PolicyScope> scopeResolver = null; // TestScopeResolver.createScopeResolver(serverTestBuildInfo, | ||
| // pluginsTestBuildInfo); | ||
| List<String> pluginNames = List.of(); // = pluginsTestBuildInfo.stream().map(TestBuildInfo::componentName).toList(); | ||
|  | ||
| var pluginDescriptors = parsePluginsDescriptors(pluginNames); | ||
| var pluginsData = pluginDescriptors.stream() | ||
| .map(descriptor -> new TestPluginData(descriptor.getName(), descriptor.isModular(), false)) | ||
| .toList(); | ||
| Map<String, Policy> pluginPolicies = parsePluginsPolicies(pluginsData); | ||
|  | ||
| // TODO: create here the test pathLookup | ||
| PathLookup pathLookup = null; | ||
|  | ||
| FilesEntitlementsValidation.validate(pluginPolicies, pathLookup); | ||
|  | ||
| return new PolicyManager( | ||
| HardcodedEntitlements.serverPolicy(null, null), | ||
| HardcodedEntitlements.agentEntitlements(), | ||
| pluginPolicies, | ||
| scopeResolver, | ||
| Map.of(), | ||
| null, // TODO: this will need to change -- encapsulate it when we extract isTriviallyAllowed | ||
| pathLookup, | ||
| Set.of() | ||
| ); | ||
| } | ||
|  | ||
| private static ElasticsearchEntitlementChecker initChecker() { | ||
|         
                  ldematte marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| final PolicyManager policyManager = createPolicyManager(); | ||
|  | ||
| final Class<?> clazz = EntitlementCheckerUtils.getVersionSpecificCheckerClass( | ||
| ElasticsearchEntitlementChecker.class, | ||
| Runtime.version().feature() | ||
| ); | ||
|  | ||
| Constructor<?> constructor; | ||
| try { | ||
| constructor = clazz.getConstructor(PolicyManager.class); | ||
| } catch (NoSuchMethodException e) { | ||
| throw new AssertionError("entitlement impl is missing no arg constructor", e); | ||
| } | ||
| try { | ||
| return (ElasticsearchEntitlementChecker) constructor.newInstance(policyManager); | ||
| } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { | ||
| throw new AssertionError(e); | ||
| } | ||
| } | ||
| } | ||
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.