Merge "Sonar Fix: Owner.java"
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / update / NotifyCredExpiring.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.update;
23
24 import java.io.File;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.PrintStream;
28 import java.text.ParseException;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.Comparator;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Set;
39 import java.util.TreeMap;
40
41 import org.onap.aaf.auth.batch.Batch;
42 import org.onap.aaf.auth.batch.BatchPrincipal;
43 import org.onap.aaf.auth.batch.actions.Email;
44 import org.onap.aaf.auth.batch.actions.EmailPrint;
45 import org.onap.aaf.auth.batch.actions.Message;
46 import org.onap.aaf.auth.batch.helpers.Cred;
47 import org.onap.aaf.auth.batch.helpers.NS;
48 import org.onap.aaf.auth.batch.helpers.Notification;
49 import org.onap.aaf.auth.batch.helpers.UserRole;
50 import org.onap.aaf.auth.batch.helpers.Notification.TYPE;
51 import org.onap.aaf.auth.dao.cass.CredDAO;
52 import org.onap.aaf.auth.dao.hl.Question;
53 import org.onap.aaf.auth.env.AuthzTrans;
54 import org.onap.aaf.auth.layer.Result;
55 import org.onap.aaf.auth.org.EmailWarnings;
56 import org.onap.aaf.auth.org.Organization;
57 import org.onap.aaf.auth.org.Organization.Identity;
58 import org.onap.aaf.auth.org.OrganizationException;
59 import org.onap.aaf.auth.org.OrganizationFactory;
60 import org.onap.aaf.cadi.CadiException;
61 import org.onap.aaf.cadi.util.CSV;
62 import org.onap.aaf.misc.env.APIException;
63 import org.onap.aaf.misc.env.Env;
64 import org.onap.aaf.misc.env.TimeTaken;
65 import org.onap.aaf.misc.env.util.Chrono;
66
67
68 public class NotifyCredExpiring extends Batch {
69
70     private static final String UNKNOWN_ID = "unknown@deprecated.id";
71     private static final String AAF_INSTANTIATED_MECHID = "AAF INSTANTIATED MECHID";
72     private static final String EXPIRATION_DATE = "EXPIRATION DATE";
73     private static final String QUICK_LINK = "QUICK LINK TO UPDATE PAGE";
74     private static final String DASH_1 = "-----------------------";
75     private static final String DASH_2 = "---------------";
76     private static final String DASH_3 = "----------------------------------------------------";
77     private static final String LINE = "\n----------------------------------------------------------------";
78     private Email email;
79     private int maxEmails;
80     private final PrintStream ps;
81     private final AuthzTrans noAvg;
82     private String supportEmailAddr;
83         private CSV csv;
84         private CSVInfo csvInfo;
85
86     public NotifyCredExpiring(AuthzTrans trans) throws APIException, IOException, OrganizationException {
87         super(trans.env());
88         TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE);
89         try {
90             session = cluster.connect();
91         } finally {
92             tt.done();
93         }
94         
95         noAvg = env.newTransNoAvg();
96         noAvg.setUser(new BatchPrincipal("batch:NotifyCredExpiring"));
97         
98         if (isDryRun()) {
99             email = new EmailPrint();
100             maxEmails=3;
101             maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3"));
102         } else {
103             email = new Email();
104             maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3"));
105         }
106         
107         email.subject("AAF Password Expiration Notification (ENV: %s)",batchEnv);
108         email.preamble("AAF (MOTS 22830) is the AT&T Authorization System used by many AT&T Tools and Applications.\n\n" +
109                 "  The following Credentials are expiring on the dates shown. Failure to act before the expiration date "
110                 + "will cause your App's Authentications to fail.\n");
111         email.signature("Sincerely,\nAAF Team (Our MOTS# 22830)\n"
112                 + "https://wiki.web.att.com/display/aaf/Contact+Us\n"
113                 + "(Use 'Other Misc Requests (TOPS)')");
114         
115         boolean quit = false;
116         if(args().length<1) {
117                 System.err.println("Need CSV formatted Expiring Report");
118                 quit = true;
119         } else {
120                 File f = new File(logDir(),args()[0]);
121                 System.out.println("Reading " + f.getCanonicalPath());
122                 csv = new CSV(f);
123         }
124         
125         if(args().length<2) {
126                 System.err.println("Need Email Template");
127                 //quit = true;
128         }
129         if(quit) {
130                 System.exit(2);
131         }
132         
133         csvInfo = new CSVInfo(System.err);
134         try {
135                         csv.visit(csvInfo);
136                 } catch (CadiException e) {
137                         throw new APIException(e);
138                 }
139         
140         Notification.load(trans, session, Notification.v2_0_18);
141         
142         ps = new PrintStream(new FileOutputStream(logDir() + "/email"+Chrono.dateOnlyStamp()+".log",true));
143         ps.printf("### Approval Notify %s for %s%s\n",Chrono.dateTime(),batchEnv,dryRun?", DryRun":"");
144     }
145     
146     @Override
147     protected void run(AuthzTrans trans) {
148         
149         // Temp structures
150         Map<String,List<LastCred>> ownerCreds = new TreeMap<>();
151         
152
153         List<LastCred> noOwner = new ArrayList<>();
154         ownerCreds.put(UNKNOWN_ID,noOwner);
155         int emailCount=0;
156
157 //        // Get a list of ONLY the ones needing email by Owner
158 //        for (Entry<String, List<Cred>> es : Cred.byNS.entrySet()) {
159 //            for (Cred c : es.getValue()) {
160 //                List<UserRole> ownerURList = UserRole.getByRole().get(es.getKey()+".owner");
161 //                if (ownerURList!=null) {
162 //                    for (UserRole ur:ownerURList) {
163 //                        String owner = ur.user();
164 //                        List<LastCred> llc = ownerCreds.get(owner);
165 //                        if (llc==null) {
166 //                            ownerCreds.put(owner, (llc=new ArrayList<>()));
167 //                        }
168 //                        llc.add(new LastCred(c,last));
169 //                    }
170 //                } else {
171 //                    noOwner.add(new LastCred(c,last));
172 //                }
173 //            }
174 //        }
175 //        
176 //        boolean bCritical,bNormal,bEarly;
177 //        Message msg = new Message();
178 //        Notification ownNotf;
179 //        StringBuilder logMessage = new StringBuilder();
180 //        for (Entry<String,List<LastCred>> es : ownerCreds.entrySet()) {
181 //            String owner = es.getKey();
182 //            boolean header = true;
183 //            try {
184 //                Organization org = OrganizationFactory.obtain(env, owner);
185 //                Identity user = org.getIdentity(noAvg, owner);
186 //                if (!UNKNOWN_ID.equals(owner) && user==null) {
187 //                    ps.printf("Invalid Identity: %s\n", owner);
188 //                } else {
189 //                    logMessage.setLength(0);
190 //                    if (maxEmails>emailCount) {
191 //                        bCritical=bNormal=bEarly = false;
192 //                        email.clear();
193 //                        msg.clear();
194 //                        email.addTo(user==null?supportEmailAddr:user.email());
195 //
196 //                        ownNotf = Notification.get(es.getKey(),TYPE.CN);
197 //                        if (ownNotf==null) {
198 //                            ownNotf = Notification.create(user==null?UNKNOWN_ID:user.fullID(), TYPE.CN);
199 //                        }
200 //                        last = ownNotf.last;
201 //                        // Get Max ID size for formatting purposes
202 //                        int length = AAF_INSTANTIATED_MECHID.length();
203 //                        for (LastCred lc : es.getValue()) {
204 //                            length = Math.max(length, lc.cred.id.length());
205 //                        }
206 //                        String id_exp_fmt = "\t%-"+length+"s  %15s  %s";
207 //
208 //                        Collections.sort(es.getValue(),LastCred.COMPARE);
209 //                        for (LastCred lc : es.getValue()) {
210 //                            if (lc.last.after(must) && lc.last.before(early) && 
211 //                                (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) {
212 //                                if (!bEarly && header) {
213 //                                    msg.line("\tThe following are friendly 2 month reminders, just in case you need to schedule your updates early.  "
214 //                                            + "You will be reminded next month\n");
215 //                                    msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK);
216 //                                    msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3);
217 //                                    header = false;
218 //                                }
219 //                                bEarly = true;
220 //                            } else if (lc.last.after(critical) && lc.last.before(must) && 
221 //                                    (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) {
222 //                                if (!bNormal) {
223 //                                    boolean last2wks = lc.last.before(within2Weeks);
224 //                                    if (last2wks) {
225 //                                        try {
226 //                                            Identity supvsr = user.responsibleTo();
227 //                                            email.addCC(supvsr.email());
228 //                                        } catch (OrganizationException e) {
229 //                                            trans.error().log(e, "Supervisor cannot be looked up");
230 //                                        }
231 //                                    }
232 //                                    if (header) {
233 //                                        msg.line("\tIt is now important for you to update Passwords all all configurations using them for the following.\n" +
234 //                                                (last2wks?"\tNote: Your Supervisor is CCd\n":"\tNote: Your Supervisor will be notified if this is not being done before the last 2 weeks\n"));
235 //                                        msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK);
236 //                                        msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3);
237 //                                    }
238 //                                    header = false;
239 //                                }
240 //                                bNormal=true;
241 //                            } else if (lc.last.after(tooLate) && lc.last.before(critical)) { // Email Every Day, with Supervisor
242 //                                if (!bCritical && header) {
243 //                                    msg.line("\t!!! WARNING: These Credentials will expire in LESS THAN ONE WEEK !!!!\n" +
244 //                                             "\tYour supervisor is added to this Email\n");
245 //                                    msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK);
246 //                                    msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3);
247 //                                    header = false;
248 //                                }
249 //                                bCritical = true;
250 //                                try {
251 //                                    if (user!=null) {
252 //                                        Identity supvsr = user.responsibleTo();
253 //                                        if (supvsr!=null) {
254 //                                            email.addCC(supvsr.email());
255 //                                            supvsr = supvsr.responsibleTo();
256 //                                            if (supvsr!=null) {
257 //                                                email.addCC(supvsr.email());
258 //                                            }
259 //                                        }
260 //                                    }
261 //                                } catch (OrganizationException e) {
262 //                                    trans.error().log(e, "Supervisor cannot be looked up");
263 //                                }
264 //                            }
265 //                            if (bEarly || bNormal || bCritical) {
266 //                                if (logMessage.length()==0) {
267 //                                    logMessage.append("NotifyCredExpiring");
268 //                                }
269 //                                logMessage.append("\n\t");
270 //                                logMessage.append(lc.cred.id);
271 //                                logMessage.append('\t');
272 //                                logMessage.append(Chrono.dateOnlyStamp(lc.last));
273 //                                msg.line(id_exp_fmt, lc.cred.id, Chrono.dateOnlyStamp(lc.last)+"     ",env.getProperty(GUI_URL)+"/creddetail?ns="+Question.domain2ns(lc.cred.id));
274 //                            }
275 //                        }
276 //                        
277 //                        if (bEarly || bNormal || bCritical) {
278 //                            msg.line(LINE);
279 //                            msg.line("Why are you receiving this Notification?\n");
280 //                                msg.line("You are the listed owner of one or more AAF Namespaces. ASPR requires that those responsible for "
281 //                                        + "applications and their access review them regularly for accuracy.  The AAF WIKI page for AT&T is https://wiki.web.att.com/display/aaf.  "
282 //                                        + "You might like https://wiki.web.att.com/display/aaf/AAF+in+a+Nutshell.  More detailed info regarding questions of being a Namespace Owner is available at https://wiki.web.att.com/pages/viewpage.action?pageId=594741363\n");
283 //                                msg.line("You may view the Namespaces you listed as Owner for in this AAF Env by viewing the following webpage:\n");
284 //                                msg.line("   %s/ns\n\n",env.getProperty(GUI_URL));
285 //                            email.msg(msg);
286 //                            Result<Void> rv = email.exec(trans, org,"");
287 //                            if (rv.isOK()) {
288 //                                ++emailCount;
289 //                                if (!isDryRun()) {
290 //                                    ownNotf.update(noAvg, session, false);
291 //                                    // SET LastNotification
292 //                                }
293 //                                email.log(ps,logMessage.toString());
294 //                            } else {
295 //                                trans.error().log(rv.errorString());
296 //                            }
297 //                        }
298 //                    }
299 //                }
300 //            } catch (OrganizationException e) {
301 //                trans.info().log(e);
302 //            }
303 //        }
304         trans.info().printf("%d emails sent for %s", emailCount,batchEnv);
305     }
306     
307     
308     private static class CSVInfo implements CSV.Visitor {
309         private PrintStream out;
310         private Set<String> unsupported;
311         private NotifyCredVisitor credv;
312         private List<LastCred> llc;
313         
314         public CSVInfo(PrintStream out) {
315                 this.out = out;
316                 credv = new NotifyCredVisitor(llc = new ArrayList<>());
317         }
318         
319                 @Override
320                 public void visit(List<String> row) throws IOException, CadiException {
321                         
322                         switch(row.get(0)) {
323                            case NotifyCredVisitor.SUPPORTS:
324                                    credv.visit(row);
325                                    break;
326                            default:
327                                    if(unsupported==null) {
328                                            unsupported = new HashSet<String>();
329                                    }
330                                    if(!unsupported.contains(row.get(0))) {
331                                            unsupported.add(row.get(0));
332                                            out.println("Unsupported Type: " + row.get(0));
333                                    }
334                         }
335                 }
336     }
337     
338     private static class Contact {
339         public List<String> contacts;
340                 private List<UserRole> owners;
341         
342         public Contact(final String ns) {
343                 contacts = new ArrayList<>();
344                 loadFromNS(ns);
345         }
346         
347         public void loadFromNS(final String ns) {
348                 owners = UserRole.getByRole().get(ns+".owner");
349         }
350     }
351     
352     private static class LastCred extends Contact {
353         public final String id;
354         public final int type;
355         public final Date expires;
356         
357         public LastCred(final String id, final String ns, final int type, final Date expires) {
358                         super(ns);
359                         this.id = id;
360                         this.type = type;
361                         this.expires = expires;
362                 }
363     }
364     
365     private static class NotifyCredVisitor implements CSV.Visitor {
366         public static final String SUPPORTS = "cred";
367                 private final List<LastCred> lastCred;
368         
369         public NotifyCredVisitor(final List<LastCred> lastCred) {
370                 this.lastCred = lastCred;
371         }
372         
373                 @Override
374                 public void visit(List<String> row) throws IOException, CadiException {
375                          try {
376                                 lastCred.add(new LastCred(
377                                         row.get(1), 
378                                         row.get(2),
379                                         Integer.parseInt(row.get(3)), 
380                                         Chrono.dateOnlyFmt.parse(row.get(4))
381                                         )
382                                 );
383                         } catch (NumberFormatException | ParseException e) {
384                                 throw new CadiException(e);
385                         }
386                 }
387     }
388     
389     @Override
390     protected void _close(AuthzTrans trans) {
391         session.close();
392         ps.close();
393     }
394 }