summaryrefslogtreecommitdiffstats
path: root/aaf/src/main/java/com/att/cadi/aaf/v2_0/AAFTaf.java
blob: 4e189ce1db87543d43e42f51cce1c8bc3eaae4a8 (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
/*******************************************************************************
 * ============LICENSE_START====================================================
 * * org.onap.aaf
 * * ===========================================================================
 * * Copyright © 2017 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====================================================
 * *
 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 * *
 ******************************************************************************/
package com.att.cadi.aaf.v2_0;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.att.cadi.AbsUserCache;
import com.att.cadi.Access.Level;
import com.att.cadi.CachedPrincipal;
import com.att.cadi.CachedPrincipal.Resp;
import com.att.cadi.GetCred;
import com.att.cadi.Hash;
import com.att.cadi.Taf.LifeForm;
import com.att.cadi.User;
import com.att.cadi.aaf.AAFPermission;
import com.att.cadi.client.Future;
import com.att.cadi.client.Rcli;
import com.att.cadi.principal.BasicPrincipal;
import com.att.cadi.principal.CachedBasicPrincipal;
import com.att.cadi.taf.HttpTaf;
import com.att.cadi.taf.TafResp;
import com.att.cadi.taf.TafResp.RESP;
import com.att.cadi.taf.basic.BasicHttpTafResp;

public class AAFTaf<CLIENT> extends AbsUserCache<AAFPermission> implements HttpTaf {
//	private static final String INVALID_AUTH_TOKEN = "Invalid Auth Token";
//	private static final String AUTHENTICATING_SERVICE_UNAVAILABLE = "Authenticating Service unavailable";
	private AAFCon<CLIENT> aaf;
	private boolean warn;

	public AAFTaf(AAFCon<CLIENT> con, boolean turnOnWarning) {
		super(con.access,con.cleanInterval,con.highCount, con.usageRefreshTriggerCount);
		aaf = con;
		warn = turnOnWarning;
	}

	public AAFTaf(AAFCon<CLIENT> con, boolean turnOnWarning, AbsUserCache<AAFPermission> other) {
		super(other);
		aaf = con;
		warn = turnOnWarning;
	}

	public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) {
		//TODO Do we allow just anybody to validate?

		// Note: Either Carbon or Silicon based LifeForms ok
		String authz = req.getHeader("Authorization");
		if(authz != null && authz.startsWith("Basic ")) {
			if(warn&&!req.isSecure())aaf.access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel");
			try {
				CachedBasicPrincipal bp;
				if(req.getUserPrincipal() instanceof CachedBasicPrincipal) {
					bp = (CachedBasicPrincipal)req.getUserPrincipal();
				} else {
					bp = new CachedBasicPrincipal(this,authz,aaf.getRealm(),aaf.userExpires);
				}
				// First try Cache
				User<AAFPermission> usr = getUser(bp);
				if(usr != null && usr.principal != null) {
					if(usr.principal instanceof GetCred) {
						if(Hash.isEqual(bp.getCred(),((GetCred)usr.principal).getCred())) {
							return new BasicHttpTafResp(aaf.access,bp,bp.getName()+" authenticated by cached AAF password",RESP.IS_AUTHENTICATED,resp,aaf.getRealm(),false);
						}
					}
				}
				
				Miss miss = missed(bp.getName());
				if(miss!=null && !miss.mayContinue(bp.getCred())) {
					return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req,
							"User/Pass Retry limit exceeded"), 
							RESP.FAIL,resp,aaf.getRealm(),true);
				}
				
				Rcli<CLIENT> userAAF = aaf.client(AAFCon.AAF_LATEST_VERSION).forUser(aaf.basicAuthSS(bp));
				Future<String> fp = userAAF.read("/authn/basicAuth", "text/plain");
				if(fp.get(aaf.timeout)) {
					if(usr!=null) {
						usr.principal = bp;
					} else {
						addUser(new User<AAFPermission>(bp,aaf.userExpires));
					}
					return new BasicHttpTafResp(aaf.access,bp,bp.getName()+" authenticated by AAF password",RESP.IS_AUTHENTICATED,resp,aaf.getRealm(),false);
				} else {
					// Note: AddMiss checks for miss==null, and is part of logic
					boolean rv= addMiss(bp.getName(),bp.getCred());
					if(rv) {
						return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req,
								"User/Pass combo invalid via AAF"), 
								RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),true);
					} else {
						return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req,
								"User/Pass combo invalid via AAF - Retry limit exceeded"), 
								RESP.FAIL,resp,aaf.getRealm(),true);
					}
				}
			} catch (IOException e) {
				String msg = buildMsg(null,req,"Invalid Auth Token");
				aaf.access.log(Level.WARN,msg,'(', e.getMessage(), ')');
				return new BasicHttpTafResp(aaf.access,null,msg, RESP.TRY_AUTHENTICATING, resp, aaf.getRealm(),true);
			} catch (Exception e) {
				String msg = buildMsg(null,req,"Authenticating Service unavailable");
				aaf.access.log(Level.WARN,msg,'(', e.getMessage(), ')');
				return new BasicHttpTafResp(aaf.access,null,msg, RESP.FAIL, resp, aaf.getRealm(),false);
			}
		}
		return new BasicHttpTafResp(aaf.access,null,"Requesting HTTP Basic Authorization",RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),false);
	}
	
	private String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) {
		StringBuilder sb = new StringBuilder();
		for(Object s : msg) {
			sb.append(s.toString());
		}
		if(pr!=null) {
			sb.append(" for ");
			sb.append(pr.getName());
		}
		sb.append(" from ");
		sb.append(req.getRemoteAddr());
		sb.append(':');
		sb.append(req.getRemotePort());
		return sb.toString();
	}


	
	public Resp revalidate(CachedPrincipal prin) {
		//  !!!! TEST THIS.. Things may not be revalidated, if not BasicPrincipal
		if(prin instanceof BasicPrincipal) {
			Future<String> fp;
			try {
				Rcli<CLIENT> userAAF = aaf.client(AAFCon.AAF_LATEST_VERSION).forUser(aaf.transferSS(prin));
				fp = userAAF.read("/authn/basicAuth", "text/plain");
				return fp.get(aaf.timeout)?Resp.REVALIDATED:Resp.UNVALIDATED;
			} catch (Exception e) {
				aaf.access.log(e, "Cannot Revalidate",prin.getName());
				return Resp.INACCESSIBLE;
			}
		}
		return Resp.NOT_MINE;
	}

}