summaryrefslogtreecommitdiffstats
path: root/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/AAFcli.java
blob: 72aa0ccd62760b9ce93443589324119da0b8b2d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/**
 * ============LICENSE_START====================================================
 * org.onap.aaf
 * ===========================================================================
 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
 * ===========================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END====================================================
 *
 */

package org.onap.aaf.auth.cmd;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.onap.aaf.auth.cmd.mgmt.Mgmt;
import org.onap.aaf.auth.cmd.ns.NS;
import org.onap.aaf.auth.cmd.perm.Perm;
import org.onap.aaf.auth.cmd.role.Role;
import org.onap.aaf.auth.cmd.user.User;
import org.onap.aaf.auth.common.Define;
import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.Access;
import org.onap.aaf.cadi.CadiException;
import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.PropAccess;
import org.onap.aaf.cadi.SecuritySetter;
import org.onap.aaf.cadi.Access.Level;
import org.onap.aaf.cadi.aaf.v2_0.AAFLocator;
import org.onap.aaf.cadi.client.Retryable;
import org.onap.aaf.cadi.config.Config;
import org.onap.aaf.cadi.config.SecurityInfoC;
import org.onap.aaf.cadi.http.HBasicAuthSS;
import org.onap.aaf.cadi.http.HMangr;
import org.onap.aaf.cadi.sso.AAFSSO;
import org.onap.aaf.misc.env.APIException;

import jline.console.ConsoleReader;

public class AAFcli {
	private static final String HTTPS = "https://";
	protected static PrintWriter pw;
	protected HMangr hman;
	// Storage for last reused client. We can do this
	// because we're technically "single" threaded calls.
	public Retryable<?> prevCall;

	protected SecuritySetter<HttpURLConnection> ss;
//	protected AuthzEnv env;
	private boolean close;
	private List<Cmd> cmds;

	// Lex State
	private ArrayList<Integer> expect = new ArrayList<Integer>();
	private boolean verbose = true;
	private int delay;
	private SecurityInfoC<HttpURLConnection> si;
	private boolean request = false;
	private String force = null;
	private boolean gui = false;
	// Package on purpose
	Access access;
	AuthzEnv env;

	private static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF);
	private static boolean isConsole = false;
	private static boolean isTest = false;
	private static boolean showDetails = false;
	private static boolean ignoreDelay = false;
	private static int globalDelay=0;
	
	public static int timeout() {
		return TIMEOUT;
	}

	// Create when only have Access
	public AAFcli(Access access, Writer wtr, HMangr hman, SecurityInfoC<HttpURLConnection> si, SecuritySetter<HttpURLConnection> ss) throws APIException {
		this(access,new AuthzEnv(access.getProperties()),wtr,hman, si,ss);
	}

	public AAFcli(Access access, AuthzEnv env, Writer wtr, HMangr hman, SecurityInfoC<HttpURLConnection> si, SecuritySetter<HttpURLConnection> ss) throws APIException {
		this.env = env;
		this.access = access;
		this.ss = ss;
		this.hman = hman;
		this.si = si;
		if (wtr instanceof PrintWriter) {
			pw = (PrintWriter) wtr;
			close = false;
		} else {
			pw = new PrintWriter(wtr);
			close = true;
		}


		/*
		 * Create Cmd Tree
		 */
		cmds = new ArrayList<Cmd>();

		Role role = new Role(this);
		cmds.add(new Help(this, cmds));
		cmds.add(new Version(this));
		cmds.add(new Perm(role));
		cmds.add(role);
		cmds.add(new User(this));
		cmds.add(new NS(this));
		cmds.add(new Mgmt(this));
	}

	public void verbose(boolean v) {
		verbose = v;
	}

	public void close() {
		if (hman != null) {
			hman.close();
			hman = null;
		}
		if (close) {
			pw.close();
		}
	}

	public boolean eval(String line) throws Exception {
		if (line.length() == 0) {
			return true;
		} else if (line.startsWith("#")) {
			pw.println(line);
			return true;
		}

		String[] largs = argEval(line);
		int idx = 0;

		// Variable replacement
		StringBuilder sb = null;
		while (idx < largs.length) {
			int e = 0;
			for (int v = largs[idx].indexOf("@["); v >= 0; v = largs[idx].indexOf("@[", v + 1)) {
				if (sb == null) {
					sb = new StringBuilder();
				}
				sb.append(largs[idx], e, v);
				if ((e = largs[idx].indexOf(']', v)) >= 0) {
					String p = access.getProperty(largs[idx].substring(v + 2, e),null);
					if(p==null) {
						p = System.getProperty(largs[idx].substring(v+2,e));
					}
					++e;
					if (p != null) {
						sb.append(p);
					}
				}
			}
			if (sb != null && sb.length() > 0) {
				sb.append(largs[idx], e, largs[idx].length());
				largs[idx] = sb.toString();
				sb.setLength(0);
			}
			++idx;
		}

		idx = 0;
		boolean rv = true;
		while (rv && idx < largs.length) {
			// Allow Script to change Credential
			if (!gui) {
				if("as".equalsIgnoreCase(largs[idx])) {
					if (largs.length > ++idx) {
						// get Password from Props with ID as Key
						String user = largs[idx++];
						int colon = user.indexOf(':');
						String pass;
						if (colon > 0) {
							pass = user.substring(colon + 1);
							user = user.substring(0, colon);
						} else {
							pass = access.getProperty(user, null);
						}
						if (pass != null) {
							pass = access.decrypt(pass, false);
							access.getProperties().put(user, pass);
							ss = new HBasicAuthSS(si, user, pass);
							pw.println("as " + user);
						} else { // get Pass from System Properties, under name of
							// Tag
							pw.println("ERROR: No password set for " + user);
							rv = false;
						}
						continue;
					}
				} else if ("expect".equalsIgnoreCase(largs[idx])) {
					expect.clear();
					if (largs.length > idx++) {
						if (!"nothing".equals(largs[idx])) {
							for (String str : largs[idx].split(",")) {
								try {
									if ("Exception".equalsIgnoreCase(str)) {
										expect.add(-1);
									} else {
										expect.add(Integer.parseInt(str));
									}
								} catch (NumberFormatException e) {
									throw new CadiException("\"expect\" should be followed by Number");
								}
							}
						++idx;
						}
					}
					continue;
					// Sleep, typically for reports, to allow DB to update
					// Milliseconds
					
				} else if ("sleep".equalsIgnoreCase(largs[idx])) {
					Integer t = Integer.parseInt(largs[++idx]);
					pw.println("sleep " + t);
					Thread.sleep(t);
					++idx;
					continue;
				} else if ("delay".equalsIgnoreCase(largs[idx])) {
					delay = Integer.parseInt(largs[++idx]);
					pw.println("delay " + delay);
					++idx;
					continue;
				} else if ("pause".equalsIgnoreCase(largs[idx])) {
					pw.println("Press <Return> to continue...");
					++idx;
					// Sonar insists we do something with the string, though it's only a pause.  Not very helpful...
					String sonar = new BufferedReader(new InputStreamReader(System.in)).readLine();
					sonar=""; // this useless code brought to you by Sonar.
					pw.print(sonar);
					continue;
				} else if ("exit".equalsIgnoreCase(largs[idx])) {
					pw.println("Exiting...");
					return false;
				}

			} 
			
			if("REQUEST".equalsIgnoreCase(largs[idx])) {
				request=true;
				++idx;
			} else if("FORCE".equalsIgnoreCase(largs[idx])) {
				force="true";
				++idx;
			} else if("DETAILS".equalsIgnoreCase(largs[idx])) {
				showDetails=true;
				++idx;
			} else if ("set".equalsIgnoreCase(largs[idx])) {
				while (largs.length > ++idx) {
					int equals = largs[idx].indexOf('=');
					String tag, value;
					if (equals < 0) {
						tag = largs[idx];
						value = access.getProperty(Config.AAF_APPPASS,null);
						if(value==null) {
							break;
						} else {
							value = access.decrypt(value, false);
							if(value==null) {
								break;
							}
							access.getProperties().put(tag, value);
							pw.println("set " + tag + " <encrypted>");
						}
					} else {
						tag = largs[idx].substring(0, equals);
						value = largs[idx].substring(++equals);
						pw.println("set " + tag + ' ' + value);
					}
					boolean isTrue = "TRUE".equalsIgnoreCase(value);
					if("FORCE".equalsIgnoreCase(tag)) {
						force = value;
					} else if("REQUEST".equalsIgnoreCase(tag)) {
						request = isTrue;
					} else if("DETAILS".equalsIgnoreCase(tag)) {
						showDetails = isTrue;
					} else {
						access.getProperties().put(tag, value);
					}
				}
				continue;
				// Allow Script to indicate if Failure is what is expected
			}

			int ret = 0;
			for (Cmd c : cmds) {
				if (largs[idx].equalsIgnoreCase(c.getName())) {
					if (verbose) {
						pw.println(line);
						if (expect.size() > 0) {
							pw.print("** Expect ");
							boolean first = true;
							for (Integer i : expect) {
								if (first) {
									first = false;
								} else {
									pw.print(',');
								}
								pw.print(i);
							}
							pw.println(" **");
						}
					}
					try {
						ret = c.exec(++idx, largs);
						if (delay+globalDelay > 0) {
							Thread.sleep((long)(delay+globalDelay));
						}
					} catch (Exception e) {
						if (expect.contains(-1)) {
							pw.println(e.getMessage());
							ret = -1;
						} else {
							throw e;
						}
					} finally {
						clearSingleLineProperties();
					}
					rv = expect.isEmpty() ? true : expect.contains(ret);
					if (verbose) {
						if (rv) {
							pw.println();
						} else {
							pw.print("!!! Unexpected Return Code: ");
							pw.print(ret);
							pw.println(", VALIDATE OUTPUT!!!");
						}
					}
					return rv;
				}
			}
			pw.write("Unknown Instruction \"");
			pw.write(largs[idx]);
			pw.write("\"\n");
			idx = largs.length;// always end after one command
		}
		return rv;
	}

	private String[] argEval(String line) {
		StringBuilder sb = new StringBuilder();
		ArrayList<String> arr = new ArrayList<String>();
		boolean start = true;
		char quote = 0;
		char last = 0;
		for (int i = 0; i < line.length(); ++i) {
			char ch;
			if (Character.isWhitespace(ch = line.charAt(i))) {
				if (start || last==',') {
					continue; // trim
				} else if (quote != 0) {
					sb.append(ch);
				} else {
					arr.add(sb.toString());
					sb.setLength(0);
					start = true;
				}
			} else if (ch == '\'' || ch == '"') { // toggle
				if (quote == ch) {
					quote = 0;
				} else {
					quote = ch;
				}
			} else if(ch=='|' && quote==0) {
				arr.add(sb.toString());
				sb.setLength(0);
				start = true;
			} else {
				start = false;
				sb.append(ch);
				last = ch;
			}
		}
		if (sb.length() > 0) {
			arr.add(sb.toString());
		}

		String[] rv = new String[arr.size()];
		arr.toArray(rv);
		return rv;
	}

	public static void keyboardHelp() {
		System.out.println("'C-' means hold the ctrl key down while pressing the next key.");
		System.out.println("'M-' means hold the alt key down while pressing the next key.");
		System.out.println("For instance, C-b means hold ctrl key and press b, M-b means hold alt and press b\n");

		System.out.println("Basic Keybindings:");
		System.out.println("\tC-l - clear screen");        
		System.out.println("\tC-a - beginning of line");
		System.out.println("\tC-e - end of line");
		System.out.println("\tC-b - backward character (left arrow also works)");
		System.out.println("\tM-b - backward word");
		System.out.println("\tC-f - forward character (right arrow also works)");
		System.out.println("\tM-f - forward word");
		System.out.println("\tC-d - delete character under cursor");
		System.out.println("\tM-d - delete word forward");
		System.out.println("\tM-backspace - delete word backward");
		System.out.println("\tC-k - delete from cursor to end of line");
		System.out.println("\tC-u - delete entire line, regardless of cursor position\n");

		System.out.println("Command History:");
		System.out.println("\tC-r - search backward in history (repeating C-r continues the search)");
		System.out.println("\tC-p - move backwards through history (up arrow also works)");
		System.out.println("\tC-n - move forwards through history (down arrow also works)\n");

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int rv = 0;
		
		try {
			AAFSSO aafsso = new AAFSSO(args);
			try {
				PropAccess access = aafsso.access();
				Define.set(access);
				AuthzEnv env = new AuthzEnv(access);
				
				StringBuilder err = aafsso.err();
				String noexit = access.getProperty("no_exit");
				if (err != null) {
					err.append("to continue...");
					System.err.println(err);
					if(noexit!=null) {
						System.exit(1);
					}
				}
	
				Reader rdr = null;
				boolean exitOnFailure = true;
				/*
				 * Check for "-" options anywhere in command line
				 */
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < args.length; ++i) {
					if ("-i".equalsIgnoreCase(args[i])) {
						rdr = new InputStreamReader(System.in);
						// } else if("-o".equalsIgnoreCase(args[i])) {
						// // shall we do something different? Output stream is
						// already done...
					} else if ("-f".equalsIgnoreCase(args[i])) {
						if (args.length > i + 1) {
							rdr = new FileReader(args[++i]);
						}
					} else if ("-a".equalsIgnoreCase(args[i])) {
						exitOnFailure = false;
					} else if ("-c".equalsIgnoreCase(args[i])) {
						isConsole = true;
					} else if ("-s".equalsIgnoreCase(args[i]) && args.length > i + 1) {
						access.setProperty(Cmd.STARTDATE, args[++i]);
					} else if ("-e".equalsIgnoreCase(args[i]) && args.length > i + 1) {
						access.setProperty(Cmd.ENDDATE, args[++i]);
					} else if ("-t".equalsIgnoreCase(args[i])) {
						isTest = true;
					} else if ("-d".equalsIgnoreCase(args[i])) {
						showDetails = true;
					} else if ("-n".equalsIgnoreCase(args[i])) {
						ignoreDelay = true;
					} else {
						if (sb.length() > 0) {
							sb.append(' ');
						}
						sb.append(args[i]);
					}
				}
	
				SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(access, HttpURLConnection.class);
				Locator<URI> loc;
				String aafUrl = access.getProperty(Config.AAF_URL);
				if(aafUrl==null) {
					aafsso.setLogDefault();
					aafsso.setStdErrDefault();
					aafUrl=AAFSSO.cons.readLine("aaf_url=%s", HTTPS);
					if(aafUrl.length()==0) {
						System.exit(0);
					} else if(!aafUrl.startsWith(HTTPS)) {
						aafUrl=HTTPS+aafUrl;
					}
					aafsso.addProp(Config.AAF_URL, aafUrl);
				} 
				// Note, with AAF Locator, this may not longer be necessary 3/2018 Jonathan
				if(!aafsso.loginOnly()) {
					try {
						loc = new AAFLocator(si,new URI(aafUrl));
					} catch (Throwable t) {
						aafsso.setStdErrDefault();
						throw t;
					} finally {
						// Other Access is done writing to StdOut and StdErr, reset Std out
						aafsso.setLogDefault();
					}

					TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF));
					HMangr hman = new HMangr(access, loc).readTimeout(TIMEOUT).apiVersion("2.0");
					
					if(access.getProperty(Config.AAF_DEFAULT_REALM)==null) {
						access.log(Level.ERROR, Config.AAF_DEFAULT_REALM,"is required");
					}
		
					
					AAFcli aafcli = new AAFcli(access,env, new OutputStreamWriter(System.out), hman, si, 
						new HBasicAuthSS(si,aafsso.user(), access.decrypt(aafsso.enc_pass(),false)));
					if(!ignoreDelay) {
						File delay = new File("aafcli.delay");
						if(delay.exists()) {
							BufferedReader br = new BufferedReader(new FileReader(delay));
							try {
								globalDelay = Integer.parseInt(br.readLine());
							} catch(Exception e) {
								access.log(Level.DEBUG,e);
							} finally {
								br.close();
							}
						}
					}
					try {
						if (isConsole) {
							System.out.println("Type 'help' for short help or 'help -d' for detailed help with aafcli commands");
							System.out.println("Type '?' for help with command line editing");
							System.out.println("Type 'q', 'quit', or 'exit' to quit aafcli\n");
		
							ConsoleReader reader = new ConsoleReader();
							try {
								reader.setPrompt("aafcli > ");
			
								String line;
								while ((line = reader.readLine()) != null) {
									showDetails = (line.contains("-d"))?true:false;
			
									if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("q") || line.equalsIgnoreCase("exit")) {
										break;
									} else if (line.equalsIgnoreCase("--help -d") || line.equalsIgnoreCase("help -d") 
											|| line.equalsIgnoreCase("help")) {
										line = "--help";
									} else if (line.equalsIgnoreCase("cls")) {
										reader.clearScreen();
										continue;
									} else if (line.equalsIgnoreCase("?")) {
										keyboardHelp();
										continue;
									}
									try {
										aafcli.eval(line);
										pw.flush();
									} catch (Exception e) {
										pw.println(e.getMessage());
										pw.flush();
									}
								}
							} finally {
								reader.close();
							}
						} else if (rdr != null) {
							BufferedReader br = new BufferedReader(rdr);
							String line;
							while ((line = br.readLine()) != null) {
								if (!aafcli.eval(line) && exitOnFailure) {
									rv = 1;
									break;
								}
							}
						} else { // just run the command line
							aafcli.verbose(false);
							if (sb.length() == 0) {
								sb.append("--help");
							}
							rv = aafcli.eval(sb.toString()) ? 0 : 1;
						}
						
					} finally {
						aafcli.close();
		
						// Don't close if No Reader, or it's a Reader of Standard In
						if (rdr != null && !(rdr instanceof InputStreamReader)) {
							rdr.close();
						}
					}
				}
				aafsso.writeFiles();
			} finally {
				aafsso.close();
			}
			
		} catch (MessageException e) {
			System.out.println("MessageException caught");

			System.err.println(e.getMessage());
		} catch (Throwable e) {
			e.printStackTrace(System.err);
		}
		System.exit(rv);
	}

	public boolean isTest() {
		return AAFcli.isTest;
	}
	
	public boolean isDetailed() {
		return AAFcli.showDetails;
	}

	public String typeString(Class<?> cls, boolean json) {
		return "application/" + cls.getSimpleName() + "+" + (json ? "json" : "xml") + ";version=" + hman.apiVersion();
	}

	public String forceString() {
		return force;
	}

	public boolean addRequest() {
		return request;
	}

	public void clearSingleLineProperties() {
		force  = null;
		request = false;
		showDetails = false;
	}

	public void gui(boolean b) {
		gui  = b;
	}

}