@Test
  public void shouldPerformCheckConnectionOnPluginAndCatchAnyExceptionsThrownByThePlugin()
      throws Exception {
    String pluginId = "yum";
    PackageRepository packageRepository = packageRepository(pluginId);
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();

    PackageRepositoryService service =
        new PackageRepositoryService(
            pluginManager,
            packageAsRepositoryExtension,
            goConfigService,
            securityService,
            entityHashingService,
            localizer);

    ArgumentCaptor<RepositoryConfiguration> argumentCaptor =
        ArgumentCaptor.forClass(RepositoryConfiguration.class);
    when(packageAsRepositoryExtension.checkConnectionToRepository(
            eq(pluginId), argumentCaptor.capture()))
        .thenThrow(new RuntimeException("Check Connection not implemented!!"));

    service.checkConnection(packageRepository, result);

    assertThat(result.isSuccessful(), is(false));
    when(localizer.localize(
            "PACKAGE_REPOSITORY_CHECK_CONNECTION_FAILED", "Check Connection not implemented!!"))
        .thenReturn("error_msg");
    assertThat(result.message(localizer), is("error_msg"));
    verify(packageAsRepositoryExtension)
        .checkConnectionToRepository(eq(pluginId), any(RepositoryConfiguration.class));
  }
Пример #2
0
  @Test
  public void shouldReturnTheCorrectLocalizedMessageForDuplicatePipelinesInAnEnvironment() {
    BasicEnvironmentConfig environmentConfig = environmentConfig("uat");
    goConfigService.addPipeline(
        PipelineConfigMother.createPipelineConfig("foo", "dev", "job"), "foo-grp");
    environmentConfig.addPipeline(new CaseInsensitiveString("foo"));
    goConfigService.addEnvironment(environmentConfig);

    ArrayList<String> pipelines = new ArrayList<>();
    pipelines.add("foo");
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    service.createEnvironment(
        env("foo-env", pipelines, new ArrayList<Map<String, String>>(), new ArrayList<String>()),
        new Username(new CaseInsensitiveString("any")),
        result);

    result = new HttpLocalizedOperationResult();
    service.createEnvironment(
        env("env", pipelines, new ArrayList<Map<String, String>>(), new ArrayList<String>()),
        new Username(new CaseInsensitiveString("any")),
        result);
    assertThat(
        result.message(localizer),
        is(
            "Failed to add environment. Associating pipeline(s) which is already part of uat environment"));
  }
  @Test
  public void shouldPopulateErrorsForCheckConnectionOnPlugin() throws Exception {
    String pluginId = "yum";
    PackageRepository packageRepository = packageRepository(pluginId);
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    PackageRepositoryService service =
        new PackageRepositoryService(
            pluginManager,
            packageAsRepositoryExtension,
            goConfigService,
            securityService,
            entityHashingService,
            localizer);

    ArgumentCaptor<RepositoryConfiguration> argumentCaptor =
        ArgumentCaptor.forClass(RepositoryConfiguration.class);

    when(packageAsRepositoryExtension.checkConnectionToRepository(
            eq(pluginId), argumentCaptor.capture()))
        .thenReturn(new Result().withErrorMessages("Repo invalid!!", "Could not connect"));
    service.checkConnection(packageRepository, result);

    RepositoryConfiguration packageConfigurations = argumentCaptor.getValue();
    PackageMaterialTestHelper.assertPackageConfiguration(
        packageConfigurations.list(), packageRepository.getConfiguration());
    assertThat(result.isSuccessful(), is(false));

    when(localizer.localize(
            "PACKAGE_REPOSITORY_CHECK_CONNECTION_FAILED", "Repo invalid!!\nCould not connect"))
        .thenReturn("error_msg");
    assertThat(result.message(localizer), is("error_msg"));
    verify(packageAsRepositoryExtension)
        .checkConnectionToRepository(eq(pluginId), any(RepositoryConfiguration.class));
  }
  @Test
  public void shouldPerformCheckConnectionOnPlugin() throws Exception {
    String pluginId = "yum";
    PackageRepository packageRepository = packageRepository(pluginId);
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();

    PackageRepositoryService service =
        new PackageRepositoryService(
            pluginManager,
            packageAsRepositoryExtension,
            goConfigService,
            securityService,
            entityHashingService,
            localizer);

    ArgumentCaptor<RepositoryConfiguration> argumentCaptor =
        ArgumentCaptor.forClass(RepositoryConfiguration.class);
    when(packageAsRepositoryExtension.checkConnectionToRepository(
            eq(pluginId), argumentCaptor.capture()))
        .thenReturn(new Result().withSuccessMessages("Accessed Repo File!!!"));

    service.checkConnection(packageRepository, result);

    RepositoryConfiguration packageConfigurations = argumentCaptor.getValue();
    PackageMaterialTestHelper.assertPackageConfiguration(
        packageConfigurations.list(), packageRepository.getConfiguration());
    assertThat(result.isSuccessful(), is(true));
    when(localizer.localize("CONNECTION_OK", "Accessed Repo File!!!")).thenReturn("success_msg");
    assertThat(result.message(localizer), is("success_msg"));
    verify(packageAsRepositoryExtension)
        .checkConnectionToRepository(eq(pluginId), any(RepositoryConfiguration.class));
  }
Пример #5
0
 @Test
 public void shouldPopulateResultWithErrorIfEnvNotFound() throws NoSuchEnvironmentException {
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   ConfigElementForEdit<EnvironmentConfig> edit = service.forEdit("foo-env", result);
   assertThat(result.message(localizer), is("Environment named 'foo-env' not found."));
   assertThat(edit, is(nullValue()));
 }
Пример #6
0
  @Test
  public void shouldNotUpdateEnvironmentIfEditingOverAStaleCopy() throws Exception {
    configHelper.addEnvironments("prod");
    String staleMd5 = goConfigDao.md5OfConfigFile();
    service.updateEnvironment(
        "prod",
        environmentConfig("uat1"),
        new Username(new CaseInsensitiveString("foo")),
        staleMd5);
    assertThat("md5 should be stale", goConfigDao.md5OfConfigFile(), is(not(staleMd5)));

    HttpLocalizedOperationResult result =
        service.updateEnvironment(
            "prod",
            environmentConfig("uat2"),
            new Username(new CaseInsensitiveString("foo")),
            staleMd5);

    assertThat(result.isSuccessful(), is(false));
    assertThat(
        result.message(localizer),
        is(
            "Failed to update environment 'prod'. "
                + ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH));
  }
Пример #7
0
  public void create(List<UserSearchModel> userSearchModels, HttpLocalizedOperationResult result) {
    if (userSearchModels.isEmpty()) {
      result.badRequest(LocalizedMessage.string("NO_USERS_SELECTED"));
      return;
    }
    synchronized (enableUserMutex) {
      for (UserSearchModel userSearchModel : userSearchModels) {
        User user = userSearchModel.getUser();

        if (userExists(user)) {
          result.conflict(
              LocalizedMessage.string(
                  "USER_ALREADY_EXISTS", user.getName(), user.getDisplayName(), user.getEmail()));
          return;
        }

        if (user.isAnonymous()) {
          result.badRequest(LocalizedMessage.string("USERNAME_NOT_PERMITTED", user.getName()));
          return;
        }

        if (!userSearchModel.getUserSourceType().equals(UserSourceType.PASSWORD_FILE)
            && validateEmailAndMatcher(result, user)) {
          return;
        }
        userDao.saveOrUpdate(user);
        result.setMessage(LocalizedMessage.string("USER_SUCCESSFULLY_ADDED", user.getName()));
      }
    }
  }
 @Test
 public void shouldNotConsiderNoMingleConfigAnError() {
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   MingleConfig mingleConfig =
       mingleConfigService.mingleConfigForPipelineNamed(
           "bar", new Username(new CaseInsensitiveString("admin")), result);
   assertThat(mingleConfig, is(nullValue()));
   assertThat(result.isSuccessful(), is(true));
 }
Пример #9
0
 @Test
 public void shouldReturnAClonedInstanceOfEnvironmentConfig() throws NoSuchEnvironmentException {
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   configHelper.addEnvironments("foo-env");
   assertThat(service.named("foo-env"), sameInstance(service.named("foo-env")));
   assertThat(
       service.named("foo-env"),
       not(sameInstance(service.forEdit("foo-env", result).getConfigElement())));
   assertThat(result.isSuccessful(), is(true));
 }
Пример #10
0
 public void deleteUser(String username, HttpLocalizedOperationResult result) {
   try {
     userDao.deleteUser(username);
     result.setMessage(LocalizedMessage.string("USER_DELETE_SUCCESSFUL", username));
   } catch (UserNotFoundException e) {
     result.notFound(
         LocalizedMessage.string("USER_NOT_FOUND", username),
         HealthStateType.general(HealthStateScope.GLOBAL));
   } catch (UserEnabledException e) {
     result.badRequest(LocalizedMessage.string("USER_NOT_DISABLED", username));
   }
 }
 @Test
 public void shouldNotAllowUnauthorizedUserToGetMingleConfig() {
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   MingleConfig mingleConfig =
       mingleConfigService.mingleConfigForPipelineNamed(
           "foo", new Username(new CaseInsensitiveString("some_loser")), result);
   assertThat(mingleConfig, is(nullValue()));
   assertThat(result.isSuccessful(), is(false));
   assertThat(
       result.message(localizer), is("You do not have view permissions for pipeline 'foo'."));
   assertThat(result.httpCode(), is(401));
 }
Пример #12
0
 @Test
 public void shouldReturnBadRequestForInvalidEnvName() {
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   service.createEnvironment(
       env(
           "foo env",
           new ArrayList<String>(),
           new ArrayList<Map<String, String>>(),
           new ArrayList<String>()),
       new Username(new CaseInsensitiveString("any")),
       result);
   assertThat(result.httpCode(), is(HttpServletResponse.SC_BAD_REQUEST));
   assertThat(result.message(localizer), containsString("Failed to add environment."));
 }
  @Test
  public void shouldCheckIfUserCanAccessAdminPagesWhileUpdatingPackageRepository()
      throws Exception {
    Username username = new Username(new CaseInsensitiveString("user"));
    when(securityService.canViewAdminPage(username)).thenReturn(false);

    UpdateConfigFromUI updateCommand =
        service.getPackageRepositoryUpdateCommand(new PackageRepository(), username);
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    updateCommand.checkPermission(GoConfigMother.configWithPipelines("sample"), result);

    assertThat(result.isSuccessful(), is(false));
    assertThat(result.httpCode(), is(401));
    verify(securityService).canViewAdminPage(username);
  }
  @Test
  public void shouldNotContinueIfTheUserDontHavePermissionsToOperateOnPackageRepositories()
      throws Exception {
    when(goConfigService.isUserAdmin(currentUser)).thenReturn(false);
    CreatePackageRepositoryCommand command =
        new CreatePackageRepositoryCommand(
            goConfigService, packageRepositoryService, packageRepository, currentUser, result);

    HttpLocalizedOperationResult expectedResult = new HttpLocalizedOperationResult();
    expectedResult.unauthorized(
        LocalizedMessage.string("UNAUTHORIZED_TO_EDIT"), HealthStateType.unauthorised());

    assertThat(command.canContinue(cruiseConfig), is(false));
    assertThat(result, is(expectedResult));
  }
Пример #15
0
 @Test
 public void shouldReturnTheCorrectLocalizedMessageForDuplicateEnvironment() {
   configHelper.addEnvironments("foo-env");
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   service.createEnvironment(
       env(
           "foo-env",
           new ArrayList<String>(),
           new ArrayList<Map<String, String>>(),
           new ArrayList<String>()),
       new Username(new CaseInsensitiveString("any")),
       result);
   assertThat(
       result.message(localizer),
       is("Failed to add environment. Environment 'foo-env' already exists."));
 }
Пример #16
0
 @Test
 public void shouldReturnTheCorrectLocalizedMessageWhenUserDoesNotHavePermissionToDelete()
     throws IOException, NoSuchEnvironmentException {
   configHelper.addEnvironments("foo");
   configHelper.turnOnSecurity();
   configHelper.addAdmins("super_hero");
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   service.deleteEnvironment(
       service.getEnvironmentConfig("foo"),
       new Username(new CaseInsensitiveString("evil_hacker")),
       result);
   assertThat(
       result.message(localizer),
       is(
           "Failed to delete environment 'foo'. User 'evil_hacker' does not have permission to update environments"));
 }
Пример #17
0
  @Test
  public void shouldDeleteAnEnvironment() throws Exception {
    String environmentName = "dev";
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    goConfigService.addEnvironment(
        new BasicEnvironmentConfig(new CaseInsensitiveString(environmentName)));

    assertTrue(goConfigService.hasEnvironmentNamed(new CaseInsensitiveString(environmentName)));
    service.deleteEnvironment(
        service.getEnvironmentConfig(environmentName),
        new Username(new CaseInsensitiveString("foo")),
        result);
    assertFalse(goConfigService.hasEnvironmentNamed(new CaseInsensitiveString(environmentName)));
    assertThat(
        result.message(localizer), containsString("Environment 'dev' was deleted successfully."));
  }
Пример #18
0
 @Test
 public void shouldReturnBadRequestForUpdateWhenUsingInvalidEnvName() {
   configHelper.addEnvironments("foo-env");
   HttpLocalizedOperationResult result =
       service.updateEnvironment(
           "foo-env",
           env(
               "foo env",
               new ArrayList<String>(),
               new ArrayList<Map<String, String>>(),
               new ArrayList<String>()),
           new Username(new CaseInsensitiveString("any")),
           goConfigDao.md5OfConfigFile());
   assertThat(result.httpCode(), is(HttpServletResponse.SC_BAD_REQUEST));
   assertThat(
       result.message(localizer), containsString("Failed to update environment 'foo-env'."));
 }
Пример #19
0
 private boolean validateEmailAndMatcher(HttpLocalizedOperationResult result, User user) {
   try {
     validate(user);
   } catch (ValidationException e) {
     result.badRequest(LocalizedMessage.string("USER_FIELD_VALIDATIONS_FAILED", e.getMessage()));
     return true;
   }
   return false;
 }
Пример #20
0
 @Test
 public void shouldReturnTheCorrectLocalizedMessageForNoPermission() throws IOException {
   configHelper.turnOnSecurity();
   configHelper.addAdmins("super_hero");
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   service.createEnvironment(
       env(
           "foo-env",
           new ArrayList<String>(),
           new ArrayList<Map<String, String>>(),
           new ArrayList<String>()),
       new Username(new CaseInsensitiveString("evil_hacker")),
       result);
   assertThat(
       result.message(localizer),
       is(
           "Failed to add environment. User 'evil_hacker' does not have permission to add environments"));
 }
Пример #21
0
 @Deprecated()
 public CruiseConfig loadCruiseConfigForEdit(
     Username username, HttpLocalizedOperationResult result) {
   if (!isUserAdmin(username) && !isUserTemplateAdmin(username)) {
     result.unauthorized(
         LocalizedMessage.string("UNAUTHORIZED_TO_ADMINISTER"), HealthStateType.unauthorised());
   }
   return clonedConfigForEdit();
 }
Пример #22
0
 private boolean isAuthorized() {
   if (!(goConfigService.isUserAdmin(username)
       || goConfigService.isGroupAdministrator(username.getUsername()))) {
     result.unauthorized(
         LocalizedMessage.string("UNAUTHORIZED_TO_EDIT"), HealthStateType.unauthorised());
     return false;
   }
   return true;
 }
Пример #23
0
 @Test
 public void
     shouldReturnBadRequestForUpdateWhenUsingInvalidEnvName_ForNewUpdateEnvironmentMethod_ForNewUpdateEnvironmentMethod()
         throws NoSuchEnvironmentException {
   configHelper.addEnvironments("foo-env");
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   service.updateEnvironment(
       service.getEnvironmentConfig("foo-env"),
       env(
           "foo env",
           new ArrayList<String>(),
           new ArrayList<Map<String, String>>(),
           new ArrayList<String>()),
       new Username(new CaseInsensitiveString("any")),
       result);
   assertThat(result.httpCode(), is(HttpServletResponse.SC_BAD_REQUEST));
   assertThat(
       result.message(localizer), containsString("Failed to update environment 'foo-env'."));
 }
Пример #24
0
 private boolean isAdminOfGroup(
     String toGroupName, Username username, HttpLocalizedOperationResult result) {
   if (!isUserAdminOfGroup(username.getUsername(), toGroupName)) {
     result.unauthorized(
         LocalizedMessage.string("UNAUTHORIZED_TO_EDIT_GROUP", toGroupName),
         HealthStateType.unauthorised());
     return false;
   }
   return true;
 }
Пример #25
0
 private boolean isValidGroup(
     String groupName, CruiseConfig cruiseConfig, HttpLocalizedOperationResult result) {
   if (!cruiseConfig.hasPipelineGroup(groupName)) {
     result.notFound(
         LocalizedMessage.string("PIPELINE_GROUP_NOT_FOUND", groupName),
         HealthStateType.general(HealthStateScope.forGroup(groupName)));
     return false;
   }
   return true;
 }
Пример #26
0
 @Test
 public void shouldReturnTheCorrectLocalizedMessageForUpdateWhenDuplicateEnvironmentExists() {
   configHelper.addEnvironments("foo-env");
   configHelper.addEnvironments("bar-env");
   HttpLocalizedOperationResult result =
       service.updateEnvironment(
           "bar-env",
           env(
               "foo-env",
               new ArrayList<String>(),
               new ArrayList<Map<String, String>>(),
               new ArrayList<String>()),
           new Username(new CaseInsensitiveString("any")),
           goConfigDao.md5OfConfigFile());
   assertThat(
       result.message(localizer),
       is(
           "Failed to update environment 'bar-env'. Duplicate unique value [foo-env] declared for identity constraint \"uniqueEnvironmentName\" of element \"environments\"."));
 }
Пример #27
0
 @Test
 public void shouldReturnTheCorrectLocalizedMessageWhenUserDoesNotHavePermissionToUpdate()
     throws IOException {
   configHelper.addEnvironments("foo");
   configHelper.turnOnSecurity();
   configHelper.addAdmins("super_hero");
   HttpLocalizedOperationResult result =
       service.updateEnvironment(
           "foo",
           env(
               "foo-env",
               new ArrayList<String>(),
               new ArrayList<Map<String, String>>(),
               new ArrayList<String>()),
           new Username(new CaseInsensitiveString("evil_hacker")),
           goConfigDao.md5OfConfigFile());
   assertThat(
       result.message(localizer),
       is(
           "Failed to update environment 'foo'. User 'evil_hacker' does not have permission to update environments"));
 }
Пример #28
0
 @Test
 public void
     shouldReturnTheCorrectLocalizedMessageForUpdateWhenDuplicateEnvironmentExists_ForNewUpdateEnvironmentMethod()
         throws NoSuchEnvironmentException {
   configHelper.addEnvironments("foo-env");
   configHelper.addEnvironments("bar-env");
   HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
   service.updateEnvironment(
       service.getEnvironmentConfig("bar-env"),
       env(
           "foo-env",
           new ArrayList<String>(),
           new ArrayList<Map<String, String>>(),
           new ArrayList<String>()),
       new Username(new CaseInsensitiveString("any")),
       result);
   assertThat(
       result.message(localizer),
       is(
           "Failed to update environment 'bar-env'. failed to save : Duplicate unique value [foo-env] declared for identity constraint \"uniqueEnvironmentName\" of element \"environments\"."));
 }
Пример #29
0
 @Override
 public boolean isValid(CruiseConfig preprocessedConfig) {
   PackageRepositories repositories = preprocessedConfig.getPackageRepositories();
   this.preprocessedRepository = repositories.find(this.repository.getRepoId());
   preprocessedRepository.validate(null);
   repositories.validate(null);
   boolean isValidConfiguration =
       packageRepositoryService.validatePluginId(preprocessedRepository)
           && packageRepositoryService.validateRepositoryConfiguration(preprocessedRepository);
   BasicCruiseConfig.copyErrors(preprocessedRepository, this.repository);
   return getAllErrors(this.repository).isEmpty() && isValidConfiguration && result.isSuccessful();
 }
  @Test
  public void shouldNotContinueIfRepoIdIsChanged() {
    when(goConfigService.isUserAdmin(currentUser)).thenReturn(true);
    when(goConfigService.getPackageRepository(repoId)).thenReturn(oldPackageRepo);
    when(entityHashingService.md5ForEntity(oldPackageRepo)).thenReturn("md5");
    HttpLocalizedOperationResult expectResult = new HttpLocalizedOperationResult();
    expectResult.unprocessableEntity(
        LocalizedMessage.string("PACKAGE_REPOSITORY_ID_CHANGED", "repository"));

    UpdatePackageRepositoryCommand command =
        new UpdatePackageRepositoryCommand(
            goConfigService,
            packageRepositoryService,
            newPackageRepo,
            currentUser,
            "md5",
            entityHashingService,
            result,
            "old-repo-id");

    assertThat(command.canContinue(cruiseConfig), is(false));
    assertThat(result, is(expectResult));
  }