QPID-8273: [Broker-J] Add switch to force message validation

This closes #19

(cherry picked from commit a1fbde2bac77c9305a4347876c6a27409361ec77)
diff --git a/broker-core/src/test/java/org/apache/qpid/server/protocol/v0_8/FieldTableTest.java b/broker-core/src/test/java/org/apache/qpid/server/protocol/v0_8/FieldTableTest.java
index e932eff..2b304ea 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/protocol/v0_8/FieldTableTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/protocol/v0_8/FieldTableTest.java
@@ -929,6 +929,46 @@
         assertTrue("unexpected property value", destinationTable.getBoolean(myBooleanTestProperty));
     }
 
+    public void testValidateMalformedFieldTable()
+    {
+        final FieldTable fieldTable = buildMalformedFieldTable();
+
+        try
+        {
+            fieldTable.validate();
+            fail("Exception is expected");
+        }
+        catch (RuntimeException e)
+        {
+            // pass
+        }
+    }
+
+    public void testValidateCorrectFieldTable()
+    {
+        final FieldTable ft = FieldTable.convertToFieldTable(Collections.singletonMap("testKey", "testValue"));
+        final int encodedSize = (int)ft.getEncodedSize() + Integer.BYTES;
+        final QpidByteBuffer buf = QpidByteBuffer.allocate(encodedSize);
+        ft.writeToBuffer(buf);
+        buf.flip();
+        buf.position(Integer.BYTES);
+
+        final FieldTable fieldTable = new FieldTable(buf);
+        assertEquals(1, fieldTable.size());
+        fieldTable.validate();
+        assertTrue("Expected key is not found", fieldTable.containsKey("testKey"));
+    }
+
+    private FieldTable buildMalformedFieldTable()
+    {
+        final QpidByteBuffer buf = QpidByteBuffer.allocate(1);
+        buf.put((byte) -1);
+
+        buf.flip();
+
+        return new FieldTable(buf);
+    }
+
     private void assertBytesEqual(byte[] expected, byte[] actual)
     {
         Assert.assertEquals(expected.length, actual.length);
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java
index 595b726..ca3e8be 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java
@@ -129,6 +129,7 @@
 
 
     private final Pre0_10CreditManager _creditManager;
+    private final boolean _forceMessageValidation;
 
 
     /**
@@ -233,6 +234,8 @@
             }
         }),_accessControllerContext);
 
+        _forceMessageValidation = connection.getContextValue(Boolean.class, AMQPConnection_0_8.FORCE_MESSAGE_VALIDATION);
+
     }
 
     private void message(final LogMessage message)
@@ -2198,7 +2201,17 @@
             }
             else
             {
-                publishContentHeader(new ContentHeaderBody(properties, bodySize));
+                if (!_forceMessageValidation || properties.checkValid())
+                {
+                    publishContentHeader(new ContentHeaderBody(properties, bodySize));
+                }
+                else
+                {
+                    properties.dispose();
+                    _connection.sendConnectionClose(ErrorCodes.FRAME_ERROR,
+                                                    "Attempt to send a malformed content header",
+                                                    _channelId);
+                }
             }
         }
         else
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQPConnection_0_8.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQPConnection_0_8.java
index 35f787a..1943dfa 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQPConnection_0_8.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQPConnection_0_8.java
@@ -51,6 +51,11 @@
     @ManagedContextDefault(name= BATCH_LIMIT)
     long DEFAULT_BATCH_LIMIT = 10L;
 
+    String FORCE_MESSAGE_VALIDATION = "qpid.connection.forceValidation";
+    @SuppressWarnings("unused")
+    @ManagedContextDefault(name= FORCE_MESSAGE_VALIDATION)
+    boolean DEFAULT_FORCE_MESSAGE_VALIDATION = false;
+
     @DerivedAttribute(description = "The actual negotiated value of heartbeat delay.")
     int getHeartbeatDelay();
 
diff --git a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java
index 94522ea..4157e44 100644
--- a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java
+++ b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java
@@ -123,6 +123,7 @@
         when(_amqConnection.getContextValue(Long.class, Session.PRODUCER_AUTH_CACHE_TIMEOUT)).thenReturn(Session.PRODUCER_AUTH_CACHE_TIMEOUT_DEFAULT);
         when(_amqConnection.getContextValue(Integer.class, Session.PRODUCER_AUTH_CACHE_SIZE)).thenReturn(Session.PRODUCER_AUTH_CACHE_SIZE_DEFAULT);
         when(_amqConnection.getContextValue(Long.class, Connection.MAX_UNCOMMITTED_IN_MEMORY_SIZE)).thenReturn(Connection.DEFAULT_MAX_UNCOMMITTED_IN_MEMORY_SIZE);
+        when(_amqConnection.getContextValue(Boolean.class, AMQPConnection_0_8.FORCE_MESSAGE_VALIDATION)).thenReturn(true);
         when(_amqConnection.getTaskExecutor()).thenReturn(taskExecutor);
         when(_amqConnection.getChildExecutor()).thenReturn(taskExecutor);
         when(_amqConnection.getModel()).thenReturn(BrokerModel.getInstance());
diff --git a/systests/protocol-tests-amqp-0-8/src/test/java/org/apache/qpid/tests/protocol/v0_8/extension/basic/MalformedMessageValidation.java b/systests/protocol-tests-amqp-0-8/src/test/java/org/apache/qpid/tests/protocol/v0_8/extension/basic/MalformedMessageValidation.java
new file mode 100644
index 0000000..6391081
--- /dev/null
+++ b/systests/protocol-tests-amqp-0-8/src/test/java/org/apache/qpid/tests/protocol/v0_8/extension/basic/MalformedMessageValidation.java
@@ -0,0 +1,87 @@
+/*
+ *
+ * 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.qpid.tests.protocol.v0_8.extension.basic;
+
+import static org.apache.qpid.tests.utils.BrokerAdmin.KIND_BROKER_J;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.protocol.v0_8.FieldTable;
+import org.apache.qpid.server.protocol.v0_8.FieldTableFactory;
+import org.apache.qpid.server.protocol.v0_8.transport.ChannelOpenOkBody;
+import org.apache.qpid.server.protocol.v0_8.transport.ConnectionCloseBody;
+import org.apache.qpid.tests.protocol.v0_8.FrameTransport;
+import org.apache.qpid.tests.protocol.v0_8.Interaction;
+import org.apache.qpid.tests.utils.BrokerAdmin;
+import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
+import org.apache.qpid.tests.utils.BrokerSpecific;
+import org.apache.qpid.tests.utils.ConfigItem;
+
+@BrokerSpecific(kind = KIND_BROKER_J)
+@ConfigItem(name = "qpid.connection.forceValidation", value = "true")
+public class MalformedMessageValidation extends BrokerAdminUsingTestBase
+{
+    private InetSocketAddress _brokerAddress;
+    private static final String CONTENT_TEXT = "Test";
+
+    @Before
+    public void setUp()
+    {
+        _brokerAddress = getBrokerAdmin().getBrokerAddress(BrokerAdmin.PortType.ANONYMOUS_AMQP);
+        getBrokerAdmin().createQueue(BrokerAdmin.TEST_QUEUE_NAME);
+    }
+
+    @Test
+    public void malformedHeaderValue() throws Exception
+    {
+        final FieldTable malformedHeader = createMalformedHeaders();
+        byte[] contentBytes = CONTENT_TEXT.getBytes(StandardCharsets.UTF_8);
+        try(FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = transport.newInteraction();
+            interaction.openAnonymousConnection()
+                       .channel().open().consumeResponse(ChannelOpenOkBody.class)
+                       .basic().publishExchange("")
+                       .publishRoutingKey(BrokerAdmin.TEST_QUEUE_NAME)
+                       .contentHeaderPropertiesHeaders(malformedHeader)
+                       .content(contentBytes)
+                       .publishMessage()
+                       .consumeResponse(ConnectionCloseBody.class);
+        }
+        assertThat(getBrokerAdmin().getQueueDepthMessages(BrokerAdmin.TEST_QUEUE_NAME), is(equalTo(0)));
+    }
+
+    private static FieldTable createMalformedHeaders()
+    {
+        final QpidByteBuffer buf = QpidByteBuffer.allocate(1);
+        buf.put((byte) -1);
+        buf.flip();
+        return FieldTableFactory.createFieldTable(buf);
+    }
+}