Line data Source code
1 : // Copyright (C) 2022 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.httpd.raw; 16 : 17 : import static com.google.gerrit.server.experiments.ExperimentFeaturesConstants.GERRIT_BACKEND_FEATURE_ATTACH_NONCE_TO_DOCUMENTATION; 18 : 19 : import com.google.common.cache.Cache; 20 : import com.google.gerrit.httpd.HtmlDomUtil; 21 : import com.google.gerrit.server.experiments.ExperimentFeatures; 22 : import java.nio.charset.StandardCharsets; 23 : import java.nio.file.Path; 24 : import java.util.Optional; 25 : import javax.servlet.http.HttpServletRequest; 26 : import javax.servlet.http.HttpServletResponse; 27 : 28 : abstract class DocServlet extends ResourceServlet { 29 : private static final long serialVersionUID = 1L; 30 : 31 : private final ExperimentFeatures experimentFeatures; 32 : 33 : DocServlet(Cache<Path, Resource> cache, boolean refresh, ExperimentFeatures experimentFeatures) { 34 100 : super(cache, refresh); 35 100 : this.experimentFeatures = experimentFeatures; 36 100 : } 37 : 38 : @Override 39 : protected boolean shouldProcessResourceBeforeServe( 40 : HttpServletRequest req, HttpServletResponse rsp, Path p) { 41 1 : String nonce = (String) req.getAttribute("nonce"); 42 1 : if (!experimentFeatures.isFeatureEnabled(GERRIT_BACKEND_FEATURE_ATTACH_NONCE_TO_DOCUMENTATION) 43 : || nonce == null) { 44 1 : return false; 45 : } 46 1 : return ResourceServlet.contentType(p.toString()).equals("text/html"); 47 : } 48 : 49 : @Override 50 : protected Resource processResourceBeforeServe( 51 : HttpServletRequest req, HttpServletResponse rsp, Resource resource) { 52 : // ResourceServlet doesn't set character encoding for a resource. Gerrit will 53 : // default to setting charset to utf-8, if none provided. So we guess UTF_8 here. 54 1 : Optional<String> updatedHtml = 55 1 : HtmlDomUtil.attachNonce( 56 1 : new String(resource.raw, StandardCharsets.UTF_8), (String) req.getAttribute("nonce")); 57 1 : if (updatedHtml.isEmpty()) { 58 0 : return resource; 59 : } 60 1 : return new Resource( 61 : resource.lastModified, 62 : resource.contentType, 63 1 : updatedHtml.get().getBytes(StandardCharsets.UTF_8)); 64 : } 65 : }