1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.xml.secure;
19
20 import java.util.function.BooleanSupplier;
21 import java.util.function.Supplier;
22
23 import javax.xml.parsers.DocumentBuilderFactory;
24 import javax.xml.parsers.FactoryConfigurationError;
25 import javax.xml.parsers.ParserConfigurationException;
26 import javax.xml.transform.Source;
27 import javax.xml.transform.TransformerException;
28 import javax.xml.transform.URIResolver;
29 import javax.xml.transform.dom.DOMSource;
30
31 import org.w3c.dom.Document;
32
33 /**
34 * {@link URIResolver} floor: consults an optional caller-supplied resolver and ignores (resolves to empty) whatever the caller does not resolve.
35 * <p>
36 * The XSLT counterpart of {@link FallbackIgnoreEntityResolver2}, guarding {@code xsl:import}/{@code xsl:include} at compile time and {@code document()} at
37 * transform time. The secure {@link javax.xml.transform.TransformerFactory} and {@link javax.xml.transform.Transformer} wrappers install one of these and
38 * route a caller-set resolver through {@link #setDelegate} rather than letting it replace the floor. A caller opts a specific URI in by returning a
39 * non-{@code null} {@link Source}; anything left unresolved resolves to an empty {@link Source}, so the external resource is neither fetched nor leaked.
40 * </p>
41 * <p>
42 * The shape of that empty {@link Source} is supplied by the caller: the default is a well-formed empty DOM document (which every stock TrAX consumer accepts),
43 * while the Saxon path supplies {@code EmptySource.getInstance()} so its consumers get the "empty" shape they expect.
44 * </p>
45 * <p>
46 * An opted-in {@link javax.xml.transform.stream.StreamSource} or reader-less {@link javax.xml.transform.sax.SAXSource} is rewritten to carry a secure reader
47 * before it is returned, so the implementation parses the opted-in content on the same floor instead of with an internal reader at its own defaults. A
48 * {@link javax.xml.transform.dom.DOMSource} or a {@link javax.xml.transform.sax.SAXSource} carrying the caller's own reader is returned as-is.
49 * </p>
50 */
51 final class FallbackIgnoreURIResolver implements URIResolver {
52
53 /**
54 * Backing for the default ignore outcome. Consumers parse the resolved {@link Source}, and an empty character stream is not a well-formed XML document
55 * (XSLTC rejects it for {@code document()} and for an ignored {@code xsl:include}/{@code xsl:import}), so the default supplier answers with a well-formed
56 * empty document that evaluates to no content. It is never mutated, so one instance serves every resolution.
57 *
58 * @see #newEmptyDocument()
59 */
60 private static final Document EMPTY_DOCUMENT;
61
62 static {
63 EMPTY_DOCUMENT = newEmptyDocument();
64 }
65
66 /**
67 * Creates a new empty document.
68 *
69 * @return a new empty document.
70 * @throws SecureException Thrown if a {@link DocumentBuilder} cannot be created which satisfies the configuration requested.
71 * @throws ExceptionInInitializerError Thrown from a factory in case of a {@link java.util.ServiceConfigurationError service
72 * configuration error} or if the implementation is not available or cannot be instantiated.
73 */
74 private static Document newEmptyDocument() {
75 try {
76 return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
77 } catch (final ParserConfigurationException e) {
78 throw new ExceptionInInitializerError(e);
79 }
80 }
81
82 private URIResolver delegate;
83
84 /**
85 * Produces the empty {@link Source} returned for an unresolved reference; a new value per call keeps callers from mutating a shared Source.
86 */
87 private final Supplier<Source> emptySource;
88
89 /**
90 * Whether the opted-in rewrite should use the pluggable parser lookup instead of the platform's built-in parser; read per resolution so the factory-level floor tracks a later
91 * {@value SecureSAXParserFactory#OVERRIDE_DEFAULT_PARSER} toggle.
92 */
93 private final BooleanSupplier overrideDefaultParser;
94
95 /**
96 * Constructs a new resolver.
97 *
98 * @param delegate the resolver to delegate resolution to; may be {@code null}.
99 * @param emptySource the empty-{@link Source} supplier for the ignore outcome, or {@code null} for the default empty DOM document.
100 * @param overrideDefaultParser whether the opted-in rewrite should use the pluggable parser lookup instead of the platform's built-in parser, read at each resolution.
101 */
102 FallbackIgnoreURIResolver(final URIResolver delegate, final Supplier<Source> emptySource, final BooleanSupplier overrideDefaultParser) {
103 this.delegate = delegate;
104 this.emptySource = emptySource != null ? emptySource : () -> new DOMSource(EMPTY_DOCUMENT);
105 this.overrideDefaultParser = overrideDefaultParser;
106 }
107
108 /**
109 * Gets the delegate provided by the constructor or set by {@link #setDelegate}, may be {@code null}.
110 *
111 * @return The delegate provided by the constructor or set by {@link #setDelegate}, may be {@code null}.
112 */
113 URIResolver getDelegate() {
114 return delegate;
115 }
116
117 /**
118 * {@inheritDoc}
119 *
120 * @throws FactoryConfigurationError Thrown from a factory in case of a {@link java.util.ServiceConfigurationError service
121 * configuration error} or if the implementation is not available or cannot be instantiated.
122 */
123 @Override
124 public Source resolve(final String href, final String base) throws TransformerException {
125 final Source resolved = delegate != null ? delegate.resolve(href, base) : null;
126 if (resolved != null) {
127 // The implementation parses the opted-in handle with an internal reader at its own defaults; the rewrite hands it a secure reader instead.
128 return SecureSAXParserFactory.secure(resolved, overrideDefaultParser.getAsBoolean());
129 }
130 if (SecureException.throwOnUnresolved()) {
131 throw new TransformerException(SecureException.forbidden("uri", null, null, href, base));
132 }
133 return emptySource.get();
134 }
135
136 /**
137 * Sets the delegate to consult first, replacing any previous delegate. A {@code null} value removes the delegate and leaves a pure ignore-all floor.
138 *
139 * @param delegate The delegate to consult first, or {@code null} for a pure ignore-all floor.
140 */
141 void setDelegate(final URIResolver delegate) {
142 this.delegate = delegate;
143 }
144 }