Update Fixes from testing
[aaf/authz.git] / auth / auth-cass / src / main / java / org / onap / aaf / auth / dao / cass / CredDAO.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.security.SecureRandom;
30 import java.util.Date;
31 import java.util.List;
32
33 import org.onap.aaf.auth.dao.Bytification;
34 import org.onap.aaf.auth.dao.CIDAO;
35 import org.onap.aaf.auth.dao.Cached;
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.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.util.Chrono;
43
44 import com.datastax.driver.core.Cluster;
45 import com.datastax.driver.core.Row;
46
47 /**
48  * CredDAO manages credentials. 
49  * @author Jonathan
50  * Date: 7/19/13
51  */
52 public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> {
53     public static final String TABLE = "cred";
54     public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F
55     public static final int RAW = -1;
56     public static final int NONE = 0;
57     public static final int FQI = 10;
58     public static final int BASIC_AUTH = 1;
59     public static final int BASIC_AUTH_SHA256 = 2;
60     public static final int CERT_SHA256_RSA =200;
61     public static final SecureRandom srand = new SecureRandom();
62     
63     private HistoryDAO historyDAO;
64     private CIDAO<AuthzTrans> infoDAO;
65     private PSInfo psNS;
66     private PSInfo psID;
67     private PSInfo psIDBath;
68     
69     public CredDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException {
70         super(trans, CredDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
71         init(trans);
72     }
73
74     public CredDAO(AuthzTrans trans, HistoryDAO hDao, CacheInfoDAO ciDao) throws APIException, IOException {
75         super(trans, CredDAO.class.getSimpleName(),hDao, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
76         historyDAO = hDao;
77         infoDAO = ciDao;
78         init(trans);
79     }
80
81     public static final int KEYLIMIT = 3;
82     public static class Data extends CacheableData implements Bytification {
83         
84         public String                   id;
85         public Integer                  type;
86         public Date                     expires;
87         public Integer                  other;
88         public String                   ns;
89         public String                    tag;
90         public String                    notes;
91         public ByteBuffer               cred;  //   this is a blob in cassandra
92
93
94         @Override
95         public int[] invalidate(Cached<?,?> cache) {
96             return new int[] {
97                 seg(cache,id) // cache is for all entities
98             };
99         }
100         
101         @Override
102         public ByteBuffer bytify() throws IOException {
103             ByteArrayOutputStream baos = new ByteArrayOutputStream();
104             CredLoader.deflt.marshal(this,new DataOutputStream(baos));
105             return ByteBuffer.wrap(baos.toByteArray());
106         }
107         
108         @Override
109         public void reconstitute(ByteBuffer bb) throws IOException {
110             CredLoader.deflt.unmarshal(this, toDIS(bb));
111         }
112
113         public String toString() {
114             return id + ' ' + type + ' ' + Chrono.dateTime(expires);
115         }
116     }
117
118     public static class CredLoader extends Loader<Data> implements Streamer<Data>{
119         public static final int MAGIC=153323443;
120         public static final int VERSION=2;
121         public static final int BUFF_SIZE=48; // Note: 
122
123         public static final CredLoader deflt = new CredLoader(KEYLIMIT);
124         public CredLoader(int keylimit) {
125             super(keylimit);
126         }
127
128         @Override
129         public Data load(Data data, Row row) {
130             data.id = row.getString(0);
131             data.type = row.getInt(1);    // NOTE: in datastax driver,  If the int value is NULL, 0 is returned!
132             data.expires = row.getTimestamp(2);
133             data.other = row.getInt(3);
134             data.ns = row.getString(4);     
135             data.tag = row.getString(5);
136             data.notes = row.getString(6);
137             data.cred = row.getBytesUnsafe(7);            
138             return data;
139         }
140
141         @Override
142         protected void key(Data data, int _idx, Object[] obj) {
143             int idx = _idx;
144
145             obj[idx] = data.id;
146             obj[++idx] = data.type;
147             obj[++idx] = data.expires;
148         }
149
150         @Override
151         protected void body(Data data, int idx, Object[] obj) {
152             int i;
153             obj[i=idx] = data.other;
154             obj[++i] = data.ns;
155             obj[++i] = data.tag;
156             obj[++i] = data.notes;
157             obj[++i] = data.cred;
158         }
159
160         @Override
161         public void marshal(Data data, DataOutputStream os) throws IOException {
162             writeHeader(os,MAGIC,VERSION);
163             writeString(os, data.id);
164             os.writeInt(data.type);    
165             os.writeLong(data.expires==null?-1:data.expires.getTime());
166             os.writeInt(data.other==null?0:data.other);
167             writeString(os, data.ns);
168             writeString(os, data.tag);
169             writeString(os, data.notes);
170             if (data.cred==null) {
171                 os.writeInt(-1);
172             } else {
173                 int l = data.cred.limit()-data.cred.position();
174                 os.writeInt(l);
175                 os.write(data.cred.array(),data.cred.position(),l);
176             }
177         }
178
179         @Override
180         public void unmarshal(Data data, DataInputStream is) throws IOException {
181             /*int version = */readHeader(is,MAGIC,VERSION);
182             // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields
183             byte[] buff = new byte[BUFF_SIZE];
184             data.id = readString(is,buff);
185             data.type = is.readInt();
186             
187             long l = is.readLong();
188             data.expires = l<0?null:new Date(l);
189             data.other = is.readInt();
190             data.ns = readString(is,buff);
191             data.tag = readString(is,buff);
192             data.notes = readString(is,buff);
193             
194             int i = is.readInt();
195             data.cred=null;
196             if (i>=0) {
197                 byte[] bytes = new byte[i]; // a bit dangerous, but lessened because of all the previous sized data reads
198                 int read = is.read(bytes);
199                 if (read>0) {
200                     data.cred = ByteBuffer.wrap(bytes);
201                 }
202             }
203         }
204     }
205
206     private void init(AuthzTrans trans) throws APIException, IOException {
207         // Set up sub-DAOs
208         if (historyDAO==null) {
209             historyDAO = new HistoryDAO(trans,this);
210         }
211         if (infoDAO==null) {
212             infoDAO = new CacheInfoDAO(trans,this);
213         }
214         
215
216         String[] helpers = setCRUD(trans, TABLE, Data.class, CredLoader.deflt);
217         
218         psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
219                 " WHERE ns = ?", CredLoader.deflt,readConsistency);
220         
221         psID = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
222                 " WHERE id = ?", CredLoader.deflt,readConsistency);
223         
224         // NOTE: (type) in ((1),(2)) is valid for Cass 2.1.14.  After 2.1.14, more obvious
225         // syntax of type in (1,2) is available
226         // ALSO, 1 & 2 STAND FOR BASIC_AUTH (MD5) AND BASIC_AUTH_SHA256(with salt).
227         // If more Basic Auth Protocols become available, add here but do NOT
228         // add X509, and there can be man Certs, and we don't need to read them every time, or
229         // as discovered, or provide CASS Outage due to too many Certs to read.
230         psIDBath = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
231                 " WHERE id = ? and (type) in ((1),(2))", CredLoader.deflt,readConsistency);
232     }
233     
234     /* (non-Javadoc)
235      * @see org.onap.aaf.auth.dao.CassDAOImpl#create(org.onap.aaf.misc.env.TransStore, java.lang.Object)
236      */
237     @Override
238     public Result<Data> create(AuthzTrans trans, Data data) {
239         if(data.tag == null) {
240             if(data.type==0) {
241                 data.tag="PlaceHolder";
242             } else {
243                 long l = srand.nextLong();
244                 data.tag = Long.toHexString(l);
245             }
246         }
247         return super.create(trans, data);
248     }
249
250     public Result<List<Data>> readNS(AuthzTrans trans, String ns) {
251         return psNS.read(trans, R_TEXT, new Object[]{ns});
252     }
253     
254     public Result<List<Data>> readID(AuthzTrans trans, String id) {
255         return psID.read(trans, R_TEXT, new Object[]{id});
256     }
257     
258     public Result<List<Data>> readIDBAth(AuthzTrans trans, String id) {
259         return psIDBath.read(trans, R_TEXT, new Object[] {id});
260     }
261
262     /**
263      * Log Modification statements to History
264      *
265      * @param modified        which CRUD action was done
266      * @param data            entity data that needs a log entry
267      * @param overrideMessage if this is specified, we use it rather than crafting a history message based on data
268      */
269     @Override
270     protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
271         boolean memo = override.length>0 && override[0]!=null;
272         boolean subject = override.length>1 && override[1]!=null;
273
274         HistoryDAO.Data hd = HistoryDAO.newInitedData();
275         hd.user = trans.user();
276         hd.action = modified.name();
277         hd.target = TABLE;
278         hd.subject = subject?override[1]: data.id;
279         hd.memo = memo
280                 ? String.format("%s by %s", override[0], hd.user)
281                 : (modified.name() + "d credential for " + data.id);
282         String spacer = ": ";
283         if(data.notes!=null) {
284             hd.memo+=spacer + data.notes;
285             spacer = ", ";
286         }
287
288         if(data.tag!=null) {
289             hd.memo+=spacer + data.tag;
290         }
291
292         // Detail?
293            if (modified==CRUD.delete) {
294                     try {
295                         hd.reconstruct = data.bytify();
296                     } catch (IOException e) {
297                         trans.error().log(e,"Could not serialize CredDAO.Data");
298                     }
299                 }
300
301         if (historyDAO.create(trans, hd).status!=Status.OK) {
302             trans.error().log("Cannot log to History");
303         }
304         if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) {
305             trans.error().log("Cannot touch Cred");
306         }
307     }
308 }