Approval Batch, prep better JUnit
[aaf/authz.git] / auth / auth-cass / src / main / java / org / onap / aaf / auth / dao / cass / UserRoleDAO.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 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
22 package org.onap.aaf.auth.dao.cass;
23
24 import java.io.ByteArrayOutputStream;
25 import java.io.DataInputStream;
26 import java.io.DataOutputStream;
27 import java.io.IOException;
28 import java.nio.ByteBuffer;
29 import java.util.Date;
30 import java.util.List;
31
32 import org.onap.aaf.auth.dao.Bytification;
33 import org.onap.aaf.auth.dao.Cached;
34 import org.onap.aaf.auth.dao.CassDAOImpl;
35 import org.onap.aaf.auth.dao.DAOException;
36 import org.onap.aaf.auth.dao.Loader;
37 import org.onap.aaf.auth.dao.Streamer;
38 import org.onap.aaf.auth.dao.hl.Question;
39 import org.onap.aaf.auth.env.AuthzTrans;
40 import org.onap.aaf.auth.layer.Result;
41 import org.onap.aaf.misc.env.APIException;
42 import org.onap.aaf.misc.env.Slot;
43 import org.onap.aaf.misc.env.util.Chrono;
44
45 import com.datastax.driver.core.Cluster;
46 import com.datastax.driver.core.Row;
47
48 public class UserRoleDAO extends CassDAOImpl<AuthzTrans,UserRoleDAO.Data> {
49     public static final String TABLE = "user_role";
50     
51     public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F
52
53     private static final String TRANS_UR_SLOT = "_TRANS_UR_SLOT_";
54     public Slot transURSlot;
55     
56     private final HistoryDAO historyDAO;
57     private final CacheInfoDAO infoDAO;
58     
59     private PSInfo psByUser, psByRole, psUserInRole;
60
61
62
63     public UserRoleDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException {
64         super(trans, UserRoleDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
65         transURSlot = trans.slot(TRANS_UR_SLOT);
66         init(trans);
67
68         // Set up sub-DAOs
69         historyDAO = new HistoryDAO(trans, this);
70         infoDAO = new CacheInfoDAO(trans,this);
71     }
72
73     public UserRoleDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) {
74         super(trans, UserRoleDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
75         transURSlot = trans.slot(TRANS_UR_SLOT);
76         historyDAO = hDAO;
77         infoDAO = ciDAO;
78         init(trans);
79     }
80
81     private static final int KEYLIMIT = 2;
82     public static class Data extends CacheableData implements Bytification {
83         public String  user;
84         public String  role;
85         public String  ns; 
86         public String  rname; 
87         public Date   expires;
88         
89         @Override
90         public int[] invalidate(Cached<?,?> cache) {
91             // Note: I'm not worried about Name collisions, because the formats are different:
92             // Jonathan... etc versus
93             // com. ...
94             // The "dot" makes the difference.
95             return new int[] {
96                 seg(cache,user,role),
97                 seg(cache,user),
98                 seg(cache,role)
99             };
100         }
101
102         @Override
103         public ByteBuffer bytify() throws IOException {
104             ByteArrayOutputStream baos = new ByteArrayOutputStream();
105             URLoader.deflt.marshal(this,new DataOutputStream(baos));
106             return ByteBuffer.wrap(baos.toByteArray());
107         }
108         
109         @Override
110         public void reconstitute(ByteBuffer bb) throws IOException {
111             URLoader.deflt.unmarshal(this, toDIS(bb));
112         }
113
114         public void role(String ns, String rname) {
115             this.ns = ns;
116             this.rname = rname;
117             this.role = ns + '.' + rname;
118         }
119         
120         public void role(RoleDAO.Data rdd) {
121             ns = rdd.ns;
122             rname = rdd.name;
123             role = rdd.fullName();
124         }
125
126         
127         public boolean role(AuthzTrans trans, Question ques, String role) {
128             this.role = role;
129             Result<NsSplit> rnss = ques.deriveNsSplit(trans, role);
130             if (rnss.isOKhasData()) {
131                 ns = rnss.value.ns;
132                 rname = rnss.value.name;
133                 return true;
134             } else {
135                 return false;
136             }
137         }
138
139         @Override
140         public String toString() {
141             return user + '|' + ns + '|' +  rname + '|' + Chrono.dateStamp(expires);
142         }
143     }
144     
145     private static class URLoader extends Loader<Data> implements Streamer<Data> {
146         public static final int MAGIC=738469903;
147         public static final int VERSION=1;
148         public static final int BUFF_SIZE=48;
149         
150         public static final URLoader deflt = new URLoader(KEYLIMIT);
151
152         public URLoader(int keylimit) {
153             super(keylimit);
154         }
155
156         @Override
157         public Data load(Data data, Row row) {
158             data.user = row.getString(0);
159             data.role = row.getString(1);
160             data.ns = row.getString(2);
161             data.rname = row.getString(3);
162             data.expires = row.getTimestamp(4);
163             return data;
164         }
165
166         @Override
167         protected void key(Data data, int _idx, Object[] obj) {
168                 int idx = _idx;
169             obj[idx]=data.user;
170             obj[++idx]=data.role;
171         }
172
173         @Override
174         protected void body(Data data, int _idx, Object[] obj) {
175                 int idx = _idx;
176             obj[idx]=data.ns;
177             obj[++idx]=data.rname;
178             obj[++idx]=data.expires;
179         }
180         
181         @Override
182         public void marshal(Data data, DataOutputStream os) throws IOException {
183             writeHeader(os,MAGIC,VERSION);
184
185             writeString(os, data.user);
186             writeString(os, data.role);
187             writeString(os, data.ns);
188             writeString(os, data.rname);
189             os.writeLong(data.expires==null?-1:data.expires.getTime());
190         }
191
192         @Override
193         public void unmarshal(Data data, DataInputStream is) throws IOException {
194             /*int version = */readHeader(is,MAGIC,VERSION);
195             // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields
196             
197             byte[] buff = new byte[BUFF_SIZE];
198             data.user = readString(is,buff);
199             data.role = readString(is,buff);
200             data.ns = readString(is,buff);
201             data.rname = readString(is,buff);
202             long l = is.readLong();
203             data.expires = l<0?null:new Date(l);
204         }
205
206     };
207     
208     private void init(AuthzTrans trans) {
209         String[] helper = setCRUD(trans, TABLE, Data.class, URLoader.deflt);
210         
211         psByUser = new PSInfo(trans, SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE user = ?", 
212             new URLoader(1) {
213                 @Override
214                 protected void key(Data data, int idx, Object[] obj) {
215                     obj[idx]=data.user;
216                 }
217             },readConsistency);
218         
219         // Note: We understand this call may have poor performance, so only should be used in Management (Delete) func
220         psByRole = new PSInfo(trans, SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE role = ? ALLOW FILTERING", 
221                 new URLoader(1) {
222                     @Override
223                     protected void key(Data data, int idx, Object[] obj) {
224                         obj[idx]=data.role;
225                     }
226                 },readConsistency);
227         
228         psUserInRole = new PSInfo(trans,SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE user = ? AND role = ?",
229                 URLoader.deflt,readConsistency);
230     }
231
232     public Result<List<Data>> readByUser(AuthzTrans trans, String user) {
233         return psByUser.read(trans, R_TEXT + " by User " + user, new Object[]{user});
234     }
235
236     /**
237      * Note: Use Sparingly. Cassandra's forced key structure means this will perform fairly poorly
238      * @param trans
239      * @param role
240      * @return
241      * @throws DAOException
242      */
243     public Result<List<Data>> readByRole(AuthzTrans trans, String role) {
244         return psByRole.read(trans, R_TEXT + " by Role " + role, new Object[]{role});
245     }
246     
247     /**
248      * Direct Lookup of User Role
249      * Don't forget to check for Expiration
250      */
251     public Result<List<Data>> readByUserRole(AuthzTrans trans, String user, String role) {
252         return psUserInRole.read(trans, R_TEXT + " by User " + user + " and Role " + role, new Object[]{user,role});
253     }
254
255
256     /**
257      * Log Modification statements to History
258      * @param modified           which CRUD action was done
259      * @param data               entity data that needs a log entry
260      * @param overrideMessage    if this is specified, we use it rather than crafting a history message based on data
261      */
262     @Override
263     protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
264         boolean memo = override.length>0 && override[0]!=null;
265         boolean subject = override.length>1 && override[1]!=null;
266
267         HistoryDAO.Data hd = HistoryDAO.newInitedData();
268         HistoryDAO.Data hdRole = HistoryDAO.newInitedData();
269         
270         hd.user = hdRole.user = trans.user();
271         hd.action = modified.name();
272         // Modifying User/Role is an Update to Role, not a Create.  Jonathan, 07-14-2015
273         hdRole.action = CRUD.update.name();
274         hd.target = TABLE;
275         hdRole.target = RoleDAO.TABLE;
276         hd.subject = subject?override[1] : (data.user + '|'+data.role);
277         hdRole.subject = data.role;
278         switch(modified) {
279             case create: 
280                 hd.memo = hdRole.memo = memo
281                     ? String.format("%s by %s", override[0], hd.user)
282                     : String.format("%s added to %s",data.user,data.role);    
283                 break;
284             case update: 
285                 hd.memo = hdRole.memo = memo
286                     ? String.format("%s by %s", override[0], hd.user)
287                     : String.format("%s - %s was updated",data.user,data.role);
288                 break;
289             case delete: 
290                 hd.memo = hdRole.memo = memo
291                     ? String.format("%s by %s", override[0], hd.user)
292                     : String.format("%s removed from %s",data.user,data.role);
293                 try {
294                     hd.reconstruct = hdRole.reconstruct = data.bytify();
295                 } catch (IOException e) {
296                     trans.warn().log(e,"Deleted UserRole could not be serialized");
297                 }
298                 break;
299             default:
300                 hd.memo = hdRole.memo = memo
301                 ? String.format("%s by %s", override[0], hd.user)
302                 : "n/a";
303         }
304
305         if (historyDAO.create(trans, hd).status!=Status.OK) {
306             trans.error().log("Cannot log to History");
307         }
308         
309         if (historyDAO.create(trans, hdRole).status!=Status.OK) {
310             trans.error().log("Cannot log to History");
311         }
312         // uses User as Segment
313         if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) {
314             trans.error().log("Cannot touch CacheInfo");
315         }
316     }
317 }