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