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

Matthew Swift
22.18.2016 9bdba2b5de74b9cdb94b809bebbda7465243ecb9
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
/*
 * 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.opends.server.protocols.http.rest2ldap;
 
import static org.forgerock.http.routing.RouteMatchers.newResourceApiVersionBehaviourManager;
import static org.forgerock.http.routing.Version.version;
import static org.forgerock.json.resource.RouteMatchers.resourceApiVersionContextFilter;
import static org.forgerock.opendj.ldap.schema.CoreSchema.getBooleanSyntax;
import static org.forgerock.opendj.ldap.schema.CoreSchema.getIntegerSyntax;
import static org.forgerock.opendj.rest2ldap.Rest2Ldap.*;
import static org.forgerock.opendj.rest2ldap.WritabilityPolicy.CREATE_ONLY;
import static org.forgerock.opendj.rest2ldap.WritabilityPolicy.READ_ONLY;
import static org.forgerock.opendj.rest2ldap.WritabilityPolicy.READ_WRITE;
import static org.forgerock.util.Options.defaultOptions;
import static org.opends.messages.ConfigMessages.ERR_BAD_ADMIN_API_RESOURCE_VERSION;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.forgerock.http.Handler;
import org.forgerock.http.HttpApplication;
import org.forgerock.http.HttpApplicationException;
import org.forgerock.http.io.Buffer;
import org.forgerock.http.routing.ResourceApiVersionBehaviourManager;
import org.forgerock.http.routing.Version;
import org.forgerock.json.JsonPointer;
import org.forgerock.json.resource.BadRequestException;
import org.forgerock.json.resource.ConnectionFactory;
import org.forgerock.json.resource.CrestApplication;
import org.forgerock.json.resource.FilterChain;
import org.forgerock.json.resource.Request;
import org.forgerock.json.resource.RequestHandler;
import org.forgerock.json.resource.ResourceException;
import org.forgerock.json.resource.Resources;
import org.forgerock.json.resource.Router;
import org.forgerock.json.resource.http.CrestHttp;
import org.forgerock.opendj.config.AbstractManagedObjectDefinition;
import org.forgerock.opendj.config.AggregationPropertyDefinition;
import org.forgerock.opendj.config.DefaultBehaviorProvider;
import org.forgerock.opendj.config.DefinedDefaultBehaviorProvider;
import org.forgerock.opendj.config.InstantiableRelationDefinition;
import org.forgerock.opendj.config.LDAPProfile;
import org.forgerock.opendj.config.ManagedObjectDefinition;
import org.forgerock.opendj.config.ManagedObjectOption;
import org.forgerock.opendj.config.PropertyDefinition;
import org.forgerock.opendj.config.PropertyOption;
import org.forgerock.opendj.config.RelationDefinition;
import org.forgerock.opendj.config.RelationOption;
import org.forgerock.opendj.config.SingletonRelationDefinition;
import org.forgerock.opendj.config.TopCfgDefn;
import org.forgerock.opendj.ldap.AttributeDescription;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.Functions;
import org.forgerock.opendj.ldap.schema.Syntax;
import org.forgerock.opendj.rest2ldap.AbstractRequestHandler;
import org.forgerock.opendj.rest2ldap.ReferencePropertyMapper;
import org.forgerock.opendj.rest2ldap.Resource;
import org.forgerock.opendj.rest2ldap.Rest2Ldap;
import org.forgerock.opendj.rest2ldap.SimplePropertyMapper;
import org.forgerock.opendj.rest2ldap.SubResourceCollection;
import org.forgerock.opendj.rest2ldap.SubResourceSingleton;
import org.forgerock.opendj.server.config.meta.GlobalCfgDefn;
import org.forgerock.opendj.server.config.meta.RootCfgDefn;
import org.forgerock.opendj.server.config.server.AdminEndpointCfg;
import org.forgerock.services.context.Context;
import org.forgerock.util.Factory;
import org.forgerock.util.Function;
import org.forgerock.util.promise.Promise;
import org.opends.server.api.HttpEndpoint;
import org.opends.server.core.ServerContext;
import org.opends.server.types.InitializationException;
import org.opends.server.util.BuildVersion;
 
/**
 * An HTTP endpoint providing access to the server's monitoring backend (cn=monitor) and its configuration (cn=config).
 */
public final class AdminEndpoint extends HttpEndpoint<AdminEndpointCfg>
{
  private static final Version ADMIN_API_VERSION = version("1.0");
  private static final String TYPE_PROPERTY = "_schema";
  private static final String ADMIN_API = "admin-api";
  private static final String MONITOR = "monitor";
  private static final String CONFIG = "config";
 
  /**
   * Create a new AdminEndpoint with the supplied configuration.
   *
   * @param configuration
   *          Configuration to use for the {@link HttpApplication}
   * @param serverContext
   *          Server of this LDAP server
   */
  public AdminEndpoint(AdminEndpointCfg configuration, ServerContext serverContext)
  {
    super(configuration, serverContext);
  }
 
  @Override
  public HttpApplication newHttpApplication() throws InitializationException
  {
    return new AdminHttpApplication();
  }
 
  /** Specialized {@link HttpApplication} using internal connections to this local LDAP server. */
  private final class AdminHttpApplication implements HttpApplication
  {
    private LDAPProfile ldapProfile = LDAPProfile.getInstance();
 
    @Override
    public Handler start() throws HttpApplicationException
    {
      return newHttpHandler(startRequestHandler());
    }
 
    FilterChain startRequestHandler() throws HttpApplicationException
    {
      final Map<String, Resource> resources = new HashMap<>();
 
      // Define the entry point to the admin API.
      resources.put(ADMIN_API, resource(ADMIN_API).subResources(singletonOf(MONITOR).urlTemplate(MONITOR)
                                                                                    .dnTemplate("cn=monitor")
                                                                                    .isReadOnly(true),
                                                                singletonOf(CONFIG).urlTemplate(CONFIG)
                                                                                   .dnTemplate("cn=config")));
 
      // Define the monitoring endpoint.
      resources.put(MONITOR, resource(MONITOR).includeAllUserAttributesByDefault(true)
                                              .excludedDefaultUserAttributes("objectClass", "cn")
                                              .objectClass ("ds-monitor-entry")
                                              .property("_id", simple("cn"))
                                              .subResource(collectionOf(MONITOR).useClientDnNaming("cn")));
 
      // Build the configuration endpoint using the configuration framework.
      final TopCfgDefn topCfgDefn = TopCfgDefn.getInstance();
      final RootCfgDefn rootCfgDefn = RootCfgDefn.getInstance();
      final GlobalCfgDefn globalCfgDefn = GlobalCfgDefn.getInstance();
 
      // The configuration framework exposes the root and global configuration as separate resources, but it would be
      // nice if we exposed them as a single resource.
      final Resource config = resource(CONFIG);
      configureResourceProperties(globalCfgDefn, config);
      configureResourceSubResources(rootCfgDefn, config, true);
      resources.put(CONFIG, config);
 
      resources.put(topCfgDefn.getName(), buildResource(topCfgDefn));
      for (final AbstractManagedObjectDefinition<?, ?> mod : topCfgDefn.getAllChildren())
      {
        if (!mod.hasOption(ManagedObjectOption.HIDDEN) && mod != globalCfgDefn && mod != rootCfgDefn)
        {
          resources.put(mod.getName(), buildResource(mod));
        }
      }
 
      // Now that all resources are defined, perform a second pass processing all relation definitions in order to
      // identity which attributes should be used for the "_id" property.
      for (final AbstractManagedObjectDefinition<?, ?> mod : topCfgDefn.getAllChildren())
      {
        for (final RelationDefinition<?, ?> rd : mod.getRelationDefinitions())
        {
          if (rd instanceof InstantiableRelationDefinition)
          {
            final InstantiableRelationDefinition<?, ?> ird = (InstantiableRelationDefinition) rd;
            final AbstractManagedObjectDefinition<?, ?> d = rd.getChildDefinition();
            final String rdnType = ldapProfile.getRelationChildRDNType(ird);
            resources.get(d.getName()).property("_id", simple(rdnType).isRequired(true).writability(CREATE_ONLY));
          }
        }
      }
 
      final Rest2Ldap rest2Ldap = rest2Ldap(defaultOptions(), resources.values());
      final RequestHandler handler = rest2Ldap.newRequestHandlerFor(ADMIN_API);
      final Router versionRouter = new Router();
      versionRouter.addRoute(ADMIN_API_VERSION, handler);
      versionRouter.setDefaultRoute(new AbstractRequestHandler()
      {
        @Override
        protected <V> Promise<V, ResourceException> handleRequest(final Context context, final Request request)
        {
          final String message = ERR_BAD_ADMIN_API_RESOURCE_VERSION.get(request.getResourceVersion(), ADMIN_API_VERSION)
                                                                   .toString();
          return new BadRequestException(message).asPromise();
        }
      });
 
      // FIXME: Disable the warning header for now due to CREST-389 / CREST-390.
      final ResourceApiVersionBehaviourManager behaviourManager = newResourceApiVersionBehaviourManager();
      behaviourManager.setWarningEnabled(false);
      return new FilterChain(versionRouter, resourceApiVersionContextFilter(behaviourManager));
    }
 
    private Handler newHttpHandler(RequestHandler handler)
    {
      final org.forgerock.json.resource.ConnectionFactory factory = Resources.newInternalConnectionFactory(handler);
      return CrestHttp.newHttpHandler(new CrestApplication()
      {
        @Override
        public ConnectionFactory getConnectionFactory()
        {
          return factory;
        }
 
        @Override
        public String getApiId()
        {
          return "frapi:opendj:admin";
        }
 
        @Override
        public String getApiVersion()
        {
          return BuildVersion.binaryVersion().toStringNoRevision();
        }
      });
    }
 
    private Resource buildResource(final AbstractManagedObjectDefinition<?, ?> mod)
    {
      final Resource resource = resource(mod.getName());
      if (!mod.isTop())
      {
        resource.description(mod.getSynopsis());
      }
      configureResourceProperties(mod, resource);
      configureResourceSubResources(mod, resource, false);
      return resource;
    }
 
    private void configureResourceSubResources(final AbstractManagedObjectDefinition<?, ?> mod, final Resource resource,
                                               final boolean removeCnEqualsConfig)
    {
      for (final RelationDefinition<?, ?> rd : mod.getRelationDefinitions())
      {
        if (rd.hasOption(RelationOption.HIDDEN))
        {
          continue;
        }
 
        if (rd instanceof InstantiableRelationDefinition)
        {
          final InstantiableRelationDefinition<?, ?> ird = (InstantiableRelationDefinition) rd;
          final AbstractManagedObjectDefinition<?, ?> d = rd.getChildDefinition();
          final SubResourceCollection collection = collectionOf(d.getName())
                  .useClientDnNaming(ldapProfile.getRelationChildRDNType(ird))
                  .urlTemplate(ird.getPluralName())
                  .dnTemplate(getRelationRdnSequence(rd, removeCnEqualsConfig))
                  .glueObjectClasses(ldapProfile.getRelationObjectClasses(rd).toArray(new String[0]));
          resource.subResource(collection);
        }
        else if (rd instanceof SingletonRelationDefinition)
        {
          if (mod == RootCfgDefn.getInstance() && rd.getChildDefinition() == GlobalCfgDefn.getInstance())
          {
            // Special case: ignore the root -> global configuration relation because these two resources are merged
            // into a single resource within the REST API.
            continue;
          }
          final SubResourceSingleton singleton = singletonOf(rd.getChildDefinition().getName())
                  .urlTemplate(rd.getName())
                  .dnTemplate(getRelationRdnSequence(rd, removeCnEqualsConfig));
          resource.subResource(singleton);
        }
        // Optional/set NYI
      }
    }
 
    private String getRelationRdnSequence(final RelationDefinition<?, ?> rd, final boolean removeCnEqualsConfig)
    {
      final String rdnSequence = ldapProfile.getRelationRDNSequence(rd);
      if (removeCnEqualsConfig)
      {
        final DN dn = DN.valueOf(rdnSequence);
        return dn.localName(dn.size() - 1).toString();
      }
      return rdnSequence;
    }
 
    private void configureResourceProperties(final AbstractManagedObjectDefinition<?, ?> mod, final Resource resource)
    {
      resource.isAbstract(!(mod instanceof ManagedObjectDefinition));
      if (mod.getParent() != null)
      {
        resource.superType(mod.getParent().getName());
      }
 
      final String objectClass = ldapProfile.getObjectClass(mod);
      if (objectClass != null)
      {
        resource.objectClass(objectClass);
      }
 
      resource.resourceTypeProperty(new JsonPointer(TYPE_PROPERTY));
      resource.property(TYPE_PROPERTY, resourceType());
      resource.property("_rev", simple("etag").writability(READ_ONLY));
 
      for (final PropertyDefinition<?> pd : mod.getPropertyDefinitions())
      {
        if (pd.hasOption(PropertyOption.HIDDEN))
        {
          continue;
        }
 
        final String attributeName = ldapProfile.getAttributeName(mod, pd);
        if (pd instanceof AggregationPropertyDefinition)
        {
          final AggregationPropertyDefinition apd = (AggregationPropertyDefinition) pd;
          final String relationChildRdnType = ldapProfile.getRelationChildRDNType(apd.getRelationDefinition());
          final SimplePropertyMapper referencePropertyMapper = simple(relationChildRdnType).isRequired(true);
          final DN baseDn = apd.getParentPath().toDN()
                               .child(ldapProfile.getRelationRDNSequence(apd.getRelationDefinition()));
          final ReferencePropertyMapper mapper = reference(attributeName,
                                                           baseDn.toString(),
                                                           relationChildRdnType,
                                                           referencePropertyMapper);
          resource.property(pd.getName(), mapper);
        }
        else
        {
          final SimplePropertyMapper mapper = simple(attributeName)
                  .isRequired(pd.hasOption(PropertyOption.MANDATORY))
                  .writability(pd.hasOption(PropertyOption.READ_ONLY) ? CREATE_ONLY : READ_WRITE)
                  .isMultiValued(pd.hasOption(PropertyOption.MULTI_VALUED));
 
          // Define the default value as well if possible.
          final DefaultBehaviorProvider<?> dbp = pd.getDefaultBehaviorProvider();
          if (dbp instanceof DefinedDefaultBehaviorProvider)
          {
            final DefinedDefaultBehaviorProvider<?> ddbp = (DefinedDefaultBehaviorProvider) dbp;
            final Collection<String> defaultValues = ddbp.getDefaultValues();
            final List<Object> decodedDefaultValues = new ArrayList<>(defaultValues.size());
            final Function<String, ?, ? extends RuntimeException> converter = getConverter(attributeName);
            for (final String defaultValue : defaultValues)
            {
              decodedDefaultValues.add(converter.apply(defaultValue));
            }
            mapper.defaultJsonValues(decodedDefaultValues);
          }
          resource.property(pd.getName(), mapper);
        }
      }
    }
 
    private Function<String, ?, ? extends RuntimeException> getConverter(final String attributeName)
    {
      final AttributeDescription attributeDescription = AttributeDescription.valueOf(attributeName);
      final Syntax syntax = attributeDescription.getAttributeType().getSyntax();
      if (syntax.equals(getBooleanSyntax()))
      {
        return Functions.stringToBoolean();
      }
      else if (syntax.equals(getIntegerSyntax()))
      {
        return Functions.stringToLong();
      }
      else
      {
        return Functions.identityFunction();
      }
    }
 
    @Override
    public void stop()
    {
      // Nothing to do
    }
 
    @Override
    public Factory<Buffer> getBufferFactory()
    {
      return null;
    }
  }
}