private String generateKid(JsonValue jwkSet, String algorithm) {

    final JwsAlgorithm jwsAlgorithm = JwsAlgorithm.valueOf(algorithm);
    if (JwsAlgorithmType.RSA.equals(jwsAlgorithm.getAlgorithmType())) {
      JsonValue jwks = jwkSet.get(OAuth2Constants.JWTTokenParams.KEYS);
      if (!jwks.isNull() && !jwks.asList().isEmpty()) {
        return jwks.get(0).get(OAuth2Constants.JWTTokenParams.KEY_ID).asString();
      }
    }

    return null;
  }
Example #2
0
 private void init(JsonValue configuration) {
   JsonValue additionalPolicies = configuration.get("additionalFiles");
   if (!additionalPolicies.isNull()) {
     configuration.remove("additionalFiles");
     List<String> list = new ArrayList<String>();
     for (JsonValue policy : additionalPolicies) {
       try {
         list.add(FileUtil.readFile(IdentityServer.getFileForProjectPath(policy.asString())));
       } catch (Exception e) {
         logger.error("Error loading additional policy script " + policy.asString(), e);
       }
     }
     configuration.add("additionalPolicies", list);
   }
 }
Example #3
0
  /**
   * Will validate the Json representation of the service configuration against the serviceSchema
   * for a realm, and return a corresponding Map representation.
   *
   * @param jsonValue The request body.
   * @param realm The realm, or null if global.
   * @return Map representation of jsonValue
   */
  public Map<String, Set<String>> fromJson(String realm, JsonValue jsonValue)
      throws JsonException, BadRequestException {
    if (!initialised) {
      init();
    }

    Map<String, Set<String>> result = new HashMap<>();
    if (jsonValue == null || jsonValue.isNull()) {
      return result;
    }
    Map<String, Object> translatedAttributeValuePairs =
        getTranslatedAttributeValuePairs(jsonValue.asMap());

    for (String attributeName : translatedAttributeValuePairs.keySet()) {

      // Ignore _id field used to name resource when creating
      if (ResourceResponse.FIELD_CONTENT_ID.equals(attributeName)) {
        continue;
      }

      if (shouldNotBeUpdated(attributeName)) {
        throw new BadRequestException("Invalid attribute, '" + attributeName + "', specified");
      }

      if (shouldBeIgnored(attributeName)) {
        continue;
      }

      final Object attributeValue = translatedAttributeValuePairs.get(attributeName);
      Set<String> value = new HashSet<>();

      if (attributeValue instanceof HashMap) {
        final HashMap<String, Object> attributeMap = (HashMap<String, Object>) attributeValue;
        for (String name : attributeMap.keySet()) {
          value.add("[" + name + "]=" + convertJsonToString(attributeName, attributeMap.get(name)));
        }
      } else if (attributeValue instanceof List) {
        List<Object> attributeArray = (ArrayList<Object>) attributeValue;
        for (Object val : attributeArray) {
          value.add(convertJsonToString(attributeName, val));
        }
      } else {
        value.add(convertJsonToString(attributeName, attributeValue));
      }
      result.put(attributeName, value);
    }

    try {
      if (result.isEmpty()
          || (realm == null && schema.validateAttributes(result))
          || (realm != null && schema.validateAttributes(result, realm))) {
        return result;
      } else {
        throw new JsonException("Invalid attributes");
      }
    } catch (InvalidAttributeValueException e) {
      throw new BadRequestException(e.getLocalizedMessage(), e);
    } catch (SMSException e) {
      throw new JsonException("Unable to validate attributes", e);
    }
  }
  /**
   * TODO Implement this method
   *
   * <p>{@inheritDoc}
   */
  public Promise<QueryResponse, ResourceException> handleQuery(
      final Context context, final QueryRequest request, final QueryResourceHandler handler) {
    EventEntry measure =
        Publisher.start(
            Name.get(
                "openidm/internal/script/" + this.getScriptEntry().getName().getName() + "/query"),
            null,
            null);
    try {
      final ScriptEntry _scriptEntry = getScriptEntry();
      if (!_scriptEntry.isActive()) {
        throw new ServiceUnavailableException("Inactive script: " + _scriptEntry.getName());
      }
      final Script script = _scriptEntry.getScript(context);
      script.setBindings(script.createBindings());
      customizer.handleQuery(context, request, script.getBindings());

      final Function<Void> queryCallback =
          new Function<Void>() {
            @Override
            public Void call(Parameter scope, Function<?> callback, Object... arguments)
                throws ResourceException, NoSuchMethodException {
              if (arguments.length == 3 && null != arguments[2]) {
                if (arguments[2] instanceof Map) {}

                if (arguments[2] instanceof JsonValue) {

                } else {
                  throw new NoSuchMethodException(
                      FunctionFactory.getNoSuchMethodMessage("callback", arguments));
                }
              } else if (arguments.length >= 2 && null != arguments[1]) {
                if (arguments[1] instanceof Map) {}

                if (arguments[1] instanceof JsonValue) {

                } else {
                  throw new NoSuchMethodException(
                      FunctionFactory.getNoSuchMethodMessage("callback", arguments));
                }
              } else if (arguments.length >= 1 && null != arguments[0]) {
                if (arguments[0] instanceof Map) {}

                if (arguments[0] instanceof JsonValue) {

                } else {
                  throw new NoSuchMethodException(
                      FunctionFactory.getNoSuchMethodMessage("callback", arguments));
                }
              } else {
                throw new NoSuchMethodException(
                    FunctionFactory.getNoSuchMethodMessage("callback", arguments));
              }
              return null;
            }
          };
      script.putSafe("callback", queryCallback);
      Object rawResult = script.eval();
      JsonValue result = null;
      if (rawResult instanceof JsonValue) {
        result = (JsonValue) rawResult;
      } else {
        result = new JsonValue(rawResult);
      }
      QueryResponse queryResponse = newQueryResponse();
      // Script can either
      // - return null and instead use callback hook to call
      //   handleResource, handleResult, handleError
      //   careful! script MUST call handleResult or handleError itself
      // or
      // - return a result list of resources
      // or
      // - return a full query result structure
      if (!result.isNull()) {
        if (result.isList()) {
          // Script may return just the result elements as a list
          handleQueryResultList(result, handler);
        } else {
          // Or script may return a full query response structure,
          // with meta-data and results field
          if (result.isDefined(QueryResponse.FIELD_RESULT)) {
            handleQueryResultList(result.get(QueryResponse.FIELD_RESULT), handler);
            queryResponse =
                newQueryResponse(
                    result.get(QueryResponse.FIELD_PAGED_RESULTS_COOKIE).asString(),
                    result
                        .get(QueryResponse.FIELD_TOTAL_PAGED_RESULTS_POLICY)
                        .asEnum(CountPolicy.class),
                    result.get(QueryResponse.FIELD_TOTAL_PAGED_RESULTS).asInteger());
          } else {
            logger.debug("Script returned unexpected query result structure: ", result.getObject());
            return new InternalServerErrorException(
                    "Script returned unexpected query result structure of type "
                        + result.getObject().getClass())
                .asPromise();
          }
        }
      }
      return queryResponse.asPromise();
    } catch (ScriptException e) {
      return convertScriptException(e).asPromise();
    } catch (ResourceException e) {
      return e.asPromise();
    } catch (Exception e) {
      return new InternalServerErrorException(e.getMessage(), e).asPromise();
    } finally {
      measure.end();
    }
  }