diff options
Diffstat (limited to 'cadi')
87 files changed, 5720 insertions, 1336 deletions
diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java index 37fb859e..e586d991 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java @@ -71,7 +71,6 @@ public class AAFPermission implements Permission { * If you want a simple field comparison, it is faster without REGEX */ public boolean match(Permission p) { - boolean rv; String aafType; String aafInstance; String aafAction; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java index 4f60edaf..e7e3ef35 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java @@ -79,15 +79,16 @@ public class AAFLocator extends AbsAAFLocator<BasicTrans> { int slash = aaf_locator_host.lastIndexOf("//"); host = aaf_locator_host.substring(slash+2); } - client = new HClient(ss, new URI( - locatorURI.getScheme(), - locatorURI.getUserInfo(), - host, - locatorURI.getPort(), - "/locate/"+name + '/' + version, - null, - null - ), connectTimeout); + URI uri = new URI( + locatorURI.getScheme(), + locatorURI.getUserInfo(), + host, + locatorURI.getPort(), + "/locate/"+name + '/' + version, + null, + null + ); + client = createClient(ss, uri, connectTimeout); } else { client = new HClient(ss, locatorURI, connectTimeout); } @@ -129,4 +130,8 @@ public class AAFLocator extends AbsAAFLocator<BasicTrans> { protected URI getURI() { return client.getURI(); } + + protected HClient createClient(SecuritySetter<HttpURLConnection> ss, URI uri, int connectTimeout) throws LocatorException { + return new HClient(ss, uri, connectTimeout); + } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java index 41f237d6..84d23655 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java @@ -59,6 +59,8 @@ import aaf.v2_0.Perms; * */ public class AAFLurPerm extends AbsAAFLur<AAFPermission> { + private static final String ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR = "org.osaaf.cadi.oauth.OAuth2Lur"; + /** * Need to be able to transmutate a Principal into either ATTUID or MechID, which are the only ones accepted at this * point by AAF. There is no "domain", aka, no "@att.com" in "ab1234@att.com". @@ -90,7 +92,7 @@ public class AAFLurPerm extends AbsAAFLur<AAFPermission> { Constructor<?> tmconst = tmcls.getConstructor(AAFCon.class,String.class); Object tokMangr = tmconst.newInstance(con,oauth2_url); @SuppressWarnings("unchecked") - Class<Lur> oa2cls = (Class<Lur>)Config.loadClass(access,"org.osaaf.cadi.oauth.OAuth2Lur"); + Class<Lur> oa2cls = (Class<Lur>)Config.loadClass(access,ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR); Constructor<Lur> oa2const = oa2cls.getConstructor(tmcls); Lur oa2 = oa2const.newInstance(tokMangr); setPreemptiveLur(oa2); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java index 074b704b..2094948a 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java @@ -7,9 +7,9 @@ * 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. @@ -41,10 +41,10 @@ public class AAFTrustChecker implements TrustChecker { private Lur lur; /** - * + * * Instance will be replaced by Identity - * @param lur - * + * @param lur + * * @param tag * @param perm */ @@ -87,28 +87,30 @@ public class AAFTrustChecker implements TrustChecker { @Override public TafResp mayTrust(TafResp tresp, HttpServletRequest req) { String user_info = req.getHeader(tag); - if(user_info !=null ) { - String[] info = Split.split(',', user_info); - if(info.length>0) { - String[] flds = Split.splitTrim(':',info[0]); - if(flds.length>3 && "AS".equals(flds[3])) { // is it set for "AS" - String pn = tresp.getPrincipal().getName(); - if(pn.equals(id) // We do trust our own App Components: if a trust entry is made with self, always accept - || lur.fish(tresp.getPrincipal(), perm)) { // Have Perm set by Config.CADI_TRUST_PERM - return new TrustTafResp(tresp, - new TrustPrincipal(tresp.getPrincipal(), flds[0]), - " " + flds[0] + " validated using " + flds[2] + " by " + flds[1] + ',' - ); - } else if(pn.equals(flds[0])) { // Ignore if same identity - return tresp; - } else { - return new TrustNotTafResp(tresp, tresp.getPrincipal().getName() + " requested trust as " - + flds[0] + ", but does not have Authorization"); - } - } - } + if (user_info == null) { + return tresp; + } + + String[] info = Split.split(',', user_info); + String[] flds = Split.splitTrim(':', info[0]); + if (flds.length < 4) { + return tresp; + } + if (!("AS".equals(flds[3]))) { // is it set for "AS" + return tresp; + } + + String principalName = tresp.getPrincipal().getName(); + if(principalName.equals(id) // We do trust our own App Components: if a trust entry is made with self, always accept + || lur.fish(tresp.getPrincipal(), perm)) { // Have Perm set by Config.CADI_TRUST_PERM + String desc = " " + flds[0] + " validated using " + flds[2] + " by " + flds[1] + ','; + return new TrustTafResp(tresp, new TrustPrincipal(tresp.getPrincipal(), flds[0]), desc); + } else if(principalName.equals(flds[0])) { // Ignore if same identity + return tresp; + } else { + String desc = tresp.getPrincipal().getName() + " requested trust as " + flds[0] + ", but does not have Authorization"; + return new TrustNotTafResp(tresp, desc); } - return tresp; } }
\ No newline at end of file diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java index ab0f595c..fc297606 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java @@ -82,21 +82,8 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> this.version = Config.AAF_DEFAULT_VERSION; } else { String[] split = Split.split(':', name); - - switch(split.length) { - case 1: - this.name = split[0]; - this.version = Config.AAF_DEFAULT_VERSION; - break; - case 0: - this.name = name; - this.version = Config.AAF_DEFAULT_VERSION; - break; - default: - this.version = split[1]; - this.name = split[0]; - - } + this.name = split[0]; + this.version = (split.length > 1) ? split[1] : Config.AAF_DEFAULT_VERSION; } } @@ -138,13 +125,11 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> if(key.startsWith("http")) { if(name!=null) { if(locatorCreator != null) { - if(name!=null) { - AbsAAFLocator<?> aal = locatorCreator.create(name, version); - if(pathInfo!=null) { - aal.setPathInfo(pathInfo); - } - return aal; + AbsAAFLocator<?> aal = locatorCreator.create(name, version); + if(pathInfo!=null) { + aal.setPathInfo(pathInfo); } + return aal; } } else { return new PropertyLocator(key); @@ -491,7 +476,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> try { return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment); } catch (URISyntaxException e) { - throw new LocatorException("Error coping URL"); + throw new LocatorException("Error copying URL"); } } return rv; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/cm/PlaceArtifactInKeystore.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/cm/PlaceArtifactInKeystore.java index 9360e02f..2b498d4f 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/cm/PlaceArtifactInKeystore.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/cm/PlaceArtifactInKeystore.java @@ -125,17 +125,16 @@ public class PlaceArtifactInKeystore extends ArtifactDir { char[] truststorePassArray = trustStorePass.toCharArray(); jks.load(null,truststorePassArray); // load in - // Add Trusted Certificates + // Add Trusted Certificates, but PKCS12 doesn't support for(int i=0; i<trustCAs.length;++i) { jks.setCertificateEntry("ca_" + arti.getCa() + '_' + i, trustCAs[i]); } // Write out write(fks,Chmod.to644,jks,truststorePassArray); - + return true; } catch (Exception e) { throw new CadiException(e); } - return false; } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java index 7131b607..8b98f5bf 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java @@ -113,11 +113,7 @@ public class Persisting<T> implements Persistable<T> { //TODO other elements to add here... // Ideas: Is it valid? // if not, How many times has it been checked in the last minute - if(expired()) { - return true; - } else { - return false; - } + return expired(); } @Override diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java index 0241fe5d..8948bc3c 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java @@ -7,9 +7,9 @@ * 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. @@ -41,106 +41,87 @@ import org.onap.aaf.cadi.util.MyConsole; import org.onap.aaf.cadi.util.SubStandardConsole; import org.onap.aaf.cadi.util.TheConsole; - public class AAFSSO { - public static final MyConsole cons = TheConsole.implemented()?new TheConsole():new SubStandardConsole(); - + public static final MyConsole cons = TheConsole.implemented() ? new TheConsole() : new SubStandardConsole(); + private static final int EIGHT_HOURS = 8 * 60 * 60 * 1000; + private Properties diskprops = null; // use for temp storing User/Password on disk - private File dot_aaf = null, sso=null; // instantiated, if ever, with diskprops - - boolean removeSSO=false; + private File dot_aaf = null; + private File sso = null; // instantiated, if ever, with diskprops + + boolean removeSSO = false; boolean loginOnly = false; + boolean doExit = true; private PropAccess access; private StringBuilder err; - private String user,encrypted_pass; + private String user; + private String encrypted_pass; private boolean use_X509; - private PrintStream os, stdout=null,stderr=null; + private PrintStream os; private Method close; public AAFSSO(String[] args) throws IOException, CadiException { - List<String> larg = new ArrayList<String>(args.length); - - // Cover for bash's need to escape *.. (\\*) - // also, remove SSO if required - for (int i = 0; i < args.length; ++i) { - if ("\\*".equals(args[i])) { - args[i] = "*"; - } - - if("-logout".equalsIgnoreCase(args[i])) { - removeSSO=true; - } else if("-login".equalsIgnoreCase(args[i])) { - loginOnly = true; - } else { - larg.add(args[i]); - } - } - - String[] nargs = new String[larg.size()]; - larg.toArray(nargs); + String[] nargs = parseArgs(args); - dot_aaf = new File(System.getProperty("user.home")+"/.aaf"); - if(!dot_aaf.exists()) { + dot_aaf = new File(System.getProperty("user.home") + "/.aaf"); + if (!dot_aaf.exists()) { dot_aaf.mkdirs(); } - File f = new File(dot_aaf,"sso.out"); - os = new PrintStream(new FileOutputStream(f,true)); - stdout = System.out; - stderr = System.err; + File f = new File(dot_aaf, "sso.out"); + os = new PrintStream(new FileOutputStream(f, true)); System.setOut(os); System.setErr(os); - access = new PropAccess(os,nargs); + access = new PropAccess(os, nargs); Config.setDefaultRealm(access); user = access.getProperty(Config.AAF_APPID); encrypted_pass = access.getProperty(Config.AAF_APPPASS); - - File dot_aaf_kf = new File(dot_aaf,"keyfile"); - - sso = new File(dot_aaf,"sso.props"); - if(removeSSO) { - if(dot_aaf_kf.exists()) { - dot_aaf_kf.setWritable(true,true); + + File dot_aaf_kf = new File(dot_aaf, "keyfile"); + + sso = new File(dot_aaf, "sso.props"); + if (removeSSO) { + if (dot_aaf_kf.exists()) { + dot_aaf_kf.setWritable(true, true); dot_aaf_kf.delete(); } - if(sso.exists()) { + if (sso.exists()) { sso.delete(); } System.out.println("AAF SSO information removed"); - System.exit(0); + if (doExit) { + System.exit(0); + } } - - if(!dot_aaf_kf.exists()) { + + if (!dot_aaf_kf.exists()) { FileOutputStream fos = new FileOutputStream(dot_aaf_kf); try { fos.write(Symm.keygen()); - dot_aaf_kf.setExecutable(false,false); - dot_aaf_kf.setWritable(false,false); - dot_aaf_kf.setReadable(false,false); - dot_aaf_kf.setReadable(true, true); + setReadonly(dot_aaf_kf); } finally { fos.close(); } } String keyfile = access.getProperty(Config.CADI_KEYFILE); // in case it's CertificateMan props - if(keyfile==null) { + if (keyfile == null) { access.setProperty(Config.CADI_KEYFILE, dot_aaf_kf.getAbsolutePath()); } - + String alias = access.getProperty(Config.CADI_ALIAS); - if(user==null && alias!=null && access.getProperty(Config.CADI_KEYSTORE_PASSWORD)!=null) { + if ((user == null) && (alias != null) && (access.getProperty(Config.CADI_KEYSTORE_PASSWORD) != null)) { user = alias; access.setProperty(Config.AAF_APPID, user); use_X509 = true; } else { use_X509 = false; Symm decryptor = Symm.obtain(dot_aaf_kf); - if (user==null) { - if(sso.exists() && sso.lastModified()>System.currentTimeMillis()-(8*60*60*1000 /* 8 hours */)) { + if (user == null) { + if (sso.exists() && (sso.lastModified() > (System.currentTimeMillis() - EIGHT_HOURS))) { String cm_url = access.getProperty(Config.CM_URL); // SSO might overwrite... FileInputStream fos = new FileInputStream(sso); try { @@ -148,9 +129,9 @@ public class AAFSSO { user = access.getProperty(Config.AAF_APPID); encrypted_pass = access.getProperty(Config.AAF_APPPASS); // decrypt with .aaf, and re-encrypt with regular Keyfile - access.setProperty(Config.AAF_APPPASS, + access.setProperty(Config.AAF_APPPASS, access.encrypt(decryptor.depass(encrypted_pass))); - if(cm_url!=null) { //Command line CM_URL Overwrites ssofile. + if (cm_url != null) { //Command line CM_URL Overwrites ssofile. access.setProperty(Config.CM_URL, cm_url); } } finally { @@ -160,22 +141,22 @@ public class AAFSSO { diskprops = new Properties(); String realm = Config.getDefaultRealm(); // Turn on Console Sysout - System.setOut(stdout); - user=cons.readLine("aaf_id(%s@%s): ",System.getProperty("user.name"),realm); - if(user==null) { - user = System.getProperty("user.name")+'@'+realm; - } else if(user.length()==0) { // - user = System.getProperty("user.name")+'@' + realm; - } else if(user.indexOf('@')<0 && realm!=null) { - user = user+'@'+realm; + System.setOut(System.out); + user = cons.readLine("aaf_id(%s@%s): ", System.getProperty("user.name"), realm); + if (user == null) { + user = System.getProperty("user.name") + '@' + realm; + } else if (user.length() == 0) { // + user = System.getProperty("user.name") + '@' + realm; + } else if ((user.indexOf('@') < 0) && (realm != null)) { + user = user + '@' + realm; } - access.setProperty(Config.AAF_APPID,user); - diskprops.setProperty(Config.AAF_APPID,user); + access.setProperty(Config.AAF_APPID, user); + diskprops.setProperty(Config.AAF_APPID, user); encrypted_pass = new String(cons.readPassword("aaf_password: ")); System.setOut(os); - encrypted_pass = Symm.ENC+decryptor.enpass(encrypted_pass); - access.setProperty(Config.AAF_APPPASS,encrypted_pass); - diskprops.setProperty(Config.AAF_APPPASS,encrypted_pass); + encrypted_pass = Symm.ENC + decryptor.enpass(encrypted_pass); + access.setProperty(Config.AAF_APPPASS, encrypted_pass); + diskprops.setProperty(Config.AAF_APPPASS, encrypted_pass); diskprops.setProperty(Config.CADI_KEYFILE, access.getProperty(Config.CADI_KEYFILE)); } } @@ -183,8 +164,8 @@ public class AAFSSO { if (user == null) { err = new StringBuilder("Add -D" + Config.AAF_APPID + "=<id> "); } - - if (encrypted_pass == null && alias==null) { + + if (encrypted_pass == null && alias == null) { if (err == null) { err = new StringBuilder(); } else { @@ -193,42 +174,35 @@ public class AAFSSO { err.append("-D" + Config.AAF_APPPASS + "=<passwd> "); } } - + public void setLogDefault() { - access.setLogLevel(PropAccess.DEFAULT); - if(stdout!=null) { - System.setOut(stdout); - } + this.setLogDefault(PropAccess.DEFAULT); } public void setStdErrDefault() { access.setLogLevel(PropAccess.DEFAULT); - if(stderr!=null) { - System.setErr(stderr); - } + System.setErr(System.err); } public void setLogDefault(Level level) { access.setLogLevel(level); - if(stdout!=null) { - System.setOut(stdout); - } + System.setOut(System.out); } - + public boolean loginOnly() { return loginOnly; } public void addProp(String key, String value) { - if(diskprops!=null) { + if (diskprops != null) { diskprops.setProperty(key, value); } } - + public void writeFiles() throws IOException { - // Store Creds, if they work - if(diskprops!=null) { - if(!dot_aaf.exists()) { + // Store Creds, if they work + if (diskprops != null) { + if (!dot_aaf.exists()) { dot_aaf.mkdirs(); } FileOutputStream fos = new FileOutputStream(sso); @@ -236,18 +210,12 @@ public class AAFSSO { diskprops.store(fos, "AAF Single Signon"); } finally { fos.close(); - sso.setWritable(false,false); - sso.setExecutable(false,false); - sso.setReadable(false,false); - sso.setReadable(true,true); + setReadonly(sso); } } - if(sso!=null) { - sso.setReadable(false,false); - sso.setWritable(false,false); - sso.setExecutable(false,false); - sso.setReadable(true,true); - sso.setWritable(true,true); + if (sso != null) { + setReadonly(sso); + sso.setWritable(true, true); } } @@ -258,21 +226,21 @@ public class AAFSSO { public StringBuilder err() { return err; } - + public String user() { return user; } - + public String enc_pass() { return encrypted_pass; } - + public boolean useX509() { return use_X509; } - + public void close() { - if(close!=null) { + if (close != null) { try { close.invoke(null); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { @@ -281,4 +249,37 @@ public class AAFSSO { close = null; } } + + private String[] parseArgs(String[] args) + { + List<String> larg = new ArrayList<String>(args.length); + + // Cover for bash's need to escape *.. (\\*) + // also, remove SSO if required + for (int i = 0; i < args.length; ++i) { + if ("\\*".equals(args[i])) { + args[i] = "*"; + } + + if ("-logout".equalsIgnoreCase(args[i])) { + removeSSO = true; + } else if ("-login".equalsIgnoreCase(args[i])) { + loginOnly = true; + } else if ("-noexit".equalsIgnoreCase(args[i])) { + doExit = false; + } else { + larg.add(args[i]); + } + } + String[] nargs = new String[larg.size()]; + larg.toArray(nargs); + return nargs; + } + + private void setReadonly(File file) { + file.setExecutable(false, false); + file.setWritable(false, false); + file.setReadable(false, false); + file.setReadable(true, true); + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/cert/test/JU_AAFListedCertIdentity.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/cert/test/JU_AAFListedCertIdentity.java new file mode 100644 index 00000000..f2d91b02 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/cert/test/JU_AAFListedCertIdentity.java @@ -0,0 +1,177 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.aaf.cert.test; + +import static org.mockito.Mockito.*; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import org.junit.*; +import org.mockito.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.aaf.cert.AAFListedCertIdentity; +import org.onap.aaf.cadi.aaf.v2_0.AAFCon; +import org.onap.aaf.cadi.client.Future; +import org.onap.aaf.cadi.client.Rcli; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.util.Chrono; +import org.onap.aaf.misc.rosetta.env.RosettaDF; + +import aaf.v2_0.Certs; +import aaf.v2_0.Certs.Cert; +import aaf.v2_0.Users; +import aaf.v2_0.Users.User; + +public class JU_AAFListedCertIdentity { + + @Mock private AAFCon<?> conMock; + @Mock private Rcli<Object> rcliMock; + @Mock private RosettaDF<Users> userDFMock; + @Mock private RosettaDF<Certs> certDFMock; + @Mock private Future<Users> futureUsersMock; + @Mock private Future<Certs> futureCertsMock; + + @Mock private Users usersMock; + @Mock private User userMock1; + @Mock private User userMock2; + @Mock private User userMock3; + + @Mock private Certs certsMock; + @Mock private Cert certMock1; + @Mock private Cert certMock2; + @Mock private Cert certMock3; + + @Mock private HttpServletRequest reqMock; + @Mock private X509Certificate x509Mock; + + private List<User> usersList; + private List<Cert> certsList; + + private PropAccess access; + + private ByteArrayOutputStream outStream; + + private static final String USERS = "user1,user2,user3"; + private static final String ID = "id"; + private static final String FINGERPRINT = "fingerprint"; + + private static final byte[] certBytes = "certificate".getBytes(); + + @Before + public void setup() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + MockitoAnnotations.initMocks(this); + + certsList = new ArrayList<>(); + certsList.add(certMock1); + certsList.add(certMock2); + certsList.add(certMock3); + + usersList = new ArrayList<>(); + usersList.add(userMock1); + usersList.add(userMock2); + usersList.add(userMock3); + + outStream = new ByteArrayOutputStream(); + access = new PropAccess(new PrintStream(outStream), new String[0]); + outStream.reset(); + access.setProperty(Config.AAF_CERT_IDS, USERS); + setFinal(conMock, conMock.getClass().getField("usersDF"), userDFMock); + setFinal(conMock, conMock.getClass().getField("certsDF"), certDFMock); + setFinal(conMock, conMock.getClass().getField("access"), access); + } + + @Test + public void test() throws APIException, CadiException, CertificateException { + doReturn(rcliMock).when(conMock).client(Config.AAF_DEFAULT_VERSION); + when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/tguard/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock); + when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/basicAuth/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock); + when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/csp/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock); + + when(futureUsersMock.get(5000)).thenReturn(true); + futureUsersMock.value = usersMock; + when(usersMock.getUser()).thenReturn(usersList); + + when(rcliMock.read("/authn/cert/id/user1", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock); + when(rcliMock.read("/authn/cert/id/user2", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock); + when(rcliMock.read("/authn/cert/id/user3", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock); + + when(futureCertsMock.get(5000)).thenReturn(true); + futureCertsMock.value = certsMock; + when(certsMock.getCert()).thenReturn(certsList); + + when(userMock1.getId()).thenReturn("user1"); + when(userMock2.getId()).thenReturn("user2"); + when(userMock3.getId()).thenReturn("user3"); + + prepareCert(certMock1); + prepareCert(certMock2); + prepareCert(certMock3); + + AAFListedCertIdentity certID = new AAFListedCertIdentity(access, conMock); + + when(x509Mock.getEncoded()).thenReturn(certBytes); + certID.identity(reqMock, null, null); + certID.identity(reqMock, null, certBytes); + certID.identity(reqMock, x509Mock, null); + certID.identity(reqMock, x509Mock, certBytes); + + Set<String> hashSetOfUsers = AAFListedCertIdentity.trusted("basicAuth"); + assertThat(hashSetOfUsers.contains("user1"), is(true)); + assertThat(hashSetOfUsers.contains("user2"), is(true)); + assertThat(hashSetOfUsers.contains("user3"), is(true)); + + } + + private void setFinal(Object object, Field field, Object newValue) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + field.setAccessible(true); + + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & Modifier.FINAL); + + field.set(object, newValue); + } + + private void prepareCert(Cert cert) { + Date date = new Date(); + when(cert.getExpires()).thenReturn(Chrono.timeStamp(new Date(date.getTime() + (60 * 60 * 24)))); + when(cert.getId()).thenReturn(ID); + when(cert.getFingerprint()).thenReturn(FINGERPRINT.getBytes()); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertMarshal.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertMarshal.java new file mode 100644 index 00000000..560014d1 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertMarshal.java @@ -0,0 +1,99 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.aaf.marshal.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import javax.xml.datatype.XMLGregorianCalendar; + +import org.junit.*; + +import org.onap.aaf.cadi.aaf.marshal.CertMarshal; +import org.onap.aaf.misc.env.util.Chrono; +import org.onap.aaf.misc.rosetta.OutRaw; +import org.onap.aaf.misc.rosetta.ParseException; +import org.onap.aaf.misc.rosetta.marshal.DataWriter; + +import aaf.v2_0.Certs.Cert; + +public class JU_CertMarshal { + + private static final String fingerprint = "fingerprint"; + private static final String id = "id"; + private static final String x500 = "x500"; + + private String fingerprintAsString; + + private XMLGregorianCalendar expires; + + private ByteArrayOutputStream outStream; + + @Before + public void setup() { + expires = Chrono.timeStamp(); + outStream = new ByteArrayOutputStream(); + StringBuilder sb = new StringBuilder(); + DataWriter.HEX_BINARY.write(fingerprint.getBytes(), sb); + fingerprintAsString = sb.toString(); + } + + @Test + public void test() throws ParseException, IOException { + Cert cert = setupCert(); + CertMarshal cm = new CertMarshal(); + OutRaw raw = new OutRaw(); + + raw.extract(cert, new PrintStream(outStream), cm); + + String[] output = outStream.toString().split("\n"); + + String[] expected = new String[] { + "{ - ", + ", - fingerprint : \"" + fingerprintAsString + "\"", + ", - id : \"" + id + "\"", + ", - x500 : \"" + x500 + "\"", + ", - expires : \"" + Chrono.dateTime(expires) + "\"", + "} - ", + }; + + assertThat(output.length, is(expected.length)); + + for (int i = 0; i < output.length; i++) { + assertThat(output[i], is(expected[i])); + } + } + + private Cert setupCert() { + Cert cert = new Cert(); + cert.setId(id); + cert.setX500(x500); + cert.setExpires(expires); + cert.setFingerprint(fingerprint.getBytes()); + return cert; + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertsMarshal.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertsMarshal.java new file mode 100644 index 00000000..6598fbe4 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/marshal/test/JU_CertsMarshal.java @@ -0,0 +1,118 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.aaf.marshal.test; + +import org.junit.*; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; + +import javax.xml.datatype.XMLGregorianCalendar; +import org.onap.aaf.cadi.aaf.marshal.CertsMarshal; +import org.onap.aaf.misc.env.util.Chrono; +import org.onap.aaf.misc.rosetta.OutRaw; +import org.onap.aaf.misc.rosetta.ParseException; +import org.onap.aaf.misc.rosetta.marshal.DataWriter; + +import aaf.v2_0.Certs; +import aaf.v2_0.Certs.Cert; + +public class JU_CertsMarshal { + + private static final String fingerprint = "fingerprint"; + private static final String id = "id"; + private static final String x500 = "x500"; + + private String fingerprintAsString; + + private XMLGregorianCalendar expires; + + private ByteArrayOutputStream outStream; + + @Before + public void setup() { + expires = Chrono.timeStamp(); + outStream = new ByteArrayOutputStream(); + StringBuilder sb = new StringBuilder(); + DataWriter.HEX_BINARY.write(fingerprint.getBytes(), sb); + fingerprintAsString = sb.toString(); + } + + @Test + public void test() throws ParseException, IOException { + CertsStub certs = new CertsStub(); + CertsMarshal cm = new CertsMarshal(); + OutRaw raw = new OutRaw(); + + raw.extract(certs, new PrintStream(outStream), cm); + String[] output = outStream.toString().split("\n"); + + String[] expected = new String[] { + "{ - ", + "[ - cert", + "{ - ", + ", - fingerprint : \"" + fingerprintAsString + "\"", + ", - id : \"" + id + "\"", + ", - x500 : \"" + x500 + "\"", + ", - expires : \"" + Chrono.dateTime(expires) + "\"", + "} - ", + ", - ", + "{ - ", + ", - fingerprint : \"" + fingerprintAsString + "\"", + ", - id : \"" + id + "\"", + ", - x500 : \"" + x500 + "\"", + ", - expires : \"" + Chrono.dateTime(expires) + "\"", + "} - ", + "] - ", + "} - ", + }; + + assertThat(output.length, is(expected.length)); + + for (int i = 0; i < output.length; i++) { + assertThat(output[i], is(expected[i])); + } + } + + private Cert setupCert() { + Cert cert = new Cert(); + cert.setId(id); + cert.setX500(x500); + cert.setExpires(expires); + cert.setFingerprint(fingerprint.getBytes()); + return cert; + } + + private class CertsStub extends Certs { + public CertsStub() { + cert = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + cert.add(setupCert()); + } + } + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFLocator.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFLocator.java index 4c5af016..5388f75b 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFLocator.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFLocator.java @@ -21,59 +21,103 @@ package org.onap.aaf.cadi.aaf.v2_0.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.ByteArrayOutputStream; +import java.io.PrintStream; +import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.URI; -import static org.junit.Assert.*; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; import org.onap.aaf.cadi.PropAccess; -import org.onap.aaf.cadi.Locator.Item; +import org.onap.aaf.cadi.SecuritySetter; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.LocatorException; import org.onap.aaf.cadi.aaf.v2_0.AAFLocator; import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator; +import org.onap.aaf.cadi.client.Future; import org.onap.aaf.cadi.config.Config; import org.onap.aaf.cadi.config.SecurityInfoC; +import org.onap.aaf.cadi.http.HClient; +import org.onap.aaf.misc.env.Data.TYPE; import org.onap.aaf.misc.env.impl.BasicTrans; -import org.onap.aaf.misc.rosetta.env.RosettaEnv; +import org.onap.aaf.misc.rosetta.env.RosettaDF; -public class JU_AAFLocator { +import locate.v1_0.Endpoint; +import locate.v1_0.Endpoints; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } +public class JU_AAFLocator { + + @Mock private HClient clientMock; + @Mock private Future<Endpoints> futureMock; + @Mock private Endpoints endpointsMock; + + private PropAccess access; + + private ByteArrayOutputStream errStream; + + private static final String uriString = "https://example.com"; @Before public void setUp() throws Exception { - } + MockitoAnnotations.initMocks(this); + + doReturn(futureMock).when(clientMock).futureRead((RosettaDF<?>)any(), eq(TYPE.JSON)); + when(clientMock.timeout()).thenReturn(1); + when(clientMock.getURI()).thenReturn(new URI(uriString)); + when(futureMock.get(1)).thenReturn(true); + + futureMock.value = endpointsMock; + List<Endpoint> endpoints = new ArrayList<>(); + endpoints.add(new Endpoint()); + when(endpointsMock.getEndpoint()).thenReturn(endpoints); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + + errStream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errStream)); + } + @After - public void tearDown() throws Exception { + public void tearDown() { + System.setErr(System.err); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + Field field = SecurityInfoC.class.getDeclaredField("sicMap"); + field.setAccessible(true); + field.set(null, new HashMap<Class<?>,SecurityInfoC<?>>()); } @Test - public void test() { - // TODO: Ian [JUnit] This fails because these files don't exist - assertTrue(true); - // try { - // PropAccess propAccess = new PropAccess("cadi_prop_files=/opt/app/aaf/common/com.att.aaf.common.props:/opt/app/aaf/common/com.att.aaf.props"); - // SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(propAccess, HttpURLConnection.class); - // String alu = propAccess.getProperty(Config.AAF_LOCATE_URL,"https://mithrilcsp.sbc.com:8095/locate"); - // URI locatorURI = new URI(alu+"/com.att.aaf.service/2.0"); - // AbsAAFLocator<BasicTrans> al = new AAFLocator(si, locatorURI); - // Assert.assertTrue(al.refresh()); - // Item i = al.first(); - // i = al.next(i); - // i = al.best(); - // } catch (Exception e) { - // Assert.fail(); - // } + public void test() throws CadiException, URISyntaxException, LocatorException { + access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat + access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon + SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(access, HttpURLConnection.class); + String alu = access.getProperty(Config.AAF_LOCATE_URL,"https://mithrilcsp.sbc.com:8095/locate"); + URI locatorURI = new URI(alu+"/com.att.aaf.service/2.0"); + AbsAAFLocator<BasicTrans> al = new AAFLocator(si, locatorURI) { + @Override + protected HClient createClient(SecuritySetter<HttpURLConnection> ss, URI uri, int connectTimeout) throws LocatorException { + return clientMock; + } + }; + assertThat(al.refresh(), is(true)); + when(futureMock.get(1)).thenReturn(false); + assertThat(al.refresh(), is(false)); + String errorMessage = errStream.toString().split(": ", 2)[1]; + assertThat(errorMessage, is("Error reading location information from " + uriString + ": 0 null\n \n")); } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFTrustChecker.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFTrustChecker.java new file mode 100644 index 00000000..1e469eca --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AAFTrustChecker.java @@ -0,0 +1,130 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.aaf.v2_0.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.aaf.cadi.Lur; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.aaf.v2_0.AAFTrustChecker; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.principal.TaggedPrincipal; +import org.onap.aaf.cadi.taf.TafResp; +import org.onap.aaf.cadi.taf.TrustNotTafResp; +import org.onap.aaf.cadi.taf.TrustTafResp; +import org.onap.aaf.misc.env.Env; + +public class JU_AAFTrustChecker { + + private final static String type = "type"; + private final static String instance = "instance"; + private final static String action = "action"; + private final static String key = type + '|' + instance + '|' + action; + private final static String name = "name"; + private final static String otherName = "otherName"; + + private PropAccess access; + + @Mock private Env envMock; + @Mock private TafResp trespMock; + @Mock private HttpServletRequest reqMock; + @Mock private TaggedPrincipal tpMock; + @Mock private Lur lurMock; + @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() { + AAFTrustChecker trustChecker; + + // coverage calls + trustChecker = new AAFTrustChecker(access); + trustChecker = new AAFTrustChecker(envMock); + + access.setProperty(Config.CADI_TRUST_PERM, "example"); + when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn("example"); + trustChecker = new AAFTrustChecker(access); + trustChecker = new AAFTrustChecker(envMock); + + access.setProperty(Config.CADI_TRUST_PERM, key); + when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn(key); + trustChecker = new AAFTrustChecker(access); + trustChecker = new AAFTrustChecker(envMock); + + trustChecker.setLur(lurMock); + + assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); + + when(reqMock.getHeader(null)).thenReturn("comma,comma,comma"); + assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); + + when(reqMock.getHeader(null)).thenReturn("colon:colon:colon:colon,comma,comma"); + assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); + + when(reqMock.getHeader(null)).thenReturn("colon:colon:colon:AS,comma,comma"); + when(trespMock.getPrincipal()).thenReturn(tpMock); + when(tpMock.getName()).thenReturn(name); + when(lurMock.fish(princMock, null)).thenReturn(true); + TafResp tntResp = trustChecker.mayTrust(trespMock, reqMock); + + assertThat(tntResp instanceof TrustNotTafResp, is(true)); + assertThat(tntResp.toString(), is("name requested trust as colon, but does not have Authorization")); + + when(reqMock.getHeader(null)).thenReturn(name + ":colon:colon:AS,comma,comma"); + assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock)); + + when(envMock.getProperty(Config.CADI_ALIAS, null)).thenReturn(name); + when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn(null); + trustChecker = new AAFTrustChecker(envMock); + trustChecker.setLur(lurMock); + + when(trespMock.getPrincipal()).thenReturn(princMock); + when(princMock.getName()).thenReturn(otherName); + when(lurMock.fish(princMock, null)).thenReturn(true); + TafResp ttResp = trustChecker.mayTrust(trespMock, reqMock); + assertThat(ttResp instanceof TrustTafResp, is(true)); + assertThat(ttResp.toString(), is(name + " by trust of " + name + " validated using colon by colon, null")); + + when(princMock.getName()).thenReturn(name); + ttResp = trustChecker.mayTrust(trespMock, reqMock); + assertThat(ttResp instanceof TrustTafResp, is(true)); + assertThat(ttResp.toString(), is(name + " by trust of " + name + " validated using colon by colon, null")); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AbsAAFLocator.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AbsAAFLocator.java new file mode 100644 index 00000000..e9c74cbf --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/test/JU_AbsAAFLocator.java @@ -0,0 +1,193 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.aaf.v2_0.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; +import org.junit.*; +import org.mockito.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.URI; +import java.net.URISyntaxException; + +import org.onap.aaf.cadi.Access; +import org.onap.aaf.cadi.Locator.Item; +import org.onap.aaf.cadi.LocatorException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator; +import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator.LocatorCreator; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.misc.env.impl.BasicTrans; + +public class JU_AbsAAFLocator { + + @Mock private LocatorCreator locatorCreatorMock; + + private PropAccess access; + private URI uri; + + private static final String uriString = "example.com"; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat + access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon + + uri = new URI(uriString); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + AbsAAFLocator.setCreator(null); + } + + @Test + public void test() throws LocatorException { + AAFLocatorStub loc; + + // Test with http + loc = new AAFLocatorStub(access, "httpname"); + assertThat(loc.getName(), is("httpname")); + assertThat(loc.getVersion(), is(Config.AAF_DEFAULT_VERSION)); + assertThat(loc.toString(), is("AAFLocator for " + "httpname" + " on " + loc.getURI())); + + loc = new AAFLocatorStub(access, "name"); + assertThat(loc.getName(), is("name")); + assertThat(loc.getVersion(), is(Config.AAF_DEFAULT_VERSION)); + loc = new AAFLocatorStub(access, "name:v2.0"); + assertThat(loc.getName(), is("name")); + assertThat(loc.getVersion(), is("v2.0")); + } + + @Test + public void createTest() throws LocatorException { + AbsAAFLocator.setCreator(locatorCreatorMock); + + assertThat(AbsAAFLocator.create("nonsense"), is(nullValue())); + assertThat(AbsAAFLocator.create("nonsense/locate"), is(nullValue())); + assertThat(AbsAAFLocator.create("nonsense/locate/"), is(nullValue())); + assertThat(AbsAAFLocator.create("nonsense/locate//"), is(nullValue())); + assertThat(AbsAAFLocator.create("nonsense/locate/name:v2.0"), is(nullValue())); + + assertThat(AbsAAFLocator.create("http/locate/name:v2.0"), is(nullValue())); + + doReturn(mock(AbsAAFLocator.class)).when(locatorCreatorMock).create(anyString(), anyString()); + assertThat(AbsAAFLocator.create("http/locate/name:v2.0/path"), is(not(nullValue()))); + + AbsAAFLocator.setCreator(null); + assertThat(AbsAAFLocator.create("http/locate/name:v2.0"), is(nullValue())); + + assertThat(AbsAAFLocator.create("http"), is(not(nullValue()))); + + AbsAAFLocator.setCreator(locatorCreatorMock); + assertThat(AbsAAFLocator.create("first", "second"), is(not(nullValue()))); + } + + @Test + public void nameFromLocatorURITest() throws LocatorException, URISyntaxException { + AAFLocatorStub loc = new AAFLocatorStub(access, "name:v2.0"); + assertThat(loc.getNameFromURI(new URI("example.com")), is("example.com")); + assertThat(loc.getNameFromURI(new URI("example.com/extra/stuff")), is("example.com/extra/stuff")); + assertThat(loc.getNameFromURI(new URI("example.com/locate/stuff")), is("stuff")); // n' stuff + } + + @Test + public void setSelfTest() throws LocatorException { + AbsAAFLocator.setCreatorSelf("host", 8000); + AbsAAFLocator.setCreator(null); + AbsAAFLocator.setCreatorSelf("host", 8000); + (new AAFLocatorStub(access, "name:v2.0")).setSelf("host", 8000); // oof + } + + @Test + public void coverage() throws LocatorException { + AAFLocatorStub loc = new AAFLocatorStub(access, "name:v2.0"); + assertThat(loc.get(null), is(nullValue())); + + try { + loc.get(mock(Item.class)); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + try { + loc.invalidate(mock(Item.class)); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + try { + loc.best(); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + assertThat(loc.first(), is(nullValue())); + + assertThat(loc.hasItems(), is(false)); + assertThat(loc.next(null), is(nullValue())); + + try { + loc.next(mock(Item.class)); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + loc.destroy(); + + + assertThat(loc.exposeGetURI(uri), is(uri)); + + assertThat(loc.setPathInfo("pathInfo"), is(not(nullValue()))); + assertThat(loc.setQuery("query"), is(not(nullValue()))); + assertThat(loc.setFragment("fragment"), is(not(nullValue()))); + + assertThat(loc.exposeGetURI(uri), is(not(uri))); + } + + + @Test(expected = LocatorException.class) + public void throwsTest() throws LocatorException { + @SuppressWarnings("unused") + AAFLocatorStub loc = new AAFLocatorStub(new PropAccess(), "name"); + } + + private class AAFLocatorStub extends AbsAAFLocator<BasicTrans> { + public AAFLocatorStub(Access access, String name) throws LocatorException { + super(access, name, 10000L); + } + @Override public boolean refresh() { return false; } + @Override protected URI getURI() { return uri; } + public String getName() { return name; } + public String getVersion() { return version; } + public String getNameFromURI(URI uri) { return nameFromLocatorURI(uri); } + public URI exposeGetURI(URI uri) throws LocatorException { return super.getURI(uri); } + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java new file mode 100644 index 00000000..d0d67e23 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java @@ -0,0 +1,171 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.cm.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.File; +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.cm.ArtifactDir; +import org.onap.aaf.cadi.util.Chmod; +import org.onap.aaf.misc.env.Trans; + +import certman.v1_0.Artifacts.Artifact; +import certman.v1_0.CertInfo; + +public class JU_ArtifactDir { + + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String dirName = "src/test/resources/artifacts"; + private static final String nsName = "org.onap.test"; + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + + private List<String> issuers; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + issuers = new ArrayList<>(); + issuers.add("issuer1"); + issuers.add("issuer2"); + } + + @After + public void tearDown() { + ArtifactDir.clear(); + } + + @AfterClass + public static void tearDownOnce() { + cleanup(); + } + + @Test + public void test() throws CadiException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { + ArtifactDirStud artiDir = new ArtifactDirStud(); + + try { + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("File Artifacts require a path\nFile Artifacts require an AAF Namespace")); + } + + when(artiMock.getDir()).thenReturn(dirName); + try { + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("File Artifacts require an AAF Namespace")); + } + + when(artiMock.getNs()).thenReturn(nsName); + when(certInfoMock.getCaIssuerDNs()).thenReturn(issuers); + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + + File writableFile = new File(dirName + '/' + nsName + "writable.txt"); + artiDir.write(writableFile, Chmod.to755, "first data point", "second data point"); + try { + artiDir.write(writableFile, Chmod.to755, (String[])null); + fail("Should've thrown an exception"); + } catch(NullPointerException e) { + } + + KeyStore ks = KeyStore.getInstance("pkcs12"); + try { + artiDir.write(writableFile, Chmod.to755, ks, luggagePassword.toCharArray()); + fail("Should've thrown an exception"); + } catch(CadiException e) { + } + + ks.load(null, null); + artiDir.write(writableFile, Chmod.to755, ks, luggagePassword.toCharArray()); + + ArtifactDirStud artiDir2 = new ArtifactDirStud(); + artiDir2.place(transMock, certInfoMock, artiMock, "machine"); + + // coverage + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + + ArtifactDir.clear(); + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + + } + + @Test(expected = CadiException.class) + public void throwsTest() throws CadiException { + ArtifactDirStud artiDir = new ArtifactDirStud(); + when(artiMock.getDir()).thenReturn(dirName); + when(artiMock.getNs()).thenReturn(nsName); + artiDir.place(transMock, certInfoMock, artiMock, "machine"); + } + + private class ArtifactDirStud extends ArtifactDir { + @Override + protected boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { + // This is only here so that we have a concrete class to test + return false; + } + + // Expose the protected methods + + public void write(File f, Chmod c, String ... data) throws IOException { + super.write(f, c, data); + } + public void write(File f, Chmod c, KeyStore ks, char[] pass ) throws IOException, CadiException { + super.write(f, c, ks, pass); + } + } + + private static void cleanup() { + File dir = new File(dirName); + if (dir.exists()) { + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CmAgent.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CmAgent.java new file mode 100644 index 00000000..34ccf57b --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_CmAgent.java @@ -0,0 +1,123 @@ +/******************************************************************************* + * ============LICENSE_START==================================================== + * * org.onap.aaf + * * =========================================================================== + * * 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.aaf.cadi.cm.test; + +import java.io.ByteArrayInputStream; +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.aaf.cadi.cm.CmAgent; + +public class JU_CmAgent { + + private static final String resourceDirString = "src/test/resources"; + private static final String aafDir = resourceDirString + "/aaf"; + + private ByteArrayInputStream inStream; + + @Before + public void setup() { + System.setProperty("user.home", aafDir); + + // Simulate user input + inStream = new ByteArrayInputStream("test\nhttp://example.com\nhttp://example.com".getBytes()); + System.setIn(inStream); + } + + @After + public void tearDown() { + recursiveDelete(new File(aafDir)); + } + + @Test + public void test() { + String[] args; + args = new String[] { + "-login", + "-noexit", + }; + CmAgent.main(args); + + inStream.reset(); + args = new String[] { + "noexit=true", + }; + CmAgent.main(args); + + inStream.reset(); + args = new String[] { + "place", + }; + CmAgent.main(args); + + inStream.reset(); + args = new String[] { + "create" + }; + CmAgent.main(args); + + inStream.reset(); + args = new String[] { + "read" + }; + CmAgent.main(args); + + inStream.reset(); + args = new String[] { + "copy" + }; + CmAgent.main(args); + + inStream.reset(); + args = new String[] { + "update" + }; + CmAgent.main(args); + + inStream.reset(); + args = new String[] { + "delete" + }; + CmAgent.main(args); + + inStream.reset(); + args = new String[] { + "showpass" + }; + CmAgent.main(args); + + } + + private void recursiveDelete(File file) { + for (File f : file.listFiles()) { + if (f.isDirectory()) { + recursiveDelete(f); + } + f.delete(); + } + file.delete(); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java index 27eeddc5..fb186b89 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java @@ -7,9 +7,9 @@ * * 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. @@ -19,13 +19,22 @@ * * * * ******************************************************************************/ + package org.onap.aaf.cadi.cm.test; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import static org.mockito.Mockito.*; -import org.junit.*; -import org.mockito.*; +import static org.junit.Assert.assertThat; +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.anyInt; +import static org.mockito.Mockito.anyString; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import java.io.BufferedReader; import java.io.File; @@ -50,6 +59,7 @@ import javax.crypto.Cipher; import org.onap.aaf.cadi.cm.CertException; import org.onap.aaf.cadi.cm.Factory; +import org.onap.aaf.cadi.cm.Factory.Base64InputStream; import org.onap.aaf.cadi.cm.Factory.StripperInputStream; import org.onap.aaf.misc.env.Env; @@ -59,34 +69,23 @@ import org.onap.aaf.misc.env.Trans; public class JU_Factory { - @Mock - Trans transMock; - - @Mock - TimeTaken timeTakenMock; - - @Mock - LogTarget logTargetMock; - - @Mock - X509Certificate x509CertMock; - - @Mock - Certificate certMock; - - @Mock - Principal subjectDN; + private static final String message = "The quick brown fox jumps over the lazy dog."; + private static final String subjectDNText = "subjectDN"; + private static final String certText = "Some text that might be included in a certificate"; + private static final String resourceDirName = "src/test/resources"; - private final String resourceDirName = "src/test/resources"; private File resourceDir; private File publicKeyFile; private File privateKeyFile; private File certFile; - - private static final String message = "The quick brown fox jumps over the lazy dog."; - private static final String subjectDNText = "subjectDN"; - private static final String certText = "Some text that might be included in a certificate"; + @Mock private Trans transMock; + @Mock private TimeTaken timeTakenMock; + @Mock private LogTarget logTargetMock; + @Mock private X509Certificate x509CertMock; + @Mock private Certificate certMock; + @Mock private Principal subjectDN; + @Before public void setup() throws CertificateEncodingException { @@ -118,10 +117,6 @@ public class JU_Factory { privateKeyFile = new File(resourceDirName, "/privateKey"); publicKeyFile.delete(); privateKeyFile.delete(); - - if (resourceDir.list().length == 0) { - resourceDir.delete(); - } } @Test @@ -295,25 +290,32 @@ public class JU_Factory { assertThat(Factory.verify(transMock, signedString.getBytes(), signedBytes, kp.getPublic()), is(true)); } - // TODO: Ian - finish these tests - // @Test - // public void base64ISTest() throws Exception { - // KeyPair kp = Factory.generateKeyPair(transMock); - - // String privateKeyString = Factory.toString(transMock, kp.getPrivate()); - // String cleaned = cleanupString(privateKeyString); - // System.out.println(cleaned); - // writeToFile(privateKeyFile, cleaned); - // Base64InputStream b64is = new Base64InputStream(privateKeyFile); - // byte[] buffer = new byte[10000]; - // b64is.read(buffer); - // System.out.println(new String(buffer)); - // b64is.close(); - // } - - // @Test - // public void getSecurityProviderTest() { - // } + @Test + public void base64ISTest() throws Exception { + KeyPair kp = Factory.generateKeyPair(transMock); + + String privateKeyString = Factory.toString(transMock, kp.getPrivate()); + String cleaned = cleanupString(privateKeyString); + writeToFile(privateKeyFile, cleaned, null); + Base64InputStream b64is = new Base64InputStream(privateKeyFile); + byte[] buffer = new byte[10000]; + b64is.read(buffer); + b64is.close(); + + FileInputStream fis = new FileInputStream(privateKeyFile); + b64is = new Base64InputStream(fis); + b64is.close(); + fis.close(); + } + + @Test + public void getSecurityProviderTest() throws CertException { + String[][] params = { + {"test", "test"}, + {"test", "test"}, + }; + assertThat(Factory.getSecurityProvider("PKCS12", params), is(nullValue())); + } private String cleanupString(String str) { String[] lines = str.split("\n", 0); @@ -324,7 +326,7 @@ public class JU_Factory { return join("", rawLines); } - /** + /** * Note: String.join is not part of JDK 7, which is what we compile to for CADI */ private String join(String delim, List<String> rawLines) { @@ -340,7 +342,7 @@ public class JU_Factory { } return sb.toString(); } - + private void writeToFile(File file, String contents, String header) throws Exception { PrintWriter writer = new PrintWriter(file, "UTF-8"); if (header != null) { diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInFiles.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInFiles.java new file mode 100644 index 00000000..3c83112c --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInFiles.java @@ -0,0 +1,100 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.cm.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.junit.*; +import org.mockito.*; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.cm.PlaceArtifactInFiles; +import org.onap.aaf.misc.env.Trans; + +import certman.v1_0.Artifacts.Artifact; +import certman.v1_0.CertInfo; + +public class JU_PlaceArtifactInFiles { + + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String dirName = "src/test/resources/artifacts"; + private static final String nsName = "org.onap.test"; + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + + private List<String> certs; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + certs = new ArrayList<>(); + certs.add("cert1"); + certs.add("cert2"); + + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + when(certInfoMock.getCerts()).thenReturn(certs); + + when(artiMock.getDir()).thenReturn(dirName); + when(artiMock.getNs()).thenReturn(nsName); + } + + @AfterClass + public static void tearDownOnce() { + cleanup(); + PlaceArtifactInFiles.clear(); + } + + @Test + public void test() throws CadiException { + PlaceArtifactInFiles placer = new PlaceArtifactInFiles(); + placer.place(transMock, certInfoMock, artiMock, "machine"); + assertThat(placer._place(transMock, certInfoMock, artiMock), is(true)); + assertThat(new File(dirName + '/' + nsName + ".crt").exists(), is(true)); + assertThat(new File(dirName + '/' + nsName + ".key").exists(), is(true)); + + when(certInfoMock.getCerts()).thenReturn(null); + try { + placer._place(transMock, certInfoMock, artiMock); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + } + + private static void cleanup() { + File dir = new File(dirName); + if (dir.exists()) { + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java new file mode 100644 index 00000000..d146f631 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java @@ -0,0 +1,147 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.cm.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import java.security.cert.CertificateException; + +import org.junit.*; +import org.mockito.*; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.cm.PlaceArtifactInKeystore; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import certman.v1_0.Artifacts.Artifact; +import certman.v1_0.CertInfo; + +public class JU_PlaceArtifactInKeystore { + + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String caName = "onap"; + private static final String dirName = "src/test/resources/artifacts"; + private static final String nsName = "org.onap.test"; + private static final String mechID = "m12345"; + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + + private static String privateKeyString; + private static String x509Chain; + private static String x509String; + + private List<String> certs; + + @Before + public void setup() throws FileNotFoundException, IOException, CertificateException { + MockitoAnnotations.initMocks(this); + + x509Chain = fromFile(new File("src/test/resources/cert.pem")); + x509String = fromFile(new File("src/test/resources/exampleCertificate.cer")); + privateKeyString = fromFile(new File("src/test/resources/key.pem")); + + certs = new ArrayList<>(); + + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + when(certInfoMock.getCerts()).thenReturn(certs); + + when(artiMock.getCa()).thenReturn(caName); + when(artiMock.getDir()).thenReturn(dirName); + when(artiMock.getNs()).thenReturn(nsName); + when(artiMock.getMechid()).thenReturn(mechID); + + when(certInfoMock.getPrivatekey()).thenReturn(privateKeyString); + + when(transMock.start("Reconstitute Private Key", Env.SUB)).thenReturn(mock(TimeTaken.class)); + } + + @AfterClass + public static void tearDownOnce() { + cleanup(); + PlaceArtifactInKeystore.clear(); + } + + @Test + public void test() throws CadiException { + // Note: PKCS12 can't be tested in JDK 7 and earlier. Can't handle Trusting Certificates. + PlaceArtifactInKeystore placer = new PlaceArtifactInKeystore("jks"); + + certs.add(x509String); + certs.add(x509Chain); + assertThat(placer.place(transMock, certInfoMock, artiMock, "machine"), is(true)); + for (String ext : new String[] {"chal", "keyfile", "jks", "props", "trust.jks"}) { + assertThat(new File(dirName + '/' + nsName + '.' + ext).exists(), is(true)); + } + + // coverage + assertThat(placer.place(transMock, certInfoMock, artiMock, "machine"), is(true)); + + when(certInfoMock.getCerts()).thenReturn(null); + try { + placer._place(transMock, certInfoMock, artiMock); + fail("Should've thrown an exception"); + } catch (Exception e) { + } + + } + + private static void cleanup() { + File dir = new File(dirName); + if (dir.exists()) { + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + } + + public String fromFile(File file) throws IOException { + BufferedReader br = new BufferedReader(new FileReader(file)); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + String line; + baos.write(br.readLine().getBytes()); + // Here comes the hacky part + baos.write("\n".getBytes()); + while((line=br.readLine())!=null) { + if(line.length()>0) { + baos.write(line.getBytes()); + baos.write("\n".getBytes()); + } + } + br.close(); + return baos.toString(); + } +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactOnStream.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactOnStream.java new file mode 100644 index 00000000..6e390bed --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactOnStream.java @@ -0,0 +1,101 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.cm.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; + +import org.junit.*; +import org.mockito.*; + +import org.onap.aaf.cadi.cm.PlaceArtifactOnStream; +import org.onap.aaf.misc.env.LogTarget; +import org.onap.aaf.misc.env.Trans; + +import certman.v1_0.Artifacts.Artifact; +import certman.v1_0.CertInfo; + +public class JU_PlaceArtifactOnStream { + + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + private static final String privateKeyString = "I'm a private key!"; + + private ByteArrayOutputStream outStream; + + private List<String> certs; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + certs = new ArrayList<>(); + certs.add("cert1"); + certs.add("cert2"); + + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + when(certInfoMock.getCerts()).thenReturn(certs); + when(certInfoMock.getPrivatekey()).thenReturn(privateKeyString); + + outStream = new ByteArrayOutputStream(); + } + + @Test + public void test() { + PlaceArtifactOnStream placer = new PlaceArtifactOnStream(new PrintStream(outStream)); + placer.place(transMock, certInfoMock, artiMock, "machine"); + + String[] output = outStream.toString().split("\n", 0); + + String[] expected = { + "Challenge: " + luggagePassword, + "PrivateKey:", + privateKeyString, + "Certificate Chain:", + "cert1", + "cert2" + }; + + assertThat(output.length, is(expected.length)); + for (int i = 0; i < output.length; i++) { + assertThat(output[i], is(expected[i])); + } + + // coverage + when(certInfoMock.getNotes()).thenReturn(""); + placer.place(transMock, certInfoMock, artiMock, "machine"); + + when(certInfoMock.getNotes()).thenReturn("Some Notes"); + when(transMock.info()).thenReturn(mock(LogTarget.class)); + placer.place(transMock, certInfoMock, artiMock, "machine"); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactScripts.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactScripts.java new file mode 100644 index 00000000..0ed29e10 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactScripts.java @@ -0,0 +1,92 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.cm.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import static org.mockito.Mockito.*; + +import java.io.File; + +import org.junit.*; +import org.mockito.*; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.cm.PlaceArtifactScripts; +import org.onap.aaf.misc.env.Trans; + +import certman.v1_0.Artifacts.Artifact; +import certman.v1_0.CertInfo; + +public class JU_PlaceArtifactScripts { + + @Mock private Trans transMock; + @Mock private CertInfo certInfoMock; + @Mock private Artifact artiMock; + + private static final String dirName = "src/test/resources/artifacts"; + private static final String nsName = "org.onap.test"; + private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life + private static final String notification = "A notification"; + private static final String osUser = "user"; // That's the stupidest combination I've ever heard in my life + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + when(artiMock.getDir()).thenReturn(dirName); + when(artiMock.getNs()).thenReturn(nsName); + when(artiMock.getNotification()).thenReturn(notification); + when(artiMock.getOsUser()).thenReturn(osUser); + + when(certInfoMock.getChallenge()).thenReturn(luggagePassword); + } + + @AfterClass + public static void tearDownOnce() { + cleanup(); + PlaceArtifactScripts.clear(); + } + + @Test + public void test() throws CadiException { + PlaceArtifactScripts placer = new PlaceArtifactScripts(); + placer.place(transMock, certInfoMock, artiMock, "machine"); + + assertThat(new File(dirName + '/' + nsName + ".crontab.sh").exists(), is(true)); + assertThat(new File(dirName + '/' + nsName + ".check.sh").exists(), is(true)); + + //coverage + when(artiMock.getNotification()).thenReturn("mailto: " + notification); + placer.place(transMock, certInfoMock, artiMock, "machine"); + } + + private static void cleanup() { + File dir = new File(dirName); + if (dir.exists()) { + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/lur/aaf/test/JU_JMeter.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/lur/aaf/test/JU_JMeter.java index 13df1ac5..a4fb20f9 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/lur/aaf/test/JU_JMeter.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/lur/aaf/test/JU_JMeter.java @@ -30,9 +30,11 @@ import java.io.FileReader; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; +import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.security.Principal; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Properties; @@ -43,6 +45,7 @@ import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp; import org.onap.aaf.cadi.aaf.v2_0.AAFLurPerm; import org.onap.aaf.cadi.aaf.v2_0.AAFTaf; import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.config.SecurityInfoC; import org.onap.aaf.cadi.locator.DNSLocator; import org.onap.aaf.cadi.principal.CachedBasicPrincipal; @@ -143,6 +146,13 @@ public class JU_JMeter { }; + @AfterClass + public static void tearDownAfterClass() throws Exception { + Field field = SecurityInfoC.class.getDeclaredField("sicMap"); + field.setAccessible(true); + field.set(null, new HashMap<Class<?>,SecurityInfoC<?>>()); + } + private static int index = -1; private synchronized Principal getIndex() { diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTaf.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTaf.java new file mode 100644 index 00000000..52b2beb4 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTaf.java @@ -0,0 +1,85 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.oauth.test; + +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.any; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.LocatorException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.oauth.OAuth2HttpTaf; +import org.onap.aaf.cadi.oauth.OAuth2Principal; +import org.onap.aaf.cadi.oauth.TokenMgr; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.cadi.Taf.LifeForm; +import org.onap.aaf.cadi.client.Result; + +public class JU_OAuth2HttpTaf { + + private static final String authz = "Bearer John Doe"; + + @Mock private TokenMgr tmgrMock; + @Mock private HttpServletResponse respMock; + @Mock private HttpServletRequest reqMock; + @Mock private OAuth2Principal princMock; + + private PropAccess access; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws APIException, CadiException, LocatorException { + OAuth2HttpTaf taf = new OAuth2HttpTaf(access, tmgrMock); + + taf.validate(LifeForm.CBLF, reqMock, respMock); + when(reqMock.getHeader("Authorization")).thenReturn(authz); + + doReturn(Result.ok(200, princMock)).when(tmgrMock).toPrincipal(anyString(), (byte[])any()); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + when(reqMock.isSecure()).thenReturn(true); + + doReturn(Result.err(404, "not found")).when(tmgrMock).toPrincipal(anyString(), (byte[])any()); + taf.validate(LifeForm.CBLF, reqMock, respMock); + + taf.revalidate(null, null); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTafResp.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTafResp.java new file mode 100644 index 00000000..94737b0c --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2HttpTafResp.java @@ -0,0 +1,68 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.oauth.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.oauth.OAuth2HttpTafResp; +import org.onap.aaf.cadi.oauth.OAuth2Principal; +import org.onap.aaf.cadi.principal.TrustPrincipal; +import org.onap.aaf.cadi.taf.TafResp.RESP; + +public class JU_OAuth2HttpTafResp { + + private static final String description = "description"; + + @Mock private TrustPrincipal princMock; + @Mock private OAuth2Principal oauthMock; + @Mock private HttpServletResponse respMock; + + private PropAccess access; + + private RESP status; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + status = RESP.NO_FURTHER_PROCESSING; + } + + @Test + public void test() throws IOException { + OAuth2HttpTafResp resp = new OAuth2HttpTafResp(access, princMock, description, status, respMock); + resp = new OAuth2HttpTafResp(access, oauthMock, description, status, respMock, true); + assertThat(resp.isFailedAttempt(), is(true)); + assertThat(resp.isAuthenticated(), is(status)); + assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED)); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Lur.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Lur.java new file mode 100644 index 00000000..853c4ae3 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Lur.java @@ -0,0 +1,100 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.oauth.test; + +import static org.mockito.Mockito.when; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +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.aaf.cadi.Permission; +import org.onap.aaf.cadi.aaf.AAFPermission; +import org.onap.aaf.cadi.oauth.OAuth2Lur; +import org.onap.aaf.cadi.oauth.OAuth2Principal; +import org.onap.aaf.cadi.oauth.TokenMgr; +import org.onap.aaf.cadi.oauth.TokenPerm; +import org.onap.aaf.cadi.principal.BearerPrincipal; + +public class JU_OAuth2Lur { + + private List<AAFPermission> aafPerms; + private List<Permission> perms; + + @Mock private TokenMgr tmMock; + @Mock private AAFPermission pondMock; + @Mock private Principal princMock; + @Mock private OAuth2Principal oauthPrincMock; + @Mock private BearerPrincipal bearPrincMock; + @Mock private TokenPerm tpMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test() { + OAuth2Lur lur = new OAuth2Lur(tmMock); + lur.createPerm("testPerm"); + lur.createPerm("testPerm1|testPerm2|testPerm3"); + + assertThat(lur.fish(princMock, pondMock), is(false)); + assertThat(lur.fish(oauthPrincMock, pondMock), is(false)); + + when(oauthPrincMock.tokenPerm()).thenReturn(tpMock); + assertThat(lur.fish(oauthPrincMock, pondMock), is(false)); + + aafPerms = new ArrayList<>(); + aafPerms.add(pondMock); + aafPerms.add(pondMock); + when(tpMock.perms()).thenReturn(aafPerms); + when(pondMock.match(pondMock)).thenReturn(false).thenReturn(true); + assertThat(lur.fish(oauthPrincMock, pondMock), is(true)); + + perms = new ArrayList<>(); + perms.add(pondMock); + perms.add(pondMock); + lur.fishAll(oauthPrincMock, perms); + + when(oauthPrincMock.tokenPerm()).thenReturn(null); + lur.fishAll(oauthPrincMock, perms); + + assertThat(lur.handlesExclusively(pondMock), is(false)); + + assertThat(lur.handles(null), is(false)); + assertThat(lur.handles(princMock), is(false)); + assertThat(lur.handles(bearPrincMock), is(false)); + when(bearPrincMock.getBearer()).thenReturn("not null :)"); + assertThat(lur.handles(bearPrincMock), is(true)); + + lur.destroy(); + lur.clear(null, null); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Principal.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Principal.java new file mode 100644 index 00000000..45736949 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuth2Principal.java @@ -0,0 +1,60 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.oauth.test; + +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.oauth.OAuth2Principal; +import org.onap.aaf.cadi.oauth.TokenPerm; + +public class JU_OAuth2Principal { + + @Mock TokenPerm tpMock; + + + private static final String username = "username"; + + private static final byte[] hash = "hashstring".getBytes(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + when(tpMock.getUsername()).thenReturn(username); + } + + @Test + public void test() { + OAuth2Principal princ = new OAuth2Principal(tpMock, hash); + assertThat(princ.getName(), is(username)); + assertThat(princ.tokenPerm(), is(tpMock)); + assertThat(princ.tag(), is("OAuth")); + assertThat(princ.personalName(), is(username)); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java index 8d43c1b5..a30f274f 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java @@ -23,9 +23,11 @@ package org.onap.aaf.cadi.oauth.test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.lang.reflect.Field; import java.net.ConnectException; import java.util.Date; import java.util.GregorianCalendar; +import java.util.HashMap; import org.junit.After; import org.junit.AfterClass; @@ -39,6 +41,7 @@ import org.onap.aaf.cadi.client.Rcli; import org.onap.aaf.cadi.client.Result; import org.onap.aaf.cadi.client.Retryable; import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.config.SecurityInfoC; import org.onap.aaf.cadi.oauth.TimedToken; import org.onap.aaf.cadi.oauth.TokenClient; import org.onap.aaf.cadi.oauth.TokenClientFactory; @@ -74,6 +77,9 @@ public class JU_OAuthTest { @AfterClass public static void tearDownAfterClass() throws Exception { + Field field = SecurityInfoC.class.getDeclaredField("sicMap"); + field.setAccessible(true); + field.set(null, new HashMap<Class<?>,SecurityInfoC<?>>()); } @Before diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TimedToken.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TimedToken.java new file mode 100644 index 00000000..775a0398 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TimedToken.java @@ -0,0 +1,84 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.oauth.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.mockito.Mockito.when; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.oauth.TimedToken; +import org.onap.aaf.cadi.persist.Persist; + +import aafoauth.v2_0.Token; + +public class JU_TimedToken { + + private static final byte[] hash = "hashstring".getBytes(); + + private static final int expires = 10000; + + private Path path; + + @Mock private Persist<Token, ?> persistMock; + @Mock private Token tokenMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + when(tokenMock.getExpiresIn()).thenReturn(expires); + path = Files.createTempFile("fake", ".txt"); + } + + @Test + public void test() { + int actuallyExpires = ((int)(System.currentTimeMillis() / 1000)) + expires; + TimedToken ttoken = new TimedToken(persistMock, tokenMock, hash, path); + + assertThat(ttoken.get(), is(tokenMock)); + assertThat(ttoken.checkSyncTime(), is(true)); + assertThat(ttoken.checkReloadable(), is(false)); + assertThat(ttoken.hasBeenTouched(), is(false)); + assertThat(Math.abs(ttoken.expires() - actuallyExpires) < 10, is(true)); + assertThat(ttoken.expired(), is(false)); + + assertThat(ttoken.match(hash), is(true)); + assertThat(ttoken.getHash(), is(hash)); + + assertThat(ttoken.path(), is(path)); + + assertThat(ttoken.count(), is(0)); + ttoken.inc(); + assertThat(ttoken.count(), is(1)); + ttoken.clearCount(); + assertThat(ttoken.count(), is(0)); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenPerm.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenPerm.java index 861e32e0..6bbed0ed 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenPerm.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TokenPerm.java @@ -7,9 +7,9 @@ * 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. @@ -21,18 +21,78 @@ package org.onap.aaf.cadi.oauth.test; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import org.junit.*; +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 org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import java.io.IOException; import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Path; import org.onap.aaf.cadi.Permission; +import org.onap.aaf.cadi.oauth.TokenPerm; import org.onap.aaf.cadi.oauth.TokenPerm.LoadPermissions; +import org.onap.aaf.cadi.persist.Persist; +import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.rosetta.ParseException; +import org.onap.aaf.misc.rosetta.env.RosettaDF; + +import aaf.v2_0.Perms; +import aafoauth.v2_0.Introspect; public class JU_TokenPerm { + private static final byte[] hash = "hashstring".getBytes(); + + private static final String clientId = "clientId"; + private static final String username = "username"; + private static final String token = "token"; + private static final String scopes = "scopes"; + private static final String content = "content"; + + private static final long expires = 10000L; + + private static Path path; + + @Mock private Persist<Introspect, ?> persistMock; + @Mock private RosettaDF<Perms> dfMock; + @Mock private Introspect introspectMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + when(introspectMock.getExp()).thenReturn(expires); + when(introspectMock.getClientId()).thenReturn(clientId); + when(introspectMock.getUsername()).thenReturn(username); + when(introspectMock.getAccessToken()).thenReturn(token); + when(introspectMock.getScope()).thenReturn(scopes); + when(introspectMock.getExp()).thenReturn(expires); + + path = Files.createTempFile("fake", ".txt"); + } + + @Test + public void tokenTest() throws APIException { + TokenPerm tokenPerm = new TokenPerm(persistMock, dfMock, introspectMock, hash, path); + assertThat(tokenPerm.perms().size(), is(0)); + assertThat(tokenPerm.getClientId(), is(clientId)); + assertThat(tokenPerm.getUsername(), is(username)); + assertThat(tokenPerm.getToken(), is(token)); + assertThat(tokenPerm.getScopes(), is(scopes)); + assertThat(tokenPerm.getIntrospect(), is(introspectMock)); + + when(introspectMock.getContent()).thenReturn(content); + tokenPerm = new TokenPerm(persistMock, dfMock, introspectMock, hash, path); + } + @Test public void test() throws ParseException { String json; @@ -132,5 +192,5 @@ public class JU_TokenPerm { fail(e.getMessage()); } } - + } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TzHClient.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TzHClient.java new file mode 100644 index 00000000..7febf51f --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_TzHClient.java @@ -0,0 +1,113 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.oauth.test; + +import static org.junit.Assert.assertThat; +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.doReturn; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.net.HttpURLConnection; +import java.net.URI; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.Locator; +import org.onap.aaf.cadi.Locator.Item; +import org.onap.aaf.cadi.LocatorException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.client.Rcli; +import org.onap.aaf.cadi.client.Retryable; +import org.onap.aaf.cadi.oauth.TimedToken; +import org.onap.aaf.cadi.oauth.TzHClient; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.config.SecurityInfoC; + +public class JU_TzHClient { + + @Mock private Retryable<Integer> retryableMock; + @Mock private TimedToken tokenMock; + @Mock private SecurityInfoC<HttpURLConnection> siMock; + @Mock private Locator<URI> locMock; + @Mock private Item itemMock; + @Mock private Rcli<HttpURLConnection> clientMock; + + private PropAccess access; + + private ByteArrayOutputStream errStream; + + private final static String client_id = "id"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat + access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon } + + errStream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setErr(System.err); + } + + @Test + public void test() throws CadiException, LocatorException, APIException, IOException { + TzHClient client = new TzHClient(access, "tag"); + try { + client.best(retryableMock); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("OAuth2 Token has not been set")); + } + client.setToken(client_id, tokenMock); + when(tokenMock.expired()).thenReturn(true); + try { + client.best(retryableMock); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is("Expired Token")); + } + + client = new TzHClient(access, siMock, locMock); + when(tokenMock.expired()).thenReturn(false); + doReturn(clientMock).when(retryableMock).lastClient(); + + when(retryableMock.item()).thenReturn(itemMock); + client.setToken(client_id, tokenMock); + assertThat(client.best(retryableMock), is(nullValue())); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persist.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persist.java new file mode 100644 index 00000000..f8d76a95 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persist.java @@ -0,0 +1,151 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.persist.test; + +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Matchers.any; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Path; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.Access; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.LocatorException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.client.Holder; +import org.onap.aaf.cadi.client.Result; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.persist.Persist; +import org.onap.aaf.cadi.persist.Persist.Loader; +import org.onap.aaf.cadi.persist.Persistable; +import org.onap.aaf.cadi.persist.Persisting; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.rosetta.env.RosettaDF; +import org.onap.aaf.misc.rosetta.env.RosettaData; +import org.onap.aaf.misc.rosetta.env.RosettaEnv; + +public class JU_Persist { + + private static final String resourceDirString = "src/test/resources"; + private static final String tokenDirString = "tokenDir"; + private static final String key = "key"; + + private static final int data = 5; + + private static final byte[] cred = "password".getBytes(); + + private PropAccess access; + private Result<Persistable<Integer>> result; + + @Mock private RosettaEnv envMock; + @Mock private Persist<Integer, ?> persistMock; + @Mock private RosettaDF<Integer> dfMock; + @Mock private RosettaData<Integer> dataMock; + @Mock private Persistable<Integer> ctMock1; + @Mock private Persisting<Integer> ctMock2; + @Mock private Loader<Persistable<Integer>> loaderMock; + + @Before + public void setup() throws APIException, CadiException, LocatorException { + MockitoAnnotations.initMocks(this); + + doReturn(dfMock).when(envMock).newDataFactory((Class<?>[]) any()); + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.load(data)).thenReturn(dataMock); + + + result = Result.ok(200, ctMock1); + when(loaderMock.load(key)).thenReturn(result); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString); + } + + @After + public void tearDown() { + File dir = new File(resourceDirString + '/' + tokenDirString); + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + + @Test + public void test() throws CadiException, APIException, LocatorException, InterruptedException { + Persist<Integer, Persistable<Integer>> persist = new PersistStub(access, envMock, null, tokenDirString); + // Second call for coverage + persist = new PersistStub(access, envMock, null, tokenDirString); + assertThat(persist.getDF(), is(dfMock)); + persist.put(key, ctMock2); + Result<Persistable<Integer>> output = persist.get(key, cred, loaderMock); + assertThat(output.code, is(200)); + assertThat(output.isOK(), is(true)); + + when(ctMock2.checkSyncTime()).thenReturn(true); + when(ctMock2.hasBeenTouched()).thenReturn(true); + output = persist.get(key, cred, loaderMock); + assertThat(output.code, is(200)); + assertThat(output.isOK(), is(true)); + + persist.delete(key); + + assertThat(persist.get(null, null, null), is(nullValue())); + + // Uncommenting this lets us begin to test the nested Clean class, but + // will dramatically slow down every build that runs tests - We need to + // either refactor or find a more creative way to test Clean +// Thread.sleep(25000); + + persist.close(); + } + + private class PersistStub extends Persist<Integer, Persistable<Integer>> { + public PersistStub(Access access, RosettaEnv env, Class<Integer> cls, String sub_dir) + throws CadiException, APIException { super(access, env, cls, sub_dir); } + @Override + protected Persistable<Integer> newCacheable(Integer t, long expires_secsFrom1970, byte[] hash, Path path) + throws APIException, IOException { return null; } + @Override + public<T> Path writeDisk(final RosettaDF<T> df, final T t, final byte[] cred, final Path target, final long expires) throws CadiException { + return null; + } + @SuppressWarnings("unchecked") + @Override + public <T> T readDisk(final RosettaDF<T> df, final byte[] cred, final String filename,final Holder<Path> hp, final Holder<Long> hl) throws CadiException { + return (T)new Integer(data); + } + + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_PersistFile.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_PersistFile.java new file mode 100644 index 00000000..cbe865eb --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_PersistFile.java @@ -0,0 +1,121 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.persist.test; + +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.hamcrest.CoreMatchers.is; +import static org.mockito.Mockito.when; +import static org.mockito.Matchers.any; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; + +import javax.crypto.CipherInputStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.client.Holder; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.persist.PersistFile; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.rosetta.env.RosettaDF; +import org.onap.aaf.misc.rosetta.env.RosettaData; + +public class JU_PersistFile { + + private static final String resourceDirString = "src/test/resources"; + private static final String tokenDirString = "tokenDir"; + private static final String tokenFileName = "token"; + + private static final int data = 5; + private static final long expires = 10000; + + private static final byte[] cred = "password".getBytes(); + + private PropAccess access; + private Holder<Path> hp = new Holder<Path>(null); + private Holder<Long> hl = new Holder<Long>(null); + + @Mock private RosettaDF<Integer> dfMock; + @Mock private RosettaData<Integer> dataMock; + @Mock private Holder<Path> hpMock; + + @Before + public void setup() throws APIException { + MockitoAnnotations.initMocks(this); + + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.load(data)).thenReturn(dataMock); + when(dataMock.load((CipherInputStream)any())).thenReturn(dataMock); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString); + } + + @After + public void tearDown() { + File dir = new File(resourceDirString + '/' + tokenDirString); + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + + @Test + public void test() throws CadiException, APIException, IOException { + PersistFile persistFile = new PersistFile(access, tokenDirString); + // Second call is for coverage + persistFile = new PersistFile(access, tokenDirString); + Path filepath = persistFile.writeDisk(dfMock, data, cred, tokenFileName, expires); + persistFile.readDisk(dfMock, cred, tokenFileName, hp, hl); + assertThat(persistFile.readExpiration(filepath), is(expires)); + + FileTime ft1 = persistFile.getFileTime(tokenFileName, hp); + FileTime ft2 = persistFile.getFileTime(tokenFileName, hpMock); + assertThat(ft1.toMillis(), is(ft2.toMillis())); + + persistFile.deleteFromDisk(filepath); + persistFile.deleteFromDisk(resourceDirString + '/' + tokenDirString + '/' + tokenFileName); + assertThat(persistFile.readExpiration(filepath), is(0L)); + + persistFile.getPath(resourceDirString + '/' + tokenDirString + '/' + tokenFileName); + + persistFile.writeDisk(dfMock, data, null, tokenFileName, expires); + try { + persistFile.readDisk(dfMock, cred, tokenFileName, hp, hl); + fail("Should've thrown an exception"); + } catch (CadiException e) { + assertThat(e.getMessage(), is(CadiException.class.getName() + ": Hash does not match in Persistence")); + } + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persisting.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persisting.java new file mode 100644 index 00000000..bb2b918a --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/persist/test/JU_Persisting.java @@ -0,0 +1,130 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.persist.test; + +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.mockito.Mockito.when; +import static org.mockito.Matchers.any; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.PrintStream; +import java.nio.file.Path; +import java.nio.file.Paths; + +import javax.crypto.CipherInputStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.persist.Persist; +import org.onap.aaf.cadi.persist.PersistFile; +import org.onap.aaf.cadi.persist.Persisting; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.rosetta.env.RosettaDF; +import org.onap.aaf.misc.rosetta.env.RosettaData; + +public class JU_Persisting { + + private static final String resourceDirString = "src/test/resources"; + private static final String tokenDirString = "tokenDir"; + private static final String tokenFileName = "token"; + + private static final int data = 5; + private static final long expires = 10000; + + private static final byte[] cred = "password".getBytes(); + + private PropAccess access; + + @Mock private Persist<Integer, ?> persistMock; + @Mock private RosettaDF<Integer> dfMock; + @Mock private RosettaData<Integer> dataMock; + + @Before + public void setup() throws APIException { + MockitoAnnotations.initMocks(this); + + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.load(data)).thenReturn(dataMock); + when(dataMock.load((CipherInputStream)any())).thenReturn(dataMock); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString); + + persistMock.access = access; + } + + @After + public void tearDown() { + File dir = new File(resourceDirString + '/' + tokenDirString); + for (File f : dir.listFiles()) { + f.delete(); + } + dir.delete(); + } + + @Test + public void test() throws CadiException, APIException { + Path tokenPath = Paths.get(resourceDirString, tokenDirString); + + Persisting<Integer> persisting = new Persisting<>(persistMock, data, expires, cred, tokenPath); + assertThat(persisting.get(), is(data)); + assertThat(persisting.expires(), is(expires)); + assertThat(persisting.expired(), is(true)); + assertThat(persisting.hasBeenTouched(), is(true)); + + PersistFile persistFile = new PersistFile(access, tokenDirString); + tokenPath = persistFile.writeDisk(dfMock, data, cred, tokenFileName, expires); + persisting = new Persisting<>(persistMock, data, expires, cred, tokenPath); + assertThat(persisting.hasBeenTouched(), is(false)); + + persisting = new Persisting<>(persistMock, data, expires * (int)10e9, cred, tokenPath); + assertThat(persisting.expired(), is(false)); + + assertThat(persisting.checkSyncTime(), is(true)); + assertThat(persisting.checkSyncTime(), is(false)); + + assertThat(persisting.checkReloadable(), is(false)); + + assertThat(persisting.getHash(), is(cred)); + + assertThat(persisting.match(null), is(false)); + assertThat(persisting.match("random!".getBytes()), is(false)); + assertThat(persisting.match("passwrod".getBytes()), is(false)); + assertThat(persisting.match(cred), is(true)); + + persisting.clearCount(); + assertThat(persisting.count(), is(0)); + persisting.inc(); + assertThat(persisting.count(), is(1)); + + assertThat(persisting.path(), is(tokenPath)); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java new file mode 100644 index 00000000..34997fe6 --- /dev/null +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java @@ -0,0 +1,122 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.sso.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.sso.AAFSSO; + +public class JU_AAFSSO { + + private static final String resourceDirString = "src/test/resources"; + private static final String aafDir = resourceDirString + "/aaf"; + + private ByteArrayInputStream inStream; + + @Before + public void setup() { + System.setProperty("user.home", aafDir); + + // Simulate user input + inStream = new ByteArrayInputStream("test\npassword".getBytes()); + System.setIn(inStream); + } + + @After + public void tearDown() { + recursiveDelete(new File(aafDir)); + } + + @Test + public void test() throws IOException, CadiException { + AAFSSO sso; + String[] args; + + args = new String[] { + "-login", + "-noexit", + }; + sso = new AAFSSO(args); + + assertThat(new File(aafDir).exists(), is(true)); + assertThat(new File(aafDir + "/.aaf").exists(), is(true)); + assertThat(new File(aafDir + "/.aaf/keyfile").exists(), is(true)); + assertThat(new File(aafDir + "/.aaf/sso.out").exists(), is(true)); + assertThat(sso.loginOnly(), is(true)); + + assertThat(new File(aafDir + "/.aaf/sso.props").exists(), is(false)); + sso.writeFiles(); + assertThat(new File(aafDir + "/.aaf/sso.props").exists(), is(true)); + + sso.setLogDefault(); + sso.setStdErrDefault(); + + inStream.reset(); + args = new String[] { + "-logout", + "\\*", + "-noexit", + }; + sso = new AAFSSO(args); + + assertThat(new File(aafDir).exists(), is(true)); + assertThat(new File(aafDir + "/.aaf").exists(), is(true)); + assertThat(new File(aafDir + "/.aaf/keyfile").exists(), is(true)); + assertThat(new File(aafDir + "/.aaf/sso.out").exists(), is(true)); + assertThat(sso.loginOnly(), is(false)); + + PropAccess access = sso.access(); + assertThat(sso.enc_pass(), is(access.getProperty(Config.AAF_APPPASS))); + assertThat(sso.user(), is(access.getProperty(Config.AAF_APPID))); + + sso.addProp("key", "value"); + assertThat(sso.err(), is(nullValue())); + + assertThat(sso.useX509(), is(false)); + + sso.close(); + sso.close(); + } + + private void recursiveDelete(File file) { + for (File f : file.listFiles()) { + if (f.isDirectory()) { + recursiveDelete(f); + } + f.delete(); + } + file.delete(); + } + +} diff --git a/cadi/aaf/src/test/java/org/onap/aaf/content/JU_Content.java b/cadi/aaf/src/test/java/org/onap/aaf/content/JU_Content.java index 21012e68..e997378d 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/content/JU_Content.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/content/JU_Content.java @@ -23,25 +23,16 @@ package org.onap.aaf.content; import java.io.StringReader; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.onap.aaf.misc.rosetta.env.RosettaDF; import org.onap.aaf.misc.rosetta.env.RosettaData; import org.onap.aaf.misc.rosetta.env.RosettaEnv; import aaf.v2_0.Error; -public class JU_Content { - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } +// TODO: This test doesn't really do anything. It should be deleted as soon as coverage is above 50% +public class JU_Content { @Test public void parseErrorJSON() throws Exception { @@ -70,11 +61,15 @@ public class JU_Content { errDF.out(RosettaData.TYPE.JSON); RosettaData<Error> data = errDF.newData(); data.load(err); - System.out.println(data.asString()); + + @SuppressWarnings("unused") + String output = data.asString(); +// System.out.println(output); data.load(new StringReader(msg)); err = data.asObject(); - System.out.println(err.getText()); + output = err.getText(); +// System.out.println(output); } diff --git a/cadi/aaf/src/test/resources/cert.pem b/cadi/aaf/src/test/resources/cert.pem new file mode 100644 index 00000000..175c949d --- /dev/null +++ b/cadi/aaf/src/test/resources/cert.pem @@ -0,0 +1,33 @@ +-----BEGIN CERTIFICATE----- +MIIFqzCCA5OgAwIBAgIJAKR74mLLmqGoMA0GCSqGSIb3DQEBCwUAMGwxCzAJBgNV +BAYTAlVTMREwDwYDVQQIDAhNaXNzb3VyaTERMA8GA1UEBwwIU3QgTG91aXMxETAP +BgNVBAoMCEZha2UgT3JnMREwDwYDVQQLDAhmYWtlLm9yZzERMA8GA1UEAwwISm9o +biBEb2UwHhcNMTgwNTAzMjEwMzEzWhcNMTgwNjAyMjEwMzEzWjBsMQswCQYDVQQG +EwJVUzERMA8GA1UECAwITWlzc291cmkxETAPBgNVBAcMCFN0IExvdWlzMREwDwYD +VQQKDAhGYWtlIE9yZzERMA8GA1UECwwIZmFrZS5vcmcxETAPBgNVBAMMCEpvaG4g +RG9lMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvfadEz8rdI3Q6LsA +3e4cPYGkYkty7gyVmD52DYxQYsrykJewI4iqJ+jZb2kfEYjz5Tw3hAi1cw2Db5Vr +2yB3GLR9lk6Eryj1/tDEVXrWDJpXPSEKcyLDzvsLEXi6ZabVZbSzX41/YSct1Hn/ +ucHo2oFtKz6GLVQ0Jb5dp5sQiV8KDdrj2+KDRkQR6WeEY5a89wAwcoYEOlIXx6+4 +jurhUzdvyRiXFxEl2B20IGDQ0byEUnbXEgcCDBJVNyU+dxXMSLHcxFNKEjhaYcn1 +29nEzStfEV8NuxqiE7TCZNUCy2BAMxd9k4kmZ4Tb6tOyza+fEUBu4BLBywusyeVb +D/mupHyG6K/xyMAVmSqGYVjweEFX+UkITHsvkZS2+Iizjt1x658RuLcI8YvEHPbm +lU+wirNoc/1wOxR3V53ZSjqnghLql8TUDVH7ysp+khthiJnr26fRSZNSkNBbNhax +FkC9UYuVuoHscUjsRzX0RkELo4OJG6n11SUyB0K9WLI6b33yfBXFOpOXByavvjkS +BZM7pNOG77GSz/uCaQ/glE7PSnDx1AzGWGdv9YqKAFU6lEMdw2HCozzc2aX/GXPW +hvh2Hjvt2ZKJc87DVvLsdySQwsJ05YF71kxMmxqnwqnD5/h0pMjxThyDm7DfaGek +9gAw7nqCOQJbvafl8ZnKFKnAI/0CAwEAAaNQME4wHQYDVR0OBBYEFFn1zEUXwHY2 +odqzPA0BTkoBqTzWMB8GA1UdIwQYMBaAFFn1zEUXwHY2odqzPA0BTkoBqTzWMAwG +A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggIBADWOO+YOdwIL0Wdws89s2h1I +TAN2glpQNDcwiMlT5VISqrb4R5oGYQuc7eR3X6fUArZwo38QW2C5+A4gXCUmy+UE +Hyneac+RXTxD29Glxn14dt174VsJ7mlFxkOd7ft8beaRhga5DAot6HyjJwS2K8GP +cNoM9zJFbJcRjs4oO93fOdp5M3mOOcwMbfQLZIFUx93Y7cn3Uoyz/Yfws/KKuY9r +faUGNB9bSSZc+aM7ZLorMwDb45Beu443czUfzOhWLxiDK9pqwY9k7DV4x4ahvPhx +OiRl31ksL/esCc4G2oOe9wATh1gwnIDJWE1bgNepKwjqinlWRQqq7JcRbpXyQ2t0 +0v0P60cVcIMO6iCuCvKO4wZh5nUrHQlTfHfWDyH5UN2nUa12BpOidvgp5AzuVG6e +pIYbRViwdOzEOAKOlHCuZN/rFkQAmi6baz4/7JV9GeW92xZyDc9GGM/JQY3lMRfw +ablgXEuJFJGVQkO6/LkqcEvFpLVcdTeJeWxJvR9lwJJX1NXTQN91aFqLznc50idK +UiKjE+3eBG/S64htp48+a6xi2r6uujRl/VAOoTjunGuSvDdmThlwnnlnp4iqcm7k +m4nB2/4SvSzQ8r4cUl0sFCZ7OLW8WM4dpZcfklk7ApZ4TFTMzUi4zUtCk4Vfdxbm +MX+3SmP+Pjf0p+1DtdhM +-----END CERTIFICATE----- diff --git a/cadi/aaf/src/test/resources/key.pem b/cadi/aaf/src/test/resources/key.pem new file mode 100644 index 00000000..a5818db0 --- /dev/null +++ b/cadi/aaf/src/test/resources/key.pem @@ -0,0 +1,52 @@ +-----BEGIN PRIVATE KEY----- +MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQC99p0TPyt0jdDo +uwDd7hw9gaRiS3LuDJWYPnYNjFBiyvKQl7AjiKon6NlvaR8RiPPlPDeECLVzDYNv +lWvbIHcYtH2WToSvKPX+0MRVetYMmlc9IQpzIsPO+wsReLplptVltLNfjX9hJy3U +ef+5wejagW0rPoYtVDQlvl2nmxCJXwoN2uPb4oNGRBHpZ4Rjlrz3ADByhgQ6UhfH +r7iO6uFTN2/JGJcXESXYHbQgYNDRvIRSdtcSBwIMElU3JT53FcxIsdzEU0oSOFph +yfXb2cTNK18RXw27GqITtMJk1QLLYEAzF32TiSZnhNvq07LNr58RQG7gEsHLC6zJ +5VsP+a6kfIbor/HIwBWZKoZhWPB4QVf5SQhMey+RlLb4iLOO3XHrnxG4twjxi8Qc +9uaVT7CKs2hz/XA7FHdXndlKOqeCEuqXxNQNUfvKyn6SG2GImevbp9FJk1KQ0Fs2 +FrEWQL1Ri5W6gexxSOxHNfRGQQujg4kbqfXVJTIHQr1YsjpvffJ8FcU6k5cHJq++ +ORIFkzuk04bvsZLP+4JpD+CUTs9KcPHUDMZYZ2/1iooAVTqUQx3DYcKjPNzZpf8Z +c9aG+HYeO+3ZkolzzsNW8ux3JJDCwnTlgXvWTEybGqfCqcPn+HSkyPFOHIObsN9o +Z6T2ADDueoI5Alu9p+XxmcoUqcAj/QIDAQABAoICADRkPuAfDQIhVtvJL60Fzd4c +0lSV0IXdDKknmPGVoFoO9SVx4I98UsmdC9MRYBM6/WFc4UbWDA1GTdjJkiymYJJ8 +vSJmV2vj1SzJMU0OCtkA/EyMv1AP54c/b8cK0AXXJIXfd5VD9jy6TIaMez4lP+57 +wbsqjGEWFyfNwBDI0J/CiYhWtX9gkqofff0sorPA0C8jazk6wxG+sHZPfYxVNX35 +DSieUpV3EkPvtU00xoMCBlCkHB8JtcPUjpIeAINhjK0D+Qpgmk46IptT0y4meoPH +kXm+CJBxAQCEWxTqNtIWor40nVrCecgVOX4jku3toOZmKe483hv9BVPNoPbf+w1C +5PI8eLCVeKp10dhSP9+HsKhwENqac/pF4RISnf5St0hccdyzHlwyRXVY2UJDd8Ik +Hv4zh3iSzuhd5ar4Pgpwvl/9dsJBDQtxf2RgBMLlf9TbIaFTA+Q55Ir/+BsaCxkr +Uz+bk00cF2nrUU7cqu0TXzsOCmCq02Oc4ELZ3zXGu1t2EjeIkAatbrCTigdiGimj +gpB5bSRUNKyu9lQgHP/XIiWeiYmRb1I9j2ICxbvdZm5Kj5o2/6i9vy4ouCvd9qF3 +IdK2/U+sBF6XFKvGMzRC3giID+PYSqMcoBybuUzWgfKLu3WMpuhnPKPtorokc7d7 +M3+Wc7UfSbQUn2JY/2wBAoIBAQDjLLIaFLkbfg6HMQu/JPspLibYzAXbGRw+SJj5 +vkqVmlPFj2pNpEFHLHdN7gmmKxmq3crTL47g3XoOAI4vk5obpO5ICtrsXF/OSL4a +MAm63wvY+KiIUAhRTNzu53xjQ+PwaG1A7VghkPeAtk/HCI2vqJH7UoLWUcR7abUL +gCILuGnxk7QnjJNWoD6pJ6RV4vnkRx/2cZO+rYE6Wm2kBeaNoW/aEKXYYBsAty2E +/dJ1GkEm4x59+R43Lu665GTaDKJPItxTyv7QpKvWbdPUab8g5YdA12p2//HrLCb3 +yMBedxys2VDpaIBSN6INi/6BMCRMtoDdol1gzHm2/dlMWuD9AoIBAQDWES+VNosh +MkLsPcAp1Psq0+ucQCWpyAMgpgkN0SbBJDcMR+xqrmrxunOWuFeWg5A48xiCQNdW +uA8X6X3TWGsFaNyFD5BNPl1WncmzwtqTCjqgn/EDdTWS40eLFZJMxBf0infjPMFS +dkrIcbLOHb56miBf+CnMZ1uEmwo0h2epwkaU6Kk1wm3X8bojUVGzY5O5x8AJzDeP +EC4hmC34FnPu19LRNT/29vzX5X8mLuy7RYcdzCy9ut//G+m+OVoMImvTI6cxLN0v +zcJyJmrYoR9yVfHjcUA43CgkCSqIlVPSYIvBFLL/O9ZZspfZqAERYcCFT38uAtF/ +nPfuTk6mUz8BAoIBABGkzQhdh6rs9W/mjUUBOEiQfw/jeKj1oE3uEYOEFgLcg5ka +dGUnVrKSb4mr7S/stQeiRjh0vyIT0YD45hIn4pY3DxKlVS96VS6OU8Vw6bCL1j25 +wk0j+iFmWNptPCnxgeiQE7wxMuEYg0CJ6FRLA8Yaz4u3ctX2b84t/ZOxFfPXFNNg +Z2OS9XaK55L3sznAcSwbog3f8Fuk2h6QG2fb1XY2jZtgI6FUhYRetbhYhln1+g1t +IlciXAhpKr11M6gDxy9iQ752S6gkwfvbd9JNjDyf1wtgL7KiWkWrnjMsclRj5+Q8 +1J3sMdsw2vM2ZkPeW1Nh8UxFaf80oldmC9R0UnkCggEAbmLwWY6F0jl73xy8shWc +62najnlZsqJsUnKsKo7W4DQPmuqf1CdbCInwPyGSMRBo16Ur10cehB5n0hnag5iN +n32Cca8j52EoepjlQShS1A4rS1cOzoyrcrJ22xblmWZpP/YDeo+C1UYgrBpNbRJT +fh9qYHK1Ay2tOMVGTu4gG58ODI2pbAp14CxLoxi0+792lw+VTLgdUk2yrCowUkUp +xVlP4ggGkxCsM5ypo4QBGVTyJwB5deEezwuSzj/+2lEJrxgsiCQtbxA4m+qJoGn9 +sFT3ZiSpTGji3ipH36S5U7vrdUZ6QzmVAC4jNd73pgH1aAkleRGE/Lxx8VY6InS9 +AQKCAQEAjUxVkW7ei0XOvz3hzEM8s84StZAzz/OOchxxLIDwWtmrnTRlDCDFNgfn +kjWggY8ySvEGeeh/Bq1UjZn46yJEnbBaluSlwtpB9/QNlvVESfi72F6qXxPrAb7w +wvMLFk2abUQk1MUursiC4Xch5Br9wGAQqzPIFNQRlhH3t47ZGyQn9Sc0FONLfPpO +NR+A0BBvfQG7/fg1JLNcmh9AdQr0gxTUJyR4a32An4IcSQZqCyF7Zzr3ERJ3n2tR +0S0NaYmQEs7sqULnG2f8USc53z5/skAo2OXeOZXmCpY7PH7Zfq85ojnsB/d9rAfm +43jbRd3vVTO310fh3QIgNQ3tg+u3mg== +-----END PRIVATE KEY----- diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java index 46099887..456184c3 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java @@ -28,6 +28,7 @@ import java.io.OutputStream; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; @@ -121,18 +122,11 @@ public class HClient implements EClient<HttpURLConnection> { } pi.append(pathinfo); } - URL url = new URI( - uri.getScheme(), - uri.getUserInfo(), - uri.getHost(), - uri.getPort(), - pi==null?uri.getPath():pi.toString(), - query, - fragment).toURL(); pathinfo=null; query=null; fragment=null; - huc = (HttpURLConnection) url.openConnection(); + //huc = (HttpURLConnection) url.openConnection(); + huc = getConnection(uri, pi); huc.setRequestMethod(meth); if(ss!=null) { ss.setSecurity(huc); @@ -169,10 +163,21 @@ public class HClient implements EClient<HttpURLConnection> { return connectTimeout; } - public abstract class HFuture<T> extends Future<T> { + protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException { + URL url = new URI( + uri.getScheme(), + uri.getUserInfo(), + uri.getHost(), + uri.getPort(), + pi==null?uri.getPath():pi.toString(), + query, + fragment).toURL(); + return (HttpURLConnection) url.openConnection(); + } + + public abstract class HFuture<T> extends Future<T> { protected HttpURLConnection huc; protected int respCode; - protected String respMessage; protected IOException exception; protected StringBuilder errContent; @@ -258,10 +263,6 @@ public class HClient implements EClient<HttpURLConnection> { return exception; } - public String respMessage() { - return respMessage; - } - @Override public String header(String tag) { return huc.getHeaderField(tag); @@ -285,9 +286,6 @@ public class HClient implements EClient<HttpURLConnection> { public String body() { if (errContent != null) { return errContent.toString(); - - } else if (respMessage != null) { - return respMessage; } return ""; } @@ -314,8 +312,6 @@ public class HClient implements EClient<HttpURLConnection> { return value; } else if (errContent != null) { return errContent.toString(); - } else if (respMessage != null) { - return respMessage; } return ""; } @@ -346,8 +342,6 @@ public class HClient implements EClient<HttpURLConnection> { } } else if (errContent != null) { return errContent.toString(); - } else if (respMessage != null) { - return respMessage; } return ""; } @@ -369,8 +363,6 @@ public class HClient implements EClient<HttpURLConnection> { public String body() { if (errContent != null) { return errContent.toString(); - } else if (respMessage != null) { - return respMessage; } return Integer.toString(respCode); } @@ -419,7 +411,7 @@ public class HClient implements EClient<HttpURLConnection> { @Override public String body() { - return errContent==null?respMessage:errContent.toString(); + return errContent==null?null:errContent.toString(); } }; } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java index 655a0c22..ed60b877 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java @@ -73,34 +73,7 @@ public class DNSLocator implements Locator<URI> { throw new LocatorException("DNSLocator accepts only https or http protocols. (requested URL " + aaf_locate + ')'); } - int colon = aaf_locate.indexOf(':',start); - int slash; - if(colon>0) { - start = colon+1; - int left = aaf_locate.indexOf('[',start); - if(left>0) { - int right = aaf_locate.indexOf(']',left+1); - if(right>0) { - int dash = aaf_locate.indexOf('-',left+1); - if(dash<0) { - startPort = endPort = Integer.parseInt(aaf_locate.substring(left+1,right)); - } else { - startPort = Integer.parseInt(aaf_locate.substring(left+1,dash)); - endPort = Integer.parseInt(aaf_locate.substring(dash + 1,right)); - } - } - - } else { - slash = aaf_locate.indexOf('/',colon+1); - if(slash<0) { - startPort = endPort = Integer.parseInt(aaf_locate.substring(start)); - } else { - startPort = endPort = Integer.parseInt(aaf_locate.substring(start,slash)); - } - } - } else { - startPort = endPort = port; - } + parsePorts(aaf_locate.substring(start), port); } @Override @@ -185,6 +158,46 @@ public class DNSLocator implements Locator<URI> { } return false; } + + private void parsePorts(String aaf_locate, int defaultPort) throws LocatorException { + int slash, start; + int colon = aaf_locate.indexOf(':'); + if(colon > 0) { + start = colon + 1; + int left = aaf_locate.indexOf('[', start); + if(left > 0) { + int right = aaf_locate.indexOf(']', left + 1); + if (right < 0) { + throw new LocatorException("Missing closing bracket in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } else if (right == (left + 1)) { + throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } + int dash = aaf_locate.indexOf('-', left + 1); + if (dash == (right - 1) || dash == (left + 1)) { + throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } + if(dash < 0) { + startPort = endPort = Integer.parseInt(aaf_locate.substring(left + 1, right)); + } else { + startPort = Integer.parseInt(aaf_locate.substring(left + 1, dash)); + endPort = Integer.parseInt(aaf_locate.substring(dash + 1, right)); + } + + } else { + slash = aaf_locate.indexOf('/', start); + if (slash == start) { + throw new LocatorException("Missing port before '/' in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } + if(slash < 0) { + startPort = endPort = Integer.parseInt(aaf_locate.substring(start)); + } else { + startPort = endPort = Integer.parseInt(aaf_locate.substring(start, slash)); + } + } + } else { + startPort = endPort = defaultPort; + } + } private class Host { private URI uri; diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java index 17f9bafb..fd8e99dc 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java @@ -7,9 +7,9 @@ * 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. @@ -29,274 +29,273 @@ import org.onap.aaf.cadi.routing.GreatCircle; import org.onap.aaf.misc.env.util.Split; /** - * This Locator is to handle Hot Peer load protection, when the Servers are + * This Locator is to handle Hot Peer load protection, when the Servers are * 1) Static * 2) Well known client URL - * + * * The intention is to change traffic over to the Hot Peer, if a server goes down, and reinstate * when it is back up. - * + * * Example of this kind of Service is a MS Certificate Server - * + * * @author Jonathan * * @param <CLIENT> */ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { - private final String[] urlstrs; - private final CLIENT[] clients; - private final long[] failures; - private final double[] distances; - private int preferred; - private long invalidateTime; - private Thread refreshThread; - protected Access access; + private final String[] urlstrs; + private final CLIENT[] clients; + private final long[] failures; + private final double[] distances; + private int preferred; + private long invalidateTime; + private Thread refreshThread; + protected Access access; - /** - * Construct: Expect one or more Strings in the form: - * 192.555.112.223:39/38.88087/-77.30122 - * separated by commas - * - * @param trans - * @param urlstr - * @param invalidateTime - * @param localLatitude - * @param localLongitude - * @throws LocatorException - */ - @SuppressWarnings("unchecked") - protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException { - this.access = access; - urlstrs = Split.split(',', urlstr); - clients = (CLIENT[])new Object[urlstrs.length]; - failures = new long[urlstrs.length]; - distances= new double[urlstrs.length]; - this.invalidateTime = invalidateTime; - - double distance = Double.MAX_VALUE; - for(int i=0;i<urlstrs.length;++i) { - String[] info = Split.split('/', urlstrs[i]); - if(info.length<3) { - throw new LocatorException("Configuration needs LAT and LONG, i.e. ip:port/lat/long"); - } - try { - clients[i] = _newClient(urlstrs[i]); - failures[i] = 0L; - } catch(LocatorException le) { - failures[i] = System.currentTimeMillis()+invalidateTime; - } - - double d = GreatCircle.calc(info[1],info[2],localLatitude,localLongitude); - distances[i]=d; - - // find preferred server - if(d<distance) { - preferred = i; - distance=d; - } - } - - access.printf(Level.INIT,"Preferred Client is %s",urlstrs[preferred]); - for(int i=0;i<urlstrs.length;++i) { - if(i!=preferred) { - access.printf(Level.INIT,"Alternate Client is %s",urlstrs[i]); - } - } - } - - protected abstract CLIENT _newClient(String hostInfo) throws LocatorException; - /** - * If client can reconnect, then return. Otherwise, destroy and return null; - * @param client - * @return - * @throws LocatorException - */ - protected abstract CLIENT _invalidate(CLIENT client); - - protected abstract void _destroy(CLIENT client); - - @Override - public Item best() throws LocatorException { - if(failures[preferred]==0L) { - return new HPItem(preferred); - } else { - long now = System.currentTimeMillis(); - double d = Double.MAX_VALUE; - int best = -1; - boolean tickle = false; - // try for best existing client - for(int i=0;i<urlstrs.length;++i) { - if(failures[i]<now && distances[i]<d) { - if(clients[i]!=null) { - best = i; - break; - } else { - tickle = true; // There's some failed clients which can be restored - } + /** + * Construct: Expect one or more Strings in the form: + * 192.555.112.223:39/38.88087/-77.30122 + * separated by commas + * + * @param trans + * @param urlstr + * @param invalidateTime + * @param localLatitude + * @param localLongitude + * @throws LocatorException + */ + @SuppressWarnings("unchecked") + protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException { + this.access = access; + urlstrs = Split.split(',', urlstr); + clients = (CLIENT[])new Object[urlstrs.length]; + failures = new long[urlstrs.length]; + distances= new double[urlstrs.length]; + this.invalidateTime = invalidateTime; + + double distance = Double.MAX_VALUE; + for(int i=0;i<urlstrs.length;++i) { + String[] info = Split.split('/', urlstrs[i]); + if(info.length<3) { + throw new LocatorException("Configuration needs LAT and LONG, i.e. ip:port/lat/long"); + } + try { + clients[i] = _newClient(urlstrs[i]); + failures[i] = 0L; + } catch(LocatorException le) { + failures[i] = System.currentTimeMillis()+invalidateTime; + } + + double d = GreatCircle.calc(info[1],info[2],localLatitude,localLongitude); + distances[i]=d; + + // find preferred server + if(d<distance) { + preferred = i; + distance=d; + } + } + + access.printf(Level.INIT,"Preferred Client is %s",urlstrs[preferred]); + for(int i=0;i<urlstrs.length;++i) { + if(i!=preferred) { + access.printf(Level.INIT,"Alternate Client is %s",urlstrs[i]); + } + } + } + + protected abstract CLIENT _newClient(String hostInfo) throws LocatorException; + /** + * If client can reconnect, then return. Otherwise, destroy and return null; + * @param client + * @return + * @throws LocatorException + */ + protected abstract CLIENT _invalidate(CLIENT client); + + protected abstract void _destroy(CLIENT client); + + @Override + public Item best() throws LocatorException { + if(failures[preferred]==0L) { + return new HPItem(preferred); + } else { + long now = System.currentTimeMillis(); + double d = Double.MAX_VALUE; + int best = -1; + boolean tickle = false; + // try for best existing client + for(int i=0;i<urlstrs.length;++i) { + if(failures[i]<now && distances[i]<d) { + if(clients[i]!=null) { + best = i; + break; + } else { + tickle = true; // There's some failed clients which can be restored } } - if(best<0 && tickle) { - tickle=false; - if(refresh()) { - // try again - for(int i=0;i<urlstrs.length;++i) { - if(failures[i]==0L && distances[i]<d) { - if(clients[i]!=null) { - best = i; - break; - } + } + if(best<0 && tickle) { + tickle=false; + if(refresh()) { + // try again + for(int i=0;i<urlstrs.length;++i) { + if(failures[i]==0L && distances[i]<d) { + if(clients[i]!=null) { + best = i; + break; } } } } - - /* - * If a valid client is available, but there are some that can refresh, return the client immediately - * but start a Thread to do the background Client setup. - */ - if(tickle) { - synchronized(clients) { - if(refreshThread==null) { - refreshThread = new Thread(new Runnable(){ - @Override - public void run() { - refresh(); - refreshThread = null; - } - }); - refreshThread.setDaemon(true); - refreshThread.start(); - } - } - } - - if(best<0) { - throw new LocatorException("No Clients available"); - } - - - return new HPItem(best); } - } - - @Override - public CLIENT get(Item item) throws LocatorException { - HPItem hpi = (HPItem)item; - CLIENT c = clients[hpi.idx]; - if(c==null) { - if(failures[hpi.idx]>System.currentTimeMillis()) { - throw new LocatorException("Client requested is invalid"); - } else { - synchronized(clients) { - c = _newClient(urlstrs[hpi.idx]); - failures[hpi.idx]=0L; + /* + * If a valid client is available, but there are some that can refresh, return the client immediately + * but start a Thread to do the background Client setup. + */ + if(tickle) { + synchronized(clients) { + if(refreshThread==null) { + refreshThread = new Thread(new Runnable(){ + @Override + public void run() { + refresh(); + refreshThread = null; + } + }); + refreshThread.setDaemon(true); + refreshThread.start(); } } - } else if(failures[hpi.idx]>0){ - throw new LocatorException("Client requested is invalid"); } - return c; - } - - public String info(Item item) { - HPItem hpi = (HPItem)item; - if(hpi!=null && hpi.idx<urlstrs.length) { - return urlstrs[hpi.idx]; - } else { - return "Invalid Item"; + + if(best<0) { + throw new LocatorException("No Clients available"); } + + return new HPItem(best); } + } + - @Override - public boolean hasItems() { - for(int i=0;i<clients.length;++i) { - if(clients[i]!=null && failures[i]==0L) { - return true; + @Override + public CLIENT get(Item item) throws LocatorException { + HPItem hpi = (HPItem)item; + CLIENT c = clients[hpi.idx]; + if(c==null) { + if(failures[hpi.idx]>System.currentTimeMillis()) { + throw new LocatorException("Client requested is invalid"); + } else { + synchronized(clients) { + c = _newClient(urlstrs[hpi.idx]); + failures[hpi.idx]=0L; } } - return false; - } - - @Override - public synchronized void invalidate(Item item) throws LocatorException { - HPItem hpi = (HPItem)item; - failures[hpi.idx] = System.currentTimeMillis() + invalidateTime; - CLIENT c = clients[hpi.idx]; - clients[hpi.idx] = _invalidate(c); + } else if(failures[hpi.idx]>0){ + throw new LocatorException("Client requested is invalid"); } - - @Override - public Item first() throws LocatorException { - return new HPItem(0); + return c; + } + + public String info(Item item) { + HPItem hpi = (HPItem)item; + if(hpi!=null && hpi.idx<urlstrs.length) { + return urlstrs[hpi.idx]; + } else { + return "Invalid Item"; } - - @Override - public Item next(Item item) throws LocatorException { - HPItem hpi = (HPItem)item; - if(++hpi.idx>=clients.length) { - return null; + } + + @Override + public boolean hasItems() { + for(int i=0;i<clients.length;++i) { + if(clients[i]!=null && failures[i]==0L) { + return true; } - return hpi; } - - @Override - public boolean refresh() { - boolean force = !hasItems(); // If no Items at all, reset - boolean rv = true; - long now = System.currentTimeMillis(); - for(int i=0;i<clients.length;++i) { - if(failures[i]>0L && (failures[i]<now || force)) { // retry - try { - synchronized(clients) { - if(clients[i]==null) { - clients[i]=_newClient(urlstrs[i]); - } - failures[i]=0L; + return false; + } + + @Override + public synchronized void invalidate(Item item) throws LocatorException { + HPItem hpi = (HPItem)item; + failures[hpi.idx] = System.currentTimeMillis() + invalidateTime; + CLIENT c = clients[hpi.idx]; + clients[hpi.idx] = _invalidate(c); + } + + @Override + public Item first() throws LocatorException { + return new HPItem(0); + } + + @Override + public Item next(Item item) throws LocatorException { + HPItem hpi = (HPItem)item; + if(++hpi.idx>=clients.length) { + return null; + } + return hpi; + } + + @Override + public boolean refresh() { + boolean force = !hasItems(); // If no Items at all, reset + boolean rv = true; + long now = System.currentTimeMillis(); + for(int i=0;i<clients.length;++i) { + if(failures[i]>0L && (failures[i]<now || force)) { // retry + try { + synchronized(clients) { + if(clients[i]==null) { + clients[i]=_newClient(urlstrs[i]); } - } catch (LocatorException e) { - failures[i]=now+invalidateTime; - rv = false; + failures[i]=0L; } + } catch (LocatorException e) { + failures[i]=now+invalidateTime; + rv = false; } } - return rv; } - - @Override - public void destroy() { - for(int i=0;i<clients.length;++i) { - if(clients[i]!=null) { - _destroy(clients[i]); - clients[i] = null; - } + return rv; + } + + @Override + public void destroy() { + for(int i=0;i<clients.length;++i) { + if(clients[i]!=null) { + _destroy(clients[i]); + clients[i] = null; } } + } - private static class HPItem implements Item { - private int idx; + private static class HPItem implements Item { + private int idx; - public HPItem(int i) { - idx = i; - } + public HPItem(int i) { + idx = i; } - + } - /* - * Convenience Functions - */ - public CLIENT bestClient() throws LocatorException { - return get(best()); - } - public boolean invalidate(CLIENT client) throws LocatorException { - for(int i=0;i<clients.length;++i) { - if(clients[i]==client) { // yes, "==" is appropriate here.. Comparing Java Object Reference - invalidate(new HPItem(i)); - return true; - } + /* + * Convenience Functions + */ + public CLIENT bestClient() throws LocatorException { + return get(best()); + } + + public boolean invalidate(CLIENT client) throws LocatorException { + for(int i=0;i<clients.length;++i) { + if(clients[i]==client) { // yes, "==" is appropriate here.. Comparing Java Object Reference + invalidate(new HPItem(i)); + return true; } - return false; } + return false; + } - }
\ No newline at end of file +}
\ No newline at end of file diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java index e6923ee1..1b9f6c3a 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java @@ -26,9 +26,7 @@ import java.io.IOException; import java.io.PrintStream; import java.net.HttpURLConnection; -import static org.junit.Assert.*; import static org.mockito.Mockito.*; -import static org.hamcrest.CoreMatchers.*; import org.junit.*; import org.mockito.*; @@ -67,6 +65,7 @@ public class JU_HBasicAuthSS { @Test public void test() throws IOException { // All the constructors accomplish the same thing + @SuppressWarnings("unused") HBasicAuthSS auth = new HBasicAuthSS(si); // TODO: While these test _should_ pass, and they _do_ pass on my local machine, they won't diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java new file mode 100644 index 00000000..646d63fa --- /dev/null +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java @@ -0,0 +1,320 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.http.test; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; + +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; +import org.mockito.*; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.LocatorException; +import org.onap.aaf.cadi.SecuritySetter; +import org.onap.aaf.cadi.client.EClient.Transfer; +import org.onap.aaf.cadi.client.Future; +import org.onap.aaf.cadi.http.HClient; +import org.onap.aaf.cadi.http.HClient.HFuture; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.rosetta.env.RosettaDF; +import org.onap.aaf.misc.rosetta.env.RosettaData; + +public class JU_HClient { + + @Mock private SecuritySetter<HttpURLConnection> ssMock; + @Mock private Transfer transferMock; + @Mock private HttpURLConnection hucMock; + @Mock private HttpServletResponse respMock; + @Mock private RosettaDF<HttpURLConnection> dfMock; + @Mock private RosettaData<HttpURLConnection> dataMock; + + private static final String uriString = "http://example.com:8080/path/to/a/file.txt"; + private static final String fragment = "fragment"; + private static final String method = "method"; + private static final String pathinfo = "pathinfo"; + private static final String queryParams = "queryParams"; + + private static final String errorString = "error string"; + private static final String successString = "success string"; + + private static final String tag1 = "tag1"; + private static final String tag2 = "tag2"; + private static final String value1 = "value1"; + private static final String value2 = "value2"; + + private URI uri; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + uri = new URI(uriString); + } + + @Test + public void accessorsMutatorsTest() throws LocatorException { + HClient client = new HClient(ssMock, uri, 0); + client.setFragment(fragment); + client.setMethod(method); + client.setPathInfo(pathinfo); + client.setPayload(transferMock); + client.setQueryParams(queryParams); + assertThat(client.getURI(), is(uri)); + assertThat(client.timeout(), is(0)); + assertThat(client.toString(), is("HttpURLConnection Client configured to " + uri.toString())); + } + + @Test + public void sendTest() throws LocatorException, APIException, URISyntaxException { + HClientStub client; + client = new HClientStub(ssMock, uri, 0, null); + client.send(); + + client.setPathInfo("/pathinfo"); + client.send(); + + client.setPathInfo("pathinfo"); + client.send(); + + client = new HClientStub(null, uri, 0, null); + client.send(); + + client.addHeader(tag1, value1); + client.addHeader(tag2, value2); + client.send(); + + client.setPayload(transferMock); + client.send(); + } + + @Test(expected = APIException.class) + public void sendThrows1Test() throws APIException, LocatorException, URISyntaxException { + HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); + client.send(); + } + + @Test(expected = APIException.class) + public void sendThrows2Test() throws APIException, LocatorException, URISyntaxException { + HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); + client.addHeader(tag1, value1); + client.addHeader(tag2, value2); + client.send(); + } + + @Test + public void futureCreateTest() throws LocatorException, CadiException, IOException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + HFuture<HttpURLConnection> future = (HFuture<HttpURLConnection>) client.futureCreate(HttpURLConnection.class); + + // Test a bad response code (default 0) without output + assertThat(future.get(0), is(false)); + assertThat(future.body().length(), is(0)); + + // Test a bad response code (default 0) with output + ByteArrayInputStream bais = new ByteArrayInputStream(errorString.getBytes()); + when(hucMock.getInputStream()).thenReturn(bais); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + + // Test a good response code + when(hucMock.getResponseCode()).thenReturn(201); + assertThat(future.get(0), is(true)); + } + + @Test + public void futureReadStringTest() throws LocatorException, CadiException, IOException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future<String> future = client.futureReadString(); + + // Test a bad response code (default 0) without output + assertThat(future.get(0), is(false)); + assertThat(future.body().length(), is(0)); + + // Test a bad response code (default 0) with output + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is(successString)); + } + + @Test + public void futureReadTest() throws LocatorException, CadiException, IOException, APIException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future<HttpURLConnection> future = client.futureRead(dfMock, null); + + // Test a bad response code (default 0) without output + assertThat(future.get(0), is(false)); + assertThat(future.body().length(), is(0)); + + // Test a bad response code (default 0) with output + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.in(null)).thenReturn(dataMock); + when(dataMock.load((InputStream)any())).thenReturn(dataMock); + when(dataMock.asObject()).thenReturn(hucMock); + when(dataMock.asString()).thenReturn(successString); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is(successString)); + } + + @Test + public void future1Test() throws LocatorException, CadiException, IOException, APIException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future<HttpURLConnection> future = client.future(hucMock); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is("200")); + + // Test a bad response code + when(hucMock.getResponseCode()).thenReturn(0); + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + } + + @Test + public void future2Test() throws LocatorException, CadiException, IOException, APIException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future<Void> future = client.future(respMock, 200); + + ServletOutputStream sos = new ServletOutputStream() { + @Override public void write(int arg0) throws IOException { } + }; + when(respMock.getOutputStream()).thenReturn(sos); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is(nullValue())); + + // Test a bad response code + when(hucMock.getResponseCode()).thenReturn(0); + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is("")); + } + + @Test + public void hfutureTest() throws CadiException, IOException, LocatorException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + HFutureStub future = new HFutureStub(client, hucMock); + assertThat(future.get(0), is(false)); + + // Test a bad response code (default 0) with output + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + + assertThat(future.get(0), is(false)); + + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + + StringBuilder sb = future.inputStreamToString(new ByteArrayInputStream(errorString.getBytes())); + assertThat(sb.toString(), is(errorString)); + + assertThat(future.code(), is(200)); + assertThat(future.huc(), is(hucMock)); + + assertThat(future.exception(), is(nullValue())); + assertThat(future.header("string"), is(nullValue())); + + // coverage... + future.setHuc(null); + future.close(); + } + + @Test + public void headerTest() throws LocatorException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + String tag1 = "tag1"; + String tag2 = "tag2"; + String value1 = "value1"; + String value2 = "value2"; + client.addHeader(tag1, value1); + client.addHeader(tag2, value2); + } + + @Test(expected = LocatorException.class) + public void throws1Test() throws LocatorException { + @SuppressWarnings("unused") + HClient client = new HClient(ssMock, null, 0); + } + + private class HClientStub extends HClient { + public HClientStub(SecuritySetter<HttpURLConnection> ss, URI uri, int connectTimeout, HttpURLConnection huc) throws LocatorException { + super(ss, uri, connectTimeout); + setHuc(huc); + } + public void setHuc(HttpURLConnection huc) { + Field field; + try { + field = HClient.class.getDeclaredField("huc"); + field.setAccessible(true); + field.set(this, huc); + field.setAccessible(false); + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); + fail("Caught an exception: " + e.getMessage()); + } + } + @Override + public HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException { + return hucMock; + } + } + + private class HFutureStub extends HFuture<HttpURLConnection> { + public HFutureStub(HClient hClient, HttpURLConnection huc) { + hClient.super(huc); + } + + @Override public String body() { return null; } + public void setHuc(HttpURLConnection huc) { this.huc = huc; } + } + +} diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java index d9f75ff1..a80e52f7 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java @@ -21,35 +21,105 @@ package org.onap.aaf.cadi.locator.test; +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; import java.net.URI; -import java.net.URL; -import java.net.URLConnection; -import org.junit.AfterClass; -import org.junit.Test; +import org.onap.aaf.cadi.LocatorException; import org.onap.aaf.cadi.PropAccess; import org.onap.aaf.cadi.Locator.Item; import org.onap.aaf.cadi.locator.DNSLocator; public class JU_DNSLocator { - - @AfterClass - public static void tearDownAfterClass() throws Exception { + + private PropAccess access; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); } @Test - public void test() { - // TODO: Actually test this class - Ian + public void test() throws LocatorException { + DNSLocator dl; + Item item; + URI uri; + + dl = new DNSLocator(access, "https", "localhost", "8100-8101"); - DNSLocator dl = new DNSLocator(new PropAccess(), "https", "aaf.it.att.com","8150-8152"); - try { - Item item = dl.best(); - URI uri = dl.get(item); - URL url = uri.toURL(); - URLConnection conn = url.openConnection(); - conn.connect(); - } catch (Exception e) { + item = dl.best(); + uri = dl.get(item); + assertThat(uri.toString(), is("https://127.0.0.1:8100")); + item = dl.best(); + assertThat(uri.toString(), is("https://127.0.0.1:8100")); + + assertThat(dl.hasItems(), is(true)); + for (item = dl.first(); item != null; item = dl.next(item)) { + dl.invalidate(item); } + assertThat(dl.hasItems(), is(false)); + + // This doesn't actually do anything besides increase coverage + dl.destroy(); + } + + @Test + public void constructorTest() throws LocatorException { + // For coverage + new DNSLocator(access, "https", "localhost", "8100"); + new DNSLocator(access, "https", "localhost", "8100-8101"); + + new DNSLocator(access, "http:localhost"); + new DNSLocator(access, "https:localhost"); + new DNSLocator(access, "https:localhost:8100"); + new DNSLocator(access, "https:localhost:[8100]"); + new DNSLocator(access, "https:localhost:[8100-8101]"); + new DNSLocator(access, "https:localhost:8000/"); + } + + @Test + public void refreshTest() throws LocatorException { + DNSLocator dl = new DNSLocator(access, "https", "bogushost", "8100-8101"); + assertThat(dl.refresh(), is(false)); + } + + @Test(expected = LocatorException.class) + public void throws1Test() throws LocatorException { + new DNSLocator(access, null); + } + + @Test(expected = LocatorException.class) + public void throws2Test() throws LocatorException { + new DNSLocator(access, "ftp:invalid"); + } + + @Test(expected = LocatorException.class) + public void throws3Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[8100"); + } + + @Test(expected = LocatorException.class) + public void throws4Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[]"); + } + + @Test(expected = LocatorException.class) + public void throws5Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[8100-]"); + } + + @Test(expected = LocatorException.class) + public void throws6Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[-8101]"); + } + + @Test(expected = LocatorException.class) + public void throws7Test() throws LocatorException { + new DNSLocator(access, "https:localhost:/"); } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java new file mode 100644 index 00000000..1478cafe --- /dev/null +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java @@ -0,0 +1,150 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.locator.test; + +import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.*; +import org.junit.*; +import org.mockito.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.onap.aaf.cadi.Access; +import org.onap.aaf.cadi.Locator; +import org.onap.aaf.cadi.LocatorException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.http.HClient; +import org.onap.aaf.cadi.http.HX509SS; +import org.onap.aaf.cadi.locator.HClientHotPeerLocator; + +public class JU_HClientHotPeerLocator { + + @Mock private HX509SS ssMock; + + private PropAccess access; + private ByteArrayOutputStream outStream; + + // Note: - The IP and port are irrelevant for these tests + private static final String goodURL1 = "fakeIP1:fakePort1/38/-90"; // Approx St Louis + private static final String goodURL2 = "fakeIP2:fakePort2/33/-96"; // Approx Dallas + private static final String badURL = "~%$!@#$//"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + outStream = new ByteArrayOutputStream(); + access = new PropAccess(new PrintStream(outStream), new String[0]); + } + + @Test + public void test() throws LocatorException { + HClientHotPeerLocator loc; + String urlStr = goodURL1 + ',' + goodURL2; + loc = new HClientHotPeerLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); + assertThat(loc.hasItems(), is(true)); + + String[] messages = outStream.toString().split("\n"); + String preffered = messages[0].split(" ", 4)[3]; + String alternate = messages[1].split(" ", 4)[3]; + assertThat(preffered, is("Preferred Client is " + goodURL1)); + assertThat(alternate, is("Alternate Client is " + goodURL2)); + + HClient firstClient = loc.get(loc.first()); + HClient bestClient = loc.bestClient(); + assertThat(bestClient, is(firstClient)); + + Locator.Item item = loc.first(); + assertThat(loc.info(item), is(goodURL1)); + + item = loc.next(item); + assertThat(loc.info(item), is(goodURL2)); + + item = loc.next(item); + assertThat(item, is(nullValue())); + assertThat(loc.info(item), is("Invalid Item")); + + item = loc.first(); + loc.invalidate(item); + + loc.invalidate(loc.bestClient()); + loc.invalidate(loc.get(loc.next(item))); + loc.destroy(); + } + + @Test(expected = LocatorException.class) + public void failuresTest() throws LocatorException { + HClientHotPeerLocator loc; + String urlStr = goodURL1 + ',' + goodURL2 + ',' + badURL; + loc = new HClientHotPeerLocator(access, urlStr, 1000000, "38.627", "-90.199", ssMock); + String[] messages = outStream.toString().split("\n"); + String preffered = messages[0].split(" ", 4)[3]; + String alternate1 = messages[1].split(" ", 4)[3]; + String alternate2 = messages[2].split(" ", 4)[3]; + assertThat(preffered, is("Preferred Client is " + badURL)); + assertThat(alternate1, is("Alternate Client is " + goodURL1)); + assertThat(alternate2, is("Alternate Client is " + goodURL2)); + + outStream.reset(); + + loc.invalidate(loc.first()); + + loc.destroy(); + loc.best(); + } + + @Test + public void hasNoItemTest() throws LocatorException { + HClientHotPeerLocator loc; + loc = new HClientHotPeerLocator(access, badURL, 0, "38.627", "-90.199", ssMock); + assertThat(loc.hasItems(), is(false)); + loc.invalidate(loc.first()); + } + + @Test(expected = LocatorException.class) + public void invalidClientTest() throws LocatorException { + @SuppressWarnings("unused") + HClientHotPeerLocator loc = new HClientHotPeerLocator(access, "InvalidClient", 0, "38.627", "-90.199", ssMock); + } + + @Test(expected = LocatorException.class) + public void coverageTest() throws LocatorException { + CoverageLocator loc; + String urlStr = goodURL1 + ',' + goodURL2; + loc = new CoverageLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); + assertThat(loc._invalidate(null), is(nullValue())); + loc._destroy(null); + + loc._newClient("bad string"); + } + + private class CoverageLocator extends HClientHotPeerLocator { + public CoverageLocator(Access access, String urlstr, long invalidateTime, String localLatitude, + String localLongitude, HX509SS ss) throws LocatorException { + super(access, urlstr, invalidateTime, localLatitude, localLongitude, ss); + } + public HClient _newClient(String clientInfo) throws LocatorException { return super._newClient(clientInfo); } + public HClient _invalidate(HClient client) { return super._invalidate(client); } + public void _destroy(HClient client) { super._destroy(client); } + } +} diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java b/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java index be1e739b..c65a9b22 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java @@ -60,7 +60,6 @@ public abstract class AbsUserCache<PERM extends Permission> { private Clean clean; protected Access access; -// private final static Permission teaser = new LocalPermission("***NoPERM****"); protected AbsUserCache(Access access, long cleanInterval, int highCount, int usageCount) { this.access = access; @@ -154,7 +153,7 @@ public abstract class AbsUserCache<PERM extends Permission> { } Miss miss = missMap.get(mkey); if(miss==null) { - missMap.put(mkey, new Miss(bs,clean==null?MIN_INTERVAL:clean.timeInterval)); + missMap.put(mkey, new Miss(bs,clean==null?MIN_INTERVAL:clean.timeInterval,key)); return true; } return miss.mayContinue(); @@ -322,7 +321,6 @@ public abstract class AbsUserCache<PERM extends Permission> { for(User<PERM> user : al) { ++total; if(user.count>usageTriggerCount) { - // access.log(Level.AUDIT, "Checking Thread", new Date(now)); boolean touched = false, removed=false; if(user.principal instanceof CachedPrincipal) { CachedPrincipal cp = (CachedPrincipal)user.principal; @@ -333,7 +331,6 @@ public abstract class AbsUserCache<PERM extends Permission> { break; case REVALIDATED: user.resetCount(); - // access.log(Level.AUDIT, "CACHE revalidated credentials"); touched = true; break; default: @@ -346,9 +343,7 @@ public abstract class AbsUserCache<PERM extends Permission> { } } - // access.log(Level.AUDIT, "User Perm Expires", new Date(user.permExpires)); if(!removed && lur!=null && user.permExpires<= now ) { - // access.log(Level.AUDIT, "Reloading"); if(lur.reload(user).equals(Resp.REVALIDATED)) { user.renewPerm(); access.log(Level.DEBUG, "Reloaded Perms for",user); @@ -376,12 +371,17 @@ public abstract class AbsUserCache<PERM extends Permission> { keys.addAll(missMap.keySet()); for(String key : keys) { Miss m = missMap.get(key); - if(m!=null && m.timestamp<System.currentTimeMillis()) { - synchronized(missMap) { - missMap.remove(key); + if(m!=null) { + long timeLeft = m.timestamp - System.currentTimeMillis(); + if(timeLeft<0) { + synchronized(missMap) { + missMap.remove(key); + } + access.log(Level.INFO, m.name, " has been removed from Missed Credential Map (" + m.tries + " invalid tries)"); + ++miss; + } else { + access.log(Level.INFO, m.name, " remains in Missed Credential Map (" + m.tries + " invalid tries) for " + (timeLeft/1000) + " more seconds"); } - access.log(Level.INFO, key, "has been removed from Missed Credential Map (" + m.tries + " invalid tries)"); - ++miss; } } } @@ -419,11 +419,14 @@ public abstract class AbsUserCache<PERM extends Permission> { private long timetolive; private long tries; + + private final String name; - public Miss(byte[] first, long timeInterval) { + public Miss(final byte[] first, final long timeInterval, final String name) { timestamp = System.currentTimeMillis() + timeInterval; this.timetolive = timeInterval; tries = 0L; + this.name = name; } @@ -437,6 +440,7 @@ public abstract class AbsUserCache<PERM extends Permission> { } return true; } + } /** diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java b/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java index 99bdb49c..ea126f54 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java @@ -47,8 +47,7 @@ import org.onap.aaf.cadi.util.JsonOutputStream; */ public class CmdLine { - public static Access access; - + private static boolean systemExit = true; /** * @param args */ @@ -349,10 +348,13 @@ public class CmdLine { System.out.println(" sha256 <text> <salts(s)> (Digest String into SHA256 Hash)"); System.out.println(" md5 <text> (Digest String into MD5 Hash)"); } - String forceExit = access.getProperty("force_exit", null); - if (forceExit == null) { + if (systemExit) { System.exit(1); } } + public static void setSystemExit(boolean shouldExit) { + systemExit = shouldExit; + } + } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java index 26ad758f..d7c7526f 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java @@ -65,6 +65,14 @@ import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf; */ public class Config { + private static final String AAF_V2_0 = "org.onap.aaf.cadi.aaf.v2_0"; + private static final String AAF_V2_0_AAFCON = AAF_V2_0+".AAFCon"; + private static final String AAF_V2_0_AAF_LUR_PERM = AAF_V2_0+".AAFLurPerm"; + private static final String OAUTH = "org.onap.auth.oauth"; + private static final String OAUTH_TOKEN_MGR = OAUTH+".TokenMgr"; + private static final String OAUTH_HTTP_TAF = OAUTH+".OAuth2HttpTaf"; + private static final String OAUTH_DIRECT_TAF = OAUTH+".OAuthDirectTAF"; + public static final String UTF_8 = "UTF-8"; // Property Names associated with configurations. @@ -142,14 +150,20 @@ public class Config { public static final String AAF_APPPASS = "aaf_password"; public static final String AAF_LUR_CLASS = "aaf_lur_class"; public static final String AAF_TAF_CLASS = "aaf_taf_class"; - public static final String AAF_TAF_CLASS_DEF = "org.osaaf.cadi.aaf.v2_0.AAFTaf"; public static final String AAF_CONNECTOR_CLASS = "aaf_connector_class"; public static final String AAF_LOCATOR_CLASS = "aaf_locator_class"; public static final String AAF_CONN_TIMEOUT = "aaf_conn_timeout"; public static final String AAF_CONN_TIMEOUT_DEF = "3000"; public static final String AAF_CONN_IDLE_TIMEOUT = "aaf_conn_idle_timeout"; // only for Direct Jetty Access. public static final String AAF_CONN_IDLE_TIMEOUT_DEF = "10000"; // only for Direct Jetty Access. - + + // Default Classes: These are for Class loading to avoid direct compile links + public static final String AAF_TAF_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFTaf"; + public static final String AAF_LOCATOR_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFLocator"; + public static final String CADI_OLUR_CLASS_DEF = "org.onap.aaf.cadi.olur.OLur"; + public static final String CADI_OBASIC_HTTP_TAF_DEF = "org.onap.aaf.cadi.obasic.OBasicHttpTaf"; + public static final String CADI_AAF_CON_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFCon"; + public static final String AAF_CALL_TIMEOUT = "aaf_timeout"; public static final String AAF_CALL_TIMEOUT_DEF = "5000"; public static final String AAF_USER_EXPIRES = "aaf_user_expires"; @@ -184,7 +198,7 @@ public class Config { private static String defaultRealm="none"; public static final String AAF_DOMAIN_SUPPORT = "aaf_domain_support"; - public static final String AAF_DOMAIN_SUPPORT_DEF = ".com"; + public static final String AAF_DOMAIN_SUPPORT_DEF = ".com:.org"; // OAUTH2 public static final String AAF_OAUTH2_TOKEN_URL = "aaf_oauth2_token_url"; @@ -200,19 +214,11 @@ public class Config { public static void setDefaultRealm(Access access) throws CadiException { try { - boolean hasCSP; - try { - Class.forName("org.osaaf.cadi.taf.csp.CSPTaf"); - hasCSP=true; - } catch(ClassNotFoundException e) { - hasCSP = logProp(access,Config.CSP_DOMAIN, null)!=null; - } defaultRealm = logProp(access,Config.AAF_DEFAULT_REALM, - hasCSP?"csp.att.com": - logProp(access,Config.BASIC_REALM, - logProp(access,HOSTNAME,InetAddress.getLocalHost().getHostName()) - ) - ); + logProp(access,Config.BASIC_REALM, + logProp(access,HOSTNAME,InetAddress.getLocalHost().getHostName()) + ) + ); } catch (UnknownHostException e) { //defaultRealm="none"; } @@ -223,7 +229,7 @@ public class Config { ///////////////////////////////////////////////////// // Setup AAFCon for any following ///////////////////////////////////////////////////// - Class<?> aafConClass = loadClass(access,"org.onap.aaf.cadi.aaf.v2_0.AAFCon"); + Class<?> aafConClass = loadClass(access,CADI_AAF_CON_DEF); Object aafcon = null; if(con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) { aafcon = con; @@ -312,7 +318,7 @@ public class Config { if(!hasOAuthDirectTAF) { if(basic_realm!=null) { @SuppressWarnings("unchecked") - Class<HttpTaf> obasicCls = (Class<HttpTaf>)loadClass(access,"org.osaaf.cadi.obasic.OBasicHttpTaf"); + Class<HttpTaf> obasicCls = (Class<HttpTaf>)loadClass(access,CADI_OBASIC_HTTP_TAF_DEF); if(obasicCls!=null) { try { String tokenurl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL, null); @@ -386,7 +392,7 @@ public class Config { String oauth_token_url = logProp(access,Config.AAF_OAUTH2_TOKEN_URL,null); Class<?> oadtClss; try { - oadtClss = Class.forName("org.osaaf.authz.oauth.OAuthDirectTAF"); + oadtClss = Class.forName(OAUTH_DIRECT_TAF); } catch (ClassNotFoundException e1) { oadtClss = null; } @@ -401,9 +407,9 @@ public class Config { } else if(oauth_token_url!=null) { String oauth_introspect_url = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL,null); @SuppressWarnings("unchecked") - Class<HttpTaf> oaTCls = (Class<HttpTaf>)loadClass(access,"org.osaaf.cadi.oauth.OAuth2HttpTaf"); + Class<HttpTaf> oaTCls = (Class<HttpTaf>)loadClass(access,OAUTH_HTTP_TAF); if(oaTCls!=null) { - Class<?> oaTTmgrCls = loadClass(access, "org.osaaf.cadi.oauth.TokenMgr"); + Class<?> oaTTmgrCls = loadClass(access, OAUTH_TOKEN_MGR); if(oaTTmgrCls!=null) { try { Method oaTTmgrGI = oaTTmgrCls.getMethod("getInstance",PropAccess.class,String.class,String.class); @@ -516,7 +522,7 @@ public class Config { String introspect_url = logProp(access,AAF_OAUTH2_INTROSPECT_URL, null); if(token_url!=null && introspect_url !=null) { try { - Class<?> olurCls = loadClass(access, "org.osaaf.cadi.olur.OLur"); + Class<?> olurCls = loadClass(access, CADI_OLUR_CLASS_DEF); if(olurCls!=null) { Constructor<?> olurCnst = olurCls.getConstructor(PropAccess.class,String.class,String.class); Lur olur = (Lur)olurCnst.newInstance(access,token_url,introspect_url); @@ -558,15 +564,15 @@ public class Config { if(aafURL==null) { access.log(Level.INIT,"No AAF LUR properties, AAF will not be loaded"); } else {// There's an AAF_URL... try to configure an AAF - String aafLurClassStr = logProp(access,AAF_LUR_CLASS,"org.osaaf.cadi.aaf.v2_0.AAFLurPerm"); + String aafLurClassStr = logProp(access,AAF_LUR_CLASS,AAF_V2_0_AAF_LUR_PERM); ////////////AAF Lur 2.0 ///////////// - if(aafLurClassStr!=null && aafLurClassStr.startsWith("org.osaaf.cadi.aaf.v2_0")) { + if(aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) { try { Object aafcon = loadAAFConnector(si, aafURL); if(aafcon==null) { access.log(Level.INIT,"AAF LUR class,",aafLurClassStr,"cannot be constructed without valid AAFCon object."); } else { - Class<?> aafAbsAAFCon = loadClass(access, "org.osaaf.cadi.aaf.v2_0.AAFCon"); + Class<?> aafAbsAAFCon = loadClass(access, AAF_V2_0_AAFCON); if(aafAbsAAFCon!=null) { Method mNewLur = aafAbsAAFCon.getMethod("newLur"); Object aaflur = mNewLur.invoke(aafcon); @@ -632,30 +638,31 @@ public class Config { return false; } - private static final String COM_ATT_CADI_AAF_V2_0_AAF_CON_HTTP = "org.osaaf.cadi.aaf.v2_0.AAFConHttp"; + private static final String AAF_V2_0_AAF_CON_HTTP = "org.onap.aaf.cadi.aaf.v2_0.AAFConHttp"; + public static Object loadAAFConnector(SecurityInfoC<HttpURLConnection> si, String aafURL) { Access access = si.access; Object aafcon = null; Class<?> aafConClass = null; try { - if(aafURL!=null) { - String aafConnector = access.getProperty(AAF_CONNECTOR_CLASS, COM_ATT_CADI_AAF_V2_0_AAF_CON_HTTP); - if(COM_ATT_CADI_AAF_V2_0_AAF_CON_HTTP.equals(aafConnector)) { - aafConClass = loadClass(access, COM_ATT_CADI_AAF_V2_0_AAF_CON_HTTP); - if(aafConClass!=null) { - for(Constructor<?> c : aafConClass.getConstructors()) { + if (aafURL!=null) { + String aafConnector = access.getProperty(AAF_CONNECTOR_CLASS, AAF_V2_0_AAF_CON_HTTP); + if (AAF_V2_0_AAF_CON_HTTP.equals(aafConnector)) { + aafConClass = loadClass(access, AAF_V2_0_AAF_CON_HTTP); + if (aafConClass != null) { + for (Constructor<?> c : aafConClass.getConstructors()) { List<Object> lo = new ArrayList<Object>(); - for(Class<?> pc : c.getParameterTypes()) { - if(pc.equals(PropAccess.class)) { + for (Class<?> pc : c.getParameterTypes()) { + if (pc.equals(Access.class)) { lo.add(access); - } else if(pc.equals(Locator.class)) { + } else if (pc.equals(Locator.class)) { lo.add(loadLocator(si, aafURL)); } else { continue; } } - if(c.getParameterTypes().length!=lo.size()) { + if (c.getParameterTypes().length != lo.size()) { continue; // back to another Constructor } else { aafcon = c.newInstance(lo.toArray()); @@ -664,13 +671,13 @@ public class Config { } } } - if(aafcon!=null) { - String mechid = logProp(access,Config.AAF_APPID, null); + if (aafcon != null) { + String mechid = logProp(access, Config.AAF_APPID, null); String pass = access.getProperty(Config.AAF_APPPASS, null); - if(mechid!=null && pass!=null) { + if (mechid != null && pass != null) { try { Method basicAuth = aafConClass.getMethod("basicAuth", String.class, String.class); - basicAuth.invoke(aafcon, mechid,pass); + basicAuth.invoke(aafcon, mechid, pass); } catch (NoSuchMethodException nsme) { // it's ok, don't use } @@ -678,9 +685,9 @@ public class Config { } } } catch (Exception e) { - access.log(e,"AAF Connector could not be constructed with given Constructors."); + access.log(e, "AAF Connector could not be constructed with given Constructors."); } - + return aafcon; } @@ -713,7 +720,7 @@ public class Config { } try { - Class<?> lcls = loadClass(access,"org.onap.aaf.cadi.aaf.v2_0.AAFLocator"); + Class<?> lcls = loadClass(access,AAF_LOCATOR_CLASS_DEF); if(lcls==null) { throw new CadiException("Need to include aaf-cadi-aaf jar for AAFLocator"); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java index 2d252ea9..b34d096d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java @@ -224,8 +224,8 @@ public class SecurityInfo { } TrustManager tms[] = tmf.getTrustManagers(); - if(tms != null) { - tm = new X509TrustManager[(tms == null) ? 0 : tms.length]; + if(tms != null && tms.length>0) { + tm = new X509TrustManager[tms.length]; for(int i = 0; i < tms.length; ++i) { try { tm[i] = (X509TrustManager)tms[i]; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AUTHZServlet.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AUTHZServlet.java index f7c4b7f1..f72a99bf 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AUTHZServlet.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/AUTHZServlet.java @@ -47,7 +47,7 @@ public class AUTHZServlet<S extends Servlet> implements Servlet { delegate = null; } RolesAllowed rolesAllowed = cls.getAnnotation(RolesAllowed.class); - if(rolesAllowed == null) { + if (rolesAllowed == null) { roles = null; } else { roles = rolesAllowed.value(); @@ -55,7 +55,9 @@ public class AUTHZServlet<S extends Servlet> implements Servlet { } public void init(ServletConfig sc) throws ServletException { - if(delegate == null) throw new ServletException("Invalid Servlet Delegate"); + if (delegate == null) { + throw new ServletException("Invalid Servlet Delegate"); + } delegate.init(sc); } @@ -68,27 +70,24 @@ public class AUTHZServlet<S extends Servlet> implements Servlet { } public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { - if(roles==null) { - delegate.service(req,resp); - } else { // Validate - try { - HttpServletRequest hreq = (HttpServletRequest)req; - boolean proceed = false; - for(String role : roles) { - if(hreq.isUserInRole(role)) { - proceed = true; - break; - } - } - if(proceed) { - delegate.service(req,resp); - } else { - //baseRequest.getServletContext().log(hreq.getUserPrincipal().getName()+" Refused " + roles); - ((HttpServletResponse)resp).sendError(403); // forbidden + if (roles == null) { + delegate.service(req, resp); + return; + } + + // Validate + try { + HttpServletRequest hreq = (HttpServletRequest)req; + for (String role : roles) { + if (hreq.isUserInRole(role)) { + delegate.service(req, resp); + return; } - } catch(ClassCastException e) { - throw new ServletException("JASPIServlet only supports HTTPServletRequest/HttpServletResponse"); } + + ((HttpServletResponse)resp).sendError(403); // forbidden + } catch (ClassCastException e) { + throw new ServletException("JASPIServlet only supports HTTPServletRequest/HttpServletResponse"); } } @@ -96,5 +95,4 @@ public class AUTHZServlet<S extends Servlet> implements Servlet { delegate.destroy(); } - } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java index d1c40b23..006d6b4e 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java @@ -100,6 +100,7 @@ public class CadiHTTPManip { } SecurityInfoC<HttpURLConnection> si; si = SecurityInfoC.instance(access, HttpURLConnection.class); + lur = Config.configLur(si, con, additionalTafLurs); tc.setLur(lur); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapPermConverter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapPermConverter.java index 052b9ff1..f0786b12 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapPermConverter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapPermConverter.java @@ -34,7 +34,7 @@ public class MapPermConverter implements PermConverter { * @param value */ public MapPermConverter() { - map = new HashMap<String,String>(); + map = new HashMap<>(); } /** @@ -48,7 +48,7 @@ public class MapPermConverter implements PermConverter { public String convert(String minimal) { String rv = map.get(minimal); - return rv==null?minimal:rv; + return (rv == null) ? minimal : rv; } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/NullPermConverter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/NullPermConverter.java index 211a4bfe..8b70d95d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/NullPermConverter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/NullPermConverter.java @@ -7,9 +7,9 @@ * 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. @@ -23,18 +23,20 @@ package org.onap.aaf.cadi.filter; /** - * A NullPermConverter - * + * A NullPermConverter + * * Obey the PermConverter Interface, but passed in "minimal" String is not converted. - * + * * @author Jonathan * */ public class NullPermConverter implements PermConverter { - private NullPermConverter() {} private static final NullPermConverter singleton = new NullPermConverter(); - public static NullPermConverter singleton() {return singleton;} + + private NullPermConverter() {} + + public static NullPermConverter singleton() { return singleton; } public String convert(String minimal) { return minimal; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PathFilter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PathFilter.java index c508a5ce..cf87c840 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PathFilter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/PathFilter.java @@ -7,9 +7,9 @@ * 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. @@ -39,44 +39,44 @@ import org.onap.aaf.cadi.config.Config; /** * PathFilter - * + * * This class implements Servlet Filter, and uses AAF to validate access to a Path. - * + * * This class can be used in a standard J2EE Servlet manner. - * + * * @author Jonathan, collaborating with Xue Gao * */ public class PathFilter implements Filter { - private ServletContext context; - private String aaf_type; - private String not_authorized_msg; private final Log log; + private ServletContext context; + private String aafType; + private String notAuthorizedMsg; + /** * Construct a viable Filter for installing in Container WEB.XML, etc. - * + * */ public PathFilter() { log = new Log() { public void info(String ... msg) { - context.log(build("INFO:",msg)); + context.log(build("INFO:", msg)); } public void audit(String ... msg) { - context.log(build("AUDIT:",msg)); + context.log(build("AUDIT:", msg)); } private String build(String type, String []msg) { StringBuilder sb = new StringBuilder(type); - for(String s : msg) { + for (String s : msg) { sb.append(' '); sb.append(s); } return sb.toString(); } - }; } - + /** * Filter that can be constructed within Java * @param access @@ -91,10 +91,10 @@ public class PathFilter implements Filter { } }; } - + /** * Init - * + * * Standard Filter "init" call with FilterConfig to obtain properties. POJOs can construct a * FilterConfig with the mechanism of their choice, and standard J2EE Servlet engines utilize this * mechanism already. @@ -103,16 +103,16 @@ public class PathFilter implements Filter { // need the Context for Logging, instantiating ClassLoader, etc context = filterConfig.getServletContext(); StringBuilder sb = new StringBuilder(); - StringBuilder err = new StringBuilder(); + StringBuilder err = new StringBuilder(); Object attr = context.getAttribute(Config.PATHFILTER_NS); - if(attr==null) { + if (attr == null) { err.append("PathFilter - pathfilter_ns is not set"); } else { - sb.append(attr.toString()); + sb.append(attr.toString()); } attr = context.getAttribute(Config.PATHFILTER_STACK); - if(attr==null) { + if (attr == null) { log.info("PathFilter - No pathfilter_stack set, ignoring"); } else { sb.append('.'); @@ -120,7 +120,7 @@ public class PathFilter implements Filter { } attr = context.getAttribute(Config.PATHFILTER_URLPATTERN); - if(attr==null) { + if (attr == null) { log.info("PathFilter - No pathfilter_urlpattern set, defaulting to 'urlpattern'"); sb.append(".urlpattern"); } else { @@ -128,20 +128,20 @@ public class PathFilter implements Filter { sb.append(attr.toString()); } - log.info("PathFilter - AAF Permission Type is",sb.toString()); - + log.info("PathFilter - AAF Permission Type is", sb.toString()); + sb.append('|'); - - aaf_type = sb.toString(); + + aafType = sb.toString(); attr = context.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG); - if(attr==null) { - not_authorized_msg = "Forbidden - Not Authorized to access this Path"; + if (attr == null) { + notAuthorizedMsg = "Forbidden - Not Authorized to access this Path"; } else { - not_authorized_msg = attr.toString(); + notAuthorizedMsg = attr.toString(); } - if(err.length()>0) { + if (err.length() > 0) { throw new ServletException(err.toString()); } } @@ -153,7 +153,7 @@ public class PathFilter implements Filter { /** * doFilter - * + * * This is the standard J2EE invocation. Analyze the request, modify response as necessary, and * only call the next item in the filterChain if request is suitably Authenticated. */ @@ -161,23 +161,20 @@ public class PathFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest)request; HttpServletResponse hresp = (HttpServletResponse)response; - String perm = aaf_type+hreq.getPathInfo()+'|'+hreq.getMethod(); - if(hreq.isUserInRole(perm)) { + String perm = aafType + hreq.getPathInfo() + '|' + hreq.getMethod(); + if (hreq.isUserInRole(perm)) { chain.doFilter(request, response); } else { - log.audit("PathFilter has denied",hreq.getUserPrincipal().getName(),"access to",perm); - hresp.sendError(403,not_authorized_msg); + log.audit("PathFilter has denied", hreq.getUserPrincipal().getName(), "access to", perm); + hresp.sendError(403, notAuthorizedMsg); } } /** - * Containers call "destroy" when time to cleanup + * Containers call "destroy" when time to cleanup */ public void destroy() { log.info("PathFilter destroyed."); } - - } - diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java index c1a27fa7..0f9adb94 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java @@ -7,9 +7,9 @@ * 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. @@ -38,10 +38,9 @@ import org.onap.aaf.cadi.User; import org.onap.aaf.cadi.Access.Level; import org.onap.aaf.cadi.config.Config; - /** * An in-memory Lur that can be configured locally with User info via properties, similar to Tomcat-users.xml mechanisms. - * + * * @author Jonathan * */ @@ -50,120 +49,69 @@ public final class LocalLur extends AbsUserCache<LocalPermission> implements Lur public static final String COLON = "\\s*:\\s*"; public static final String COMMA = "\\s*,\\s*"; public static final String PERCENT = "\\s*%\\s*"; - + // Use to quickly determine whether any given group is supported by this LUR private final Set<String> supportingGroups; - private String supportedRealm; - + private String supportedRealm; + /** * Construct by building structure, see "build" - * + * * Reconstruct with "build" - * - * @param userProperty - * @param groupProperty + * + * @param userProperties + * @param groupProperties * @param decryptor * @throws IOException */ - public LocalLur(Access access, String userProperty, String groupProperty) throws IOException { + public LocalLur(Access access, String userProperties, String groupProperties) throws IOException { super(access, 0, 0, Integer.MAX_VALUE); // data doesn't expire supportedRealm = access.getProperty(Config.BASIC_REALM, "localized"); - supportingGroups = new TreeSet<String>(); - - if(userProperty!=null) { - // For each User name... - for(String user : userProperty.trim().split(SEMI)) { - String[] us = user.split(COLON,2); - String[] userpass = us[0].split(PERCENT,2); - String u; - User<LocalPermission> usr; - if(userpass.length>1) { - if(userpass.length>0 && userpass[0].indexOf('@')<0) { - userpass[0]=userpass[0] + '@' + access.getProperty(Config.AAF_DEFAULT_REALM,Config.getDefaultRealm()); - } - - u = userpass[0]; - byte[] pass = access.decrypt(userpass[1], true).getBytes(); - usr = new User<LocalPermission>(new ConfigPrincipal(u, pass)); - } else { - u = us[0]; - usr = new User<LocalPermission>(new ConfigPrincipal(u, (byte[])null)); - } - addUser(usr); - access.log(Level.INIT, "Local User:",usr.principal); - - if(us.length>1) { - Map<String, Permission> newMap = usr.newMap(); - for(String group : us[1].split(COMMA)) { - supportingGroups.add(group); - usr.add(newMap,new LocalPermission(group)); - } - usr.setMap(newMap); - } - } + supportingGroups = new TreeSet<>(); + + if (userProperties != null) { + parseUserProperties(userProperties); } - if(groupProperty!=null) { - // For each Group name... - for(String group : groupProperty.trim().split(SEMI)) { - String[] gs = group.split(COLON,2); - if(gs.length>1) { - supportingGroups.add(gs[0]); - LocalPermission p = new LocalPermission(gs[0]); - // Add all users (known by comma separators) - - for(String grpMem : gs[1].split(COMMA)) { - // look for password, if so, put in passMap - String[] userpass = grpMem.split(PERCENT,2); - if(userpass.length>0 && userpass[0].indexOf('@')<0) { - userpass[0]=userpass[0] + '@' + access.getProperty(Config.AAF_DEFAULT_REALM,Config.getDefaultRealm()); - } - User<LocalPermission> usr = null; - if(userpass.length>1) { - byte[] pass = access.decrypt(userpass[1], true).getBytes(); - usr = getUser(userpass[0],pass); - if(usr==null)addUser(usr=new User<LocalPermission>(new ConfigPrincipal(userpass[0],pass))); - else usr.principal=new ConfigPrincipal(userpass[0],pass); - } else { - addUser(usr=new User<LocalPermission>(new ConfigPrincipal(userpass[0],(byte[])null))); - } - usr.add(p); - access.log(Level.INIT, "Local User:",usr.principal); - } - } - } + + if (groupProperties != null) { + parseGroupProperties(groupProperties); } } - + public boolean validate(String user, CredVal.Type type, byte[] cred, Object state) { - User<LocalPermission> usr = getUser(user,cred); - switch(type) { - case PASSWORD: - // covers null as well as bad pass - if(usr!=null && cred!=null && usr.principal instanceof ConfigPrincipal) { - return Hash.isEqual(cred,((ConfigPrincipal)usr.principal).getCred()); - } - break; + if (cred == null) { + return false; + } + User<LocalPermission> usr = getUser(user, cred); + if (usr == null) { + return false; + } + // covers null as well as bad pass + if ((type == Type.PASSWORD) && (usr.principal instanceof ConfigPrincipal)) {; + return Hash.isEqual(cred, ((ConfigPrincipal)usr.principal).getCred()); } return false; } // @Override public boolean fish(Principal bait, Permission pond) { - if(pond == null) { + if (pond == null) { return false; } - if(handles(bait) && pond instanceof LocalPermission) { // local Users only have LocalPermissions - User<LocalPermission> user = getUser(bait); - return user==null?false:user.contains((LocalPermission)pond); + if (handles(bait) && pond instanceof LocalPermission) { // local Users only have LocalPermissions + User<LocalPermission> user = getUser(bait); + if (user != null) { + return user.contains((LocalPermission)pond); } + } return false; } // We do not want to expose the actual Group, so make a copy. public void fishAll(Principal bait, List<Permission> perms) { - if(handles(bait)) { + if (handles(bait)) { User<LocalPermission> user = getUser(bait); - if(user!=null) { + if (user != null) { user.copyPermsTo(perms); } } @@ -174,13 +122,12 @@ public final class LocalLur extends AbsUserCache<LocalPermission> implements Lur */ @Override public boolean handles(Principal principal) { - return principal!=null && principal.getName().endsWith(supportedRealm); + if (principal == null) { + return false; + } + return principal.getName().endsWith(supportedRealm); } -// public boolean supports(String userName) { -// return userName!=null && userName.endsWith(supportedRealm); -// } -// public boolean handlesExclusively(Permission pond) { return supportingGroups.contains(pond.getKey()); } @@ -192,5 +139,74 @@ public final class LocalLur extends AbsUserCache<LocalPermission> implements Lur public Permission createPerm(String p) { return new LocalPermission(p); } + + private void parseUserProperties(String userProperties) throws IOException { + // For each User name... + for (String userProperty : userProperties.trim().split(SEMI)) { + String[] userInfo = userProperty.split(COLON, 2); + String[] userPass = userInfo[0].split(PERCENT, 2); + String userName = userPass[0]; + + byte[] password = null; + if (userPass.length > 1) { + password = access.decrypt(userPass[1], true).getBytes(); + if (userName.indexOf('@') < 0) { + userName += '@' + access.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm()); + } + } + User<LocalPermission> usr; + usr = new User<>(new ConfigPrincipal(userName, password)); + addUser(usr); + access.log(Level.INIT, "Local User:", usr.principal); + + if (userInfo.length > 1) { + Map<String, Permission> newMap = usr.newMap(); + for (String group : userInfo[1].split(COMMA)) { + supportingGroups.add(group); + usr.add(newMap, new LocalPermission(group)); + } + usr.setMap(newMap); + } + } + } + + + private void parseGroupProperties(String groupProperties) throws IOException { + // For each Group name... + for (String group : groupProperties.trim().split(SEMI)) { + String[] groups = group.split(COLON, 2); + if (groups.length <= 1) { + continue; + } + supportingGroups.add(groups[0]); + LocalPermission p = new LocalPermission(groups[0]); + + // Add all users (known by comma separators) + for (String groupMember : groups[1].split(COMMA)) { + // look for password, if so, put in passMap + String[] userPass = groupMember.split(PERCENT, 2); + String userName = userPass[0]; + if (userName.indexOf('@') < 0) { + userName += '@' + access.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm()); + } + + User<LocalPermission> usr = null; + byte[] password = null; + if (userPass.length > 1) { + password = access.decrypt(userPass[1], true).getBytes(); + } + usr = getUser(userName, password); + if (usr == null) { + usr = new User<>(new ConfigPrincipal(userName, password)); + addUser(usr); + } + else { + usr.principal = new ConfigPrincipal(userName, password); + } + usr.add(p); + access.log(Level.INIT, "Local User:", usr.principal); + } + } + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java index 6a49401c..22ba702c 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java @@ -121,6 +121,6 @@ public class BasicPrincipal extends BearerPrincipal implements GetCred { @Override public String personalName() { - return null; // personalName not available with Basic Auth + return name; // personalName not available with Basic Auth } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java index a2fc730e..c216fb57 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java @@ -62,7 +62,7 @@ public abstract class AbsTafResp implements TafResp { * Respond in the affirmative if the TAF was able to Authenticate */ public boolean isValid() { - return principal!=null; + return principal != null; } /** diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java index e575be14..5cd6323d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java @@ -7,9 +7,9 @@ * 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. @@ -30,19 +30,19 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.onap.aaf.cadi.Access; +import org.onap.aaf.cadi.Access.Level; import org.onap.aaf.cadi.CachedPrincipal; +import org.onap.aaf.cadi.CachedPrincipal.Resp; import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.Locator; -import org.onap.aaf.cadi.TrustChecker; -import org.onap.aaf.cadi.Access.Level; -import org.onap.aaf.cadi.CachedPrincipal.Resp; import org.onap.aaf.cadi.Taf.LifeForm; +import org.onap.aaf.cadi.TrustChecker; /** * HttpEpiTaf - * + * * An extension of the basic "EpiTAF" concept, check known HTTP Related TAFs for valid credentials - * + * * @author Jonathan * */ @@ -51,10 +51,10 @@ public class HttpEpiTaf implements HttpTaf { private Access access; private Locator<URI> locator; private TrustChecker trustChecker; - + /** * HttpEpiTaf constructor - * + * * Construct the HttpEpiTaf from variable Http specific TAF parameters * @param tafs @@ -65,52 +65,52 @@ public class HttpEpiTaf implements HttpTaf { this.access = access; this.locator = locator; this.trustChecker = tc; - // Establish what Header Property to look for UserChain/Trust Props -// trustChainProp = access.getProperty(Config.CADI_TRUST_PROP, Config.CADI_TRUST_PROP_DEFAULT); + // Establish what Header Property to look for UserChain/Trust Props - if(tafs.length==0) throw new CadiException("Need at least one HttpTaf implementation in constructor"); + if (tafs.length == 0) { + throw new CadiException("Need at least one HttpTaf implementation in constructor"); + } } /** * validate - * - * Respond with the first Http specific TAF to authenticate user based on variable info + * + * Respond with the first Http specific TAF to authenticate user based on variable info * and "LifeForm" (is it a human behind a browser, or a server utilizing HTTP Protocol). - * + * * If there is no HttpTAF that can authenticate, respond with the first TAF that suggests it can * establish an Authentication conversation (TRY_AUTHENTICATING) (Examples include a redirect to CSP - * Servers for CSP Cookie, or BasicAuth 401 response, suggesting User/Password for given Realm + * Servers for CSP Cookie, or BasicAuth 401 response, suggesting User/Password for given Realm * submission - * + * * If no TAF declares either, respond with NullTafResp (which denies all questions) */ public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { // Given a LifeForm Neutral, for HTTP, we need to discover true Life-Form Readings - if(reading==LifeForm.LFN) { + if (reading == LifeForm.LFN) { reading = tricorderScan(req); } - TafResp tresp=null, firstTry = null; + TafResp tresp = null; + TafResp firstTry = null; List<Redirectable> redirectables = null; - List<TafResp> trlog = access.willLog(Level.DEBUG)?new ArrayList<TafResp>():null; + List<TafResp> log = (access.willLog(Level.DEBUG)) ? new ArrayList<TafResp>() : null; try { - for(HttpTaf taf : tafs) { + for (HttpTaf taf : tafs) { tresp = taf.validate(reading, req, resp); - if(trlog!=null) { - trlog.add(tresp); - } + addToLog(log, tresp); switch(tresp.isAuthenticated()) { case TRY_ANOTHER_TAF: break; // and loop case TRY_AUTHENTICATING: - if(tresp instanceof Redirectable) { - if(redirectables==null) { - redirectables = new ArrayList<Redirectable>(); + if (tresp instanceof Redirectable) { + if (redirectables == null) { + redirectables = new ArrayList<>(); } redirectables.add((Redirectable)tresp); - } else if(firstTry==null) { + } else if (firstTry == null) { firstTry = tresp; } - break; + break; case IS_AUTHENTICATED: tresp = trustChecker.mayTrust(tresp, req); return tresp; @@ -118,69 +118,79 @@ public class HttpEpiTaf implements HttpTaf { return tresp; } } - } finally { - if(trlog!=null) { - for( TafResp tr : trlog) { - access.log(Level.DEBUG, tr.desc()); - } - } + } finally { + printLog(log); } - - // If No TAFs configured, at this point. It is safer at this point to be "not validated", + + // If No TAFs configured, at this point. It is safer at this point to be "not validated", // rather than "let it go" // Note: if exists, there will always be more than 0 entries, according to above code - if(redirectables==null) { - return firstTry!=null?firstTry:NullTafResp.singleton(); + if (redirectables == null) { + return (firstTry != null) ? firstTry : NullTafResp.singleton(); } - + // If there is one Tryable entry then return it - if(redirectables.size()>1) { - return LoginPageTafResp.create(access,locator,resp,redirectables); + if (redirectables.size() > 1) { + return LoginPageTafResp.create(access, locator, resp, redirectables); } else { return redirectables.get(0); } } - + public boolean revalidate(Principal prin) throws Exception { return false; } /* * Since this is internal, we use a little Star Trek humor to indicate looking in the HTTP Request to see if we can determine what kind - * of "LifeForm" reading we can determine, i.e. is there a Human (CarbonBasedLifeForm) behind a browser, or is it mechanical + * of "LifeForm" reading we can determine, i.e. is there a Human (CarbonBasedLifeForm) behind a browser, or is it mechanical * id (SiliconBasedLifeForm)? This makes a difference in some Authentication, i.e CSP, which doesn't work well for SBLFs */ private LifeForm tricorderScan(HttpServletRequest req) { // For simplicity's sake, we'll say Humans use FQDNs, not IPs. - - String auth = req.getParameter("Authentication"); - if(auth!=null) { - if("BasicAuth".equals(auth)) { - return LifeForm.SBLF; - } - } + // Current guess that only Browsers bother to set "Agent" codes that identify the kind of browser they are. // If mechanical frameworks are found that populate this, then more advanced analysis may be required // Jonathan 1/22/2013 String agent = req.getHeader("User-Agent"); - if(agent!=null && agent.startsWith("Mozilla")) // covers I.E./Firefox/Safari/probably any other "advanced" Browser see http://en.wikipedia.org/wiki/User_agent - return LifeForm.CBLF; + if (agent != null && agent.startsWith("Mozilla")) { // covers I.E./Firefox/Safari/probably any other "advanced" Browser see http://en.wikipedia.org/wiki/User_agent + return LifeForm.CBLF; + } return LifeForm.SBLF; // notably skips "curl","wget", (which is desired behavior. We don't want to try CSP, etc on these) } public Resp revalidate(CachedPrincipal prin, Object state) { Resp resp; - for(HttpTaf taf : tafs) { - resp = taf.revalidate(prin,state); - switch(resp) { - case NOT_MINE: - break; - default: - return resp; + for (HttpTaf taf : tafs) { + resp = taf.revalidate(prin, state); + if (resp != Resp.NOT_MINE) { + return resp; } +// switch(resp) { +// case NOT_MINE: +// break; +// default: +// return resp; +// } } return Resp.NOT_MINE; } + + private void addToLog(List<TafResp> log, TafResp tresp) { + if (log == null) { + return; + } + log.add(tresp); + } + + private void printLog(List<TafResp> log) { + if (log == null) { + return; + } + for (TafResp tresp : log) { + access.log(Level.DEBUG, tresp.desc()); + } + } /** * List HttpTafs with their "toString" representations... primarily useful for Debugging in an IDE @@ -188,7 +198,7 @@ public class HttpEpiTaf implements HttpTaf { */ public String toString() { StringBuilder sb = new StringBuilder(); - for(HttpTaf ht : tafs) { + for (HttpTaf ht : tafs) { sb.append(ht.toString()); sb.append(". "); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/LoginPageTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/LoginPageTafResp.java index 9c9cbc22..3f80170e 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/LoginPageTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/LoginPageTafResp.java @@ -53,34 +53,42 @@ public class LoginPageTafResp extends AbsTafResp { return RESP.TRY_AUTHENTICATING; } - public static TafResp create(Access access, Locator<URI> locator, final HttpServletResponse resp, List<Redirectable> redir) { - if(locator!=null) { - try { - Item item = locator.best(); - URI uri = locator.get(item); - if(uri!=null) { - StringBuilder sb = new StringBuilder(uri.toString()); - String query = uri.getQuery(); - boolean first = query==null || query.length()==0; - int count=0; - for(Redirectable t : redir) { - if(first) { - sb.append('?'); - first=false; - } - else sb.append('&'); - sb.append(t.get()); - ++count; - } - if(count>0)return new LoginPageTafResp(access, resp, sb.toString()); + public static TafResp create(Access access, Locator<URI> locator, final HttpServletResponse resp, List<Redirectable> redirectables) { + if (locator == null) { + if (!redirectables.isEmpty()) { + access.log(Level.DEBUG,"LoginPage Locator is not configured. Taking first Redirectable Taf"); + return redirectables.get(0); + } + return NullTafResp.singleton(); + } + + try { + Item item = locator.best(); + URI uri = locator.get(item); + if (uri == null) { + return NullTafResp.singleton(); + } + + StringBuilder sb = new StringBuilder(uri.toString()); + String query = uri.getQuery(); + boolean first = ((query == null) || (query.length() == 0)); + for (Redirectable redir : redirectables) { + if (first) { + sb.append('?'); + first = false; + } + else { + sb.append('&'); } - } catch (Exception e) { - access.log(e, "Error deriving Login Page location"); + sb.append(redir.get()); } - } else if(!redir.isEmpty()) { - access.log(Level.DEBUG,"LoginPage Locator is not configured. Taking first Redirectable Taf"); - return redir.get(0); + if (!redirectables.isEmpty()) { + return new LoginPageTafResp(access, resp, sb.toString()); + } + } catch (Exception e) { + access.log(e, "Error deriving Login Page location"); } + return NullTafResp.singleton(); } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/WSSEParser.java b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/WSSEParser.java index 9e36c11f..017337b1 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/WSSEParser.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/WSSEParser.java @@ -21,7 +21,6 @@ package org.onap.aaf.cadi.wsse; -import java.io.IOException; import java.io.InputStream; import javax.xml.stream.XMLStreamException; @@ -46,7 +45,6 @@ public class WSSEParser { private static final String SOAP_NS = "http://schemas.xmlsoap.org/soap/envelope/"; private static final String WSSE_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; private Match<BasicCred> parseTree; - //private XMLInputFactory inputFactory; public WSSEParser() { // soap:Envelope/soap:Header/wsse:Security/wsse:UsernameToken/[wsse:Password&wsse:Username] @@ -72,10 +70,9 @@ public class WSSEParser { ).stopAfter() // Stop Processing when Header Ends ).exclusive()// Envelope must match Header, and no other. FYI, Body comes after Header short circuits (see above), so it's ok ).exclusive(); // root must be Envelope - //inputFactory = XMLInputFactory.newInstance(); } - public XMLStreamException parse(BasicCred bc, InputStream is) throws IOException { + public XMLStreamException parse(BasicCred bc, InputStream is) { try { parseTree.onMatch(bc, new XReader(is)); return null; diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java index c442e6f2..842a7098 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_SecurityInfo.java @@ -21,11 +21,13 @@ package org.onap.aaf.cadi.config.test; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import static org.mockito.Mockito.*; -import org.junit.*; -import org.mockito.*; + +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; diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java index 63b8cf2d..7d7ca77c 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_UsersDump.java @@ -21,9 +21,13 @@ package org.onap.aaf.cadi.config.test; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import org.junit.*; +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; @@ -64,7 +68,7 @@ public class JU_UsersDump { 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(); @@ -85,6 +89,9 @@ public class JU_UsersDump { 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)); diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java new file mode 100644 index 00000000..6daa2720 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java @@ -0,0 +1,107 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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.aaf.cadi.filter.AUTHZServlet; + +import javax.servlet.Servlet; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequestWrapper; +import javax.servlet.http.HttpServletRequest; +import javax.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/aaf/cadi/filter/test/JU_AccessGetter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java new file mode 100644 index 00000000..b53a9ea9 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AccessGetter.java @@ -0,0 +1,54 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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.aaf.cadi.PropAccess; +import org.onap.aaf.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/aaf/cadi/filter/test/JU_FCGetTest.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_FCGetTest.java deleted file mode 100644 index 694c59e7..00000000 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_FCGetTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START==================================================== - * * org.onap.aaf - * * =========================================================================== - * * 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.aaf.cadi.filter.test; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.when; - -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.onap.aaf.cadi.PropAccess; - -public class JU_FCGetTest { - - @Test - public void netYetTested() { - //fail("Tests not yet implemented"); - } - -// @Mock -// private ServletContext context; - -// @Mock -// private FilterConfig config; - -// @Mock -// private PropAccess access = new PropAccess(); - -// @Before -// public void setUp() { -// MockitoAnnotations.initMocks(this); -// } - -// @Test -// public void testGetStringFromDef() { -// PropAccess access = new PropAccess(); - -// FCGet fcGet = new FCGet(access, context, config); - -// String user = fcGet.get("user", "DefaultUser", true); - -// assertEquals(user, "DefaultUser"); -// } - -// @Test -// public void testGetStringFromContext() { -// PropAccess access = new PropAccess(); -// when(context.getInitParameter("user")).thenReturn("ContextUser"); - -// FCGet fcGet = new FCGet(access, context, null); - -// String user = fcGet.get("user", "DefaultUser", true); - -// assertEquals(user,"ContextUser"); -// } - -// @Test -// public void testGetStringFromFilter() { -// PropAccess access = new PropAccess(); -// when(config.getInitParameter("user")).thenReturn("FilterUser"); - -// FCGet fcGet = new FCGet(access, null, config); - -// String user = fcGet.get("user", "DefaultUser", true); - -// assertEquals(user,"FilterUser"); -// } - -// @Test -// public void testGetStringWithNullContextFilter() { - -// when(access.getProperty("user", "DefaultUser")).thenReturn(null); - -// FCGet fcGet = new FCGet(access, null, null); - -// String user = fcGet.get("user", "DefaultUser", true); - -// assertEquals(user,"DefaultUser"); -// } -} diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java new file mode 100644 index 00000000..9fb951a2 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_MapPermConverter.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.filter.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.onap.aaf.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/aaf/cadi/filter/test/JU_NullPermConverter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java new file mode 100644 index 00000000..0a6dc2d5 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_NullPermConverter.java @@ -0,0 +1,38 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.cadi.filter.test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.junit.Test; +import org.onap.aaf.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/aaf/cadi/filter/test/JU_PathFilter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java new file mode 100644 index 00000000..a36dd462 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_PathFilter.java @@ -0,0 +1,105 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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 javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.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/aaf/cadi/lur/test/JU_EpiLur.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java new file mode 100644 index 00000000..f7c3a0a2 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_EpiLur.java @@ -0,0 +1,128 @@ +/** + * + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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.aaf.cadi.CachingLur; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.CredVal; +import org.onap.aaf.cadi.Lur; +import org.onap.aaf.cadi.Permission; +import org.onap.aaf.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/aaf/cadi/lur/test/JU_LocalLur.java b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java index fd8e3575..d86a0754 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/lur/test/JU_LocalLur.java @@ -7,9 +7,9 @@ * * 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. @@ -19,85 +19,156 @@ * * * * ******************************************************************************/ + package org.onap.aaf.cadi.lur.test; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertTrue; +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 java.util.Set; -import java.util.TreeSet; +import org.junit.Before; import org.junit.Test; -import org.onap.aaf.cadi.Lur; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.onap.aaf.cadi.Permission; import org.onap.aaf.cadi.PropAccess; -import org.onap.aaf.cadi.Symm; +import org.onap.aaf.cadi.AbsUserCache; import org.onap.aaf.cadi.CredVal.Type; -import org.onap.aaf.cadi.config.UsersDump; +import org.onap.aaf.cadi.lur.ConfigPrincipal; import org.onap.aaf.cadi.lur.LocalLur; import org.onap.aaf.cadi.lur.LocalPermission; public class JU_LocalLur { + private static final String password = "<pass>"; + private String encrypted; + + private PropAccess access; + private ByteArrayOutputStream outStream; + + @Mock Permission permMock; + + @Before + public void setup() throws IOException { + MockitoAnnotations.initMocks(this); + + encrypted = rot13(password); + + 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 { - Symm symmetric = Symm.baseCrypt().obtain(); - LocalLur up; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(Symm.ENC.getBytes()); - symmetric.enpass("<pass>", baos); - PropAccess ta = new PropAccess(); - Lur ml = up = new LocalLur(ta,"myname:groupA,groupB","admin:myname,yourname;suser:hisname,hername,m1234%"+baos.toString()); + 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@none")); + + 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")); -// Permission admin = new LocalPermission("admin"); -// Permission suser = new LocalPermission("suser"); -// -// // Check User fish -// assertTrue(ml.fish(new JUPrincipal("myname"),admin)); -// assertTrue(ml.fish(new JUPrincipal("hisname"),admin)); -// assertFalse(ml.fish(new JUPrincipal("noname"),admin)); -// assertTrue(ml.fish(new JUPrincipal("itsname"),suser)); -// assertTrue(ml.fish(new JUPrincipal("hername"),suser)); -// assertFalse(ml.fish(new JUPrincipal("myname"),suser)); -// -// // Check validate password -// assertTrue(up.validate("m1234",Type.PASSWORD, "<pass>".getBytes())); -// assertFalse(up.validate("m1234",Type.PASSWORD, "badPass".getBytes())); -// - // Check fishAll - Set<String> set = new TreeSet<String>(); - List<Permission> perms = new ArrayList<Permission>(); - ml.fishAll(new JUPrincipal("myname"), perms); - for(Permission p : perms) { - set.add(p.getKey()); - } -// assertEquals("[admin, groupA, groupB]",set.toString()); - UsersDump.write(System.out, up); - System.out.flush(); + 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); + 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"); } - - // Simplistic Principal for testing purposes - private static class JUPrincipal implements Principal { - private String name; - public JUPrincipal(String name) { - this.name = name; - } -// @Override - public String getName() { - return name; + + 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/aaf/cadi/principal/test/JU_BasicPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java index dee7fc21..32d6cd0a 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_BasicPrincipal.java @@ -22,9 +22,13 @@ package org.onap.aaf.cadi.principal.test; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import static org.mockito.Mockito.*; +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; @@ -33,9 +37,6 @@ import java.util.Date; import org.onap.aaf.cadi.BasicCred; import org.onap.aaf.cadi.Symm; import org.onap.aaf.cadi.principal.BasicPrincipal; -import org.onap.aaf.cadi.principal.StringTagLookup; -import org.onap.aaf.cadi.principal.TaggedPrincipal; -import org.onap.aaf.cadi.principal.TaggedPrincipal.TagLookup; public class JU_BasicPrincipal { @@ -103,7 +104,7 @@ public class JU_BasicPrincipal { assertTrue(Math.abs(bp.created() - created) < 10); assertThat(bp.toString(), is(expected)); assertThat(bp.tag(), is("BAth")); - assertThat(bp.personalName(), is(nullValue())); + assertThat(bp.personalName(), is(bp.getName())); // This test hits the abstract class BearerPrincipal assertThat(bp.getBearer(), is(bearer)); diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java index aa9a01a5..20e1d4d9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_CachedBasicPrincipal.java @@ -22,25 +22,24 @@ package org.onap.aaf.cadi.principal.test; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import static org.mockito.Mockito.*; -import org.junit.*; +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 java.util.Date; import org.onap.aaf.cadi.BasicCred; import org.onap.aaf.cadi.CachedPrincipal; -import org.onap.aaf.cadi.CachedPrincipal.Resp; -import org.onap.aaf.cadi.Symm; import org.onap.aaf.cadi.principal.CachedBasicPrincipal; -import org.onap.aaf.cadi.principal.StringTagLookup; -import org.onap.aaf.cadi.principal.TaggedPrincipal; -import org.onap.aaf.cadi.principal.TaggedPrincipal.TagLookup; import org.onap.aaf.cadi.taf.HttpTaf; public class JU_CachedBasicPrincipal { diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java new file mode 100644 index 00000000..137eab3b --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTaf.java @@ -0,0 +1,187 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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 javax.servlet.AsyncContext; +import javax.servlet.DispatcherType; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.servlet.http.Part; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.BasicCred; +import org.onap.aaf.cadi.CachedPrincipal; +import org.onap.aaf.cadi.CachedPrincipal.Resp; +import org.onap.aaf.cadi.CredVal; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.Symm; +import org.onap.aaf.cadi.Taf.LifeForm; +import org.onap.aaf.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 getRealPath(String arg0) { 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 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 { } + } +} diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java new file mode 100644 index 00000000..8eba1faf --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/basic/test/JU_BasicHttpTafResp.java @@ -0,0 +1,67 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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 javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.principal.TaggedPrincipal; +import org.onap.aaf.cadi.taf.TafResp.RESP; +import org.onap.aaf.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/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java new file mode 100644 index 00000000..36f17ef1 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/cert/test/JU_X509HttpTafResp.java @@ -0,0 +1,63 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.principal.TaggedPrincipal; +import org.onap.aaf.cadi.taf.TafResp.RESP; +import org.onap.aaf.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/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java new file mode 100644 index 00000000..34b2a513 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTafResp.java @@ -0,0 +1,57 @@ +/** + * + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.taf.TafResp.RESP; +import org.onap.aaf.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/aaf/cadi/taf/test/JU_AbsTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java new file mode 100644 index 00000000..6d0c04b7 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_AbsTafResp.java @@ -0,0 +1,87 @@ +/******************************************************************************* +* ============LICENSE_START==================================================== +* * org.onap.aaf +* * =========================================================================== +* * 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.aaf.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.aaf.cadi.Access; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.principal.TaggedPrincipal; +import org.onap.aaf.cadi.taf.AbsTafResp; +import org.onap.aaf.cadi.taf.TafResp.RESP; + +public class JU_AbsTafResp { + + 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, taggedPrinc, description) { + @Override public RESP authenticate() throws IOException { + return null; + } + }; + + assertThat(tafResp.isValid(), is(true)); + assertThat(tafResp.desc(), is(description)); + 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, null, 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.getAccess(), is(nullValue())); + assertThat(tafResp.isFailedAttempt(), is(false)); + } + +} diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java new file mode 100644 index 00000000..93a20474 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_HttpEpiTaf.java @@ -0,0 +1,145 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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 javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.Access.Level; +import org.onap.aaf.cadi.CachedPrincipal.Resp; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.Locator; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.Taf.LifeForm; +import org.onap.aaf.cadi.TrustChecker; +import org.onap.aaf.cadi.taf.HttpEpiTaf; +import org.onap.aaf.cadi.taf.HttpTaf; +import org.onap.aaf.cadi.taf.NullTaf; +import org.onap.aaf.cadi.taf.Redirectable; +import org.onap.aaf.cadi.taf.TafResp; +import org.onap.aaf.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/aaf/cadi/taf/test/JU_LoginPageTafResp.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java new file mode 100644 index 00000000..3124bbd4 --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/test/JU_LoginPageTafResp.java @@ -0,0 +1,101 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 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.aaf.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 javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aaf.cadi.Access; +import org.onap.aaf.cadi.Locator; +import org.onap.aaf.cadi.Locator.Item; +import org.onap.aaf.cadi.LocatorException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.taf.LoginPageTafResp; +import org.onap.aaf.cadi.taf.Redirectable; +import org.onap.aaf.cadi.taf.TafResp; +import org.onap.aaf.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/aaf/cadi/test/JU_AbsUserCache.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java index 441765a6..b2739b9d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AbsUserCache.java @@ -21,11 +21,13 @@ package org.onap.aaf.cadi.test; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import static org.mockito.Mockito.*; -import org.junit.*; -import org.mockito.*; +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; @@ -35,13 +37,17 @@ 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.aaf.cadi.AbsUserCache; -import org.onap.aaf.cadi.AbsUserCache.*; import org.onap.aaf.cadi.Access; import org.onap.aaf.cadi.CachedPrincipal.Resp; import org.onap.aaf.cadi.CachingLur; import org.onap.aaf.cadi.GetCred; -import org.onap.aaf.cadi.Hash; import org.onap.aaf.cadi.Permission; import org.onap.aaf.cadi.PropAccess; import org.onap.aaf.cadi.User; @@ -51,14 +57,10 @@ import org.onap.aaf.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; @@ -67,7 +69,7 @@ public class JU_AbsUserCache { private String name1 = "name1"; private String name2 = "name2"; private byte[] password = "password".getBytes(); - + private static Field timerField; @BeforeClass @@ -300,22 +302,22 @@ public class JU_AbsUserCache { @Test public void handlesExclusivelyTest() { - AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE); + 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); + 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 = 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); + 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 @@ -332,26 +334,26 @@ public class JU_AbsUserCache { } 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); } + 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; } + 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) { } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java index 52be7d5e..efcc1b29 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java @@ -21,10 +21,11 @@ ******************************************************************************/ package org.onap.aaf.cadi.test; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import org.junit.*; -import org.mockito.*; +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; @@ -37,8 +38,12 @@ 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.aaf.cadi.CmdLine; -import org.onap.aaf.cadi.PropAccess; import org.onap.aaf.cadi.Symm; public class JU_CmdLine { @@ -59,12 +64,12 @@ public class JU_CmdLine { public void setup() throws Exception { MockitoAnnotations.initMocks(this); - System.setOut(new PrintStream(outContent)); + System.setOut(new PrintStream(outContent)); Properties p = new Properties(); p.setProperty("force_exit", "false"); - CmdLine.access = new PropAccess(p); + CmdLine.setSystemExit(false); keyfile = "src/test/resources/keyfile"; password = "password"; @@ -79,8 +84,8 @@ public class JU_CmdLine { @After public void restoreStreams() throws IOException { - System.setOut(System.out); - System.setIn(System.in); + System.setOut(System.out); + System.setIn(System.in); } @Test @@ -95,13 +100,6 @@ public class JU_CmdLine { assertThat(decrypted, is(password)); } - // @Test - // public void regurgitateTest() { - // // TODO: We may still want to remove the regurgitate functionality - // // from the CmdLine - Ian - // fail("Tests not yet implemented"); - // } - @Test public void encode64Test() throws Exception { CmdLine.main(new String[]{"encode64", password}); diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java index 32ca8f84..b2600aa5 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_Vars.java @@ -46,7 +46,6 @@ public class JU_Vars { @Test public void convertTest1() { - String test = "te%t"; List<String> list = new ArrayList<String>(); list.add("method"); assertEquals(Vars.convert("test", list), "test"); @@ -54,7 +53,6 @@ public class JU_Vars { @Test public void convertTest2() { - String test = "te%s%t"; List<String> list = new ArrayList<String>(); list.add("method"); assertEquals(Vars.convert("test", list), "test"); diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java new file mode 100644 index 00000000..0d7bdc2c --- /dev/null +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java @@ -0,0 +1,163 @@ +/******************************************************************************* +* ============LICENSE_START==================================================== +* * org.onap.aaf +* * =========================================================================== +* * 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.aaf.cadi.wsse.test; + +import org.junit.Test; +import org.onap.aaf.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/aaf/cadi/wsse/test/JU_WSSE_Read.java b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSE_Read.java deleted file mode 100644 index 599987d7..00000000 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSE_Read.java +++ /dev/null @@ -1,189 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START==================================================== - * * org.onap.aaf - * * =========================================================================== - * * 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.aaf.cadi.wsse.test; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.assertNull; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; - -import javax.xml.stream.XMLStreamException; - -import org.junit.Test; -import org.onap.aaf.cadi.BasicCred; -import org.onap.aaf.cadi.BufferedServletInputStream; -import org.onap.aaf.cadi.wsse.WSSEParser; - -public class JU_WSSE_Read { - -// @Test -// public void test() { -// try { -// 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; -// } -// }; - -// WSSEParser wp = new WSSEParser(); - -// 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(); -// } -// } catch(Exception e) { -// e.printStackTrace(System.err); -// } -// } - -} diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_XReader.java b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_XReader.java index 15fe1145..e75cea4e 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_XReader.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_XReader.java @@ -21,19 +21,20 @@ ******************************************************************************/ package org.onap.aaf.cadi.wsse.test; -import static org.junit.Assert.*; -import static org.hamcrest.CoreMatchers.*; -import org.junit.*; +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.is; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; 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.aaf.cadi.wsse.XEvent; import org.onap.aaf.cadi.wsse.XReader; @@ -123,17 +124,6 @@ public class JU_XReader { } } - // @Test - // public void tagTest() { - // String prefix = "prefix"; - // String name = "name"; - // String value = "value"; - // XReader.Tag tag = new Tag(prefix, name, value); - - // assertThat(tag.toString(), is(prefix + ':' + name + "=\'" + value + "'")); - // } - - private static XEvent getNextEvent(XReader xr) throws XMLStreamException { if (xr.hasNext()) { return xr.nextEvent(); diff --git a/cadi/oauth-enduser/pom.xml b/cadi/oauth-enduser/pom.xml index 0f9bacab..83ea803a 100644 --- a/cadi/oauth-enduser/pom.xml +++ b/cadi/oauth-enduser/pom.xml @@ -37,7 +37,7 @@ <properties> <!-- SONAR --> - <!-- <sonar.skip>true</sonar.skip> --> + <sonar.skip>true</sonar.skip> <jacoco.version>0.7.7.201606060606</jacoco.version> <sonar-jacoco-listeners.version>3.2</sonar-jacoco-listeners.version> <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin> diff --git a/cadi/shiro/pom.xml b/cadi/shiro/pom.xml index 0346dbe7..4e7790cf 100644 --- a/cadi/shiro/pom.xml +++ b/cadi/shiro/pom.xml @@ -35,7 +35,7 @@ <properties> <!-- SONAR --> - <!-- <sonar.skip>true</sonar.skip> --> + <sonar.skip>true</sonar.skip> <jacoco.version>0.7.7.201606060606</jacoco.version> <sonar-jacoco-listeners.version>3.2</sonar-jacoco-listeners.version> <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin> diff --git a/cadi/shiro/src/main/java/org/onap/aaf/cadi/shiro/AAFAuthorizationInfo.java b/cadi/shiro/src/main/java/org/onap/aaf/cadi/shiro/AAFAuthorizationInfo.java index 90935900..bfdc6bf1 100644 --- a/cadi/shiro/src/main/java/org/onap/aaf/cadi/shiro/AAFAuthorizationInfo.java +++ b/cadi/shiro/src/main/java/org/onap/aaf/cadi/shiro/AAFAuthorizationInfo.java @@ -31,9 +31,9 @@ import org.onap.aaf.cadi.Access; import org.onap.aaf.cadi.Access.Level; /** - * We treate "roles" and "permissions" in a similar way for first pass. + * We treat "roles" and "permissions" in a similar way for first pass. * - * @author jg1555 + * @author JonathanGathman * */ public class AAFAuthorizationInfo implements AuthorizationInfo { |