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