9aebee52ee505d1419549834896400516c6e119e
[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  * Modifications Copyright (C) 2019 IBM.
7  * ===========================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END====================================================
20  *
21  */
22
23 package org.onap.aaf.auth.batch.helpers;
24
25 import java.util.ArrayList;
26 import java.util.Calendar;
27 import java.util.Date;
28 import java.util.GregorianCalendar;
29 import java.util.HashSet;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Set;
33 import java.util.SortedMap;
34 import java.util.TreeMap;
35
36 import org.onap.aaf.auth.dao.cass.CredDAO;
37 import org.onap.aaf.auth.dao.hl.Question;
38 import org.onap.aaf.cadi.util.CSV;
39 import org.onap.aaf.misc.env.Env;
40 import org.onap.aaf.misc.env.TimeTaken;
41 import org.onap.aaf.misc.env.Trans;
42 import org.onap.aaf.misc.env.util.Chrono;
43
44 import com.datastax.driver.core.ResultSet;
45 import com.datastax.driver.core.Row;
46 import com.datastax.driver.core.Session;
47 import com.datastax.driver.core.SimpleStatement;
48 import com.datastax.driver.core.Statement;
49
50 public class Cred  {
51     public static final SortedMap<String,Cred> data = new TreeMap<>();
52     protected static final SortedMap<String,List<Cred>> byNS = new TreeMap<>();
53
54     public final String id;
55     public final List<Instance> instances;
56     public final String ns;
57
58     public Cred(String id) {
59         this.id = id;
60         instances = new ArrayList<>();
61         ns=Question.domain2ns(id);
62     }
63
64     public static class Instance {
65         public final int type;
66         public final Date expires;
67         public final Date written;
68         public final Integer other;
69         public final String tag;
70         public List<Note> notes;
71
72
73         public Instance(int type, Date expires, Integer other, long written, String tag) {
74             this.type = type;
75             this.expires = expires;
76             this.other = other;
77             this.written = new Date(written);
78             this.tag = tag;
79         }
80
81         /**
82          * Usually returns Null...
83          * @return
84          */
85         public List<Note> notes() {
86             return notes;
87         }
88
89         public void addNote(int level, String note) {
90             if(notes==null) {
91                 notes=new ArrayList<>();
92             }
93             notes.add(new Note(level,note));
94         }
95
96         public String toString() {
97             return expires.toString() + ": " + type + ' ' + tag;
98         }
99     }
100
101     public static class Note {
102         public final int level;
103         public final String note;
104
105         public Note(int level, String note) {
106             this.level = level;
107             this.note = note;
108         }
109     }
110     public Date last(final int ... types) {
111         Date last = null;
112         for (Instance i : instances) {
113             if (types.length>0) { // filter by types, if requested
114                 boolean quit = true;
115                 for (int t : types) {
116                     if (t==i.type) {
117                         quit=false;
118                         break;
119                     }
120                 }
121                 if (quit) {
122                     continue;
123                 }
124             }
125             if (last==null || i.expires.after(last)) {
126                 last = i.expires;
127             }
128         }
129         return last;
130     }
131
132
133     public Set<Integer> types() {
134         Set<Integer> types = new HashSet<>();
135         for (Instance i : instances) {
136             types.add(i.type);
137         }
138         return types;
139     }
140
141     public static void load(Trans trans, Session session, int ... types ) {
142         load(trans, session,"select id, type, expires, other, writetime(cred), tag from authz.cred;",types);
143     }
144
145     public static void loadOneNS(Trans trans, Session session, String ns,int ... types ) {
146         load(trans, session,"select id, type, expires, other, writetime(cred), tag from authz.cred WHERE ns='" + ns + "';", types);
147     }
148
149     private static void load(Trans trans, Session session, String query, int ...types) {
150
151         trans.info().log( "query: " + query );
152         TimeTaken tt = trans.start("Read Creds", Env.REMOTE);
153
154         ResultSet results;
155         try {
156             Statement stmt = new SimpleStatement( query );
157             results = session.execute(stmt);
158         } finally {
159             tt.done();
160         }
161         int count = 0;
162         try {
163             Iterator<Row> iter = results.iterator();
164             Row row;
165             tt = trans.start("Load Credentials", Env.SUB);
166             try {
167                 while (iter.hasNext()) {
168                     ++count;
169                     row = iter.next();
170                     int type = row.getInt(1);
171                     if (types.length>0) { // filter by types, if requested
172                         boolean hastype = false;
173                         for (int t : types) {
174                             if (t==type) {
175                                 hastype=true;
176                                 break;
177                             }
178                         }
179                         if (!hastype) {
180                             continue;
181                         }
182                     }
183                     add(row.getString(0), row.getInt(1),row.getTimestamp(2),row.getInt(3),row.getLong(4),
184                             row.getString(5));
185                 }
186             } finally {
187                 tt.done();
188             }
189         } finally {
190             trans.info().log("Found",count,"creds");
191         }
192     }
193
194     public static void add(
195             final String id,
196             final int type,
197             final Date timestamp,
198             final int other,
199             final long written,
200             final String tag
201             ) {
202         Cred cred = data.get(id);
203         if (cred==null) {
204             cred = new Cred(id);
205             data.put(id, cred);
206         }
207         cred.instances.add(new Instance(type, timestamp, other, written/1000,tag));
208
209         List<Cred> lscd = byNS.get(cred.ns);
210         if (lscd==null) {
211             lscd=new ArrayList<>();
212             byNS.put(cred.ns,lscd);
213         }
214         boolean found = false;
215         for (Cred c : lscd) {
216             if (c.id.equals(cred.id)) {
217                 found=true;
218                 break;
219             }
220         }
221         if (!found) {
222             lscd.add(cred);
223         }
224     }
225
226
227     /**
228      * Count entries in Cred data.
229      * Note, as opposed to other methods, need to load the whole cred table for the Types.
230      * @param numbuckets
231      * @return
232      */
233     public static CredCount count(int numbuckets) {
234         CredCount cc = new CredCount(numbuckets);
235         for (Cred c : data.values()) {
236             for (Instance ci : c.instances) {
237                 cc.inc(ci.type,ci.written, ci.expires);
238             }
239         }
240         return cc;
241     }
242
243     public static class CredCount {
244         public int [] raw;
245         public int [] basicAuth;
246         public int [] basicAuth256;
247         public int [] cert;
248         public int [] x509Added;
249         public int [] x509Expired;
250         public Date [] dates;
251
252         public CredCount(int numbuckets) {
253             raw = new int[numbuckets];
254             basicAuth = new int[numbuckets];
255             basicAuth256 = new int[numbuckets];
256             cert = new int[numbuckets];
257             x509Added = new int[numbuckets];
258             x509Expired = new int[numbuckets];
259             dates = new Date[numbuckets];
260             GregorianCalendar gc = new GregorianCalendar();
261             dates[0]=gc.getTime(); // now
262             gc.set(Calendar.DAY_OF_MONTH, 1);
263             gc.set(Calendar.HOUR, 0);
264             gc.set(Calendar.MINUTE, 0);
265             gc.set(Calendar.SECOND,0);
266             gc.set(Calendar.MILLISECOND,0);
267             gc.add(Calendar.MILLISECOND, -1); // last milli of month
268             for (int i = 1; i < numbuckets; ++i) {
269                 dates[i] = gc.getTime();
270                 gc.add(Calendar.MONTH, -1);
271             }
272
273         }
274
275         public void inc(int type, Date start, Date expires) {
276             for (int i = 0; i < dates.length - 1; ++i) {
277                 if (start.before(dates[i])) {
278                     if ((type == CredDAO.CERT_SHA256_RSA)&&(start.after(dates[i + 1]))) {
279                             ++x509Added[i];
280                          }
281                     if (expires.after(dates[i])) {
282                         switch(type) {
283                             case CredDAO.RAW:
284                                 ++raw[i];
285                                 break;
286                             case CredDAO.BASIC_AUTH:
287                                 ++basicAuth[i];
288                                 break;
289                             case CredDAO.BASIC_AUTH_SHA256:
290                                 ++basicAuth256[i];
291                                 break;
292                             case CredDAO.CERT_SHA256_RSA:
293                                 ++cert[i];
294                                 break;
295                         }
296                     }
297                 }
298             }
299         }
300
301         public long authCount(int idx) {
302             return (long)basicAuth[idx] + basicAuth256[idx];
303         }
304
305         public long x509Count(int idx) {
306             return cert[idx];
307         }
308
309
310
311     }
312
313     public void row(final CSV.Writer csvw, final Instance inst) {
314         csvw.row("cred",id,ns,Integer.toString(inst.type),Chrono.dateOnlyStamp(inst.expires),
315                 inst.expires.getTime(),inst.tag);
316     }
317
318     public void row(final CSV.Writer csvw, final Instance inst, final String reason) {
319         csvw.row("cred",id,ns,Integer.toString(inst.type),Chrono.dateOnlyStamp(inst.expires),
320                 inst.expires.getTime(),inst.tag,reason);
321     }
322
323     public static void batchDelete(StringBuilder sb, List<String> row) {
324         long l = Long.parseLong(row.get(5));
325         String date = Chrono.batchFmt.format(new Date(l));
326         sb.append("DELETE from authz.cred WHERE id='");
327         sb.append(row.get(1));
328         sb.append("' AND type=");
329         sb.append(Integer.parseInt(row.get(3)));
330         // Note: We have to work with long, because Expires is part of Key... can't easily do date.
331         sb.append(" AND expires='");
332         sb.append(date);
333         sb.append("';\n");
334
335     }
336
337     public String toString() {
338         StringBuilder sb = new StringBuilder(id);
339         sb.append('[');
340         for (Instance i : instances) {
341             sb.append('{');
342             sb.append(i.type);
343             sb.append(",\"");
344             sb.append(i.expires);
345             sb.append("\"}");
346         }
347         sb.append(']');
348         return sb.toString();
349     }
350
351     /* (non-Javadoc)
352      * @see java.lang.Object#hashCode()
353      */
354     @Override
355     public int hashCode() {
356         return id.hashCode();
357     }
358
359     /* (non-Javadoc)
360      * @see java.lang.Object#equals(java.lang.Object)
361      */
362     @Override
363     public boolean equals(Object obj) {
364         return id.equals(obj);
365     }
366
367
368     public static String histSubject(List<String> row) {
369         return row.get(1);
370     }
371
372
373     public static String histMemo(String fmt, String orgName, List<String> row) {
374         String reason;
375         if(row.size()>5) { // Reason included
376             reason = row.get(5);
377         } else {
378             reason = String.format(fmt, row.get(1),orgName,row.get(4));
379         }
380         return reason;
381     }
382
383
384     public static void clear() {
385         data.clear();
386         byNS.clear();
387     }
388
389
390
391 }