dpol1 commented on code in PR #2116:
URL: https://github.com/apache/stormcrawler/pull/2116#discussion_r3947732988
##########
external/tika/src/main/java/org/apache/stormcrawler/tika/ParserBolt.java:
##########
@@ -162,11 +162,43 @@ public void execute(Tuple tuple) {
// check that the mimetype is in the whitelist
if (!mimeTypeWhiteList.isEmpty()) {
boolean mt_match = false;
- // see if a mimetype was guessed in JSOUPBolt
+ // parse.Content-Type is assumed byte-detected (JSoupParserBolt
uses Tika detection,
+ // not the raw server header). A custom upstream writing a
header-copied value bypasses
+ // this check — that is a caller responsibility.
String mimeType = metadata.getFirstValue("parse.Content-Type");
- // otherwise rely on what could have been obtained from HTTP
if (mimeType == null) {
- mimeType = metadata.getFirstValue(HttpHeaders.CONTENT_TYPE,
this.protocolMDprefix);
+ // parse.Content-Type is absent: detect from content bytes so
that
+ // the whitelist is evaluated against the same type Tika will
use
+ // to select a parser, not the server-declared HTTP header
which is
+ // untrusted and may differ from what the bytes actually are.
+ String httpCTHint =
+ metadata.getFirstValue(HttpHeaders.CONTENT_TYPE,
this.protocolMDprefix);
+ org.apache.tika.metadata.Metadata detectionMd =
+ new org.apache.tika.metadata.Metadata();
+ if (StringUtils.isNotBlank(httpCTHint)) {
+ // pass the header as a hint only — detect() weighs it but
+ // content bytes take precedence
Review Comment:
Not quite: for bytes with no magic match Tika returns
`application/octet-stream` and `applyHint` swaps in any hint that specialises
it, which every type does. So on unrecognised content the server header wins,
and the "undetectable content is now rejected" note in the description only
holds when no `Content-Type` header was sent. The result still matches what
`AutoDetectParser` dispatches on, so the change is fine, but say "the hint
narrows the magic result" rather than "bytes take precedence".
##########
external/tika/src/test/java/org/apache/stormcrawler/tika/ParserBoltWhitelistDetectionTest.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.stormcrawler.tika;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.http.HttpHeaders;
+import org.apache.storm.task.OutputCollector;
+import org.apache.stormcrawler.Constants;
+import org.apache.stormcrawler.Metadata;
+import org.apache.stormcrawler.TestUtil;
+import org.apache.stormcrawler.parse.ParsingTester;
+import org.apache.stormcrawler.persistence.Status;
+import org.apache.stormcrawler.protocol.ProtocolResponse;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Regression test for: when no parse.Content-Type is present, ParserBolt must
evaluate
+ * parser.mimetype.whitelist against the byte-detected MIME type (via
tika.detect()), not the
+ * server-declared HTTP Content-Type header. Previously the whitelist checked
the header while
+ * Tika's AutoDetectParser dispatched on the bytes, allowing a server to claim
a whitelisted type
+ * while serving arbitrary content.
+ */
+class ParserBoltWhitelistDetectionTest extends ParsingTester {
+
+ @BeforeEach
+ void setupParserBolt() {
+ bolt = new ParserBolt();
+ setupParserBolt(bolt);
+ }
+
+ /**
+ * The whitelist allows Word documents (application/.+word.*). The server
header claims Word,
+ * but the body bytes are plain HTML. After the fix, detection on bytes
yields text/html which
+ * does NOT match the whitelist, so the document must be rejected with
ERROR.
+ */
+ @Test
+ void whitelistAppliesToTheDetectedType() throws IOException {
+ Map<String, Object> conf = new HashMap<>();
+ // the whitelist shipped by the archetypes
+ conf.put("parser.mimetype.whitelist", "application/.+word.*");
+ conf.put(ProtocolResponse.PROTOCOL_MD_PREFIX_PARAM, "http.");
+ bolt.prepare(conf, TestUtil.getMockedTopologyContext(), new
OutputCollector(output));
+
+ // no parse.Content-Type: no JSoupParserBolt upstream, or
detect.mimetype disabled
+ Metadata metadata = new Metadata();
+ metadata.addValue(
+ "http." + HttpHeaders.CONTENT_TYPE,
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
+
+ // the body is NOT a word document
+ byte[] content =
+ "<html><body><p>not a word document</p></body></html>"
+ .getBytes(StandardCharsets.UTF_8);
+ parse("https://example.org/doc.docx", content, metadata);
+
+ System.out.println("detected type: " +
metadata.getFirstValue("parse.Content-Type"));
Review Comment:
Leftover println, and this is where the assert belongs: check
`parse.Content-Type` starts with `text/html` here and in
`filenameHintInfluencesDetection`, otherwise the tests pass for any reason the
whitelist rejects or accepts. `whitelistUsesPreexistingParsedContentType` has
the same gap: HTML bytes pass whether or not the bolt re-detects; plain text at
a `.txt` URL with `parse.Content-Type` preset to `text/html` would prove the
preset value is trusted.
##########
external/tika/src/main/java/org/apache/stormcrawler/tika/ParserBolt.java:
##########
@@ -162,11 +162,43 @@ public void execute(Tuple tuple) {
// check that the mimetype is in the whitelist
if (!mimeTypeWhiteList.isEmpty()) {
boolean mt_match = false;
- // see if a mimetype was guessed in JSOUPBolt
+ // parse.Content-Type is assumed byte-detected (JSoupParserBolt
uses Tika detection,
+ // not the raw server header). A custom upstream writing a
header-copied value bypasses
+ // this check — that is a caller responsibility.
String mimeType = metadata.getFirstValue("parse.Content-Type");
- // otherwise rely on what could have been obtained from HTTP
if (mimeType == null) {
- mimeType = metadata.getFirstValue(HttpHeaders.CONTENT_TYPE,
this.protocolMDprefix);
+ // parse.Content-Type is absent: detect from content bytes so
that
+ // the whitelist is evaluated against the same type Tika will
use
+ // to select a parser, not the server-declared HTTP header
which is
+ // untrusted and may differ from what the bytes actually are.
+ String httpCTHint =
+ metadata.getFirstValue(HttpHeaders.CONTENT_TYPE,
this.protocolMDprefix);
+ org.apache.tika.metadata.Metadata detectionMd =
+ new org.apache.tika.metadata.Metadata();
+ if (StringUtils.isNotBlank(httpCTHint)) {
+ // pass the header as a hint only — detect() weighs it but
+ // content bytes take precedence
+
detectionMd.set(org.apache.tika.metadata.Metadata.CONTENT_TYPE, httpCTHint);
+ }
+ // pass the filename so detection matches what the parser
dispatches on;
+ // without it, an ambiguous byte sequence (e.g. plain text
with a .html
+ // extension) can resolve differently here than at parse time
+ try {
+ URL _url = URLUtil.toURL(url);
+ detectionMd.set(TikaCoreProperties.RESOURCE_NAME_KEY,
_url.getFile());
+ } catch (MalformedURLException e1) {
+ throw new IllegalStateException("Malformed URL", e1);
+ }
+ try {
+ mimeType = tika.detect(new ByteArrayInputStream(content),
detectionMd);
+ } catch (IOException e) {
+ LOG.warn("Failed to detect MIME type for {}: {}", url,
e.getMessage());
+ }
+ if (mimeType != null) {
+ // write back so downstream code and metadata consumers see
+ // the same value (avoids a second detection pass)
Review Comment:
The parse path never reads `parse.Content-Type`, `AutoDetectParser` detects
again, and on success the `parse.` copy loop overwrites this. The write-back
only survives on the rejected tuple, which is useful when debugging a
rejection, so keep it but fix the comment.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]