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