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