You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ws.apache.org by gi...@apache.org on 2011/09/18 15:51:36 UTC
svn commit: r1172285 [37/48] - in /webservices/wss4j/branches/swssf: ./
cxf-integration/ cxf-integration/src/ cxf-integration/src/main/
cxf-integration/src/main/java/ cxf-integration/src/main/java/org/
cxf-integration/src/main/java/org/swssf/ cxf-integ...
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/PerformanceTimingTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/PerformanceTimingTest.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/PerformanceTimingTest.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/PerformanceTimingTest.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,340 @@
+/**
+ * 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.swssf.test;
+
+import org.apache.ws.security.handler.WSHandlerConstants;
+import org.swssf.WSSec;
+import org.swssf.ext.Constants;
+import org.swssf.ext.OutboundWSSec;
+import org.swssf.ext.SecurePart;
+import org.swssf.ext.SecurityProperties;
+import org.swssf.securityEvent.SecurityEvent;
+import org.swssf.test.utils.XmlReaderToWriter;
+import org.testng.annotations.Test;
+import org.w3c.dom.Document;
+
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.*;
+import java.util.ArrayList;
+import java.util.Properties;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class PerformanceTimingTest extends AbstractTestBase {
+
+ private File prepareBigEncryptedFile(int factor) throws Exception {
+ File target = genBigFile(factor);
+ File output = new File("target/enc.xml");
+ doStreamingSecurityOutbound(target, output);
+ return output;
+ }
+
+ private void doStreamingSecurityOutbound(File source, File output) throws Exception {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ securityProperties.setEncryptionUser("receiver");
+ securityProperties.loadEncryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.addEncryptionPart(new SecurePart("test", "http://www.example.com", SecurePart.Modifier.Content));
+ securityProperties.setSignatureUser("transmitter");
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.ENCRYPT};
+ securityProperties.setOutAction(actions);
+ securityProperties.setTimestampTTL(60 * 60 * 24 * 7); //a week for testing:)
+
+ InputStream sourceDocument = new BufferedInputStream(new FileInputStream(source));
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(new FileOutputStream(output), "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(sourceDocument);
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+ xmlStreamReader.close();
+ }
+
+ private File genBigFile(int factor) throws IOException {
+ File source = new File("ReferenzInstanzdokument20060922.xml");
+ File target = new File("target/tmp.xml");
+ FileWriter fileWriter = new FileWriter(target);
+ fileWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
+ "<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
+ "<env:Header></env:Header>\n" +
+ "<env:Body><test xmlns=\"http://www.example.com\">");
+ fileWriter.close();
+ FileOutputStream fileOutputStream = new FileOutputStream(target, true);
+ for (int i = 0; i <= factor; i++) {
+ int read = 0;
+ byte[] buffer = new byte[4096];
+ FileInputStream fileInputStream = new FileInputStream(source);
+ while ((read = fileInputStream.read(buffer)) != -1) {
+ fileOutputStream.write(buffer, 0, read);
+ }
+ fileInputStream.close();
+ }
+ fileWriter = new FileWriter(target, true);
+ fileWriter.write("</test></env:Body>\n" +
+ "</env:Envelope>");
+ fileWriter.close();
+ return target;
+ }
+
+ /*
+ private int countTags(File file) throws Exception {
+ int tagCount = 0;
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new FileInputStream(file));
+ while (xmlStreamReader.hasNext()) {
+ int eventType = xmlStreamReader.next();
+ if (eventType == XMLStreamConstants.START_ELEMENT) {
+ tagCount++;
+ }
+ }
+ return tagCount;
+ }
+
+ @Test(groups = { "timing", "policy" })
+ public void setUp() throws Exception {
+ File input = prepareBigEncryptedFile(1);
+ doDOMInSecurity(input, false);
+ doStreamingInSecurity(input, false);
+ }
+
+ @Test(groups = "timing")
+ public void testStreamingTimePerformance() throws Exception {
+
+ FileWriter samples = new FileWriter("timing-samples.txt");
+
+ for (int i = 1; i <= 15; i++) {
+ System.out.println("Run " + i);
+ File input = prepareBigEncryptedFile(i * 10);
+
+ long start = System.currentTimeMillis();
+
+ int tagCount = doStreamingInSecurity(input, false);
+
+ samples.write("" + tagCount);
+ samples.write(" ");
+ samples.write("" + (System.currentTimeMillis() - start) / 1000.0);
+ samples.write(" ");
+ samples.flush();
+
+ System.out.println("Stream Time: " + (System.currentTimeMillis() - start) / 1000.0 + "s");
+ System.out.println("Tag Count: " + tagCount);
+ System.out.println("");
+ System.gc();
+
+ start = System.currentTimeMillis();
+
+ tagCount = doDOMInSecurity(input, true);
+
+ samples.write("" + (System.currentTimeMillis() - start) / 1000.0);
+ samples.write("\n");
+ samples.flush();
+
+ System.out.println("DOM Time: " + (System.currentTimeMillis() - start) / 1000.0 + "s");
+ System.out.println("Tag Count: " + tagCount);
+ System.out.println("");
+ System.gc();
+ System.out.println("Used memory: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024));
+ }
+
+ samples.close();
+ }
+*/
+ private int[] tagCounts = new int[]{33391, 63731, 94071, 124411, 154751, 185091, 215431, 245771, 276111, 306451, 336791, 367131, 397471, 427811, 458151};
+
+ @Test(groups = {"timing-out"})
+ public void setUpOut() throws Exception {
+ File input = genBigFile(1);
+ Document doc = doOutboundSecurityWithWSS4J(new FileInputStream(input), WSHandlerConstants.ENCRYPT, new Properties());
+ javax.xml.transform.Transformer transformer = TransformerFactory.newInstance().newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(new File("target/bigfile-dom.xml")));
+ doStreamingSecurityOutbound(input, new File("target/bigfile-stream.xml"));
+ }
+
+ @Test(groups = "timing-out")
+ public void testStreamingOutTimePerformance() throws Exception {
+
+ FileWriter samples = new FileWriter("timing-out-samples.txt");
+
+ for (int i = 1; i <= 15; i++) {
+ System.out.println("Run " + i);
+ File input = genBigFile(i * 10);
+
+ long start = System.currentTimeMillis();
+
+ doStreamingSecurityOutbound(input, new File("target/bigfile-stream.xml"));
+
+ samples.write("" + tagCounts[i - 1]);
+ samples.write(" ");
+ samples.write("" + (System.currentTimeMillis() - start) / 1000.0);
+ samples.write(" ");
+ samples.flush();
+
+ System.out.println("Stream Time: " + (System.currentTimeMillis() - start) / 1000.0 + "s");
+ System.out.println("Tag Count: " + tagCounts[i - 1]);
+ System.out.println("");
+ System.gc();
+
+ start = System.currentTimeMillis();
+
+ Document doc = doOutboundSecurityWithWSS4J(new FileInputStream(input), WSHandlerConstants.ENCRYPT, new Properties());
+ javax.xml.transform.Transformer transformer = TransformerFactory.newInstance().newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(new File("target/bigfile-dom.xml")));
+
+ samples.write("" + (System.currentTimeMillis() - start) / 1000.0);
+ samples.write("\n");
+ samples.flush();
+
+ System.out.println("DOM Time: " + (System.currentTimeMillis() - start) / 1000.0 + "s");
+ System.out.println("Tag Count: " + tagCounts[i - 1]);
+ System.out.println("");
+ System.gc();
+ System.out.println("Used memory: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024));
+ }
+
+ samples.close();
+ }
+/*
+ @Test(groups = "policy")
+ public void testPolicyTimePerformance() throws Exception {
+
+ FileWriter samples = new FileWriter("policy-timing-samples.txt");
+
+ for (int i = 1; i <= 15; i++) {
+ System.out.println("Run " + i);
+ File input = prepareBigEncryptedFile(i * 10);
+
+ long start = System.currentTimeMillis();
+
+ int tagCount = doStreamingInSecurity(input, true);
+
+ samples.write("" + tagCount);
+ samples.write(" ");
+ samples.write("" + (System.currentTimeMillis() - start) / 1000.0);
+ samples.write(" ");
+ samples.flush();
+
+ System.out.println("Stream Time: " + (System.currentTimeMillis() - start) / 1000.0 + "s");
+ System.out.println("Tag Count: " + tagCount);
+ System.out.println("");
+ System.gc();
+
+ start = System.currentTimeMillis();
+
+ tagCount = doDOMInSecurity(input, true);
+
+ samples.write("" + (System.currentTimeMillis() - start) / 1000.0);
+ samples.write("\n");
+ samples.flush();
+
+ System.out.println("DOM Time: " + (System.currentTimeMillis() - start) / 1000.0 + "s");
+ System.out.println("Tag Count: " + tagCount);
+ System.out.println("");
+ System.gc();
+ System.out.println("Used memory: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024));
+ }
+
+ samples.close();
+ }
+
+ private int doDOMInSecurity(File input, boolean doPolicy) throws Exception {
+ int tagCount;
+ String action = WSHandlerConstants.ENCRYPT;
+
+ XMLStreamReader xmlStreamReader = null;
+ if (doPolicy) {
+ MessageContext messageContext = doInboundSecurityWithWSS4J_1(documentBuilderFactory.newDocumentBuilder().parse(input), action);
+ System.out.println(messageContext);
+
+ Vector<WSHandlerResult> recv_results = (Vector<WSHandlerResult>)messageContext.getProperty(WSHandlerConstants.RECV_RESULTS);
+ for (int i = 0; i < recv_results.size(); i++) {
+ WSHandlerResult wsHandlerResult = recv_results.get(i);
+ Vector<WSSecurityEngineResult> wsSecurityEngineResults = wsHandlerResult.getResults();
+ for (int j = 0; j < wsSecurityEngineResults.size(); j++) {
+ WSSecurityEngineResult wsSecurityEngineResult = wsSecurityEngineResults.get(j);
+ if (((Integer)wsSecurityEngineResult.get(WSSecurityEngineResult.TAG_ACTION)) == WSConstants.ENCR) {
+ List<WSDataRef> dataRefUris = (List<WSDataRef>)wsSecurityEngineResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
+ //this is not correct but works for measuring
+ if (!dataRefUris.get(0).getName().equals(Constants.TAG_soap11_Body)) {
+ return 0;
+ }
+ }
+ }
+ }
+
+ } else {
+ Document document = doInboundSecurityWithWSS4J(documentBuilderFactory.newDocumentBuilder().parse(input), action);
+ xmlStreamReader = new W3CDOMStreamReader(document.getDocumentElement());
+ }
+
+ tagCount = 0;
+ while (xmlStreamReader.hasNext()) {
+ int eventType = xmlStreamReader.next();
+ if (eventType == XMLStreamConstants.START_ELEMENT) {
+ tagCount++;
+ }
+ }
+
+ xmlStreamReader.close();
+ return tagCount;
+ }
+
+ private int doStreamingInSecurity(File input, boolean doPolicy) throws Exception {
+ SecurityProperties inSecurityProperties = new SecurityProperties();
+ inSecurityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ inSecurityProperties.setCallbackHandler(new CallbackHandlerImpl());
+
+ PolicyEnforcer policyEnforcer = null;
+ if (doPolicy) {
+ System.out.println("Added policy");
+ PolicyEnforcerFactory policyEnforcerFactory = PolicyEnforcerFactory.newInstance(new File("policyPerformance.wsdl").toURI().toURL());
+ policyEnforcer = policyEnforcerFactory.newPolicyEnforcer(null);
+ inSecurityProperties.addInputProcessor(new PolicyInputProcessor(policyEnforcer, null));
+ }
+ InboundWSSec xmlSec = WSSec.getInboundWSSec(inSecurityProperties);
+ FileInputStream fileInputStream = new FileInputStream(input);
+ XMLStreamReader outXmlStreamReader = xmlSec.processInMessage(xmlInputFactory.createXMLStreamReader(fileInputStream), policyEnforcer);
+
+ int tagCount = 0;
+
+ try {
+ while (outXmlStreamReader.hasNext()) {
+ int eventType = outXmlStreamReader.next();
+ if (eventType == XMLStreamConstants.START_ELEMENT) {
+ tagCount++;
+ }
+ }
+ fileInputStream.close();
+ outXmlStreamReader.close();
+ } catch (XMLStreamException e) {
+ if (e.getCause() instanceof WSSPolicyException) {
+ //ignore
+ } else {
+ throw e;
+ }
+ }
+ return tagCount;
+ }
+ */
+}
Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/PerformanceTimingTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/ProfilingTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/ProfilingTest.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/ProfilingTest.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/ProfilingTest.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,227 @@
+/**
+ * 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.swssf.test;
+
+import org.swssf.WSSec;
+import org.swssf.ext.InboundWSSec;
+import org.swssf.ext.SecurityProperties;
+import org.swssf.test.utils.XmlReaderToWriter;
+import org.testng.annotations.Test;
+
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamReader;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class ProfilingTest extends AbstractTestBase {
+/*
+ @Test(invocationCount = 1)
+ public void testWSS4JOutbound() throws Exception {
+ InputStream sourceDocument = new BufferedInputStream(new FileInputStream("ICHAGCompany-3000.xml"));
+
+ String action = WSHandlerConstants.TIMESTAMP + " " + WSHandlerConstants.SIGNATURE + " " + WSHandlerConstants.ENCRYPT;
+ Document securedDocument = doOutboundSecurityWithWSS4J(sourceDocument, action, new Properties());
+
+ javax.xml.transform.Transformer transformer = TransformerFactory.newInstance().newTransformer();
+ transformer.transform(new DOMSource(securedDocument), new StreamResult(new FileOutputStream("ICHAGCompany-3000-sig-enc.xml")));
+ }
+ */
+
+ @Test(invocationCount = 1)
+ public void testStreamingSecOutbound() throws Exception {
+/*
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ securityProperties.setEncryptionUser("receiver");
+ securityProperties.loadEncryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("transmitter");
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.TIMESTAMP, Constants.Action.SIGNATURE, Constants.Action.ENCRYPT};
+ securityProperties.setOutAction(actions);
+ securityProperties.setTimestampTTL(60 * 60 * 24 * 7); //a week for testing:)
+
+ InputStream sourceDocument = new BufferedInputStream(new FileInputStream("ICHAGCompany-3000.xml"));
+ OutboundWSSec xmlSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = xmlSecOut.processOutMessage(new FileOutputStream("ICHAGCompany-3000-sig-enc.xml"));
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(sourceDocument);
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+ xmlStreamReader.close();
+
+ */
+ }
+
+
+/*
+ @Test(invocationCount = 1)
+ public void testWSS4JInbound() throws Exception {
+ InputStream sourceDocument = new FileInputStream("ICHAGCompany-3000-sig-enc.xml");
+ String action = WSHandlerConstants.TIMESTAMP + " " + WSHandlerConstants.SIGNATURE + " " + WSHandlerConstants.ENCRYPT;
+ Document document = doInboundSecurityWithWSS4J(documentBuilderFactory.newDocumentBuilder().parse(sourceDocument), action);
+ }
+*/
+
+ @Test(invocationCount = 1, dependsOnMethods = {"testStreamingSecOutbound"})
+ public void testStreamingSecInbound() throws Exception {
+
+ final ThreadStopper threadStopper = new ThreadStopper();
+ final List<Integer> times = new ArrayList<Integer>();
+ final List<Integer> memory = new ArrayList<Integer>();
+
+ Runnable myRunnable = new Runnable() {
+
+ public void run() {
+
+ int sleepTime = 100;
+
+ long currentTime = System.currentTimeMillis();
+
+ while (!threadStopper.isStop()) {
+ try {
+ Thread.sleep(sleepTime);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ System.gc();
+ times.add(((int) (System.currentTimeMillis() - currentTime - sleepTime)));
+ memory.add(((int) ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024)));
+ currentTime = System.currentTimeMillis();
+ }
+ }
+ };
+
+ Thread thread = new Thread(myRunnable);
+ thread.setPriority(8);
+ thread.start();
+
+ InputStream sourceDocument = new FileInputStream("ICHAGCompany-3000-sig-enc.xml");
+
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ securityProperties.setStrictTimestampCheck(false);
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader outXmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(sourceDocument));
+
+ XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
+ XmlReaderToWriter.writeAll(outXmlStreamReader, xmlOutputFactory.createXMLStreamWriter(new OutputStream() {
+ @Override
+ public void write(int b) throws IOException {
+ //dev/null
+ }
+ }));
+
+ threadStopper.setStop(true);
+ thread.join();
+
+ int minTime = Integer.MAX_VALUE;
+ int averageTime = 0;
+ int maxTime = Integer.MIN_VALUE;
+ for (int i = 0; i < times.size(); i++) {
+ int time = times.get(i);
+ minTime = time < minTime ? time : minTime;
+ maxTime = time > maxTime ? time : maxTime;
+ averageTime += time;
+ }
+ System.out.println("Min gc time: " + minTime);
+ System.out.println("Average gc time: " + averageTime / times.size());
+ System.out.println("Max gc time: " + maxTime);
+
+ int minMem = Integer.MAX_VALUE;
+ int averageMem = 0;
+ int maxMem = Integer.MIN_VALUE;
+ for (int i = 0; i < memory.size(); i++) {
+ int mem = memory.get(i);
+ minMem = mem < minMem ? mem : minMem;
+ maxMem = mem > maxMem ? mem : maxMem;
+ averageMem += mem;
+ }
+ System.out.println("Min memory usage: " + minMem + "MB");
+ System.out.println("Average memory usage: " + averageMem / memory.size() + "MB");
+ System.out.println("Max memory usage: " + maxMem + "MB");
+ }
+
+ class ThreadStopper {
+ private volatile boolean stop = false;
+
+ public boolean isStop() {
+ return stop;
+ }
+
+ public void setStop(boolean stop) {
+ this.stop = stop;
+ }
+ }
+
+
+/*
+ @Test(invocationCount = 1)
+ public void testStreamingSecOutbound() throws Exception {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ securityProperties.setEncryptionUser("receiver");
+ securityProperties.loadEncryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("transmitter");
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.ENCRYPT};
+ securityProperties.setOutAction(actions);
+ securityProperties.setTimestampTTL(60 * 60 * 24 * 7); //a week for testing:)
+
+ InputStream sourceDocument = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ OutboundWSSec xmlSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = xmlSecOut.processOutMessage(new FileOutputStream("plain-soap-sig-enc.xml"));
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(sourceDocument);
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+ xmlStreamReader.close();
+ }
+
+ @Test(invocationCount = 1, dependsOnMethods = {"testStreamingSecOutbound"})
+ public void testStreamingSecInbound() throws Exception {
+
+ InputStream sourceDocument = new FileInputStream("plain-soap-sig-enc.xml");
+
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+
+ InboundWSSec xmlSec = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader outXmlStreamReader = xmlSec.processInMessage(xmlInputFactory.createXMLStreamReader(sourceDocument));
+
+ XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
+ XmlReaderToWriter.writeAll(outXmlStreamReader, xmlOutputFactory.createXMLStreamWriter(new OutputStream() {
+ @Override
+ public void write(int b) throws IOException {
+ //dev/null
+ }
+ }));
+ }
+*/
+}
Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/ProfilingTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/RFC2253ParserTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/RFC2253ParserTest.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/RFC2253ParserTest.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/RFC2253ParserTest.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,122 @@
+/**
+ * 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.swssf.test;
+
+import org.swssf.impl.util.RFC2253Parser;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class RFC2253ParserTest {
+
+ @Test
+ public void testToXML1() throws Exception {
+ Assert.assertEquals(RFC2253Parser.rfc2253toXMLdsig("CN=\"Steve, Kille\", O=Isode Limited, C=GB"), "CN=Steve\\, Kille,O=Isode Limited,C=GB");
+ }
+
+ @Test
+ public void testToXML2() throws Exception {
+ Assert.assertEquals(RFC2253Parser.rfc2253toXMLdsig("CN=Steve Kille , O=Isode Limited,C=GB"), "CN=Steve Kille,O=Isode Limited,C=GB");
+ }
+
+ @Test
+ public void testToXML3() throws Exception {
+ Assert.assertEquals(RFC2253Parser.rfc2253toXMLdsig("\\ OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\ \\ "), "\\20OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\20\\20");
+ }
+
+ @Test
+ public void testToXML4() throws Exception {
+ Assert.assertEquals(RFC2253Parser.rfc2253toXMLdsig("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"), "CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB");
+ }
+
+ @Test
+ public void testToXML5() throws Exception {
+ Assert.assertEquals(RFC2253Parser.rfc2253toXMLdsig("CN=Before\\0DAfter,O=Test,C=GB"), "CN=Before\\0DAfter,O=Test,C=GB");
+ }
+
+ @Test
+ public void testToXML6() throws Exception {
+ Assert.assertEquals(RFC2253Parser.rfc2253toXMLdsig("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"), "CN=L. Eagle\\,O\\=Sue\\, \\= \\+ \\< \\> \\# \\;Grabbit and Runn,C=GB");
+ }
+
+ @Test
+ public void testToXML7() throws Exception {
+ Assert.assertEquals(RFC2253Parser.rfc2253toXMLdsig("1.3.6.1.4.1.1466.0=#04024869,O=Test,C=GB"), "1.3.6.1.4.1.1466.0=#04024869,O=Test,C=GB");
+ }
+
+ @Test
+ public void testToXML8() throws Exception {
+ StringBuilder sb = new StringBuilder();
+ sb.append('L');
+ sb.append('u');
+ sb.append('\uc48d');
+ sb.append('i');
+ sb.append('\uc487');
+ Assert.assertEquals(RFC2253Parser.rfc2253toXMLdsig("SN=" + sb.toString()), "SN=Lu\uc48di\uc487");
+ }
+
+ @Test
+ public void testToRFC1() throws Exception {
+ Assert.assertEquals(RFC2253Parser.xmldsigtoRFC2253("CN=\"Steve, Kille\", O=Isode Limited, C=GB"), "CN=Steve\\, Kille,O=Isode Limited,C=GB");
+ }
+
+ @Test
+ public void testToRFC2() throws Exception {
+ Assert.assertEquals(RFC2253Parser.xmldsigtoRFC2253("CN=Steve Kille , O=Isode Limited,C=GB"), "CN=Steve Kille,O=Isode Limited,C=GB");
+ }
+
+ @Test
+ public void testToRFC3() throws Exception {
+ Assert.assertEquals(RFC2253Parser.xmldsigtoRFC2253("\\20OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\20\\20 "), "\\ OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\ \\ ");
+ }
+
+ @Test
+ public void testToRFC4() throws Exception {
+ Assert.assertEquals(RFC2253Parser.xmldsigtoRFC2253("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"), "CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB");
+ }
+
+ @Test
+ public void testToRFC5() throws Exception {
+ Assert.assertEquals(RFC2253Parser.xmldsigtoRFC2253("CN=Before\\12After,O=Test,C=GB"), "CN=Before\\\u0012After,O=Test,C=GB");
+ }
+
+ @Test
+ public void testToRFC6() throws Exception {
+ Assert.assertEquals(RFC2253Parser.xmldsigtoRFC2253("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"), "CN=L. Eagle\\,O\\=Sue\\, \\= \\+ \\< \\> \\# \\;Grabbit and Runn,C=GB");
+ }
+
+ @Test
+ public void testToRFC7() throws Exception {
+ Assert.assertEquals(RFC2253Parser.xmldsigtoRFC2253("1.3.6.1.4.1.1466.0=\\#04024869,O=Test,C=GB"), "1.3.6.1.4.1.1466.0=\\#04024869,O=Test,C=GB");
+ }
+
+ @Test
+ public void testToRFC8() throws Exception {
+ StringBuilder sb = new StringBuilder();
+ sb.append('L');
+ sb.append('u');
+ sb.append('\uc48d');
+ sb.append('i');
+ sb.append('\uc487');
+ Assert.assertEquals(RFC2253Parser.xmldsigtoRFC2253("SN=" + sb.toString()), "SN=Lu\uc48di\uc487");
+ }
+}
Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/RFC2253ParserTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SecurityContextTokenTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SecurityContextTokenTest.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SecurityContextTokenTest.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SecurityContextTokenTest.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,442 @@
+/**
+ * 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.swssf.test;
+
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSSConfig;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.components.crypto.CryptoFactory;
+import org.apache.ws.security.handler.WSHandlerConstants;
+import org.apache.ws.security.message.*;
+import org.apache.ws.security.util.WSSecurityUtil;
+import org.swssf.WSSec;
+import org.swssf.ext.Constants;
+import org.swssf.ext.InboundWSSec;
+import org.swssf.ext.OutboundWSSec;
+import org.swssf.ext.SecurityProperties;
+import org.swssf.securityEvent.SecurityEvent;
+import org.swssf.test.utils.SOAPUtil;
+import org.swssf.test.utils.SecretKeyCallbackHandler;
+import org.swssf.test.utils.StAX2DOM;
+import org.swssf.test.utils.XmlReaderToWriter;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+
+import javax.xml.crypto.dsig.SignatureMethod;
+import javax.xml.soap.SOAPConstants;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.util.ArrayList;
+import java.util.Properties;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class SecurityContextTokenTest extends AbstractTestBase {
+
+ @BeforeClass
+ public void setUp() throws Exception {
+ WSSConfig.init();
+ }
+
+ @Test
+ public void testSCTDKTEncryptOutbound() throws Exception {
+ byte[] secret = new byte[128 / 8];
+ Constants.secureRandom.nextBytes(secret);
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.ENCRYPT_WITH_DERIVED_KEY};
+ securityProperties.setOutAction(actions);
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(secret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ securityProperties.loadEncryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setEncryptionUser("receiver");
+ securityProperties.setEncryptionSymAlgorithm("http://www.w3.org/2001/04/xmlenc#aes128-cbc");
+ securityProperties.setDerivedKeyTokenReference(Constants.DerivedKeyTokenReference.SecurityContextToken);
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_soap11_Body.getLocalPart());
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_SecurityContextToken.getNamespaceURI(), Constants.TAG_wsc0502_SecurityContextToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_DerivedKeyToken.getNamespaceURI(), Constants.TAG_wsc0502_DerivedKeyToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_ReferenceList.getNamespaceURI(), Constants.TAG_xenc_ReferenceList.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedKey.getNamespaceURI(), Constants.TAG_xenc_EncryptedKey.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ }
+ {
+ String action = WSHandlerConstants.ENCRYPT;
+ Properties properties = new Properties();
+ WSS4JCallbackHandlerImpl callbackHandler = new WSS4JCallbackHandlerImpl(secret);
+ properties.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
+ doInboundSecurityWithWSS4J_1(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action, SOAPConstants.SOAP_1_1_PROTOCOL, properties, false);
+ }
+ }
+
+ @Test
+ public void testSCTDKTEncryptInbound() throws Exception {
+
+ byte[] tempSecret = WSSecurityUtil.generateNonce(16);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ sctBuilder.prepare(doc, crypto);
+
+ // Store the secret
+ SecretKeyCallbackHandler callbackHandler = new SecretKeyCallbackHandler();
+ callbackHandler.addSecretKey(sctBuilder.getIdentifier(), tempSecret);
+
+ String tokenId = sctBuilder.getSctId();
+
+ // Derived key encryption
+ WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+ encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+ encrBuilder.setExternalKey(tempSecret, tokenId);
+ encrBuilder.build(doc, secHeader);
+
+ sctBuilder.prependSCTElementToHeader(doc, secHeader);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(tempSecret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ }
+ }
+
+ @Test
+ public void testSCTKDKTSignOutbound() throws Exception {
+ byte[] secret = new byte[128 / 8];
+ Constants.secureRandom.nextBytes(secret);
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.SIGNATURE_WITH_DERIVED_KEY};
+ securityProperties.setOutAction(actions);
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(secret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("transmitter");
+ securityProperties.setDerivedKeyTokenReference(Constants.DerivedKeyTokenReference.SecurityContextToken);
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_SecurityContextToken.getNamespaceURI(), Constants.TAG_wsc0502_SecurityContextToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_DerivedKeyToken.getNamespaceURI(), Constants.TAG_wsc0502_DerivedKeyToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_ReferenceList.getNamespaceURI(), Constants.TAG_xenc_ReferenceList.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedKey.getNamespaceURI(), Constants.TAG_xenc_EncryptedKey.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ }
+ {
+ String action = WSHandlerConstants.SIGNATURE;
+ Properties properties = new Properties();
+ WSS4JCallbackHandlerImpl callbackHandler = new WSS4JCallbackHandlerImpl(secret);
+ properties.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
+ doInboundSecurityWithWSS4J_1(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action, SOAPConstants.SOAP_1_1_PROTOCOL, properties, false);
+ }
+ }
+
+ @Test
+ public void testSCTKDKTSignInbound() throws Exception {
+
+ byte[] tempSecret = WSSecurityUtil.generateNonce(16);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ sctBuilder.prepare(doc, crypto);
+
+ // Store the secret
+ SecretKeyCallbackHandler callbackHandler = new SecretKeyCallbackHandler();
+ callbackHandler.addSecretKey(sctBuilder.getIdentifier(), tempSecret);
+
+ String tokenId = sctBuilder.getSctId();
+
+ // Derived key signature
+ WSSecDKSign sigBuilder = new WSSecDKSign();
+ sigBuilder.setExternalKey(tempSecret, tokenId);
+ sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
+ sigBuilder.build(doc, secHeader);
+
+ sctBuilder.prependSCTElementToHeader(doc, secHeader);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(tempSecret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+ }
+ }
+
+ @Test
+ public void testSCTKDKTSignAbsoluteInbound() throws Exception {
+
+ byte[] tempSecret = WSSecurityUtil.generateNonce(16);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ sctBuilder.prepare(doc, crypto);
+
+ // Store the secret
+ SecretKeyCallbackHandler callbackHandler = new SecretKeyCallbackHandler();
+ callbackHandler.addSecretKey(sctBuilder.getIdentifier(), tempSecret);
+
+ // Derived key signature
+ WSSecDKSign sigBuilder = new WSSecDKSign();
+ sigBuilder.setExternalKey(tempSecret, sctBuilder.getIdentifier());
+ sigBuilder.setTokenIdDirectId(true);
+ sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
+ sigBuilder.build(doc, secHeader);
+
+ sctBuilder.prependSCTElementToHeader(doc, secHeader);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(tempSecret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+ }
+ }
+
+ @Test
+ public void testSCTKDKTSignEncrypt() throws Exception {
+
+ byte[] tempSecret = WSSecurityUtil.generateNonce(16);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ sctBuilder.prepare(doc, crypto);
+
+ // Store the secret
+ SecretKeyCallbackHandler callbackHandler = new SecretKeyCallbackHandler();
+ callbackHandler.addSecretKey(sctBuilder.getIdentifier(), tempSecret);
+
+ String tokenId = sctBuilder.getSctId();
+
+ // Derived key signature
+ WSSecDKSign sigBuilder = new WSSecDKSign();
+ sigBuilder.setExternalKey(tempSecret, tokenId);
+ sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
+ sigBuilder.build(doc, secHeader);
+
+ // Derived key encryption
+ WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+ encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+ encrBuilder.setExternalKey(tempSecret, tokenId);
+ encrBuilder.build(doc, secHeader);
+
+ sctBuilder.prependSCTElementToHeader(doc, secHeader);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(tempSecret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ }
+ }
+
+ @Test
+ public void testSCTKDKTEncryptSign() throws Exception {
+
+ byte[] tempSecret = WSSecurityUtil.generateNonce(16);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ sctBuilder.prepare(doc, crypto);
+
+ // Store the secret
+ SecretKeyCallbackHandler callbackHandler = new SecretKeyCallbackHandler();
+ callbackHandler.addSecretKey(sctBuilder.getIdentifier(), tempSecret);
+
+ String tokenId = sctBuilder.getSctId();
+
+ // Derived key encryption
+ WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+ encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+ encrBuilder.setExternalKey(tempSecret, tokenId);
+ encrBuilder.build(doc, secHeader);
+
+ // Derived key signature
+ WSSecDKSign sigBuilder = new WSSecDKSign();
+ sigBuilder.setExternalKey(tempSecret, tokenId);
+ sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
+ sigBuilder.build(doc, secHeader);
+
+ sctBuilder.prependSCTElementToHeader(doc, secHeader);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(tempSecret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ }
+ }
+
+ @Test
+ public void testSCTSign() throws Exception {
+
+ byte[] tempSecret = WSSecurityUtil.generateNonce(16);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ sctBuilder.prepare(doc, crypto);
+
+ // Store the secret
+ SecretKeyCallbackHandler callbackHandler = new SecretKeyCallbackHandler();
+ callbackHandler.addSecretKey(sctBuilder.getIdentifier(), tempSecret);
+
+ String tokenId = sctBuilder.getSctId();
+
+ WSSecSignature builder = new WSSecSignature();
+ builder.setSecretKey(tempSecret);
+ builder.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
+ builder.setCustomTokenValueType(WSConstants.WSC_SCT);
+ builder.setCustomTokenId(tokenId);
+ builder.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
+ builder.build(doc, crypto, secHeader);
+
+ sctBuilder.prependSCTElementToHeader(doc, secHeader);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(tempSecret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+ }
+ }
+}
Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SecurityContextTokenTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SignatureConfirmationTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SignatureConfirmationTest.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SignatureConfirmationTest.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SignatureConfirmationTest.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,323 @@
+/**
+ * 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.swssf.test;
+
+import org.apache.ws.security.handler.WSHandlerConstants;
+import org.swssf.WSSec;
+import org.swssf.ext.*;
+import org.swssf.securityEvent.SecurityEvent;
+import org.swssf.securityEvent.SecurityEventListener;
+import org.swssf.test.utils.StAX2DOM;
+import org.swssf.test.utils.XmlReaderToWriter;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import javax.xml.rpc.handler.MessageContext;
+import javax.xml.soap.SOAPConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.Vector;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class SignatureConfirmationTest extends AbstractTestBase {
+
+ @Test
+ public void testDefaultConfigurationInbound() throws Exception {
+
+ List sigv;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml");
+ String action = WSHandlerConstants.SIGNATURE;
+ Properties properties = new Properties();
+ properties.setProperty(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, "true");
+ MessageContext messageContext = doOutboundSecurityWithWSS4J_1(sourceDocument, action, properties, SOAPConstants.SOAP_1_1_PROTOCOL);
+ sigv = (List) messageContext.getProperty(WSHandlerConstants.SEND_SIGV);
+ Document securedDocument = (Document) messageContext.getProperty(SECURED_DOCUMENT);
+
+ //some test that we can really sure we get what we want from WSS4J
+ NodeList nodeList = securedDocument.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(securedDocument), new StreamResult(baos));
+ }
+
+ final List<SecurityEvent> securityEventList = new ArrayList<SecurityEvent>();
+ //done signature; now test sig-verification:
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+
+ SecurityEventListener securityEventListener = new SecurityEventListener() {
+ public void registerSecurityEvent(SecurityEvent securityEvent) throws WSSecurityException {
+ securityEventList.add(securityEvent);
+ }
+ };
+
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())), new ArrayList<SecurityEvent>(), securityEventListener);
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ //header element must still be there
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+ }
+
+ //so we have a request generated, now do the response:
+ baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.SIGNATURE_CONFIRMATION};
+ securityProperties.setOutAction(actions);
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("receiver");
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", securityEventList);
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Reference.getNamespaceURI(), Constants.TAG_dsig_Reference.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 2);
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsse11_SignatureConfirmation.getNamespaceURI(), Constants.TAG_wsse11_SignatureConfirmation.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ Assert.assertNotSame(((Element) nodeList.item(0)).getAttribute(Constants.ATT_NULL_Value.getLocalPart()), "");
+ Assert.assertNotNull(((Element) nodeList.item(0)).getAttribute(Constants.ATT_wsu_Id.getLocalPart()), "");
+ Assert.assertTrue(((Element) nodeList.item(0)).getAttributeNS(Constants.ATT_wsu_Id.getNamespaceURI(), Constants.ATT_wsu_Id.getLocalPart()).startsWith("SigConf-"));
+
+ nodeList = document.getElementsByTagNameNS(Constants.NS_SOAP11, Constants.TAG_soap_Body_LocalName);
+ Assert.assertEquals(nodeList.getLength(), 1);
+ String idAttrValue = ((Element) nodeList.item(0)).getAttributeNS(Constants.ATT_wsu_Id.getNamespaceURI(), Constants.ATT_wsu_Id.getLocalPart());
+ Assert.assertNotNull(idAttrValue);
+ Assert.assertTrue(idAttrValue.startsWith("id-"), "wsu:id Attribute doesn't start with id");
+ }
+
+ //verify SigConf response:
+ {
+ String action = WSHandlerConstants.SIGNATURE;
+ Properties properties = new Properties();
+ properties.put(WSHandlerConstants.SEND_SIGV, sigv);
+ doInboundSecurityWithWSS4J_1(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action, SOAPConstants.SOAP_1_1_PROTOCOL, properties, true);
+ }
+ }
+
+ @Test
+ public void testDefaultConfigurationOutbound() throws Exception {
+
+ final List<SecurityEvent> securityEventList = new ArrayList<SecurityEvent>();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.SIGNATURE};
+ securityProperties.setOutAction(actions);
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("transmitter");
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+
+ SecurityEventListener securityEventListener = new SecurityEventListener() {
+ public void registerSecurityEvent(SecurityEvent securityEvent) throws WSSecurityException {
+ securityEventList.add(securityEvent);
+ }
+ };
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>(), securityEventListener);
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Reference.getNamespaceURI(), Constants.TAG_dsig_Reference.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+
+ Vector wsHandlerResult;
+ //done signature; now test sig-verification:
+ {
+ String action = WSHandlerConstants.SIGNATURE;
+ Properties properties = new Properties();
+ properties.setProperty(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, "true");
+ MessageContext messageContext = doInboundSecurityWithWSS4J_1(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action);
+ wsHandlerResult = (Vector) messageContext.getProperty(WSHandlerConstants.RECV_RESULTS);
+
+ Document document = (Document) messageContext.getProperty(SECURED_DOCUMENT);
+ }
+
+ //so we have a request generated, now do the response:
+ baos = new ByteArrayOutputStream();
+ {
+ InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml");
+ String action = WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION + " " + WSHandlerConstants.SIGNATURE;
+ Properties properties = new Properties();
+ properties.put(WSHandlerConstants.RECV_RESULTS, wsHandlerResult);
+ MessageContext messageContext = doOutboundSecurityWithWSS4J_1(sourceDocument, action, properties, SOAPConstants.SOAP_1_1_PROTOCOL);
+ Document securedDocument = (Document) messageContext.getProperty(SECURED_DOCUMENT);
+
+ //some test that we can really sure we get what we want from WSS4J
+ NodeList nodeList = securedDocument.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ nodeList = securedDocument.getElementsByTagNameNS(Constants.TAG_wsse11_SignatureConfirmation.getNamespaceURI(), Constants.TAG_wsse11_SignatureConfirmation.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ Assert.assertNotSame(((Element) nodeList.item(0)).getAttribute(Constants.ATT_NULL_Value.getLocalPart()), "");
+ Assert.assertNotNull(((Element) nodeList.item(0)).getAttribute(Constants.ATT_wsu_Id.getLocalPart()), "");
+
+ nodeList = securedDocument.getElementsByTagNameNS(Constants.NS_SOAP11, Constants.TAG_soap_Body_LocalName);
+ Assert.assertEquals(nodeList.getLength(), 1);
+ String idAttrValue = ((Element) nodeList.item(0)).getAttributeNS(Constants.ATT_wsu_Id.getNamespaceURI(), Constants.ATT_wsu_Id.getLocalPart());
+ Assert.assertNotNull(idAttrValue);
+ Assert.assertTrue(idAttrValue.startsWith("id-"), "wsu:id Attribute doesn't start with id");
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(securedDocument), new StreamResult(baos));
+ }
+
+ //verify SigConf response:
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.setEnableSignatureConfirmationVerification(true);
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())), securityEventList, null);
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ //header element must still be there
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+ }
+ }
+
+ @Test
+ public void testOutboundNoSignatureConfirmation() throws Exception {
+
+ final List<SecurityEvent> securityEventList = new ArrayList<SecurityEvent>();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.SIGNATURE};
+ securityProperties.setOutAction(actions);
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("transmitter");
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+
+ SecurityEventListener securityEventListener = new SecurityEventListener() {
+ public void registerSecurityEvent(SecurityEvent securityEvent) throws WSSecurityException {
+ securityEventList.add(securityEvent);
+ }
+ };
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>(), securityEventListener);
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Reference.getNamespaceURI(), Constants.TAG_dsig_Reference.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+
+ //done signature; now test sig-verification:
+ {
+ String action = WSHandlerConstants.SIGNATURE;
+ Properties properties = new Properties();
+ MessageContext messageContext = doInboundSecurityWithWSS4J_1(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action);
+ Document document = (Document) messageContext.getProperty(SECURED_DOCUMENT);
+ }
+
+ //so we have a request generated, now do the response:
+ baos = new ByteArrayOutputStream();
+ {
+ InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml");
+ String action = WSHandlerConstants.SIGNATURE;
+ Properties properties = new Properties();
+ MessageContext messageContext = doOutboundSecurityWithWSS4J_1(sourceDocument, action, properties, SOAPConstants.SOAP_1_1_PROTOCOL);
+ Document securedDocument = (Document) messageContext.getProperty(SECURED_DOCUMENT);
+
+ //some test that we can really sure we get what we want from WSS4J
+ NodeList nodeList = securedDocument.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ nodeList = securedDocument.getElementsByTagNameNS(Constants.TAG_wsse11_SignatureConfirmation.getNamespaceURI(), Constants.TAG_wsse11_SignatureConfirmation.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+
+ nodeList = securedDocument.getElementsByTagNameNS(Constants.NS_SOAP11, Constants.TAG_soap_Body_LocalName);
+ Assert.assertEquals(nodeList.getLength(), 1);
+ String idAttrValue = ((Element) nodeList.item(0)).getAttributeNS(Constants.ATT_wsu_Id.getNamespaceURI(), Constants.ATT_wsu_Id.getLocalPart());
+ Assert.assertNotNull(idAttrValue);
+ Assert.assertTrue(idAttrValue.startsWith("id-"), "wsu:id Attribute doesn't start with id");
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(securedDocument), new StreamResult(baos));
+ }
+
+ //verify SigConf response:
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.setEnableSignatureConfirmationVerification(true);
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())), securityEventList, null);
+
+ try {
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+ Assert.fail("Expected XMLStreamException");
+ } catch (XMLStreamException e) {
+ Assert.assertNotNull(e.getCause());
+ Assert.assertTrue(e.getCause() instanceof WSSecurityException);
+ Assert.assertEquals(e.getCause().getMessage(), "The signature or decryption was invalid");
+ }
+ }
+ }
+}
Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/SignatureConfirmationTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision