@Test
  public void crestUpdateIsAllowed() throws SSOException, DelegationException {
    // Given...
    final Set<String> actions = new HashSet<>(Arrays.asList("MODIFY"));
    final DelegationPermission permission =
        new DelegationPermission(
            "/abc", "rest", "1.0", "policies", "modify", actions, EXTENSIONS, DUMB_FUNC);
    given(factory.newInstance("/abc", "rest", "1.0", "policies", "modify", actions, EXTENSIONS))
        .willReturn(permission);

    given(subjectContext.getCallerSSOToken()).willReturn(token);
    given(evaluator.isAllowed(eq(token), eq(permission), eq(ENVIRONMENT))).willReturn(true);

    JsonValue jsonValue = json(object(field("someKey", "someValue")));
    Promise<ResourceResponse, ResourceException> promise =
        Promises.newResultPromise(Responses.newResourceResponse("1", "1.0", jsonValue));
    given(provider.updateInstance(isA(Context.class), eq("123"), isA(UpdateRequest.class)))
        .willReturn(promise);

    // When...
    final FilterChain chain = AuthorizationFilters.createAuthorizationFilter(provider, module);
    final Router router = new Router();
    router.addRoute(RoutingMode.STARTS_WITH, Router.uriTemplate("/policies"), chain);

    final RealmContext context = new RealmContext(subjectContext);
    context.setSubRealm("abc", "abc");
    final UpdateRequest request =
        Requests.newUpdateRequest("/policies/123", JsonValue.json(new Object()));
    Promise<ResourceResponse, ResourceException> result = router.handleUpdate(context, request);

    // Then...
    assertThat(result).succeeded().withContent().stringAt("someKey").isEqualTo("someValue");
  }
Пример #2
0
 /**
  * Updates the underlying backend policies.
  *
  * <p>NOTE: if the update of the underlying policies fails, the underlying policies may be in an
  * inconsistent state.
  *
  * @param context The request context.
  * @param policies The updated underlying policies to update.
  * @return A promise containing the list of updated underlying policies or a {@code
  *     ResourceException} if the update failed.
  */
 public Promise<List<Resource>, ResourceException> updatePolicies(
     ServerContext context, Set<JsonValue> policies) {
   List<Promise<Resource, ResourceException>> promises =
       new ArrayList<Promise<Resource, ResourceException>>();
   for (JsonValue policy : policies) {
     String policyName = policy.get("name").asString();
     promises.add(
         policyResource.handleUpdate(context, Requests.newUpdateRequest(policyName, policy)));
   }
   return Promises.when(promises);
 }
Пример #3
0
  @Test
  public void testResource() throws Exception {
    ScriptName scriptName = new ScriptName("resource", getLanguageName());
    ScriptEntry scriptEntry = getScriptRegistry().takeScript(scriptName);
    Assert.assertNotNull(scriptEntry);

    Script script = scriptEntry.getScript(new RootContext());
    // Set RequestLevel Scope
    script.put("ketto", 2);
    script.putSafe("callback", mock(Function.class));

    JsonValue createContent = new JsonValue(new LinkedHashMap<String, Object>());
    createContent.put("externalId", "701984");
    createContent.put("userName", "*****@*****.**");
    createContent.put(
        "assignedDashboard", Arrays.asList("Salesforce", "Google", "ConstantContact"));
    createContent.put("displayName", "Babs Jensen");
    createContent.put("nickName", "Babs");

    JsonValue updateContent = createContent.copy();
    updateContent.put("_id", UUID.randomUUID().toString());
    updateContent.put("profileUrl", "https://login.example.com/bjensen");

    final Context context =
        new ApiInfoContext(
            new SecurityContext(new RootContext(), "*****@*****.**", null), "", "");
    script.put("context", context);

    CreateRequest createRequest = Requests.newCreateRequest("/Users", "701984", createContent);
    script.put("createRequest", createRequest);
    ReadRequest readRequest = Requests.newReadRequest("/Users/701984");
    script.put("readRequest", readRequest);
    UpdateRequest updateRequest = Requests.newUpdateRequest("/Users/701984", updateContent);
    script.put("updateRequest", updateRequest);
    PatchRequest patchRequest =
        Requests.newPatchRequest("/Users/701984", PatchOperation.replace("userName", "ddoe"));
    script.put("patchRequest", patchRequest);
    QueryRequest queryRequest = Requests.newQueryRequest("/Users/");
    script.put("queryRequest", queryRequest);
    DeleteRequest deleteRequest = Requests.newDeleteRequest("/Users/701984");
    script.put("deleteRequest", deleteRequest);
    ActionRequest actionRequest = Requests.newActionRequest("/Users", "clear");
    script.put("actionRequest", actionRequest);
    script.eval();
  }
  /**
   * Persist the supplied {@link JsonValue} {@code value} as the new state of this singleton
   * relationship on {@code resourceId}.
   *
   * <p><em>This is currently the only means of creating an instance of this singleton</em>
   *
   * @param context The context of this request
   * @param resourceId Id of the resource relation fields in value are to be memebers of
   * @param value A {@link JsonValue} map of relationship fields and their values
   * @return The persisted instance of {@code value}
   */
  @Override
  public Promise<JsonValue, ResourceException> setRelationshipValueForResource(
      Context context, String resourceId, JsonValue value) {
    if (value.isNotNull()) {
      try {
        final JsonValue id = value.get(FIELD_ID);

        // Update if we got an id, otherwise replace
        if (id != null && id.isNotNull()) {
          final UpdateRequest updateRequest = Requests.newUpdateRequest("", value);
          updateRequest.setAdditionalParameter(PARAM_FIRST_ID, resourceId);
          return updateInstance(context, value.get(FIELD_ID).asString(), updateRequest)
              .then(
                  new Function<ResourceResponse, JsonValue, ResourceException>() {
                    @Override
                    public JsonValue apply(ResourceResponse resourceResponse)
                        throws ResourceException {
                      return resourceResponse.getContent();
                    }
                  });
        } else { // no id, replace current instance
          clear(context, resourceId);

          final CreateRequest createRequest = Requests.newCreateRequest("", value);
          createRequest.setAdditionalParameter(PARAM_FIRST_ID, resourceId);
          return createInstance(context, createRequest)
              .then(
                  new Function<ResourceResponse, JsonValue, ResourceException>() {
                    @Override
                    public JsonValue apply(ResourceResponse resourceResponse)
                        throws ResourceException {
                      return resourceResponse.getContent();
                    }
                  });
        }
      } catch (ResourceException e) {
        return e.asPromise();
      }

    } else {
      clear(context, resourceId);
      return newResultPromise(json(null));
    }
  }
Пример #5
0
 /**
  * Update a link.
  *
  * @throws SynchronizationException if updating link fails
  */
 void update() throws SynchronizationException {
   if (_id == null) {
     throw new SynchronizationException("Attempt to update non-existent link");
   }
   JsonValue jv = toJsonValue();
   try {
     UpdateRequest r = Requests.newUpdateRequest(linkId(_id), jv);
     r.setRevision(_rev);
     Resource resource =
         mapping
             .getService()
             .getConnectionFactory()
             .getConnection()
             .update(mapping.getService().getServerContext(), r);
     _rev = resource.getRevision();
   } catch (ResourceException ose) {
     LOGGER.warn("Failed to update link", ose);
     throw new SynchronizationException(ose);
   }
 }
 @Override
 public Promise<ActionResponse, ResourceException> handleAction(
     final Context context, final ActionRequest request) {
   try {
     Map<String, String> params = request.getAdditionalParameters();
     switch (request.getActionAsEnum(Action.class)) {
       case updateDbCredentials:
         String newUser = params.get("user");
         String newPassword = params.get("password");
         if (newUser == null || newPassword == null) {
           return adapt(new BadRequestException("Expecting 'user' and 'password' parameters"))
               .asPromise();
         }
         synchronized (dbLock) {
           DBHelper.updateDbCredentials(dbURL, user, password, newUser, newPassword);
           JsonValue config =
               connectionFactory
                   .getConnection()
                   .read(context, Requests.newReadRequest("config", PID))
                   .getContent();
           config.put("user", newUser);
           config.put("password", newPassword);
           UpdateRequest updateRequest = Requests.newUpdateRequest("config/" + PID, config);
           connectionFactory.getConnection().update(context, updateRequest);
           return newActionResponse(new JsonValue(params)).asPromise();
         }
       case command:
         return newActionResponse(new JsonValue(command(request))).asPromise();
       default:
         return adapt(new BadRequestException("Unknown action: " + request.getAction()))
             .asPromise();
     }
   } catch (IllegalArgumentException e) {
     return adapt(new BadRequestException("Unknown action: " + request.getAction())).asPromise();
   } catch (ResourceException e) {
     return e.asPromise();
   }
 }
  void doPut(final HttpServletRequest req, final HttpServletResponse resp) {
    try {
      // Parse out the required API versions.
      final AcceptAPIVersion acceptVersion = parseAcceptAPIVersion(req);

      // Prepare response.
      prepareResponse(req, resp);

      // Validate request.
      preprocessRequest(req);

      if (req.getHeader(HEADER_IF_MATCH) != null && req.getHeader(HEADER_IF_NONE_MATCH) != null) {
        // FIXME: i18n
        throw new PreconditionFailedException(
            "Simultaneous use of If-Match and If-None-Match not " + "supported for PUT requests");
      }

      final Map<String, String[]> parameters = req.getParameterMap();
      final JsonValue content = getJsonContent(req);

      final String rev = getIfNoneMatch(req);
      if (ETAG_ANY.equals(rev)) {
        // This is a create with a user provided resource ID: split the
        // path into the parent resource name and resource ID.
        final String resourceName = getResourceName(req);
        final int i = resourceName.lastIndexOf('/');
        final CreateRequest request;
        if (resourceName.isEmpty()) {
          // FIXME: i18n.
          throw new BadRequestException("No new resource ID in HTTP PUT request");
        } else if (i < 0) {
          // We have a pathInfo of the form "{id}"
          request = Requests.newCreateRequest(EMPTY_STRING, content);
          request.setNewResourceId(resourceName);
        } else {
          // We have a pathInfo of the form "{container}/{id}"
          request = Requests.newCreateRequest(resourceName.substring(0, i), content);
          request.setNewResourceId(resourceName.substring(i + 1));
        }
        for (final Map.Entry<String, String[]> p : parameters.entrySet()) {
          final String name = p.getKey();
          final String[] values = p.getValue();
          if (HttpUtils.isMultiPartRequest(req.getContentType())) {
            // Ignore - multipart content adds form parts to the parameter set
          } else if (parseCommonParameter(name, values, request)) {
            continue;
          } else {
            request.setAdditionalParameter(name, asSingleValue(name, values));
          }
        }
        doRequest(req, resp, acceptVersion, request);
      } else {
        final UpdateRequest request =
            Requests.newUpdateRequest(getResourceName(req), content).setRevision(getIfMatch(req));
        for (final Map.Entry<String, String[]> p : parameters.entrySet()) {
          final String name = p.getKey();
          final String[] values = p.getValue();
          if (HttpUtils.isMultiPartRequest(req.getContentType())) {
            // Ignore - multipart content adds form parts to the parameter set
          } else if (parseCommonParameter(name, values, request)) {
            continue;
          } else {
            request.setAdditionalParameter(name, asSingleValue(name, values));
          }
        }
        doRequest(req, resp, acceptVersion, request);
      }
    } catch (final Exception e) {
      fail(req, resp, e);
    }
  }
Пример #8
0
  /**
   * Stores the <code>Dictionary</code> under the given <code>pid</code>.
   *
   * @param pid The identifier of the dictionary.
   * @param properties The <code>Dictionary</code> to store.
   * @throws IOException If an error occurrs storing the dictionary. If this exception is thrown, it
   *     is expected, that {@link #exists(String) exists(pid} returns <code>false</code>.
   */
  public void store(String pid, Dictionary properties) throws IOException {
    logger.debug("Store call for {} {}", pid, properties);

    // Store config handling settings in memory
    if (pid.startsWith("org.apache.felix.fileinstall")) {
      tempStore.put(pid, properties);
      return;
    }

    try {
      if (isReady(0) && requireRepository) {
        String id = pidToId(pid);

        Map<String, Object> obj = dictToMap(properties);
        JsonValue content = new JsonValue(obj);
        String configResourceId =
            ConfigBootstrapHelper.getId(
                content.get(ConfigBootstrapHelper.CONFIG_ALIAS).asString(),
                content.get(ConfigBootstrapHelper.SERVICE_PID).asString(),
                content.get(ConfigBootstrapHelper.SERVICE_FACTORY_PID).asString());
        String configString = (String) obj.get(JSONEnhancedConfig.JSON_CONFIG_PROPERTY);
        Map<Object, Object> configMap = deserializeConfig(configString);
        if (configMap != null) {
          configMap.put("_id", configResourceId);
        }
        obj.put(JSONEnhancedConfig.JSON_CONFIG_PROPERTY, configMap);

        Map<String, Object> existing = null;
        try {
          ReadRequest readRequest = Requests.newReadRequest(id);
          existing = repo.read(readRequest).getContent().asMap();
        } catch (NotFoundException ex) {
          // Just detect that it doesn't exist
        }
        if (existing != null) {
          String rev = (String) existing.get("_rev");

          existing.remove("_rev");
          existing.remove("_id");
          obj.remove("_rev"); // beware, this means _id and _rev should not be in config file
          obj.remove("_id"); // beware, this means _id and _rev should not be in config file
          obj.remove(RepoPersistenceManager.BUNDLE_LOCATION);
          obj.remove(RepoPersistenceManager.FELIX_FILEINSTALL_FILENAME);
          if (!existing.equals(obj)) {
            logger.trace("Not matching {} {}", existing, obj);
            boolean retry;
            do {
              retry = false;
              try {
                UpdateRequest r = Requests.newUpdateRequest(id, new JsonValue(obj));
                r.setRevision(rev);
                repo.update(r);
              } catch (PreconditionFailedException ex) {
                logger.debug("Concurrent change during update, retrying {} {}", pid, rev);
                ReadRequest readRequest = Requests.newReadRequest(id);
                existing = repo.read(readRequest).getContent().asMap();
                retry = true;
              }
            } while (retry);
            logger.debug("Updated existing config {} {} {}", new Object[] {pid, rev, obj});
          } else {
            logger.debug(
                "Existing config same as store request, ignoring {} {} {}",
                new Object[] {pid, rev, obj});
          }
        } else {
          logger.trace("Creating: {} {} ", id, obj);
          // This may create a new (empty) configuration, which felix marks with
          // _felix___cm__newConfiguration=true
          String newResourceId = id.substring(CONFIG_CONTEXT_PREFIX.length());
          CreateRequest createRequest =
              Requests.newCreateRequest(CONFIG_CONTEXT_PREFIX, new JsonValue(obj));
          createRequest.setNewResourceId(newResourceId);
          obj = repo.create(createRequest).getContent().asMap();
          logger.debug("Stored new config in repository {} {}", pid, obj);
        }
      } else {
        tempStore.put(pid, properties);
        logger.debug("Stored in memory {} {}", pid, properties);
      }
    } catch (ResourceException ex) {
      throw new IOException("Failed to store configuration in repository: " + ex.getMessage(), ex);
    }
  }