Approval Batch, prep better JUnit
[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, CadiException {
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(env.access(),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                 csv.visit(csvInfo);
122         
123         Notification.load(trans, session, Notification.v2_0_18);
124         
125         ps = new PrintStream(new FileOutputStream(logDir() + "/email"+Chrono.dateOnlyStamp()+".log",true));
126         ps.printf("### Approval Notify %s for %s%s\n",Chrono.dateTime(),batchEnv,dryRun?", DryRun":"");
127     }
128     
129     @Override
130     protected void run(AuthzTrans trans) {
131         
132         // Temp structures
133         Map<String,List<LastCred>> ownerCreds = new TreeMap<>();
134         
135
136         List<LastCred> noOwner = new ArrayList<>();
137         ownerCreds.put(UNKNOWN_ID,noOwner);
138         int emailCount=0;
139
140 //        // Get a list of ONLY the ones needing email by Owner
141 //        for (Entry<String, List<Cred>> es : Cred.byNS.entrySet()) {
142 //            for (Cred c : es.getValue()) {
143 //                List<UserRole> ownerURList = UserRole.getByRole().get(es.getKey()+".owner");
144 //                if (ownerURList!=null) {
145 //                    for (UserRole ur:ownerURList) {
146 //                        String owner = ur.user();
147 //                        List<LastCred> llc = ownerCreds.get(owner);
148 //                        if (llc==null) {
149 //                            ownerCreds.put(owner, (llc=new ArrayList<>()));
150 //                        }
151 //                        llc.add(new LastCred(c,last));
152 //                    }
153 //                } else {
154 //                    noOwner.add(new LastCred(c,last));
155 //                }
156 //            }
157 //        }
158 //        
159 //        boolean bCritical,bNormal,bEarly;
160 //        Message msg = new Message();
161 //        Notification ownNotf;
162 //        StringBuilder logMessage = new StringBuilder();
163 //        for (Entry<String,List<LastCred>> es : ownerCreds.entrySet()) {
164 //            String owner = es.getKey();
165 //            boolean header = true;
166 //            try {
167 //                Organization org = OrganizationFactory.obtain(env, owner);
168 //                Identity user = org.getIdentity(noAvg, owner);
169 //                if (!UNKNOWN_ID.equals(owner) && user==null) {
170 //                    ps.printf("Invalid Identity: %s\n", owner);
171 //                } else {
172 //                    logMessage.setLength(0);
173 //                    if (maxEmails>emailCount) {
174 //                        bCritical=bNormal=bEarly = false;
175 //                        email.clear();
176 //                        msg.clear();
177 //                        email.addTo(user==null?supportEmailAddr:user.email());
178 //
179 //                        ownNotf = Notification.get(es.getKey(),TYPE.CN);
180 //                        if (ownNotf==null) {
181 //                            ownNotf = Notification.create(user==null?UNKNOWN_ID:user.fullID(), TYPE.CN);
182 //                        }
183 //                        last = ownNotf.last;
184 //                        // Get Max ID size for formatting purposes
185 //                        int length = AAF_INSTANTIATED_MECHID.length();
186 //                        for (LastCred lc : es.getValue()) {
187 //                            length = Math.max(length, lc.cred.id.length());
188 //                        }
189 //                        String id_exp_fmt = "\t%-"+length+"s  %15s  %s";
190 //
191 //                        Collections.sort(es.getValue(),LastCred.COMPARE);
192 //                        for (LastCred lc : es.getValue()) {
193 //                            if (lc.last.after(must) && lc.last.before(early) && 
194 //                                (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) {
195 //                                if (!bEarly && header) {
196 //                                    msg.line("\tThe following are friendly 2 month reminders, just in case you need to schedule your updates early.  "
197 //                                            + "You will be reminded next month\n");
198 //                                    msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK);
199 //                                    msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3);
200 //                                    header = false;
201 //                                }
202 //                                bEarly = true;
203 //                            } else if (lc.last.after(critical) && lc.last.before(must) && 
204 //                                    (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) {
205 //                                if (!bNormal) {
206 //                                    boolean last2wks = lc.last.before(within2Weeks);
207 //                                    if (last2wks) {
208 //                                        try {
209 //                                            Identity supvsr = user.responsibleTo();
210 //                                            email.addCC(supvsr.email());
211 //                                        } catch (OrganizationException e) {
212 //                                            trans.error().log(e, "Supervisor cannot be looked up");
213 //                                        }
214 //                                    }
215 //                                    if (header) {
216 //                                        msg.line("\tIt is now important for you to update Passwords all all configurations using them for the following.\n" +
217 //                                                (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"));
218 //                                        msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK);
219 //                                        msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3);
220 //                                    }
221 //                                    header = false;
222 //                                }
223 //                                bNormal=true;
224 //                            } else if (lc.last.after(tooLate) && lc.last.before(critical)) { // Email Every Day, with Supervisor
225 //                                if (!bCritical && header) {
226 //                                    msg.line("\t!!! WARNING: These Credentials will expire in LESS THAN ONE WEEK !!!!\n" +
227 //                                             "\tYour supervisor is added to this Email\n");
228 //                                    msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK);
229 //                                    msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3);
230 //                                    header = false;
231 //                                }
232 //                                bCritical = true;
233 //                                try {
234 //                                    if (user!=null) {
235 //                                        Identity supvsr = user.responsibleTo();
236 //                                        if (supvsr!=null) {
237 //                                            email.addCC(supvsr.email());
238 //                                            supvsr = supvsr.responsibleTo();
239 //                                            if (supvsr!=null) {
240 //                                                email.addCC(supvsr.email());
241 //                                            }
242 //                                        }
243 //                                    }
244 //                                } catch (OrganizationException e) {
245 //                                    trans.error().log(e, "Supervisor cannot be looked up");
246 //                                }
247 //                            }
248 //                            if (bEarly || bNormal || bCritical) {
249 //                                if (logMessage.length()==0) {
250 //                                    logMessage.append("NotifyCredExpiring");
251 //                                }
252 //                                logMessage.append("\n\t");
253 //                                logMessage.append(lc.cred.id);
254 //                                logMessage.append('\t');
255 //                                logMessage.append(Chrono.dateOnlyStamp(lc.last));
256 //                                msg.line(id_exp_fmt, lc.cred.id, Chrono.dateOnlyStamp(lc.last)+"     ",env.getProperty(GUI_URL)+"/creddetail?ns="+Question.domain2ns(lc.cred.id));
257 //                            }
258 //                        }
259 //                        
260 //                        if (bEarly || bNormal || bCritical) {
261 //                            msg.line(LINE);
262 //                            msg.line("Why are you receiving this Notification?\n");
263 //                                msg.line("You are the listed owner of one or more AAF Namespaces. ASPR requires that those responsible for "
264 //                                        + "applications and their access review them regularly for accuracy.  The AAF WIKI page for AT&T is https://wiki.web.att.com/display/aaf.  "
265 //                                        + "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");
266 //                                msg.line("You may view the Namespaces you listed as Owner for in this AAF Env by viewing the following webpage:\n");
267 //                                msg.line("   %s/ns\n\n",env.getProperty(GUI_URL));
268 //                            email.msg(msg);
269 //                            Result<Void> rv = email.exec(trans, org,"");
270 //                            if (rv.isOK()) {
271 //                                ++emailCount;
272 //                                if (!isDryRun()) {
273 //                                    ownNotf.update(noAvg, session, false);
274 //                                    // SET LastNotification
275 //                                }
276 //                                email.log(ps,logMessage.toString());
277 //                            } else {
278 //                                trans.error().log(rv.errorString());
279 //                            }
280 //                        }
281 //                    }
282 //                }
283 //            } catch (OrganizationException e) {
284 //                trans.info().log(e);
285 //            }
286 //        }
287         trans.info().printf("%d emails sent for %s", emailCount,batchEnv);
288     }
289     
290     
291     private static class CSVInfo implements CSV.Visitor {
292         private PrintStream out;
293         private Set<String> unsupported;
294         private NotifyCredVisitor credv;
295         private List<LastCred> llc;
296         
297         public CSVInfo(PrintStream out) {
298                 this.out = out;
299                 credv = new NotifyCredVisitor(llc = new ArrayList<>());
300         }
301         
302                 @Override
303                 public void visit(List<String> row) throws IOException, CadiException {
304                         
305                         switch(row.get(0)) {
306                            case NotifyCredVisitor.SUPPORTS:
307                                    credv.visit(row);
308                                    break;
309                            default:
310                                    if(unsupported==null) {
311                                            unsupported = new HashSet<String>();
312                                    }
313                                    if(!unsupported.contains(row.get(0))) {
314                                            unsupported.add(row.get(0));
315                                            out.println("Unsupported Type: " + row.get(0));
316                                    }
317                         }
318                 }
319     }
320     
321     private static class Contact {
322         public List<String> contacts;
323                 private List<UserRole> owners;
324         
325         public Contact(final String ns) {
326                 contacts = new ArrayList<>();
327                 loadFromNS(ns);
328         }
329         
330         public void loadFromNS(final String ns) {
331                 owners = UserRole.getByRole().get(ns+".owner");
332         }
333     }
334     
335     private static class LastCred extends Contact {
336         public final String id;
337         public final int type;
338         public final Date expires;
339         
340         public LastCred(final String id, final String ns, final int type, final Date expires) {
341                         super(ns);
342                         this.id = id;
343                         this.type = type;
344                         this.expires = expires;
345                 }
346     }
347     
348     private static class NotifyCredVisitor implements CSV.Visitor {
349         public static final String SUPPORTS = "cred";
350                 private final List<LastCred> lastCred;
351         
352         public NotifyCredVisitor(final List<LastCred> lastCred) {
353                 this.lastCred = lastCred;
354         }
355         
356                 @Override
357                 public void visit(List<String> row) throws IOException, CadiException {
358                          try {
359                                 lastCred.add(new LastCred(
360                                         row.get(1), 
361                                         row.get(2),
362                                         Integer.parseInt(row.get(3)), 
363                                         Chrono.dateOnlyFmt.parse(row.get(4))
364                                         )
365                                 );
366                         } catch (NumberFormatException | ParseException e) {
367                                 throw new CadiException(e);
368                         }
369                 }
370     }
371     
372     @Override
373     protected void _close(AuthzTrans trans) {
374         session.close();
375         ps.close();
376     }
377 }