summaryrefslogtreecommitdiffstats
path: root/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java
blob: d1a3b19ba4c62289bbdb9a190266681961b25b2d (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
/**
 * ============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.cadi.aaf.v2_0;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.onap.aaf.cadi.AbsUserCache;
import org.onap.aaf.cadi.Access;
import org.onap.aaf.cadi.CachedPrincipal;
import org.onap.aaf.cadi.CadiException;
import org.onap.aaf.cadi.User;
import org.onap.aaf.cadi.aaf.AAFPermission;
import org.onap.aaf.cadi.client.Future;
import org.onap.aaf.cadi.client.Rcli;
import org.onap.aaf.cadi.locator.SingleEndpointLocator;
import org.onap.aaf.cadi.lur.ConfigPrincipal;

import aaf.v2_0.CredRequest;

public class AAFAuthn<CLIENT> extends AbsUserCache<AAFPermission> {
    private AAFCon<CLIENT> con;
    private String realm;

    /**
     * Configure with Standard AAF properties, Stand alone
     * @param con
     * @throws Exception ..
     */
    // Package on purpose
    AAFAuthn(AAFCon<CLIENT> con) {
        super(con.access,con.cleanInterval,con.highCount,con.usageRefreshTriggerCount);
        this.con = con;
    }

    /**
     * Configure with Standard AAF properties, but share the Cache (with AAF Lur)
     * @param con
     * @throws Exception
     */
    // Package on purpose
    AAFAuthn(AAFCon<CLIENT> con, AbsUserCache<AAFPermission> cache) {
        super(cache);
        this.con = con;
    }

    /**
     * Return Native Realm of AAF Instance.
     *
     * @return
     */
    public String getRealm() {
        return realm;
    }

    /**
     * Returns null if ok, or an Error String;
     *
     * Convenience function.  Passes "null" for State object
     */
    public String validate(String user, String password) throws IOException {
        return validate(user,password,null);
    }

    /**
     * Returns null if ok, or an Error String;
     *
     * For State Object, you may put in HTTPServletRequest or AuthzTrans, if available.  Otherwise,
     * leave null
     *
     * @param user
     * @param password
     * @return
     * @throws IOException
     * @throws CadiException
     * @throws Exception
     */
    public String validate(String user, String password, Object state) throws IOException {
        password = access.decrypt(password, false);
        byte[] bytes = password.getBytes();
        User<AAFPermission> usr = getUser(user,bytes);

        if (usr != null && !usr.permExpired()) {
            if (usr.principal==null) {
                return "User already denied";
            } else {
                return null; // good
            }
        }

        AAFCachedPrincipal cp = new AAFCachedPrincipal(user, bytes, con.userExpires);
        // Since I've relocated the Validation piece in the Principal, just revalidate, then do Switch
        // Statement
        switch(cp.revalidate(state)) {
            case REVALIDATED:
                if (usr!=null) {
                    usr.principal = cp;
                } else {
                    addUser(new User<AAFPermission>(cp,con.userExpires));
                }
                return null;
            case INACCESSIBLE:
                return "AAF Inaccessible";
            case UNVALIDATED:
                addUser(new User<AAFPermission>(user,bytes,con.userExpires));
                return "user/pass combo invalid for " + user;
            case DENIED:
                return "AAF denies API for " + user;
            default:
                return "AAFAuthn doesn't handle Principal " + user;
        }
    }

    private class AAFCachedPrincipal extends ConfigPrincipal implements CachedPrincipal {
        private long expires;
        private long timeToLive;

        private AAFCachedPrincipal(String name, byte[] pass, int timeToLive) {
            super(name,pass);
            this.timeToLive = timeToLive;
            expires = timeToLive + System.currentTimeMillis();
        }

        public Resp revalidate(Object state) {
            int maxRetries = 15;
            try { // these SHOULD be an AAFConHttp and a AAFLocator or SingleEndpointLocator objects, but put in a try to be safe
                AAFConHttp forceCastCon = (AAFConHttp) con;
                if (forceCastCon.hman().loc instanceof SingleEndpointLocator) {
                    maxRetries = 1; // we cannot retry the single LGW gateway!
                } else {
                    AAFLocator forceCastLoc = (AAFLocator) forceCastCon.hman().loc;
                    maxRetries = forceCastLoc.maxIters();
                }
            } catch (Exception e) {
                access.log(Access.Level.DEBUG, e);
            }
            List<URI> attemptedUris = new ArrayList<>();
            URI thisUri = null;
            for (int retries = 0;; retries++) {
                try {
                    Miss missed = missed(getName(), getCred());
                    if (missed == null || missed.mayContinue()) {
                        CredRequest cr = new CredRequest();
                        cr.setId(getName());
                        cr.setPassword(new String(getCred()));
                        Rcli<CLIENT> client = con.clientIgnoreAlreadyAttempted(attemptedUris);
                        thisUri = client.getURI();
                        Future<String> fp = client.readPost("/authn/validate", con.credReqDF, cr);
                        //Rcli<CLIENT> client = con.client().forUser(con.basicAuth(getName(), new String(getCred())));
                        //Future<String> fp = client.read(
                        //        "/authn/basicAuth",
                        //        "text/plain"
                        //       );
                        if (fp.get(con.timeout)) {
                            expires = System.currentTimeMillis() + timeToLive;
                            addUser(new User<AAFPermission>(this, timeToLive));
                            return Resp.REVALIDATED;
                        } else {
                            addMiss(getName(), getCred());
                            return Resp.UNVALIDATED;
                        }
                    } else {
                        return Resp.UNVALIDATED;
                    }
                } catch (Exception e) {
                    if (thisUri != null)  {
                        attemptedUris.add(thisUri);
                    }
                    con.access.log(e);
                    if (retries > maxRetries) {
                        return Resp.INACCESSIBLE;
                    }
                }
            }
        }

        public long expires() {
            return expires;
        }
    }

}