/**
   * Gets the list of approvals
   *
   * @param tenantId the URN of a tenant
   * @brief List Approvals
   * @return a list of approvals
   * @throws DatabaseException when a DB error occurs
   */
  @GET
  @Path("")
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public ApprovalList getApprovals(
      @DefaultValue("") @QueryParam(SearchConstants.TENANT_ID_PARAM) String tenantId)
      throws DatabaseException {

    StorageOSUser user = getUserFromContext();
    if (StringUtils.isBlank(tenantId)) {
      tenantId = user.getTenantId();
    }

    verifyAuthorizedInTenantOrg(uri(tenantId), getUserFromContext());

    List<ApprovalRequest> approvals = approvalManager.getApprovals(uri(tenantId));

    ApprovalList approvalList = new ApprovalList();
    for (ApprovalRequest approval : approvals) {
      NamedRelatedResourceRep approvalRestRep =
          toNamedRelatedResource(ResourceTypeEnum.APPROVAL, approval.getId(), approval.getLabel());
      approvalList.getApprovals().add(approvalRestRep);
    }

    return approvalList;
  }
  /**
   * parameter: 'orderId' The id of the order to search for approvals parameter: 'approvalStatus'
   * The status for the approval. parameter: 'tenantId' The id of the tenant (if not the current
   * tenant)
   *
   * @return Return a list of matching approvals or an empty list if no match was found.
   */
  @Override
  protected SearchResults getOtherSearchResults(
      Map<String, List<String>> parameters, boolean authorized) {

    StorageOSUser user = getUserFromContext();
    String tenantId = user.getTenantId();
    if (parameters.containsKey(SearchConstants.TENANT_ID_PARAM)) {
      tenantId = parameters.get(SearchConstants.TENANT_ID_PARAM).get(0);
    }
    verifyAuthorizedInTenantOrg(uri(tenantId), user);

    if (!parameters.containsKey(SearchConstants.ORDER_ID_PARAM)
        && !parameters.containsKey(SearchConstants.APPROVAL_STATUS_PARAM)) {
      throw APIException.badRequests.invalidParameterSearchMissingParameter(
          getResourceClass().getName(),
          SearchConstants.ORDER_ID_PARAM + " or " + SearchConstants.APPROVAL_STATUS_PARAM);
    }

    if (parameters.containsKey(SearchConstants.ORDER_ID_PARAM)
        && parameters.containsKey(SearchConstants.APPROVAL_STATUS_PARAM)) {
      throw APIException.badRequests.parameterForSearchCouldNotBeCombinedWithAnyOtherParameter(
          getResourceClass().getName(),
          SearchConstants.ORDER_ID_PARAM,
          SearchConstants.APPROVAL_STATUS_PARAM);
    }

    List<ApprovalRequest> approvals = Lists.newArrayList();
    if (parameters.containsKey(SearchConstants.ORDER_ID_PARAM)) {
      String orderId = parameters.get(SearchConstants.ORDER_ID_PARAM).get(0);
      ArgValidator.checkFieldNotEmpty(orderId, SearchConstants.ORDER_ID_PARAM);
      approvals = approvalManager.findApprovalsByOrderId(uri(orderId));
    } else if (parameters.containsKey(SearchConstants.APPROVAL_STATUS_PARAM)) {
      String approvalStatus = parameters.get(SearchConstants.APPROVAL_STATUS_PARAM).get(0);
      ArgValidator.checkFieldNotEmpty(approvalStatus, SearchConstants.APPROVAL_STATUS_PARAM);
      approvals =
          approvalManager.findApprovalsByStatus(
              uri(tenantId), ApprovalStatus.valueOf(approvalStatus));
    }

    ResRepFilter<SearchResultResourceRep> resRepFilter =
        (ResRepFilter<SearchResultResourceRep>)
            getPermissionFilter(getUserFromContext(), _permissionsHelper);

    List<SearchResultResourceRep> searchResultResourceReps = Lists.newArrayList();
    for (ApprovalRequest approval : approvals) {
      RestLinkRep selfLink =
          new RestLinkRep("self", RestLinkFactory.newLink(getResourceType(), approval.getId()));
      SearchResultResourceRep searchResultResourceRep = new SearchResultResourceRep();
      searchResultResourceRep.setId(approval.getId());
      searchResultResourceRep.setLink(selfLink);
      if (authorized || resRepFilter.isAccessible(searchResultResourceRep)) {
        searchResultResourceReps.add(searchResultResourceRep);
      }
    }

    SearchResults result = new SearchResults();
    result.setResource(searchResultResourceReps);
    return result;
  }
 private String getOwner(String orgOwner) {
   String owner = orgOwner;
   if (null == orgOwner || orgOwner.isEmpty()) {
     StorageOSUser user = getUserFromContext();
     owner = user.getName();
   }
   return owner;
 }
 /**
  * Checks if the user is authorized in the tenant org or not. Authorized if, The user is in the
  * tenant org. The user who is not in the tenant org, but is a TenantAdmin of the tenant org.
  *
  * @param tenantId the tenants list that shares the vCenter.
  * @return true if the user is authorized for the tenant org, false otherwise.
  */
 protected boolean verifyAuthorizedInTenantOrg(URI tenantId) {
   StorageOSUser user = getUserFromContext();
   if (tenantId.toString().equals(user.getTenantId())
       || _permissionsHelper.userHasGivenRole(user, tenantId, Role.TENANT_ADMIN)) {
     return true;
   }
   return false;
 }
 @Deprecated
 public void createRecentCatalogService(CatalogService catalogService, StorageOSUser user) {
   List<RecentService> recentServices = getRecentServices(user.getUserName());
   if (catalogService != null) {
     RecentService found = findRecentService(recentServices, catalogService, user);
     if (found != null) {
       // Delete and Re-Save to update Created Time
       client.delete(found);
       createRecentService(catalogService.getId(), user.getUserName());
     } else {
       cleanUpRecentServices(recentServices);
       createRecentService(catalogService.getId(), user.getUserName());
     }
   }
 }
  /**
   * Updates the tenant information in the Task data object and TaskResourceRep (the response object
   * to the API request). Both Task and TaskResourceRep is updated with the user's tenant
   * information if it they don't contain any tenant information already.
   *
   * @param taskResourceRep api response to be updated.
   */
  private void updateTaskTenant(TaskResourceRep taskResourceRep) {
    Task task = _dbClient.queryObject(Task.class, taskResourceRep.getId());
    if (areEqual(task.getTenant(), NullColumnValueGetter.getNullURI())) {
      StorageOSUser user = getUserFromContext();
      URI userTenantUri = URI.create(user.getTenantId());
      task.setTenant(userTenantUri);

      RelatedResourceRep tenant = new RelatedResourceRep();
      tenant.setId(userTenantUri);
      tenant.setLink(new RestLinkRep("self", URI.create("/tenants/" + userTenantUri.toString())));

      taskResourceRep.setTenant(tenant);
      _dbClient.persistObject(task);

      List<String> traceParams = new ArrayList<String>();
      traceParams.add(task.getId().toString());
      traceParams.add(user.getName());
      traceParams.add(user.getTenantId());

      _log.info("Update the task {} with the user's {} tenant {}", traceParams);
    }
  }
 @Deprecated
 public List<CatalogService> getRecentCatalogServices(StorageOSUser user) {
   List<CatalogService> catalogServices = Lists.newArrayList();
   List<RecentService> recentServices = getRecentServices(user.getUserName());
   for (RecentService recentService : recentServices) {
     CatalogService catalogService =
         client.catalogServices().findById(recentService.getCatalogServiceId());
     if (catalogService != null) {
       catalogServices.add(catalogService);
     }
   }
   SortedIndexUtils.sort(catalogServices);
   return catalogServices;
 }
  /**
   * Checks if the user is authorized to view the vCenter. Authorized if, The user a TenantOrg user
   * of one the tenant that shares the vCenter. The user is a TenantAdmin of one of the tenant that
   * shares the vCenter.
   *
   * @param aclEntries the tenants list that shares the vCenter.
   */
  private void verifyAuthorizedInTenantOrg(List<ACLEntry> aclEntries) {
    boolean isUserAuthorized = false;
    StorageOSUser user = getUserFromContext();
    Iterator<ACLEntry> aclEntriesIterator = aclEntries.iterator();
    while (aclEntriesIterator.hasNext()) {
      ACLEntry aclEntry = aclEntriesIterator.next();
      if (aclEntry == null) {
        continue;
      }

      if (user.getTenantId().toString().equals(aclEntry.getTenant())
          || isSystemAdminOrMonitorUser()
          || _permissionsHelper.userHasGivenRole(
              user, URI.create(aclEntry.getTenant()), Role.TENANT_ADMIN)) {
        isUserAuthorized = true;
        break;
      }
    }

    if (!isUserAuthorized) {
      throw APIException.forbidden.insufficientPermissionsForUser(user.getName());
    }
  }
예제 #9
0
  /**
   * Get the summary list of all Quotas for the given tenant
   *
   * @prereq none
   * @param tenant_id the URN of the tenant asking for quotas
   * @param target_tenant_id
   * @brief Get the summary list of all Quotas
   * @return Quota details of target_tenant_id
   */
  @GET
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Path("/{target_tenant_id}")
  @CheckPermission(
      roles = {Role.SYSTEM_MONITOR, Role.TENANT_ADMIN},
      acls = {ACL.ANY})
  public Response getQuotaDetails(
      @PathParam("target_tenant_id") String openstack_target_tenant_id,
      @Context HttpHeaders header) {

    Project project =
        getCinderHelper().getProject(openstack_target_tenant_id.toString(), getUserFromContext());

    if (project == null) {
      throw APIException.badRequests.projectWithTagNonexistent(openstack_target_tenant_id);
    }

    long maxQuota = 0;
    if (project.getQuotaEnabled()) {
      maxQuota = (long) (project.getQuota().intValue());
    } else {
      maxQuota = DEFAULT_PROJECT_TOTALGB_QUOTA;
    }

    List<URI> quotas = _dbClient.queryByType(QuotaOfCinder.class, true);
    Map<String, String> vpoolsMap = new HashMap<String, String>();
    boolean bDefProjQuotasExist = false;

    CinderQuotaDetails respCinderQuota = new CinderQuotaDetails();

    for (URI quota : quotas) {
      QuotaOfCinder quotaObj = _dbClient.queryObject(QuotaOfCinder.class, quota);

      if ((quotaObj.getProject() != null)
          && (quotaObj.getProject().toString().equalsIgnoreCase(project.getId().toString()))) {
        if (quotaObj.getVpool() != null) {
          VirtualPool pool = _dbClient.queryObject(VirtualPool.class, quotaObj.getVpool());
          respCinderQuota.quota_set.put(
              "gigabytes" + "_" + pool.getLabel(), String.valueOf(quotaObj.getTotalQuota()));
          respCinderQuota.quota_set.put(
              "snapshots" + "_" + pool.getLabel(), String.valueOf(quotaObj.getSnapshotsLimit()));
          respCinderQuota.quota_set.put(
              "volumes" + "_" + pool.getLabel(), String.valueOf(quotaObj.getVolumesLimit()));
          vpoolsMap.put(pool.getLabel(), pool.getLabel());
        } else {
          respCinderQuota.quota_set.put("gigabytes", String.valueOf(quotaObj.getTotalQuota()));
          respCinderQuota.quota_set.put("snapshots", String.valueOf(quotaObj.getSnapshotsLimit()));
          respCinderQuota.quota_set.put(
              "volumes", String.valueOf(quotaObj.getVolumesLimit().intValue()));
          bDefProjQuotasExist = true;
        }
      }
    }

    if (!bDefProjQuotasExist) {
      respCinderQuota.quota_set.put("gigabytes", String.valueOf(maxQuota));
      respCinderQuota.quota_set.put("snapshots", String.valueOf(DEFAULT_PROJECT_SNAPSHOTS_QUOTA));
      respCinderQuota.quota_set.put("volumes", String.valueOf(DEFAULT_PROJECT_VOLUMES_QUOTA));
      getCinderHelper().createProjectDefaultQuota(project);
    }

    StorageOSUser user = getUserFromContext();
    URI tenantId = URI.create(user.getTenantId());

    List<URI> vpools = _dbClient.queryByType(VirtualPool.class, true);
    for (URI vpool : vpools) {
      VirtualPool pool = _dbClient.queryObject(VirtualPool.class, vpool);
      _log.debug("Looking up vpool {}", pool.getLabel());
      if (pool != null && pool.getType().equalsIgnoreCase(VirtualPool.Type.block.name())) {
        if (_permissionsHelper.tenantHasUsageACL(tenantId, pool)) {
          if (vpoolsMap.containsKey(pool.getLabel())) {
            continue;
          } else {
            respCinderQuota.quota_set.put(
                "gigabytes" + "_" + pool.getLabel(),
                String.valueOf(DEFAULT_VOLUME_TYPE_TOTALGB_QUOTA));
            respCinderQuota.quota_set.put(
                "snapshots" + "_" + pool.getLabel(),
                String.valueOf(DEFAULT_VOLUME_TYPE_SNAPSHOTS_QUOTA));
            respCinderQuota.quota_set.put(
                "volumes" + "_" + pool.getLabel(),
                String.valueOf(DEFAULT_VOLUME_TYPE_VOLUMES_QUOTA));
            getCinderHelper().createVpoolDefaultQuota(project, pool);
          }
        }
      }
    }

    return getQuotaDetailFormat(header, respCinderQuota);
  }
  /**
   * This call returns the list of tenants that the user maps to including the details of the
   * mappings. It also returns a list of the virtual data center roles and tenant roles assigned to
   * this user.
   *
   * @brief Show my Tenant and assigned roles
   * @prereq none
   * @return List of tenants user mappings,VDC role and tenant role of the user.
   */
  @GET
  @Path("/whoami")
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public UserInfo getMyInfo() {
    Principal principal = sc.getUserPrincipal();
    if (!(principal instanceof StorageOSUser)) {
      throw APIException.forbidden.invalidSecurityContext();
    }
    StorageOSUser user = (StorageOSUser) principal;
    UserInfo info = new UserInfo();
    info.setCommonName(user.getName());
    // To Do - fix Distinguished name - for now setting it to name
    info.setDistinguishedName(user.getName());
    info.setTenant(user.getTenantId());
    info.setTenantName(_permissionsHelper.getTenantNameByID(user.getTenantId()));
    info.setVdcRoles(new ArrayList<String>());
    info.setHomeTenantRoles(new ArrayList<String>());
    info.setSubTenantRoles(new ArrayList<SubTenantRoles>());

    // special check: root in geo scenario
    boolean isLocalVdcSingleSite = VdcUtil.isLocalVdcSingleSite();
    boolean isRootInGeo = user.getName().equalsIgnoreCase("root") && (!isLocalVdcSingleSite);

    // add Vdc Roles
    if (user.getRoles() != null) {
      for (String role : user.getRoles()) {

        // geo scenario, return RESTRICTED_*_ADMIN for root, instead of *_ADMIN
        if (isRootInGeo) {
          if (role.equalsIgnoreCase(Role.SYSTEM_ADMIN.toString())) {
            role = Role.RESTRICTED_SYSTEM_ADMIN.toString();
          }

          if (role.equalsIgnoreCase(Role.SECURITY_ADMIN.toString())) {
            role = Role.RESTRICTED_SECURITY_ADMIN.toString();
          }
        }

        info.getVdcRoles().add(role);
      }
    }

    // geo scenario, skip adding tenant roles for root
    if (isRootInGeo) {
      return info;
    }

    try {
      Set<String> tenantRoles =
          _permissionsHelper.getTenantRolesForUser(user, URI.create(user.getTenantId()), false);
      if (tenantRoles != null) {
        for (String role : tenantRoles) {
          info.getHomeTenantRoles().add(role);
        }
      }

      Map<String, Collection<String>> subTenantRoles =
          _permissionsHelper.getSubtenantRolesForUser(user);
      if (subTenantRoles != null) {
        for (Entry<String, Collection<String>> entry : subTenantRoles.entrySet()) {
          SubTenantRoles subRoles = new SubTenantRoles();
          subRoles.setTenant(entry.getKey());
          subRoles.setTenantName(_permissionsHelper.getTenantNameByID(entry.getKey()));
          subRoles.setRoles(new ArrayList<String>(entry.getValue()));
          info.getSubTenantRoles().add(subRoles);
        }
      }

    } catch (DatabaseException ex) {
      throw SecurityException.fatals.failedReadingTenantRoles(ex);
    }

    return info;
  }