private boolean isAuthorized() {
   if (!(goConfigService.isUserAdmin(username)
       || goConfigService.isGroupAdministrator(username.getUsername()))) {
     result.unauthorized(
         LocalizedMessage.string("UNAUTHORIZED_TO_EDIT"), HealthStateType.unauthorised());
     return false;
   }
   return true;
 }
Beispiel #2
0
 private boolean doesPipelineExist(String pipelineName, LocalizedOperationResult result) {
   if (!getCurrentConfig().hasPipelineNamed(new CaseInsensitiveString(pipelineName))) {
     result.notFound(
         LocalizedMessage.string("RESOURCE_NOT_FOUND", "pipeline", pipelineName),
         HealthStateType.general(HealthStateScope.forPipeline(pipelineName)));
     return false;
   }
   return true;
 }
Beispiel #3
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();
 }
Beispiel #4
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;
 }
Beispiel #5
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;
 }
Beispiel #6
0
 @Override
 public boolean canContinue(CruiseConfig cruiseConfig) {
   if (goConfigService.groups().hasGroup(groupName)
       && !goConfigService.isUserAdminOfGroup(currentUser.getUsername(), groupName)) {
     result.unauthorized(
         LocalizedMessage.string("UNAUTHORIZED_TO_EDIT_GROUP", groupName),
         HealthStateType.unauthorised());
     return false;
   }
   return true;
 }
Beispiel #7
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));
   }
 }
Beispiel #8
0
 public boolean canEditPipeline(
     String pipelineName, Username username, LocalizedOperationResult result, String groupName) {
   if (!doesPipelineExist(pipelineName, result)) {
     return false;
   }
   if (!isUserAdminOfGroup(username.getUsername(), groupName)) {
     result.unauthorized(
         LocalizedMessage.string("UNAUTHORIZED_TO_EDIT_PIPELINE", pipelineName),
         HealthStateType.unauthorisedForPipeline(pipelineName));
     return false;
   }
   return true;
 }
  @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));
  }
Beispiel #10
0
  @Test
  public void shouldReturnNotFoundIfTheMaterialDoesNotBelongToTheGivenPipeline() {
    when(securityService.hasViewPermissionForPipeline("pavan", "pipeline")).thenReturn(true);
    LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class);

    when(goConfigService.materialForPipelineWithFingerprint("pipeline", "sha"))
        .thenThrow(new RuntimeException("Not found"));

    materialService.searchRevisions(
        "pipeline", "sha", "23", new Username(new CaseInsensitiveString("pavan")), operationResult);
    verify(operationResult)
        .notFound(
            LocalizedMessage.materialWithFingerPrintNotFound("pipeline", "sha"),
            HealthStateType.general(HealthStateScope.forPipeline("pipeline")));
  }
Beispiel #11
0
 @Test
 public void shouldNotBeAuthorizedToViewAPipeline() {
   when(securityService.hasViewPermissionForPipeline("pavan", "pipeline")).thenReturn(false);
   LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class);
   materialService.searchRevisions(
       "pipeline",
       "sha",
       "search-string",
       new Username(new CaseInsensitiveString("pavan")),
       operationResult);
   verify(operationResult)
       .unauthorized(
           LocalizedMessage.cannotViewPipeline("pipeline"),
           HealthStateType.general(HealthStateScope.forPipeline("pipeline")));
 }
 @Test
 public void shouldThrowExceptionWhenADuplicateAgentTriesToUpdateStatus() throws Exception {
   AgentRuntimeInfo runtimeInfo =
       new AgentRuntimeInfo(
           agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), null, null);
   runtimeInfo.setCookie("invalid_cookie");
   AgentInstance original =
       AgentInstance.createFromLiveAgent(
           new AgentRuntimeInfo(
               agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), null, null),
           new SystemEnvironment());
   try {
     when(agentService.findAgentAndRefreshStatus(runtimeInfo.getUUId())).thenReturn(original);
     agentService.updateRuntimeInfo(runtimeInfo);
     fail("should throw exception when cookie mismatched");
   } catch (Exception e) {
     assertThat(
         e.getMessage(),
         is(format("Agent [%s] has invalid cookie", runtimeInfo.agentInfoDebugString())));
     assertThat(
         Arrays.asList(logFixture.getMessages()),
         hasItem(
             format(
                 "Found agent [%s] with duplicate uuid. Please check the agent installation.",
                 runtimeInfo.agentInfoDebugString())));
     verify(serverHealthService)
         .update(
             ServerHealthState.warning(
                 format(
                     "[%s] has duplicate unique identifier which conflicts with [%s]",
                     runtimeInfo.agentInfoForDisplay(), original.agentInfoForDisplay()),
                 "Please check the agent installation. Click <a href='http://www.go.cd/documentation/user/current/faq/agent_guid_issue.html' target='_blank'>here</a> for more info.",
                 HealthStateType.duplicateAgent(
                     HealthStateScope.forAgent(runtimeInfo.getCookie())),
                 Timeout.THIRTY_SECONDS));
   }
   verify(agentInstances).findAgentAndRefreshStatus(runtimeInfo.getUUId());
   verifyNoMoreInteractions(agentInstances);
 }
  @Test
  public void shouldSetAServerHealthMessageWhenMaterialForPipelineWithBuildCauseIsNotFound()
      throws IllegalArtifactLocationException, IOException {
    PipelineConfig pipelineConfig =
        PipelineConfigMother.pipelineConfig(
            "last",
            new StageConfig(
                new CaseInsensitiveString("stage"), new JobConfigs(new JobConfig("job-one"))));
    pipelineConfig.materialConfigs().clear();
    SvnMaterialConfig onDirOne =
        MaterialConfigsMother.svnMaterialConfig(
            "google.com", "dirOne", "loser", "boozer", false, "**/*.html");
    final P4MaterialConfig onDirTwo =
        MaterialConfigsMother.p4MaterialConfig(
            "host:987654321", "zoozer", "secret", "through-the-window", true);
    onDirTwo.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, "dirTwo"));
    pipelineConfig.addMaterialConfig(onDirOne);
    pipelineConfig.addMaterialConfig(onDirTwo);

    configHelper.addPipeline(pipelineConfig);

    Pipeline building = PipelineMother.building(pipelineConfig);
    final Pipeline pipeline = dbHelper.savePipelineWithMaterials(building);

    CruiseConfig cruiseConfig = configHelper.currentConfig();
    PipelineConfig cfg = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("last"));
    cfg.removeMaterialConfig(cfg.materialConfigs().get(1));
    configHelper.writeConfigFile(cruiseConfig);

    assertThat(
        serverHealthService.filterByScope(HealthStateScope.forPipeline("last")).size(), is(0));

    final long jobId = pipeline.getStages().get(0).getJobInstances().get(0).getId();

    Date currentTime = new Date(System.currentTimeMillis() - 1);
    Pipeline loadedPipeline =
        (Pipeline)
            transactionTemplate.execute(
                new TransactionCallback() {
                  public Object doInTransaction(TransactionStatus status) {
                    Pipeline loadedPipeline = null;
                    try {
                      loadedPipeline = loader.pipelineWithPasswordAwareBuildCauseByBuildId(jobId);
                      fail(
                          "should not have loaded pipeline with build-cause as one of the necessary materials was not found");
                    } catch (Exception e) {
                      assertThat(e, is(instanceOf(StaleMaterialsOnBuildCause.class)));
                      assertThat(
                          e.getMessage(),
                          is(
                              "Cannot load job 'last/"
                                  + pipeline.getCounter()
                                  + "/stage/1/job-one' because material "
                                  + onDirTwo
                                  + " was not found in config."));
                    }
                    return loadedPipeline;
                  }
                });

    assertThat(loadedPipeline, is(nullValue()));

    JobInstance reloadedJobInstance = jobInstanceService.buildById(jobId);
    assertThat(reloadedJobInstance.getState(), is(JobState.Completed));
    assertThat(reloadedJobInstance.getResult(), is(JobResult.Failed));

    assertThat(
        serverHealthService
            .filterByScope(HealthStateScope.forJob("last", "stage", "job-one"))
            .size(),
        is(1));
    ServerHealthState error =
        serverHealthService
            .filterByScope(HealthStateScope.forJob("last", "stage", "job-one"))
            .get(0);
    assertThat(
        error,
        is(
            ServerHealthState.error(
                "Cannot load job 'last/"
                    + pipeline.getCounter()
                    + "/stage/1/job-one' because material "
                    + onDirTwo
                    + " was not found in config.",
                "Job for pipeline 'last/"
                    + pipeline.getCounter()
                    + "/stage/1/job-one' has been failed as one or more material configurations were either changed or removed.",
                HealthStateType.general(HealthStateScope.forJob("last", "stage", "job-one")))));
    DateTime expiryTime = (DateTime) ReflectionUtil.getField(error, "expiryTime");
    assertThat(expiryTime.toDate().after(currentTime), is(true));
    assertThat(
        expiryTime.toDate().before(new Date(System.currentTimeMillis() + 5 * 60 * 1000 + 1)),
        is(true));

    String logText =
        FileUtil.readToEnd(consoleService.findConsoleArtifact(reloadedJobInstance.getIdentifier()));
    assertThat(
        logText,
        containsString(
            "Cannot load job 'last/"
                + pipeline.getCounter()
                + "/stage/1/job-one' because material "
                + onDirTwo
                + " was not found in config."));
    assertThat(
        logText,
        containsString(
            "Job for pipeline 'last/"
                + pipeline.getCounter()
                + "/stage/1/job-one' has been failed as one or more material configurations were either changed or removed."));
  }