diff --git a/ChangeLog.md b/ChangeLog.md index 7f9a870113..4e6e1ed1ed 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -16,6 +16,14 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> +**2026-11-20 Arturo Bernal (abernal AT apache DOT org)** + +* _3.0.2-git-2_ + +* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/search` is the first endpoint of a versioned REST API, described by the OpenAPI file `openapi.yaml` ([PR#589](https://github.com/apache/jspwiki/pull/589)) +* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/search/suggestions` and `GET /api/v1/plugins` are added to the REST API; the suggestions leave out the pages the caller may not view ([PR#590](https://github.com/apache/jspwiki/pull/590)) +* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/pages/{name}`, `GET /api/v1/pages/{name}/history` and `GET /api/v1/pages/{name}/attachments` are added to the REST API, to read a page, its versions and its attachments if the caller may view the page + **2026-11-19 Arturo Bernal (abernal AT apache DOT org)** * _3.0.2-git-1_ diff --git a/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java b/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java index 26cb6a0efa..ad73c8ffa7 100644 --- a/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java +++ b/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java @@ -69,7 +69,7 @@ public final class Release { *

* If the build identifier is empty, it is not added. */ - public static final String BUILD = "1"; + public static final String BUILD = "2"; /** * This is the generic version string you should use when printing out the version. It is of diff --git a/jspwiki-api/src/main/java/org/apache/wiki/api/exceptions/ProviderException.java b/jspwiki-api/src/main/java/org/apache/wiki/api/exceptions/ProviderException.java index 0fda596a5c..86cb06c900 100644 --- a/jspwiki-api/src/main/java/org/apache/wiki/api/exceptions/ProviderException.java +++ b/jspwiki-api/src/main/java/org/apache/wiki/api/exceptions/ProviderException.java @@ -37,4 +37,15 @@ public ProviderException( final String msg ) { super( msg ); } + /** + * Creates a ProviderException that tells what caused it. + * + * @param msg exception message. + * @param cause the exception that made the provider fail. + * @since 3.0.1 + */ + public ProviderException( final String msg, final Throwable cause ) { + super( msg, cause ); + } + } diff --git a/jspwiki-main/pom.xml b/jspwiki-main/pom.xml index 3ea5c62eaa..fcb039b5b7 100644 --- a/jspwiki-main/pom.xml +++ b/jspwiki-main/pom.xml @@ -212,6 +212,12 @@ test + + org.yaml + snakeyaml + test + + org.hsqldb hsqldb diff --git a/jspwiki-main/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java b/jspwiki-main/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java new file mode 100644 index 0000000000..228faa1adf --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java @@ -0,0 +1,409 @@ +/* + 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. + */ +package org.apache.wiki.rest; + +import com.google.gson.Gson; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.lucene.queryparser.classic.ParseException; +import org.apache.wiki.api.core.Attachment; +import org.apache.wiki.api.core.Context; +import org.apache.wiki.api.core.ContextEnum; +import org.apache.wiki.api.core.Engine; +import org.apache.wiki.api.core.Page; +import org.apache.wiki.api.core.Session; +import org.apache.wiki.api.exceptions.ProviderException; +import org.apache.wiki.api.plugin.Plugin; +import org.apache.wiki.api.providers.WikiProvider; +import org.apache.wiki.api.search.SearchResult; +import org.apache.wiki.api.spi.Wiki; +import org.apache.wiki.auth.AuthorizationManager; +import org.apache.wiki.attachment.AttachmentManager; +import org.apache.wiki.auth.permissions.PagePermission; +import org.apache.wiki.auth.permissions.PermissionFactory; +import org.apache.wiki.pages.PageManager; +import org.apache.wiki.plugin.PluginManager; +import org.apache.wiki.search.SearchManager; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +/** + * Version 1 of the REST API of the wiki, described by {@code openapi.yaml} in this package. It answers with JSON, also when it fails. + * A caller that is not allowed to read gets 401 if it is anonymous and 403 if it is logged in. + * + * @since 3.0.1 + */ +public class ApiV1Servlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + private static final Logger LOG = LogManager.getLogger( ApiV1Servlet.class ); + private static final Gson GSON = new Gson(); + + /** Number of entries returned when the request does not say how many it wants. */ + static final int DEFAULT_MAX = 20; + + private static final String PAGES = "/pages/"; + private static final String HISTORY = "/history"; + private static final String ATTACHMENTS = "/attachments"; + + private transient Engine engine; + + /** {@inheritDoc} */ + @Override + public void init( final ServletConfig config ) throws ServletException { + super.init( config ); + engine = Wiki.engine().find( config ); + } + + /** {@inheritDoc} */ + @Override + protected void doGet( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final String path = req.getPathInfo(); + if( "/search".equals( path ) ) { + search( req, resp ); + } else if( "/search/suggestions".equals( path ) ) { + suggestions( req, resp ); + } else if( "/plugins".equals( path ) ) { + plugins( req, resp ); + } else if( path != null && path.startsWith( PAGES ) ) { + pages( req, resp, path.substring( PAGES.length() ) ); + } else { + error( resp, HttpServletResponse.SC_NOT_FOUND, "No such resource." ); + } + } + + private void search( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final Session session = authorized( req, resp ); + final String query = session == null ? null : query( req, resp ); + final int max = query == null ? 0 : max( req, resp ); + if( max < 1 ) { + return; + } + + final Context context = Wiki.context().create( engine, req, ContextEnum.PAGE_VIEW.getRequestContext() ); + try { + final Collection< SearchResult > found = engine.getManager( SearchManager.class ).findPages( query, context ); + if( found == null ) { + // The Lucene provider logs a failure of its index, for instance before it is first built, and returns null + error( resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The search index is not available." ); + return; + } + final List< Hit > hits = new ArrayList<>(); + for( final SearchResult result : found ) { + if( hits.size() == max ) { + break; + } + hits.add( new Hit( result.getPage().getName(), result.getScore() ) ); + } + json( resp, HttpServletResponse.SC_OK, hits ); + } catch( final ProviderException e ) { + if( e.getCause() instanceof ParseException ) { + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter query is not a valid query." ); + } else { + LOG.error( "The search for the REST API failed", e ); + error( resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The search failed." ); + } + } catch( final IOException e ) { + LOG.error( "The search for the REST API failed", e ); + error( resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The search failed." ); + } + } + + private void suggestions( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final Session session = authorized( req, resp ); + final String query = session == null ? null : query( req, resp ); + final int max = query == null ? 0 : max( req, resp ); + if( max > 0 ) { + json( resp, HttpServletResponse.SC_OK, engine.getManager( SearchManager.class ).suggestPages( query, max, session ) ); + } + } + + private void plugins( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + if( authorized( req, resp ) == null ) { + return; + } + final Locale locale = req.getLocale() != null ? req.getLocale() : Locale.getDefault(); + final List< Plugin > discovered = new ArrayList<>( engine.getManager( PluginManager.class ).getDiscoveredPlugins() ); + discovered.sort( Comparator.comparing( plugin -> plugin.getDisplayName( locale ) ) ); + final List< PluginEntry > entries = new ArrayList<>(); + for( final Plugin plugin : discovered ) { + entries.add( new PluginEntry( plugin.getDisplayName( locale ), plugin.getSnipExample() ) ); + } + json( resp, HttpServletResponse.SC_OK, entries ); + } + + /** Serves a page, its history or its attachments. The part of the path before the optional suffix is the page name. */ + private void pages( final HttpServletRequest req, final HttpServletResponse resp, final String rest ) throws IOException { + final String suffix = rest.endsWith( HISTORY ) ? HISTORY : rest.endsWith( ATTACHMENTS ) ? ATTACHMENTS : ""; + final String name = rest.substring( 0, rest.length() - suffix.length() ); + if( name.isEmpty() ) { + error( resp, HttpServletResponse.SC_NOT_FOUND, "No such resource." ); + return; + } + if( !plausible( name ) ) { + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The name of the page is not valid." ); + return; + } + final Session session = authorized( req, resp ); + if( session == null ) { + return; + } + // The permission is checked before the existence of the page, so that the answer does not depend on whether a page is there + if( !engine.getManager( AuthorizationManager.class ).checkPermission( session, PermissionFactory.getPagePermission( Wiki.contents().page( engine, name ), PagePermission.VIEW_ACTION ) ) ) { + denied( resp, session ); + return; + } + final int version = HISTORY.equals( suffix ) || ATTACHMENTS.equals( suffix ) ? WikiProvider.LATEST_VERSION : version( req, resp ); + if( version == 0 ) { + return; + } + + try { + final Page page = engine.getManager( PageManager.class ).getPageInfo( name, version ); + if( page == null ) { + error( resp, HttpServletResponse.SC_NOT_FOUND, "The page does not exist." ); + } else if( HISTORY.equals( suffix ) ) { + history( resp, page ); + } else if( ATTACHMENTS.equals( suffix ) ) { + attachments( resp, page ); + } else { + final String text = engine.getManager( PageManager.class ).getPageText( name, page.getVersion() ); + json( resp, HttpServletResponse.SC_OK, new PageContent( page, text ) ); + } + } catch( final ProviderException e ) { + LOG.error( "The request for the page {} of the REST API failed", name, e ); + error( resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The page could not be read." ); + } + } + + private void history( final HttpServletResponse resp, final Page page ) throws IOException { + final List< Page > versions = engine.getManager( PageManager.class ).getVersionHistory( page.getName() ); + if( versions == null ) { + error( resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The history of the page could not be read." ); + return; + } + final List< Revision > revisions = new ArrayList<>(); + for( final Page version : versions ) { + revisions.add( new Revision( version ) ); + } + if( revisions.isEmpty() ) { + // A page that was put in the page directory by hand has no history, but it still has its current version + revisions.add( new Revision( page ) ); + } + revisions.sort( Comparator.comparingInt( ( Revision revision ) -> revision.version ).reversed() ); + json( resp, HttpServletResponse.SC_OK, revisions ); + } + + private void attachments( final HttpServletResponse resp, final Page page ) throws ProviderException, IOException { + final List< AttachmentEntry > entries = new ArrayList<>(); + for( final Attachment attachment : engine.getManager( AttachmentManager.class ).listAttachments( page ) ) { + entries.add( new AttachmentEntry( attachment ) ); + } + json( resp, HttpServletResponse.SC_OK, entries ); + } + + /** + * Tells whether the text can be the name of a page. The providers encode the names they turn into files, so this is only an extra + * barrier before a name that comes from the caller reaches them: no parent directory, no backslash and no control character. + */ + private static boolean plausible( final String name ) { + return !name.contains( ".." ) && name.indexOf( '\\' ) < 0 && name.chars().noneMatch( Character::isISOControl ); + } + + /** Returns the version parameter, the latest version when it is absent, and 0 after answering 400 when it is not a positive integer. */ + private static int version( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final String value = req.getParameter( "version" ); + if( value == null ) { + return WikiProvider.LATEST_VERSION; + } + try { + final int version = Integer.parseInt( value.trim() ); + if( version > 0 ) { + return version; + } + } catch( final NumberFormatException e ) { + // answered below + } + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter version must be an integer greater than zero." ); + return 0; + } + + /** A provider that keeps no old versions numbers its only version -1, which the API reports as 1. */ + private static int number( final int version ) { + return Math.max( 1, version ); + } + + private static String instant( final Date date ) { + return date == null ? null : date.toInstant().toString(); + } + + /** Returns the session of the caller, or null after answering 401 or 403 when the caller may not read. */ + private Session authorized( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final Session session = Wiki.session().find( engine, req ); + if( engine.getManager( AuthorizationManager.class ).checkPermission( session, PagePermission.VIEW ) ) { + return session; + } + denied( resp, session ); + return null; + } + + /** Returns the query parameter, or null after answering 400 when it is missing. */ + private static String query( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final String query = req.getParameter( "query" ); + if( StringUtils.isBlank( query ) ) { + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter query is required." ); + return null; + } + return query; + } + + /** Returns the max parameter, the default when it is absent, and 0 after answering 400 when it is not a positive integer. */ + private static int max( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final String value = req.getParameter( "max" ); + if( value == null ) { + return DEFAULT_MAX; + } + try { + final int max = Integer.parseInt( value.trim() ); + if( max > 0 ) { + return max; + } + } catch( final NumberFormatException e ) { + // answered below + } + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter max must be an integer greater than zero." ); + return 0; + } + + private static void denied( final HttpServletResponse resp, final Session session ) throws IOException { + if( session.isAuthenticated() ) { + error( resp, HttpServletResponse.SC_FORBIDDEN, "The permission to read is missing." ); + } else { + error( resp, HttpServletResponse.SC_UNAUTHORIZED, "Authentication is required." ); + } + } + + private static void error( final HttpServletResponse resp, final int status, final String message ) throws IOException { + json( resp, status, new Failure( status, message ) ); + } + + private static void json( final HttpServletResponse resp, final int status, final Object body ) throws IOException { + resp.setStatus( status ); + resp.setContentType( "application/json" ); + resp.setCharacterEncoding( StandardCharsets.UTF_8.name() ); + resp.getWriter().write( GSON.toJson( body ) ); + } + + /** An entry of the answer to a search. */ + private static final class Hit { + private final String page; + private final int score; + + Hit( final String page, final int score ) { + this.page = page; + this.score = score; + } + } + + /** An entry of the list of plugins. */ + private static final class PluginEntry { + private final String displayName; + private final String snip; + + PluginEntry( final String displayName, final String snip ) { + this.displayName = displayName; + this.snip = snip; + } + } + + /** The content of a page. */ + private static final class PageContent { + private final String name; + private final int version; + private final String author; + private final String lastModified; + private final String text; + + PageContent( final Page page, final String text ) { + this.name = page.getName(); + this.version = number( page.getVersion() ); + this.author = page.getAuthor(); + this.lastModified = instant( page.getLastModified() ); + this.text = text; + } + } + + /** An entry of the history of a page. */ + private static final class Revision { + private final int version; + private final String author; + private final String lastModified; + private final String changeNote; + + Revision( final Page page ) { + this.version = number( page.getVersion() ); + this.author = page.getAuthor(); + this.lastModified = instant( page.getLastModified() ); + this.changeNote = page.getAttribute( Page.CHANGENOTE ); + } + } + + /** An entry of the list of attachments of a page. */ + private static final class AttachmentEntry { + private final String name; + private final int version; + private final long size; + private final String author; + private final String lastModified; + + AttachmentEntry( final Attachment attachment ) { + this.name = attachment.getFileName(); + this.version = number( attachment.getVersion() ); + this.size = attachment.getSize(); + this.author = attachment.getAuthor(); + this.lastModified = instant( attachment.getLastModified() ); + } + } + + /** The body of every answer that is not a success. */ + private static final class Failure { + private final int status; + private final String message; + + Failure( final int status, final String message ) { + this.status = status; + this.message = message; + } + } + +} diff --git a/jspwiki-main/src/main/java/org/apache/wiki/search/DefaultSearchManager.java b/jspwiki-main/src/main/java/org/apache/wiki/search/DefaultSearchManager.java index 2bc434229b..2c38136275 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/search/DefaultSearchManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/search/DefaultSearchManager.java @@ -29,12 +29,14 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.api.core.ContextEnum; import org.apache.wiki.api.core.Engine; import org.apache.wiki.api.core.Page; +import org.apache.wiki.api.core.Session; import org.apache.wiki.api.exceptions.FilterException; import org.apache.wiki.api.exceptions.NoRequiredPropertyException; import org.apache.wiki.api.filters.BasePageFilter; import org.apache.wiki.api.search.SearchResult; import org.apache.wiki.api.spi.Wiki; import org.apache.wiki.auth.AuthorizationManager; +import org.apache.wiki.auth.permissions.PagePermission; import org.apache.wiki.auth.permissions.PermissionFactory; import org.apache.wiki.event.WikiEvent; import org.apache.wiki.event.WikiEventManager; @@ -59,6 +61,7 @@ Licensed to the Apache Software Foundation (ASF) under one import java.util.Map; import java.util.Properties; import java.util.Set; +import java.util.function.Predicate; import org.apache.wiki.api.plugin.Plugin; import org.apache.wiki.plugin.PluginManager; import static org.apache.wiki.search.SearchManager.PLUGIN_SEARCH; @@ -91,6 +94,52 @@ public DefaultSearchManager( final Engine engine, final Properties properties ) WikiAjaxDispatcherServlet.registerServlet( PLUGIN_SEARCH, new PluginSearch() ); } + /** {@inheritDoc} */ + @Override + public List< String > suggestPages( final String text, final int max, final Session session ) { + final AuthorizationManager mgr = m_engine.getManager( AuthorizationManager.class ); + return suggest( text, max, name -> mgr.checkPermission( session, new PagePermission( m_engine.getApplicationName() + ":" + name, PagePermission.VIEW_ACTION ) ) ); + } + + /** + * Looks for the names of the pages that start with the given text and that the filter accepts. + * + * @param wikiName the page name, optionally followed by a slash and the beginning of an attachment name + * @param maxLength maximum number of suggestions + * @param accepted tells whether a name may be suggested + * @return the suggestions + */ + private List< String > suggest( String wikiName, final int maxLength, final Predicate< String > accepted ) { + final StopWatch sw = new StopWatch(); + sw.start(); + final List< String > list = new ArrayList<>( Math.min( maxLength, 100 ) ); + if( !wikiName.isEmpty() ) { + // split pagename and attachment filename + String filename = ""; + final int pos = wikiName.indexOf("/"); + if( pos >= 0 ) { + filename = wikiName.substring( pos ).toLowerCase(); + wikiName = wikiName.substring( 0, pos ); + } + + final String cleanWikiName = MarkupParser.cleanLink(wikiName).toLowerCase() + filename; + final String oldStyleName = MarkupParser.wikifyLink(wikiName).toLowerCase() + filename; + final Set< String > allPages = m_engine.getManager( ReferenceManager.class ).findCreated(); + + for( final Iterator< String > i = allPages.iterator(); i.hasNext() && list.size() < maxLength; ) { + final String p = i.next(); + final String pp = p.toLowerCase(); + if( ( pp.startsWith( cleanWikiName ) || pp.startsWith( oldStyleName ) ) && accepted.test( p ) ) { + list.add( p ); + } + } + } + + sw.stop(); + LOG.debug( "Suggestion request for {} done in {}", wikiName, sw ); + return list; + } + /** * Provides a JSON AJAX API to the JSPWiki Plugin discovery mechanism, * primarily used for [{}] based auto complete @@ -228,37 +277,8 @@ private boolean mayView( final Context wikiContext, final String pageName ) { * @param wikiContext the context of the viewer, whose view permission decides which page names are suggested * @return the suggestions */ - public List< String > getSuggestions( String wikiName, final int maxLength, final Context wikiContext ) { - final StopWatch sw = new StopWatch(); - sw.start(); - final List< String > list = new ArrayList<>( maxLength ); - if( !wikiName.isEmpty() ) { - // split pagename and attachment filename - String filename = ""; - final int pos = wikiName.indexOf("/"); - if( pos >= 0 ) { - filename = wikiName.substring( pos ).toLowerCase(); - wikiName = wikiName.substring( 0, pos ); - } - - final String cleanWikiName = MarkupParser.cleanLink(wikiName).toLowerCase() + filename; - final String oldStyleName = MarkupParser.wikifyLink(wikiName).toLowerCase() + filename; - final Set< String > allPages = m_engine.getManager( ReferenceManager.class ).findCreated(); - - int counter = 0; - for( final Iterator< String > i = allPages.iterator(); i.hasNext() && counter < maxLength; ) { - final String p = i.next(); - final String pp = p.toLowerCase(); - if( ( pp.startsWith( cleanWikiName) || pp.startsWith( oldStyleName ) ) && mayView( wikiContext, p ) ) { - list.add( p ); - counter++; - } - } - } - - sw.stop(); - LOG.debug( "Suggestion request for {} done in {}", wikiName, sw ); - return list; + public List< String > getSuggestions( final String wikiName, final int maxLength, final Context wikiContext ) { + return suggest( wikiName, maxLength, name -> mayView( wikiContext, name ) ); } /** diff --git a/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java b/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java index e6ff9cfdab..3ef5e5bbdf 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java @@ -538,7 +538,7 @@ public Collection< SearchResult > findPages( final String query, final int flags LOG.error( "Failed during lucene search", e ); } catch( final ParseException e ) { LOG.error( "Broken query; cannot parse query: {}", query, e ); - throw new ProviderException( "You have entered a query Lucene cannot process [" + query + "]: " + e.getMessage() ); + throw new ProviderException( "You have entered a query Lucene cannot process [" + query + "]: " + e.getMessage(), e ); } catch( final InvalidTokenOffsetsException e ) { LOG.error( "Tokens are incompatible with provided text ", e ); } diff --git a/jspwiki-main/src/main/java/org/apache/wiki/search/SearchManager.java b/jspwiki-main/src/main/java/org/apache/wiki/search/SearchManager.java index cb241c3aa3..398d2a471a 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/search/SearchManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/search/SearchManager.java @@ -20,6 +20,7 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.api.core.Context; import org.apache.wiki.api.core.Page; +import org.apache.wiki.api.core.Session; import org.apache.wiki.api.exceptions.ProviderException; import org.apache.wiki.api.filters.PageFilter; import org.apache.wiki.api.search.SearchResult; @@ -28,6 +29,7 @@ Licensed to the Apache Software Foundation (ASF) under one import java.io.IOException; import java.util.Collection; +import java.util.List; /** @@ -55,6 +57,17 @@ public interface SearchManager extends PageFilter, InternalModule, WikiEventList */ SearchProvider getSearchEngine(); + /** + * Suggests the names of the pages that start with the given text, leaving out the pages the session may not view. + * + * @param text the beginning of a page name, optionally followed by a slash and the beginning of an attachment name. + * @param max the maximum number of names to return. + * @param session the session of the caller. + * @return the names of the pages, in no particular order. + * @since 3.0.1 + */ + List< String > suggestPages( String text, int max, Session session ); + /** * Sends a search to the current search provider. The query is is whatever native format the query engine wants to use. * diff --git a/jspwiki-main/src/main/resources/org/apache/wiki/rest/openapi.yaml b/jspwiki-main/src/main/resources/org/apache/wiki/rest/openapi.yaml new file mode 100644 index 0000000000..84399a8f33 --- /dev/null +++ b/jspwiki-main/src/main/resources/org/apache/wiki/rest/openapi.yaml @@ -0,0 +1,321 @@ +# 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. + +# Description of the REST API of the wiki, JSPWIKI-1310. A test compares it with the answers of ApiV1Servlet. +openapi: 3.0.3 +info: + title: JSPWiki API + version: 1.0.0 + description: Search of the pages the caller may view, page name suggestions and the installed plugins. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: /api/v1 +security: + - sessionCookie: [] +paths: + /search: + get: + operationId: searchPages + summary: Search the pages the caller may view. + parameters: + - name: query + in: query + required: true + schema: + type: string + minLength: 1 + - $ref: '#/components/parameters/max' + responses: + '200': + description: Matching pages, best match first. Empty when nothing matches. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SearchResult' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '500': + $ref: '#/components/responses/InternalError' + '503': + $ref: '#/components/responses/Unavailable' + /search/suggestions: + get: + operationId: suggestPages + summary: Suggest the names of the pages that start with the given text and that the caller may view. + parameters: + - name: query + in: query + required: true + schema: + type: string + minLength: 1 + - $ref: '#/components/parameters/max' + responses: + '200': + description: Page names. Empty when there is no suggestion. + content: + application/json: + schema: + type: array + items: + type: string + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + /plugins: + get: + operationId: listPlugins + summary: List the plugins discovered by the wiki, sorted by display name for the locale of the request. + responses: + '200': + description: The plugins with an example of how to insert each one. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Plugin' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + /pages/{name}: + get: + operationId: getPage + summary: Read a page the caller may view, in the latest version or in the one asked for. + parameters: + - $ref: '#/components/parameters/name' + - name: version + in: query + required: false + description: Version of the page. The latest version when absent. + schema: + type: integer + minimum: 1 + responses: + '200': + description: The page with its markup. + content: + application/json: + schema: + $ref: '#/components/schemas/Page' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalError' + /pages/{name}/history: + get: + operationId: getPageHistory + summary: List the versions of a page the caller may view, the latest first. + parameters: + - $ref: '#/components/parameters/name' + responses: + '200': + description: The versions of the page. A provider that does not keep old versions lists only the current one. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Revision' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalError' + /pages/{name}/attachments: + get: + operationId: listPageAttachments + summary: List the attachments of a page the caller may view, sorted by name. + parameters: + - $ref: '#/components/parameters/name' + responses: + '200': + description: The attachments of the page. Empty when it has none or when attachments are disabled. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Attachment' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalError' +components: + securitySchemes: + sessionCookie: + type: apiKey + in: cookie + name: JSESSIONID + parameters: + name: + name: name + in: path + required: true + description: Name of the page. A name with "..", a backslash or a control character is not valid. + schema: + type: string + minLength: 1 + max: + name: max + in: query + required: false + description: Maximum number of entries to return. + schema: + type: integer + minimum: 1 + default: 20 + schemas: + SearchResult: + type: object + required: [page, score] + properties: + page: + type: string + description: Name of the page. + score: + type: integer + description: Relevance of the page for the query. Higher is better. + Page: + type: object + required: [name, version, text] + properties: + name: + type: string + version: + type: integer + author: + type: string + lastModified: + type: string + format: date-time + text: + type: string + description: Wiki markup of the page, without any conversion. + Revision: + type: object + required: [version] + properties: + version: + type: integer + author: + type: string + lastModified: + type: string + format: date-time + changeNote: + type: string + Attachment: + type: object + required: [name, version, size] + properties: + name: + type: string + description: File name of the attachment. + version: + type: integer + size: + type: integer + description: Size in bytes. + author: + type: string + lastModified: + type: string + format: date-time + Plugin: + type: object + required: [displayName, snip] + properties: + displayName: + type: string + snip: + type: string + description: Example of the markup that inserts the plugin. + Error: + type: object + required: [status, message] + properties: + status: + type: integer + message: + type: string + responses: + BadRequest: + description: A required parameter is missing or invalid. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Unauthorized: + description: The caller is not authenticated and anonymous access is not allowed. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Forbidden: + description: The caller is authenticated but lacks the permission. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + NotFound: + description: The page does not exist. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + InternalError: + description: The request could not be served because of an error of the wiki. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Unavailable: + description: The search index is not available, for instance right after the wiki has started. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' diff --git a/jspwiki-main/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java b/jspwiki-main/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java new file mode 100644 index 0000000000..ad0a5defe4 --- /dev/null +++ b/jspwiki-main/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java @@ -0,0 +1,666 @@ +/* + 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. + */ +package org.apache.wiki.rest; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.wiki.HttpMockFactory; +import org.apache.wiki.TestEngine; +import org.apache.wiki.api.core.Attachment; +import org.apache.wiki.api.core.Session; +import org.apache.wiki.api.spi.Wiki; +import org.apache.wiki.attachment.AttachmentManager; +import org.apache.wiki.auth.AuthenticationManager; +import org.apache.wiki.auth.AuthorizationManager; +import org.apache.wiki.auth.Users; +import org.apache.wiki.pages.PageManager; +import org.apache.wiki.search.SearchManager; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.yaml.snakeyaml.Yaml; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +class ApiV1ServletTest { + + private static final Gson GSON = new Gson(); + private static final Map< String, Object > CONTRACT = contract(); + + private TestEngine engine; + + @AfterEach + void tearDown() { + if( engine != null ) { + engine.stop(); + } + } + + @Test + void searchAnswersWithTheContract() throws Exception { + startEngine( null ); + engine.saveText( "ApiSearchPage", "The dawn of the third age of mankind." ); + engine.saveText( "ApiSearchOther", "Another page about mankind." ); + + final Reply[] reply = new Reply[ 1 ]; + Awaitility.await( "both pages are indexed" ).ignoreExceptions().until( () -> { + reply[ 0 ] = search( null, "query", "mankind" ); + return reply[ 0 ].json().getAsJsonArray().size() == 2; + } ); + + assertMatchesContract( "/search", reply[ 0 ] ); + Assertions.assertEquals( 200, reply[ 0 ].status ); + final JsonObject first = reply[ 0 ].json().getAsJsonArray().get( 0 ).getAsJsonObject(); + Assertions.assertTrue( first.get( "page" ).getAsString().startsWith( "ApiSearch" ) ); + } + + @Test + void searchWithoutMatchesAnswersWithAnEmptyList() throws Exception { + startEngine( null ); + + final Reply[] answer = new Reply[ 1 ]; + Awaitility.await( "the index is built" ).until( () -> { + answer[ 0 ] = search( null, "query", "nothingwillmatchthis" ); + return answer[ 0 ].status != 503; + } ); + final Reply reply = answer[ 0 ]; + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 200, reply.status ); + Assertions.assertEquals( 0, reply.json().getAsJsonArray().size() ); + } + + @Test + void searchReturnsAtMostMaxEntries() throws Exception { + startEngine( null ); + engine.saveText( "ApiMaxOne", "common words here" ); + engine.saveText( "ApiMaxTwo", "common words there" ); + Awaitility.await( "both pages are indexed" ).ignoreExceptions().until( () -> search( null, "query", "common" ).json().getAsJsonArray().size() == 2 ); + + final Reply reply = search( null, "query", "common", "max", "1" ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 1, reply.json().getAsJsonArray().size() ); + } + + @Test + void searchWithoutQueryIsABadRequest() throws Exception { + startEngine( null ); + + final Reply reply = search( null ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 400, reply.status ); + } + + @Test + void searchWithAQueryThatCannotBeParsedIsABadRequest() throws Exception { + startEngine( null ); + + final Reply[] answer = new Reply[ 1 ]; + Awaitility.await( "the index is built" ).until( () -> { + answer[ 0 ] = search( null, "query", "\"unbalanced" ); + return answer[ 0 ].status != 503; + } ); + final Reply reply = answer[ 0 ]; + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 400, reply.status ); + } + + @Test + void searchWithAMaxThatIsNotAPositiveIntegerIsABadRequest() throws Exception { + startEngine( null ); + + for( final String max : new String[] { "0", "-3", "many", "" } ) { + final Reply reply = search( null, "query", "mankind", "max", max ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 400, reply.status, "max=" + max ); + } + } + + @Test + void searchByAnAnonymousCallerWithoutPermissionIs401( @TempDir final Path dir ) throws Exception { + startEngine( policy( dir, "Authenticated" ) ); + + final Reply reply = search( null, "query", "mankind" ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 401, reply.status ); + } + + @Test + void searchByALoggedInCallerWithoutPermissionIs403( @TempDir final Path dir ) throws Exception { + startEngine( policy( dir, "Admin" ) ); + final HttpServletRequest request = request( "query", "mankind" ); + final Session session = Wiki.session().find( engine, request ); + engine.getManager( AuthenticationManager.class ).login( session, request, Users.JANNE, Users.JANNE_PASS ); + Assertions.assertTrue( session.isAuthenticated() ); + + final Reply reply = call( request ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 403, reply.status ); + } + + @Test + void searchBeforeTheIndexIsBuiltIs503() throws Exception { + startEngine( null, "600" ); + + final Reply reply = search( null, "query", "mankind" ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 503, reply.status ); + } + + @Test + void suggestionsAnswerWithTheContract() throws Exception { + startEngine( null ); + engine.saveText( "ApiSugOne", "one" ); + engine.saveText( "ApiSugTwo", "two" ); + engine.saveText( "ApiOther", "other" ); + + final Reply reply = call( requestTo( "/search/suggestions", "query", "ApiSug" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( 200, reply.status ); + Assertions.assertEquals( Set.of( "ApiSugOne", "ApiSugTwo" ), names( reply ) ); + } + + @Test + void suggestionsReturnAtMostMaxEntries() throws Exception { + startEngine( null ); + engine.saveText( "ApiSugOne", "one" ); + engine.saveText( "ApiSugTwo", "two" ); + + final Reply reply = call( requestTo( "/search/suggestions", "query", "ApiSug", "max", "1" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( 1, reply.json().getAsJsonArray().size() ); + } + + @Test + void suggestionsLeaveOutThePagesTheCallerMayNotView() throws Exception { + startEngine( null ); + engine.saveText( "ApiSugOpen", "open" ); + engine.saveText( "ApiSugSecret", "[{ALLOW view Admin}] secret" ); + + final Reply reply = call( requestTo( "/search/suggestions", "query", "ApiSug" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( Set.of( "ApiSugOpen" ), names( reply ) ); + } + + @Test + void suggestionsWithoutQueryAreABadRequest() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/search/suggestions" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( 400, reply.status ); + } + + @Test + void suggestionsByAnAnonymousCallerWithoutPermissionAre401( @TempDir final Path dir ) throws Exception { + startEngine( policy( dir, "Authenticated" ) ); + + final Reply reply = call( requestTo( "/search/suggestions", "query", "Api" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( 401, reply.status ); + } + + @Test + void pluginsAnswerWithTheContractSortedByDisplayName() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/plugins" ) ); + + assertMatchesContract( "/plugins", reply ); + Assertions.assertEquals( 200, reply.status ); + final List< String > displayNames = new ArrayList<>(); + reply.json().getAsJsonArray().forEach( entry -> displayNames.add( entry.getAsJsonObject().get( "displayName" ).getAsString() ) ); + Assertions.assertFalse( displayNames.isEmpty(), "the wiki has plugins" ); + final List< String > sorted = new ArrayList<>( displayNames ); + sorted.sort( null ); + Assertions.assertEquals( sorted, displayNames ); + } + + @Test + void pluginsByALoggedInCallerWithoutPermissionAre403( @TempDir final Path dir ) throws Exception { + startEngine( policy( dir, "Admin" ) ); + final HttpServletRequest request = requestTo( "/plugins" ); + final Session session = Wiki.session().find( engine, request ); + engine.getManager( AuthenticationManager.class ).login( session, request, Users.JANNE, Users.JANNE_PASS ); + + final Reply reply = call( request ); + + assertMatchesContract( "/plugins", reply ); + Assertions.assertEquals( 403, reply.status ); + } + + @Test + void anUnknownResourceIs404() throws Exception { + startEngine( null ); + final HttpServletRequest request = request(); + Mockito.doReturn( "/nothing" ).when( request ).getPathInfo(); + + final Reply reply = call( request ); + + Assertions.assertEquals( 404, reply.status ); + Assertions.assertEquals( 404, reply.json().getAsJsonObject().get( "status" ).getAsInt() ); + } + + @Test + void pageAnswersWithTheContract() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadPage", "Some *markup* here." ); + + final Reply reply = call( requestTo( "/pages/ApiReadPage" ) ); + + assertMatchesContract( "/pages/{name}", reply ); + Assertions.assertEquals( 200, reply.status ); + final JsonObject page = reply.json().getAsJsonObject(); + Assertions.assertEquals( "ApiReadPage", page.get( "name" ).getAsString() ); + Assertions.assertEquals( 1, page.get( "version" ).getAsInt() ); + Assertions.assertTrue( page.get( "text" ).getAsString().contains( "Some *markup* here." ) ); + } + + @Test + void pageInAnOlderVersionAnswersWithThatText() throws Exception { + startEngine( null, "0", "VersioningFileProvider" ); + engine.saveText( "ApiReadVersions", "first text" ); + engine.saveText( "ApiReadVersions", "second text" ); + + final Reply latest = call( requestTo( "/pages/ApiReadVersions" ) ); + final Reply first = call( requestTo( "/pages/ApiReadVersions", "version", "1" ) ); + + assertMatchesContract( "/pages/{name}", first ); + Assertions.assertEquals( 2, latest.json().getAsJsonObject().get( "version" ).getAsInt() ); + Assertions.assertTrue( latest.json().getAsJsonObject().get( "text" ).getAsString().contains( "second text" ) ); + Assertions.assertEquals( 1, first.json().getAsJsonObject().get( "version" ).getAsInt() ); + Assertions.assertTrue( first.json().getAsJsonObject().get( "text" ).getAsString().contains( "first text" ) ); + } + + @Test + void pageThatDoesNotExistIs404() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/pages/ApiNoSuchPage" ) ); + + assertMatchesContract( "/pages/{name}", reply ); + Assertions.assertEquals( 404, reply.status ); + } + + @Test + void pageWithAVersionThatIsNotAPositiveIntegerIsABadRequest() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadBadVersion", "text" ); + + for( final String version : new String[] { "0", "-1", "last", "" } ) { + final Reply reply = call( requestTo( "/pages/ApiReadBadVersion", "version", version ) ); + + assertMatchesContract( "/pages/{name}", reply ); + Assertions.assertEquals( 400, reply.status, "version=" + version ); + } + } + + @Test + void pageTheCallerMayNotViewIs401ForAnAnonymousCallerAnd403ForALoggedInOne() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadSecret", "[{ALLOW view Admin}] secret" ); + + final Reply anonymous = call( requestTo( "/pages/ApiReadSecret" ) ); + final HttpServletRequest request = requestTo( "/pages/ApiReadSecret" ); + final Session session = Wiki.session().find( engine, request ); + engine.getManager( AuthenticationManager.class ).login( session, request, Users.JANNE, Users.JANNE_PASS ); + final Reply loggedIn = call( request ); + + assertMatchesContract( "/pages/{name}", anonymous ); + assertMatchesContract( "/pages/{name}", loggedIn ); + Assertions.assertEquals( 401, anonymous.status ); + Assertions.assertEquals( 403, loggedIn.status ); + Assertions.assertFalse( anonymous.body.toString().contains( "secret" ) ); + Assertions.assertFalse( loggedIn.body.toString().contains( "secret" ) ); + } + + @Test + void historyAnswersWithTheVersionsLatestFirst() throws Exception { + startEngine( null, "0", "VersioningFileProvider" ); + engine.saveText( "ApiReadHistory", "one" ); + engine.saveText( "ApiReadHistory", "two" ); + engine.saveText( "ApiReadHistory", "three" ); + + final Reply reply = call( requestTo( "/pages/ApiReadHistory/history" ) ); + + assertMatchesContract( "/pages/{name}/history", reply ); + Assertions.assertEquals( 200, reply.status ); + final List< Integer > versions = new ArrayList<>(); + reply.json().getAsJsonArray().forEach( entry -> versions.add( entry.getAsJsonObject().get( "version" ).getAsInt() ) ); + Assertions.assertEquals( List.of( 3, 2, 1 ), versions ); + } + + @Test + void historyOfAPageWithoutOldVersionsListsTheCurrentOne() throws Exception { + startEngine( null, "0", "VersioningFileProvider" ); + Files.write( Path.of( engine.getWikiProperties().getProperty( "jspwiki.fileSystemProvider.pageDir" ), "ApiReadByHand.txt" ), + "put here by hand".getBytes( StandardCharsets.UTF_8 ) ); + + final Reply reply = call( requestTo( "/pages/ApiReadByHand/history" ) ); + + assertMatchesContract( "/pages/{name}/history", reply ); + Assertions.assertEquals( 200, reply.status ); + Assertions.assertEquals( 1, reply.json().getAsJsonArray().size() ); + Assertions.assertEquals( 1, reply.json().getAsJsonArray().get( 0 ).getAsJsonObject().get( "version" ).getAsInt() ); + } + + @Test + void historyOfAPageThatDoesNotExistIs404() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/pages/ApiNoSuchPage/history" ) ); + + assertMatchesContract( "/pages/{name}/history", reply ); + Assertions.assertEquals( 404, reply.status ); + } + + @Test + void historyOfAPageTheCallerMayNotViewIs401() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadSecretHistory", "[{ALLOW view Admin}] secret" ); + + final Reply reply = call( requestTo( "/pages/ApiReadSecretHistory/history" ) ); + + assertMatchesContract( "/pages/{name}/history", reply ); + Assertions.assertEquals( 401, reply.status ); + } + + @Test + void attachmentsAnswerWithTheContract() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadAttachments", "text" ); + final Attachment attachment = Wiki.contents().attachment( engine, "ApiReadAttachments", "b.txt" ); + engine.getManager( AttachmentManager.class ).storeAttachment( attachment, new ByteArrayInputStream( "hello".getBytes( StandardCharsets.UTF_8 ) ) ); + final Attachment other = Wiki.contents().attachment( engine, "ApiReadAttachments", "a.txt" ); + engine.getManager( AttachmentManager.class ).storeAttachment( other, new ByteArrayInputStream( "hi".getBytes( StandardCharsets.UTF_8 ) ) ); + + final Reply reply = call( requestTo( "/pages/ApiReadAttachments/attachments" ) ); + + assertMatchesContract( "/pages/{name}/attachments", reply ); + Assertions.assertEquals( 200, reply.status ); + final JsonArray entries = reply.json().getAsJsonArray(); + Assertions.assertEquals( 2, entries.size() ); + Assertions.assertEquals( "a.txt", entries.get( 0 ).getAsJsonObject().get( "name" ).getAsString() ); + Assertions.assertEquals( 2, entries.get( 0 ).getAsJsonObject().get( "size" ).getAsInt() ); + Assertions.assertEquals( "b.txt", entries.get( 1 ).getAsJsonObject().get( "name" ).getAsString() ); + } + + @Test + void attachmentsOfAPageWithoutAttachmentsAreAnEmptyList() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadNoAttachments", "text" ); + + final Reply reply = call( requestTo( "/pages/ApiReadNoAttachments/attachments" ) ); + + assertMatchesContract( "/pages/{name}/attachments", reply ); + Assertions.assertEquals( 200, reply.status ); + Assertions.assertEquals( 0, reply.json().getAsJsonArray().size() ); + } + + @Test + void attachmentsOfAPageTheCallerMayNotViewAre401() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadSecretAttachments", "[{ALLOW view Admin}] secret" ); + + final Reply reply = call( requestTo( "/pages/ApiReadSecretAttachments/attachments" ) ); + + assertMatchesContract( "/pages/{name}/attachments", reply ); + Assertions.assertEquals( 401, reply.status ); + } + + @Test + void attachmentsOfAPageThatDoesNotExistAre404() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/pages/ApiNoSuchPage/attachments" ) ); + + assertMatchesContract( "/pages/{name}/attachments", reply ); + Assertions.assertEquals( 404, reply.status ); + } + + @Test + void aNameThatCouldLeaveTheDirectoryOfThePagesIsABadRequest() throws Exception { + startEngine( null ); + + for( final String name : new String[] { "..", "a..b", "a\\b", "a\u0000b", "a\nb" } ) { + for( final String suffix : new String[] { "", "/history", "/attachments" } ) { + final Reply reply = call( requestTo( "/pages/" + name + suffix ) ); + + assertMatchesContract( suffix.isEmpty() ? "/pages/{name}" : "/pages/{name}" + suffix, reply ); + Assertions.assertEquals( 400, reply.status, name + suffix ); + } + } + } + + @Test + void pagesWithoutANameIs404() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/pages/" ) ); + + Assertions.assertEquals( 404, reply.status ); + } + + @Test + void contractDeclaresTheParametersTheServletEnforces() { + final Map< String, Object > get = map( map( map( CONTRACT, "paths" ), "/search" ), "get" ); + final List< Object > parameters = list( get, "parameters" ); + + final Map< String, Object > query = map( parameters.get( 0 ), null ); + Assertions.assertEquals( "query", query.get( "name" ) ); + Assertions.assertEquals( Boolean.TRUE, query.get( "required" ) ); + + final Map< String, Object > max = resolve( parameters.get( 1 ) ); + Assertions.assertEquals( "max", max.get( "name" ) ); + Assertions.assertEquals( ApiV1Servlet.DEFAULT_MAX, map( max, "schema" ).get( "default" ) ); + Assertions.assertEquals( 1, map( max, "schema" ).get( "minimum" ) ); + } + + private void startEngine( final String policy ) { + startEngine( policy, "0" ); + } + + private void startEngine( final String policy, final String initialIndexDelay ) { + startEngine( policy, initialIndexDelay, null ); + } + + private void startEngine( final String policy, final String initialIndexDelay, final String pageProvider ) { + final Properties props = TestEngine.getTestProperties(); + props.setProperty( SearchManager.PROP_SEARCHPROVIDER, "LuceneSearchProvider" ); + props.setProperty( "jspwiki.lucene.indexdelay", "0" ); + props.setProperty( "jspwiki.lucene.initialdelay", initialIndexDelay ); + props.setProperty( "jspwiki.workDir", props.getProperty( "jspwiki.workDir" ) + System.currentTimeMillis() ); + props.setProperty( "jspwiki.fileSystemProvider.pageDir", props.getProperty( "jspwiki.fileSystemProvider.pageDir" ) + System.currentTimeMillis() ); + if( pageProvider != null ) { + props.setProperty( PageManager.PROP_PAGEPROVIDER, pageProvider ); + } + if( policy != null ) { + props.setProperty( AuthorizationManager.POLICY, policy ); + } + engine = TestEngine.build( props ); + } + + /** Writes a policy file that lets only the given role view the pages. */ + private static String policy( final Path dir, final String role ) throws Exception { + final Path file = dir.resolve( "api.policy" ); + Files.write( file, ( "grant principal org.apache.wiki.auth.authorize.Role \"" + role + "\" {\n" + + " permission org.apache.wiki.auth.permissions.PagePermission \"*:*\", \"view\";\n" + + "};\n" ).getBytes( StandardCharsets.UTF_8 ) ); + return file.toAbsolutePath().toString(); + } + + private HttpServletRequest request( final String... parameters ) { + return requestTo( "/search", parameters ); + } + + private HttpServletRequest requestTo( final String pathInfo, final String... parameters ) { + final HttpServletRequest request = HttpMockFactory.createHttpRequest( "/JSPWiki", "/api/v1" + pathInfo ); + Mockito.doReturn( "GET" ).when( request ).getMethod(); + Mockito.doReturn( pathInfo ).when( request ).getPathInfo(); + for( int i = 0; i < parameters.length; i += 2 ) { + Mockito.doReturn( parameters[ i + 1 ] ).when( request ).getParameter( parameters[ i ] ); + } + return request; + } + + private Reply search( final HttpServletRequest request, final String... parameters ) throws Exception { + return call( request != null ? request : request( parameters ) ); + } + + private Reply call( final HttpServletRequest request ) throws Exception { + // The context is a mock, so the engine that TestEngine stashed in it has to be handed over again + final ServletContext context = engine.getServletContext(); + Mockito.doReturn( engine ).when( context ).getAttribute( "org.apache.wiki.WikiEngine" ); + final ServletConfig config = Mockito.mock( ServletConfig.class ); + Mockito.doReturn( context ).when( config ).getServletContext(); + final ApiV1Servlet servlet = new ApiV1Servlet(); + servlet.init( config ); + + final Reply reply = new Reply(); + final HttpServletResponse response = Mockito.mock( HttpServletResponse.class ); + Mockito.doAnswer( invocation -> reply.status = invocation.getArgument( 0 ) ).when( response ).setStatus( Mockito.anyInt() ); + Mockito.doAnswer( invocation -> reply.contentType = invocation.getArgument( 0 ) ).when( response ).setContentType( Mockito.anyString() ); + Mockito.doReturn( new PrintWriter( reply.body ) ).when( response ).getWriter(); + servlet.service( request, response ); + return reply; + } + + /** Checks the status, the content type and the shape of the body against what the contract declares for the operation. */ + private static void assertMatchesContract( final String path, final Reply reply ) { + final Map< String, Object > responses = map( map( map( map( CONTRACT, "paths" ), path ), "get" ), "responses" ); + final Object declared = responses.get( String.valueOf( reply.status ) ); + Assertions.assertNotNull( declared, "the contract has no response " + reply.status + " for " + path ); + + final Map< String, Object > content = map( resolve( declared ), "content" ); + Assertions.assertTrue( content.containsKey( reply.contentType ), "content type " + reply.contentType + " is not declared" ); + assertMatchesSchema( resolve( map( content, reply.contentType ).get( "schema" ) ), reply.json(), "body" ); + } + + private static void assertMatchesSchema( final Map< String, Object > schema, final JsonElement value, final String where ) { + switch( String.valueOf( schema.get( "type" ) ) ) { + case "array": + Assertions.assertTrue( value.isJsonArray(), where + " must be an array" ); + value.getAsJsonArray().forEach( item -> assertMatchesSchema( resolve( schema.get( "items" ) ), item, where + "[]" ) ); + break; + case "object": + Assertions.assertTrue( value.isJsonObject(), where + " must be an object" ); + final JsonObject object = value.getAsJsonObject(); + for( final Object required : list( schema, "required" ) ) { + Assertions.assertTrue( object.has( required.toString() ), where + " lacks " + required ); + } + final Map< String, Object > properties = map( schema, "properties" ); + for( final String name : object.keySet() ) { + Assertions.assertTrue( properties.containsKey( name ), where + "." + name + " is not in the contract" ); + assertMatchesSchema( resolve( properties.get( name ) ), object.get( name ), where + "." + name ); + } + break; + case "string": + Assertions.assertTrue( value.isJsonPrimitive() && value.getAsJsonPrimitive().isString(), where + " must be a string" ); + break; + case "integer": + Assertions.assertTrue( value.isJsonPrimitive() && value.getAsJsonPrimitive().isNumber() + && value.getAsDouble() == Math.rint( value.getAsDouble() ), where + " must be an integer" ); + break; + default: + Assertions.fail( "the test does not know the type of " + where ); + } + } + + private static Map< String, Object > contract() { + try( InputStream in = ApiV1Servlet.class.getResourceAsStream( "openapi.yaml" ) ) { + return new Yaml().load( in ); + } catch( final java.io.IOException e ) { + throw new IllegalStateException( e ); + } + } + + /** Follows a local reference such as #/components/schemas/Error. */ + private static Map< String, Object > resolve( final Object node ) { + Map< String, Object > current = map( node, null ); + while( current.containsKey( "$ref" ) ) { + Object target = CONTRACT; + for( final String part : current.get( "$ref" ).toString().substring( 2 ).split( "/" ) ) { + target = map( target, null ).get( part ); + } + current = map( target, null ); + } + return current; + } + + @SuppressWarnings( "unchecked" ) + private static Map< String, Object > map( final Object node, final String key ) { + return ( Map< String, Object > )( key == null ? node : ( ( Map< String, Object > )node ).get( key ) ); + } + + @SuppressWarnings( "unchecked" ) + private static List< Object > list( final Map< String, Object > node, final String key ) { + return ( List< Object > )node.get( key ); + } + + private static Set< String > names( final Reply reply ) { + final Set< String > names = new HashSet<>(); + reply.json().getAsJsonArray().forEach( name -> names.add( name.getAsString() ) ); + return names; + } + + /** What the servlet wrote to a mock response. */ + private static final class Reply { + int status; + String contentType; + final StringWriter body = new StringWriter(); + + JsonElement json() { + return GSON.fromJson( body.toString(), JsonElement.class ); + } + } + +} diff --git a/jspwiki-war/src/main/webapp/WEB-INF/web.xml b/jspwiki-war/src/main/webapp/WEB-INF/web.xml index afce534d0d..454761b373 100644 --- a/jspwiki-war/src/main/webapp/WEB-INF/web.xml +++ b/jspwiki-war/src/main/webapp/WEB-INF/web.xml @@ -213,6 +213,12 @@ 1 + + + ApiV1Servlet + org.apache.wiki.rest.ApiV1Servlet + + ATOM @@ -251,6 +257,11 @@ /admin/ajax/* + + ApiV1Servlet + /api/v1/* + +