26f9a995080eedaa60b704396bc2e2a5a19e2927
[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     }
146     
147     private static class URLoader extends Loader<Data> implements Streamer<Data> {
148         public static final int MAGIC=738469903;
149         public static final int VERSION=1;
150         public static final int BUFF_SIZE=48;
151         
152         public static final URLoader deflt = new URLoader(KEYLIMIT);
153
154         public URLoader(int keylimit) {
155             super(keylimit);
156         }
157
158         @Override
159         public Data load(Data data, Row row) {
160             data.user = row.getString(0);
161             data.role = row.getString(1);
162             data.ns = row.getString(2);
163             data.rname = row.getString(3);
164             data.expires = row.getTimestamp(4);
165             return data;
166         }
167
168         @Override
169         protected void key(Data data, int _idx, Object[] obj) {
170                 int idx = _idx;
171             obj[idx]=data.user;
172             obj[++idx]=data.role;
173         }
174
175         @Override
176         protected void body(Data data, int _idx, Object[] obj) {
177                 int idx = _idx;
178             obj[idx]=data.ns;
179             obj[++idx]=data.rname;
180             obj[++idx]=data.expires;
181         }
182         
183         @Override
184         public void marshal(Data data, DataOutputStream os) throws IOException {
185             writeHeader(os,MAGIC,VERSION);
186
187             writeString(os, data.user);
188             writeString(os, data.role);
189             writeString(os, data.ns);
190             writeString(os, data.rname);
191             os.writeLong(data.expires==null?-1:data.expires.getTime());
192         }
193
194         @Override
195         public void unmarshal(Data data, DataInputStream is) throws IOException {
196             /*int version = */readHeader(is,MAGIC,VERSION);
197             // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields
198             
199             byte[] buff = new byte[BUFF_SIZE];
200             data.user = readString(is,buff);
201             data.role = readString(is,buff);
202             data.ns = readString(is,buff);
203             data.rname = readString(is,buff);
204             long l = is.readLong();
205             data.expires = l<0?null:new Date(l);
206         }
207
208     };
209     
210     private void init(AuthzTrans trans) {
211         String[] helper = setCRUD(trans, TABLE, Data.class, URLoader.deflt);
212         
213         psByUser = new PSInfo(trans, SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE user = ?", 
214             new URLoader(1) {
215                 @Override
216                 protected void key(Data data, int idx, Object[] obj) {
217                     obj[idx]=data.user;
218                 }
219             },readConsistency);
220         
221         // Note: We understand this call may have poor performance, so only should be used in Management (Delete) func
222         psByRole = new PSInfo(trans, SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE role = ? ALLOW FILTERING", 
223                 new URLoader(1) {
224                     @Override
225                     protected void key(Data data, int idx, Object[] obj) {
226                         obj[idx]=data.role;
227                     }
228                 },readConsistency);
229         
230         psUserInRole = new PSInfo(trans,SELECT_SP + helper[FIELD_COMMAS] + " FROM user_role WHERE user = ? AND role = ?",
231                 URLoader.deflt,readConsistency);
232     }
233
234     public Result<List<Data>> readByUser(AuthzTrans trans, String user) {
235         return psByUser.read(trans, R_TEXT + " by User " + user, new Object[]{user});
236     }
237
238     /**
239      * Note: Use Sparingly. Cassandra's forced key structure means this will perform fairly poorly
240      * @param trans
241      * @param role
242      * @return
243      * @throws DAOException
244      */
245     public Result<List<Data>> readByRole(AuthzTrans trans, String role) {
246         return psByRole.read(trans, R_TEXT + " by Role " + role, new Object[]{role});
247     }
248     
249     /**
250      * Direct Lookup of User Role
251      * Don't forget to check for Expiration
252      */
253     public Result<List<Data>> readByUserRole(AuthzTrans trans, String user, String role) {
254         return psUserInRole.read(trans, R_TEXT + " by User " + user + " and Role " + role, new Object[]{user,role});
255     }
256
257
258     /**
259      * Log Modification statements to History
260      * @param modified           which CRUD action was done
261      * @param data               entity data that needs a log entry
262      * @param overrideMessage    if this is specified, we use it rather than crafting a history message based on data
263      */
264     @Override
265     protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
266         boolean memo = override.length>0 && override[0]!=null;
267         boolean subject = override.length>1 && override[1]!=null;
268
269         HistoryDAO.Data hd = HistoryDAO.newInitedData();
270         HistoryDAO.Data hdRole = HistoryDAO.newInitedData();
271         
272         hd.user = hdRole.user = trans.user();
273         hd.action = modified.name();
274         // Modifying User/Role is an Update to Role, not a Create.  Jonathan, 07-14-2015
275         hdRole.action = CRUD.update.name();
276         hd.target = TABLE;
277         hdRole.target = RoleDAO.TABLE;
278         hd.subject = subject?override[1] : (data.user + '|'+data.role);
279         hdRole.subject = data.role;
280         switch(modified) {
281             case create: 
282                 hd.memo = hdRole.memo = memo
283                     ? String.format("%s by %s", override[0], hd.user)
284                     : String.format("%s added to %s",data.user,data.role);    
285                 break;
286             case update: 
287                 hd.memo = hdRole.memo = memo
288                     ? String.format("%s by %s", override[0], hd.user)
289                     : String.format("%s - %s was updated",data.user,data.role);
290                 break;
291             case delete: 
292                 hd.memo = hdRole.memo = memo
293                     ? String.format("%s by %s", override[0], hd.user)
294                     : String.format("%s removed from %s",data.user,data.role);
295                 try {
296                     hd.reconstruct = hdRole.reconstruct = data.bytify();
297                 } catch (IOException e) {
298                     trans.warn().log(e,"Deleted UserRole could not be serialized");
299                 }
300                 break;
301             default:
302                 hd.memo = hdRole.memo = memo
303                 ? String.format("%s by %s", override[0], hd.user)
304                 : "n/a";
305         }
306
307         if (historyDAO.create(trans, hd).status!=Status.OK) {
308             trans.error().log("Cannot log to History");
309         }
310         
311         if (historyDAO.create(trans, hdRole).status!=Status.OK) {
312             trans.error().log("Cannot log to History");
313         }
314         // uses User as Segment
315         if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) {
316             trans.error().log("Cannot touch CacheInfo");
317         }
318     }
319 }