@SuppressWarnings("unchecked")
  protected Map<Long, String> populateNewServiceLinks(ApiRequest request) {
    final Map<Long, String> newServiceLinks = new HashMap<>();
    final Map<String, Long> newServiceLinksMaps =
        DataAccessor.fromMap(request.getRequestObject())
            .withKey(ServiceDiscoveryConstants.FIELD_SERVICE_LINKS)
            .withDefault(Collections.EMPTY_MAP)
            .as(Map.class);

    if (newServiceLinksMaps != null) {
      for (String linkName : newServiceLinksMaps.keySet()) {
        newServiceLinks.put(newServiceLinksMaps.get(linkName), linkName);
      }
    }

    final List<? extends Long> newConsumedServicesIds =
        DataAccessor.fromMap(request.getRequestObject())
            .withKey(ServiceDiscoveryConstants.FIELD_SERVICE_IDS)
            .asList(jsonMapper, Long.class);

    if (newConsumedServicesIds != null) {
      for (Long consumedServiceId : newConsumedServicesIds) {
        newServiceLinks.put(consumedServiceId, null);
      }
    }
    return newServiceLinks;
  }
 public Account getAccountAccess(String token, ApiRequest request) {
   if (!StringUtils.equals(AbstractTokenUtil.TOKEN, request.getType()) && isConfigured()) {
     request.setAttribute(tokenUtils().tokenType(), token);
     return getAccountAccessInternal();
   }
   return null;
 }
Exemple #3
0
 protected String getContent(ApiRequest request, String dot) {
   if ("html".equals(request.getResponseFormat())) {
     request.setResponseContentType("text/html; charset=utf-8");
     return asHtml(dot);
   } else {
     request.setResponseContentType("text/plain");
     return dot;
   }
 }
Exemple #4
0
  @Override
  protected Object createInternal(String type, ApiRequest request) {
    if (!StringUtils.equals(ADConstants.CONFIG, request.getType())) {
      return null;
    }

    LDAPConstants config = request.proxyRequestObject(LDAPConstants.class);
    LDAPUtils.validateConfig(config);
    return updateCurrentConfig(config);
  }
Exemple #5
0
 @Override
 protected void postAuthModification(Account account) {
   if (account != null) {
     ApiRequest request = ApiContext.getContext().getApiRequest();
     String accessToken = (String) request.getAttribute(AzureConstants.AZURE_ACCESS_TOKEN);
     String refreshToken = (String) request.getAttribute(AzureConstants.AZURE_REFRESH_TOKEN);
     DataAccessor.fields(account).withKey(AzureConstants.AZURE_ACCESS_TOKEN).set(accessToken);
     DataAccessor.fields(account).withKey(AzureConstants.AZURE_REFRESH_TOKEN).set(refreshToken);
     getObjectManager().persist(account);
   }
 }
  private Account getAccountRequested(
      Account authenticatedAsAccount, Set<Identity> identities, ApiRequest request) {
    Account project;

    String projectId =
        request.getServletContext().getRequest().getHeader(ProjectConstants.PROJECT_HEADER);
    if (projectId == null || projectId.isEmpty()) {
      projectId = request.getServletContext().getRequest().getParameter("projectId");
    }
    if (projectId == null || projectId.isEmpty()) {
      projectId = (String) request.getAttribute(ProjectConstants.PROJECT_HEADER);
    }

    if (projectId == null || projectId.isEmpty()) {
      return authenticatedAsAccount;
    }

    String parsedProjectId;

    try {
      parsedProjectId = ApiContext.getContext().getIdFormatter().parseId(projectId);
    } catch (NumberFormatException e) {
      throw new ClientVisibleException(
          ResponseCodes.BAD_REQUEST,
          "InvalidFormat",
          "projectId header format is incorrect " + projectId,
          null);
    }

    if (StringUtils.isEmpty(parsedProjectId)) {
      throw new ClientVisibleException(ResponseCodes.FORBIDDEN);
    }
    try {
      project = authDao.getAccountById(new Long(parsedProjectId));
      if (project == null || !project.getState().equalsIgnoreCase(CommonStatesConstants.ACTIVE)) {
        throw new ClientVisibleException(ResponseCodes.FORBIDDEN);
      }
      if (authenticatedAsAccount.getId().equals(project.getId())) {
        return authenticatedAsAccount;
      }
    } catch (NumberFormatException e) {
      throw new ClientVisibleException(ResponseCodes.FORBIDDEN);
    }
    Policy tempPolicy =
        getPolicy(authenticatedAsAccount, authenticatedAsAccount, identities, request);
    if (authDao.hasAccessToProject(
        project.getId(),
        authenticatedAsAccount.getId(),
        tempPolicy.isOption(Policy.AUTHORIZED_FOR_ALL_ACCOUNTS),
        identities)) {
      return project;
    }
    throw new ClientVisibleException(ResponseCodes.FORBIDDEN);
  }
 protected void saveInContext(ApiRequest request, Policy policy, SchemaFactory schemaFactory) {
   if (schemaFactory != null) {
     request.setSchemaFactory(schemaFactory);
   }
   String accountId =
       (String)
           ApiContext.getContext()
               .getIdFormatter()
               .formatId(objectManager.getType(Account.class), policy.getAccountId());
   request.getServletContext().getResponse().addHeader(ACCOUNT_ID_HEADER, accountId);
   ApiContext.getContext().setPolicy(policy);
 }
  @Override
  public Object resourceAction(String type, ApiRequest request, ResourceManager next) {
    if (request.getAction().equalsIgnoreCase(ServiceDiscoveryConstants.ACTION_SERVICE_UPGRADE)) {
      Service service = objManager.loadResource(Service.class, request.getId());
      if (ServiceDiscoveryUtil.isNoopService(service, allocatorService)) {
        throw new ValidationErrorException(
            ValidationErrorCodes.INVALID_ACTION, "Can't upgrade selector only service");
      }
    }

    return super.resourceAction(type, request, next);
  }
 @Override
 protected Object createInternal(String type, ApiRequest request) {
   if (!StringUtils.equals(AbstractTokenUtil.TOKEN, request.getType())) {
     return null;
   }
   return createToken(request);
 }
  protected Account getAccount(ApiRequest request) {
    Account account = null;

    for (AccountLookup lookup : accountLookups) {
      if (lookup.isConfigured()) {
        account = lookup.getAccount(request);
        if (account != null) {
          request.setAttribute(AccountConstants.AUTH_TYPE, lookup.getName());
          break;
        }
      }
    }

    if (account != null) {
      return account;
    }

    if (SecurityConstants.SECURITY.get()) {
      for (AccountLookup lookup : accountLookups) {
        if (lookup.challenge(request)) {
          break;
        }
      }
    }

    return null;
  }
  @Override
  public Object create(String type, ApiRequest request, ResourceManager next) {
    Service service = request.proxyRequestObject(Service.class);

    validateSelectorOnlyService(request, service);
    return super.create(type, request, next);
  }
 @Override
 public Account getAccount(ApiRequest request) {
   if (!StringUtils.equals(AbstractTokenUtil.TOKEN, request.getType()) && isConfigured()) {
     tokenUtils().findAndSetJWT();
     return getAccountAccessInternal();
   }
   return null;
 }
 @SuppressWarnings("unchecked")
 protected void validateSelectorOnlyService(ApiRequest request, Service service) {
   Map<String, Object> data = CollectionUtils.toMap(request.getRequestObject());
   Map<String, Object> primaryLaunchConfig =
       (Map<String, Object>) data.get(ServiceDiscoveryConstants.FIELD_LAUNCH_CONFIG);
   Object selector = data.get(ServiceDiscoveryConstants.FIELD_SELECTOR_CONTAINER);
   boolean isSelector = selector != null && !selector.toString().isEmpty();
   validateImage(primaryLaunchConfig, isSelector);
 }
Exemple #14
0
  public boolean writeResponse(String dot, ApiRequest request) throws IOException {
    if (dot != null) {
      String content = getContent(request, dot);
      try {
        request.getOutputStream().write(content.getBytes("UTF-8"));
      } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
      }
      return true;
    }

    return false;
  }
  protected Map<String, ServiceLink> populateNewServiceLinks(ApiRequest request) {
    Map<String, ServiceLink> newServiceLinks = new HashMap<>();
    List<? extends ServiceLink> serviceLinks =
        DataAccessor.fromMap(request.getRequestObject())
            .withKey(ServiceConstants.FIELD_SERVICE_LINKS)
            .withDefault(Collections.EMPTY_LIST)
            .asList(jsonMapper, ServiceLink.class);

    if (serviceLinks != null) {
      for (ServiceLink serviceLink : serviceLinks) {
        newServiceLinks.put(serviceLink.getUuid(), serviceLink);
      }
    }

    return newServiceLinks;
  }
  @Override
  public Object create(String type, ApiRequest request, ResourceManager next) {
    ServiceEvent event = request.proxyRequestObject(ServiceEvent.class);

    /* Will never return null, MissingRequired will be thrown if missing */
    Agent agent = getAgent();
    if (agent == null) {
      throw new ClientVisibleException(ResponseCodes.FORBIDDEN, VERIFY_AGENT);
    }

    HealthcheckInstanceHostMap healthcheckInstanceHostMap = null;
    String[] splitted = event.getHealthcheckUuid().split("_");
    if (splitted.length > 2) {
      healthcheckInstanceHostMap = serviceDao.getHealthCheckInstanceUUID(splitted[0], splitted[1]);
    } else {
      healthcheckInstanceHostMap =
          objectManager.findOne(
              HealthcheckInstanceHostMap.class, ObjectMetaDataManager.UUID_FIELD, splitted[0]);
    }

    if (healthcheckInstanceHostMap == null) {
      throw new ClientVisibleException(ResponseCodes.FORBIDDEN, VERIFY_AGENT);
    }

    HealthcheckInstance healthcheckInstance =
        objectManager.loadResource(
            HealthcheckInstance.class, healthcheckInstanceHostMap.getHealthcheckInstanceId());

    if (healthcheckInstance == null) {
      return null;
    }
    Long resourceAccId =
        DataAccessor.fromDataFieldOf(agent)
            .withKey(AgentConstants.DATA_AGENT_RESOURCES_ACCOUNT_ID)
            .as(Long.class);

    if (!healthcheckInstanceHostMap.getAccountId().equals(resourceAccId)) {
      throw new ClientVisibleException(ResponseCodes.FORBIDDEN, VERIFY_AGENT);
    }

    event.setInstanceId(healthcheckInstance.getInstanceId());
    event.setHealthcheckInstanceId(healthcheckInstance.getId());
    event.setHostId(healthcheckInstanceHostMap.getHostId());

    return super.create(type, request, next);
  }
  @Override
  public Object create(String type, ApiRequest request, ResourceManager next) {
    Environment env = request.proxyRequestObject(Environment.class);

    if (env.getName().startsWith("-") || env.getName().endsWith("-")) {
      ValidationErrorCodes.throwValidationError(ValidationErrorCodes.INVALID_CHARACTERS, "name");
    }

    ResourceManager rm = locator.getResourceManagerByType(type);

    Map<Object, Object> criteria = new HashMap<>();
    criteria.put(ObjectMetaDataManager.NAME_FIELD, env.getName());
    criteria.put(ObjectMetaDataManager.REMOVED_FIELD, new Condition(ConditionType.NULL));
    List<?> existingEnv = rm.list(type, criteria, null);
    if (!existingEnv.isEmpty()) {
      ValidationErrorCodes.throwValidationError(ValidationErrorCodes.NOT_UNIQUE, "name");
    }
    return super.create(type, request, next);
  }