Add Cred Reporting Mailer
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / helpers / Cred.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.batch.helpers;
23
24 import java.util.ArrayList;
25 import java.util.Date;
26 import java.util.GregorianCalendar;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Set;
31 import java.util.TreeMap;
32
33 import org.onap.aaf.auth.dao.cass.CredDAO;
34 import org.onap.aaf.auth.dao.hl.Question;
35 import org.onap.aaf.cadi.util.CSV;
36 import org.onap.aaf.misc.env.Env;
37 import org.onap.aaf.misc.env.TimeTaken;
38 import org.onap.aaf.misc.env.Trans;
39 import org.onap.aaf.misc.env.util.Chrono;
40
41 import com.datastax.driver.core.ResultSet;
42 import com.datastax.driver.core.Row;
43 import com.datastax.driver.core.Session;
44 import com.datastax.driver.core.SimpleStatement;
45 import com.datastax.driver.core.Statement;
46
47 public class Cred  {
48     public static final TreeMap<String,Cred> data = new TreeMap<>();
49     public static final TreeMap<String,List<Cred>> byNS = new TreeMap<>();
50
51     public final String id;
52     public final List<Instance> instances;
53     public final String ns;
54     
55     public Cred(String id) {
56         this.id = id;
57         instances = new ArrayList<>();
58         ns=Question.domain2ns(id);
59     }
60     
61     public static class Instance {
62         public final int type;
63         public final Date expires,written;
64         public final Integer other;
65         public final String tag;
66         public final Integer attn;
67         public final String notes;
68
69         
70         public Instance(int type, Date expires, Integer other, long written, String tag, int attn, String notes) {
71             this.type = type;
72             this.expires = expires;
73             this.other = other;
74             this.written = new Date(written);
75             this.tag = tag;
76             this.attn = attn;
77             this.notes = notes;
78         }
79         
80         public String toString() {
81                 return expires.toString() + ": " + type + ' ' + notes;
82         }
83     }
84     
85     public Date last(final int ... types) {
86         Date last = null;
87         for (Instance i : instances) {
88             if (types.length>0) { // filter by types, if requested
89                 boolean quit = true;
90                 for (int t : types) {
91                     if (t==i.type) {
92                         quit=false;
93                         break;
94                     }
95                 }
96                 if (quit) {
97                     continue;
98                 }
99             }
100             if (last==null || i.expires.after(last)) {
101                 last = i.expires;
102             }
103         }
104         return last;
105     }
106
107     
108     public Set<Integer> types() {
109         Set<Integer> types = new HashSet<>();
110         for (Instance i : instances) {
111             types.add(i.type);
112         }
113         return types;
114     }
115
116     public static void load(Trans trans, Session session, int ... types ) {
117         load(trans, session,"select id, type, expires, other, writetime(cred), tag, attn, notes from authz.cred;",types);
118         
119     }
120
121     public static void loadOneNS(Trans trans, Session session, String ns,int ... types ) {
122         load(trans, session,"select id, type, expires, other, writetime(cred), tag, attn, notes from authz.cred WHERE ns='" + ns + "';");
123     }
124
125     private static void load(Trans trans, Session session, String query, int ...types) {
126
127         trans.info().log( "query: " + query );
128         TimeTaken tt = trans.start("Read Creds", Env.REMOTE);
129        
130         ResultSet results;
131         try {
132             Statement stmt = new SimpleStatement( query );
133             results = session.execute(stmt);
134         } finally {
135             tt.done();
136         }
137         int count = 0;
138         try {
139             Iterator<Row> iter = results.iterator();
140             Row row;
141             tt = trans.start("Load Credentials", Env.SUB);
142             try {
143                 while (iter.hasNext()) {
144                     ++count;
145                     row = iter.next();
146                     int type = row.getInt(1);
147                     if (types.length>0) { // filter by types, if requested
148                         boolean hastype = false;
149                         for (int t : types) {
150                             if (t==type) {
151                                 hastype=true;
152                                 break;
153                             }
154                         }
155                         if (!hastype) {
156                             continue;
157                         }
158                     }
159                     add(row.getString(0), row.getInt(1),row.getTimestamp(2),row.getInt(3),row.getLong(4),
160                                 row.getString(5),row.getInt(6),row.getString(7));
161                 }
162             } finally {
163                 tt.done();
164             }
165         } finally {
166             trans.info().log("Found",count,"creds");
167         }
168     }
169
170     public static void add(
171                 final String id, 
172                 final int type,
173                 final Date timestamp,
174                 final int other,
175                 final long written,
176                 final String tag,
177                 final int attn,
178                 final String notes
179                 ) {
180         Cred cred = data.get(id);
181         if (cred==null) {
182             cred = new Cred(id);
183             data.put(id, cred);
184         }
185         cred.instances.add(new Instance(type, timestamp, other, written/1000,tag,attn,notes));
186         
187         List<Cred> lscd = byNS.get(cred.ns);
188         if (lscd==null) {
189             byNS.put(cred.ns, (lscd=new ArrayList<>()));
190         }
191         boolean found = false;
192         for (Cred c : lscd) {
193             if (c.id.equals(cred.id)) {
194                 found=true;
195                 break;
196             }
197         }
198         if (!found) {
199             lscd.add(cred);
200         }
201         }
202
203
204         /** 
205      * Count entries in Cred data.
206      * Note, as opposed to other methods, need to load the whole cred table for the Types.
207      * @param numbuckets 
208      * @return
209      */
210     public static CredCount count(int numbuckets) {
211         CredCount cc = new CredCount(numbuckets);
212         for (Cred c : data.values()) {
213             for (Instance ci : c.instances) {
214                 cc.inc(ci.type,ci.written, ci.expires);
215             }
216         }
217         return cc;
218     }
219
220     public static class CredCount {
221         public int raw[];
222         public int basic_auth[];
223         public int basic_auth_256[];
224         public int cert[];
225         public int x509Added[];
226         public int x509Expired[];
227         public Date dates[];
228         
229         public CredCount(int numbuckets) {
230             raw = new int[numbuckets];
231             basic_auth = new int[numbuckets];
232             basic_auth_256 = new int[numbuckets];
233             cert = new int[numbuckets];
234             x509Added = new int[numbuckets];
235             x509Expired = new int[numbuckets];
236             dates = new Date[numbuckets];
237             GregorianCalendar gc = new GregorianCalendar();
238             dates[0]=gc.getTime(); // now
239             gc.set(GregorianCalendar.DAY_OF_MONTH, 1);
240             gc.set(GregorianCalendar.HOUR, 0);
241             gc.set(GregorianCalendar.MINUTE, 0);
242             gc.set(GregorianCalendar.SECOND,0);
243             gc.set(GregorianCalendar.MILLISECOND,0);
244             gc.add(GregorianCalendar.MILLISECOND, -1); // last milli of month
245             for (int i=1;i<numbuckets;++i) {
246                 dates[i] = gc.getTime();
247                 gc.add(GregorianCalendar.MONTH, -1);
248             }
249             
250         }
251         
252         public void inc(int type, Date start, Date expires) {
253             for (int i=0;i<dates.length-1;++i) {
254                 if (start.before(dates[i])) {
255                     if (type==CredDAO.CERT_SHA256_RSA) {
256                         if (start.after(dates[i+1])) {
257                             ++x509Added[i];
258                         }
259                     }
260                     if (expires.after(dates[i])) {
261                         switch(type) {
262                             case CredDAO.RAW:
263                                 ++raw[i];
264                                 break;
265                             case CredDAO.BASIC_AUTH:
266                                 ++basic_auth[i];
267                                 break;
268                             case CredDAO.BASIC_AUTH_SHA256:
269                                 ++basic_auth_256[i];
270                                 break;
271                             case CredDAO.CERT_SHA256_RSA:
272                                 ++cert[i];
273                                 break;
274                         }
275                     }
276                 }
277             }
278         }
279
280         public long authCount(int idx) {
281             return (long)basic_auth[idx]+basic_auth_256[idx];
282         }
283         
284         public long x509Count(int idx) {
285             return cert[idx];
286         }
287
288     }
289     
290     public void row(final CSV.Writer csvw, final Instance inst) {
291         csvw.row("cred",id,ns,Integer.toString(inst.type),Chrono.dateOnlyStamp(inst.expires),
292                         inst.expires.getTime(),inst.tag,inst.attn,inst.notes);
293     }
294
295
296     public static void batchDelete(StringBuilder sb, List<String> row) {
297         sb.append("DELETE from authz.cred WHERE id='");
298         sb.append(row.get(1));
299         sb.append("' AND type=");
300         sb.append(Integer.parseInt(row.get(3)));
301         // Note: We have to work with long, because Expires is part of Key... can't easily do date.
302         sb.append(" AND expires=dateof(maxtimeuuid(");
303         sb.append(row.get(5));
304         sb.append("));\n");
305         }
306
307         public String toString() {
308         StringBuilder sb = new StringBuilder(id);
309         sb.append('[');
310         for (Instance i : instances) {
311             sb.append('{');
312             sb.append(i.type);
313             sb.append(",\"");
314             sb.append(i.expires);
315             sb.append("\"}");
316         }
317         sb.append(']');
318         return sb.toString();
319     }
320
321     /* (non-Javadoc)
322      * @see java.lang.Object#hashCode()
323      */
324     @Override
325     public int hashCode() {
326         return id.hashCode();
327     }
328
329     /* (non-Javadoc)
330      * @see java.lang.Object#equals(java.lang.Object)
331      */
332     @Override
333     public boolean equals(Object obj) {
334         return id.equals(obj);
335     }
336
337
338         public static String histSubject(List<String> row) {
339                 return row.get(1);
340         }
341
342
343         public static String histMemo(String fmt, String orgName, List<String> row) {
344                 return String.format(fmt, row.get(1),orgName,row.get(4));
345         }
346
347 }