Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,31 @@ License: ISC https://github.com/d3/d3/blob/main/LICENSE
This product includes the highlight.js Javascript library created by Ivan Sagalaev
Copyright (c) 2006, Ivan Sagalaev, https://github.com/isagalaev/highlight.js

This product includes the Scalar API Reference JavaScript library.
Copyright (c) 2023-present Scalar, https://github.com/scalar/scalar

MIT License

Copyright (c) 2023-present Scalar

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

This product includes the Chosen Javascript library created by Patrick Filler
Copyright (c) 2011-2014 by Harvest, https://github.com/harvesthq/chosen

Expand Down
7 changes: 7 additions & 0 deletions changelog/unreleased/PR-5201-api-explorer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
title: Add an API Explorer to the Solr Admin UI
type: added
authors:
- name: Eric Pugh
links:
- name: PR#5201
url: https://github.com/apache/solr/pull/5201
2 changes: 2 additions & 0 deletions dev-docs/apis.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Many libraries implement the JAX-RS spec: Solr currently uses the implementation
These v2 API definitions consist of two parts: a JAX-RS annotated interface in the `api` module "defining" the API, and a class in `core` "implementing" the interface.
Separating the API "definition" and "implementation" in this way allows us to only define each API in a single place, and use code generators to produce other API-related bits such as SolrJ code and ref-guide documentation.

One of those other bits is an OpenAPI spec - see link:local-api-explorer.adoc[local-api-explorer.adoc] for how to browse it with the API Explorer against a running local Solr.

=== Writing JAX-RS APIs

Writing a new v2 API may appear daunting, but additions in reality are actually pretty simple:
Expand Down
29 changes: 29 additions & 0 deletions dev-docs/local-api-explorer.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
= Browsing the V2 API with the API Explorer

Solr's v2 (JAX-RS) API is described by an OpenAPI spec generated at build time
from the annotated interfaces in `solr/api/src/java/.../client/api/endpoint`.
The API Explorer is bundled in the Admin UI and renders the generated spec using Scalar.
It's loaded in an iframe from `solr/webapp/web/libs/scalar/index.html` rather than mounted
directly into the Angular app: Scalar manages its own URL hash for deep-linking to operations,
which conflicts with AngularJS's `ngRoute` (both rewrite `window.location.hash`), causing an
infinite digest/navigation loop. A dedicated document/window avoids the conflict entirely.

== Usage

Build and start a local Solr with `./gradlew dev` and `bin/solr start -c`.
Open the *API Explorer* item in the Admin UI's left nav to browse endpoints and send requests.
The page and its assets are served locally; API requests go directly to the same Solr origin.
Executing a request can change the running instance, just as calling its API directly can.

Rebuild the webapp after changing API annotations to refresh the explorer's spec.

== Maintaining Scalar

`solr/webapp/scalar` downloads the `@scalar/api-reference` npm package at build time and
copies its `dist/browser/standalone.js` into the webapp's war, so the bundle is never
checked into source control. Its version is recorded as `scalar-api-reference` in
`gradle/libs.versions.toml`; bump that version to upgrade, and review the new version's
license and bundled dependencies. The MIT license text is recorded in the root `NOTICE.txt`.
The initializer lives in `solr/webapp/web/libs/scalar/scalar-init.js` as a
separate script so it also works with a policy that disallows inline scripts.
Default CDN fonts, the request proxy, AI chat, hosted-client links, developer tools, and telemetry are disabled.
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ perfmark = "0.27.0"
picocli = "4.7.6"
prometheus-metrics = "1.8.0"
quicktheories = "0.26"
# @keep Scalar API Reference version used by the webapp
scalar-api-reference = "1.46.4"
selenium = "4.47.0"
semver4j = "6.0.0"
slf4j = "2.0.20"
Expand Down
1 change: 1 addition & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ gradle.ext.withJsClient = disableJsClientValue == null || disableJsClientValue !
if (gradle.ext.withJsClient) {
include(":solr:webapp:js-client")
}
include(":solr:webapp:scalar")

// Configures development for joint Lucene/ Solr composite build.
apply from: file('gradle/lucene-dev/lucene-dev-repo-composite.gradle')
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.info.License;
import io.swagger.v3.oas.annotations.servers.Server;

@OpenAPIDefinition(
info =
@Info(
title = "v2 API",
description = "OpenAPI spec for Solr's v2 API endpoints",
license = @License(name = "ASL 2.0"),
version = SolrVersion.LATEST_STRING))
version = SolrVersion.LATEST_STRING),
// A relative URL keeps API-explorer tooling (e.g. Swagger UI) same-origin with
// whichever node ends up serving it, so "try it out" calls need no CORS setup.
servers = @Server(url = "/api", description = "This Solr node"))
public class ApiMetadata {}
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) thro
HttpHeaders.CONTENT_SECURITY_POLICY,
"default-src 'none'; base-uri 'none'; connect-src "
+ connectSrc
+ "; form-action 'self'; font-src 'self'; frame-ancestors 'none'; img-src 'self' data:; media-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; worker-src 'self';");
// frame-src: the Admin UI's API Explorer loads a same-origin page in an
// iframe (Scalar manages its own URL hash for deep-linking, which conflicts
// with AngularJS's ngRoute if mounted directly into the app instead).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[ques] is this comment suited here? or should be in some dev docs?

if i am right, we are adding frame-src 'self'; entry here. there were many entries here already, so just adding for 1 we should avoid.

+ "; form-action 'self'; font-src 'self'; frame-ancestors 'none'; frame-src 'self'; img-src 'self' data:; media-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; worker-src 'self';");

// We have to close this to flush OutputStreamWriter buffer
try (Writer out =
Expand Down
16 changes: 16 additions & 0 deletions solr/server/etc/jetty.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,22 @@
</New>
</Arg>
</Call>
<!-- The Admin UI's API Explorer loads this one page in an iframe (Scalar manages its
own URL hash for deep-linking, which conflicts with ngRoute if mounted directly);
this narrower rule runs after the blanket rule above and overrides frame-ancestors
for just this path, so same-origin framing isn't blocked. -->
<Call name="addRule">
<Arg>
<New class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
<Set name="pattern">/solr/libs/scalar/index.html</Set>
<Set name="headerName">Content-Security-Policy</Set>
<Set name="headerValue">default-src 'none'; base-uri 'none'; connect-src 'self'; form-action 'self'; font-src 'self'; frame-ancestors 'self'; img-src 'self' data:; media-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; worker-src 'self';</Set>
</New>
</Arg>
</Call>
<!-- Note: /solr/index.html (and /solr/) is served by LoadAdminUiServlet (see web.xml),
which sets its own Content-Security-Policy that overrides anything set here - its
frame-src 'self' addition (needed by the API Explorer iframe above) lives there. -->
<Call name="addRule">
<Arg>
<New class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ The path to the Solr Admin UI given above is `\http://hostname:port/solr`, which
A convenience redirect is also supported, so simply accessing the Admin UI at `\http://hostname:port/` will also redirect to `\http://hostname:port/solr/#/`.
====

=== API Explorer

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should we be refreshing the base image on this adoc as well to keep the docs consistent with latest state?

image::solr-admin-ui/dashboard.png[image,height=400] ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

we should...


The *API Explorer* item in the Admin UI's left-hand navigation opens interactive documentation for Solr's v2 API.
It renders the OpenAPI specification bundled with Solr and lets you browse endpoints and send requests to the running instance.
Requests use the instance's authentication and authorization rules and can modify its data or configuration.
Comment on lines +54 to +56

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I see other sections also have a screenshot of their UI, should we also keep home page screenshot of the api explorer in this section.

something similar to this should work?

Screenshot 2026-11-13 at 12 58 44 AM


=== Login Screen

If authentication has been enabled, Solr will present a login screen to unauthenticated users before allowing them further access to the Admin UI.
Expand Down
31 changes: 31 additions & 0 deletions solr/webapp/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ configurations {
solrCore
generatedJSClientBundle
uiBundle
openapiSpec
scalarBundle
}

dependencies {
Expand All @@ -53,6 +55,10 @@ dependencies {
generatedJSClientBundle project(path: ":solr:webapp:js-client", configuration: "jsClientBundle")
}
uiBundle files(layout.buildDirectory.dir("generated/ui-resources")) { builtBy tasks.named('prepareUiResources') }
// Supplies the generated specification to the API Explorer.
openapiSpec project(path: ":solr:api", configuration: "openapiSpec")
// Supplies the Scalar browser bundle that renders the API Explorer.
scalarBundle project(path: ":solr:webapp:scalar", configuration: "scalarBundle")

// Browser-based tests of the AngularJS Admin UI (see src/test)
testImplementation project(':solr:core')
Expand Down Expand Up @@ -108,6 +114,20 @@ tasks.withType(Test).configureEach {
logger.warn('NOTE: :solr:webapp tests are disabled because -PdisableJsClient=true ' +
'excludes the js-client bundle the Admin UI tests need.')
}

// The API Explorer's iframe page loads the Scalar bundle and fetches the OpenAPI spec;
// both are build-time-generated files the war ships, and like the js-client bundle above,
// neither exists in the source tree these tests serve.
if (seleniumEnabled) {
def scalarBundle = configurations.scalarBundle
def openapiSpec = configurations.openapiSpec
inputs.files(scalarBundle).withPropertyName('scalarBundle')
inputs.files(openapiSpec).withPropertyName('openapiSpec')
doFirst {
systemProperty 'tests.ui.scalar.bundle', new File(scalarBundle.singleFile, 'standalone.js')
systemProperty 'tests.ui.scalar.spec', openapiSpec.singleFile
}
}
}

war {
Expand All @@ -121,6 +141,17 @@ war {
from(configurations.uiBundle, {
into "ui"
})

// Supplies the generated specification to the API Explorer.
from(configurations.openapiSpec, {
into "libs/scalar"
rename { "spec.json" }
})

// Supplies the Scalar browser bundle that renders the API Explorer.
from(configurations.scalarBundle, {
into "libs/scalar"
})
}

// Expose 'war' archive as an artifact so that it can be packaged in the distribution.
Expand Down
2 changes: 1 addition & 1 deletion solr/webapp/gradle.lockfile
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,4 @@ org.slf4j:jul-to-slf4j:2.0.20=serverLib
org.slf4j:slf4j-api:2.0.20=jarValidation,serverLib,solrCore,testCompileClasspath,testRuntimeClasspath
org.testcontainers:testcontainers:2.0.5=jarValidation,testRuntimeClasspath
org.xerial.snappy:snappy-java:1.1.10.8=jarValidation,solrCore,testRuntimeClasspath
empty=compileClasspath,generatedJSClientBundle,generatedUIBundle,missingdoclet,providedCompile,providedRuntime,runtimeClasspath,uiBundle,war
empty=compileClasspath,generatedJSClientBundle,generatedUIBundle,missingdoclet,openapiSpec,providedCompile,providedRuntime,runtimeClasspath,uiBundle,war
59 changes: 59 additions & 0 deletions solr/webapp/scalar/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import com.github.gradle.node.npm.task.NpmTask

// Downloads the pre-built @scalar/api-reference browser bundle via npm, for :solr:webapp to
// include in the war. Keeps the large generated bundle out of source control, unlike a
// hand-vendored copy.

plugins {
id("base")
alias(libs.plugins.nodegradle.node)
}

description = "Downloads the Scalar API Reference browser bundle for the Admin UI's API Explorer"

val scalarBundleDir = layout.buildDirectory.dir("scalarBundle").get().asFile
Comment thread
epugh marked this conversation as resolved.
Resolved

val scalarBundle = configurations.create("scalarBundle") {
isCanBeConsumed = true
isCanBeResolved = false
}

val downloadScalarApiReference = tasks.register<NpmTask>("downloadScalarApiReference") {
args.set(listOf("install", "@scalar/api-reference@${libs.versions.scalar.api.reference.get()}"))

inputs.property("scalar-api-reference version", libs.versions.scalar.api.reference.get())
outputs.dir(project.extra["nodeProjectDir"].toString() + "/node_modules/@scalar/api-reference")
}

val copyScalarBundle = tasks.register<Sync>("copyScalarBundle") {
dependsOn(downloadScalarApiReference)

from(project.extra["nodeProjectDir"].toString() + "/node_modules/@scalar/api-reference/dist/browser") {
include("standalone.js")
}

into(scalarBundleDir)
}

artifacts {
add("scalarBundle", scalarBundleDir) {
builtBy(copyScalarBundle)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;

/**
* Tests the Admin UI with BasicAuth enabled: the login screen flow and the Security screen,
* including adding a user through the UI dialog.
*/
/** Tests login, security management, and API Explorer requests with BasicAuth enabled. */
public class AdminUiSecurityAuthTest extends AdminUiTestBase {

private static final String USER = "solr";
Expand Down Expand Up @@ -130,6 +127,87 @@ public void testLoginAndSecurityScreen() throws Exception {
waitForPageContains(permission);
}

@Test
public void testApiExplorerUsesAdminCredentials() throws Exception {
ensureCloudCluster();
driver.get(baseUrl + "/index.html#/");
((JavascriptExecutor) driver).executeScript("sessionStorage.clear();");
openPage("", By.id("login"));
setText(By.id("username"), USER);
setText(By.id("password"), PASS);
click(By.xpath("//div[@id='login']//button[@type='submit']"));
waitFor(By.id("nodes-table"));

try {
driver.get(baseUrl + "/index.html#/~api-explorer");
driver.switchTo().frame(waitFor(By.cssSelector("#content #api-explorer iframe")));
By collectionsGroup =
By.xpath(
"//button[@aria-expanded and .//div[contains(@class,'group/button-label')"
+ " and normalize-space(.)='collections']]");
By listCollections =
By.xpath(
"//*[self::a or self::button][.//div[contains(@class,'group/button-label')"
+ " and contains(., 'List all collections in this Solr cluster')]]");
if ("false".equals(waitFor(collectionsGroup).getDomAttribute("aria-expanded"))) {
activateExplorerControl(collectionsGroup);
}
activateExplorerControl(listCollections);
waitForPageContains("List all collections in this Solr cluster");
// Observe the actual request and response without replacing the Solr endpoint.
// Store only whether the credential matches, never the credential itself.
((JavascriptExecutor) driver)
.executeScript(
"const original = window.fetch;"
+ " window.fetch = async function(input, init) {"
+ " const request = input instanceof Request ? input : new Request(input, init);"
+ " const response = await original.call(this, input, init);"
+ " if (new URL(request.url).pathname === '/api/collections'"
+ " && request.method === 'GET') {"
+ " let collections = false;"
+ " try { collections = Array.isArray((await response.clone().json()).collections); }"
+ " catch (ignored) {}"
+ " const auth = sessionStorage.getItem('auth.header');"
+ " window.explorerResult = {status: response.status, collections: collections,"
+ " authenticated: !!auth && request.headers.get('Authorization') === auth,"
+ " requestedWith: request.headers.get('X-Requested-With')};"
+ " } return response; };");
activateExplorerControl(
By.xpath(
"//button[contains(@class,'show-api-client-button') and @method='get'"
+ " and contains(., '(get /collections)')]"));
activateExplorerControl(
By.xpath(
"//div[contains(@class,'scalar-address-bar')]//button"
+ "[.//span[contains(., 'Send get request')]]"));
waitUntil(
"the explorer should receive the collections response",
() ->
Boolean.TRUE.equals(
((JavascriptExecutor) driver).executeScript("return !!window.explorerResult;")));
@SuppressWarnings("unchecked")
Map<String, Object> result =
(Map<String, Object>)
((JavascriptExecutor) driver).executeScript("return window.explorerResult;");
assertEquals(200L, result.get("status"));
assertEquals(Boolean.TRUE, result.get("collections"));
assertEquals(Boolean.TRUE, result.get("authenticated"));
assertEquals("XMLHttpRequest", result.get("requestedWith"));
waitForTextContains(By.cssSelector("body"), "200 OK");
driver.switchTo().defaultContent();
driver.get(baseUrl + "/index.html#/~cloud?view=nodes");
waitFor(By.id("nodes-table"));
} finally {
driver.switchTo().defaultContent();
((JavascriptExecutor) driver).executeScript("sessionStorage.clear();");
}
driver.get("about:blank");
}

private void activateExplorerControl(By locator) {
((JavascriptExecutor) driver).executeScript("arguments[0].click();", waitFor(locator));
}

/** Returns the authorization config as fetched with credentials. */
private NamedList<Object> authorizationApi() {
try {
Expand Down
Loading
Loading