예제 #1
0
 @SuppressWarnings("unchecked")
 @Override
 public Resource filter(ApiRequest request, Object original, Resource converted) {
   if (original instanceof AuditLogRecord) {
     AuditLogRecord auditLogRecord = (AuditLogRecord) original;
     if (auditLogRecord.getResourceId() != null) {
       converted
           .getLinks()
           .put(
               "resource",
               ApiContext.getUrlBuilder()
                   .resourceReferenceLink(
                       auditLogRecord.getResourceType(),
                       String.valueOf(auditLogRecord.getResourceId())));
     }
     if (StringUtils.isNotBlank(auditLogRecord.getAuthenticatedAsIdentityId())) {
       converted
           .getLinks()
           .put(
               "authenticatedAsIdentity",
               ApiContext.getUrlBuilder()
                   .resourceReferenceLink(
                       Identity.class,
                       String.valueOf(auditLogRecord.getAuthenticatedAsIdentityId())));
     }
     Map<String, Object> data =
         (Map<String, Object>) ((AuditLogRecord) original).getData().get("fields");
     makeMap(data, "requestObject", converted);
     makeMap(data, "responseObject", converted);
   }
   return converted;
 }
예제 #2
0
  @Override
  public Resource filter(ApiRequest request, Object original, Resource converted) {
    boolean add = false;
    boolean hostStats = false;
    boolean containerStats = false;
    boolean project = false;

    if (original instanceof Host
        && DockerHostConstants.KIND_DOCKER.equals(((Host) original).getKind())) {
      add = true;
      hostStats = true;
      containerStats = true;
    } else if (original instanceof Instance
        && InstanceConstants.CONTAINER_LIKE.contains(((Instance) original).getKind())) {
      containerStats = true;
      add = true;
    } else if (original instanceof Account
        && AccountConstants.PROJECT_KIND.equals(((Account) original).getKind())) {
      project = true;
    } else if (original instanceof Service) {
      containerStats = true;
    }

    if (add) {
      converted
          .getLinks()
          .put(
              StatsConstants.LINK_STATS,
              ApiContext.getUrlBuilder().resourceLink(converted, StatsConstants.LINK_STATS));
    }
    if (hostStats) {
      converted
          .getLinks()
          .put(
              StatsConstants.HOST_STATS,
              ApiContext.getUrlBuilder().resourceLink(converted, StatsConstants.HOST_STATS));
    }
    if (containerStats) {
      converted
          .getLinks()
          .put(
              StatsConstants.CONTAINER_STATS,
              ApiContext.getUrlBuilder().resourceLink(converted, StatsConstants.CONTAINER_STATS));
    }
    if (project) {
      converted
          .getLinks()
          .put(
              StatsConstants.HOST_STATS,
              ApiContext.getUrlBuilder()
                  .resourceLink(
                      converted,
                      "projects/" + converted.getId() + "/" + StatsConstants.HOST_STATS));
    }

    return converted;
  }
예제 #3
0
 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 Identity getIdentity(Long id) {
   Account account = getAccountById(id);
   if (account == null || account.getKind().equalsIgnoreCase(ProjectConstants.TYPE)) {
     return null;
   }
   Credential credential =
       create()
           .selectFrom(CREDENTIAL)
           .where(
               CREDENTIAL
                   .KIND
                   .equalIgnoreCase(CredentialConstants.KIND_PASSWORD)
                   .and(CREDENTIAL.ACCOUNT_ID.eq(id))
                   .and(CREDENTIAL.STATE.equalIgnoreCase(CommonStatesConstants.ACTIVE)))
           .fetchAny();
   String accountId =
       (String)
           ApiContext.getContext()
               .getIdFormatter()
               .formatId(objectManager.getType(Account.class), account.getId());
   return new Identity(
       ProjectConstants.RANCHER_ID,
       accountId,
       account.getName(),
       null,
       null,
       credential == null ? null : credential.getPublicValue());
 }
 @Override
 public Account getAccountByKeys(String access, String secretKey) {
   try {
     Credential credential =
         create()
             .selectFrom(CREDENTIAL)
             .where(CREDENTIAL.STATE.eq(CommonStatesConstants.ACTIVE))
             .and(CREDENTIAL.PUBLIC_VALUE.eq(access))
             .and(CREDENTIAL.KIND.in(SUPPORTED_TYPES.get()))
             .fetchOne();
     if (credential == null) {
       return null;
     }
     boolean secretIsCorrect =
         ApiContext.getContext()
             .getTransformationService()
             .compare(secretKey, credential.getSecretValue());
     if (secretIsCorrect) {
       return create()
           .selectFrom(ACCOUNT)
           .where(
               ACCOUNT
                   .ID
                   .eq(credential.getAccountId())
                   .and(ACCOUNT.STATE.eq(CommonStatesConstants.ACTIVE)))
           .fetchOneInto(AccountRecord.class);
     } else {
       return null;
     }
   } catch (InvalidResultException e) {
     throw new ClientVisibleException(ResponseCodes.CONFLICT, "MultipleKeys");
   }
 }
 @Override
 public Account getAccountByLogin(String publicValue, String secretValue) {
   Credential credential =
       create()
           .selectFrom(CREDENTIAL)
           .where(CREDENTIAL.STATE.eq(CommonStatesConstants.ACTIVE))
           .and(
               CREDENTIAL
                   .PUBLIC_VALUE
                   .eq(publicValue)
                   .and(CREDENTIAL.KIND.equalIgnoreCase(CredentialConstants.KIND_PASSWORD)))
           .fetchOne();
   if (credential == null) {
     return null;
   }
   boolean secretIsCorrect =
       ApiContext.getContext()
           .getTransformationService()
           .compare(secretValue, credential.getSecretValue());
   if (secretIsCorrect) {
     return create()
         .selectFrom(ACCOUNT)
         .where(
             ACCOUNT
                 .ID
                 .eq(credential.getAccountId())
                 .and(ACCOUNT.STATE.eq(CommonStatesConstants.ACTIVE)))
         .fetchOneInto(AccountRecord.class);
   } else {
     return null;
   }
 }
예제 #7
0
  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);
  }
예제 #8
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);
   }
 }
예제 #9
0
  @Override
  public void handle(ApiRequest request) throws IOException {
    if (ApiContext.getContext().getPolicy() != null) {
      return;
    }
    if (ApiContext.getContext().getTransformationService() == null) {
      ApiContext.getContext().setTransformationService(transformationService);
    }

    Account authenticatedAsAccount = getAccount(request);
    if (authenticatedAsAccount == null
        || !StringUtils.equals(CommonStatesConstants.ACTIVE, authenticatedAsAccount.getState())) {
      throw new ClientVisibleException(ResponseCodes.UNAUTHORIZED);
    }

    Set<Identity> identities = getIdentities(authenticatedAsAccount);
    if (identities == null || identities.size() == 0) {
      throw new ClientVisibleException(ResponseCodes.UNAUTHORIZED);
    }

    Account account = getAccountRequested(authenticatedAsAccount, identities, request);
    Policy policy = getPolicy(account, authenticatedAsAccount, identities, request);
    if (policy == null) {
      log.error("Failed to find policy for [{}]", account.getId());
      throwUnauthorized();
    }

    SchemaFactory schemaFactory = getSchemaFactory(account, policy, request);
    if (schemaFactory == null) {
      log.error("Failed to find a schema for account type [{}]", account.getKind());
      if (SecurityConstants.SECURITY.get()) {
        throwUnauthorized();
      }
    }
    saveInContext(request, policy, schemaFactory);
  }
예제 #10
0
  private Token createToken(ApiRequest request) {
    Token token = null;
    if (SecurityConstants.AUTH_PROVIDER.get() == null
        || SecurityConstants.NO_PROVIDER.equalsIgnoreCase(SecurityConstants.AUTH_PROVIDER.get())) {
      throw new ClientVisibleException(
          ResponseCodes.INTERNAL_SERVER_ERROR,
          "NoAuthProvider",
          "No Auth provider is configured.",
          null);
    }
    for (TokenCreator tokenCreator : tokenCreators) {
      if (tokenCreator.isConfigured()
          && tokenCreator.providerType().equalsIgnoreCase(SecurityConstants.AUTH_PROVIDER.get())) {
        token = tokenCreator.getToken(request);
        break;
      }
    }
    if (token == null) {
      throw new ClientVisibleException(
          ResponseCodes.BAD_REQUEST, "codeInvalid", "Code provided is invalid.", null);
    }

    Identity[] identities = token.getIdentities();
    List<Identity> transFormedIdentities = new ArrayList<>();
    for (Identity identity : identities) {
      transFormedIdentities.add(identityManager.untransform(identity, true));
    }
    token.setIdentities(transFormedIdentities);
    token.setUserIdentity(identityManager.untransform(token.getUserIdentity(), true));
    token.setJwt(
        authTokenDao
            .createToken(
                token.getJwt(),
                token.getAuthProvider(),
                ((Policy) ApiContext.getContext().getPolicy()).getAccountId())
            .getKey());
    return token;
  }
예제 #11
0
 protected String getLink(ProcessDefinition def) {
   return ApiContext.getUrlBuilder()
       .resourceReferenceLink(ProcessDefinitionApi.class, def.getName())
       .toExternalForm();
 }