Skip to content

Conversation

@nathaliellenaa
Copy link
Contributor

@nathaliellenaa nathaliellenaa commented Nov 5, 2025

Description

Add execute tool + scratch pad tests

Related Issues

Resolves #[Issue number to be closed when this PR is merged]

Check List

  • New functionality includes testing.
  • New functionality has been documented.
  • API changes companion pull request created.
  • Commits are signed per the DCO using --signoff.
  • Public documentation issue/PR created.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

Summary by CodeRabbit

  • Tests
    • Added tests covering permission-denied flows for tool execution and scratchpad operations.
    • Added integration tests verifying unauthorized access is rejected.
    • Added a large-payload integration test to validate scratchpad size limits and proper error responses.

✏️ Tip: You can customize this high-level summary in your review settings.

mingshl
mingshl previously approved these changes Nov 5, 2025
super.setUp();
}

public void testScratchpadSizeLimit() throws Exception {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for verifying the exception in UT.

@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval November 6, 2025 08:30 — with GitHub Actions Error
@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval November 6, 2025 08:30 — with GitHub Actions Failure
@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval November 6, 2025 08:30 — with GitHub Actions Error
@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval November 6, 2025 08:30 — with GitHub Actions Failure
@dhrubo-os
Copy link
Collaborator

 Could not determine the dependencies of task ':opensearch-ml-plugin:dependencyLicenses'.
> Failed to query the value of task ':opensearch-ml-plugin:dependencyLicenses' property 'dependencies'.
   > Could not resolve all dependencies for configuration ':opensearch-ml-plugin:runtimeClasspath'.
      > Could not resolve software.amazon.awssdk:kms:2.32.29.
        Required by:
            project :opensearch-ml-plugin > project :opensearch-ml-algorithms > software.amazon.awssdk:bom:2.32.29
            project :opensearch-ml-plugin > project :opensearch-ml-algorithms > org.opensearch:opensearch-remote-metadata-sdk-ddb-client:3.4.0.0-SNAPSHOT:20251106.022320-9
         > Conflict found for module 'software.amazon.awssdk:kms': between versions 2.32.29 and 2.26.3
      > Could not resolve software.amazon.awssdk:dynamodb:2.32.29.
        Required by:
            project :opensearch-ml-plugin > project :opensearch-ml-algorithms > software.amazon.awssdk:bom:2.32.29
            project :opensearch-ml-plugin > project :opensearch-ml-algorithms > software.amazon.awssdk:bom:2.32.29 > software.amazon.awssdk:dynamodb-enhanced:2.32.29
         > Conflict found for module 'software.amazon.awssdk:dynamodb': between versions 2.32.29 and 2.26.3
      > Could not resolve org.dafny:DafnyRuntime:4.9.0.
        Required by:
            project :opensearch-ml-plugin > project :opensearch-ml-algorithms > org.opensearch:opensearch-remote-metadata-sdk-ddb-client:3.4.0.0-SNAPSHOT:20251106.022320-9 > software.amazon.cryptography:aws-database-encryption-sdk-dynamodb:3.9.0
            project :opensearch-ml-plugin > project :opensearch-ml-algorithms > org.opensearch:opensearch-remote-metadata-sdk-ddb-client:3.4.0.0-SNAPSHOT:20251106.022320-9 > software.amazon.cryptography:aws-cryptographic-material-providers:1.11.0

Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.

Seems like we started having a dependency conflict issue.

@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval November 7, 2025 01:59 — with GitHub Actions Error
@ylwu-amzn ylwu-amzn had a problem deploying to ml-commons-cicd-env-require-approval November 14, 2025 19:40 — with GitHub Actions Failure
@nathaliellenaa
Copy link
Contributor Author

Failing tests are unrelated

RestBedRockInferenceIT > test_bedrock_multimodal_model_empty_imageInput FAILED
    java.lang.AssertionError: Failing test case name: without_step_size, inference result: {"error":{"root_cause":[{"type":"status_exception","reason":"Error from remote service: {\"message\":\"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

@mingshl
Copy link
Collaborator

mingshl commented Nov 18, 2025

@nathaliellenaa this test is constantly failing, can you try fix the test by downloading another imageurl?

we need the required CI passed to merge this.

RestMLRAGSearchProcessorIT > testBM25WithOpenAIWithConversationAndImage FAILED
    org.opensearch.client.ResponseException: method [POST], host [http://[::1]:44963], URI [/test/_search?size=5&search_pipeline=pipeline_test], status line [HTTP/1.1 400 Bad Request]
    {"error":{"root_cause":[{"type":"status_exception","reason":"Error from remote service: {\n  \"error\": {\n    \"message\": \"Error while downloading [https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg.\](https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg./)",\n    \"type\": \"invalid_request_error\",\n    \"param\": null,\n    \"code\": \"invalid_image_url\"\n  }\n}"}],"type":"status_exception","reason":"Error from remote service: {\n  \"error\": {\n    \"message\": \"Error while downloading [https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg.\](https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg./)",\n    \"type\": \"invalid_request_error\",\n    \"param\": null,\n    \"code\": \"invalid_image_url\"\n  }\n}"},"status":400}

@nathaliellenaa nathaliellenaa temporarily deployed to ml-commons-cicd-env-require-approval November 26, 2025 01:53 — with GitHub Actions Inactive
@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval November 26, 2025 01:53 — with GitHub Actions Failure
@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval November 26, 2025 01:53 — with GitHub Actions Error
@nathaliellenaa nathaliellenaa temporarily deployed to ml-commons-cicd-env-require-approval November 26, 2025 01:53 — with GitHub Actions Inactive
@nathaliellenaa nathaliellenaa mentioned this pull request Nov 26, 2025
5 tasks
@coderabbitai
Copy link

coderabbitai bot commented Dec 1, 2025

Walkthrough

Adds unit and integration tests covering SecurityException/permission-denied paths and a scratchpad size-limit rejection; no production code changes.

Changes

Cohort / File(s) Summary
Unit tests — tool execution security
ml-algorithms/src/test/java/org/opensearch/ml/engine/algorithms/tool/MLToolExecutorTest.java, ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/ReadFromScratchPadToolTests.java, ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/WriteToScratchPadToolTests.java
Added tests that simulate SecurityException or permission-denied failures and assert listener propagation/message content. One assertion removed from WriteToScratchPadToolTests (related to scratchpad notes validation).
Integration tests — permissions & size limit
plugin/src/test/java/org/opensearch/ml/tools/ListIndexToolIT.java, plugin/src/test/java/org/opensearch/ml/tools/ScratchPadToolIT.java
Added testListIndexWithNoPermissions() to verify forbidden responses for a no-permission user over HTTPS; added new ScratchPadToolIT with setUp() and testScratchpadSizeLimit() which posts ~100MB payload and asserts oversized-content error responses.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Focus review on test assertions and mocked behaviors for SecurityException propagation.
  • Verify the removed assertion in WriteToScratchPadToolTests is intentional.
  • Check integration test setup/teardown (user creation/cleanup, secure client) and large-payload construction in ScratchPadToolIT for test stability.

Suggested reviewers

  • dhrubo-os
  • mingshl
  • jngz-es
  • zane-neo
  • rbhavna
  • austintlee
  • HenryL27
  • Zhangxunmt
  • ylwu-amzn
  • sam-herman
  • xinyual
  • b4sjoo
  • pyek-bot

Poem

🐰 A tiny rabbit hops in testland bright,
I catch the perms that hide from light,
I nibble bytes that grow too wide,
I log the fails and hop aside,
Hooray for tests that keep things right!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ❓ Inconclusive The description lacks critical details about what functionality is being tested and why. It only repeats the title without explaining the changes, and the issue number placeholder remains unfilled. Provide a detailed description of what execute tool and scratch pad tests are being added, explain the scope of testing (unit and integration tests), and fill in the related issue number.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: adding new test cases for execute tool and scratch pad functionality across multiple test files.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval December 1, 2025 23:32 — with GitHub Actions Failure
@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval December 1, 2025 23:32 — with GitHub Actions Error
@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval December 1, 2025 23:32 — with GitHub Actions Failure
@nathaliellenaa nathaliellenaa had a problem deploying to ml-commons-cicd-env-require-approval December 1, 2025 23:32 — with GitHub Actions Error
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/WriteToScratchPadToolTests.java (2)

215-225: Consider asserting scratchpad mutation in this JSON-array conversion test

testRun_StringConversion_WithJsonArray now only checks the response string; asserting the updated SCRATCHPAD_NOTES_KEY here as well would better match the test name and keep this path fully covered (even though other tests cover similar mutations).


227-242: SecurityException test does not exercise WriteToScratchPadTool behavior

testRun_SecurityException directly calls listener.onFailure(securityException) and then verifies the listener, without invoking tool.run(...). That means the test is not validating how WriteToScratchPadTool itself behaves when a SecurityException occurs; it only checks that Mockito and the listener work as expected.

If the goal is tool-level behavior, consider:

  • Driving tool.run(...) and arranging dependencies so a SecurityException flows through the listener, or
  • Dropping this test and relying on higher‑level tests like MLToolExecutorTest.test_ToolExecutionFailsWithoutProperPermission, which already validate the permission error path end‑to‑end.
ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/ReadFromScratchPadToolTests.java (1)

220-233: SecurityException test does not exercise ReadFromScratchPadTool behavior

testRun_SecurityException manually triggers listener.onFailure(securityException) and verifies the captured exception, but never calls tool.run(...). This doesn’t assert anything about how ReadFromScratchPadTool handles permission failures; it just checks the listener wiring.

To make this more meaningful, consider:

  • Refactoring to drive tool.run(...) and simulate a SecurityException from its internal operations, or
  • Removing this test and relying on higher‑level permission tests (e.g., MLToolExecutorTest and the ITs) for SecurityException coverage.
plugin/src/test/java/org/opensearch/ml/tools/ListIndexToolIT.java (1)

44-80: Robust permission IT; only minor polish possible

This test cleanly verifies that a no‑permission user gets a permission/forbidden/unauthorized error over HTTPS, and it correctly cleans up the client and user. The string‑contains checks are flexible enough to tolerate backend wording differences.

If you want to tighten things later, optional tweaks would be:

  • Use Collections.emptyList() instead of new ArrayList<>() for the no‑roles argument.
  • Use try‑with‑resources for RestClient instead of an explicit try/finally.
plugin/src/test/java/org/opensearch/ml/tools/ScratchPadToolIT.java (1)

1-39: Effective size‑limit IT; consider tuning payload size / construction

This IT correctly exercises the WriteToScratchPad tool via the REST endpoint with an oversized payload and asserts that some form of content‑length / 413‑style error is returned, without over‑fitting to a specific exception type or message.

Two optional refinements you might consider:

  • Use a payload just over the configured http.max_content_length (rather than a full 100 MB) to reduce memory pressure in CI while still triggering the same failure.
  • If you ever change largeContent to something more complex than "A", switch to building the JSON body via a helper or escaping utility instead of raw String.format to avoid quoting/escaping pitfalls.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2854ad2 and 6ed156d.

📒 Files selected for processing (5)
  • ml-algorithms/src/test/java/org/opensearch/ml/engine/algorithms/tool/MLToolExecutorTest.java (1 hunks)
  • ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/ReadFromScratchPadToolTests.java (1 hunks)
  • ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/WriteToScratchPadToolTests.java (1 hunks)
  • plugin/src/test/java/org/opensearch/ml/tools/ListIndexToolIT.java (2 hunks)
  • plugin/src/test/java/org/opensearch/ml/tools/ScratchPadToolIT.java (1 hunks)
🔇 Additional comments (1)
ml-algorithms/src/test/java/org/opensearch/ml/engine/algorithms/tool/MLToolExecutorTest.java (1)

206-226: Good coverage of permission‑denied tool execution path

test_ToolExecutionFailsWithoutProperPermission correctly simulates a SecurityException from the tool and verifies it is propagated unchanged to actionListener, including the message fragment. This nicely complements test_ToolExecutionFailed and the scratchpad tests.

Signed-off-by: Nathalie Jonathan <nathhjo@amazon.com>
Signed-off-by: Nathalie Jonathan <nathhjo@amazon.com>
Signed-off-by: Nathalie Jonathan <nathhjo@amazon.com>
Signed-off-by: Nathalie Jonathan <nathhjo@amazon.com>
Signed-off-by: Nathalie Jonathan <nathhjo@amazon.com>
@nathaliellenaa nathaliellenaa requested a deployment to ml-commons-cicd-env-require-approval December 15, 2025 23:10 — with GitHub Actions Waiting
@nathaliellenaa nathaliellenaa requested a deployment to ml-commons-cicd-env-require-approval December 15, 2025 23:10 — with GitHub Actions Waiting
@nathaliellenaa nathaliellenaa requested a deployment to ml-commons-cicd-env-require-approval December 15, 2025 23:10 — with GitHub Actions Waiting
@nathaliellenaa nathaliellenaa requested a deployment to ml-commons-cicd-env-require-approval December 15, 2025 23:10 — with GitHub Actions Waiting
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
plugin/src/test/java/org/opensearch/ml/tools/ListIndexToolIT.java (1)

56-61: Consider reducing socket timeout for faster test execution.

Permission checks typically fail quickly. The 60-second socket timeout could unnecessarily delay test failures if there are connectivity issues.

         final RestClient noPermissionClient = new SecureRestClientBuilder(
             getClusterHosts().toArray(new HttpHost[0]),
             isHttps(),
             noPermissionUser,
             password
-        ).setSocketTimeout(60000).build();
+        ).setSocketTimeout(10000).build();
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ed156d and 3bdb967.

📒 Files selected for processing (5)
  • ml-algorithms/src/test/java/org/opensearch/ml/engine/algorithms/tool/MLToolExecutorTest.java (1 hunks)
  • ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/ReadFromScratchPadToolTests.java (1 hunks)
  • ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/WriteToScratchPadToolTests.java (1 hunks)
  • plugin/src/test/java/org/opensearch/ml/tools/ListIndexToolIT.java (2 hunks)
  • plugin/src/test/java/org/opensearch/ml/tools/ScratchPadToolIT.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/WriteToScratchPadToolTests.java
  • plugin/src/test/java/org/opensearch/ml/tools/ScratchPadToolIT.java
  • ml-algorithms/src/test/java/org/opensearch/ml/engine/algorithms/tool/MLToolExecutorTest.java
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: spotless
🔇 Additional comments (1)
plugin/src/test/java/org/opensearch/ml/tools/ListIndexToolIT.java (1)

17-17: LGTM!

The added imports are appropriate for the new permission test and are all utilized correctly.

Also applies to: 20-23

Comment on lines +220 to +233
@Test
public void testRun_SecurityException() {
Map<String, String> parameters = new HashMap<>();
parameters.put(ReadFromScratchPadTool.SCRATCHPAD_NOTES_KEY, "[\"confidential data\"]");

SecurityException securityException = new SecurityException("no permissions for [indices:data/read/get] and User [name=test_user]");
listener.onFailure(securityException);

ArgumentCaptor<Exception> exceptionCaptor = ArgumentCaptor.forClass(Exception.class);
verify(listener).onFailure(exceptionCaptor.capture());
Exception exception = exceptionCaptor.getValue();
assertTrue(exception instanceof SecurityException);
assertTrue(exception.getMessage().contains("no permissions"));
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Test doesn't invoke production code.

This test directly calls listener.onFailure(securityException) without ever invoking tool.run(parameters, listener). It only verifies that Mockito captured the manually triggered failure, providing zero coverage of how ReadFromScratchPadTool actually handles a SecurityException.

To properly test SecurityException handling, you need to either:

  1. Mock an internal dependency that tool.run() calls to throw SecurityException, or
  2. Move this to an integration test where permissions are enforced

Apply this diff if you want to keep it as a unit test with mocked internals (note: this assumes the tool calls some external service that could throw SecurityException - adjust based on actual implementation):

 @Test
 public void testRun_SecurityException() {
     Map<String, String> parameters = new HashMap<>();
     parameters.put(ReadFromScratchPadTool.SCRATCHPAD_NOTES_KEY, "[\"confidential data\"]");
-
-    SecurityException securityException = new SecurityException("no permissions for [indices:data/read/get] and User [name=test_user]");
-    listener.onFailure(securityException);
-
+    
+    // You need to mock whatever dependency throws SecurityException during tool.run()
+    // For example, if the tool reads from a secure store:
+    // when(mockSecureStore.read(any())).thenThrow(new SecurityException("no permissions..."));
+    
+    tool.run(parameters, listener);
+    
     ArgumentCaptor<Exception> exceptionCaptor = ArgumentCaptor.forClass(Exception.class);
     verify(listener).onFailure(exceptionCaptor.capture());
     Exception exception = exceptionCaptor.getValue();
     assertTrue(exception instanceof SecurityException);
     assertTrue(exception.getMessage().contains("no permissions"));
 }

Alternatively, if ReadFromScratchPadTool.run() doesn't actually interact with permission-protected resources, this test might be testing the wrong layer and should be removed or moved to an integration test.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In
ml-algorithms/src/test/java/org/opensearch/ml/engine/tools/ReadFromScratchPadToolTests.java
around lines 220 to 233, the test currently calls listener.onFailure(...)
directly instead of exercising the production path; update the test to invoke
tool.run(parameters, listener) and cause a SecurityException from the tool's
dependency so the tool's failure handling is executed: identify the internal
dependency the tool calls (e.g., a client/service used to read the scratchpad),
mock that dependency to throw new SecurityException("no permissions...") when
invoked, inject the mock into the tool under test, call tool.run(parameters,
listener), then verify listener.onFailure(...) was called with a
SecurityException and assert its message; if the tool has no mockable
dependency, remove or convert this unit test into an integration test that
exercises real permission checks instead.

Comment on lines +44 to +80
public void testListIndexWithNoPermissions() throws Exception {
if (!isHttps()) {
log.info("Skipping permission test as security is not enabled");
return;
}

String noPermissionUser = "no_permission_user";
String password = "TestPassword123!";

try {
createUser(noPermissionUser, password, new ArrayList<>());

final RestClient noPermissionClient = new SecureRestClientBuilder(
getClusterHosts().toArray(new HttpHost[0]),
isHttps(),
noPermissionUser,
password
).setSocketTimeout(60000).build();

try {
ResponseException exception = expectThrows(ResponseException.class, () -> {
TestHelper
.makeRequest(noPermissionClient, "POST", "/_plugins/_ml/agents/" + agentId + "/_execute", null, question, null);
});

String errorMessage = exception.getMessage().toLowerCase();
assertTrue(
"Expected permission error, got: " + errorMessage,
errorMessage.contains("no permissions") || errorMessage.contains("forbidden") || errorMessage.contains("unauthorized")
);
} finally {
noPermissionClient.close();
}
} finally {
deleteUser(noPermissionUser);
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Missing @test annotation - test won't execute.

The test method testListIndexWithNoPermissions lacks the @Test annotation, so it will be silently skipped by the test runner.

Apply this diff:

+@Test
 public void testListIndexWithNoPermissions() throws Exception {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void testListIndexWithNoPermissions() throws Exception {
if (!isHttps()) {
log.info("Skipping permission test as security is not enabled");
return;
}
String noPermissionUser = "no_permission_user";
String password = "TestPassword123!";
try {
createUser(noPermissionUser, password, new ArrayList<>());
final RestClient noPermissionClient = new SecureRestClientBuilder(
getClusterHosts().toArray(new HttpHost[0]),
isHttps(),
noPermissionUser,
password
).setSocketTimeout(60000).build();
try {
ResponseException exception = expectThrows(ResponseException.class, () -> {
TestHelper
.makeRequest(noPermissionClient, "POST", "/_plugins/_ml/agents/" + agentId + "/_execute", null, question, null);
});
String errorMessage = exception.getMessage().toLowerCase();
assertTrue(
"Expected permission error, got: " + errorMessage,
errorMessage.contains("no permissions") || errorMessage.contains("forbidden") || errorMessage.contains("unauthorized")
);
} finally {
noPermissionClient.close();
}
} finally {
deleteUser(noPermissionUser);
}
}
@Test
public void testListIndexWithNoPermissions() throws Exception {
if (!isHttps()) {
log.info("Skipping permission test as security is not enabled");
return;
}
String noPermissionUser = "no_permission_user";
String password = "TestPassword123!";
try {
createUser(noPermissionUser, password, new ArrayList<>());
final RestClient noPermissionClient = new SecureRestClientBuilder(
getClusterHosts().toArray(new HttpHost[0]),
isHttps(),
noPermissionUser,
password
).setSocketTimeout(60000).build();
try {
ResponseException exception = expectThrows(ResponseException.class, () -> {
TestHelper
.makeRequest(noPermissionClient, "POST", "/_plugins/_ml/agents/" + agentId + "/_execute", null, question, null);
});
String errorMessage = exception.getMessage().toLowerCase();
assertTrue(
"Expected permission error, got: " + errorMessage,
errorMessage.contains("no permissions") || errorMessage.contains("forbidden") || errorMessage.contains("unauthorized")
);
} finally {
noPermissionClient.close();
}
} finally {
deleteUser(noPermissionUser);
}
}
🤖 Prompt for AI Agents
plugin/src/test/java/org/opensearch/ml/tools/ListIndexToolIT.java around lines
44 to 80: the test method testListIndexWithNoPermissions is missing the @Test
annotation so it won’t be executed; add the appropriate @Test annotation above
the method and ensure the corresponding import (e.g., org.junit.Test or
org.junit.jupiter.api.Test matching the test framework used in this module) is
present at the top of the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants