Update for more Logging Info
[aaf/authz.git] / auth / auth-cass / src / main / java / org / onap / aaf / auth / dao / cass / RoleDAO.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.HashSet;
30 import java.util.List;
31 import java.util.Set;
32
33 import org.onap.aaf.auth.dao.Bytification;
34 import org.onap.aaf.auth.dao.Cached;
35 import org.onap.aaf.auth.dao.CassAccess;
36 import org.onap.aaf.auth.dao.CassDAOImpl;
37 import org.onap.aaf.auth.dao.Loader;
38 import org.onap.aaf.auth.dao.Streamer;
39 import org.onap.aaf.auth.dao.hl.Question;
40 import org.onap.aaf.auth.env.AuthzTrans;
41 import org.onap.aaf.auth.layer.Result;
42 import org.onap.aaf.misc.env.APIException;
43 import org.onap.aaf.misc.env.util.Split;
44
45 import com.datastax.driver.core.Cluster;
46 import com.datastax.driver.core.Row;
47 import com.datastax.driver.core.exceptions.DriverException;
48
49 public class RoleDAO extends CassDAOImpl<AuthzTrans,RoleDAO.Data> {
50
51     public static final String TABLE = "role";
52     public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F
53     
54     private final HistoryDAO historyDAO;
55     private final CacheInfoDAO infoDAO;
56
57     private PSInfo psChildren, psNS, psName;
58
59     public RoleDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException {
60         super(trans, RoleDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
61         // Set up sub-DAOs
62         historyDAO = new HistoryDAO(trans, this);
63         infoDAO = new CacheInfoDAO(trans,this);
64         init(trans);
65     }
66
67     public RoleDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) {
68         super(trans, RoleDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
69         historyDAO = hDAO;
70         infoDAO = ciDAO;
71         init(trans);
72     }
73
74
75     //////////////////////////////////////////
76     // Data Definition, matches Cassandra DM
77     //////////////////////////////////////////
78     private static final int KEYLIMIT = 2;
79     /**
80      * Data class that matches the Cassandra Table "role"
81      * @author Jonathan
82      */
83     public static class Data extends CacheableData implements Bytification {
84         public String        ns;
85         public String        name;
86         public Set<String>  perms;
87         public String        description;
88
89         ////////////////////////////////////////
90         // Getters
91         public Set<String> perms(boolean mutable) {
92             if (perms == null) {
93                 perms = new HashSet<>();
94             } else if (mutable && !(perms instanceof HashSet)) {
95                 perms = new HashSet<>(perms);
96             }
97             return perms;
98         }
99         
100         public static Data create(NsDAO.Data ns, String name) {
101             NsSplit nss = new NsSplit(ns,name);        
102             RoleDAO.Data rv = new Data();
103             rv.ns = nss.ns;
104             rv.name=nss.name;
105             return rv;
106         }
107         
108         public String fullName() {
109                 StringBuilder sb = new StringBuilder();
110                 if(ns==null) {
111                         sb.append('.');
112                 } else {
113                 sb.append(ns.indexOf('@')<0?'.':':'); 
114                 }
115                 sb.append(name);
116                 return sb.toString();
117         }
118         
119         public String encode() {
120             return ns + '|' + name;
121         }
122         
123         /**
124          * Decode Perm String, including breaking into appropriate Namespace
125          * 
126          * @param trans
127          * @param q
128          * @param r
129          * @return
130          */
131         public static Result<Data> decode(AuthzTrans trans, Question q, String r) {
132             String[] ss = Split.splitTrim('|', r,2);
133             Data data = new Data();
134             if (ss[1]==null) { // older 1 part encoding must be evaluated for NS
135                 Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]);
136                 if (nss.notOK()) {
137                     return Result.err(nss);
138                 }
139                 data.ns=nss.value.ns;
140                 data.name=nss.value.name;
141             } else { // new 4 part encoding
142                 data.ns=ss[0];
143                 data.name=ss[1];
144             }
145             return Result.ok(data);
146         }
147
148         /**
149          * Decode from UserRole Data
150          * @param urdd
151          * @return
152          */
153         public static RoleDAO.Data decode(UserRoleDAO.Data urdd) {
154             RoleDAO.Data rd = new RoleDAO.Data();
155             rd.ns = urdd.ns;
156             rd.name = urdd.rname;
157             return rd;
158         }
159
160
161         /**
162          * Decode Perm String, including breaking into appropriate Namespace
163          * 
164          * @param trans
165          * @param q
166          * @param p
167          * @return
168          */
169         public static Result<String[]> decodeToArray(AuthzTrans trans, Question q, String p) {
170             String[] ss = Split.splitTrim('|', p,2);
171             if (ss[1]==null) { // older 1 part encoding must be evaluated for NS
172                 Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]);
173                 if (nss.notOK()) {
174                     return Result.err(nss);
175                 }
176                 ss[0] = nss.value.ns;
177                 ss[1] = nss.value.name;
178             }
179             return Result.ok(ss);
180         }
181         
182         @Override
183         public int[] invalidate(Cached<?,?> cache) {
184             return new int[] {
185                 seg(cache,ns,name),
186                 seg(cache,ns),
187                 seg(cache,name),
188             };
189         }
190
191         @Override
192         public ByteBuffer bytify() throws IOException {
193             ByteArrayOutputStream baos = new ByteArrayOutputStream();
194             RoleLoader.deflt.marshal(this,new DataOutputStream(baos));
195             return ByteBuffer.wrap(baos.toByteArray());
196         }
197         
198         @Override
199         public void reconstitute(ByteBuffer bb) throws IOException {
200             RoleLoader.deflt.unmarshal(this, toDIS(bb));
201         }
202
203         @Override
204         public String toString() {
205             return ns + '.' + name;
206         }
207     }
208
209     private static class RoleLoader extends Loader<Data> implements Streamer<Data> {
210         public static final int MAGIC=923577343;
211         public static final int VERSION=1;
212         public static final int BUFF_SIZE=96;
213
214         public static final RoleLoader deflt = new RoleLoader(KEYLIMIT);
215         
216         public RoleLoader(int keylimit) {
217             super(keylimit);
218         }
219         
220         @Override
221         public Data load(Data data, Row row) {
222             // Int more efficient
223             data.ns = row.getString(0);
224             data.name = row.getString(1);
225             data.perms = row.getSet(2,String.class);
226             data.description = row.getString(3);
227             return data;
228         }
229
230         @Override
231         protected void key(Data data, int _idx, Object[] obj) {
232                 int idx = _idx;
233             obj[idx]=data.ns;
234             obj[++idx]=data.name;
235         }
236
237         @Override
238         protected void body(Data data, int _idx, Object[] obj) {
239                 int idx = _idx;
240             obj[idx]=data.perms;
241             obj[++idx]=data.description;
242         }
243
244         @Override
245         public void marshal(Data data, DataOutputStream os) throws IOException {
246             writeHeader(os,MAGIC,VERSION);
247             writeString(os, data.ns);
248             writeString(os, data.name);
249             writeStringSet(os,data.perms);
250             writeString(os, data.description);
251         }
252
253         @Override
254         public void unmarshal(Data data, DataInputStream is) throws IOException {
255             /*int version = */readHeader(is,MAGIC,VERSION);
256             // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields
257             byte[] buff = new byte[BUFF_SIZE];
258             data.ns = readString(is, buff);
259             data.name = readString(is,buff);
260             data.perms = readStringSet(is,buff);
261             data.description = readString(is,buff);
262         }
263     };
264
265     private void init(AuthzTrans trans) {
266         String[] helpers = setCRUD(trans, TABLE, Data.class, RoleLoader.deflt);
267         
268         psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
269                 " WHERE ns = ?", new RoleLoader(1),readConsistency);
270
271         psName = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
272                 " WHERE name = ?", new RoleLoader(1),readConsistency);
273
274         psChildren = new PSInfo(trans, SELECT_SP +  helpers[FIELD_COMMAS] +  " FROM " + TABLE + 
275                 " WHERE ns=? AND name > ? AND name < ?", 
276                 new RoleLoader(3) {
277             @Override
278             protected void key(Data data, int _idx, Object[] obj) {
279                     int idx = _idx;
280                 obj[idx] = data.ns;
281                 obj[++idx]=data.name + DOT;
282                 obj[++idx]=data.name + DOT_PLUS_ONE;
283             }
284         },readConsistency);
285         
286     }
287
288     public Result<List<Data>> readNS(AuthzTrans trans, String ns) {
289         return psNS.read(trans, R_TEXT + " NS " + ns, new Object[]{ns});
290     }
291
292     public Result<List<Data>> readName(AuthzTrans trans, String name) {
293         return psName.read(trans, R_TEXT + name, new Object[]{name});
294     }
295
296     public Result<List<Data>> readChildren(AuthzTrans trans, String ns, String role) {
297         if (role.length()==0 || "*".equals(role)) {
298             return psChildren.read(trans, R_TEXT, new Object[]{ns, FIRST_CHAR, LAST_CHAR}); 
299         } else {
300             return psChildren.read(trans, R_TEXT, new Object[]{ns, role+DOT, role+DOT_PLUS_ONE});
301         }
302     }
303
304     /**
305      * Add a single Permission to the Role's Permission Collection
306      * 
307      * @param trans
308      * @param role
309      * @param perm
310      * @param type
311      * @param action
312      * @return
313      */
314     public Result<Void> addPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) {
315         // Note: Prepared Statements for Collection updates aren't supported
316         String pencode = perm.encode();
317         try {
318             getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms + {'" + 
319                 pencode + "'} WHERE " +
320                 "ns = '" + role.ns + "' AND name = '" + role.name + "';");
321         } catch (DriverException | APIException | IOException e) {
322             reportPerhapsReset(trans,e);
323             return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
324         }
325
326         wasModified(trans, CRUD.update, role, "Added permission " + pencode + " to role " + role.fullName());
327         return Result.ok();
328     }
329
330     /**
331      * Remove a single Permission from the Role's Permission Collection
332      * @param trans
333      * @param role
334      * @param perm
335      * @param type
336      * @param action
337      * @return
338      */
339     public Result<Void> delPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) {
340         // Note: Prepared Statements for Collection updates aren't supported
341
342         String pencode = perm.encode();
343         
344         //ResultSet rv =
345         try {
346             getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms - {'" + 
347                 pencode    + "'} WHERE " +
348                 "ns = '" + role.ns + "' AND name = '" + role.name + "';");
349         } catch (DriverException | APIException | IOException e) {
350             reportPerhapsReset(trans,e);
351             return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
352         }
353
354         //TODO how can we tell when it doesn't?
355         wasModified(trans, CRUD.update, role, "Removed permission " + pencode + " from role " + role.fullName() );
356         return Result.ok();
357     }
358     
359     /**
360      * Add description to role
361      * 
362      * @param trans
363      * @param ns
364      * @param name
365      * @param description
366      * @return
367      */
368     public Result<Void> addDescription(AuthzTrans trans, String ns, String name, String description) {
369         try {
370             getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '" 
371                 + description + "' WHERE ns = '" + ns + "' AND name = '" + name + "';");
372         } catch (DriverException | APIException | IOException e) {
373             reportPerhapsReset(trans,e);
374             return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
375         }
376
377         Data data = new Data();
378         data.ns=ns;
379         data.name=name;
380         wasModified(trans, CRUD.update, data, "Added description " + description + " to role " + data.fullName(), null );
381         return Result.ok();
382     }
383     
384     
385     /**
386      * Log Modification statements to History
387      * @param modified           which CRUD action was done
388      * @param data               entity data that needs a log entry
389      * @param overrideMessage    if this is specified, we use it rather than crafting a history message based on data
390      */
391     @Override
392     protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
393         boolean memo = override.length>0 && override[0]!=null;
394         boolean subject = override.length>1 && override[1]!=null;
395
396         HistoryDAO.Data hd = HistoryDAO.newInitedData();
397         hd.user = trans.user();
398         hd.action = modified.name();
399         hd.target = TABLE;
400         hd.subject = subject ? override[1] : data.fullName();
401         hd.memo = memo ? override[0] : (data.fullName() + " was "  + modified.name() + 'd' );
402         if (modified==CRUD.delete) {
403             try {
404                 hd.reconstruct = data.bytify();
405             } catch (IOException e) {
406                 trans.error().log(e,"Could not serialize RoleDAO.Data");
407             }
408         }
409
410         if (historyDAO.create(trans, hd).status!=Status.OK) {
411             trans.error().log("Cannot log to History");
412         }
413         if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) {
414             trans.error().log("Cannot touch CacheInfo for Role");
415         }
416     }
417
418     
419 }