diff options
Diffstat (limited to 'cadi/core/src/test')
75 files changed, 8602 insertions, 0 deletions
diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_Get.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_Get.java new file mode 100644 index 00000000..017d86e7 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_Get.java @@ -0,0 +1,107 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.config.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.config.Get; + +public class JU_Get { + + private String defaultVal = "some default value"; + + private ByteArrayOutputStream outStream; + + private TestBean tb; + + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void beanTest() { + tb = new TestBean(); + tb.setProperty1("prop1"); + + Get.Bean testBean = new Get.Bean(tb); + assertThat(testBean.get("property1", defaultVal, true), is("prop1")); + assertThat(testBean.get("property2", defaultVal, true), is(defaultVal)); + assertThat(testBean.get("thrower", defaultVal, true), is(defaultVal)); + } + + @Test + public void nullTest() { + assertThat(Get.NULL.get("name", defaultVal, true), is(defaultVal)); + } + + @Test + public void accessTest() { + + PropAccess access = new PropAccess(); + access.setProperty("tag", "value"); + Get.AccessGet accessGet = new Get.AccessGet(access); + + assertThat(accessGet.get("tag", defaultVal, true), is("value")); + outStream.reset(); + + assertThat(accessGet.get("not a real tag", defaultVal, true), is(defaultVal)); + outStream.reset(); + + assertThat(accessGet.get("not a real tag", null, true), is(nullValue())); + + outStream.reset(); + + assertThat(accessGet.get("tag", defaultVal, false), is("value")); + assertThat(outStream.toString(), is("")); + } + + public class TestBean implements java.io.Serializable { + + private static final long serialVersionUID = 1L; + private String property1 = null; + private String property2 = null; + @SuppressWarnings("unused") + private String thrower = null; + + public TestBean() { } + public String getProperty1() { return property1; } + public void setProperty1(final String value) { this.property1 = value; } + public String getProperty2() { return property2; } + public void setProperty2(final String value) { this.property2 = value; } + public String getThrower() throws Exception { throw new Exception(); } + public void setThrower(final String value) { this.thrower = value; } + + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_GetAccess.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_GetAccess.java new file mode 100644 index 00000000..309810af --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_GetAccess.java @@ -0,0 +1,105 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.config.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; + +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.config.Get; +import org.onap.ccsdk.apps.cadi.config.GetAccess; + +public class JU_GetAccess { + + private String defaultVal = "some default value"; + + private ByteArrayOutputStream outStream; + + private PropAccess access; + private Get.AccessGet accessGet; + private File file; + private String filePath; + + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + + file = File.createTempFile("GetAccess_test", ""); + filePath = file.getAbsolutePath(); + + access = new PropAccess(); + access.setProperty("cadi_prop_files", filePath); + accessGet = new Get.AccessGet(access); + + } + + @After + public void tearDown() { + System.setOut(System.out); + + file.delete(); + } + + @Test + public void constructorTest() { + String output; + + @SuppressWarnings("unused") + GetAccess getAccess = new GetAccess(accessGet); + String[] lines = outStream.toString().split(System.lineSeparator()); + assertThat(lines.length, is(5)); + output = lines[0].split(" ", 2)[1]; + + } + + @Test + public void getPropertyTest1() { + GetAccess getAccess = new GetAccess(accessGet); + + getAccess.setProperty("tag", "value"); + assertThat(getAccess.getProperty("tag", defaultVal), is("value")); + assertThat(getAccess.getProperty("not_a_tag", defaultVal), is(defaultVal)); + } + + @Test + public void getPropertyTest2() { + GetAccess getAccess = new GetAccess(accessGet); + + getAccess.setProperty("tag", "value"); + assertThat(getAccess.getProperty("tag"), is("value")); + assertThat(getAccess.getProperty("not_a_tag"), is(nullValue())); + } + + @Test + public void getTest() { + GetAccess getAccess = new GetAccess(accessGet); + assertThat((Get.AccessGet)getAccess.get(), is(accessGet)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_MapBathConverter.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_MapBathConverter.java new file mode 100644 index 00000000..4be77623 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_MapBathConverter.java @@ -0,0 +1,248 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + */ + +package org.onap.ccsdk.apps.cadi.config.test; + +import java.io.File; +import java.io.IOException; +import java.sql.Date; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.GregorianCalendar; +import java.util.Iterator; +import java.util.List; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.Symm; +import org.onap.ccsdk.apps.cadi.filter.MapBathConverter; +import org.onap.ccsdk.apps.cadi.util.CSV; +import org.onap.ccsdk.apps.cadi.util.CSV.Visitor; +import org.onap.ccsdk.apps.cadi.util.CSV.Writer; + +import junit.framework.Assert; + +/** + * Test a simple Migration conversion tool for CADI + * + * @author Instrumental(Jonathan) + * + */ +public class JU_MapBathConverter { + private static final String NEW_USER_SOMETHING_ORG = "NEW_USER@Something.org"; + private static final String OLD_ID = "OLD_ID"; + private static final String SHARED_PASS = "SHARED_PASS"; + private static CSV csv; + private static ArrayList<String> expected; + private static final Access access = new PropAccess(); + private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + + @BeforeClass + public static void createFile() throws IOException { + // Note, you cate a "MapBathConverter" by access to a File. + // We will create that file now. Local is fine. + csv = new CSV(access,"JU_MapBathConverter.csv"); + } + + @BeforeClass + public static void beforeClass() { + expected = new ArrayList<>(); + } + + @Before + public void before() { + expected.clear(); + } + + @Test + public void test() throws IOException, CadiException { + CSV.Writer cw = csv.writer(); + GregorianCalendar gc = new GregorianCalendar(); + gc.add(GregorianCalendar.MONTH, 6); + try { + try { + // CSV can simply be OLD ID and NEW, no passwords + cw.row(exp(OLD_ID), exp(NEW_USER_SOMETHING_ORG),sdf.format(gc.getTime())); + + // Style 1 - Incoming ID/pass, create new cred with NweID and same Pass + cw.row(exp(bath(OLD_ID,SHARED_PASS)), exp(NEW_USER_SOMETHING_ORG),sdf.format(gc.getTime())); + // the response should be Basic with NEW_ID and OLD_PASS + + // Style 2 + cw.row(exp(bath(OLD_ID,"OLD_PASS")), exp(bath(NEW_USER_SOMETHING_ORG,"NEW_PASS")),sdf.format(gc.getTime())); + + } finally { + cw.close(); + } + + final Iterator<String> exp = expected.iterator(); + csv.visit(new Visitor() { + @Override + public void visit(List<String> row) { + int i=0; + for(String s : row) { + switch(i++) { + case 0: + case 1: + Assert.assertEquals(exp.next(), s); + break; + case 2: + try { + Date.valueOf(s); + } catch (Exception e) { + Assert.assertTrue("Last entry should be a date",false); + } + break; + default: + Assert.fail("There should only be 3 columns in this test case."); + } + } + } + }); + + MapBathConverter mbc = new MapBathConverter(access, csv); + + // Check no lookup just returns the same + Assert.assertEquals("NonKey", "NonKey"); // if not in map, expect same value + + Iterator<String> exp1 = expected.iterator(); + // there's no passwords in CSV + String old = exp1.next(); + String nw = exp1.next(); + Assert.assertEquals(nw, mbc.convert(access,old)); + + Assert.assertEquals(bath(NEW_USER_SOMETHING_ORG,SHARED_PASS), mbc.convert(access,bath(OLD_ID,SHARED_PASS))); + + // Style 1 (new cred, old password) + old = exp1.next(); + nw = bath(exp1.next(),SHARED_PASS); + Assert.assertEquals(nw, mbc.convert(access,old)); + + // Style 2 + old = exp1.next(); + nw = exp1.next(); + Assert.assertEquals(nw, mbc.convert(access,old)); + + } finally { + csv.delete(); + } + } + + @Test + public void testInsecureRole() throws IOException { + CSV.Writer cw = csv.writer(); + GregorianCalendar gc = new GregorianCalendar(); + gc.add(GregorianCalendar.MONTH, 6); + try { + try { + // Invalid Scenario - Non Authenticated ID to authenticated User + cw.row(exp(OLD_ID), exp(bath(NEW_USER_SOMETHING_ORG,"NEW_PASS")),sdf.format(gc.getTime())); + + } finally { + cw.close(); + } + + try { + new MapBathConverter(access, csv); + Assert.fail("Invalid Data should throw Exception"); + } catch (CadiException e) { + Assert.assertTrue("Invalid Data should throw Exception",true); + } + + } finally { + csv.delete(); + } + } + + @Test + public void testTooFewColumns() throws IOException, CadiException { + CSV.Writer cw = csv.writer(); + try { + try { + cw.row(exp(bath(OLD_ID,"OLD_PASS")), exp(bath(NEW_USER_SOMETHING_ORG,"NEW_PASS"))); + } finally { + cw.close(); + } + + try { + new MapBathConverter(access, csv); + Assert.fail("file with too few rows should throw exception"); + } catch(CadiException | IOException e) { + Assert.assertTrue("Correctly thrown Exception",true); + } + } finally { + csv.delete(); + } + } + + @Test + public void testNoFile() { + try { + new MapBathConverter(access, new CSV(access,"Bogus")); + Assert.fail("Non Existent File should throw exception"); + } catch(CadiException | IOException e) { + Assert.assertTrue("Correctly thrown Exception",true); + } + } + + @Test + public void testBadRows() throws IOException { + try { + Writer cw = csv.writer(); + try { + cw.row("Single Column"); + } finally { + cw.close(); + } + + try { + new MapBathConverter(access,csv); + Assert.fail("Non Existent File should throw exception"); + } catch(CadiException | IOException e) { + Assert.assertTrue("Correctly thrown Exception",true); + } + } finally { + csv.delete(); + } + + // Check for deletion + Assert.assertFalse(csv.toString() + "should have been deleted",new File(csv.toString()).exists()); + } + + private String bath(String user, String password) throws IOException { + StringBuilder sb = new StringBuilder(user); + sb.append(':'); + sb.append(password); + byte[] encoded = Symm.base64noSplit.encode(sb.toString().getBytes()); + sb.setLength(0); + sb.append("Basic "); + sb.append(new String(encoded)); + return sb.toString(); + } + + private String exp(String s) { + expected.add(s); + return s; + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_MultiGet.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_MultiGet.java new file mode 100644 index 00000000..ccaf3596 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_MultiGet.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.config.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.config.Get; +import org.onap.ccsdk.apps.cadi.config.MultiGet; + +public class JU_MultiGet { + + private String defaultVal = "some default value"; + + private ByteArrayOutputStream outStream; + + private MultiGet multiGet; + private Get.AccessGet accessGet; + private PropAccess access; + + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + + access = new PropAccess(); + access.setProperty("tag", "value"); + accessGet = new Get.AccessGet(access); + multiGet = new MultiGet(accessGet, Get.NULL); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void getTest() { + assertThat(multiGet.get("tag", defaultVal, false), is("value")); + assertThat(multiGet.get("not_a_tag", defaultVal, false), is(defaultVal)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_RegistrationPropHolder.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_RegistrationPropHolder.java new file mode 100644 index 00000000..6a51815e --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_RegistrationPropHolder.java @@ -0,0 +1,149 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + */ + +package org.onap.ccsdk.apps.cadi.config.test; + +import static org.junit.Assert.assertEquals; + +import java.net.UnknownHostException; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.config.Config; +import org.onap.ccsdk.apps.cadi.config.RegistrationPropHolder; + +public class JU_RegistrationPropHolder { + + @Test + public void testBlank() { + PropAccess pa = new PropAccess(); + RegistrationPropHolder rph; + int ju_port = 20; + try { + //////////////// + // Check Required Properties + //////////////// + try { + rph = new RegistrationPropHolder(pa,20); + } catch (CadiException e) { + Assert.assertEquals( + "\ncadi_latitude must be defined." + + "\ncadi_longitude must be defined.",e.getMessage()); + } + + try { + pa.setProperty(Config.CADI_LATITUDE, "32.7"); + rph = new RegistrationPropHolder(pa,20); + } catch (CadiException e) { + Assert.assertEquals( + "\ncadi_longitude must be defined.",e.getMessage()); + } + + pa.setProperty(Config.CADI_LONGITUDE, "-72.0"); + rph = new RegistrationPropHolder(pa,ju_port); + + //////////////// + // Validate Default Properties + //////////////// + for(String dot_le : new String[] {"",".helm"}) { + assertEquals(rph.hostname,rph.default_fqdn); + assertEquals("",rph.lcontainer); + assertEquals(rph.hostname,rph.public_fqdn); + assertEquals(ju_port,rph.getEntryPort(dot_le)); + assertEquals(rph.hostname,rph.getEntryFQDN("",dot_le)); + } + + String ns = "myns"; + pa.setProperty(Config.AAF_LOCATOR_APP_NS, ns); + for(String dot_le : new String[] {"",".helm"}) { + assertEquals(rph.hostname,rph.default_fqdn); + assertEquals("",rph.lcontainer); + assertEquals(rph.hostname,rph.public_fqdn); + assertEquals(ju_port,rph.getEntryPort(dot_le)); + assertEquals(rph.hostname,rph.getEntryFQDN("",dot_le)); + } + + String ns2 = "onap"; + pa.setProperty(Config.AAF_LOCATOR_APP_NS+".helm", ns2); + for(String dot_le : new String[] {"",".helm"}) { + assertEquals(rph.hostname,rph.default_fqdn); + assertEquals("",rph.lcontainer); + assertEquals(rph.hostname,rph.public_fqdn); + assertEquals(ju_port,rph.getEntryPort(dot_le)); + assertEquals(rph.hostname,rph.getEntryFQDN("",dot_le)); + } + + //////////////// + // Validate Public Host and Port settings + //////////////// + String public_hostname = "com.public.hostname"; + int public_port = 999; + pa.setProperty(Config.AAF_LOCATOR_PUBLIC_FQDN, public_hostname); + pa.setProperty(Config.AAF_LOCATOR_PUBLIC_PORT,Integer.toString(public_port)); + RegistrationPropHolder pubRPH = new RegistrationPropHolder(pa,ju_port); + assertEquals(public_hostname,pubRPH.public_fqdn); + assertEquals(public_port,pubRPH.getEntryPort("")); + + + final String url = "https://aaf.osaaf.org:8095/org.osaaf.aaf.service:2.1"; + String name="theName"; + assertEquals(url,rph.replacements(getClass().getSimpleName(),url, name, "")); + + String alu = "aaf.osaaf.org:8095"; + String curl = url.replace(alu, Config.AAF_LOCATE_URL_TAG); + pa.setProperty(Config.AAF_LOCATE_URL,"https://"+alu); + assertEquals(url.replace("8095","8095/locate"),rph.replacements(getClass().getSimpleName(),curl, name, "")); + + String root_ns = "org.osaaf.aaf"; + curl = url.replace(root_ns, "AAF_NS"); + pa.setProperty(Config.AAF_ROOT_NS,root_ns); + assertEquals(url,rph.replacements(getClass().getSimpleName(),curl, name, "")); + + curl = url.replace(root_ns, "%AAF_NS"); + pa.setProperty(Config.AAF_ROOT_NS,root_ns); + assertEquals(url,rph.replacements(getClass().getSimpleName(),curl, name, "")); + + final String fqdn = "%C.%CNS.%NS.%N"; + String target = "myns.theName"; + assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, "")); + + pa.setProperty(Config.AAF_LOCATOR_CONTAINER_NS+".hello", "mycontns"); + target = "mycontns.myns.theName"; + assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, ".hello")); + + pa.setProperty(Config.AAF_LOCATOR_CONTAINER+".hello","helloC"); + target = "helloC.mycontns.myns.theName"; + assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, ".hello")); + + pa.setProperty(Config.AAF_LOCATOR_CONTAINER_NS,"c_ns"); + target = "c_ns.myns.theName"; + assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, "")); + + + } catch (UnknownHostException | CadiException e) { + e.printStackTrace(); + Assert.fail(); + } + } + + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_SecurityInfo.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_SecurityInfo.java new file mode 100644 index 00000000..99a57e32 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_SecurityInfo.java @@ -0,0 +1,136 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.config.test; + + +import static org.junit.Assert.assertNotNull; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.config.Config; +import org.onap.ccsdk.apps.cadi.config.SecurityInfo; + +public class JU_SecurityInfo { + + private static PropAccess access; + + private static final String keyStoreFileName = "src/test/resources/keystore.p12"; + private static final String keyStorePassword = "Password for the keystore"; + private static final String keyPassword = "Password for the key"; + + private static final String trustStoreFileName = "src/test/resources/truststore.jks"; + private static final String trustStorePasswd = "Password for the truststore"; + + @BeforeClass + public static void setupOnce() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + keyStore.load(null, null); + keyStore.store(new FileOutputStream(keyStoreFileName), keyStorePassword.toCharArray()); + + KeyStore trustStore = KeyStore.getInstance("JKS"); + trustStore.load(null, null); + trustStore.store(new FileOutputStream(trustStoreFileName), trustStorePasswd.toCharArray()); + } + + @Before + public void setup() throws IOException { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + + access.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); + access.setProperty(Config.CADI_KEYSTORE_PASSWORD, access.encrypt(keyStorePassword)); + access.setProperty(Config.CADI_KEY_PASSWORD, access.encrypt(keyPassword)); + + access.setProperty(Config.CADI_TRUSTSTORE, trustStoreFileName); + access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, access.encrypt(trustStorePasswd)); + } + + @AfterClass + public static void tearDownOnce() { + File keyStoreFile = new File(keyStoreFileName); + if (keyStoreFile.exists()) { + keyStoreFile.delete(); + } + File trustStoreFile = new File(trustStoreFileName); + if (trustStoreFile.exists()) { + trustStoreFile.delete(); + } + } + + @Test + public void test() throws CadiException { + SecurityInfo si = new SecurityInfo(access); + + assertNotNull(si.getSSLSocketFactory()); + assertNotNull(si.getSSLContext()); + assertNotNull(si.getKeyManagers()); + + access.setProperty(Config.CADI_TRUST_MASKS, "123.123.123.123"); + si = new SecurityInfo(access); + } + + @Test(expected = CadiException.class) + public void nullkeyStoreTest() throws CadiException { + access.setProperty(Config.CADI_KEYSTORE, "passwords.txt"); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(access); + } + + @Test(expected = CadiException.class) + public void nullTrustStoreTest() throws CadiException { + access.setProperty(Config.CADI_TRUSTSTORE, "passwords.txt"); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(access); + } + + + @Test(expected = NumberFormatException.class) + public void badTrustMaskTest() throws CadiException { + access.setProperty(Config.CADI_TRUST_MASKS, "trustMask"); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(access); + } + + @Test + public void coverageTest() throws CadiException { + PropAccess badAccess = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + @SuppressWarnings("unused") + SecurityInfo si = new SecurityInfo(badAccess); + badAccess.setProperty(Config.CADI_KEYSTORE, keyStoreFileName); + si = new SecurityInfo(badAccess); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_SecurityInfoC.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_SecurityInfoC.java new file mode 100644 index 00000000..e726c9f0 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_SecurityInfoC.java @@ -0,0 +1,110 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.config.test; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +import org.junit.*; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.SecuritySetter; +import org.onap.ccsdk.apps.cadi.config.SecurityInfoC; + +public class JU_SecurityInfoC { + + ByteArrayOutputStream outStream; + ByteArrayOutputStream errStream; + + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + System.setErr(System.err); + } + +// @Test +// public void instanceTest() throws CadiException, MalformedURLException { +// SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class ); +// assertThat(si.defSS.getID(), is(SecurityInfoC.DEF_ID)); +// try { +// si.defSS.setSecurity(new HttpURLConnectionStub()); +// fail("Should have thrown an exception"); +// } catch (CadiException e) { +// assertTrue(e instanceof CadiException); +// assertThat(e.getMessage(), is("No Client Credentials set.")); +// } +// assertThat(si.defSS.setLastResponse(0), is(0)); +// +// // Try it again for coverage +// SecurityInfoC<HttpURLConnection> siClone = SecurityInfoC.instance(new PropAccess(), HttpURLConnection.class); +// assertThat(siClone, is(si)); +// } + + @Test + public void setTest() throws MalformedURLException, CadiException { + SecurityInfoC<HttpURLConnectionStub> si = SecurityInfoC.instance(new PropAccess(), HttpURLConnectionStub.class); + SecuritySetter<HttpURLConnectionStub> ss = new SecuritySetterStub<HttpURLConnectionStub>(); + assertThat(si.set(ss), is(si)); + assertThat(si.defSS.getID(), is("Example ID")); + try { + si.defSS.setSecurity(new HttpURLConnectionStub()); + fail("Should have thrown an exception"); + } catch (CadiException e) { + assertTrue(e instanceof CadiException); + assertThat(e.getMessage(), is("Example exception")); + } + assertThat(si.defSS.setLastResponse(0), is(0)); + assertThat(si.defSS.setLastResponse(1), is(1)); + assertThat(si.defSS.setLastResponse(-1), is(-1)); + } + + public static class HttpURLConnectionStub extends HttpURLConnection { + public HttpURLConnectionStub() throws MalformedURLException { super(new URL("http://www.example.com")); } + @Override public void disconnect() { } + @Override public boolean usingProxy() { return false; } + @Override public void connect() throws IOException { } + } + + private class SecuritySetterStub<CT> implements SecuritySetter<CT> { + public String getID() { return "Example ID"; } + public void setSecurity(CT client) throws CadiException { throw new CadiException("Example exception"); } + public int setLastResponse(int respCode) { return respCode; } + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_UsersDump.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_UsersDump.java new file mode 100644 index 00000000..dfac2164 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/config/test/JU_UsersDump.java @@ -0,0 +1,145 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.config.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; + +import org.onap.ccsdk.apps.cadi.AbsUserCache; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.config.UsersDump; +import org.onap.ccsdk.apps.cadi.lur.LocalLur; +import org.onap.ccsdk.apps.cadi.lur.LocalPermission; +import org.onap.ccsdk.apps.cadi.util.Split; + +public class JU_UsersDump { + + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream stdoutSuppressor; + + private static final String expected = "<?xml version='1.0' encoding='utf-8'?>\n" + + "<!--\n" + + " Code Generated Tomcat Users and Roles from AT&T LUR on ...\n" + + "-->\n" + + "<tomcat-users>\n" + + " <role rolename=\"suser\"/>\n" + + " <role rolename=\"admin\"/>\n" + + " <role rolename=\"groupB\"/>\n" + + " <role rolename=\"groupA\"/>\n" + + " \n" + + " <user username=\"hisname@people.osaaf.org\" roles=\"suser\"/>\n" + + " <user username=\"yourname@people.osaaf.org\" roles=\"admin\"/>\n" + + " <user username=\"myname@people.osaaf.org\" roles=\"admin\"/>\n" + + " <user username=\"m1234@people.osaaf.org\" roles=\"suser\"/>\n" + + " <user username=\"myname\" roles=\"groupB,groupA\"/>\n" + + " <user username=\"hername@people.osaaf.org\" roles=\"suser\"/>\n" + + "</tomcat-users>\n"; + + private final static String groups = "myname:groupA,groupB"; + private final static String names = "admin:myname,yourname;suser:hisname,hername,m1234"; + + private AbsUserCache<LocalPermission> lur; + + @Before + public void setup() throws IOException { + outStream = new ByteArrayOutputStream(); + stdoutSuppressor = new ByteArrayOutputStream(); + + System.setOut(new PrintStream(stdoutSuppressor)); + + lur = new LocalLur(new PropAccess(), groups, names); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void writeTest() throws IOException { + UsersDump.write(outStream, lur); + String[] actualLines = Split.splitTrim('\n', outStream.toString()); + String[] expectedLines = Split.splitTrim('\n', expected); + for (String s : actualLines) { + System.out.println(s); + } + + assertThat(actualLines.length, is(expectedLines.length)); + + // Check that the output starts with an XML tag + assertThat(actualLines[0], is(expectedLines[0])); + // Check that lines 2-4 are a comment + assertThat(actualLines[1], is(expectedLines[1])); + assertThat(actualLines[3], is(expectedLines[3])); + + // Check that the rest of the output matches the expected output + for (int i = 4; i < actualLines.length; i++) { + assertThat(actualLines[i], is(expectedLines[i])); + } + + // Run the test again with outStream as a PrintStream (for coverage) + outStream.reset(); + UsersDump.write(new PrintStream(outStream), lur); + actualLines = Split.splitTrim('\n', outStream.toString()); + + assertThat(actualLines.length, is(expectedLines.length)); + + // Check that the output starts with an XML tag + assertThat(actualLines[0], is(expectedLines[0])); + // Check that lines 2-4 are a comment + assertThat(actualLines[1], is(expectedLines[1])); + assertThat(actualLines[3], is(expectedLines[3])); + + // Check that the rest of the output matches the expected output + for (int i = 4; i < actualLines.length; i++) { + assertThat(actualLines[i], is(expectedLines[i])); + } + } + + @Test + public void updateUsersTest() { + String output; + File outputFile = new File("src/test/resources/userdump.xml"); + assertThat(outputFile.exists(), is(false)); + + output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); + assertThat(output, is(nullValue())); + assertThat(outputFile.exists(), is(true)); + + output = UsersDump.updateUsers("src/test/resources/userdump.xml", (LocalLur) lur); + assertThat(output, is(nullValue())); + assertThat(outputFile.exists(), is(true)); + + outputFile.delete(); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_AUTHZServlet.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_AUTHZServlet.java new file mode 100644 index 00000000..a89f4a31 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_AUTHZServlet.java @@ -0,0 +1,107 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.filter.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.lang.reflect.Field; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.filter.AUTHZServlet; + +import jakarta.servlet.Servlet; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequestWrapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +public class JU_AUTHZServlet { + + @Mock private Servlet servletMock; + @Mock private ServletConfig servletConfigMock; + @Mock private HttpServletRequest reqMock; + @Mock private HttpServletResponse respMock; + @Mock private ServletRequestWrapper servletWrapperMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test() throws ServletException, IOException { + AUTHZServletStub servlet = new AUTHZServletStub(Servlet.class); + + try { + servlet.init(servletConfigMock); + fail("Should've thrown an exception"); + } catch (ServletException e) { + assertThat(e.getMessage(), is("Invalid Servlet Delegate")); + } + + setPrivateField(AUTHZServlet.class, "delegate", servlet, servletMock); + servlet.init(servletConfigMock); + servlet.getServletConfig(); + servlet.getServletInfo(); + + servlet.service(reqMock, respMock); + + String[] roles = new String[] {"role1", "role2"}; + setPrivateField(AUTHZServlet.class, "roles", servlet, roles); + servlet.service(reqMock, respMock); + + when(reqMock.isUserInRole("role1")).thenReturn(true); + servlet.service(reqMock, respMock); + + try { + servlet.service(servletWrapperMock, respMock); + fail("Should've thrown an exception"); + } catch (ServletException e) { + assertThat(e.getMessage(), is("JASPIServlet only supports HTTPServletRequest/HttpServletResponse")); + } + servlet.destroy(); + } + + private class AUTHZServletStub extends AUTHZServlet<Servlet> { + public AUTHZServletStub(Class<Servlet> cls) { super(cls); } + } + + private void setPrivateField(Class<?> clazz, String fieldName, Object target, Object value) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(target, value); + field.setAccessible(false); + } catch (Exception e) { + System.err.println("Could not set field [" + fieldName + "] to " + value); + } + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_AccessGetter.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_AccessGetter.java new file mode 100644 index 00000000..ce384b08 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_AccessGetter.java @@ -0,0 +1,54 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.filter.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.filter.AccessGetter; + +public class JU_AccessGetter { + + private static final String tag = "tag"; + private static final String value = "value"; + + private PropAccess access; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(tag, value); + } + + @Test + public void test() { + AccessGetter getter = new AccessGetter(access); + assertThat(getter.get(tag, null, false), is(value)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_MapPermConverter.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_MapPermConverter.java new file mode 100644 index 00000000..65d0c2d7 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_MapPermConverter.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.filter.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.filter.MapPermConverter; + +public class JU_MapPermConverter { + + private static final String tag = "tag"; + private static final String value = "value"; + private static final String nontag = "nontag"; + + @Test + public void test() { + MapPermConverter converter = new MapPermConverter(); + assertThat(converter.map().isEmpty(), is(true)); + converter.map().put(tag, value); + assertThat(converter.convert(tag), is(value)); + assertThat(converter.convert(nontag), is(nontag)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_NullPermConverter.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_NullPermConverter.java new file mode 100644 index 00000000..92b467f7 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_NullPermConverter.java @@ -0,0 +1,38 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.filter.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.filter.NullPermConverter; + +public class JU_NullPermConverter { + + @Test + public void test() { + NullPermConverter converter = NullPermConverter.singleton(); + assertThat(converter.convert("test"), is("test")); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_PathFilter.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_PathFilter.java new file mode 100644 index 00000000..6a133b13 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/filter/test/JU_PathFilter.java @@ -0,0 +1,105 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.filter.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.security.Principal; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.config.Config; +import org.onap.ccsdk.apps.cadi.filter.PathFilter; + +public class JU_PathFilter { + + private PropAccess access; + + @Mock private FilterConfig filterConfigMock; + @Mock private ServletContext contextMock; + @Mock private HttpServletRequest reqMock; + @Mock private HttpServletResponse respMock; + @Mock private FilterChain chainMock; + @Mock private Principal princMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(filterConfigMock.getServletContext()).thenReturn(contextMock); + when(reqMock.getUserPrincipal()).thenReturn(princMock); + when(princMock.getName()).thenReturn("name"); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws ServletException, IOException { + PathFilter pathFilter = new PathFilter(access); + try { + pathFilter.init(filterConfigMock); + fail("Should've thrown an exception"); + } catch (ServletException e) { + assertThat(e.getMessage(), is("PathFilter - pathfilter_ns is not set")); + } + + when(contextMock.getAttribute(Config.PATHFILTER_NS)).thenReturn(5); + when(contextMock.getAttribute(Config.PATHFILTER_STACK)).thenReturn(5); + when(contextMock.getAttribute(Config.PATHFILTER_URLPATTERN)).thenReturn(5); + when(contextMock.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG)).thenReturn(5); + pathFilter.init(filterConfigMock); + + pathFilter.doFilter(reqMock, respMock, chainMock); + + when(reqMock.isUserInRole(anyString())).thenReturn(true); + pathFilter.doFilter(reqMock, respMock, chainMock); + + pathFilter.destroy(); + + pathFilter = new PathFilter(); + pathFilter.init(filterConfigMock); + + pathFilter.doFilter(reqMock, respMock, chainMock); + + when(reqMock.isUserInRole(anyString())).thenReturn(false); + pathFilter.doFilter(reqMock, respMock, chainMock); + + pathFilter.destroy(); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_ConfigPrincipal.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_ConfigPrincipal.java new file mode 100644 index 00000000..47ccb813 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_ConfigPrincipal.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.lur.test; + +import org.junit.*; +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import java.lang.reflect.Field; + +import java.io.IOException; + +import org.onap.ccsdk.apps.cadi.lur.ConfigPrincipal; + +public class JU_ConfigPrincipal { + + private final String name = "User"; + private final String pass = "pass"; + + // Expected output of base64("User:pass") + private final String b64encoded = "VXNlcjpwYXNz"; + + private Field content_field; + + @Before + public void setup() throws NoSuchFieldException { + content_field = ConfigPrincipal.class.getDeclaredField("content"); + content_field.setAccessible(true); + } + + @Test + public void testConfigPrincipalStringString() throws IOException, IllegalArgumentException, IllegalAccessException { + ConfigPrincipal p = new ConfigPrincipal(name, pass); + + assertThat(p.getName(), is(name)); + assertThat(p.toString(), is(name)); + assertThat(p.getCred(), is(pass.getBytes())); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + content_field.set(p, "pass"); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + + // One more time for coverage purposes + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + } + + @Test + public void testConfigPrincipalStringByteArray() throws IOException, IllegalArgumentException, IllegalAccessException { + ConfigPrincipal p = new ConfigPrincipal(name, pass.getBytes()); + + assertThat(p.getName(), is(name)); + assertThat(p.toString(), is(name)); + assertThat(p.getCred(), is(pass.getBytes())); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + content_field.set(p, "pass"); + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + + // One more time for coverage purposes + assertThat(p.getAsBasicAuthHeader(), is("Basic " + b64encoded)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_EpiLur.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_EpiLur.java new file mode 100644 index 00000000..37183080 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_EpiLur.java @@ -0,0 +1,128 @@ +/** + * + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.lur.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.CachingLur; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.CredVal; +import org.onap.ccsdk.apps.cadi.Lur; +import org.onap.ccsdk.apps.cadi.Permission; +import org.onap.ccsdk.apps.cadi.lur.EpiLur; + +public class JU_EpiLur { + + private ArrayList<Permission> perms; + private CredValStub lurMock3; + + @Mock private Lur lurMock1; + @Mock private CachingLur<?> lurMock2; + @Mock private Principal princMock; + @Mock private Permission permMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + perms = new ArrayList<>(); + perms.add(permMock); + + lurMock3 = new CredValStub(); + } + + @Test + public void test() throws CadiException { + EpiLur lur; + try { + lur = new EpiLur(); + } catch (CadiException e) { + assertThat(e.getMessage(), is("Need at least one Lur implementation in constructor")); + } + lur = new EpiLur(lurMock1, lurMock2, lurMock3); + assertThat(lur.fish(null, null), is(false)); + + assertThat(lur.fish(princMock, permMock), is(false)); + + when(lurMock2.handlesExclusively(permMock)).thenReturn(true); + assertThat(lur.fish(princMock, permMock), is(false)); + + when(lurMock2.fish(princMock, permMock)).thenReturn(true); + assertThat(lur.fish(princMock, permMock), is(true)); + + lur.fishAll(princMock, perms); + + assertThat(lur.handlesExclusively(permMock), is(false)); + + assertThat(lur.get(-1), is(nullValue())); + assertThat(lur.get(0), is(lurMock1)); + assertThat(lur.get(1), is((Lur)lurMock2)); + assertThat(lur.get(2), is((Lur)lurMock3)); + assertThat(lur.get(3), is(nullValue())); + + assertThat(lur.handles(princMock), is(false)); + when(lurMock2.handles(princMock)).thenReturn(true); + assertThat(lur.handles(princMock), is(true)); + + lur.remove("id"); + + lur.clear(princMock, null); + + assertThat(lur.createPerm("perm"), is(not(nullValue()))); + + lur.getUserPassImpl(); + assertThat(lur.getUserPassImpl(), is((CredVal)lurMock3)); + + lur.toString(); + lur.destroy(); + + lur = new EpiLur(lurMock1, lurMock2); + assertThat(lur.getUserPassImpl(), is(nullValue())); + + assertThat(lur.subLur(Lur.class), is(nullValue())); + } + + private class CredValStub implements Lur, CredVal { + @Override public boolean validate(String user, Type type, byte[] cred, Object state) { return false; } + @Override public Permission createPerm(String p) { return null; } + @Override public boolean fish(Principal bait, Permission ... pond) { return false; } + @Override public void fishAll(Principal bait, List<Permission> permissions) { } + @Override public void destroy() { } + @Override public boolean handlesExclusively(Permission ... pond) { return false; } + @Override public boolean handles(Principal principal) { return false; } + @Override public void clear(Principal p, StringBuilder report) { } + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_LocalLur.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_LocalLur.java new file mode 100644 index 00000000..51850113 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_LocalLur.java @@ -0,0 +1,173 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.lur.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.AbsUserCache; +import org.onap.ccsdk.apps.cadi.CredVal.Type; +import org.onap.ccsdk.apps.cadi.Permission; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.lur.ConfigPrincipal; +import org.onap.ccsdk.apps.cadi.lur.LocalLur; +import org.onap.ccsdk.apps.cadi.lur.LocalPermission; + +public class JU_LocalLur { + + private PropAccess access; + private ByteArrayOutputStream outStream; + + @Mock Permission permMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + outStream = new ByteArrayOutputStream(); + access = new PropAccess(new PrintStream(outStream), new String[0]) { + @Override public String decrypt(String encrypted, boolean anytext) throws IOException { + return rot13(encrypted); + } + @Override public String encrypt(String unencrypted) throws IOException { + return rot13(unencrypted); + } + }; + + } + + @Test + public void test() throws IOException { + final String password = "<pass>"; + final String encrypted = rot13(password); + + LocalLur lur; + List<AbsUserCache<LocalPermission>.DumpInfo> info; + + lur = new LocalLur(access, null, null); + assertThat(lur.dumpInfo().size(), is(0)); + + lur = new LocalLur(access, "user1", null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1")); + + lur.clearAll(); + assertThat(lur.dumpInfo().size(), is(0)); + + lur = new LocalLur(access, "user1%" + encrypted, null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1@people.osaaf.org")); + + lur.clearAll(); + assertThat(lur.dumpInfo().size(), is(0)); + + lur = new LocalLur(access, "user1@domain%" + encrypted, null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1@domain")); + + lur = new LocalLur(access, "user1@domain%" + encrypted + ":groupA", null); + info = lur.dumpInfo(); + assertThat(info.size(), is(1)); + assertThat(info.get(0).user, is("user1@domain")); + + when(permMock.getKey()).thenReturn("groupA"); + assertThat(lur.handlesExclusively(permMock), is(true)); + when(permMock.getKey()).thenReturn("groupB"); + assertThat(lur.handlesExclusively(permMock), is(false)); + + assertThat(lur.fish(null, null), is(false)); + + Principal princ = new ConfigPrincipal("user1@localized", encrypted); + + lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); + assertThat(lur.fish(princ, lur.createPerm("groupA")), is(true)); + assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); + assertThat(lur.fish(princ, permMock), is(false)); + + princ = new ConfigPrincipal("user1@domain", encrypted); + assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); + + princ = new ConfigPrincipal("user1@localized", "badpass"); + assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false)); + + assertThat(lur.handles(null), is(false)); + + lur.fishAll(null, null); + + List<Permission> perms = new ArrayList<>(); + perms.add(lur.createPerm("groupB")); + perms.add(lur.createPerm("groupA")); + princ = new ConfigPrincipal("user1@localized", encrypted); + lur.fishAll(princ, perms); + princ = new ConfigPrincipal("user1@localized", "badpass"); + lur.fishAll(princ, perms); + + assertThat(lur.validate(null, null, null, null), is(false)); + assertThat(lur.validate("user", null, "badpass".getBytes(), null), is(false)); + assertThat(lur.validate("user1@localized", null, encrypted.getBytes(), null), is(false)); + + lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null); + // Inconsistent on Jenkins only. + //assertThat(lur.validate("user1@localized", Type.PASSWORD, encrypted.getBytes(), null), is(true)); + + lur = new LocalLur(access, null, "admin"); + lur = new LocalLur(access, null, "admin:user1"); + lur = new LocalLur(access, null, "admin:user1@localized"); + lur = new LocalLur(access, null, "admin:user1@localized,user2@localized%" + password + ";user:user1@localized"); + } + + public static String rot13(String input) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < input.length(); i++) { + char c = input.charAt(i); + if (c >= 'a' && c <= 'm') { + c += 13; + } else if (c >= 'A' && c <= 'M') { + c += 13; + } else if (c >= 'n' && c <= 'z') { + c -= 13; + } else if (c >= 'N' && c <= 'Z') { + c -= 13; + } + sb.append(c); + } + return sb.toString(); + } + +} + diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_LocalPermission.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_LocalPermission.java new file mode 100644 index 00000000..2c318b2c --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_LocalPermission.java @@ -0,0 +1,72 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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,Z + * * 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.lur.test; + +import static org.junit.Assert.*; + +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import static org.mockito.Mockito.*; + +import org.onap.ccsdk.apps.cadi.lur.LocalPermission; +import org.onap.ccsdk.apps.cadi.Permission; + +public class JU_LocalPermission { + + @Mock + Permission perm; + + private LocalPermission localPerm; + private String role = "Fake Role"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(perm.getKey()).thenReturn(role); + + localPerm = new LocalPermission(role); + } + + @Test + public void getKeyTest() { + assertThat(localPerm.getKey(), is(role)); + } + + @Test + public void toStringTest() { + assertThat(localPerm.toString(), is(role)); + } + + @Test + public void matchTest() { + assertTrue(localPerm.match(perm)); + } + + @Test + public void permTypeTest() { + assertThat(localPerm.permType(), is("LOCAL")); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_NullLur.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_NullLur.java new file mode 100644 index 00000000..a9938233 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/lur/test/JU_NullLur.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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,Z + * * 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.lur.test; + +import java.security.Principal; +import java.util.List; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; +import org.junit.*; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import java.lang.reflect.*; + +import org.onap.ccsdk.apps.cadi.Permission; +import org.onap.ccsdk.apps.cadi.lur.NullLur; + +public class JU_NullLur { + + @Mock + Principal p; + + @Mock + Permission perm; + + @Mock + List<Permission> perms; + + private NullLur nullLur; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + nullLur = new NullLur(); + } + + @Test + public void coverageTests() throws Exception { + + Field nullClass = NullLur.class.getDeclaredField("NULL"); + nullClass.setAccessible(true); + assertThat(((Permission) nullClass.get(NullLur.class)).permType(), is("")); + assertThat(((Permission) nullClass.get(NullLur.class)).getKey(), is("")); + assertFalse(((Permission) nullClass.get(NullLur.class)).match(perm)); + + nullLur.fishAll(p, perms); + nullLur.destroy(); + + assertFalse(nullLur.fish(p, perm)); + assertFalse(nullLur.handlesExclusively(perm)); + assertFalse(nullLur.handles(p)); + assertThat(nullLur.createPerm(""), is(nullClass.get(NullLur.class))); + + StringBuilder sb = new StringBuilder(); + nullLur.clear(p, sb); + assertThat(sb.toString(), is("NullLur\n")); + assertThat(nullLur.toString(), is("NullLur\n")); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_BasicPrincipal.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_BasicPrincipal.java new file mode 100644 index 00000000..d4479c2a --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_BasicPrincipal.java @@ -0,0 +1,124 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.principal.test; + +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.mock; +import org.junit.*; + +import java.io.IOException; +import java.util.Date; + +import org.onap.ccsdk.apps.cadi.BasicCred; +import org.onap.ccsdk.apps.cadi.Symm; +import org.onap.ccsdk.apps.cadi.principal.BasicPrincipal; + +public class JU_BasicPrincipal { + + @Test + public void Constructor1Test() throws Exception { + // Test that everything works when the content doesn't contain "Basic" + BasicPrincipal bp = new BasicPrincipal("content", "domain"); + assertThat(bp.getName(), is("content")); + assertThat(bp.getCred(), is(nullValue())); + + // Test sending a user without an implicit domain + String name = "User"; + String password = "password"; + String content = name + ":" + password; + String domain = "exampledomain.com"; + String encrypted = new String(Symm.base64.encode(content.getBytes())); + bp = new BasicPrincipal("Basic " + encrypted, domain); + assertThat(bp.getShortName(), is(name)); + assertThat(bp.getName(), is(name + "@" + domain)); + assertThat(bp.getCred(), is(password.getBytes())); + + // Test sending a user with an implicit domain + String longName = name + "@" + domain + ":" + password; + encrypted = new String(Symm.base64.encode(longName.getBytes())); + bp = new BasicPrincipal("Basic " + encrypted, domain); + assertThat(bp.getShortName(), is(name)); + assertThat(bp.getName(), is(name + "@" + domain)); + assertThat(bp.getCred(), is(password.getBytes())); + + // Check that an exception is throw if no name is given in the content + try { + bp = new BasicPrincipal("Basic " + new String(Symm.base64.encode("no name".getBytes())), ""); + fail("Should have thrown an exception"); + } catch (IOException e) { + assertThat(e.getMessage(), is("Invalid Coding")); + } + } + + @Test + public void Constructor2Test() { + String name = "User"; + String password = "password"; + BasicCred bc = mock(BasicCred.class); + when(bc.getUser()).thenReturn(name); + when(bc.getCred()).thenReturn(password.getBytes()); + + BasicPrincipal bp = new BasicPrincipal(bc, "domain"); + assertThat(bp.getName(), is(name)); + assertThat(bp.getCred(), is(password.getBytes())); + } + + @Test + public void accessorsTest() throws IOException { + String name = "User"; + String password = "password"; + String content = name + ":" + password; + String domain = "exampledomain.com"; + String encrypted = new String(Symm.base64.encode(content.getBytes())); + String bearer = "bearer"; + long created = System.currentTimeMillis(); + BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, domain); + bp.setBearer(bearer); + + String expected = "Basic Authorization for " + name + "@" + domain + " evaluated on " + new Date(bp.created()).toString(); + assertTrue(Math.abs(bp.created() - created) < 10); + assertThat(bp.toString(), is(expected)); + assertThat(bp.tag(), is("BAth")); + assertThat(bp.personalName(), is(bp.getName())); + + // This test hits the abstract class BearerPrincipal + assertThat(bp.getBearer(), is(bearer)); + } + + + @Test + public void coverageTest() throws IOException { + String name = "User"; + String password = "password:with:colons"; + String content = name + ":" + password; + String encrypted = new String(Symm.base64.encode(content.getBytes())); + @SuppressWarnings("unused") + BasicPrincipal bp = new BasicPrincipal("Basic " + encrypted, "domain"); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_CachedBasicPrincipal.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_CachedBasicPrincipal.java new file mode 100644 index 00000000..50ec96dc --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_CachedBasicPrincipal.java @@ -0,0 +1,124 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.principal.test; + +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.hamcrest.CoreMatchers.is; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.mock; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.io.IOException; +import java.lang.reflect.Field; + +import org.onap.ccsdk.apps.cadi.BasicCred; +import org.onap.ccsdk.apps.cadi.CachedPrincipal; +import org.onap.ccsdk.apps.cadi.principal.CachedBasicPrincipal; +import org.onap.ccsdk.apps.cadi.taf.HttpTaf; + +public class JU_CachedBasicPrincipal { + private Field creatorField; + private Field timeToLiveField; + + @Mock + private HttpTaf creator; + + private CachedPrincipal.Resp resp; + + @Before + public void setup() throws NoSuchFieldException, SecurityException { + MockitoAnnotations.initMocks(this); + + creatorField = CachedBasicPrincipal.class.getDeclaredField("creator"); + timeToLiveField = CachedBasicPrincipal.class.getDeclaredField("timeToLive"); + + creatorField.setAccessible(true); + timeToLiveField.setAccessible(true); + } + + @Test + public void Constructor1Test() throws IllegalArgumentException, IllegalAccessException { + String name = "User"; + String password = "password"; + BasicCred bc = mock(BasicCred.class); + when(bc.getUser()).thenReturn(name); + when(bc.getCred()).thenReturn(password.getBytes()); + + long timeToLive = 10000L; + long expires = System.currentTimeMillis() + timeToLive; + CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, bc, "domain", timeToLive); + + assertThat((HttpTaf)creatorField.get(cbp), is(creator)); + assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + } + + @Test + public void Constructor2Test() throws Exception { + String name = "User"; + String password = "password"; + String content = name + ":" + password; + long timeToLive = 10000L; + long expires = System.currentTimeMillis() + timeToLive; + CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); + + assertThat((HttpTaf)creatorField.get(cbp), is(creator)); + assertThat((Long)timeToLiveField.get(cbp), is(timeToLive)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + } + + @Test + public void revalidateTest() throws IOException, IllegalArgumentException, IllegalAccessException, InterruptedException { + resp = CachedPrincipal.Resp.REVALIDATED; + when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); + + String name = "User"; + String password = "password"; + String content = name + ":" + password; + long timeToLive = 10000L; + long expires = System.currentTimeMillis() + timeToLive; + CachedBasicPrincipal cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); + + assertTrue(Math.abs(cbp.expires() - expires) < 10); + + Thread.sleep(1); + expires = System.currentTimeMillis() + timeToLive; + assertThat(cbp.revalidate(new Object()), is(resp)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + + resp = CachedPrincipal.Resp.UNVALIDATED; + when(creator.revalidate((CachedPrincipal)any(), any())).thenReturn(resp); + expires = System.currentTimeMillis() + timeToLive; + cbp = new CachedBasicPrincipal(creator, content, "domain", timeToLive); + + assertThat(cbp.revalidate(new Object()), is(resp)); + assertTrue(Math.abs(cbp.expires() - expires) < 10); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_Kind.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_Kind.java new file mode 100644 index 00000000..208340a3 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_Kind.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.principal.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import org.onap.ccsdk.apps.cadi.principal.BasicPrincipal; +import org.onap.ccsdk.apps.cadi.principal.Kind; +import org.onap.ccsdk.apps.cadi.principal.OAuth2FormPrincipal; +import org.onap.ccsdk.apps.cadi.principal.TrustPrincipal; +import org.onap.ccsdk.apps.cadi.principal.X509Principal; + +public class JU_Kind { + + @Mock + private TrustPrincipal trust; + + @Mock + private X509Principal x509; + + @Mock + private OAuth2FormPrincipal oauth; + + @Mock + private BasicPrincipal basic; + + @Before + public void setup() throws SecurityException { + MockitoAnnotations.initMocks(this); + } + + @Test + public void getKind() { + assertThat(Kind.getKind(trust), is('U')); + assertThat(Kind.getKind(x509), is('X')); + assertThat(Kind.getKind(oauth), is('O')); + assertThat(Kind.getKind(basic), is('B')); + } + + @Test + public void coverageTest() { + @SuppressWarnings("unused") + Kind kind = new Kind(); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_OAuth2FormPrincipal.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_OAuth2FormPrincipal.java new file mode 100644 index 00000000..180f7798 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_OAuth2FormPrincipal.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.principal.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.principal.OAuth2FormPrincipal; + +public class JU_OAuth2FormPrincipal { + + private String username = "user"; + private String id = "id"; + + @Test + public void accessorsTest() { + OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); + assertThat(oauth.getName(), is(username)); + assertThat(oauth.client_id(), is(id)); + assertThat(oauth.tag(), is("OAuth")); + } + + @Test + public void personalNameTest() { + OAuth2FormPrincipal oauth = new OAuth2FormPrincipal(id, username); + assertThat(oauth.personalName(), is(username + "|" + id)); + + oauth = new OAuth2FormPrincipal(id, null); + assertThat(oauth.personalName(), is(id)); + + oauth = new OAuth2FormPrincipal(id, id); + assertThat(oauth.personalName(), is(id)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_StringTagLookup.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_StringTagLookup.java new file mode 100644 index 00000000..8e9656cf --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_StringTagLookup.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.principal.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.principal.StringTagLookup; + +public class JU_StringTagLookup { + + @Test + public void accessorsTest() throws Exception { + String tag = "tag"; + StringTagLookup stl = new StringTagLookup(tag); + assertThat(stl.lookup(), is(tag)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_TaggedPrincipal.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_TaggedPrincipal.java new file mode 100644 index 00000000..fe58f7d2 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_TaggedPrincipal.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.principal.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal; +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal.TagLookup; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.principal.StringTagLookup; + +public class JU_TaggedPrincipal { + + private final String name = "stubbedName"; + private final String tag = "tag"; + + private class TaggedPrincipalStub extends TaggedPrincipal { + public TaggedPrincipalStub() { super(); } + public TaggedPrincipalStub(final TagLookup tl) { super(tl); } + @Override public String getName() { return name; } + @Override public String tag() { return null; } + } + + private class WhinyTagLookup implements TagLookup { + public WhinyTagLookup(final String tag) { } + @Override + public String lookup() throws CadiException { + throw new CadiException(); + } + } + + @Test + public void personalNameTest() { + TaggedPrincipal tp = new TaggedPrincipalStub(); + assertThat(tp.personalName(), is(name)); + + StringTagLookup stl = new StringTagLookup(tag); + tp = new TaggedPrincipalStub(stl); + assertThat(tp.personalName(), is(tag)); + + WhinyTagLookup wtl = new WhinyTagLookup(tag); + tp.setTagLookup(wtl); + assertThat(tp.personalName(), is(name)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_TrustPrincipal.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_TrustPrincipal.java new file mode 100644 index 00000000..d47f7612 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_TrustPrincipal.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.principal.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.security.Principal; + +import org.onap.ccsdk.apps.cadi.UserChain; +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal; +import org.onap.ccsdk.apps.cadi.principal.TrustPrincipal; + +public class JU_TrustPrincipal { + + private final String ucName = "UserChain"; + private final String uc = "This is a UserChain"; + private final String taggedName = "TaggedPrincipal"; + private final String tag = "tag"; + private final String pName = "Principal"; + + private class UserChainPrincipalStub implements Principal, UserChain { + @Override public String userChain() { return uc; } + @Override public String getName() { return ucName; } + } + + private class TaggedPrincipalStub extends TaggedPrincipal { + public TaggedPrincipalStub() { super(); } + @Override public String getName() { return taggedName; } + @Override public String tag() { return tag; } + } + + private class PrincipalStub implements Principal { + @Override public String getName() { return pName; } + } + + @Test + public void userChainConstructorTest() { + UserChainPrincipalStub ucps = new UserChainPrincipalStub(); + TrustPrincipal tp = new TrustPrincipal(ucps, taggedName); + assertThat(tp.getName(), is(taggedName)); + assertThat(tp.userChain(), is(uc)); + assertSame(tp.original(), ucps); + assertThat(tp.tag(), is(uc)); + assertThat(tp.personalName(), is(ucName + '[' + uc + ']')); + } + + @Test + public void taggedPrincipalConstructorTest() { + TaggedPrincipal tagged = new TaggedPrincipalStub(); + TrustPrincipal tp = new TrustPrincipal(tagged, taggedName); + assertThat(tp.getName(), is(taggedName)); + assertThat(tp.userChain(), is(tag)); + assertSame(tp.original(), tagged); + assertThat(tp.tag(), is(tag)); + assertThat(tp.personalName(), is(taggedName + '[' + tag + ']')); + } + + @Test + public void principalConstructorTest() { + Principal principal = new PrincipalStub(); + TrustPrincipal tp = new TrustPrincipal(principal, pName); + assertThat(tp.getName(), is(pName)); + assertThat(tp.userChain(), is(principal.getClass().getSimpleName())); + assertSame(tp.original(), principal); + assertThat(tp.tag(), is(principal.getClass().getSimpleName())); + assertThat(tp.personalName(), is(pName + '[' + principal.getClass().getSimpleName() + ']')); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_UnAuthPrincipal.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_UnAuthPrincipal.java new file mode 100644 index 00000000..4eccf27e --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_UnAuthPrincipal.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.principal.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.principal.UnAuthPrincipal; + +public class JU_UnAuthPrincipal { + + private final String name = "name"; + + @Test + public void accessorsTest() { + UnAuthPrincipal up = new UnAuthPrincipal(name); + assertThat(up.getName(), is(name)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_X509Principal.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_X509Principal.java new file mode 100644 index 00000000..47ec43b1 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/principal/test/JU_X509Principal.java @@ -0,0 +1,140 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.principal.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; +import org.junit.*; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.io.IOException; +import java.security.Principal; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; + +import org.onap.ccsdk.apps.cadi.principal.X509Principal; + +public class JU_X509Principal { + + private final String name = "x509 name"; + private final byte[] cred = "super duper secret password".getBytes(); + + @Mock + X509Certificate cert; + + @Mock + Principal subject; + + @Before + public void setup() throws CertificateEncodingException { + MockitoAnnotations.initMocks(this); + when(cert.getEncoded()).thenReturn(cred); + } + + @Test + public void constructor1Test() throws IOException { + X509Principal x509 = new X509Principal(name, cert); + // Call twice to hit both branches + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.toString(), is("X509 Authentication for " + name)); + assertTrue(x509.getCred().equals(cred)); + assertThat(x509.getName(), is(name)); + assertThat(x509.tag(), is("x509")); + } + + @Test + public void constructor2Test() throws IOException { + X509Principal x509 = new X509Principal(name, cert, cred,null); + // Call twice to hit both branches + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.toString(), is("X509 Authentication for " + name)); + assertTrue(x509.getCred().equals(cred)); + assertThat(x509.getName(), is(name)); + assertThat(x509.tag(), is("x509")); + } + + @Test + public void constructor3Test() throws IOException { + final String longName = "name@domain"; + when(subject.getName()).thenReturn("OU=" + longName + ",extra"); + when(cert.getSubjectDN()).thenReturn(subject); + X509Principal x509 = new X509Principal(cert, cred,null); + // Call twice to hit both branches + assertThat(x509.getAsHeader(), is("X509 " + cred)); + assertThat(x509.toString(), is("X509 Authentication for " + longName)); + assertTrue(x509.getCred().equals(cred)); + assertThat(x509.getName(), is(longName)); + + when(subject.getName()).thenReturn(longName + ",extra"); + when(cert.getSubjectDN()).thenReturn(subject); + try { + x509 = new X509Principal(cert, cred, null); + fail("Should have thrown an Exception"); + } catch (IOException e) { + assertThat(e.getMessage(), is("X509 does not have Identity as CN")); + } + + when(subject.getName()).thenReturn("OU=" + longName); + when(cert.getSubjectDN()).thenReturn(subject); + try { + x509 = new X509Principal(cert, cred, null); + fail("Should have thrown an Exception"); + } catch (IOException e) { + assertThat(e.getMessage(), is("X509 does not have Identity as CN")); + } + + when(subject.getName()).thenReturn("OU=" + name + ",exta"); + when(cert.getSubjectDN()).thenReturn(subject); + try { + x509 = new X509Principal(cert, cred, null); + fail("Should have thrown an Exception"); + } catch (IOException e) { + assertThat(e.getMessage(), is("X509 does not have Identity as CN")); + } + + } + + @Test + public void throwsTest() throws CertificateEncodingException { + when(cert.getEncoded()).thenThrow(new CertificateEncodingException()); + X509Principal x509 = new X509Principal(name, cert); + assertThat(x509.getCred(), is(nullValue())); + try { + x509.getAsHeader(); + fail("Should have thrown an Exception"); + } catch (IOException e) { + } + } + + @Test + public void getCredTest() { + X509Principal x509 = new X509Principal(name, cert); + // Call twice to hit both branches + assertTrue(x509.getCred().equals(cred)); + assertTrue(x509.getCred().equals(cred)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/basic/test/JU_BasicHttpTaf.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/basic/test/JU_BasicHttpTaf.java new file mode 100644 index 00000000..0e75ea37 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/basic/test/JU_BasicHttpTaf.java @@ -0,0 +1,213 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.taf.basic.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import java.security.Principal; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Locale; +import java.util.Map; + +import jakarta.servlet.AsyncContext; +import jakarta.servlet.DispatcherType; +import jakarta.servlet.RequestDispatcher; +import jakarta.servlet.ServletConnection; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.HttpUpgradeHandler; +import jakarta.servlet.http.Part; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.BasicCred; +import org.onap.ccsdk.apps.cadi.CachedPrincipal; +import org.onap.ccsdk.apps.cadi.CachedPrincipal.Resp; +import org.onap.ccsdk.apps.cadi.CredVal; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.Symm; +import org.onap.ccsdk.apps.cadi.Taf.LifeForm; +import org.onap.ccsdk.apps.cadi.taf.basic.BasicHttpTaf; + +public class JU_BasicHttpTaf { + + private final static String realm = "realm"; + private final static String id = "id"; + private final static String addr = "addr"; + + private final static String name = "User"; + private final static String password = "password"; + private final static String content = name + ":" + password; + private static String encrypted; + + private final static long timeToLive = 10000L; + + private PropAccess access; + + @Mock private HttpServletResponse respMock; + @Mock private HttpServletRequest reqMock; + @Mock private CredVal rbacMock; + @Mock private CachedPrincipal princMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + encrypted = new String(Symm.base64.encode(content.getBytes())); + } + + @Test + public void test() { + BasicHttpTaf taf = new BasicHttpTaf(access, rbacMock, realm, timeToLive, true); + BasicCredStub bcstub = new BasicCredStub(); + assertThat(taf.validate(LifeForm.SBLF, bcstub, respMock), is(not(nullValue()))); + + assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); + + when(reqMock.getHeader("Authorization")).thenReturn("test"); + assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); + + when(reqMock.getHeader("Authorization")).thenReturn("Basic " + encrypted); + assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue()))); + + assertThat(taf.revalidate(princMock, "state"), is(Resp.NOT_MINE)); + + assertThat(taf.toString(), is("Basic Auth enabled on realm: " + realm)); + } + + private class BasicCredStub implements HttpServletRequest, BasicCred { + @Override public String getUser() { return id; } + @Override public String getRemoteAddr() { return addr; } + + @Override public AsyncContext getAsyncContext() { return null; } + @Override public Object getAttribute(String arg0) { return null; } + @Override public Enumeration<String> getAttributeNames() { return null; } + @Override public String getCharacterEncoding() { return null; } + @Override public int getContentLength() { return 0; } + @Override public String getContentType() { return null; } + @Override public DispatcherType getDispatcherType() { return null; } + @Override public ServletInputStream getInputStream() throws IOException { return null; } + @Override public String getLocalAddr() { return null; } + @Override public String getLocalName() { return null; } + @Override public int getLocalPort() { return 0; } + @Override public Locale getLocale() { return null; } + @Override public Enumeration<Locale> getLocales() { return null; } + @Override public String getParameter(String arg0) { return null; } + @Override public Map<String, String[]> getParameterMap() { return null; } + @Override public Enumeration<String> getParameterNames() { return null; } + @Override public String[] getParameterValues(String arg0) { return null; } + @Override public String getProtocol() { return null; } + @Override public BufferedReader getReader() throws IOException { return null; } + + @Override public String getRemoteHost() { return null; } + @Override public int getRemotePort() { return 0; } + @Override public RequestDispatcher getRequestDispatcher(String arg0) { return null; } + @Override public String getScheme() { return null; } + @Override public String getServerName() { return null; } + @Override public int getServerPort() { return 0; } + @Override public ServletContext getServletContext() { return null; } + @Override public boolean isAsyncStarted() { return false; } + @Override public boolean isAsyncSupported() { return false; } + @Override public boolean isSecure() { return false; } + @Override public void removeAttribute(String arg0) { } + @Override public void setAttribute(String arg0, Object arg1) { } + @Override public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { } + @Override public AsyncContext startAsync() throws IllegalStateException { return null; } + @Override public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) throws IllegalStateException { return null; } + @Override public byte[] getCred() { return null; } + @Override public void setUser(String user) { } + @Override public void setCred(byte[] passwd) { } + @Override public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException { return false; } + @Override public String getAuthType() { return null; } + @Override public String getContextPath() { return null; } + @Override public Cookie[] getCookies() { return null; } + @Override public long getDateHeader(String arg0) { return 0; } + @Override public String getHeader(String arg0) { return null; } + @Override public Enumeration<String> getHeaderNames() { return null; } + @Override public Enumeration<String> getHeaders(String arg0) { return null; } + @Override public int getIntHeader(String arg0) { return 0; } + @Override public String getMethod() { return null; } + @Override public Part getPart(String arg0) throws IOException, ServletException { return null; } + @Override public Collection<Part> getParts() throws IOException, ServletException { return null; } + @Override public String getPathInfo() { return null; } + @Override public String getPathTranslated() { return null; } + @Override public String getQueryString() { return null; } + @Override public String getRemoteUser() { return null; } + @Override public String getRequestURI() { return null; } + @Override public StringBuffer getRequestURL() { return null; } + @Override public String getRequestedSessionId() { return null; } + @Override public String getServletPath() { return null; } + @Override public HttpSession getSession() { return null; } + @Override public HttpSession getSession(boolean arg0) { return null; } + @Override public Principal getUserPrincipal() { return null; } + @Override public boolean isRequestedSessionIdFromCookie() { return false; } + @Override public boolean isRequestedSessionIdFromURL() { return false; } + @Override public boolean isRequestedSessionIdValid() { return false; } + @Override public boolean isUserInRole(String arg0) { return false; } + @Override public void login(String arg0, String arg1) throws ServletException { } + @Override public void logout() throws ServletException { } + @Override + public long getContentLengthLong() { + return 0L; + } + @Override + public String getRequestId() { + return null; + } + @Override + public String getProtocolRequestId() { + return null; + } + @Override + public ServletConnection getServletConnection() { + return null; + } + @Override + public String changeSessionId() { + return null; + } + @Override + public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) throws IOException, ServletException { + + throw new UnsupportedOperationException("Unimplemented method 'upgrade'"); + } + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/basic/test/JU_BasicHttpTafResp.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/basic/test/JU_BasicHttpTafResp.java new file mode 100644 index 00000000..b96738de --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/basic/test/JU_BasicHttpTafResp.java @@ -0,0 +1,67 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.taf.basic.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import jakarta.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; +import org.onap.ccsdk.apps.cadi.taf.basic.BasicHttpTafResp; + +public class JU_BasicHttpTafResp { + + private final static String realm = "realm"; + private final static String description = "description"; + + private PropAccess access; + + @Mock private HttpServletResponse respMock; + @Mock private TaggedPrincipal princMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws IOException { + BasicHttpTafResp tafResp = new BasicHttpTafResp(access, princMock, description, RESP.IS_AUTHENTICATED, respMock, realm, false); + + assertThat(tafResp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); + assertThat(tafResp.isAuthenticated(), is (RESP.IS_AUTHENTICATED)); + assertThat(tafResp.isFailedAttempt(), is(false)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/cert/test/JU_X509HttpTafResp.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/cert/test/JU_X509HttpTafResp.java new file mode 100644 index 00000000..a703a423 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/cert/test/JU_X509HttpTafResp.java @@ -0,0 +1,63 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.taf.cert.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; +import org.onap.ccsdk.apps.cadi.taf.cert.X509HttpTafResp; + +public class JU_X509HttpTafResp { + + private final static String description = "description"; + private final static RESP status = RESP.IS_AUTHENTICATED; + + private PropAccess access; + + @Mock private TaggedPrincipal princMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws IOException { + X509HttpTafResp resp = new X509HttpTafResp(access, princMock, description, status); + assertThat(resp.authenticate(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(resp.isAuthenticated(), is(status)); + assertThat(resp.toString(), is(status.name())); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/dos/test/JU_DenialOfServiceTaf.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/dos/test/JU_DenialOfServiceTaf.java new file mode 100644 index 00000000..4dc12c4e --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/dos/test/JU_DenialOfServiceTaf.java @@ -0,0 +1,372 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.taf.dos.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; +import org.junit.*; +import org.mockito.*; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.List; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.CachedPrincipal.Resp; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.config.Config; +import org.onap.ccsdk.apps.cadi.taf.TafResp; +import org.onap.ccsdk.apps.cadi.Taf.LifeForm; +import org.onap.ccsdk.apps.cadi.taf.dos.DenialOfServiceTaf; +import org.onap.ccsdk.apps.cadi.taf.dos.DenialOfServiceTaf.Counter; + +public class JU_DenialOfServiceTaf { + + @Mock + HttpServletResponse respMock; + + @Mock + HttpServletRequest reqMock1; + + @Mock + HttpServletRequest reqMock2; + + @Mock + HttpServletRequest reqMock3; + + @Mock + Access accessMock; + + private File dosIPFile; + private File dosIDFile; + private File dosDir; + private final String dosDirName = "test"; + + private final String id1 = "id1"; + private final String id2 = "id2"; + + private final String ip1 = "111.111.111.111"; + private final String ip2 = "222.222.222.222"; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + dosDir = new File(dosDirName); + dosDir.mkdirs(); + dosIPFile = new File(dosDirName, "/dosIP"); + dosIDFile = new File(dosDirName, "/dosID"); + dosIPFile.delete(); + dosIDFile.delete(); + + when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); + when(reqMock1.getRemoteAddr()).thenReturn(ip1); + when(reqMock2.getRemoteAddr()).thenReturn(ip2); + + setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); + setPrivateField(DenialOfServiceTaf.class, "deniedID", null); + setPrivateField(DenialOfServiceTaf.class, "dosIP", null); + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + } + + @After + public void tearDown() { + dosIPFile = new File(dosDirName, "/dosIP"); + dosIDFile = new File(dosDirName, "/dosID"); + dosIPFile.delete(); + dosIDFile.delete(); + } + + @Test + public void constructorTest() throws CadiException { + @SuppressWarnings("unused") + DenialOfServiceTaf dost; + + // coverage... + when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(null); + dost = new DenialOfServiceTaf(accessMock); + + when(accessMock.getProperty(Config.AAF_DATA_DIR, null)).thenReturn(dosDirName); + dost = new DenialOfServiceTaf(accessMock); + + // more coverage... + dost = new DenialOfServiceTaf(accessMock); + + // more coverage... + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + dost = new DenialOfServiceTaf(accessMock); + } + + @Test + public void validateTest() throws CadiException { + DenialOfServiceTaf dost; + TafResp tafResp; + + dost = new DenialOfServiceTaf(accessMock); + tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); + + assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); + assertThat(tafResp.taf(), is("DenialOfServiceTaf")); + + assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); + + tafResp = dost.validate(LifeForm.SBLF, reqMock1, respMock); + assertThat(tafResp.desc(), is(ip1 + " is on the IP Denial list")); + + tafResp = dost.validate(LifeForm.SBLF, reqMock2, respMock); + assertThat(tafResp.desc(), is("Not processing this transaction: This Transaction is not denied")); + assertThat(tafResp.taf(), is("DenialOfServiceTaf")); + } + + @Test + public void revalidateTest() throws CadiException { + DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); + Resp resp = dost.revalidate(null, null); + assertThat(resp, is(Resp.NOT_MINE)); + } + + @Test + public void denyIPTest() throws CadiException { + assertThat(DenialOfServiceTaf.isDeniedIP(ip1), is(nullValue())); + assertThat(DenialOfServiceTaf.denyIP(ip1), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyIP(ip2), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyIP(ip1), is(false)); // false because it's already been added + assertThat(DenialOfServiceTaf.denyIP(ip2), is(false)); // false because it's already been added + + Counter counter; + counter = DenialOfServiceTaf.isDeniedIP(ip1); + assertThat(counter.getName(), is(ip1)); + assertThat(counter.getCount(), is(0)); + assertThat(counter.getLast(), is(0L)); + assertThat(counter.toString(), is(ip1 + " is on the denied list, but has not attempted Access" )); + + DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); + dost.validate(LifeForm.SBLF, reqMock1, respMock); + long approxTime = System.currentTimeMillis(); + + counter = DenialOfServiceTaf.isDeniedIP(ip1); + assertThat(counter.getName(), is(ip1)); + assertThat(counter.getCount(), is(1)); + assertThat((Math.abs(approxTime - counter.getLast()) < 10), is(true)); + assertThat(counter.toString().contains(ip1), is(true)); + assertThat(counter.toString().contains(" has been denied 1 times since "), is(true)); + assertThat(counter.toString().contains(". Last denial was "), is(true)); + + // coverage... + dost.validate(LifeForm.SBLF, reqMock1, respMock); + + assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(true)); + assertThat(DenialOfServiceTaf.removeDenyIP(ip1), is(false)); + assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(true)); + assertThat(DenialOfServiceTaf.removeDenyIP(ip2), is(false)); + } + + @Test + public void denyIDTest() throws CadiException { + assertThat(DenialOfServiceTaf.isDeniedID(id1), is(nullValue())); + assertThat(DenialOfServiceTaf.denyID(id1), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyID(id2), is(true)); // true because it's been added + assertThat(DenialOfServiceTaf.denyID(id1), is(false)); // false because it's already been added + assertThat(DenialOfServiceTaf.denyID(id2), is(false)); // false because it's already been added + + Counter counter; + counter = DenialOfServiceTaf.isDeniedID(id1); + assertThat(counter.getName(), is(id1)); + assertThat(counter.getCount(), is(0)); + assertThat(counter.getLast(), is(0L)); + + assertThat(DenialOfServiceTaf.removeDenyID(id1), is(true)); + assertThat(DenialOfServiceTaf.removeDenyID(id1), is(false)); + assertThat(DenialOfServiceTaf.removeDenyID(id2), is(true)); + assertThat(DenialOfServiceTaf.removeDenyID(id2), is(false)); + } + + @Test + public void reportTest() throws CadiException { + DenialOfServiceTaf dost = new DenialOfServiceTaf(accessMock); + List<String> denials = dost.report(); + assertThat(denials.size(), is(0)); + + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.denyID(id2); + + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.denyIP(ip2); + + denials = dost.report(); + assertThat(denials.size(), is(4)); + for (String denied : denials) { + switch (denied.split(" ", 2)[0]) { + case ip1: + case ip2: + case id1: + case id2: + break; + default: + fail("The line: [" + denied + "] shouldn't be in the report"); + } + } + } + + @Test + public void respDenyIDTest() { + TafResp tafResp = DenialOfServiceTaf.respDenyID(accessMock, id1); + assertThat(tafResp.desc(), is(id1 + " is on the Identity Denial list")); + } + + @Test + public void ipFileIOTest() throws CadiException, IOException { + @SuppressWarnings("unused") + DenialOfServiceTaf dost; + + dosIPFile.createNewFile(); + + // coverage... + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.removeDenyIP(ip1); + + dost = new DenialOfServiceTaf(accessMock); + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.denyIP(ip2); + // coverage... + DenialOfServiceTaf.denyIP(ip2); + + String contents = readContentsFromFile(dosIPFile); + assertThat(contents.contains(ip1), is(true)); + assertThat(contents.contains(ip2), is(true)); + + // Removing all ips should delete the file + assertThat(dosIPFile.exists(), is(true)); + DenialOfServiceTaf.removeDenyIP(ip1); + DenialOfServiceTaf.removeDenyIP(ip2); + assertThat(dosIPFile.exists(), is(false)); + + dosIPFile.createNewFile(); + + DenialOfServiceTaf.denyIP(ip1); + DenialOfServiceTaf.denyIP(ip2); + + setPrivateField(DenialOfServiceTaf.class, "dosIP", null); + dost = new DenialOfServiceTaf(accessMock); + + contents = readContentsFromFile(dosIPFile); + assertThat(contents.contains(ip1), is(true)); + assertThat(contents.contains(ip2), is(true)); + + dosIPFile.delete(); + + // coverage... + setPrivateField(DenialOfServiceTaf.class, "deniedIP", null); + DenialOfServiceTaf.denyIP(ip1); + dosIPFile.delete(); + DenialOfServiceTaf.removeDenyIP(ip1); + + // coverage... + dosIPFile.delete(); + setPrivateField(DenialOfServiceTaf.class, "dosIP", null); + dost = new DenialOfServiceTaf(accessMock); + } + + @Test + public void idFileIOTest() throws CadiException, IOException { + @SuppressWarnings("unused") + DenialOfServiceTaf dost; + + dosIDFile.createNewFile(); + + // coverage... + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.removeDenyID(id1); + + dost = new DenialOfServiceTaf(accessMock); + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.denyID(id2); + // coverage... + DenialOfServiceTaf.denyID(id2); + + String contents = readContentsFromFile(dosIDFile); + assertThat(contents.contains(id1), is(true)); + assertThat(contents.contains(id2), is(true)); + + // Removing all ids should delete the file + assertThat(dosIDFile.exists(), is(true)); + DenialOfServiceTaf.removeDenyID(id1); + DenialOfServiceTaf.removeDenyID(id2); + assertThat(dosIDFile.exists(), is(false)); + + dosIDFile.createNewFile(); + + DenialOfServiceTaf.denyID(id1); + DenialOfServiceTaf.denyID(id2); + + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + dost = new DenialOfServiceTaf(accessMock); + + contents = readContentsFromFile(dosIDFile); + assertThat(contents.contains(id1), is(true)); + assertThat(contents.contains(id2), is(true)); + + dosIDFile.delete(); + + // coverage... + setPrivateField(DenialOfServiceTaf.class, "deniedID", null); + DenialOfServiceTaf.denyID(id1); + dosIDFile.delete(); + DenialOfServiceTaf.removeDenyID(id1); + + // coverage... + dosIDFile.delete(); + setPrivateField(DenialOfServiceTaf.class, "dosID", null); + dost = new DenialOfServiceTaf(accessMock); + } + + private void setPrivateField(Class<?> clazz, String fieldName, Object value) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(null, value); + field.setAccessible(false); + } catch (Exception e) { + System.err.println("Could not set field [" + fieldName + "] to " + value); + } + } + + private String readContentsFromFile(File file) throws IOException { + BufferedReader br = new BufferedReader(new FileReader(file)); + StringBuilder sb = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + sb.append(line); + } + br.close(); + return sb.toString(); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java new file mode 100644 index 00000000..70752641 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java @@ -0,0 +1,57 @@ +/** + * + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.taf.dos.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; +import org.onap.ccsdk.apps.cadi.taf.dos.DenialOfServiceTafResp; + +public class JU_DenialOfServiceTafResp { + + private final static String description = "description"; + private final static RESP status = RESP.IS_AUTHENTICATED; + + private PropAccess access; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws IOException { + DenialOfServiceTafResp resp = new DenialOfServiceTafResp(access, status, description); + assertThat(resp.isAuthenticated(), is(status)); + assertThat(resp.authenticate(), is(status)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_AbsTafResp.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_AbsTafResp.java new file mode 100644 index 00000000..97696e39 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_AbsTafResp.java @@ -0,0 +1,91 @@ +/******************************************************************************* +* ============LICENSE_START==================================================== +* * org.onap.ccsdk +* * =========================================================================== +* * Copyright © 2023 AT&T Intellectual Property. All rights reserved. +* * =========================================================================== +* * Licensed 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. +* * ============LICENSE_END==================================================== +* * +* * +******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.taf.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal; +import org.onap.ccsdk.apps.cadi.taf.AbsTafResp; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; + +public class JU_AbsTafResp { + + private static final String JUNIT = "Junit"; + private static final String name = "name"; + private static final String tag = "tag"; + private static final String description = "description"; + + private Access access; + private TaggedPrincipal taggedPrinc; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + taggedPrinc = new TaggedPrincipal() { + @Override public String getName() { return name; } + @Override public String tag() { return tag; } + }; + } + + @Test + public void test() { + AbsTafResp tafResp = new AbsTafResp(access, JUNIT, taggedPrinc, description) { + @Override public RESP authenticate() throws IOException { + return null; + } + }; + + assertThat(tafResp.isValid(), is(true)); + assertThat(tafResp.desc(), is(description)); + assertThat(tafResp.taf(), is(JUNIT)); + assertThat(tafResp.isAuthenticated(), is(RESP.IS_AUTHENTICATED)); + assertThat(tafResp.getPrincipal(), is(taggedPrinc)); + assertThat(tafResp.getAccess(), is(access)); + assertThat(tafResp.isFailedAttempt(), is(false)); + + tafResp = new AbsTafResp(null, JUNIT, "unknown", null) { + @Override public RESP authenticate() throws IOException { + return null; + } + }; + + assertThat(tafResp.isValid(), is(false)); + assertThat(tafResp.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(tafResp.getPrincipal(), is(nullValue())); + assertThat(tafResp.getTarget(), is("unknown")); + assertThat(tafResp.getAccess(), is(nullValue())); + assertThat(tafResp.taf(), is(JUNIT)); + assertThat(tafResp.isFailedAttempt(), is(false)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_EpiTaf.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_EpiTaf.java new file mode 100644 index 00000000..fc938111 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_EpiTaf.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.taf.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.IOException; + +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.Taf; +import org.onap.ccsdk.apps.cadi.taf.TafResp; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; + +import org.onap.ccsdk.apps.cadi.taf.EpiTaf; +import org.onap.ccsdk.apps.cadi.taf.NullTaf; +import org.onap.ccsdk.apps.cadi.Taf.LifeForm; +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal; + +public class JU_EpiTaf { + + @Test(expected = CadiException.class) + @SuppressWarnings("unused") + public void constructorTest() throws CadiException { + EpiTaf et = new EpiTaf(); + } + + @Test + public void validateTryAnotherTest() throws CadiException { + EpiTaf et = new EpiTaf(new TryAnotherTaf()); + TafResp output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + } + + @Test + public void validateTryAuthenticatingTest() throws CadiException { + EpiTaf et = new EpiTaf(new TryAuthenticatingTaf(), new TryAuthenticatingTaf()); + TafResp output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); + output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); + } + + @Test + public void validateDefaultCaseTest() throws CadiException { + EpiTaf et = new EpiTaf(new NullTaf()); + TafResp output = et.validate(LifeForm.CBLF); + assertThat(output.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + } + + class TryAnotherTafResp implements TafResp { + @Override public boolean isValid() { return false; } + @Override public String desc() { return null; } + @Override public RESP isAuthenticated() { return RESP.TRY_ANOTHER_TAF; } + @Override public RESP authenticate() throws IOException { return null; } + @Override public TaggedPrincipal getPrincipal() { return null; } + @Override public String getTarget() {return "unknown";} + @Override public Access getAccess() { return null; } + @Override public boolean isFailedAttempt() { return false; } + @Override public float timing() { return 0; } + @Override public void timing(long start) {} + @Override public String taf() {return "JUnit";} + } + + class TryAnotherTaf implements Taf { + @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAnotherTafResp(); } + } + + class TryAuthenticatingResp implements TafResp { + @Override public boolean isValid() { return false; } + @Override public String desc() { return null; } + @Override public RESP isAuthenticated() { return RESP.TRY_AUTHENTICATING; } + @Override public RESP authenticate() throws IOException { return null; } + @Override public TaggedPrincipal getPrincipal() { return null; } + @Override public String getTarget() {return "unknown";} + @Override public Access getAccess() { return null; } + @Override public boolean isFailedAttempt() { return false; } + @Override public float timing() { return 0; } + @Override public void timing(long start) {} + @Override public String taf() {return "JUnit";} + } + + class TryAuthenticatingTaf implements Taf { + @Override public TafResp validate(LifeForm reading, String ... info) { return new TryAuthenticatingResp(); } + } + + class EpiTafStub extends EpiTaf { + public EpiTafStub() throws CadiException { } + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_HttpEpiTaf.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_HttpEpiTaf.java new file mode 100644 index 00000000..4819540d --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_HttpEpiTaf.java @@ -0,0 +1,145 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.taf.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.URI; +import java.net.URISyntaxException; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.Access.Level; +import org.onap.ccsdk.apps.cadi.CachedPrincipal.Resp; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.Locator; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.Taf.LifeForm; +import org.onap.ccsdk.apps.cadi.TrustChecker; +import org.onap.ccsdk.apps.cadi.taf.HttpEpiTaf; +import org.onap.ccsdk.apps.cadi.taf.HttpTaf; +import org.onap.ccsdk.apps.cadi.taf.NullTaf; +import org.onap.ccsdk.apps.cadi.taf.Redirectable; +import org.onap.ccsdk.apps.cadi.taf.TafResp; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; + +public class JU_HttpEpiTaf { + + private PropAccess access; + + @Mock private Locator<URI> locMock; + @Mock private TrustChecker trustCheckerMock; + @Mock private HttpServletRequest reqMock; + @Mock private HttpServletResponse respMock; + @Mock private HttpTaf tafMock; + @Mock private TafResp trespMock; + @Mock private Redirectable redirMock; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws Exception { + HttpEpiTaf taf; + try { + taf = new HttpEpiTaf(access, locMock, trustCheckerMock); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("Need at least one HttpTaf implementation in constructor")); + } + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, new NullTaf()); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + // Coverage of tricorderScan + taf.validate(LifeForm.LFN, reqMock, respMock); + when(reqMock.getHeader("User-Agent")).thenReturn("Non-mozilla-header"); + taf.validate(LifeForm.LFN, reqMock, respMock); + when(reqMock.getHeader("User-Agent")).thenReturn("Mozilla-header"); + taf.validate(LifeForm.LFN, reqMock, respMock); + + access.setLogLevel(Level.DEBUG); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(trespMock); + when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_ANOTHER_TAF); + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(trespMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(redirMock); + when(redirMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf = new HttpEpiTaf(access, locMock, null, tafMock); + when(redirMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED); + try { + taf.validate(LifeForm.CBLF, reqMock, respMock); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + assertThat(taf.revalidate(null), is(false)); + assertThat(taf.revalidate(null), is(false)); + + when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE); + assertThat(taf.revalidate(null, null), is(Resp.NOT_MINE)); + when(tafMock.revalidate(null, null)).thenReturn(Resp.REVALIDATED); + assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); + + when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE).thenReturn(Resp.NOT_MINE).thenReturn(Resp.REVALIDATED); + taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock, tafMock); + assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED)); + + taf.toString(); + + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_LoginPageTafResp.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_LoginPageTafResp.java new file mode 100644 index 00000000..9d7a9d47 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_LoginPageTafResp.java @@ -0,0 +1,101 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.taf.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; + +import jakarta.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.Locator; +import org.onap.ccsdk.apps.cadi.Locator.Item; +import org.onap.ccsdk.apps.cadi.LocatorException; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.taf.LoginPageTafResp; +import org.onap.ccsdk.apps.cadi.taf.Redirectable; +import org.onap.ccsdk.apps.cadi.taf.TafResp; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; + +public class JU_LoginPageTafResp { + + private static final String uriString = "example.com"; + + private URI uri; + private Access access; + private List<Redirectable> redirectables; + + @Mock private HttpServletResponse respMock; + @Mock private Locator<URI> locatorMock; + @Mock private Redirectable redirMock; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + + redirectables = new ArrayList<>(); + uri = new URI(uriString); + } + + @Test + public void test() throws LocatorException, IOException { + TafResp resp; + resp = LoginPageTafResp.create(access, null, respMock, redirectables); + assertThat(resp.desc(), is("All Authentication denied")); + + redirectables.add(redirMock); + redirectables.add(redirMock); + resp = LoginPageTafResp.create(access, null, respMock, redirectables); + assertThat((Redirectable)resp, is(redirMock)); + + resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); + assertThat(resp.desc(), is("All Authentication denied")); + + when(locatorMock.get((Item)any())).thenReturn(uri); + resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); + assertThat(resp.desc(), is("Multiple Possible HTTP Logins available. Redirecting to Login Choice Page")); + assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); + assertThat(resp.isAuthenticated(), is(RESP.TRY_AUTHENTICATING)); + + redirectables = new ArrayList<>(); + resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables); + assertThat(resp.desc(), is("All Authentication denied")); + + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_NullTaf.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_NullTaf.java new file mode 100644 index 00000000..cb3ac3f2 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_NullTaf.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.taf.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.IOException; + +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.CachedPrincipal.Resp; +import org.onap.ccsdk.apps.cadi.taf.TafResp; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; + +import org.onap.ccsdk.apps.cadi.taf.NullTaf; + +public class JU_NullTaf { + + @Test + public void test() throws IOException { + NullTaf nt = new NullTaf(); + TafResp singleton1 = nt.validate(null); + TafResp singleton2 = nt.validate(null, null, null); + Resp singleton3 = nt.revalidate(null, null); + + assertThat(singleton1, is(singleton2)); + + assertFalse(singleton1.isValid()); + + assertThat(singleton1.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + + assertThat(singleton1.desc(), is("All Authentication denied")); + + assertThat(singleton1.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); + + assertThat(singleton1.getPrincipal(), is(nullValue())); + + assertThat(singleton1.getAccess(), is(Access.NULL)); + + assertTrue(singleton1.isFailedAttempt()); + + assertThat(singleton3, is(Resp.NOT_MINE)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_PuntTafResp.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_PuntTafResp.java new file mode 100644 index 00000000..3db3e868 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_PuntTafResp.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.taf.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.IOException; + +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; + +import org.onap.ccsdk.apps.cadi.taf.PuntTafResp; + + +public class JU_PuntTafResp { + + @Test + public void test() throws IOException { + String name = "name"; + String explanation = "example explanation"; + + PuntTafResp punt = new PuntTafResp(name, explanation); + + assertFalse(punt.isValid()); + assertThat(punt.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(punt.desc(), is("Not processing this transaction: " + explanation)); + assertThat(punt.taf(), is(name)); + assertThat(punt.authenticate(), is(RESP.TRY_ANOTHER_TAF)); + assertThat(punt.getPrincipal(), is(nullValue())); + assertThat(punt.getAccess(), is(Access.NULL)); + assertFalse(punt.isFailedAttempt()); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_TrustNotTafResp.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_TrustNotTafResp.java new file mode 100644 index 00000000..8c9ebfc8 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_TrustNotTafResp.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.taf.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; +import org.junit.*; +import org.mockito.*; + +import java.io.IOException; + +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.taf.TafResp; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; +import org.onap.ccsdk.apps.cadi.taf.TrustNotTafResp; +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal; + +public class JU_TrustNotTafResp { + + @Mock + TafResp delegateMock; + + @Mock + TaggedPrincipal principalMock; + + @Mock + Access accessMock; + + private final String description = "Example Description"; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + when(delegateMock.getPrincipal()).thenReturn(principalMock); + when(delegateMock.getAccess()).thenReturn(accessMock); + } + + @Test + public void test() throws IOException { + TrustNotTafResp ttr = new TrustNotTafResp(delegateMock, description); + assertThat(ttr.isValid(), is(false)); + assertThat(ttr.desc(), is(description)); + assertThat(ttr.authenticate(), is(RESP.NO_FURTHER_PROCESSING)); + assertThat(ttr.isAuthenticated(), is(RESP.NO_FURTHER_PROCESSING)); + assertThat(ttr.getPrincipal(), is(principalMock)); + assertThat(ttr.getAccess(), is(accessMock)); + assertThat(ttr.isFailedAttempt(), is(true)); + assertThat(ttr.toString(), is(description)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_TrustTafResp.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_TrustTafResp.java new file mode 100644 index 00000000..a4208abc --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/taf/test/JU_TrustTafResp.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.taf.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; +import org.junit.*; +import org.mockito.*; + +import java.io.IOException; + +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.taf.TafResp; +import org.onap.ccsdk.apps.cadi.taf.TafResp.RESP; +import org.onap.ccsdk.apps.cadi.taf.TrustTafResp; +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal; + +public class JU_TrustTafResp { + + @Mock + TafResp delegateMock; + + @Mock + TaggedPrincipal principalMock; + + @Mock + Access accessMock; + + private final String description = "Example Description"; + private final String anotherDescription = "Another Description"; + private final String name = "name"; + + private final RESP resp = RESP.IS_AUTHENTICATED; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + when(delegateMock.desc()).thenReturn(anotherDescription); + when(delegateMock.isValid()).thenReturn(true); + when(delegateMock.isAuthenticated()).thenReturn(resp); + when(delegateMock.authenticate()).thenReturn(resp); + when(delegateMock.getAccess()).thenReturn(accessMock); + when(delegateMock.isFailedAttempt()).thenReturn(true); + + when(principalMock.getName()).thenReturn(name); + } + + @Test + public void test() throws IOException { + TrustTafResp ttr = new TrustTafResp(delegateMock, principalMock, description); + assertThat(ttr.isValid(), is(true)); + assertThat(ttr.desc(), is(description + ' ' + anotherDescription)); + assertThat(ttr.authenticate(), is(resp)); + assertThat(ttr.isAuthenticated(), is(resp)); + assertThat(ttr.getPrincipal(), is(principalMock)); + assertThat(ttr.getAccess(), is(accessMock)); + assertThat(ttr.isFailedAttempt(), is(true)); + assertThat(ttr.toString(), is(name + " by trust of " + description + ' ' + anotherDescription)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_AES.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_AES.java new file mode 100644 index 00000000..2851af31 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_AES.java @@ -0,0 +1,195 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; +import org.junit.*; + + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Paths; + +import javax.crypto.CipherInputStream; +import javax.crypto.CipherOutputStream; +import javax.crypto.SecretKey; + +import org.onap.ccsdk.apps.cadi.AES; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.Symm; + +public class JU_AES { + private AES aes; + private ByteArrayInputStream baisEncrypt; + private ByteArrayInputStream baisDecrypt; + private ByteArrayOutputStream baosEncrypt; + private ByteArrayOutputStream baosDecrypt; + + private ByteArrayOutputStream errStream; + + @Before + public void setup() throws Exception { + byte[] keyBytes = new byte[AES.AES_KEY_SIZE/8]; + char[] codeset = Symm.base64.codeset; + int offset = (Math.abs(codeset[0]) + 47) % (codeset.length - keyBytes.length); + for (int i = 0; i < keyBytes.length; ++i) { + keyBytes[i] = (byte)codeset[i+offset]; + } + aes = new AES(keyBytes, 0, keyBytes.length); + + errStream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setErr(System.err); + } + + @Test + public void newKeyTest() throws Exception { + SecretKey secretKey = AES.newKey(); + assertThat(secretKey.getAlgorithm(), is(AES.class.getSimpleName())); + } + + @Test + public void encryptDecrpytFromBytes() throws Exception { + String orig = "I'm a password, really"; + byte[] encrypted = aes.encrypt(orig.getBytes()); + byte[] decrypted = aes.decrypt(encrypted); + assertThat(new String(decrypted), is(orig)); + + Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); + aeskeySpec_field.setAccessible(true); + aeskeySpec_field.set(aes, null); + + try { + aes.encrypt(orig.getBytes()); + fail("Should have thrown an exception"); + } catch (CadiException e) { + } + try { + aes.decrypt(encrypted); + fail("Should have thrown an exception"); + } catch (CadiException e) { + } + } + + @Test + public void saveToFileTest() throws Exception { + String filePath = "src/test/resources/output_key"; + File keyfile = new File(filePath); + aes.save(keyfile); + assertTrue(Files.isReadable(Paths.get(filePath))); + assertFalse(Files.isWritable(Paths.get(filePath))); + assertFalse(Files.isExecutable(Paths.get(filePath))); + keyfile.delete(); + } + + @Test + public void encryptDecryptFromInputStream() throws Exception { + String orig = "I'm a password, really"; + byte[] b64encrypted; + String output; + + CipherInputStream cisEncrypt; + CipherInputStream cisDecrypt; + + // Test CipherInputStream + baisEncrypt = new ByteArrayInputStream(orig.getBytes()); + cisEncrypt = aes.inputStream(baisEncrypt, true); + baosEncrypt = new ByteArrayOutputStream(); + transferFromInputStreamToOutputStream(cisEncrypt, baosEncrypt); + cisEncrypt.close(); + + b64encrypted = baosEncrypt.toByteArray(); + + baisDecrypt = new ByteArrayInputStream(b64encrypted); + cisDecrypt = aes.inputStream(baisDecrypt, false); + baosDecrypt = new ByteArrayOutputStream(); + transferFromInputStreamToOutputStream(cisDecrypt, baosDecrypt); + cisDecrypt.close(); + + output = new String(baosDecrypt.toByteArray()); + assertThat(output, is(orig)); + + Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); + aeskeySpec_field.setAccessible(true); + aeskeySpec_field.set(aes, null); + + assertNull(aes.inputStream(baisEncrypt, true)); + assertThat(errStream.toString(), is("Error creating Aes CipherInputStream\n")); + } + + @Test + public void encryptDecryptFromOutputStream() throws Exception { + String orig = "I'm a password, really"; + byte[] b64encrypted; + String output; + + CipherOutputStream cosEncrypt; + CipherOutputStream cosDecrypt; + + // Test CipherOutputStream + baisEncrypt = new ByteArrayInputStream(orig.getBytes()); + baosEncrypt = new ByteArrayOutputStream(); + cosEncrypt = aes.outputStream(baosEncrypt, true); + transferFromInputStreamToOutputStream(baisEncrypt, cosEncrypt); + cosEncrypt.close(); + + b64encrypted = baosEncrypt.toByteArray(); + + baosDecrypt = new ByteArrayOutputStream(); + cosDecrypt = aes.outputStream(baosDecrypt, false); + baisDecrypt = new ByteArrayInputStream(b64encrypted); + transferFromInputStreamToOutputStream(baisDecrypt, cosDecrypt); + cosDecrypt.close(); + + output = new String(baosDecrypt.toByteArray()); + assertThat(output, is(orig)); + + Field aeskeySpec_field = AES.class.getDeclaredField("aeskeySpec"); + aeskeySpec_field.setAccessible(true); + aeskeySpec_field.set(aes, null); + + assertNull(aes.outputStream(baosEncrypt, true)); + assertThat(errStream.toString(), is("Error creating Aes CipherOutputStream\n")); + } + + public void transferFromInputStreamToOutputStream(InputStream is, OutputStream os) throws IOException { + byte[] buffer = new byte[200]; + int len; + while ((len = is.read(buffer)) != -1) { + os.write(buffer, 0, len); + } + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_AbsUserCache.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_AbsUserCache.java new file mode 100644 index 00000000..f3afee81 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_AbsUserCache.java @@ -0,0 +1,351 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.lang.reflect.Field; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.AbsUserCache; +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.CachedPrincipal.Resp; +import org.onap.ccsdk.apps.cadi.CachingLur; +import org.onap.ccsdk.apps.cadi.GetCred; +import org.onap.ccsdk.apps.cadi.Permission; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.User; +import org.onap.ccsdk.apps.cadi.lur.LocalPermission; +import org.onap.ccsdk.apps.cadi.principal.CachedBasicPrincipal; + +public class JU_AbsUserCache { + + @Mock private CachingLur<Permission> cl; + @Mock private Principal principal; + @Mock private CachedBasicPrincipal cbp; + @Mock private LocalPermission permission1; + @Mock private LocalPermission permission2; + + private Access access; + + private ByteArrayOutputStream outStream; + + private String name1 = "name1"; + private String name2 = "name2"; + private byte[] password = "password".getBytes(); + + private static Field timerField; + + @BeforeClass + public static void setupOnce() throws Exception { + timerField = AbsUserCache.class.getDeclaredField("timer"); + timerField.setAccessible(true); + } + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + + // This must happen after changing System.out + access = new PropAccess(); + + when(permission1.getKey()).thenReturn("NewKey1"); + when(permission2.getKey()).thenReturn("NewKey2"); + + timerField.set(null, null); + } + + @After + public void tearDown() throws Exception { + System.setOut(System.out); + timerField.set(null, null); + } + + @SuppressWarnings("unused") + @Test + public void constructorTest() { + int cleanInterval = 65000; + int maxInterval = 70000; + + AbsUserCacheStub<Permission> aucs1 = new AbsUserCacheStub<Permission>(access, cleanInterval, maxInterval, Integer.MAX_VALUE); + String output = outStream.toString().split(" ", 2)[1]; + + outStream.reset(); + AbsUserCacheStub<Permission> aucs2 = new AbsUserCacheStub<Permission>(access, cleanInterval, maxInterval, Integer.MAX_VALUE); + output = outStream.toString().split(" ", 2)[1]; + + AbsUserCacheStub<Permission> aucs3 = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + AbsUserCacheStub<Permission> aucs4 = new AbsUserCacheStub<Permission>(aucs1); + + // For coverage + AbsUserCacheCLStub<Permission> auccls1 = new AbsUserCacheCLStub<Permission>(aucs1); + aucs1.setLur(cl); + auccls1 = new AbsUserCacheCLStub<Permission>(aucs1); + AbsUserCacheCLStub<Permission> auccls2 = new AbsUserCacheCLStub<Permission>(aucs3); + } + + @Test + public void setLurTest() { + AbsUserCacheStub<Permission> aucs1 = new AbsUserCacheStub<Permission>(access, 65000, 70000, Integer.MAX_VALUE); + AbsUserCacheStub<Permission> aucs2 = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + aucs1.setLur(cl); + aucs2.setLur(cl); + } + + @Test + public void addUserGetUserTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + User<Permission> user; + + // Test adding a user with a principal (non-GetCred). user does not have a cred + // Then test getting that user + when(principal.getName()).thenReturn(name1); + user = new User<Permission>(principal, 0); + aucs.addUser(user); + assertThat(aucs.getUser(principal), is(user)); + + // Test adding a user with a principal (GetCred). user does not have a cred + // Then test getting that user + GetCredStub gc = new GetCredStub(); + user = new User<Permission>(gc, 0); + aucs.addUser(user); + assertThat(aucs.getUser(gc), is(user)); + + // Test adding a user with no principal + // Then test getting that user via his name and cred + user = new User<Permission>(name2, password); + aucs.addUser(user); + assertThat(aucs.getUser(name2, password), is(user)); + + // Test getting a user by a CachedBasicPrincipal + when(cbp.getName()).thenReturn(name2); + when(cbp.getCred()).thenReturn(password); + assertThat(aucs.getUser(cbp), is(user)); + + // Force the user to expire, then test that he is no longer in the cache + Field permExpiresField = User.class.getDeclaredField("permExpires"); + permExpiresField.setAccessible(true); + permExpiresField.set(user, 0); + assertThat(aucs.getUser(name2, password), is(nullValue())); + + // Test adding a user with a custom key + // Then test gettin that user + user = new User<Permission>(principal, 0); + String key = principal.getName() + "NoCred"; + aucs.addUser(key, user); + assertThat(aucs.getUser(principal), is(user)); + + // Test that getUser returns null for principals that don't match any users + when(principal.getName()).thenReturn("not in the cache"); + assertThat(aucs.getUser(principal), is(nullValue())); + + // That that getUser returns null for name/creds that are not in the cache + assertThat(aucs.getUser("not a real user", "not in the cache".getBytes()), is(nullValue())); + } + + @Test + public void removeTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + User<Permission> user; + + when(principal.getName()).thenReturn(name1); + user = new User<Permission>(principal); + // Add a user with a principal + aucs.addUser(user); + // Check that the user is in the cache + assertThat(aucs.getUser(principal), is(user)); + // Remove the user + when(principal.getName()).thenReturn(name1 + "NoCred"); + aucs.remove(user); + // Check that the user is no longer in the cache + when(principal.getName()).thenReturn(name1); + assertThat(aucs.getUser(principal), is(nullValue())); + + // Add the user again + aucs.addUser(user); + // Check that the user is in the cache + assertThat(aucs.getUser(principal), is(user)); + // Remove the user by name + aucs.remove(name1 + "NoCred"); + // Check that the user is no longer in the cache + assertThat(aucs.getUser(principal), is(nullValue())); + + // Coverage test - attempt to remove a user that is not in the cache + aucs.remove(name1 + "NoCred"); + assertThat(aucs.getUser(principal), is(nullValue())); + } + + @Test + public void clearAllTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + User<Permission> user1; + User<Permission> user2; + + // Add some users to the cache + when(principal.getName()).thenReturn(name1); + user1 = new User<Permission>(principal); + when(principal.getName()).thenReturn(name2); + user2 = new User<Permission>(principal); + aucs.addUser(user1); + aucs.addUser(user2); + + // Check that the users are in the cache + when(principal.getName()).thenReturn(name1); + assertThat(aucs.getUser(principal), is(user1)); + when(principal.getName()).thenReturn(name2); + assertThat(aucs.getUser(principal), is(user2)); + + // Clear the cache + aucs.clearAll(); + + // Check that the users are no longer in the cache + when(principal.getName()).thenReturn(name1); + assertThat(aucs.getUser(principal), is(nullValue())); + when(principal.getName()).thenReturn(name2); + assertThat(aucs.getUser(principal), is(nullValue())); + } + + @Test + public void dumpInfoTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + User<Permission> user1; + User<Permission> user2; + + Principal principal1 = mock(Principal.class); + Principal principal2 = mock(Principal.class); + when(principal1.getName()).thenReturn(name1); + when(principal2.getName()).thenReturn(name2); + + // Add some users with permissions to the cache + user1 = new User<Permission>(principal1); + user1.add(permission1); + user1.add(permission2); + user2 = new User<Permission>(principal2); + user2.add(permission1); + user2.add(permission2); + aucs.addUser(user1); + aucs.addUser(user2); + + // Dump the info + List<AbsUserCache<Permission>.DumpInfo> dumpInfo = aucs.dumpInfo(); + assertThat(dumpInfo.size(), is(2)); + + // Utility lists + List<String> names = new ArrayList<>(); + names.add(name1); + names.add(name2); + List<String> permissions = new ArrayList<>(); + permissions.add("NewKey1"); + permissions.add("NewKey2"); + + // We need to use "contains" because the dumpInfo was created from a list, so we don't know it's order + for (AbsUserCache<Permission>.DumpInfo di : dumpInfo) { + assertTrue(names.contains(di.user)); + for (String perm : di.perms) { + assertTrue(permissions.contains(perm)); + } + } + } + + @Test + public void handlesExclusivelyTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + assertFalse(aucs.handlesExclusively(permission1)); + assertFalse(aucs.handlesExclusively(permission2)); + } + + @Test + public void destroyTest() { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + aucs.destroy(); + aucs = new AbsUserCacheStub<Permission>(access, 1, 1, Integer.MAX_VALUE); + aucs.destroy(); + } + + @Test + public void missTest() throws IOException { + AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + // Add the Miss to the missmap + assertTrue(aucs.addMiss("key", password)); // This one actually adds it + assertTrue(aucs.addMiss("key", password)); // this one doesn't really do anything + assertTrue(aucs.addMiss("key", password)); // neither does this one + assertFalse(aucs.addMiss("key", password)); // By this time, the missMap is tired of this nonsense, and retaliates + assertFalse(aucs.addMiss("key", password)); // Oh yea. He's angry + + // Can't really test this due to visibility + aucs.missed("key", password); + + // Coverage + AbsUserCacheStub<Permission> aucs1 = new AbsUserCacheStub<Permission>(access, 1, 1, Integer.MAX_VALUE); + aucs1.addMiss("key", password); + } + + class AbsUserCacheStub<PERM extends Permission> extends AbsUserCache<PERM> { + public AbsUserCacheStub(Access access, long cleanInterval, int highCount, int usageCount) { super(access, cleanInterval, highCount, usageCount); } + public AbsUserCacheStub(AbsUserCache<PERM> cache) { super(cache); } + @Override public void setLur(CachingLur<PERM> lur) { super.setLur(lur); } + @Override public void addUser(User<PERM> user) { super.addUser(user); } + @Override public void addUser(String key, User<PERM> user) { super.addUser(key, user); } + @Override public User<PERM> getUser(Principal p) { return super.getUser(p); } + @Override public User<PERM> getUser(CachedBasicPrincipal p) { return super.getUser(p); } + @Override public User<PERM> getUser(String user, byte[] cred) { return super.getUser(user, cred); } + @Override public void remove(User<PERM> user) { super.remove(user); } + @Override public boolean addMiss(String key, byte[] bs) { return super.addMiss(key, bs); } + @Override public Miss missed(String key, byte[] bs) throws IOException { return super.missed(key, bs); } + } + + class AbsUserCacheCLStub<PERM extends Permission> extends AbsUserCache<PERM> implements CachingLur<PERM> { + public AbsUserCacheCLStub(AbsUserCache<PERM> cache) { super(cache); } + @Override public Permission createPerm(String p) { return null; } + @Override public boolean fish(Principal bait, Permission ... pond) { return false; } + @Override public void fishAll(Principal bait, List<Permission> permissions) { } + @Override public boolean handles(Principal principal) { return false; } + @Override public Resp reload(User<PERM> user) { return null; } + @Override public void setDebug(String commaDelimIDsOrNull) { } + } + + class GetCredStub implements Principal, GetCred { + @Override public byte[] getCred() { return password; } + @Override public String getName() { return name1; } + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Access.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Access.java new file mode 100644 index 00000000..a9721d2d --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Access.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.IOException; + +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.Access.Level; + +public class JU_Access { + + @Test + public void levelTests() { + assertTrue(Level.DEBUG.inMask(0x1)); + for (int i = 2; i > 0; i <<= 1) { + assertFalse(Level.DEBUG.inMask(i)); + } + assertFalse(Level.DEBUG.inMask(0x80000000)); + + assertThat(Level.DEBUG.addToMask(0x2), is(0x3)); + assertThat(Level.DEBUG.delFromMask(0x1), is(0x0)); + assertThat(Level.DEBUG.toggle(0x2), is(0x3)); + assertThat(Level.DEBUG.toggle(0x1), is(0x0)); + assertThat(Level.DEBUG.maskOf(), is(123153)); + assertThat(Level.NONE.maskOf(), is(0)); + } + + @Test + public void nullTests() throws IOException { + // These are entirely for coverage + Access.NULL.log(Level.DEBUG); + Access.NULL.printf(Level.DEBUG, ""); + Access.NULL.log(new Exception()); + Access.NULL.classLoader(); + assertThat(Access.NULL.getProperty("", ""), is(nullValue())); + Access.NULL.load(System.in); + Access.NULL.setLogLevel(Level.DEBUG); + assertThat(Access.NULL.decrypt("test", true), is("test")); + assertFalse(Access.NULL.willLog(Level.DEBUG)); + assertThat(Access.NULL.getProperties(), is(not(nullValue()))); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Base64.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Base64.java new file mode 100644 index 00000000..319d98e5 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Base64.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.SecureRandom; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.Symm; +import org.onap.ccsdk.apps.cadi.config.Config; + +public class JU_Base64 { + private static final String encoding = "Man is distinguished, not only by his reason, but by this singular " + + "passion from other animals, which is a lust of the mind, that by a " + + "perseverance of delight in the continued and indefatigable generation of " + + "knowledge, exceeds the short vehemence of any carnal pleasure."; + + private static final String expected = + "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz\n" + + "IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg\n" + + "dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu\n" + + "dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo\n" + + "ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="; + + @Test + public void test() throws Exception { + // Test with different Padding + assertEncoded("leas", "bGVhcw=="); + assertEncoded("leasu", "bGVhc3U="); + assertEncoded("leasur", "bGVhc3Vy"); + assertEncoded("leasure", "bGVhc3VyZQ=="); + assertEncoded("leasure.", "bGVhc3VyZS4="); + + // Test with line ends + assertEncoded(encoding, expected); + } + + @Test + public void symmetric() throws IOException { + String symmetric = new String(Symm.keygen()); + Symm bsym = Symm.obtain(symmetric); + String result = bsym.encode(encoding); + assertThat(bsym.decode(result), is(encoding)); + + char[] manipulate = symmetric.toCharArray(); + int spot = new SecureRandom().nextInt(manipulate.length); + manipulate[spot]|=0xFF; + String newsymmetric = new String(manipulate); + assertThat(symmetric, is(not(newsymmetric))); + try { + bsym = Symm.obtain(newsymmetric); + result = bsym.decode(result); + assertThat(result, is(encoding)); + } catch (IOException e) { + // this is what we want to see if key wrong + } + } + + private void assertEncoded(String toEncode, String expected) throws IOException { + String result = Symm.base64.encode(toEncode); + assertThat(result, is(expected)); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Symm.base64.decode(new ByteArrayInputStream(result.getBytes()), baos); + result = baos.toString(Config.UTF_8); + assertThat(result, is(toEncode)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_BufferedCadiWrap.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_BufferedCadiWrap.java new file mode 100644 index 00000000..968afb4e --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_BufferedCadiWrap.java @@ -0,0 +1,46 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.ccsdk.apps.cadi.test; + +import jakarta.servlet.http.HttpServletRequest; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class JU_BufferedCadiWrap { + @Mock + private HttpServletRequest request; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void constructorTest() { + // TODO: Ian - This will always fail beacuse the constructor is invalid + // BufferedCadiWrap bcw = new BufferedCadiWrap(request); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_BufferedServletInputStream.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_BufferedServletInputStream.java new file mode 100644 index 00000000..a6ac1cfa --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_BufferedServletInputStream.java @@ -0,0 +1,321 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import java.io.ByteArrayInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.reflect.*; +import junit.framework.Assert; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.BufferedServletInputStream; + +import static junit.framework.Assert.assertEquals; + +public class JU_BufferedServletInputStream { + private BufferedServletInputStream bsis; + private String expected; + + @Before + public void setup() throws FileNotFoundException { + expected = new String("This is the expected output"); + bsis = new BufferedServletInputStream(new ByteArrayInputStream(expected.getBytes())); + } + + @After + public void tearDown() throws IOException { + bsis.close(); + } + + @Test + public void ByteReadNoMarkTest() throws Exception { + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + } + Assert.assertEquals(new String(output, 0, i), expected); + } + + @Test + public void ByteReadMarkTest() throws Exception { + bsis.mark(0); + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + } + Assert.assertEquals(new String(output, 0, i), expected); + } + + @Test + public void ByteReadStateIsStoreTest() throws Exception { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); + bsis.mark(0); + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + } + bsis.reset(); + Assert.assertEquals(state_field.get(bsis), 2); // state == READ + } + + @Test + public void ByteReadStateIsReadTest() throws Exception { + bsis.mark(0); // Initialize the capacitor + boolean isReset = false; + int c; + int i = 0; + byte output[] = new byte[100]; + while ((c = bsis.read()) != -1) { + output[i++] = (byte)c; + if ((i > 5) && !isReset) { + // Close the capacitor and start over. This is done for coverage purposes + i = 0; + isReset = true; + bsis.reset(); // Sets state to READ + } + } + Assert.assertEquals(new String(output, 0, i), expected); + } + + @Test + public void ByteReadStateIsNoneTest() throws Exception { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); + bsis.mark(0); // Initialize the capacitor + int c; + c = bsis.read(); + // Close the capacitor. This is done for coverage purposes + bsis.reset(); // Sets state to READ + state_field.setInt(bsis, 0); // state == NONE + c = bsis.read(); + Assert.assertEquals(c, -1); + } + + @Test + public void ByteArrayReadNoMarkTest() throws Exception { + byte output[] = new byte[100]; + int count = bsis.read(output, 0, expected.length()); + Assert.assertEquals(new String(output, 0, count), expected); + Assert.assertEquals(count, expected.length()); + } + + @Test + public void ByteArrayReadTest() throws Exception { + byte[] output = new byte[100]; + bsis.mark(0); + bsis.read(output); + Assert.assertEquals(new String(output, 0, expected.length()), expected); + } + + @Test + public void ByteArrayReadStateIsStoreTest() throws Exception { + byte output[] = new byte[100]; + bsis.mark(0); + int count = bsis.read(output, 0, expected.length()); + Assert.assertEquals(new String(output, 0, count), expected); + Assert.assertEquals(count, expected.length()); + + count = bsis.read(output, 0, 0); + Assert.assertEquals(count, -1); + } + + @Test + public void ByteArrayReadStateIsReadTest() throws Exception { + byte output[] = new byte[200]; + for (int i = 0; i < 2; ++i) { + bsis.mark(0); + bsis.read(output, 0, 100); + Assert.assertEquals(new String(output, 0, expected.length()), expected); + + bsis.reset(); + bsis.read(output, 0, output.length); + Assert.assertEquals(new String(output, 0, expected.length()), expected); + bsis = new BufferedServletInputStream(new ByteArrayInputStream(output)); + if (i == 0) { + output = new byte[200]; + } + } + + Assert.assertEquals(new String(output, 0, expected.length()), expected); + } + + @Test + public void ByteArrayReadStateIsNoneTest() throws Exception { + byte output[] = new byte[100]; + bsis.mark(0); + + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); + state_field.setInt(bsis, 0); // state == NONE + + int count = bsis.read(output, 0, 100); + Assert.assertEquals(count, -1); + } + + @Test + public void skipTest() throws Exception { + byte output[] = new byte[100]; + bsis.mark(0); + bsis.read(output, 0, 10); + long count = bsis.skip(200); + // skip returns the number left _before_ skipping. that number starts at 256 + Assert.assertEquals(count, 246); + + count = bsis.skip(200); + Assert.assertEquals(count, 17); + } + + @Test + public void availableTest() throws Exception { + int count = bsis.available(); + Assert.assertEquals(count, 27); + bsis.mark(0); + count = bsis.available(); + Assert.assertEquals(count, 27); + } + + @Test + public void bufferedTest() throws Exception { + bsis.mark(0); + Assert.assertEquals(bsis.buffered(), 0); + } + + @Test + public void closeTest() throws Exception { + Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); + capacitor_field.setAccessible(true); + bsis.mark(0); + Assert.assertNotNull(capacitor_field.get(bsis)); + bsis.close(); + Assert.assertNull(capacitor_field.get(bsis)); + } + + @Test + public void markTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + Field capacitor_field = BufferedServletInputStream.class.getDeclaredField("capacitor"); + capacitor_field.setAccessible(true); + state_field.setAccessible(true); + + // capacitor is null initially + Assert.assertNull(capacitor_field.get(bsis)); + + state_field.setInt(bsis, 0); // state == NONE + bsis.mark(0); // the value passed into mark is ignored + Assert.assertNotNull(capacitor_field.get(bsis)); + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + + state_field.setInt(bsis, 1); // state == STORE + bsis.mark(0); // the value passed into mark is ignored + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + + state_field.setInt(bsis, 2); // state == READ + bsis.mark(0); // the value passed into mark is ignored + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + } + + @Test + public void resetTest() throws Exception { + Field state_field = BufferedServletInputStream.class.getDeclaredField("state"); + state_field.setAccessible(true); + + bsis.mark(0); + Assert.assertEquals(state_field.get(bsis), 1); // state == STORE + bsis.reset(); + Assert.assertEquals(state_field.get(bsis), 2); // state == READ + bsis.reset(); + Assert.assertEquals(state_field.get(bsis), 2); // state == READ + + state_field.setInt(bsis, -1); // state is invalid + bsis.reset(); // This call does nothing. It is for coverage alone + Assert.assertEquals(state_field.get(bsis), -1); // state doesn't change + + try { + state_field.setInt(bsis, 0); // state == NONE + bsis.reset(); + } catch (IOException e) { + Assert.assertEquals(e.getMessage(), "InputStream has not been marked"); + } + } + + @Test + public void markSupportedTest() { + Assert.assertTrue(bsis.markSupported()); + } + + // "Bug" 4/22/2013 + // Some XML code expects Buffered InputStream can never return 0... This isn't actually true, but we'll accommodate as far + // as we can. + // Here, we make sure we set and read the Buffered data, making sure the buffer is empty on the last test... + @Test + public void issue04_22_2013() throws IOException { + String testString = "We want to read in and get out with a Buffered Stream seamlessly."; + ByteArrayInputStream bais = new ByteArrayInputStream(testString.getBytes()); + BufferedServletInputStream bsis = new BufferedServletInputStream(bais); + try { + bsis.mark(0); + byte aa[] = new byte[testString.length()]; // 65 count... important for our test (divisible by 5); + + int read; + for (int i=0;i<aa.length;i+=5) { + read = bsis.read(aa, i, 5); + assertEquals(5,read); + } + // System.out.println(new String(aa)); + + bsis.reset(); + + byte bb[] = new byte[aa.length]; + read = 0; + for (int i=0;read>=0;i+=read) { + read = bsis.read(bb,i,5); + switch(i) { + case 65: + assertEquals(read,-1); + break; + default: + assertEquals(read,5); + } + } + // System.out.println(new String(bb)); + assertEquals(testString,new String(aa)); + assertEquals(testString,new String(bb)); + + } finally { + bsis.close(); + bais.close(); + } + + } + + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_CadiException.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_CadiException.java new file mode 100644 index 00000000..8167ce6c --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_CadiException.java @@ -0,0 +1,122 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.CadiException; + +import static org.hamcrest.CoreMatchers.is; + +public class JU_CadiException { + @Test + public void testCadiException() { + CadiException exception = new CadiException(); + + assertNotNull(exception); + } + + @Test + public void testCadiExceptionString() { + CadiException exception = new CadiException("New Exception"); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } + + @Test + public void testCadiExceptionThrowable() { + CadiException exception = new CadiException(new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); + } + + @Test + public void testCadiExceptionStringThrowable() { + CadiException exception = new CadiException("New Exception",new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + + } + + @Test + public void testCadiException1() { + CadiException exception = new CadiException(); + + assertNotNull(exception); + } + + @Test + public void testCadiExceptionString1() { + CadiException exception = new CadiException("New Exception"); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } + + @Test + public void testCadiExceptionThrowable1() { + CadiException exception = new CadiException(new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); + } + + @Test + public void testCadiExceptionStringThrowable1() { + CadiException exception = new CadiException("New Exception",new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + + } + + @Test + public void testCadiException2() { + CadiException exception = new CadiException(); + + assertNotNull(exception); + } + + @Test + public void testCadiExceptionString2() { + CadiException exception = new CadiException("New Exception"); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } + + @Test + public void testCadiExceptionThrowable2() { + CadiException exception = new CadiException(new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); + } + + @Test + public void testCadiExceptionStringThrowable2() { + CadiException exception = new CadiException("New Exception",new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + + } + + + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_CadiWrap.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_CadiWrap.java new file mode 100644 index 00000000..8adc04ef --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_CadiWrap.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import org.junit.*; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.security.Principal; +import java.util.List; + +import jakarta.servlet.http.HttpServletRequest; + +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.CachingLur; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.CadiWrap; +import org.onap.ccsdk.apps.cadi.Lur; +import org.onap.ccsdk.apps.cadi.Permission; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.User; +import org.onap.ccsdk.apps.cadi.CachedPrincipal.Resp; +import org.onap.ccsdk.apps.cadi.filter.MapPermConverter; +import org.onap.ccsdk.apps.cadi.lur.EpiLur; +import org.onap.ccsdk.apps.cadi.principal.TaggedPrincipal; +import org.onap.ccsdk.apps.cadi.taf.TafResp; + +public class JU_CadiWrap { + + @Mock + private HttpServletRequest request; + + @Mock + private TafResp tafResp; + + @Mock + private TaggedPrincipal principle; + + @Mock + private Lur lur; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + System.setOut(new PrintStream(new ByteArrayOutputStream())); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @SuppressWarnings("unchecked") + @Test + public void testInstantiate() throws CadiException { + Access a = new PropAccess(); + when(tafResp.getAccess()).thenReturn(a); + + lur.fishAll(isA(Principal.class), (List<Permission>)isA(List.class)); + + EpiLur lur1 = new EpiLur(lur); + + CadiWrap wrap = new CadiWrap(request, tafResp, lur1); + + assertNull(wrap.getUserPrincipal()); + assertNull(wrap.getRemoteUser()); + assertNull(wrap.getUser()); + assertEquals(wrap.getPermissions(principle).size(), 0); + assertTrue(wrap.access() instanceof PropAccess); + + byte[] arr = {'1','2'}; + wrap.setCred(arr); + + assertEquals(arr, wrap.getCred()); + + wrap.setUser("User1"); + assertEquals("User1", wrap.getUser()); + + wrap.invalidate("1"); + + assertFalse(wrap.isUserInRole(null)); + + wrap.set(tafResp, lur); + + wrap.invalidate("2"); + + assertFalse(wrap.isUserInRole("User1")); + } + + @Test + public void testInstantiateWithPermConverter() throws CadiException { + Access a = new PropAccess(); + when(tafResp.getAccess()).thenReturn(a); + when(tafResp.getPrincipal()).thenReturn(principle); + + // Anonymous object for testing purposes + CachingLur<Permission> lur1 = new CachingLur<Permission>() { + @Override public Permission createPerm(String p) { return null; } + @Override public boolean fish(Principal bait, Permission ... pond) { return true; } + @Override public void fishAll(Principal bait, List<Permission> permissions) { } + @Override public void destroy() { } + @Override public boolean handlesExclusively(Permission ... pond) { return false; } + @Override public boolean handles(Principal principal) { return false; } + @Override public void remove(String user) { } + @Override public Resp reload(User<Permission> user) { return null; } + @Override public void setDebug(String commaDelimIDsOrNull) { } + @Override public void clear(Principal p, StringBuilder sb) { } + }; + + MapPermConverter pc = new MapPermConverter(); + + CadiWrap wrap = new CadiWrap(request, tafResp, lur1, pc); + + assertNotNull(wrap.getUserPrincipal()); + assertNull(wrap.getRemoteUser()); + assertNull(wrap.getUser()); + + byte[] arr = {'1','2'}; + wrap.setCred(arr); + + assertEquals(arr, wrap.getCred()); + + wrap.setUser("User1"); + assertEquals("User1", wrap.getUser()); + + wrap.invalidate("1"); + wrap.setPermConverter(new MapPermConverter()); + + assertTrue(wrap.getLur() instanceof CachingLur); + assertTrue(wrap.isUserInRole("User1")); + + wrap.set(tafResp, lur); + assertFalse(wrap.isUserInRole("Perm1")); + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Capacitor.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Capacitor.java new file mode 100644 index 00000000..b0ba7815 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Capacitor.java @@ -0,0 +1,156 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static junit.framework.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.Capacitor; + +import java.lang.reflect.*; + +public class JU_Capacitor { + private Capacitor cap; + public final static String TEST_DATA = + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + + "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + + @Before + public void setup() { + cap = new Capacitor(); + } + + @Test + public void singleByteTest() throws Exception { + assertEquals(cap.read(), -1); + cap.setForRead(); + Field curr_field = Capacitor.class.getDeclaredField("curr"); + curr_field.setAccessible(true); + Field idx_field = Capacitor.class.getDeclaredField("idx"); + idx_field.setAccessible(true); + assertNull(curr_field.get(cap)); + assertEquals(idx_field.get(cap), 0); + + for (int iter = 0; iter < 20; ++iter) { + for (int i = 0; i < 20; ++i) { + cap.put((byte)('a' + i)); + } + cap.setForRead(); + byte[] array = new byte[20]; + for (int i = 0; i < 20; ++i) { + array[i]=(byte)cap.read(); + } + assertEquals("abcdefghijklmnopqrst", new String(array)); + assertEquals(-1, cap.read()); + + cap.done(); + } + + for (int i = 0; i < 500; i++) { + cap.put((byte)'a'); + } + cap.setForRead(); + byte[] array = new byte[500]; + for (int i = 0; i < 500; ++i) { + array[i]=(byte)cap.read(); + } + assertEquals((new String(array)).length(), 500); + assertEquals(-1, cap.read()); + } + + @Test + public void availableTest() { + assertEquals(cap.available(), 0); + for (int i = 0; i < 100; ++i) { + cap.put((byte)'a'); + } + // The Capacitor can hold 256 bytes. After reading 100 bytes, + // it should have 156 available + assertEquals(cap.available(), 156); + } + + @Test + public void byteArrayTest() { + byte[] arrayA = TEST_DATA.getBytes(); + assertEquals(cap.read(arrayA, 0, arrayA.length), -1); + + cap.put(arrayA, 0, arrayA.length); + + byte[] arrayB = new byte[arrayA.length]; + cap.setForRead(); + assertEquals(arrayA.length, cap.read(arrayB, 0, arrayB.length)); + assertEquals(TEST_DATA, new String(arrayB)); + assertEquals(-1, cap.read()); + cap.done(); + + String b = "This is some content that we want to read"; + byte[] a = b.getBytes(); + byte[] c = new byte[b.length()]; // we want to use this to test reading offsets, etc + + for (int i = 0; i < a.length; i += 11) { + cap.put(a, i, Math.min(11, a.length-i)); + } + cap.reset(); + int read; + for (int i = 0; i < c.length; i += read) { + read = cap.read(c, i, Math.min(3, c.length-i)); + } + assertEquals(b, new String(c)); + } + + @Test + public void resetTest() throws Exception { + cap.reset(); + Field curr_field = Capacitor.class.getDeclaredField("curr"); + curr_field.setAccessible(true); + Field idx_field = Capacitor.class.getDeclaredField("idx"); + idx_field.setAccessible(true); + assertNull(curr_field.get(cap)); + assertEquals(idx_field.get(cap), 0); + + cap.put((byte)'a'); + cap.reset(); + assertNotNull(curr_field.get(cap)); + assertEquals(idx_field.get(cap), 1); + } + + @Test + public void skipTest() throws Exception { + // capacitor can't skip if nothing has been put into it + assertEquals(cap.skip(10), 0); + cap.put((byte)'a'); + // The Capacitor can hold 256 bytes. If we try to skip 100 bytes, + // it should only skip 1 byte, leaving 255 remaining + assertEquals(cap.skip(100), 255); + + // Skipping 200 bytes leaves 0 remaining + assertEquals(cap.skip(200), 0); + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_CmdLine.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_CmdLine.java new file mode 100644 index 00000000..473aa1a0 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_CmdLine.java @@ -0,0 +1,275 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Properties; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.CmdLine; +import org.onap.ccsdk.apps.cadi.Symm; + +public class JU_CmdLine { + + @Mock + private OutputStream thrower; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + + private String password; + private String keyfile; + private String quickBrownFoxPlain = "The quick brown fox jumps over the lazy dog"; + private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; + private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; + private Symm symm; + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + + System.setOut(new PrintStream(outContent)); + + Properties p = new Properties(); + p.setProperty("force_exit", "false"); + + CmdLine.setSystemExit(false); + keyfile = "src/test/resources/keyfile"; + password = "password"; + + File keyF = new File("src/test/resources", "keyfile"); + FileInputStream fis = new FileInputStream(keyF); + try { + symm = Symm.obtain(fis); + } finally { + fis.close(); + } + } + + @After + public void restoreStreams() throws IOException { + System.setOut(System.out); + System.setIn(System.in); + } + + @Test + public void digestTest() throws Exception { + CmdLine.main(new String[]{"digest", password, keyfile}); + String decrypted = symm.depass(outContent.toString()); + assertThat(decrypted, is(password)); + + System.setIn(new ByteArrayInputStream(password.getBytes())); + CmdLine.main(new String[]{"digest", "-i", keyfile}); + decrypted = symm.depass(outContent.toString()); + assertThat(decrypted, is(password)); + } + + @Test + public void encode64Test() throws Exception { + CmdLine.main(new String[]{"encode64", password}); + String decrypted = Symm.base64.decode(outContent.toString()); + assertThat(decrypted, is(password)); + } + + @Test + public void decode64Test() throws Exception { + String encrypted = Symm.base64.encode(password); + CmdLine.main(new String[]{"decode64", encrypted}); + assertThat(outContent.toString(), is(password + System.lineSeparator())); + } + + @Test + public void encode64urlTest() throws Exception { + CmdLine.main(new String[]{"encode64url", password}); + String decrypted = Symm.base64url.decode(outContent.toString()); + assertThat(decrypted, is(password)); + } + + @Test + public void decode64urlTest() throws Exception { + String encrypted = Symm.base64url.encode(password); + CmdLine.main(new String[]{"decode64url", encrypted}); + assertThat(outContent.toString(), is(password + System.lineSeparator())); + } + + @Test + public void md5Test() throws Exception { + CmdLine.main(new String[]{"md5", quickBrownFoxPlain}); + assertThat(outContent.toString(), is(quickBrownFoxMD5 + System.lineSeparator())); + } + + @Test + public void sha256Test() throws Exception { + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain}); + assertThat(outContent.toString(), is(quickBrownFoxSHA256 + System.lineSeparator())); + + outContent.reset(); + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); + String hash1 = outContent.toString(); + + outContent.reset(); + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "10"}); + String hash2 = outContent.toString(); + + outContent.reset(); + CmdLine.main(new String[]{"sha256", quickBrownFoxPlain, "11"}); + String hash3 = outContent.toString(); + + assertThat(hash1, is(hash2)); + assertThat(hash1, is(not(hash3))); + } + + @Test + public void keygenTest() throws Exception { + CmdLine.main(new String[]{"keygen"}); + assertThat(outContent.toString().length(), is(2074)); + + String filePath = "test/output_key"; + File testDir = new File("test"); + if (!testDir.exists()) { + testDir.mkdirs(); + } + CmdLine.main(new String[]{"keygen", filePath}); + File keyfile = new File(filePath); + assertTrue(Files.isReadable(Paths.get(filePath))); + assertFalse(Files.isWritable(Paths.get(filePath))); + //assertFalse(Files.isExecutable(Paths.get(filePath))); + keyfile.delete(); + } + + @Test + public void passgenTest() throws Exception { + CmdLine.main(new String[]{"passgen"}); + String output = outContent.toString().trim(); + assertThat(output.length(), is(24)); + assertTrue(containsAny(output, "+!@#$%^&*(){}[]?:;,.")); + assertTrue(containsAny(output, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + assertTrue(containsAny(output, "abcdefghijklmnopqrstuvwxyz")); + assertTrue(containsAny(output, "0123456789")); + + int length = 10; + outContent.reset(); + CmdLine.main(new String[]{"passgen", String.valueOf(length)}); + output = outContent.toString().trim(); + assertThat(output.length(), is(length)); + + length = 5; + outContent.reset(); + CmdLine.main(new String[]{"passgen", String.valueOf(length)}); + output = outContent.toString().trim(); + assertThat(output.length(), is(8)); + + // Check that the custom hasRepeats method works + assertTrue(hasRepeats("aa")); + assertTrue(hasRepeats("baa")); + assertTrue(hasRepeats("aab")); + assertTrue(hasRepeats("baab")); + assertFalse(hasRepeats("abc")); + assertFalse(hasRepeats("aba")); + + // Run this a bunch of times for coverage + for (int i = 0; i < 1000; i++) { + outContent.reset(); + CmdLine.main(new String[]{"passgen"}); + output = outContent.toString().trim(); + assertFalse(hasRepeats(output)); + } + } + + @Test + public void urlgenTest() throws Exception { + CmdLine.main(new String[]{"urlgen"}); + String output = outContent.toString().trim(); + assertThat(output.length(), is(24)); + + int length = 5; + outContent.reset(); + CmdLine.main(new String[]{"urlgen", String.valueOf(length)}); + output = outContent.toString().trim(); + assertThat(output.length(), is(5)); + } + + @Test + public void showHelpTest() { + String lineSeparator = System.lineSeparator(); + String expected = + "Usage: java -jar <this jar> ..." + lineSeparator + + " keygen [<keyfile>] (Generates Key on file, or Std Out)" + lineSeparator + + " digest [<passwd>|-i|] <keyfile> (Encrypts Password with \"keyfile\"" + lineSeparator + + " if passwd = -i, will read StdIn" + lineSeparator + + " if passwd is blank, will ask securely)" + lineSeparator + + " undigest <enc:...> <keyfile> (Decrypts Encoded with \"keyfile\")" + lineSeparator + + " passgen <digits> (Generate Password of given size)" + lineSeparator + + " urlgen <digits> (Generate URL field of given size)" + lineSeparator + + " encode64 <your text> (Encodes to Base64)" + lineSeparator + + " decode64 <base64 encoded text> (Decodes from Base64)" + lineSeparator + + " encode64url <your text> (Encodes to Base64 URL charset)" + lineSeparator + + " decode64url <base64url encoded text> (Decodes from Base64 URL charset)" + lineSeparator + + " sha256 <text> <salts(s)> (Digest String into SHA256 Hash)" + lineSeparator + + " md5 <text> (Digest String into MD5 Hash)" + lineSeparator; + + CmdLine.main(new String[]{}); + + assertThat(outContent.toString(), is(expected)); + } + + private boolean containsAny(String str, String searchChars) { + for (char c : searchChars.toCharArray()) { + if (str.indexOf(c) >= 0) { + return true; + } + } + return false; + } + + private boolean hasRepeats(String str) { + int c = -1; + int last; + for (int i = 0; i < str.length(); i++) { + last = c; + c = str.charAt(i); + if (c == last) { + return true; + } + } + return false; + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Hash.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Hash.java new file mode 100644 index 00000000..946d931d --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Hash.java @@ -0,0 +1,225 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.Hash; + +public class JU_Hash { + // Some common test vectors + private String quickBrownFoxVector = "The quick brown fox jumps over the lazy dog"; + private String quickBrownFoxMD5 = "0x9e107d9d372bb6826bd81d3542a419d6"; + private String quickBrownFoxSHA256 = "0xd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"; + + private String emptyVector = ""; + private String emptyMD5 = "0xd41d8cd98f00b204e9800998ecf8427e"; + private String emptySHA256 = "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + + + private byte[] same1 = "this is a twin".getBytes(); + private byte[] same2 = "this is a twin".getBytes(); + private byte[] different1 = "guvf vf n gjva".getBytes(); + private byte[] different2 = "this is an only child".getBytes(); + + + private String uppersDec = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private String uppersHex1 = "0x4142434445464748494A4B4C4D4E4F505152535455565758595A"; + private String uppersHex2 = "0x4142434445464748494a4b4c4d4e4f505152535455565758595a"; + private String uppersHexNo0x1 = "4142434445464748494a4b4c4d4e4f505152535455565758595a"; + private String uppersHexNo0x2 = "4142434445464748494A4B4C4D4E4F505152535455565758595A"; + + private String lowersDec = "abcdefghijklmnopqrstuvwxyz"; + private String lowersHex = "0x6162636465666768696a6b6c6d6e6f707172737475767778797a"; + private String lowersHexNo0x1 = "6162636465666768696a6b6c6d6e6f707172737475767778797a"; + private String lowersHexNo0x2 = "6162636465666768696A6B6C6D6E6F707172737475767778797A"; + + private String numbersDec = "1234567890"; + private String numbersHex = "0x31323334353637383930"; + private String numbersHexNo0x = "31323334353637383930"; + + @SuppressWarnings("unused") + @BeforeClass + public static void getCoverage() { + // All of this class's methods are static, so we never need to instantiate an object. + // That said, we can't get 100% coverage unless we instantiate one + Hash hash = new Hash(); + } + + @Test + public void hashMD5Test() throws Exception { + byte[] output = Hash.hashMD5(quickBrownFoxVector.getBytes()); + assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); + + output = Hash.hashMD5(emptyVector.getBytes()); + assertEquals(emptyMD5, new String(Hash.toHex(output))); + } + + @Test + public void hashMD5WithOffsetTest() throws Exception { + byte[] output = Hash.hashMD5(quickBrownFoxVector.getBytes(), 0, quickBrownFoxVector.length()); + assertEquals(quickBrownFoxMD5, new String(Hash.toHex(output))); + + output = Hash.hashMD5(emptyVector.getBytes(), 0, emptyVector.length()); + assertEquals(emptyMD5, new String(Hash.toHex(output))); + } + + @Test + public void hashMD5AsStringHexTest() throws Exception { + String output = Hash.hashMD5asStringHex(quickBrownFoxVector); + assertEquals(quickBrownFoxMD5, output); + + output = Hash.hashMD5asStringHex(emptyVector); + assertEquals(emptyMD5, output); + } + + @Test + public void hashSHA256Test() throws Exception { + byte[] output = Hash.hashSHA256(quickBrownFoxVector.getBytes()); + assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); + + output = Hash.hashSHA256(emptyVector.getBytes()); + assertEquals(emptySHA256, new String(Hash.toHex(output))); + } + + @Test + public void hashSHA256WithOffsetTest() throws Exception { + byte[] output = Hash.hashSHA256(quickBrownFoxVector.getBytes(), 0, quickBrownFoxVector.length()); + assertEquals(quickBrownFoxSHA256, new String(Hash.toHex(output))); + + output = Hash.hashSHA256(emptyVector.getBytes(), 0, emptyVector.length()); + assertEquals(emptySHA256, new String(Hash.toHex(output))); + } + + @Test + public void hashSHA256AsStringHexTest() throws Exception { + String output = Hash.hashSHA256asStringHex(quickBrownFoxVector); + assertEquals(quickBrownFoxSHA256, output); + + output = Hash.hashSHA256asStringHex(emptyVector); + assertEquals(emptySHA256, output); + } + + @Test + public void hashSaltySHA256AsStringHexTest() throws Exception { + String input = "password"; + String hash1 = Hash.hashSHA256asStringHex(input, 10); + String hash2 = Hash.hashSHA256asStringHex(input, 10); + String hash3 = Hash.hashSHA256asStringHex(input, 11); + + assertEquals(hash1, hash2); + assertThat(hash1, not(equalTo(hash3))); + } + + @Test + public void isEqualTest() throws Exception { + assertTrue(Hash.isEqual(same1, same2)); + assertFalse(Hash.isEqual(same1, different1)); + assertFalse(Hash.isEqual(same1, different2)); + } + + @Test + public void compareToTest() throws Exception { + assertEquals(0, Hash.compareTo(same1, same2)); + // different1 is rot13(same1), so the difference should be 13 + assertEquals(13, Hash.compareTo(same1, different1)); + assertEquals(-78, Hash.compareTo(same1, different2)); + } + + @Test + public void toHexNo0xTest() throws Exception { + assertEquals(uppersHexNo0x1, Hash.toHexNo0x(uppersDec.getBytes())); + assertEquals(lowersHexNo0x1, Hash.toHexNo0x(lowersDec.getBytes())); + assertEquals(numbersHexNo0x, Hash.toHexNo0x(numbersDec.getBytes())); + } + + @Test + public void toHexTest() throws Exception { + assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes())); + assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes())); + assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes())); + } + + @Test + public void toHexWithOffset() throws Exception { + assertEquals(uppersHex2, Hash.toHex(uppersDec.getBytes(), 0, uppersDec.length())); + assertEquals(lowersHex, Hash.toHex(lowersDec.getBytes(), 0, lowersDec.length())); + assertEquals(numbersHex, Hash.toHex(numbersDec.getBytes(), 0, numbersDec.length())); + } + + @Test + public void fromHexTest() throws Exception { + assertEquals(uppersDec, new String(Hash.fromHex(uppersHex1))); + assertEquals(lowersDec, new String(Hash.fromHex(lowersHex))); + assertEquals(numbersDec, new String(Hash.fromHex(numbersHex))); + + // This string doesn't begin with "0x" + assertNull(Hash.fromHex("0X65")); + + // This string has invalid hex characters + assertNull(Hash.fromHex("0xQ")); + } + + @Test + public void fromHexNo0xTest() throws Exception { + assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x1))); + assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x1))); + assertEquals(uppersDec, new String(Hash.fromHexNo0x(uppersHexNo0x2))); + assertEquals(lowersDec, new String(Hash.fromHexNo0x(lowersHexNo0x2))); + byte[] output = Hash.fromHexNo0x("ABC"); + assertEquals(new String(new byte[] {(byte)0x0A, (byte)0xBC}), new String(output)); + assertNull(Hash.fromHexNo0x("~~")); + } + + @Test + public void aaf_941() throws Exception { + // User notes: From reported error "aaf" not coded right for odd digits + // Note: In the original concept, this isn't a valid Hex digit. It has to do with whether to assume an initial + // char of "0" if left out. + + String sample = "aaf"; + byte[] bytes = Hash.fromHexNo0x(sample); + String back = Hash.toHexNo0x(bytes); + // Note: We don't presume to know that someone left off leading 0 on start. + assertEquals("0aaf", back); + + sample = "0x0aaf"; + bytes = Hash.fromHex(sample); + back = Hash.toHex(bytes); + assertEquals(sample, back); + + // Assumed leading zero. Note, we ALWAYS translate back with leading zero. + bytes = Hash.fromHex("0xaaf"); + back = Hash.toHex(bytes); + assertEquals(sample, back); + + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_LocatorException.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_LocatorException.java new file mode 100644 index 00000000..26c56c64 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_LocatorException.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.LocatorException; + +import static org.hamcrest.CoreMatchers.is; + +public class JU_LocatorException { + @Test + public void stringTest() { + LocatorException exception = new LocatorException("New Exception"); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } + + @Test + public void throwableTest() { + LocatorException exception = new LocatorException(new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("java.lang.Throwable: New Exception")); + } + + @Test + public void stringThrowableTest() { + LocatorException exception = new LocatorException("New Exception",new Throwable("New Exception")); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } + + @Test + public void characterSequenceTest() { + CharSequence testCS = new String("New Exception"); + LocatorException exception = new LocatorException(testCS); + assertNotNull(exception); + assertThat(exception.getMessage(), is("New Exception")); + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_PropAccess.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_PropAccess.java new file mode 100644 index 00000000..198c94c4 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_PropAccess.java @@ -0,0 +1,146 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.junit.Assert.*; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.Access.Level; +import org.onap.ccsdk.apps.cadi.PropAccess.LogIt; + +import static org.mockito.Mockito.*; +import static org.hamcrest.CoreMatchers.*; + +import java.lang.reflect.Field; + +import java.io.ByteArrayInputStream; +import java.io.PrintStream; +import java.util.Properties; + +@SuppressWarnings("unused") +public class JU_PropAccess { + // Note: We can't actually get coverage of the protected constructor - + // that will be done later, when testing the child class "ServletContextAccess" + + + @Test + public void ConstructorTest() throws Exception { + PropAccess prop = new PropAccess(); + assertThat(prop.getProperties(), is(not(nullValue()))); + } + + @Test + public void noPrintStreamConstructionTest() throws Exception { + // Test for coverage + PropAccess prop = new PropAccess((PrintStream)null, new String[]{"Invalid argument"}); + } + + @Test + public void propertiesConstructionTest() throws Exception { + // Coverage tests + PropAccess prop = new PropAccess(System.getProperties()); + prop = new PropAccess((PrintStream)null, System.getProperties()); + } + + @Test + public void stringConstructionTest() throws Exception { + Properties testSystemProps = new Properties(System.getProperties()); + testSystemProps.setProperty("cadi_name", "user"); + System.setProperties(testSystemProps); + PropAccess prop = new PropAccess("cadi_keyfile=src/test/resources/keyfile", "cadi_loglevel=DEBUG", "cadi_prop_files=test/cadi.properties:not_a_file"); + } + + @Test + public void loadTest() throws Exception { + // Coverage tests + Properties props = mock(Properties.class); + when(props.getProperty("cadi_prop_files")).thenReturn("test/cadi.properties").thenReturn(null); + PropAccess pa = new PropAccess(); + Field props_field = PropAccess.class.getDeclaredField("props"); + props_field.setAccessible(true); + props_field.set(pa, props); + ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); + pa.load(bais); + } + + @Test + public void specialConversionsTest() throws Exception { + // Coverage tests + Properties testSystemProps = new Properties(System.getProperties()); + testSystemProps.setProperty("java.specification.version", "1.7"); + System.setProperties(testSystemProps); + PropAccess pa = new PropAccess("AFT_LATITUDE=1", "AFT_LONGITUDE=1", "cadi_protocols=TLSv1.2"); + } + + @Test + public void logTest() throws Exception { + // Coverage tests + PropAccess pa = new PropAccess(); + + pa.log(Level.DEBUG); + pa.printf(Level.DEBUG, "not a real format string"); + + pa.setLogLevel(Level.DEBUG); + pa.log(Level.DEBUG); + pa.log(Level.DEBUG, 1, " ", null, ""); + pa.log(Level.DEBUG, "This is a string", "This is another"); + pa.set(new LogIt() { + @Override public void push(Level level, Object ... elements) {} + }); + try { + pa.log(new Exception("This exception was thrown intentionally, please ignore it")); + } catch (Exception e) { + fail("Should have thrown an exception"); + } + } + + @Test + public void classLoaderTest() { + PropAccess pa = new PropAccess(); + assertThat(pa.classLoader(), instanceOf(ClassLoader.class)); + } + + @Test + public void encryptionTest() throws Exception { + PropAccess pa = new PropAccess(); + String plainText = "This is a secret message"; + String secret_message = pa.encrypt(plainText); + String modified = secret_message.substring(4); + // Plenty of assertions to hit all branches + assertThat(pa.decrypt(secret_message, false), is(plainText)); + assertThat(pa.decrypt(null, false), is(nullValue())); + assertThat(pa.decrypt(modified, true), is(plainText)); + assertThat(pa.decrypt(modified, false), is(modified)); + } + + @Test + public void setPropertyTest() { + PropAccess pa = new PropAccess(); + pa.setProperty("test", null); + String prop = "New Property"; + String val ="And it's faithful value"; + pa.setProperty(prop, val); + + assertThat(pa.getProperty(prop), is(val)); + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_ServletContextAccess.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_ServletContextAccess.java new file mode 100644 index 00000000..250e5f87 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_ServletContextAccess.java @@ -0,0 +1,101 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.ServletContextAccess; +import org.onap.ccsdk.apps.cadi.Access.Level; +import org.onap.ccsdk.apps.cadi.PropAccess.LogIt; + +import static org.mockito.Mockito.*; +import static org.hamcrest.CoreMatchers.*; + +import java.lang.reflect.Field; + +import java.io.ByteArrayInputStream; +import java.io.PrintStream; +import java.util.Enumeration; +import java.util.Properties; +import java.util.StringTokenizer; + +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletContext; + +@SuppressWarnings("unused") +public class JU_ServletContextAccess { + + private FilterConfig filter_mock; + Enumeration<String> enumeration; + + private class CustomEnumeration implements Enumeration<String> { + private int idx = 0; + private final String[] elements = {"This", "is", "a", "test"}; + @Override + public String nextElement() { + return idx >= elements.length ? null : elements[idx++]; + } + @Override + public boolean hasMoreElements() { + return idx < elements.length; + } + } + + @Before + public void setup() { + enumeration = new CustomEnumeration(); + filter_mock = mock(FilterConfig.class); + when(filter_mock.getInitParameterNames()).thenReturn(enumeration); + } + + + @Test + public void logTest() throws Exception { + ServletContext sc_mock = mock(ServletContext.class); + when(filter_mock.getServletContext()).thenReturn(sc_mock); + ServletContextAccess sca = new ServletContextAccess(filter_mock); + + sca.log(Level.DEBUG); + + sca.setLogLevel(Level.DEBUG); + sca.log(Level.DEBUG); + + try { + sca.log(new Exception("This exception was thrown intentionally, please ignore it")); + } catch (Exception e) { + fail("Should have thrown an exception"); + } + } + + @Test + public void contextTest() { + ServletContext sc_mock = mock(ServletContext.class); + when(filter_mock.getServletContext()).thenReturn(sc_mock); + ServletContextAccess sca = new ServletContextAccess(filter_mock); + assertThat(sca.context(), instanceOf(ServletContext.class)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Symm.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Symm.java new file mode 100644 index 00000000..bdffe5aa --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_Symm.java @@ -0,0 +1,213 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import java.lang.reflect.*; +import org.junit.*; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Arrays; + +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.Symm; + +public class JU_Symm { + private Symm defaultSymm; + + private ByteArrayOutputStream outStream; + + @Before + public void setup() throws Exception { + defaultSymm = new Symm( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray() + ,76, "Use default!" ,true, "Junit 1"); + outStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + } + + @Test + public void constructorTest() throws Exception { + Symm myCustomSymm = new Symm( + "ACEGIKMOQSUWYacegikmoqsuwy02468+/".toCharArray(), 76, "Default", true, "Junit 2"); + Field convert_field = Symm.class.getDeclaredField("convert"); + convert_field.setAccessible(true); + + Class<?> Unordered_class = Class.forName("org.onap.ccsdk.apps.cadi.Symm$Unordered"); + assertThat(convert_field.get(myCustomSymm), instanceOf(Unordered_class)); + } + + @SuppressWarnings("unused") + @Test + public void copyTest() throws Exception { + Symm copy = Symm.base64.copy(76); + } + + @SuppressWarnings("deprecation") + @Test + public void deprecatedTest() { + assertEquals(Symm.base64(), Symm.base64); + assertEquals(Symm.base64noSplit(), Symm.base64noSplit); + assertEquals(Symm.base64url(), Symm.base64url); + assertEquals(Symm.baseCrypt(), Symm.encrypt); + } + + @Test + public void encodeDecodeStringTest() throws Exception { + String orig = "hello"; + String b64encrypted = Symm.base64.encode(orig); + assertEquals(Symm.base64.decode(b64encrypted), orig); + + String defaultEnrypted = defaultSymm.encode(orig); + assertEquals(defaultSymm.decode(defaultEnrypted), orig); + } + + @Test + public void encodeDecodeByteArrayTest() throws Exception { + String orig = "hello"; + byte[] b64encrypted = Symm.base64.encode(orig.getBytes()); + assertEquals(new String(Symm.base64.decode(b64encrypted)), orig); + + byte[] empty = null; + assertTrue(Arrays.equals(Symm.base64.encode(empty), new byte[0])); + } + + @Test + public void encodeDecodeStringToStreamTest() throws Exception { + String orig = "I'm a password, really"; + String b64encrypted; + String output; + + ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); + Symm.base64.encode(orig, baosEncrypt); + b64encrypted = new String(baosEncrypt.toByteArray()); + + ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); + Symm.base64.decode(b64encrypted, baosDecrypt); + output = new String(baosDecrypt.toByteArray()); + + assertEquals(orig, output); + } + + @Test + public void encryptDecryptStreamWithPrefixTest() throws Exception { + String orig = "I'm a password, really"; + byte[] b64encrypted; + String output; + + byte[] prefix = "enc:".getBytes(); + + ByteArrayInputStream baisEncrypt = new ByteArrayInputStream(orig.getBytes()); + ByteArrayOutputStream baosEncrypt = new ByteArrayOutputStream(); + Symm.base64.encode(baisEncrypt, baosEncrypt, prefix); + + b64encrypted = baosEncrypt.toByteArray(); + + ByteArrayInputStream baisDecrypt = new ByteArrayInputStream(b64encrypted); + ByteArrayOutputStream baosDecrypt = new ByteArrayOutputStream(); + Symm.base64.decode(baisDecrypt, baosDecrypt, prefix.length); + + output = new String(baosDecrypt.toByteArray()); + assertEquals(orig, output); + } + + @Test + public void randomGenTest() { + // Ian - There really isn't a great way to test for randomness... + String prev = null; + for (int i = 0; i < 10; i++) { + String current = Symm.randomGen(100); + if (current.equals(prev)) { + fail("I don't know how, but you generated the exact same random string twice in a row"); + } + prev = current; + } + assertTrue(true); + } + + @Test + public void obtainTest() throws Exception { + Symm symm = Symm.base64.obtain(); + + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + } + + @Test + public void InputStreamObtainTest() throws Exception { + byte[] keygen = Symm.keygen(); + + Symm symm = Symm.obtain(new ByteArrayInputStream(keygen)); + + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + } + + @Test + public void StringObtainTest() throws Exception { + byte[] keygen = Symm.keygen(); + + Symm symm = Symm.obtain(new String(keygen)); + + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + } + + @Test + public void AccessObtainTest() throws Exception { + PropAccess pa = new PropAccess("cadi_keyfile=src/test/resources/keyfile"); + Symm symm = Symm.obtain(pa); + String orig ="Another Password, please"; + String encrypted = symm.enpass(orig); + String decrypted = symm.depass(encrypted); + assertEquals(orig, decrypted); + + try { + PropAccess badPa = mock(PropAccess.class); + when(badPa.getProperty("cadi_keyfile", null)).thenReturn("not_a_real_file.txt"); + symm = Symm.obtain(badPa); + fail("Should have thrown an exception"); + } catch (CadiException e) { + assertTrue(e.getMessage().contains("ERROR: ")); + assertTrue(e.getMessage().contains("not_a_real_file.txt")); + assertTrue(e.getMessage().contains(" does not exist!")); + } + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_TrustChecker.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_TrustChecker.java new file mode 100644 index 00000000..dd018c1a --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_TrustChecker.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.TrustChecker; + +public class JU_TrustChecker { + + @Test + public void noTrustTests() { + assertThat(TrustChecker.NOTRUST.mayTrust(null, null), is(nullValue())); + TrustChecker.NOTRUST.setLur(null); + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_User.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_User.java new file mode 100644 index 00000000..99b01609 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/test/JU_User.java @@ -0,0 +1,186 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + + +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.security.Principal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.apps.cadi.Permission; +import org.onap.ccsdk.apps.cadi.User; +import org.onap.ccsdk.apps.cadi.lur.LocalPermission; + +public class JU_User { + + private final Long SECOND = 1000L; + private final String name = "Fakey McFake"; + private final String cred = "Fake credentials"; + + private Field perms_field; + private Field count_field; + + @Mock + private Principal principal; + + @Mock + private LocalPermission permission; + @Mock + private LocalPermission permission2; + + @Before + public void setup() throws NoSuchFieldException, SecurityException { + MockitoAnnotations.initMocks(this); + + when(principal.getName()).thenReturn("Principal"); + + when(permission.getKey()).thenReturn("NewKey"); + when(permission.match(permission)).thenReturn(true); + + when(permission2.getKey()).thenReturn("NewKey2"); + when(permission2.match(permission)).thenReturn(false); + + perms_field = User.class.getDeclaredField("perms"); + perms_field.setAccessible(true); + + count_field = User.class.getDeclaredField("count"); + count_field.setAccessible(true); + } + + @Test + public void constructorPrincipalTest() throws IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(principal); + assertThat(user.name, is(principal.getName())); + assertThat(user.principal, is(principal)); + assertThat(user.permExpires(), is(Long.MAX_VALUE)); + assertThat((int)count_field.get(user), is(0)); + } + + @Test + public void constructorNameCredTest() throws IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(name, cred.getBytes()); + assertThat(user.name, is(name)); + assertThat(user.principal, is(nullValue())); + assertThat(user.permExpires(), is(Long.MAX_VALUE)); + assertThat((int)count_field.get(user), is(0)); + assertThat(user.getCred(), is(cred.getBytes())); + } + + @Test + public void constructorPrincipalIntervalTest() throws IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(principal, 61 * SECOND); + Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; + assertThat(user.name, is(principal.getName())); + assertThat(user.principal, is(principal)); + assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); + assertThat((int)count_field.get(user), is(0)); + } + + @Test + public void constructorNameCredIntervalTest() throws IllegalArgumentException, IllegalAccessException { + String name = "Fakey McFake"; + User<Permission> user = new User<Permission>(name, cred.getBytes(), 61 * SECOND); + Long approxExpiration = System.currentTimeMillis() + 61 * SECOND; + assertThat(user.name, is(name)); + assertThat(user.principal, is(nullValue())); + assertTrue(Math.abs(user.permExpires() - approxExpiration) < 10L); + assertThat((int)count_field.get(user), is(0)); + assertThat(user.getCred(), is(cred.getBytes())); + } + + @Test + public void countCheckTest() throws IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(principal); + user.resetCount(); + assertThat((int)count_field.get(user), is(0)); + user.incCount(); + assertThat((int)count_field.get(user), is(1)); + user.incCount(); + assertThat((int)count_field.get(user), is(2)); + user.resetCount(); + assertThat((int)count_field.get(user), is(0)); + } + + @Test + public void permTest() throws InterruptedException, IllegalArgumentException, IllegalAccessException { + User<Permission> user = new User<Permission>(principal); + assertThat(user.permExpires(), is(Long.MAX_VALUE)); + user.renewPerm(); + Thread.sleep(1); // Let it expire + assertThat(user.permExpired(), is(true)); + + user = new User<Permission>(principal,100); + assertTrue(user.noPerms()); + user.add(permission); + assertFalse(user.permsUnloaded()); + assertFalse(user.noPerms()); + user.setNoPerms(); + assertThat(user.permExpired(), is(false)); + assertTrue(user.permsUnloaded()); + assertTrue(user.noPerms()); + perms_field.set(user, null); + assertTrue(user.permsUnloaded()); + assertTrue(user.noPerms()); + } + + @Test + public void addValuesToNewMapTest() { + User<Permission> user = new User<Permission>(principal); + Map<String, Permission> newMap = new HashMap<>(); + + assertFalse(user.contains(permission)); + + user.add(newMap, permission); + user.setMap(newMap); + + assertTrue(user.contains(permission)); + + List<Permission> sink = new ArrayList<>(); + user.copyPermsTo(sink); + + assertThat(sink.size(), is(1)); + assertTrue(sink.contains(permission)); + + assertThat(user.toString(), is("Principal|:NewKey")); + + user.add(newMap, permission2); + user.setMap(newMap); + assertFalse(user.contains(permission2)); + + assertThat(user.toString(), is("Principal|:NewKey2,NewKey")); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_CSV.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_CSV.java new file mode 100644 index 00000000..5be4a8c4 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_CSV.java @@ -0,0 +1,125 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright (c) 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + */ + +package org.onap.ccsdk.apps.cadi.util.test; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.Access; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.PropAccess; +import org.onap.ccsdk.apps.cadi.util.CSV; +import org.onap.ccsdk.apps.cadi.util.CSV.Visitor; +import org.onap.ccsdk.apps.cadi.util.CSV.Writer; +import org.onap.ccsdk.apps.cadi.util.Holder; + +public class JU_CSV { + + private String filename; + private File file; + private static ArrayList<Object> expected; + + @Before + public void start() { + filename = "Sample.csv"; + file = new File(filename); + } + + @After + public void end() { + if(file!=null) { + file.delete(); + } + } + + @BeforeClass + public static void before() { + expected = new ArrayList<>(); + } + + @Test + public void test() throws IOException, CadiException { + Access access = new PropAccess(); + CSV csv = new CSV(access,file); + // Can't visit for file that doesn't exist + try { + csv.visit(new Visitor() { + @Override + public void visit(List<String> row) { + }}); + } catch(IOException e) { + Assert.assertTrue("CSV correctly created exception",true); + } + + Writer writer = csv.writer(); + try { + writer.row(add("\"hello\"")); + writer.comment("Ignore Comments"); + writer.row(add("dXNlcjpwYXNzd29yZA=="),add("dXNlckBzb21ldGhpbmcub3JnOm90aGVyUGFzc3dvcmQ=")); + writer.row(); // no output + writer.row(add("There is, but one thing to say"), add(" and that is"), add("\"All the best\"")); + } finally { + writer.close(); + } + + PrintStream garbage = new PrintStream(new FileOutputStream(file, true)); + try { + garbage.println("# Ignore empty spaces, etc"); + garbage.println(" "); + garbage.println("# Ignore blank lines"); + garbage.println(); + } finally { + garbage.close(); + } + + + //////////// + // Tests + //////////// + final Holder<Integer> hi = new Holder<>(0); + csv.visit(new CSV.Visitor() { + @Override + public void visit(List<String> row) { + for(String s: row) { +// System.out.println(hi.value + ") " + s); + Assert.assertEquals(expected.get(hi.get()),s); + hi.set(hi.get()+1); // increment + } + } + }); + + } + + private String add(String s) { + expected.add(s); + return s; + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Chmod.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Chmod.java new file mode 100644 index 00000000..770b874d --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Chmod.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Set; + +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.util.Chmod; + +public class JU_Chmod { + + private File file; + private String filePath; + + @Before + public void setup() throws IOException { + file = File.createTempFile("chmod_test", ""); + filePath = file.getAbsolutePath(); + } + + @After + public void tearDown() { + file.delete(); + } + + @Test + public void to755Test() throws IOException { + Chmod.to755.chmod(file); + Set<PosixFilePermission> set = Files.getPosixFilePermissions(Paths.get(filePath)); + assertThat(PosixFilePermissions.toString(set), is("rwxr-xr-x")); + } + + @Test + public void to644Test() throws IOException { + Chmod.to644.chmod(file); + Set<PosixFilePermission> set = Files.getPosixFilePermissions(Paths.get(filePath)); + assertThat(PosixFilePermissions.toString(set), is("rw-r--r--")); + } + + @Test + public void to400Test() throws IOException { + Chmod.to400.chmod(file); + Set<PosixFilePermission> set = Files.getPosixFilePermissions(Paths.get(filePath)); + assertThat(PosixFilePermissions.toString(set), is("r--------")); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_FQI.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_FQI.java new file mode 100644 index 00000000..9c62d6d0 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_FQI.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.util.FQI; + +public class JU_FQI { + + @Test + public void reverseDomainTest() { + assertThat(FQI.reverseDomain("user@att.com"), is("com.att")); + } + + @Test + public void coverageTest() { + @SuppressWarnings("unused") + FQI fqi = new FQI(); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Holder.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Holder.java new file mode 100644 index 00000000..aaa42ad9 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Holder.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.util.Holder; + +public class JU_Holder { + + @Test + public void test() { + String str1 = "a string"; + String str2 = "another string"; + Holder<String> holder = new Holder<String>(str1); + assertThat(holder.get(), is(str1)); + assertThat(holder.toString(), is(str1)); + + holder.set(str2); + assertThat(holder.get(), is(str2)); + assertThat(holder.toString(), is(str2)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_JsonOutputStream.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_JsonOutputStream.java new file mode 100644 index 00000000..1d74b16d --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_JsonOutputStream.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; + +import java.io.ByteArrayOutputStream; + +import org.junit.*; + +import java.io.IOException; +import java.lang.reflect.Field; + +import org.onap.ccsdk.apps.cadi.util.JsonOutputStream; + +public class JU_JsonOutputStream { + + private JsonOutputStream jos; + + @Before + public void setup() { + jos = new JsonOutputStream(new ByteArrayOutputStream()); + } + + @Test + public void constructorTest() { + jos = new JsonOutputStream(System.out); + jos = new JsonOutputStream(System.err); + } + + @Test + public void writeTest() throws IOException { + byte[] json = ("{" + + "name: user," + + "password: pass," + + "contact: {" + + "email: user@att.com," + + "phone: 555-5555" + + "}," + + "list: [" + + "item1," + + "item2" + + "],[],{}," + + "list:" + + "[" + + "item1," + + "item2" + + "]" + + "}").getBytes(); + jos.write(json); + } + + @Test + public void resetIndentTest() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + Field indentField = JsonOutputStream.class.getDeclaredField("indent"); + indentField.setAccessible(true); + + assertThat((int)indentField.get(jos), is(0)); + jos.resetIndent(); + assertThat((int)indentField.get(jos), is(1)); + } + + @Test + public void coverageTest() throws IOException { + jos.flush(); + jos.close(); + + jos = new JsonOutputStream(System.out); + jos.close(); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_MaskFormatException.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_MaskFormatException.java new file mode 100644 index 00000000..80240324 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_MaskFormatException.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.util.MaskFormatException; + +public class JU_MaskFormatException { + + @Test + public void throwsTest() { + String errorMessage = "This is a MaskFormatException"; + try { + throw new MaskFormatException(errorMessage); + } catch (Exception e) { + assertThat(e.getMessage(), is(errorMessage)); + assertTrue(e instanceof MaskFormatException); + } + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_NetMask.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_NetMask.java new file mode 100644 index 00000000..c8b3da07 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_NetMask.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.util.NetMask; + +public class JU_NetMask { + + @Test + public void deriveTest() { + String test = "test"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest2() { + String test = "1.2.3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest3() { + String test = "1.2.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest4() { + String test = "1.3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest5() { + String test = "2.3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } + + @Test + public void deriveTest6() { + String test = "3.4"; + assertEquals(NetMask.derive(test.getBytes()), 0); + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Pool.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Pool.java new file mode 100644 index 00000000..3b15e466 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Pool.java @@ -0,0 +1,238 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; +import org.onap.ccsdk.apps.cadi.CadiException; +import org.onap.ccsdk.apps.cadi.util.Log; +import org.onap.ccsdk.apps.cadi.util.Pool; +import org.onap.ccsdk.apps.cadi.util.Pool.*; + +public class JU_Pool { + + private class IntegerCreator implements Creator<Integer> { + private int current = 0; + + @Override + public Integer create() { + return current++; + } + + @Override + public void destroy(Integer t) { + t = 0; + } + + @Override + public boolean isValid(Integer t) { + return (t & 0x1) == 0; + } + + @Override + public void reuse(Integer t) { + } + } + + // Used for CustomLogger Testing + private StringBuilder sb = new StringBuilder(); + + private class CustomLogger implements Log { + @Override + public void log(Log.Type type, Object... o) { + for (Object item : o) { + sb.append(item.toString()); + } + } + } + + /** + * Enter variable amount in this order + * + * count, used, max_range, max_objects + * @param intPool + * @param ints + */ + private void check(Pool<Integer> intPool, int ... ints) { + String rpt = intPool.toString(); + // Fallthrough on purpose, to process only the ints entered, but in the right order. + switch(ints.length) { + case 4: + assertTrue(rpt.contains(String.format("max_objects(%d)", ints[3]))); + case 3: + assertTrue(rpt.contains(String.format("max_range(%d)", ints[2]))); + case 2: + assertTrue(rpt.contains(String.format("used(%d)", ints[1]))); + case 1: + assertTrue(rpt.contains(String.format("count(%d)", ints[0]))); + } + } + + @Test + public void settings() throws CadiException { + Pool<Integer> intPool = new Pool<Integer>(new IntegerCreator()); + check(intPool,0,0,Pool.MAX_RANGE,Pool.MAX_OBJECTS); + + // Check MaxObjects, min is 0 + intPool.setMaxObjects(-10); + check(intPool,0,0,Pool.MAX_RANGE,0); + + intPool.setMaxObjects(10); + check(intPool,0,0,Pool.MAX_RANGE,10); + + // Check MaxRange, min is 0 + intPool.setMaxRange(-10); + check(intPool,0,0,0,10); + + intPool.setMaxRange(2); + check(intPool,0,0,2,10); + + // Validate Priming + intPool.prime(3); + check(intPool,3,3,2,10); + + // Drain + intPool.drain(); + check(intPool,0,0,2,10); + } + + @Test + public void range() throws CadiException { + Pool<Integer> intPool = new Pool<Integer>(new IntegerCreator()); + intPool.setMaxRange(2); + check(intPool,0,0,2); + + // Prime + intPool.prime(3); + check(intPool,3,3,2); + + // Using 3 leaves count (in Pool) and Used (by System) 3 + List<Pooled<Integer>> using = new ArrayList<>(); + for(int i=0;i<3;++i) { + using.add(intPool.get()); + } + check(intPool,0,3,2); + + // Using 3 more creates more Objects, and uses immediately + for(int i=0;i<3;++i) { + using.add(intPool.get()); + } + check(intPool,0,6,2); + + // Clean out all Objects in possession, but there are 6 Objects not returned yet. + intPool.drain(); + check(intPool,0,6,2); + + // Returning Objects + for(Pooled<Integer> i : using) { + i.done(); + } + + // Since Range is 2, keep only 2, and destroy the rest + check(intPool,2,2,2); + + // Shutdown (helpful for stopping Services) involves turning off range + intPool.setMaxRange(0).drain(); + check(intPool,0,0,0); + } + + @Test + public void tooManyObjects() throws CadiException { + /* + * It should be noted that "tooManyObjects" isn't enforced by the Pool, because Objects are not + * tracked (other than used) once they leave the pool. + * + * It is information that using entities, like Thread Pools, can use to limit creations of expensive objects + */ + Pool<Integer> intPool = new Pool<Integer>(new IntegerCreator()); + intPool.setMaxObjects(10).setMaxRange(2); + check(intPool,0,0,2,10); + + assertFalse(intPool.tooManyObjects()); + + // Obtain up to maxium Objects + List<Pooled<Integer>> using = new ArrayList<>(); + for(int i=0;i<10;++i) { + using.add(intPool.get()); + } + + check(intPool,0,10,2,10); + assertFalse(intPool.tooManyObjects()); + + using.add(intPool.get()); + check(intPool,0,11,2,10); + assertTrue(intPool.tooManyObjects()); + + // Returning Objects + for(Pooled<Integer> i : using) { + i.done(); + } + + // Returning Objects puts Pool back in range + check(intPool,2,2,2,10); + assertFalse(intPool.tooManyObjects()); + + } + + @Test + public void bulkTest() throws CadiException { + Pool<Integer> intPool = new Pool<Integer>(new IntegerCreator()); + + intPool.prime(10); + // Remove all of the invalid items (in this case, odd numbers) + assertFalse(intPool.validate()); + + // Make sure we got them all + assertTrue(intPool.validate()); + + // Get an item from the pool + Pooled<Integer> gotten = intPool.get(); + assertThat(gotten.content, is(0)); + + // finalize that item, then check the next one to make sure we actually purged + // the odd numbers + gotten = intPool.get(); + assertThat(gotten.content, is(2)); + + intPool.drain(); + + } + + @Test + public void loggingTest() { + Pool<Integer> intPool = new Pool<Integer>(new IntegerCreator()); + + // Log to Log.NULL for coverage + intPool.log(Log.Type.info,"Test log output"); + + intPool.setLogger(new CustomLogger()); + intPool.log(Log.Type.info,"Test log output"); + + assertThat(sb.toString(), is("Test log output")); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Split.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Split.java new file mode 100644 index 00000000..a79dade9 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Split.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.util.Split; + +public class JU_Split { + + @Test + public void splitTest() { + String[] output = Split.split('c', "ctestctc", 0, "ctestctc".length()); + assertThat(output.length, is(4)); + assertThat(output[0], is("")); + assertThat(output[1], is("test")); + assertThat(output[2], is("t")); + assertThat(output[3], is("")); + + output = Split.split('c', "ctestctc", 0, 4); + assertThat(output.length, is(2)); + assertThat(output[0], is("")); + assertThat(output[1], is("tes")); + + output = Split.split('c', "test", 0, "test".length()); + assertThat(output.length, is(1)); + assertThat(output[0], is("test")); + + assertThat(Split.split('c', null, 0, 0).length, is(0)); + + // Test with fewer arguments + output = Split.split('c', "ctestctc"); + assertThat(output.length, is(4)); + assertThat(output[0], is("")); + assertThat(output[1], is("test")); + assertThat(output[2], is("t")); + assertThat(output[3], is("")); + } + + @Test + public void splitTrimTest() { + String[] output = Split.splitTrim('c', " cte stc ctc ", 0, " cte stc ctc ".length()); + assertThat(output.length, is(5)); + assertThat(output[0], is("")); + assertThat(output[1], is("te st")); + assertThat(output[2], is("")); + assertThat(output[3], is("t")); + assertThat(output[4], is("")); + + output = Split.splitTrim('c', " cte stc ctc ", 0, 5); + assertThat(output.length, is(2)); + assertThat(output[0], is("")); + assertThat(output[1], is("te")); + + assertThat(Split.splitTrim('c', " te st ", 0, " te st ".length())[0], is("te st")); + + assertThat(Split.splitTrim('c', null, 0, 0).length, is(0)); + + // Test with 2 arguments + output = Split.splitTrim('c', " cte stc ctc "); + assertThat(output.length, is(5)); + assertThat(output[0], is("")); + assertThat(output[1], is("te st")); + assertThat(output[2], is("")); + assertThat(output[3], is("t")); + assertThat(output[4], is("")); + + // Tests with 1 argument + output = Split.splitTrim('c', " cte stc ctc ", 1); + assertThat(output.length, is(1)); + assertThat(output[0], is("cte stc ctc")); + + output = Split.splitTrim('c', "testctest2", 2); + assertThat(output.length, is(2)); + assertThat(output[0], is("test")); + assertThat(output[1], is("test2")); + + output = Split.splitTrim('c', " cte stc ctc ", 4); + assertThat(output.length, is(4)); + assertThat(output[0], is("")); + assertThat(output[1], is("te st")); + assertThat(output[2], is("")); + + assertThat(Split.splitTrim('c', null, 0).length, is(0)); + } + + @Test + public void coverageTest() { + @SuppressWarnings("unused") + Split split = new Split(); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_SubStandardConsole.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_SubStandardConsole.java new file mode 100644 index 00000000..5f5bb57a --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_SubStandardConsole.java @@ -0,0 +1,126 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; +import org.junit.*; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.lang.reflect.Field; + +import org.onap.ccsdk.apps.cadi.util.SubStandardConsole; + +public class JU_SubStandardConsole { + + private String inputString = "An input string"; + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream errStream; + private String lineSeparator = System.lineSeparator(); + + @Before + public void setup() { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setOut(System.out); + System.setErr(System.err); + } + + @Test + public void readLineTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s" + lineSeparator, ">>> "); + assertThat(output, is(inputString)); + assertThat(outStream.toString(), is(">>> " + lineSeparator)); + } + + @Test + public void readLineTest2() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s %s" + lineSeparator, ">>> ", "Another argument for coverage"); + assertThat(output, is(inputString)); + } + + @Test + public void readLineTest3() { + byte[] input = "\n".getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + String output = ssc.readLine("%s" + lineSeparator, ">>> "); + assertThat(output, is(">>> ")); + assertThat(outStream.toString(), is(">>> " + lineSeparator)); + } + + @Test + public void readPasswordTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + char[] output = ssc.readPassword("%s" + lineSeparator, ">>> "); + System.out.println(output); + assertThat(output, is(inputString.toCharArray())); + assertThat(outStream.toString(), is(">>> " + lineSeparator + "An input string" + lineSeparator)); + } + + @Test + public void printfTest() { + byte[] input = inputString.getBytes(); + System.setIn(new ByteArrayInputStream(input)); + SubStandardConsole ssc = new SubStandardConsole(); + ssc.printf("%s", "A format specifier"); + assertThat(outStream.toString(), is("A format specifier")); + } + + @Test + public void throwsTest() throws IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + BufferedReader brMock = mock(BufferedReader.class); + when(brMock.readLine()).thenThrow(new IOException()); + + SubStandardConsole ssc = new SubStandardConsole(); + + Field brField = SubStandardConsole.class.getDeclaredField("br"); + brField.setAccessible(true); + brField.set(ssc, brMock); + + assertThat(ssc.readLine(""), is("")); + assertThat(errStream.toString(), is("uh oh..." + lineSeparator)); + errStream.reset(); + assertThat(ssc.readPassword("").length, is(0)); + assertThat(errStream.toString(), is("uh oh..." + lineSeparator)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_TheConsole.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_TheConsole.java new file mode 100644 index 00000000..f4fca0f7 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_TheConsole.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.util.TheConsole; + +public class JU_TheConsole { + + @Test + public void implemented(){ + assertEquals(TheConsole.implemented(),false); + } +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_UserChainManip.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_UserChainManip.java new file mode 100644 index 00000000..607bcc18 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_UserChainManip.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import org.onap.ccsdk.apps.cadi.UserChain; +import org.onap.ccsdk.apps.cadi.util.UserChainManip; + +public class JU_UserChainManip { + + @Test + public void build(){ + UserChain.Protocol baseAuth=UserChain.Protocol.BasicAuth; + StringBuilder sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, true); + assertThat(sb.toString(), is("app:id:BasicAuth:AS")); + + // for coverage + sb = UserChainManip.build(sb, "app", "id", baseAuth, true); + assertThat(sb.toString(), is("app:id:BasicAuth:AS,app:id:BasicAuth")); + + sb = UserChainManip.build(new StringBuilder(""), "app", "id", baseAuth, false); + assertThat(sb.toString(), is("app:id:BasicAuth")); + } + + @Test + public void idToNSTEST() { + assertThat(UserChainManip.idToNS(null), is("")); + assertThat(UserChainManip.idToNS(""), is("")); + assertThat(UserChainManip.idToNS("something"), is("")); + assertThat(UserChainManip.idToNS("something@@"), is("")); + assertThat(UserChainManip.idToNS("something@@."), is("")); + assertThat(UserChainManip.idToNS("something@com"), is("com")); + assertThat(UserChainManip.idToNS("something@random.com"), is("com.random")); + assertThat(UserChainManip.idToNS("@random.com"), is("com.random")); + assertThat(UserChainManip.idToNS("something@random.com."), is("com.random")); + assertThat(UserChainManip.idToNS("something@..random...com..."), is("com.random")); + assertThat(UserChainManip.idToNS("something@this.random.com"), is("com.random.this")); + } + + @Test + public void coverageTest() { + @SuppressWarnings("unused") + UserChainManip ucm = new UserChainManip(); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Vars.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Vars.java new file mode 100644 index 00000000..6b31ef01 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/util/test/JU_Vars.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.util.test; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.util.Vars; + +public class JU_Vars { + + @Test + public void coverage() { + @SuppressWarnings("unused") + Vars my_nonstatic_object_for_coverage = new Vars(); + } + + @Test + public void convert() { + String test = "test"; + List<String> list = new ArrayList<>(); + list.add("method"); + assertEquals(Vars.convert(test, list), test); + } + + @Test + public void convertTest1() { + List<String> list = new ArrayList<>(); + list.add("method"); + assertEquals(Vars.convert("test", list), "test"); + } + + @Test + public void convertTest2() { + List<String> list = new ArrayList<>(); + list.add("method"); + assertEquals(Vars.convert("test", list), "test"); + } + + @Test + public void test() { + StringBuilder holder = new StringBuilder(); + String str,bstr; + assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "a","b")); + assertEquals("set a to b",holder.toString()); + assertEquals(str,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "a","b")); + assertEquals("set a to b",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "a","b")); + + holder.setLength(0); + assertEquals(str = "%1=%2",Vars.convert(holder,str, "a","b")); + assertEquals("a=b",holder.toString()); + assertEquals(str,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="%s=%s", "a","b")); + assertEquals("a=b",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "a","b")); + + holder.setLength(0); + assertEquals(str = "%1%2",Vars.convert(holder,str, "a","b")); + assertEquals("ab",holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="%s%s", "a","b")); + assertEquals("ab",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "a","b")); + + + holder.setLength(0); + assertEquals(str = " %1=%2 ",Vars.convert(holder,str, "a","b")); + assertEquals(" a=b ",holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr = " %s=%s ", "a","b")); + assertEquals(" a=b ",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "a","b")); + + holder.setLength(0); + assertEquals(str = " %1%2%10 ",Vars.convert(holder,str, "a","b","c","d","e","f","g","h","i","j")); + assertEquals(" abj ",holder.toString()); + assertEquals(str,Vars.convert(null,str, "a","b","c","d","e","f","g","h","i","j")); + holder.setLength(0); + assertEquals(str=" %1%2%3 ",Vars.convert(holder,bstr = " %s%s%s ", "a","b","c","d","e","f","g","h","i","j")); + assertEquals(" abc ",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "a","b","c","d","e","f","g","h","i","j")); + + + holder.setLength(0); + assertEquals(str = "set %1 to %2",Vars.convert(holder,str, "Something much","larger")); + assertEquals("set Something much to larger",holder.toString()); + assertEquals(str,Vars.convert(null,str,"Something much","larger")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="set %s to %s", "Something much","larger")); + assertEquals("set Something much to larger",holder.toString()); + assertEquals(str,Vars.convert(null,bstr, "Something much","larger")); + + holder.setLength(0); + assertEquals(str = "Text without Vars",Vars.convert(holder,str)); + assertEquals(str,holder.toString()); + assertEquals(str = "Text without Vars",Vars.convert(null,str)); + + + holder.setLength(0); + assertEquals(str = "Not %1 Enough %2 Vars %3",Vars.convert(holder,str, "a","b")); + assertEquals("Not a Enough b Vars ",holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + holder.setLength(0); + assertEquals(str,Vars.convert(holder,bstr="Not %s Enough %s Vars %s", "a","b")); + assertEquals("Not a Enough b Vars ",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "a","b")); + + holder.setLength(0); + assertEquals(str = "!@#$%^*()-+?/,:;.",Vars.convert(holder,str, "a","b")); + assertEquals(str,holder.toString()); + assertEquals(str ,Vars.convert(null,str, "a","b")); + + holder.setLength(0); + bstr = "%s !@#$%^*()-+?/,:;."; + str = "%1 !@#$%^*()-+?/,:;."; + assertEquals(str,Vars.convert(holder,bstr, "Not Acceptable")); + assertEquals("Not Acceptable !@#$%^*()-+?/,:;.",holder.toString()); + assertEquals(str ,Vars.convert(null,bstr, "Not Acceptable")); + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/wsse/test/JU_WSSEParser.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/wsse/test/JU_WSSEParser.java new file mode 100644 index 00000000..c56cc1aa --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/wsse/test/JU_WSSEParser.java @@ -0,0 +1,164 @@ +/******************************************************************************* +* ============LICENSE_START==================================================== +* * org.onap.ccsdk.apps +* * =========================================================================== +* * Copyright © 2023 AT&T Intellectual Property. All rights reserved. +* * =========================================================================== +* * Licensed 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. +* * ============LICENSE_END==================================================== +* * +* * +******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.wsse.test; + +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.wsse.WSSEParser; + +public class JU_WSSEParser { + + @Test + public void test() { + @SuppressWarnings("unused") + WSSEParser wp = new WSSEParser(); + + // TODO: test the rest of this class +// final BasicCred bc = new BasicCred() { +// private String user; +// private byte[] password; +// +// public void setUser(String user) { this.user = user; } +// public void setCred(byte[] passwd) { this.password = passwd; } +// public String getUser() { return user; } +// public byte[] getCred() { return password; } +// }; + +// FileInputStream fis; +// fis = new FileInputStream("test/example.xml"); +// BufferedServletInputStream is = new BufferedServletInputStream(fis); +// try { +// is.mark(1536); +// try { +// assertNull(wp.parse(bc, is)); +// } finally { +// is.reset(); +// assertEquals(814,is.buffered()); +// } +// String password = new String(bc.getCred()); +// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); +// assertEquals("some_user", bc.getUser()); +// assertEquals("some_password", password); +// +// } finally { +// fis.close(); +// } +// +// // CBUS (larger) +// fis = new FileInputStream("test/CBUSevent.xml"); +// is = new BufferedServletInputStream(fis); +// try { +// is.mark(1536); +// try { +// assertNull(wp.parse(bc, is)); +// } finally { +// is.reset(); +// assertEquals(667,is.buffered()); +// } +// String password = new String(bc.getCred()); +// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password); +// assertEquals("none", bc.getUser()); +// assertEquals("none", password); +// +// } finally { +// fis.close(); +// } +// +// // Closed Stream +// fis = new FileInputStream("test/example.xml"); +// fis.close(); +// bc.setCred(null); +// bc.setUser(null); +// XMLStreamException ex = wp.parse(bc, fis); +// assertNotNull(ex); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); +// +// +// fis = new FileInputStream("test/exampleNoSecurity.xml"); +// try { +// bc.setCred(null); +// bc.setUser(null); +// assertNull(wp.parse(bc, fis)); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); +// } finally { +// fis.close(); +// } +// +// fis = new FileInputStream("test/exampleBad1.xml"); +// try { +// bc.setCred(null); +// bc.setUser(null); +// assertNull(wp.parse(bc, fis)); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); +// } finally { +// fis.close(); +// } +// +// XMLStreamException e = wp.parse(bc, new ByteArrayInputStream("Not XML".getBytes())); // empty +// assertNotNull(e); +// +// e = wp.parse(bc, new ByteArrayInputStream("".getBytes())); // empty +// assertNotNull(e); +// +// +// long start, count = 0L; +// int iter = 30000; +// File f = new File("test/CBUSevent.xml"); +// fis = new FileInputStream(f); +// is = new BufferedServletInputStream(fis); +// is.mark(0); +// try { +// while (is.read()>=0); +// } finally { +// fis.close(); +// } +// +// for (int i=0;i<iter;++i) { +// start = System.nanoTime(); +// is.reset(); +// try { +// assertNull(wp.parse(bc, is)); +// } finally { +// count += System.nanoTime()-start; +// } +// } +// float ms = count/1000000f; +// System.out.println("Executed " + iter + " WSSE reads from Memory Stream in " + ms + "ms. " + ms/iter + "ms per trans"); +// +// // SPECIFIC ISSUES +// +// fis = new FileInputStream("test/error2013_04_23.xml"); +// try { +// bc.setCred(null); +// bc.setUser(null); +// assertNull(wp.parse(bc, fis)); +// assertNull(bc.getUser()); +// assertNull(bc.getCred()); +// } finally { +// fis.close(); +// } + } + +} diff --git a/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/wsse/test/JU_XReader.java b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/wsse/test/JU_XReader.java new file mode 100644 index 00000000..3cb73177 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/ccsdk/apps/cadi/wsse/test/JU_XReader.java @@ -0,0 +1,153 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.ccsdk + * * =========================================================================== + * * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * * =========================================================================== + * * Licensed 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. + * * ============LICENSE_END==================================================== + * * + * * + ******************************************************************************/ + +package org.onap.ccsdk.apps.cadi.wsse.test; + +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.is; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintWriter; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.XMLEvent; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.ccsdk.apps.cadi.wsse.XEvent; +import org.onap.ccsdk.apps.cadi.wsse.XReader; + +public class JU_XReader { + + private final static String TEST_DIR_NAME = "src/test/resources"; + private final static String TEST_XML_NAME = "test.xml"; + private static File testXML; + + private final static String COMMENT = "a comment"; + private final static String OUTER_TAG = "outerTag"; + private final static String INNER_TAG = "innerTag"; + private final static String DATA_TAG = "dataTag"; + private final static String DATA = "some text that represents data"; + private final static String SELF_CLOSING_TAG = "selfClosingTag"; + private final static String PREFIX = "prefix"; + private final static String SUFFIX = "suffix"; + + @BeforeClass + public static void setupOnce() throws IOException { + testXML = setupXMLFile(); + } + + @AfterClass + public static void tearDownOnce() { + testXML.delete(); + } + + @Test + public void test() throws XMLStreamException, IOException { + FileInputStream fis = new FileInputStream(TEST_DIR_NAME + '/' + TEST_XML_NAME); + try { + XReader xr = new XReader(fis); + assertThat(xr.hasNext(), is(true)); + XEvent xe; + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_DOCUMENT)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.COMMENT)); + assertThat(((XEvent.Comment)xe).value, is(COMMENT)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(OUTER_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(INNER_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(DATA_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.CHARACTERS)); + assertThat(xe.asCharacters().getData().toString(), is(DATA)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); + assertThat(xe.asEndElement().getName().toString(), is(DATA_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(SELF_CLOSING_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.START_ELEMENT)); + assertThat(xe.asStartElement().getName().toString(), is(SUFFIX)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); + assertThat(xe.asEndElement().getName().toString(), is(INNER_TAG)); + + xe = getNextEvent(xr); + assertThat(xe.getEventType(), is(XMLEvent.END_ELEMENT)); + assertThat(xe.asEndElement().getName().toString(), is(OUTER_TAG)); + + assertThat(xr.hasNext(), is(false)); + + } finally { + fis.close(); + } + } + + private static XEvent getNextEvent(XReader xr) throws XMLStreamException { + if (xr.hasNext()) { + return xr.nextEvent(); + } + return null; + } + + private static File setupXMLFile() throws IOException { + File xmlFile = new File(TEST_DIR_NAME, TEST_XML_NAME); + PrintWriter writer = new PrintWriter(xmlFile); + writer.println(" "); // Whitespace before the document - this is for coverage + writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); + writer.println("<!DOCTYPE xml>"); + writer.println("<!--" + COMMENT + "-->"); + writer.println("<" + OUTER_TAG + ">"); + writer.println(" <" + INNER_TAG + ">"); + writer.println(" <" + DATA_TAG + ">" + DATA + "</" + DATA_TAG + ">"); + writer.println(" <" + SELF_CLOSING_TAG + " withAnAttribute=\"That has nested \\\" marks\" />"); + writer.println(" <" + PREFIX + ":" + SUFFIX + "/>"); + writer.println(" </" + INNER_TAG + ">"); + writer.println("</" + OUTER_TAG + ">"); + writer.flush(); + writer.close(); + return xmlFile; + } +} diff --git a/cadi/core/src/test/resources/AESKeyFile b/cadi/core/src/test/resources/AESKeyFile new file mode 100644 index 00000000..35795c34 --- /dev/null +++ b/cadi/core/src/test/resources/AESKeyFile @@ -0,0 +1,27 @@ +xteeS5pA6m4SW2fMANEeF__VDm3F2wlUqyeUKDKxlSFiS_ICs0Eg7Xeqj3WqbgRqOisc1hLIbyk3 +2bal9qYwT59VxcZy-vrS3ytf0uu5gWwxGfo2-ut3CQTBfwVOj88RMdiyM13-dxJGOdQxT9_Czc9A +it4edvcVQOTeazJ9JJ0KtO5tvsdihsaYYOVbMbMWPTzyDKY2KE7iMmPaqeGPLvxZSVvjQzjU8qMp +OwzllAhRXZd0DWOullSotpt8P2VKcbnoKVA2SQvLTt5Zd9TziaaCMP88-fJQUhXvWhUPG_ZdH2R1 +MVyS0WrnBN6rY2h_aTiUswYZ6GGTDa_7O4AQixNR02NAbn7718Mw3bbe12d6nJZ2uYqMb9Hl1bzO +-mZbJ_TUVAIUBgOb7XjScIS12JLlUuf-kIlQjfT2kfAzSuwcYHUZmB_jAfdZBjyhqVj4x7N47wb1 +7GbBBbECLAPMk9633_3HzadqZu6J3TmfmW2IYR9kqEF1NwfaXgJAL4I43YDSo2XyD-i9MUb3diYd +LVElQP8gwMh2gbfRe_7BU49_HdbCk4n6BNgT0Z0EgtnMAA0ZZWmBTJTz5BlC0lXL-7NAWyOw1vRs +ovjqc46zpQq8LYtJ2Vg5WwfpqBpyXqCdp9QYTNtN0GVB4iPBvaWRsQoZKzEESHavxKbGX2_Z7h2Q +k03Okhl4Ud3MduR6pyxfxVqAdFu3xr2tEIcv_FjyD-5XiTfKcWPw-Srwy-_YiTy_io4nu2swC8Xm +TsNcWtebM0W80L1nw0MwHFFIoAMBrHUjHxIrZL5JWZyaGxUdtnbKKlkVR1kDC8_pHrevwIijAEyi +NnwDYaMw7tZo6f06J3yPVCVzVLLXFCCTkvdJAFBhaZI600mf7UZP2BMqomYVROoQNZDAO_GzP1sX +_B4oebfYPkLk3fBkHasHPDZNy-oNHDEw8ytMXlMhyKX7UHUy28E8zpZWoRMmGPnzOSwp3P-Q08DP +ja05l6vgvGtzuWNUKcFjSTdqx73JJJ1-QrZZlTd0N1gYqhRyh8YssGDYXEHh5zKuF6vNTinJwGLY +P5NnOSBCbm9rcPcZGtZYer-uNUY9Z_rscfxiVork1SfnG25FwxCRkc_Nf47THAVM9T7m9Ou_g2N8 +eethvrQxDxEi_DVRBTJYe_9iUOec4KQY7VGhTiFbfvDPRB8yF7Znu5UPJXIeOjvcf9gi8lSwTTRx +sqRpB3D5SJUSnBGzOCUvYRBbGP0olaVYyVXLcDknRTKbwkIf0tKAEFRDkvkXdlJnQ4lldFHuuHO9 +G7_iqEjCCNncdtLZMwe6LPe1usfJmnl3x95wkpVQdAKl7QoP5fMR2XoXwQbSO2qwIdgBwq9Zm6FW +wRPStR0pS2ICjHusgmLPsdf2pVZ8q0fqjjzF4Ch7MfOWjhRsK9fCvVDXlrEOACTt7o0roXuswxKT +EEbibkLsEAQOfOCYa66G37yQKRNnR8PWeRLAaZGF8ewfqF0c2KBAQuLYFlE8OthP_vFDKfVT2zMX +BfneXOJNY2kZTEJA4MQOC4_Y1JJ7NJc1zqJRuPD8Ifo4oE1Qo2FE-mjm2G_Zb4XsmBEdWsiSAYum +2DiGm5Io7OXQXv2zOKsBvcoG-24A4M3kTxhEH16sueTKY_DqOjjxkcVIUX_PM7TGkeRU9cnJ2sDH +Y749blu8BWrRKSRiksxwwNAGW_IdElVVGd89gyGGRzZ2I4h-FXf9EBS1sqo-F_hOq_O3KOoMDFWK +gdc4XIqeqmjwVTSpkKyxSCFYQW-aPBuTSdJYmPZRQQlCXwkm7SHbLRBKM4h62koA8A3hpzda3qnZ +w_Wyb8u42yZpqNuUjUUOb4JApmOVCXIe4P9yfhiTbYRvGX50XjPIHBKjAzXhKLGaBaugBYhaGpXf +kFjvsEF-4PrtQWORKudvlk8D7DnhxqgJdG0GoZAETBTCq_m1trg2TJ2WyAMidFUOWrgGPpshFq1F +Nu7buFG6nsOsg4sfLmSm2oYhVb0TmEbBGRr_Apkg6nVJzX7DE_Rvt2slZDoIrXeKSbIJ_i5Y
\ No newline at end of file diff --git a/cadi/core/src/test/resources/CBUSevent.xml b/cadi/core/src/test/resources/CBUSevent.xml new file mode 100644 index 00000000..d0f7e34e --- /dev/null +++ b/cadi/core/src/test/resources/CBUSevent.xml @@ -0,0 +1,44 @@ +<!-- + ============LICENSE_START==================================================== + * org.onap.ccsdk + * =========================================================================== + * Copyright © 2023 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * Licensed 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. + * ============LICENSE_END==================================================== + * +--> +<assembly> + <id>app</id> + <formats> + <format>jar</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <dependencySets> + <dependencySet> + <outputDirectory></outputDirectory> + <outputFileNameMapping></outputFileNameMapping> + <unpack>true</unpack> + <scope>runtime</scope> + <!-- includes> + <include>web</include> + </includes --> + </dependencySet> + </dependencySets> + <fileSets> + <fileSet> + <directory>target/classes</directory> + <outputDirectory></outputDirectory> + </fileSet> + </fileSets> +</assembly> diff --git a/cadi/core/src/test/resources/keyfile b/cadi/core/src/test/resources/keyfile new file mode 100644 index 00000000..e84bd616 --- /dev/null +++ b/cadi/core/src/test/resources/keyfile @@ -0,0 +1,27 @@ +9zgJxUXT1CrzC_A2Z0PdKi3n9l6zmErB26ZlSXCCyloxi3bGqD3lNHC3aFHfgC8-ZwNMuLBM93WY +JV4sEacNodHGjgmAqSVyMHiPTEP4XRrydfjXAvaBIERcU1Yvu4pa4Mq25RXLHt8tIAnToFVbq82n +bjkfdcv2-shgwkEvRiNIdK5TITO8JTvTRWND5MqXc9gnCKkR6Rl5dU5QGIB2SxWOPCvKBBWeUGRO +bSinrjkI-iXabuLOYUaGo6FI_XAU5S9WxvfrDVpBijUAGJW8QZe1oBIo5QmQlx6ONB4ohjEu89ZZ +gTee22MvSNUvaT8IGbj_Zt_TyuCqcdmkVahWp5ffeK2J3bmHActAC2IxXD4yV-sFLB7PW7I8KMA7 +tML3Lcy9ozmYa2E8N8B9uQ0zMHz_TVpPvj5xkVF4_FEKOTD1mkf-JYC1CyzwJS2YWWxO6fqsxIjD +1qB4OJudv4RK6hSxdVrNxc_wchVAGXVD6ulm8UPBGP_wpfItP8BGYwCHlOjUrZofewKB2Aa9Uk9m +oyk309WmPVBeRzZ0vRlXUp8jhKlAPISvv8CBbG-6SuXAszY2qedgd3huYKNreVN-xMZM2hnYbEUW +0sdcqpFqIV039Awfwjn5sZPFW4iT3yWhxib1PwFzwfaXnrwgwbLAda68mRDAWCrsDRu11IiQJqb7 +cjNLYBOGDVhX7jeUyBJUzW-xhl__DsoCZSqP39vFoPtglXHlQNtVqQ8d96mu_QMY5bcuhevI4RQ_ +SD7WcRyAiUztiC4Eb6BYwld0RITdB1-Y43jkZlfA8Ej5Zw8sX_-2J2hKdDPT4KrTYWA5T6wiIJK9 +lxIc39wGHpxQ4kz8gx0VeqRU2hgHVKovuaEvBnwv8JW3qeuowaUmiPi7UuIRwi4pFX5iQv62yrfO +5Z6EXBDVI8Ikq4UTu70vX_bCuXHtvqm97PFh2KXjBHS--iNVQ5GhnDKKv_Fd4naQjCSwTTgtxD4X +ASgLSSETGJ8wAjWHOWUuVT4jUDFIQwunNaH6y2NaDWA0tkO74oYaQIL_-kd9ChGLzGL389v8BV2X +oaw70W9L3-OOtzAz-hACbOtbbMkx2bVMmS8QhjYg-_2bpwSb8NR322pQ9AodFTU4x5HrLoERk2Rw +hRExZP7K-_idMJUGLF9gJFFS01UyBLijyWGyN0teQleXgn6IzZk7dH9roddoe9IacjiV7XfE4i1U +rVNTRKiDdHSX02KGOihs_j-Tf0PYsz0wEeACINA5MafGzc9x2b8yMzBxwPHxRszjL4dymCoLXRI5 +srLsWk2Jwtp9meW8jhkoAi5xUKzLiYIhEohIX3eEEA0O0wuK0fzcMB7IbyTYYazawUKmUXZ94OLu +Fmb-UaAEvU-9U4O3DNfbDN2ELxUHmWaqNqpGl1IV0ZxGrKNZi9Rga9-_vfVGcoVMD7vZOhiZddc9 +WRlom3tQZRx2Sm42baNH8wS34J0KuUYPcjQ-1_GEJxcH0hv6hzSm4is7mUdnyB95g1UohKdQOfaY +tOdHlXbu2zG6SyPaYyQFfQbMPwBn-hx_7bYj9Px-EhYeMpBIP8X98jkd3BlWY4sdWqxsQfAb5pml +cnDRynHag2XxLqttAWSwru_owfeXzmYsPD-PINRu-Csjzlbdhq73amTFN-U8mYA09dlCck2fW8qo +mAXLkVlboVaPuem6WvfSd93ZinsB5Wi5RX6RQxeHeo88cWrJ11Au14J8xFlurcZwdSjO4dsnZj_D +ry0uKWsyNoLogBuDansiNGGO8-1qsyRxVp3zbxOMQmPouN6l0ZfxQdACqX8_4HTD7NMNMnLYjPjC +4YfOUx4pQMdjzno05vuF5zY-UQ3SN7HkmXsF6tVJdt15cmtLFetD5LTbvdRr1eeHWuwD4-aJQx4T +SdOLQ3zHeMnNFsxR_xKsu4AGjcC2-TpGixmA1kJtYBm1WIGoxQ6N4rneEo-82yvKwYst9-DJcV6x +xy1dpJqtx3I7M6DqPVURomeh2czO6UMRPVIQ1ltj4E27_FWFsWC38ZyR4nFimovFLJNCzy2k
\ No newline at end of file |