mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Valery Kharseko
11.10.2025 4db17326cdaa92efa128a727782df5635f614c1a
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
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions copyright [year] [name of copyright owner]".
 *
 * Copyright 2016 ForgeRock AS.
 */
package org.forgerock.opendj.rest2ldap.authz;
 
import static org.forgerock.opendj.rest2ldap.authz.ConditionalFilters.asConditionalFilter;
import static org.forgerock.opendj.rest2ldap.authz.ConditionalFilters.newConditionalFilter;
import static org.forgerock.util.promise.Promises.newResultPromise;
 
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
import org.forgerock.http.Filter;
import org.forgerock.http.Handler;
import org.forgerock.http.filter.Filters;
import org.forgerock.http.oauth2.AccessTokenInfo;
import org.forgerock.http.oauth2.AccessTokenResolver;
import org.forgerock.http.oauth2.OAuth2Context;
import org.forgerock.http.oauth2.ResourceAccess;
import org.forgerock.http.oauth2.ResourceServerFilter;
import org.forgerock.http.protocol.Headers;
import org.forgerock.http.protocol.Request;
import org.forgerock.http.protocol.Response;
import org.forgerock.http.protocol.ResponseException;
import org.forgerock.http.protocol.Status;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.ConnectionFactory;
import org.forgerock.opendj.ldap.controls.ProxiedAuthV2RequestControl;
import org.forgerock.opendj.rest2ldap.AuthenticatedConnectionContext;
import org.forgerock.opendj.rest2ldap.authz.ConditionalFilters.Condition;
import org.forgerock.opendj.rest2ldap.authz.ConditionalFilters.ConditionalFilter;
import org.forgerock.services.context.Context;
import org.forgerock.services.context.SecurityContext;
import org.forgerock.util.Function;
import org.forgerock.util.Pair;
import org.forgerock.util.Reject;
import org.forgerock.util.promise.NeverThrowsException;
import org.forgerock.util.promise.Promise;
import org.forgerock.util.time.TimeService;
 
/** Factory methods to create {@link Filter} performing authentication and authorizations. */
public final class Authorization {
 
    private static final String OAUTH2_AUTHORIZATION_HEADER = "Authorization";
 
    /**
     * Creates a new {@link Filter} in charge of injecting an {@link AuthenticatedConnectionContext}. This
     * {@link Filter} tries each of the provided filters until one can apply. If no filter can be applied, the last
     * filter in the list will be applied allowing it to formulate a valid, implementation specific, error response.
     *
     * @param filters
     *            {@link Iterable} of authorization {@link ConditionalFilters} to try. If empty, the returned filter
     *            will always respond with 403 Forbidden.
     * @return A new authorization {@link Filter}
     */
    public static Filter newAuthorizationFilter(Iterable<? extends ConditionalFilter> filters) {
        return new AuthorizationFilter(filters);
    }
 
    /**
     * Creates a new {@link ConditionalFilter} performing authentication. If authentication succeed, it injects a
     * {@link SecurityContext} with the authenticationId provided by the user. Otherwise, returns a HTTP 401 -
     * Unauthorized response. The condition of this {@link ConditionalFilter} will return true if the supplied requests
     * contains credentials information, false otherwise.
     *
     * @param authenticationStrategy
     *            {@link AuthenticationStrategy} to validate the user's provided credentials.
     * @param credentialsExtractor
     *            Function to extract the credentials from the received request.
     * @throws NullPointerException
     *             if a parameter is null.
     * @return a new {@link ConditionalFilter}
     */
    public static ConditionalFilter newConditionalHttpBasicAuthenticationFilter(
            final AuthenticationStrategy authenticationStrategy,
            final Function<Headers, Pair<String, String>, NeverThrowsException> credentialsExtractor) {
        return newConditionalFilter(
                new HttpBasicAuthenticationFilter(authenticationStrategy, credentialsExtractor),
                new Condition() {
                    @Override
                    public boolean canApplyFilter(Context context, Request request) {
                        return credentialsExtractor.apply(request.getHeaders()) != null;
                    }
                });
    }
 
    /**
     * Creates a {@link ConditionalFilter} injecting an {@link AuthenticatedConnectionContext} with a connection issued
     * from the given connectionFactory. The condition is always true.
     *
     * @param connectionFactory
     *            The factory used to get the {@link Connection} to inject.
     * @return A new {@link ConditionalFilter}.
     * @throws NullPointerException
     *             if connectionFactory is null
     */
    public static ConditionalFilter newConditionalDirectConnectionFilter(ConnectionFactory connectionFactory) {
        return asConditionalFilter(new DirectConnectionFilter(connectionFactory));
    }
 
    /**
     * Creates a filter injecting an {@link AuthenticatedConnectionContext} given the information provided in the
     * {@link SecurityContext}. The connection contained in the created {@link AuthenticatedConnectionContext} will add
     * a {@link ProxiedAuthV2RequestControl} to each LDAP requests.
     *
     * @param connectionFactory
     *            The connection factory used to create the connection which will be injected in the
     *            {@link AuthenticatedConnectionContext}
     * @return A new filter.
     * @throws NullPointerException
     *             if connectionFactory is null
     */
    public static Filter newProxyAuthorizationFilter(ConnectionFactory connectionFactory) {
        return new ProxiedAuthV2Filter(connectionFactory);
    }
 
    /**
     * Creates a new {@link AccessTokenResolver} as defined in the RFC-7662.
     * <p>
     * @see <a href="https://tools.ietf.org/html/rfc7662">RFC-7662</a>
     *
     * @param httpClient
     *          Http client handler used to perform the request
     * @param introspectionEndPointURL
     *          Introspect endpoint URL to use to resolve the access token.
     * @param clientAppId
     *          Client application id to use in HTTP Basic authentication header.
     * @param clientAppSecret
     *          Client application secret to use in HTTP Basic authentication header.
     * @return A new {@link AccessTokenResolver} instance.
     */
    public static AccessTokenResolver newRfc7662AccessTokenResolver(final Handler httpClient,
                                                                    final URI introspectionEndPointURL,
                                                                    final String clientAppId,
                                                                    final String clientAppSecret) {
        return new Rfc7662AccessTokenResolver(httpClient, introspectionEndPointURL, clientAppId, clientAppSecret);
    }
 
    /**
     * Creates a new CTS access token resolver.
     *
     * @param connectionFactory
     *          The {@link ConnectionFactory} to use to perform search against the CTS.
     * @param ctsBaseDNTemplate
     *          The base DN template to use to resolve the access token DN.
     * @return A new CTS access token resolver.
     */
    public static AccessTokenResolver newCtsAccessTokenResolver(final ConnectionFactory connectionFactory,
                                                                final String ctsBaseDNTemplate) {
        return new CtsAccessTokenResolver(connectionFactory, ctsBaseDNTemplate);
    }
 
    /**
     * Creates a new file access token resolver which should only be used for test purpose.
     *
     * @param tokenFolder
     *          The folder where the access token to resolve must be stored.
     * @return A new file access token resolver which should only be used for test purpose.
     */
    public static AccessTokenResolver newFileAccessTokenResolver(final String tokenFolder) {
        return new FileAccessTokenResolver(tokenFolder);
    }
 
    /**
     * Creates a new OAuth2 authorization filter configured with provided parameters.
     *
     * @param realm
     *          The realm to displays in error responses.
     * @param scopes
     *          Scopes that an access token must have to be access a resource.
     * @param resolver
     *          The {@link AccessTokenResolver} to use to resolve an access token.
     * @param authzIdTemplate
     *          Authorization ID template.
     * @return A new OAuth2 authorization filter configured with provided parameters.
     */
    public static Filter newOAuth2ResourceServerFilter(final String realm,
                                                                  final Set<String> scopes,
                                                                  final AccessTokenResolver resolver,
                                                                  final String authzIdTemplate) {
        return createResourceServerFilter(realm, scopes, resolver, authzIdTemplate);
    }
 
    /**
     * Creates a new optional OAuth2 authorization filter configured with provided parameters.
     * <p>
     * This filter will be used only if an OAuth2 Authorization header is present in the incoming request.
     *
     * @param realm
     *          The realm to displays in error responses.
     * @param scopes
     *          Scopes that an access token must have to be access a resource.
     * @param resolver
     *          The {@link AccessTokenResolver} to use to resolve an access token.
     * @param authzIdTemplate
     *          Authorization ID template.
     * @return A new OAuth2 authorization filter configured with provided parameters.
     */
    public static ConditionalFilter newConditionalOAuth2ResourceServerFilter(final String realm,
                                                                             final Set<String> scopes,
                                                                             final AccessTokenResolver resolver,
                                                                             final String authzIdTemplate) {
        return new ConditionalFilter() {
            @Override
            public Filter getFilter() {
                return createResourceServerFilter(realm, scopes, resolver, authzIdTemplate);
            }
 
            @Override
            public Condition getCondition() {
                return new Condition() {
                    @Override
                    public boolean canApplyFilter(final Context context, final Request request) {
                        return request.getHeaders().containsKey(OAUTH2_AUTHORIZATION_HEADER);
                    }
                };
            }
        };
    }
 
    private static Filter createResourceServerFilter(final String realm,
                                                     final Set<String> scopes,
                                                     final AccessTokenResolver resolver,
                                                     final String authzIdTemplate) {
        Reject.ifTrue(realm == null || realm.isEmpty(), "realm must not be empty");
        Reject.ifNull(resolver, "Access token resolver must not be null");
        Reject.ifTrue(scopes == null || scopes.isEmpty(), "scopes set can not be empty");
        Reject.ifTrue(authzIdTemplate == null || authzIdTemplate.isEmpty(), "Authz id template must not be empty");
 
        final ResourceAccess scopesProvider = new ResourceAccess() {
            @Override
            public Set<String> getRequiredScopes(final Context context, final Request request)
                    throws ResponseException {
                return scopes;
            }
        };
 
        return Filters.chainOf(new ResourceServerFilter(resolver, TimeService.SYSTEM, scopesProvider, realm),
                               createSecurityContextInjectionFilter(authzIdTemplate));
    }
 
    private static Filter createSecurityContextInjectionFilter(final String authzIdTemplate) {
        final AuthzIdTemplate template = new AuthzIdTemplate(authzIdTemplate);
 
        return new Filter() {
            @Override
            public Promise<Response, NeverThrowsException> filter(final Context context,
                                                                  final Request request,
                                                                  final Handler next) {
                final AccessTokenInfo token = context.asContext(OAuth2Context.class).getAccessToken();
                final Map<String, Object> authz = new HashMap<>(1);
                try {
                    authz.put(template.getSecurityContextID(), template.formatAsAuthzId(token.asJsonValue()));
                } catch (final IllegalArgumentException e) {
                    return newResultPromise(new Response(Status.INTERNAL_SERVER_ERROR).setCause(e));
                }
                final Context securityContext = new SecurityContext(context, token.getToken(), authz);
                return next.handle(securityContext, request);
            }
        };
    }
 
    private Authorization() {
        // Prevent instantiation.
    }
}