summaryrefslogtreecommitdiffstats
path: root/javatests/com/google/gerrit/acceptance/rest/binding/PluginProvidedRootRestApiBindingsIT.java
blob: e9047e07d9b79e9cbd4591d994befbd47378d2db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Copyright (C) 2019 The Android Open Source Project
//
// Licensed 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 com.google.gerrit.acceptance.rest.binding;

import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.rest.util.RestApiCallHelper;
import com.google.gerrit.acceptance.rest.util.RestCall;
import com.google.gerrit.acceptance.rest.util.RestCall.Method;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.extensions.restapi.ChildCollection;
import com.google.gerrit.extensions.restapi.IdString;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.extensions.restapi.RestApiModule;
import com.google.gerrit.extensions.restapi.RestCollectionModifyView;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.extensions.restapi.RestResource;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.extensions.restapi.TopLevelResource;
import com.google.gerrit.httpd.restapi.RestApiServlet;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.servlet.ServletModule;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
import org.kohsuke.args4j.Option;

/**
 * Tests for checking plugin-provided REST API bindings directly under {@code /}.
 *
 * <p>These tests only verify that the plugin-provided REST endpoints are correctly bound, they do
 * not test the functionality of the plugin REST endpoints.
 */
public class PluginProvidedRootRestApiBindingsIT extends AbstractDaemonTest {

  /** Resource to bind a child collection. */
  public static final TypeLiteral<RestView<TestPluginResource>> TEST_KIND = new TypeLiteral<>() {};

  private static final String PLUGIN_NAME = "my-plugin";

  private static final ImmutableSet<RestCall> TEST_CALLS =
      ImmutableSet.of(
          RestCall.get("/plugins/" + PLUGIN_NAME + "/test-collection/"),
          RestCall.get("/plugins/" + PLUGIN_NAME + "/test-collection/1/detail"),
          RestCall.post("/plugins/" + PLUGIN_NAME + "/test-collection/"),
          RestCall.post("/plugins/" + PLUGIN_NAME + "/test-collection/1/update"),
          RestCall.builder(Method.GET, "/plugins/" + PLUGIN_NAME + "/not-found")
              .expectedResponseCode(SC_NOT_FOUND)
              .build());

  /** Module for all HTTP bindings. */
  static class MyPluginHttpModule extends ServletModule {
    @Override
    public void configureServlets() {
      bind(TestRootCollection.class);

      install(
          new RestApiModule() {
            @Override
            public void configure() {
              DynamicMap.mapOf(binder(), TEST_KIND);

              postOnCollection(TEST_KIND).to(TestPostOnCollection.class);
              post(TEST_KIND, "update").to(TestPost.class);
              get(TEST_KIND, "detail").to(TestGet.class);
            }
          });

      serveRegex("/(?:a/)?test-collection/(.*)$").with(TestRestApiServlet.class);
    }
  }

  @Singleton
  static class TestRestApiServlet extends RestApiServlet {
    private static final long serialVersionUID = 1L;

    @Inject
    TestRestApiServlet(RestApiServlet.Globals globals, Provider<TestRootCollection> collection) {
      super(globals, collection);
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse)
        throws ServletException, IOException {
      // This is...unfortunate. HttpPluginServlet (and/or ContextMapper) doesn't properly set the
      // servlet path on the wrapped request. Based on what RestApiServlet produces for non-plugin
      // requests, it should be:
      //   contextPath = "/plugins/checks"
      //   servletPath = "/checkers/"
      //   pathInfo = checkerUuid
      // Instead it does:
      //   contextPath = "/plugins/checks"
      //   servletPath = ""
      //   pathInfo = "/checkers/" + checkerUuid
      // This results in RestApiServlet splitting the pathInfo into ["", "checkers", checkerUuid],
      // and it passes the "" to CheckersCollection#parse, which understandably, but unfortunately,
      // fails.
      //
      // This frankly seems like a bug that should be fixed, but it would quite likely break
      // existing plugins in confusing ways. So, we work around it by introducing our own request
      // wrapper with the correct paths.
      HttpServletRequest req = (HttpServletRequest) servletRequest;
      String pathInfo = req.getPathInfo();
      String correctServletPath = "/test-collection/";
      String fixedPathInfo = pathInfo.substring(correctServletPath.length());
      HttpServletRequestWrapper wrapped =
          new HttpServletRequestWrapper(req) {
            @Override
            public String getServletPath() {
              return correctServletPath;
            }

            @Override
            public String getPathInfo() {
              return fixedPathInfo;
            }
          };

      super.service(wrapped, (HttpServletResponse) servletResponse);
    }
  }

  static class TestPluginResource implements RestResource {}

  @Singleton
  static class TestRootCollection implements ChildCollection<TopLevelResource, TestPluginResource> {
    private final DynamicMap<RestView<TestPluginResource>> views;

    @Inject
    TestRootCollection(DynamicMap<RestView<TestPluginResource>> views) {
      this.views = views;
    }

    @Override
    public RestView<TopLevelResource> list() throws RestApiException {
      return (RestReadView<TopLevelResource>)
          resource -> Response.ok(ImmutableList.of("one", "two"));
    }

    @Override
    public TestPluginResource parse(TopLevelResource parent, IdString id) throws Exception {
      return new TestPluginResource();
    }

    @Override
    public DynamicMap<RestView<TestPluginResource>> views() {
      return views;
    }
  }

  @Singleton
  static class TestPostOnCollection
      implements RestCollectionModifyView<TopLevelResource, TestPluginResource, String> {
    @Override
    public Response<String> apply(TopLevelResource parentResource, String input) throws Exception {
      return Response.ok("test");
    }
  }

  @Singleton
  static class TestPost implements RestModifyView<TestPluginResource, String> {
    @Override
    public Response<String> apply(TestPluginResource resource, String input) throws Exception {
      return Response.ok("test");
    }
  }

  @Singleton
  static class TestGet implements RestReadView<TestPluginResource> {

    @Option(name = "--crash")
    String crash;

    @Override
    public Response<String> apply(TestPluginResource resource) throws Exception {
      if (!Strings.nullToEmpty(crash).isEmpty()) {
        throw new IllegalStateException();
      }
      return Response.ok("test");
    }
  }

  @Test
  public void testEndpoints() throws Exception {
    try (AutoCloseable ignored =
        installPlugin(PLUGIN_NAME, null, MyPluginHttpModule.class, null, null)) {
      RestApiCallHelper.execute(adminRestSession, TEST_CALLS.asList());
    }
  }

  @Test
  public void testOptionOnSingletonIsIgnored() throws Exception {
    try (AutoCloseable ignored =
        installPlugin(PLUGIN_NAME, null, MyPluginHttpModule.class, null, null)) {
      RestApiCallHelper.execute(
          adminRestSession,
          RestCall.get("/plugins/" + PLUGIN_NAME + "/test-collection/1/detail?crash=xyz"));
    }
  }
}