Policy TestSuite Enabled
[policy/engine.git] / ECOMP-XACML / src / test / java / org / openecomp / policy / xacml / test / TestAnnotation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-XACML
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.xacml.test;
22
23 import java.io.IOException;
24 import java.net.MalformedURLException;
25 import java.net.URI;
26 import java.nio.file.Files;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.util.Arrays;
30 import java.util.Calendar;
31 import java.util.Collection;
32 import java.util.Date;
33 import java.util.TimeZone;
34
35 import org.apache.commons.cli.ParseException;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38
39 import com.att.research.xacml.api.DataTypeException;
40 import com.att.research.xacml.api.Response;
41 import com.att.research.xacml.std.annotations.RequestParser;
42 import com.att.research.xacml.std.annotations.XACMLAction;
43 import com.att.research.xacml.std.annotations.XACMLAttribute;
44 import com.att.research.xacml.std.annotations.XACMLEnvironment;
45 import com.att.research.xacml.std.annotations.XACMLMultiRequest;
46 import com.att.research.xacml.std.annotations.XACMLRequest;
47 import com.att.research.xacml.std.annotations.XACMLRequestReference;
48 import com.att.research.xacml.std.annotations.XACMLResource;
49 import com.att.research.xacml.std.annotations.XACMLSubject;
50 import com.att.research.xacml.std.datatypes.HexBinary;
51 import com.att.research.xacml.std.datatypes.IPAddress;
52 import com.att.research.xacml.std.datatypes.IPv4Address;
53 import com.att.research.xacml.std.datatypes.ISO8601DateTime;
54 import com.att.research.xacml.std.datatypes.ISO8601Time;
55 import com.att.research.xacml.util.FactoryException;
56
57 /**
58  * This example application shows how to use annotations for Java classes to create requests to send to the
59  * engine.
60  * 
61  *
62  */
63 public class TestAnnotation extends TestBase {
64         private static final Log logger = LogFactory.getLog(TestAnnotation.class);
65         
66         private int     num;
67         
68         /**
69          * This is a sample class that uses annotations. In addition to demonstrating how to use XACML annotations,
70          * it also demonstrates the various Java objects that can be used and how the request parser will
71          * resolve each object's datatype.
72          * 
73          *
74          */
75         @XACMLRequest(ReturnPolicyIdList=true)
76         public class MyRequestAttributes {
77                 
78                 public MyRequestAttributes(String user, String action, String resource) {
79                         this.userID = user;
80                         this.action = action;
81                         this.resource = resource;
82                         this.today = new Date();
83                         this.yesterday = Calendar.getInstance();
84                         this.yesterday.add(Calendar.DAY_OF_MONTH, -1);
85                 }
86
87                 @XACMLSubject(includeInResults=true)
88                 String  userID;
89                 
90                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id-qualifier")
91                 boolean admin = false;
92                 
93                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:key-info", issuer="com:foo:security")
94                 HexBinary publicKey = new HexBinary(new byte[] {'1', '0'});
95                 
96                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:authentication-time")
97                 ISO8601Time     authenticationTime = new ISO8601Time(8, 0, 0, 0);
98                 
99                 /**
100                  * Here our base object is "Object", but it is reflected as a Java "String". The parser
101                  * will then use the XACML http://www.w3.org/2001/XMLSchema#string as the datatype.
102                  */
103                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:authentication-method")
104                 Object authenticationMethod = new String("RSA Public Key");
105                 
106                 /**
107                  * Here our base object is "String", but we use the annotation for datatype to clarify
108                  * that the real XACML data type is http://www.w3.org/2001/XMLSchema#time. The parser will
109                  * use the data type factory to convert the "String" to a "ISO8601Time" Java object.
110                  */
111                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:request-time", datatype="http://www.w3.org/2001/XMLSchema#time")
112                 String requestTime = new String("13:20:00-05:00");
113                 
114                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:session-start-time")
115                 ISO8601DateTime sessionStart = new ISO8601DateTime(TimeZone.getDefault().getID(), 2014, 1, 1, 10, 0, 0, 0);
116                 
117                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:3.0:subject:authn-locality:ip-address")
118                 IPAddress ip = new IPv4Address(new short[] {123, 134, 156, 255 }, null, null);
119                 
120                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:3.0:subject:authn-locality:dns-name")
121                 String dnsName = "localhost";
122                 
123                 @XACMLAction()
124                 String  action;
125                 
126                 @XACMLAction(attributeId="urn:oasis:names:tc:xacml:1.0:action:implied-action")
127                 long    impliedAction;
128                 
129                 @XACMLResource()
130                 String  resource;
131                 
132                 @XACMLEnvironment()
133                 Date            today;
134                 
135                 @XACMLEnvironment()
136                 Calendar        yesterday;
137                 
138                 /**
139                  * This field demonstrates how the parser can detect collections and build a bag of values.
140                  */
141                 @XACMLAttribute(attributeId="foo:bar:attribute")
142                 Collection<Double>              fooBar = Arrays.asList(2.5, 3.5);
143                 
144                 /**
145                  * The XACMLAttribute annotation allows one to specify all the 
146                  */
147                 @XACMLAttribute(category="foo:bar:category", attributeId="foo:bar:attribute2")
148                 double          fooBar2 = 3.999;
149                 
150                 /**
151                  * This field demonstrates how the parser can detect arrays and build a bag of values.
152                  */
153                 @XACMLAttribute(category="foo:bar:category", attributeId="foo:bar:attribute:many")
154                 URI[]           fooBarMany = new URI[] {URI.create("file://opt/app/test"), URI.create("https://localhost:8443/")};
155                 
156         };
157
158         @XACMLRequest(
159                 Defaults="http://www.w3.org/TR/1999/Rec-xpath-19991116",
160                 multiRequest=@XACMLMultiRequest(values={
161                         @XACMLRequestReference(values={"subject1", "action", "resource"}),
162                         @XACMLRequestReference(values={"subject2", "action", "resource"})})
163         )
164         public class MyMultiRequestAttributes {
165                 
166                 @XACMLSubject(id="subject1")
167                 String  userID1 = "John";
168                 
169                 @XACMLSubject(id="subject2")
170                 String  userID2 = "Ringo";
171
172                 @XACMLAction(id="action")
173                 String  action = "access";
174
175                 @XACMLResource(id="resource")
176                 String  resource = "www.mywebsite.com";
177         }
178
179         public TestAnnotation(String[] args) throws MalformedURLException, ParseException, HelpException {
180                 super(args);
181         }
182
183         @Override
184         public void run() throws IOException, FactoryException {
185                 //
186                 // We are not going to iterate any existing request files. So we will override
187                 // any TestBase code that assumes there are request files present.
188                 //
189                 //
190                 // Configure ourselves
191                 //
192                 this.configure();
193                 //
194                 // Cycle through creating a few objects
195                 //
196                 this.num = 0;
197                 this.doRequest(new MyRequestAttributes("John", "access", "www.mywebsite.com"));
198                 this.num++;
199                 this.doRequest(new MyRequestAttributes("Ringo", "access", "www.mywebsite.com"));
200                 this.num++;
201                 this.doRequest(new MyMultiRequestAttributes());
202                 this.num++;
203         }
204
205         private void doRequest(Object info) {
206                 try {
207                         Response response = this.callPDP(RequestParser.parseRequest(info));
208                         Path resultFile;
209                         if (this.output != null) {
210                                 resultFile = Paths.get(this.output.toString(), "Response." + String.format("%03d", this.num) + ".json");
211                         } else {
212                                 resultFile = Paths.get(this.directory, "results", "Response." + String.format("%03d", this.num) + ".json");
213                         }
214                         //
215                         // Write the response to the result file
216                         //
217                         logger.info("Response is: " + response.toString());
218                         if (resultFile != null) {
219                                 Files.write(resultFile, response.toString().getBytes());
220                         }
221                 } catch (IllegalArgumentException | IllegalAccessException | DataTypeException | IOException e) {
222                         logger.error(e);
223                         logger.error("Exception Occured"+e);
224                 }
225         }
226         
227         public static void main(String[] args) {
228                 try {
229                         new TestAnnotation(args).run();
230                 } catch (ParseException | IOException | FactoryException e) {
231                         logger.error(e);
232                 } catch (HelpException e) {
233                         //
234                         // ignore this, its thrown just to exit the application
235                         // after dumping help to stdout.
236                         //
237                 }               
238         }
239 }