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