forked from jenkinsci/jenkins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApi.java
More file actions
366 lines (327 loc) · 14.1 KB
/
Api.java
File metadata and controls
366 lines (327 loc) · 14.1 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Seiji Sogabe
*
* 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.
*/
package hudson.model;
import hudson.ExtensionList;
import hudson.Util;
import io.jenkins.servlet.ServletExceptionWrapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.stream.StreamResult;
import jenkins.model.Jenkins;
import jenkins.security.SecureRequester;
import jenkins.security.stapler.StaplerNotDispatchable;
import jenkins.util.SystemProperties;
import jenkins.util.xml.FilteredFunctionContext;
import org.dom4j.CharacterData;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.StaplerResponse2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.Flavor;
import org.kohsuke.stapler.export.Model;
import org.kohsuke.stapler.export.ModelBuilder;
import org.kohsuke.stapler.export.NamedPathPruner;
import org.kohsuke.stapler.export.SchemaGenerator;
import org.kohsuke.stapler.export.TreePruner;
import org.kohsuke.stapler.export.TreePruner.ByDepth;
/**
* Used to expose remote access API for ".../api/"
*
* <p>
* If the parent object has a {@code _api.jelly} view, it will be included
* in the api index page.
*
* @author Kohsuke Kawaguchi
* @see Exported
* @see SecureRequester
*/
public class Api extends AbstractModelObject {
/**
* Model object to be exposed as XML/JSON/etc.
*/
public final Object bean;
public Api(Object bean) {
this.bean = bean;
}
@Override
public String getDisplayName() {
return "API";
}
@Override
public String getSearchUrl() {
return "api";
}
/**
* Exposes the bean as XML.
*/
public void doXml(StaplerRequest2 req, StaplerResponse2 rsp,
@QueryParameter String xpath,
@QueryParameter String wrapper,
@QueryParameter String tree,
@QueryParameter int depth) throws IOException, ServletException {
setHeaders(rsp);
if (!checkHeapForApiResponse(rsp)) {
return;
}
String[] excludes = req.getParameterValues("exclude");
if (xpath == null && excludes == null) {
// serve the whole thing
rsp.serveExposedBean(req, bean, Flavor.XML);
return;
}
StringWriter sw = new StringWriter();
// first write to String
Model p = MODEL_BUILDER.get(bean.getClass());
TreePruner pruner = tree != null ? new NamedPathPruner(tree) : new ByDepth(1 - depth);
p.writeTo(bean, pruner, Flavor.XML.createDataWriter(bean, sw));
// apply XPath
FilteredFunctionContext functionContext = new FilteredFunctionContext();
Object result;
try {
Document dom = new SAXReader().read(new StringReader(sw.toString()));
// apply exclusions
if (excludes != null) {
for (String exclude : excludes) {
XPath xExclude = dom.createXPath(exclude);
xExclude.setFunctionContext(functionContext);
List<org.dom4j.Node> list = xExclude.selectNodes(dom);
for (org.dom4j.Node n : list) {
Element parent = n.getParent();
if (parent != null)
parent.remove(n);
}
}
}
if (xpath == null) {
result = dom;
} else {
XPath comp = dom.createXPath(xpath);
comp.setFunctionContext(functionContext);
List list = comp.selectNodes(dom);
if (wrapper != null) {
// check if the wrapper is a valid entity name
// First position: letter or underscore
// Other positions: \w (letter, number, underscore), dash or dot
String validNameRE = "^[a-zA-Z_][\\w-\\.]*$";
if (!wrapper.matches(validNameRE)) {
rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
rsp.getWriter().print(Messages.Api_WrapperParamInvalid());
return;
}
Element root = DocumentFactory.getInstance().createElement(wrapper);
for (Object o : list) {
if (o instanceof String) {
root.addText(o.toString());
} else {
root.add(((org.dom4j.Node) o).detach());
}
}
result = root;
} else if (list.isEmpty()) {
rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
rsp.getWriter().print(Messages.Api_NoXPathMatch(xpath));
return;
} else if (list.size() > 1) {
rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
rsp.getWriter().print(Messages.Api_MultipleMatch(xpath, list.size()));
return;
} else {
result = list.getFirst();
}
}
} catch (DocumentException e) {
LOGGER.log(Level.FINER, "Failed to do XPath/wrapper handling. XML is as follows:" + sw, e);
throw new IOException("Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.", e);
}
if (isSimpleOutput(result) && !permit(req)) {
// simple output prohibited
rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "primitive XPath result sets forbidden; implement jenkins.security.SecureRequester");
return;
}
try (OutputStream o = rsp.getOutputStream()) {
if (isSimpleOutput(result)) {
// simple output allowed
rsp.setContentType("text/plain;charset=UTF-8");
String text = result instanceof CharacterData ? ((CharacterData) result).getText() : result.toString();
o.write(text.getBytes(StandardCharsets.UTF_8));
return;
}
// otherwise XML
rsp.setContentType("application/xml;charset=UTF-8");
new XMLWriter(o).write(result);
}
}
private boolean isSimpleOutput(Object result) {
return result instanceof CharacterData || result instanceof String || result instanceof Number || result instanceof Boolean;
}
/**
* Generate schema.
*/
public void doSchema(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
setHeaders(rsp);
rsp.setContentType("application/xml");
StreamResult r = new StreamResult(rsp.getOutputStream());
new SchemaGenerator(new ModelBuilder().get(bean.getClass())).generateSchema(r);
r.getOutputStream().close();
}
/**
* Exposes the bean as JSON.
*/
public void doJson(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
if (Util.isOverridden(Api.class, getClass(), "doJson", StaplerRequest.class, StaplerResponse.class)) {
try {
doJson(StaplerRequest.fromStaplerRequest2(req), StaplerResponse.fromStaplerResponse2(rsp));
} catch (javax.servlet.ServletException e) {
throw ServletExceptionWrapper.toJakartaServletException(e);
}
} else {
doJsonImpl(req, rsp);
}
}
/**
* @deprecated use {@link #doJson(StaplerRequest2, StaplerResponse2)}
*/
@Deprecated
@StaplerNotDispatchable
public void doJson(StaplerRequest req, StaplerResponse rsp) throws IOException, javax.servlet.ServletException {
try {
doJsonImpl(StaplerRequest.toStaplerRequest2(req), StaplerResponse.toStaplerResponse2(rsp));
} catch (ServletException e) {
throw ServletExceptionWrapper.fromJakartaServletException(e);
}
}
private void doJsonImpl(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
if (req.getParameter("jsonp") == null || permit(req)) {
setHeaders(rsp);
if (!checkHeapForApiResponse(rsp)) {
return;
}
rsp.serveExposedBean(req, bean, req.getParameter("jsonp") == null ? Flavor.JSON : Flavor.JSONP);
} else {
rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "jsonp forbidden; implement jenkins.security.SecureRequester");
}
}
/**
* Exposes the bean as Python literal.
*/
public void doPython(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
if (Util.isOverridden(Api.class, getClass(), "doPython", StaplerRequest.class, StaplerResponse.class)) {
try {
doPython(StaplerRequest.fromStaplerRequest2(req), StaplerResponse.fromStaplerResponse2(rsp));
} catch (javax.servlet.ServletException e) {
throw ServletExceptionWrapper.toJakartaServletException(e);
}
} else {
doPythonImpl(req, rsp);
}
}
/**
* @deprecated use {@link #doPython(StaplerRequest2, StaplerResponse2)}
*/
@Deprecated
@StaplerNotDispatchable
public void doPython(StaplerRequest req, StaplerResponse rsp) throws IOException, javax.servlet.ServletException {
try {
doPythonImpl(StaplerRequest.toStaplerRequest2(req), StaplerResponse.toStaplerResponse2(rsp));
} catch (ServletException e) {
throw ServletExceptionWrapper.fromJakartaServletException(e);
}
}
private void doPythonImpl(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
setHeaders(rsp);
if (!checkHeapForApiResponse(rsp)) {
return;
}
rsp.serveExposedBean(req, bean, Flavor.PYTHON);
}
private boolean permit(StaplerRequest2 req) {
for (SecureRequester r : ExtensionList.lookup(SecureRequester.class)) {
if (r.permit(req, bean)) {
return true;
}
}
return false;
}
/**
* Checks if there is sufficient heap memory before processing a potentially large API response.
* Large serialization operations (especially without the tree parameter) can cause OutOfMemoryError.
*
* @param rsp the response to send error to if heap is low
* @return true if it is safe to proceed, false if the request was rejected
* @see <a href="https://issues.jenkins.io/browse/JENKINS-75747">JENKINS-75747</a>
*/
private boolean checkHeapForApiResponse(StaplerResponse2 rsp) throws IOException {
long minFreeBytes = SystemProperties.getLong(Api.class.getName() + ".minFreeMemoryBytes", 50L * 1024 * 1024);
if (minFreeBytes <= 0) {
return true;
}
Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
long totalMemory = rt.totalMemory();
long freeMemory = rt.freeMemory();
long usedMemory = totalMemory - freeMemory;
long availableMemory = maxMemory - usedMemory;
if (availableMemory >= minFreeBytes) {
return true;
}
LOGGER.warning(() -> String.format(
"Rejecting API request due to low heap: available=%d, required=%d. Suggest using the tree parameter.",
availableMemory, minFreeBytes));
rsp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
rsp.setContentType("text/plain;charset=UTF-8");
rsp.getWriter().print(Messages.Api_LowMemory());
return false;
}
@Restricted(NoExternalUse.class)
protected void setHeaders(StaplerResponse2 rsp) {
rsp.setHeader("X-Jenkins", Jenkins.VERSION);
rsp.setHeader("X-Jenkins-Session", Jenkins.SESSION_HASH);
// to be really defensive against dumb browsers not taking into consideration the content-type being set
rsp.setHeader("X-Content-Type-Options", "nosniff");
// recommended by OWASP: https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html#security-headers
rsp.setHeader("X-Frame-Options", "deny");
}
private static final Logger LOGGER = Logger.getLogger(Api.class.getName());
private static final ModelBuilder MODEL_BUILDER = new ModelBuilder();
}