@Test
  public void testReadRolesInSchema() throws Exception {
    final MondrianCatalogHelper helper =
        (MondrianCatalogHelper) PentahoSystem.get(IMondrianCatalogService.class);
    Assert.assertNotNull(helper);
    MondrianCatalog mc =
        SecurityHelper.getInstance()
            .runAsUser(
                "admin",
                new Callable<MondrianCatalog>() {
                  @Override
                  public MondrianCatalog call() throws Exception {
                    return helper.getCatalog("SteelWheelsRoles", PentahoSessionHolder.getSession());
                  }
                });

    Assert.assertNotNull(mc);
    MondrianSchema ms = mc.getSchema();
    Assert.assertNotNull(ms);
    String[] roleNames = ms.getRoleNames();
    Assert.assertNotNull(roleNames);
    Assert.assertEquals(2, roleNames.length);
    Assert.assertEquals("Role1", roleNames[0]);
    Assert.assertEquals("Role2", roleNames[1]);
  }
  @Test
  public void testMondrianOneToOneUserRoleListMapper() throws Exception {
    final IConnectionUserRoleMapper mapper = new MondrianOneToOneUserRoleListMapper();
    try {
      String[] roles =
          SecurityHelper.getInstance()
              .runAsUser(
                  "simplebob",
                  new Callable<String[]>() {
                    @Override
                    public String[] call() throws Exception {
                      return mapper.mapConnectionRoles(
                          PentahoSessionHolder.getSession(), "SteelWheelsRoles");
                    }
                  });

      Assert.assertNotNull(roles);
      Assert.assertEquals(2, roles.length);
      Assert.assertEquals("Role1", roles[0]);
      Assert.assertEquals("Role2", roles[1]);

    } catch (PentahoAccessControlException e) {
      Assert.fail(e.getMessage());
    }
  }
 /**
  * Returns whether the current user is an administrator
  *
  * @return "true" or "false"
  */
 @GET
 @Path("/isAdministrator")
 public Response isAdministrator() {
   return Response.ok(
           "" + (SecurityHelper.getInstance().isPentahoAdministrator(getPentahoSession())))
       .build();
 }
  /**
   * Logs in with given username.
   *
   * @param username username of user
   * @param tenantId tenant to which this user belongs
   * @tenantAdmin true to add the tenant admin authority to the user's roles
   */
  protected void login(final String username, final ITenant tenant, String[] roles) {
    StandaloneSession pentahoSession =
        new StandaloneSession(tenantedUserNameUtils.getPrincipleId(tenant, username));
    pentahoSession.setAuthenticated(
        tenant.getId(), tenantedUserNameUtils.getPrincipleId(tenant, username));
    PentahoSessionHolder.setSession(pentahoSession);
    pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, tenant.getId());
    final String password = "******";

    List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();

    for (String roleName : roles) {
      authList.add(
          new GrantedAuthorityImpl(tenantedRoleNameUtils.getPrincipleId(tenant, roleName)));
    }
    GrantedAuthority[] authorities = authList.toArray(new GrantedAuthority[0]);
    UserDetails userDetails = new User(username, password, true, true, true, true, authorities);
    Authentication auth =
        new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
    PentahoSessionHolder.setSession(pentahoSession);
    // this line necessary for Spring Security's MethodSecurityInterceptor
    SecurityContextHolder.getContext().setAuthentication(auth);
    SecurityHelper.getInstance().becomeUser(tenantedUserNameUtils.getPrincipleId(tenant, username));
    SecurityContextHolder.getContext().setAuthentication(auth);
  }
  @Before
  public void setUp() throws Exception {
    repository = mock(IUnifiedRepository.class);

    session = mock(IPentahoSession.class);
    when(session.getName()).thenReturn("test");
    PentahoSessionHolder.setSession(session);

    userSettings =
        new HashMap<String, Serializable>() {
          {
            put(USER_SETTING_NAME_1, USER_SETTING_VALUE_1);
            put(UserSettingService.SETTING_PREFIX + COMMON_SETTING_NAME, COMMON_USER_SETTING_VALUE);
            put(USER_SETTING_NAME_2, USER_SETTING_VALUE_2);
            put(UserSettingService.SETTING_PREFIX + USER_SETTING_NAME_3, USER_SETTING_VALUE_3);
          }
        };
    globalSettings =
        new HashMap<String, Serializable>() {
          {
            put(GLOBAL_SETTING_NAME_1, GLOBAL_SETTING_VALUE_1);
            put(
                UserSettingService.SETTING_PREFIX + COMMON_SETTING_NAME,
                COMMON_GLOBAL_SETTING_VALUE);
            put(GLOBAL_SETTING_NAME_2, GLOBAL_SETTING_VALUE_2);
            put(UserSettingService.SETTING_PREFIX + GLOBAL_SETTING_NAME_3, GLOBAL_SETTING_VALUE_3);
          }
        };

    when(repository.getFileMetadata(eq(USER_FOLDER_ID))).thenReturn(userSettings);
    when(repository.getFileMetadata(eq(TENANT_FOLDER_ID))).thenReturn(globalSettings);

    final RepositoryFile tenantRepositoryFile = mock(RepositoryFile.class);
    when(tenantRepositoryFile.getId()).thenReturn(TENANT_FOLDER_ID);
    when(repository.getFile(eq(ClientRepositoryPaths.getEtcFolderPath())))
        .thenReturn(tenantRepositoryFile);

    final RepositoryFile userRepositoryFile = mock(RepositoryFile.class);
    when(userRepositoryFile.getId()).thenReturn(USER_FOLDER_ID);
    when(repository.getFile(eq(ClientRepositoryPaths.getUserHomeFolderPath(session.getName()))))
        .thenReturn(userRepositoryFile);

    securityHelper = mock(ISecurityHelper.class);
    when(securityHelper.runAsSystem(any(Callable.class)))
        .thenAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                final Callable callable = (Callable) invocation.getArguments()[0];
                if (callable != null) {
                  return callable.call();
                }
                return null;
              }
            });
    SecurityHelper.setMockInstance(securityHelper);

    userSettingService = new UserSettingService(repository);
    userSettingService.init(session);
  }
  public List<String> getPermittedRoleList(IPentahoSession session) {
    List<String> roleList = new ArrayList<String>();
    Authentication auth = SecurityHelper.getAuthentication(session, true);
    IPluginResourceLoader resLoader = PentahoSystem.get(IPluginResourceLoader.class, null);
    String roles = null;

    try {
      roles =
          resLoader.getPluginSetting(getClass(), "settings/data-access-view-roles"); // $NON-NLS-1$
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (roles != null) {
      String roleArr[] = roles.split(","); // $NON-NLS-1$

      for (String role : roleArr) {
        for (GrantedAuthority userRole : auth.getAuthorities()) {
          if (role != null && role.trim().equals(userRole.getAuthority())) {
            roleList.add(role);
          }
        }
      }
    }
    return roleList;
  }
  @Test
  public void testLookupMapUserRoleListMapper() throws Exception {
    Map<String, String> lookup = new HashMap<String, String>();
    lookup.put("ceo", "Role1");
    lookup.put("Not Pentaho", "Role2");
    lookup.put("Not Mondrian or Pentaho", "Role3");

    final MondrianLookupMapUserRoleListMapper mapper = new MondrianLookupMapUserRoleListMapper();
    mapper.setLookupMap(lookup);

    try {
      String[] roles =
          SecurityHelper.getInstance()
              .runAsUser(
                  "admin",
                  new Callable<String[]>() {
                    @Override
                    public String[] call() throws Exception {
                      return mapper.mapConnectionRoles(
                          PentahoSessionHolder.getSession(), "SteelWheelsRoles");
                    }
                  });
      Assert.assertNotNull(roles);
      Assert.assertEquals(1, roles.length);
      Assert.assertEquals("Role1", roles[0]);
    } catch (PentahoAccessControlException e) {
      Assert.fail(e.getMessage());
    }
  }
  @Test
  public void testMondrianUserSessionUserRoleListMapper() throws Exception {
    final MondrianUserSessionUserRoleListMapper mapper =
        new MondrianUserSessionUserRoleListMapper();
    mapper.setSessionProperty("rolesAttribute");

    try {
      String[] roles =
          SecurityHelper.getInstance()
              .runAsUser(
                  "admin",
                  new Callable<String[]>() {
                    @Override
                    public String[] call() throws Exception {
                      IPentahoSession session = PentahoSessionHolder.getSession();
                      session.setAttribute(
                          "rolesAttribute",
                          new Object[] {"mondrianRole1", "mondrianRole2", "mondrianRole3"});
                      return mapper.mapConnectionRoles(session, "SteelWheelsRoles");
                    }
                  });

      Assert.assertNotNull(roles);
      Assert.assertEquals(3, roles.length);
      Assert.assertEquals("mondrianRole1", roles[0]);
      Assert.assertEquals("mondrianRole2", roles[1]);
      Assert.assertEquals("mondrianRole3", roles[2]);
    } catch (PentahoAccessControlException e) {
      Assert.fail(e.getMessage());
    }
  }
  @Test
  public void testNoMatchLookupMapUserRoleListMapper() throws Exception {
    Map<String, String> lookup = new HashMap<String, String>();
    lookup.put("No Match", "Role1");
    lookup.put("No Match Here Either", "Role2");

    final MondrianLookupMapUserRoleListMapper mapper = new MondrianLookupMapUserRoleListMapper();
    mapper.setLookupMap(lookup);

    mapper.setFailOnEmptyRoleList(true);
    try {
      SecurityHelper.getInstance()
          .runAsUser(
              "admin",
              new Callable<String[]>() {
                @Override
                public String[] call() throws Exception {
                  return mapper.mapConnectionRoles(
                      PentahoSessionHolder.getSession(), "SteelWheelsRoles");
                }
              });
      Assert.fail();
    } catch (PentahoAccessControlException e) {
      // no op.
    }

    mapper.setFailOnEmptyRoleList(false);

    try {
      String[] roles =
          SecurityHelper.getInstance()
              .runAsUser(
                  "admin",
                  new Callable<String[]>() {
                    @Override
                    public String[] call() throws Exception {
                      return mapper.mapConnectionRoles(
                          PentahoSessionHolder.getSession(), "SteelWheelsRoles");
                    }
                  });
      Assert.assertNull(roles);
    } catch (PentahoAccessControlException e) {
      Assert.fail(e.getMessage());
    }
  }
 private String generateInMemoryDatasourcesXml() {
   try {
     return SecurityHelper.getInstance()
         .runAsSystem(
             new Callable<String>() {
               public String call() throws Exception {
                 return mondrianCatalogService.generateInMemoryDatasourcesXml(repo);
               }
             });
   } catch (Exception e) {
     PentahoXmlaServlet.logger.error(e);
     throw new RuntimeException(e);
   }
 }
 @Test
 public void testNoMatchMondrianOneToOneUserRoleListMapper() throws Exception {
   final MondrianOneToOneUserRoleListMapper mapper = new MondrianOneToOneUserRoleListMapper();
   mapper.setFailOnEmptyRoleList(true);
   try {
     SecurityHelper.getInstance()
         .runAsUser(
             "admin",
             new Callable<String[]>() {
               @Override
               public String[] call() throws Exception {
                 return mapper.mapConnectionRoles(
                     PentahoSessionHolder.getSession(), "SteelWheelsRoles");
               }
             });
     Assert.fail();
   } catch (PentahoAccessControlException e) {
     // No op.
   }
   mapper.setFailOnEmptyRoleList(false);
   try {
     String[] roles =
         SecurityHelper.getInstance()
             .runAsUser(
                 "simplebob",
                 new Callable<String[]>() {
                   @Override
                   public String[] call() throws Exception {
                     return mapper.mapConnectionRoles(
                         PentahoSessionHolder.getSession(), "SteelWheelsRoles");
                   }
                 });
     Assert.assertArrayEquals(new String[] {"Role1", "Role2"}, roles);
   } catch (PentahoAccessControlException e) {
     Assert.fail(e.getMessage());
   }
 }
예제 #12
0
  @SuppressWarnings("deprecation")
  public void testVoter() throws Exception {
    SecurityHelper.getInstance()
        .runAsUser(
            "suzy",
            new Callable<Void>() {

              @Override
              public Void call() throws Exception {
                RepositoryFile testFile =
                    new RepositoryFile("Test Folder", null, null); // $NON-NLS-1$
                Map<IPermissionRecipient, IPermissionMask> perms =
                    new LinkedHashMap<IPermissionRecipient, IPermissionMask>();
                perms.put(
                    new SimpleUser("suzy"),
                    new SimplePermissionMask(IPentahoAclEntry.PERM_EXECUTE));
                perms.put(
                    new SimpleRole("ROLE_CTO"),
                    new SimplePermissionMask(IPentahoAclEntry.PERM_SUBSCRIBE));
                perms.put(
                    new SimpleRole("ROLE_IS"),
                    new SimplePermissionMask(IPentahoAclEntry.PERM_ADMINISTRATION));
                SpringSecurityPermissionMgr.instance().setPermissions(perms, testFile);
                PentahoBasicAclVoter voter = new PentahoBasicAclVoter();
                assertTrue(
                    voter.hasAccess(
                        PentahoSessionHolder.getSession(),
                        testFile,
                        IPentahoAclEntry.PERM_EXECUTE));
                assertTrue(
                    voter.hasAccess(
                        PentahoSessionHolder.getSession(),
                        testFile,
                        IPentahoAclEntry.PERM_SUBSCRIBE));
                assertTrue(
                    voter.hasAccess(
                        PentahoSessionHolder.getSession(),
                        testFile,
                        IPentahoAclEntry.PERM_ADMINISTRATION));
                PentahoAclEntry entry =
                    voter.getEffectiveAcl(PentahoSessionHolder.getSession(), testFile);
                assertNotNull(entry);
                assertEquals(entry.printPermissionsBlock(), "XSCUDP"); // $NON-NLS-1$
                return null;
              }
            });
  }
 private String getDatasourcesXml() {
   final Callable<String> call =
       new Callable<String>() {
         public String call() throws Exception {
           return generateInMemoryDatasourcesXml();
         }
       };
   try {
     if (isSecurityEnabled()) {
       return SecurityHelper.getInstance().runAsSystem(call);
     } else {
       return call.call();
     }
   } catch (Exception e) {
     throw new IOlapServiceException(e);
   }
 }
 @Test
 public void testReadRolesInPlatform() throws Exception {
   SecurityHelper.getInstance()
       .runAsUser(
           "admin",
           new Callable<Void>() {
             @Override
             public Void call() throws Exception {
               Authentication auth = SecurityHelper.getInstance().getAuthentication();
               Assert.assertNotNull(auth);
               GrantedAuthority[] gAuths = auth.getAuthorities();
               Assert.assertNotNull(gAuths);
               Assert.assertEquals(3, gAuths.length);
               Assert.assertEquals("ceo", gAuths[0].getAuthority());
               Assert.assertEquals("Admin", gAuths[1].getAuthority());
               Assert.assertEquals("Authenticated", gAuths[2].getAuthority());
               return null;
             }
           });
 }
  @Test
  public void testNoMatchMondrianUserSessionUserRoleListMapper() throws Exception {
    final MondrianUserSessionUserRoleListMapper mapper =
        new MondrianUserSessionUserRoleListMapper();
    mapper.setSessionProperty("rolesAttribute");

    try {
      String[] roles =
          SecurityHelper.getInstance()
              .runAsUser(
                  "admin",
                  new Callable<String[]>() {
                    @Override
                    public String[] call() throws Exception {
                      return mapper.mapConnectionRoles(
                          PentahoSessionHolder.getSession(), "SteelWheelsRoles");
                    }
                  });

      Assert.assertNull(roles);
    } catch (PentahoAccessControlException e) {
      Assert.fail(e.getMessage());
    }
  }
  /** Initializes the cache. Only the cache specific to the sesison's locale will be populated. */
  protected void initCache(IPentahoSession session) {

    final List<Catalog> cache = getCache(session);

    final boolean needUpdate;
    final Lock readLock = cacheLock.readLock();

    try {
      readLock.lock();
      // Check if the cache is empty.
      if (cache.size() == 0) {
        needUpdate = true;
      } else {
        needUpdate = false;
      }
    } finally {
      readLock.unlock();
    }

    if (needUpdate) {
      final Lock writeLock = cacheLock.writeLock();
      try {
        writeLock.lock();

        // First clear the cache
        cache.clear();

        final Callable<Void> call =
            new Callable<Void>() {
              public Void call() throws Exception {
                // Now build the cache. Use the system session in the holder.
                for (String name : getHelper().getHostedCatalogs()) {
                  try {
                    addCatalogToCache(PentahoSessionHolder.getSession(), name);
                  } catch (Throwable t) {
                    LOG.error("Failed to initialize the cache for OLAP connection " + name, t);
                  }
                }
                for (String name : getHelper().getOlap4jServers()) {
                  try {
                    addCatalogToCache(PentahoSessionHolder.getSession(), name);
                  } catch (Throwable t) {
                    LOG.error("Failed to initialize the cache for OLAP connection " + name, t);
                  }
                }
                return null;
              }
            };

        if (isSecurityEnabled()) {
          SecurityHelper.getInstance().runAsSystem(call);
        } else {
          call.call();
        }

        // Sort it all.
        Collections.sort(
            cache,
            new Comparator<IOlapService.Catalog>() {
              public int compare(Catalog o1, Catalog o2) {
                return o1.name.compareTo(o2.name);
              }
            });

      } catch (Throwable t) {

        LOG.error("Failed to initialize the connection cache", t);

        throw new IOlapServiceException(t);

      } finally {
        writeLock.unlock();
      }
    }
  }
예제 #17
0
 /**
  * Utility method for access negotiation. For performance, not all files will be checked against
  * the supplied voter.
  *
  * @param aFile
  * @param actionOperation
  * @param session
  * @return
  */
 public static boolean hasAccess(
     final IAclSolutionFile aFile, final int actionOperation, final IPentahoSession session) {
   if (aFile == null) {
     return false;
   }
   if (!aFile.isDirectory()) {
     List extensionList = PentahoSystem.getACLFileExtensionList();
     String fName = aFile.getFileName();
     int posn = fName.lastIndexOf('.');
     if (posn >= 0) {
       if (extensionList.indexOf(fName.substring(posn)) < 0) {
         // Non-acl'd file. Return true.
         return true;
       }
     } else {
       // Untyped file. Allow access.
       return true;
     }
   }
   IAclVoter voter = PentahoSystem.get(IAclVoter.class, session);
   int aclMask = -1;
   switch (actionOperation) {
     case ISolutionRepository.ACTION_EXECUTE:
       {
         aclMask = IPentahoAclEntry.PERM_EXECUTE;
         break;
       }
     case ISolutionRepository.ACTION_ADMIN:
       {
         // aclMask = PentahoAclEntry.ADMINISTRATION;
         // break;
         return SecurityHelper.isPentahoAdministrator(session);
       }
     case ISolutionRepository.ACTION_SUBSCRIBE:
       {
         aclMask = IPentahoAclEntry.PERM_SUBSCRIBE;
         break;
       }
     case ISolutionRepository.ACTION_CREATE:
       {
         aclMask = IPentahoAclEntry.PERM_CREATE;
         break;
       }
     case ISolutionRepository.ACTION_UPDATE:
       {
         aclMask = IPentahoAclEntry.PERM_UPDATE;
         break;
       }
     case ISolutionRepository.ACTION_DELETE:
       {
         aclMask = IPentahoAclEntry.PERM_DELETE;
         break;
       }
     case ISolutionRepository.ACTION_SHARE:
       {
         aclMask = IPentahoAclEntry.PERM_UPDATE_PERMS;
         break;
       }
     default:
       {
         aclMask = IPentahoAclEntry.PERM_EXECUTE;
         break;
       }
   }
   return voter.hasAccess(session, aFile, aclMask);
 }