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