/** Associates the OpenID identity of the user with {@link #realm}. */
  private void associateUserWithOpenId(User u) throws Exception {
    WebClient wc = new WebClient().login(u.getId(), u.getId() /*assumes password==name*/);

    // Associate an OpenID with an existing user
    HtmlPage associated =
        wc.goTo("federatedLoginService/openid/startAssociate?openid=" + openid.url);
    assertTrue(
        associated.getDocumentURI().endsWith("federatedLoginService/openid/onAssociationSuccess"));
    OpenIdUserProperty p = u.getProperty(OpenIdUserProperty.class);
    assertEquals(1, p.getIdentifiers().size());
    assertEquals(openid.getUserIdentity(), p.getIdentifiers().iterator().next());
  }
  @Override
  public String findMailAddressFor(User u) {
    String username = u.getId();

    for (JiraSite site : JiraProjectProperty.DESCRIPTOR.getSites()) {
      try {
        JiraSession session = site.createSession();
        if (session != null) {
          RemoteUser user = session.service.getUser(session.token, username);
          if (user != null) {
            String email = user.getEmail();
            if (email != null) {
              email = unmaskEmail(email);
              return email;
            }
          }
        }
      } catch (IOException ex) {
        LOGGER.log(Level.WARNING, "Unable to create session with " + site.getName(), ex);
      } catch (ServiceException ex) {
        LOGGER.log(Level.WARNING, "Unable to create session with " + site.getName(), ex);
      }
    }
    return null;
  }
Example #3
0
 @Override
 protected synchronized JSON data() {
   JSONArray r = new JSONArray();
   for (User u : modified) {
     UserInfo i = users.get(u);
     JSONObject entry =
         new JSONObject()
             .accumulate("id", u.getId())
             .accumulate("fullName", u.getFullName())
             .accumulate("url", u.getUrl())
             .accumulate(
                 "avatar",
                 i.avatar != null
                     ? i.avatar
                     : Stapler.getCurrentRequest().getContextPath()
                         + Functions.getResourcePath()
                         + "/images/"
                         + iconSize
                         + "/user.png")
             .accumulate("timeSortKey", i.getTimeSortKey())
             .accumulate("lastChangeTimeString", i.getLastChangeTimeString());
     AbstractProject<?, ?> p = i.getProject();
     if (p != null) {
       entry
           .accumulate("projectUrl", p.getUrl())
           .accumulate("projectFullDisplayName", p.getFullDisplayName());
     }
     r.add(entry);
   }
   modified.clear();
   return r;
 }
  @Before
  public void setup() throws Throwable {
    // Instantiating ScmSyncConfigurationPlugin instance
    ScmSyncConfigurationPlugin scmSyncConfigPluginInstance = new ScmSyncConfigurationPlugin();

    // Mocking PluginWrapper attached to current ScmSyncConfigurationPlugin instance
    PluginWrapper pluginWrapper = PowerMockito.mock(PluginWrapper.class);
    when(pluginWrapper.getShortName()).thenReturn("scm-sync-configuration");
    // Setting field on current plugin instance
    Field wrapperField = Plugin.class.getDeclaredField("wrapper");
    boolean wrapperFieldAccessibility = wrapperField.isAccessible();
    wrapperField.setAccessible(true);
    wrapperField.set(scmSyncConfigPluginInstance, pluginWrapper);
    wrapperField.setAccessible(wrapperFieldAccessibility);

    // Mocking Hudson root directory
    currentTestDirectory = createTmpDirectory("SCMSyncConfigTestsRoot");
    currentHudsonRootDirectory =
        new File(currentTestDirectory.getAbsolutePath() + "/hudsonRootDir/");
    if (!(currentHudsonRootDirectory.mkdir())) {
      throw new IOException(
          "Could not create hudson root directory: "
              + currentHudsonRootDirectory.getAbsolutePath());
    }
    FileUtils.copyDirectoryStructure(
        new ClassPathResource(getHudsonRootBaseTemplate()).getFile(), currentHudsonRootDirectory);

    // EnvVars env = Computer.currentComputer().getEnvironment();
    // env.put("HUDSON_HOME", tmpHudsonRoot.getPath() );

    // Creating local SVN repository...
    curentLocalSvnRepository = new File(currentTestDirectory.getAbsolutePath() + "/svnLocalRepo/");
    if (!(curentLocalSvnRepository.mkdir())) {
      throw new IOException(
          "Could not create SVN local repo directory: "
              + curentLocalSvnRepository.getAbsolutePath());
    }
    FileUtils.copyDirectoryStructure(
        new ClassPathResource("svnEmptyRepository").getFile(), curentLocalSvnRepository);

    // Mocking user
    User mockedUser = Mockito.mock(User.class);
    when(mockedUser.getId()).thenReturn("fcamblor");

    // Mocking Hudson singleton instance ...
    // Warning : this line will only work on Objenesis supported VMs :
    // http://code.google.com/p/objenesis/wiki/ListOfCurrentlySupportedVMs
    Hudson hudsonMockedInstance =
        spy((Hudson) new ObjenesisStd().getInstantiatorOf(Hudson.class).newInstance());
    PowerMockito.doReturn(currentHudsonRootDirectory).when(hudsonMockedInstance).getRootDir();
    PowerMockito.doReturn(mockedUser).when(hudsonMockedInstance).getMe();
    PowerMockito.doReturn(scmSyncConfigPluginInstance)
        .when(hudsonMockedInstance)
        .getPlugin(ScmSyncConfigurationPlugin.class);

    PowerMockito.mockStatic(Hudson.class);
    PowerMockito.doReturn(hudsonMockedInstance).when(Hudson.class);
    Hudson.getInstance();
    // when(Hudson.getInstance()).thenReturn(hudsonMockedInstance);
  }
 /**
  * Try to make this user a super-user
  */
 private void tryToMakeAdmin(User u) {
     AuthorizationStrategy as = Jenkins.getInstance().getAuthorizationStrategy();
     if (as instanceof GlobalMatrixAuthorizationStrategy) {
         GlobalMatrixAuthorizationStrategy ma = (GlobalMatrixAuthorizationStrategy) as;
         ma.add(Jenkins.ADMINISTER,u.getId());
     }
 }
 /**
  * Check if User is an owner.
  *
  * @param user User to be checked
  * @param acceptCoowners Check if user belongs to co-owners
  * @return true if User belongs to primary owners (and/or co-owners)
  */
 public boolean isOwner(User user, boolean acceptCoowners) {
   if (user == null) {
     return false;
   }
   if (isPrimaryOwner(user)) {
     return true;
   }
   return acceptCoowners ? coownersIds.contains(user.getId()) : false;
 }
    /**
     * Lets the current user silently login as the given user and report back accordingly.
     */
    private void loginAndTakeBack(StaplerRequest req, StaplerResponse rsp, User u) throws ServletException, IOException {
        // ... and let him login
        Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1"));
        a = this.getSecurityComponents().manager.authenticate(a);
        SecurityContextHolder.getContext().setAuthentication(a);

        // then back to top
        req.getView(this,"success.jelly").forward(req,rsp);
    }
  /**
   * Try to resolve email address using resolvers.
   *
   * @return User address or null if resolution failed
   */
  public static String resolve(User u) {
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Resolving e-mail address for \"" + u + "\" ID=" + u.getId());
    }

    for (MailAddressResolver r : all()) {
      String email = r.findMailAddressFor(u);
      if (email != null) {
        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.fine(r + " resolved " + u.getId() + " to " + email);
        }
        return email;
      }
    }

    // fall back logic
    return resolveFast(u);
  }
  private void validateUserPropertyAddress(String address, String username, String suffix)
      throws Exception {

    PowerMockito.when(descriptor.getDefaultSuffix()).thenReturn(suffix);

    PowerMockito.when(user.getFullName()).thenReturn(username);
    PowerMockito.when(user.getId()).thenReturn(username.replace('\\', '_'));

    String a = new UserPropertyMock(user, null).getConfiguredAddress();
    assertEquals(address, a);
  }
  /** Lets the current user silently login as the given user and report back accordingly. */
  @SuppressWarnings("ACL.impersonate")
  private void loginAndTakeBack(StaplerRequest req, StaplerResponse rsp, User u)
      throws ServletException, IOException {
    // ... and let him login
    Authentication a = new WwpassAuthenticationToken(u.getId());
    a = this.getSecurityComponents().manager.authenticate(a);
    SecurityContextHolder.getContext().setAuthentication(a);

    // then back to top
    req.getView(this, "success.jelly").forward(req, rsp);
  }
  /**
   * Try to resolve user email address fast enough to be used from UI
   *
   * <p>This implementation does not trigger {@link MailAddressResolver} extension point.
   *
   * @return User address or null if resolution failed
   */
  public static String resolveFast(User u) {

    String extractedAddress = extractAddressFromId(u.getFullName());
    if (extractedAddress != null) return extractedAddress;

    if (u.getFullName().contains("@"))
      // this already looks like an e-mail ID
      return u.getFullName();

    String ds = Mailer.descriptor().getDefaultSuffix();
    if (ds != null) {
      // another common pattern is "DOMAIN\person" in Windows. Only
      // do this when this full name is not manually set. see HUDSON-5164
      Matcher m = WINDOWS_DOMAIN_REGEXP.matcher(u.getFullName());
      if (m.matches() && u.getFullName().replace('\\', '_').equals(u.getId()))
        return m.group(1) + ds; // user+defaultSuffix

      return u.getId() + ds;
    }

    return null;
  }
  @Before
  public void setUp() throws Exception {

    jenkins = PowerMockito.mock(Hudson.class);

    user = PowerMockito.mock(User.class);
    when(user.getFullName()).thenReturn("Full name");
    when(user.getId()).thenReturn("user_id");

    PowerMockito.spy(Mailer.class);
    descriptor = PowerMockito.mock(Mailer.DescriptorImpl.class);
    PowerMockito.doReturn(descriptor).when(Mailer.class, "descriptor");
  }
Example #13
0
  private void populateChangeEntry(String runId, ChangeLogSet.Entry changeSetItem) {
    String commitId = changeSetItem.getCommitId();
    if (commitId != null) {
      put("revision", commitId, runId);
    }

    User committer = changeSetItem.getAuthor();
    if (committer != null) {
      put("committerId", committer.getId(), runId);
      put("committerName", committer.getFullName(), runId);
    }

    // TODO: Branch
  }
  /** Try to make this user a super-user */
  private void tryToMakeAdmin(User u) throws IOException {
    WwpassIdentity p = u.getProperty(WwpassIdentity.class);
    p.activate();
    u.save();
    AuthorizationStrategy as = Jenkins.getInstance().getAuthorizationStrategy();

    for (PermissionAdder adder : Jenkins.getInstance().getExtensionList(PermissionAdder.class)) {
      if (adder.add(as, u, Jenkins.ADMINISTER)) {
        return;
      }
    }
    LOGGER.severe(
        "Admin permission wasn't added for user: "******", ID: " + u.getId());
  }
Example #15
0
    public final void post(BuildListener listener) throws Exception {
      try {
        post2(listener);

        if (result.isBetterOrEqualTo(Result.UNSTABLE)) createSymlink(listener, "lastSuccessful");

        if (result.isBetterOrEqualTo(Result.SUCCESS)) createSymlink(listener, "lastStable");
      } finally {
        // update the culprit list
        HashSet<String> r = new HashSet<String>();
        for (User u : getCulprits()) r.add(u.getId());
        culprits = r;
        CheckPoint.CULPRITS_DETERMINED.report();
      }
    }
Example #16
0
    public final void post(BuildListener listener) throws Exception {
      try {
        post2(listener);
        // Resolve issue with invalid symlinks for maven (see
        // http://issues.hudson-ci.org/browse/HUDSON-8340)
        if (getResult().isBetterOrEqualTo(Result.UNSTABLE))
          createSymlink(listener, "lastSuccessful");

        if (getResult().isBetterOrEqualTo(Result.SUCCESS)) createSymlink(listener, "lastStable");
      } finally {
        // update the culprit list
        HashSet<String> r = new HashSet<String>();
        for (User u : getCulprits()) r.add(u.getId());
        culprits = r;
        CheckPoint.CULPRITS_DETERMINED.report();
      }
    }
Example #17
0
  /**
   * Tests {@link Team#doImportViewsSubmit(String, org.kohsuke.stapler.StaplerRequest,
   * org.kohsuke.stapler.StaplerResponse)}.
   *
   * @throws Exception if so
   */
  public void testDoImportViewsSubmit() throws Exception {
    FreeStyleProject p = createFreeStyleProject();
    User user = User.get("bob", true);
    MyViewsProperty property = user.getProperty(MyViewsProperty.class);
    ListView view1 = new ListView("view1");
    view1.add(p);
    property.addView(view1);
    ListView view2 = new ListView("view2");
    property.addView(view2);
    user.save();

    PluginImpl.getInstance().addTeam(new Team("Team1", "Description"));
    Team team = PluginImpl.getInstance().getTeams().get("Team1");
    StaplerRequest request = mock(StaplerRequest.class);
    StaplerResponse response = mock(StaplerResponse.class);

    team.doImportViewsSubmit(user.getId(), request, response);

    verify(response).sendRedirect2(Matchers.contains(team.getUrl()));

    TeamViewsProperty views = team.getProperty(TeamViewsProperty.class);
    Collection<View> collection = views.getViews();
    assertEquals(3, collection.size());

    boolean found1 = false;
    boolean found2 = false;
    for (View next : collection) {
      if (next.getViewName().equals("view1")) {
        found1 = true;
        assertNotSame(view1, next);
        assertEquals(1, next.getItems().size());
      } else if (next.getViewName().equals("view2")) {
        found2 = true;
        assertNotSame(view2, next);
      }
    }
    assertTrue(found1);
    assertTrue(found2);
  }
Example #18
0
  public Slave(
      @Nonnull String name,
      String nodeDescription,
      String remoteFS,
      int numExecutors,
      Mode mode,
      String labelString,
      ComputerLauncher launcher,
      RetentionStrategy retentionStrategy,
      List<? extends NodeProperty<?>> nodeProperties)
      throws FormException, IOException {
    this.name = name;
    this.description = nodeDescription;
    this.numExecutors = numExecutors;
    this.mode = mode;
    this.remoteFS = Util.fixNull(remoteFS).trim();
    this.label = Util.fixNull(labelString).trim();
    this.launcher = launcher;
    this.retentionStrategy = retentionStrategy;
    getAssignedLabels(); // compute labels now

    this.nodeProperties.replaceBy(nodeProperties);
    Slave node = (Slave) Jenkins.getInstance().getNode(name);

    if (node != null) {
      this.userId = node.getUserId(); // slave has already existed
    } else {
      User user = User.current();
      userId = user != null ? user.getId() : "anonymous";
    }
    if (name.equals("")) throw new FormException(Messages.Slave_InvalidConfig_NoName(), null);

    //        if (remoteFS.equals(""))
    //            throw new FormException(Messages.Slave_InvalidConfig_NoRemoteDir(name), null);

    if (this.numExecutors <= 0)
      throw new FormException(Messages.Slave_InvalidConfig_Executors(name), null);
  }
 protected String getAuthor() {
   final User user = entry.getAuthor();
   return (user == null) ? UNKNOWN_AUTHOR : user.getId();
 }
Example #20
0
 public int compare(User arg0, User arg1) {
   return arg0.getId().compareToIgnoreCase(arg1.getId());
 }
  public BuildDTO convert(final AbstractBuild<?, ?> source) {
    assert source != null;

    log.trace("Converting: {}", source);

    BuildDTO target = new BuildDTO();
    target.setType(source.getClass().getName());
    target.setUrl(String.format("%s/%s", this.systemService.getUrl(), source.getUrl()));
    target.setId(source.getId());
    target.setNumber(source.getNumber());
    target.setDescription(source.getDescription());
    target.setProjectName(source.getProject().getFullName());
    target.setDuration(source.getDuration());
    target.setTimeStamp(source.getTimestamp().getTimeInMillis());

    if (source.getResult() != null) {
      target.setResult(convert(source.getResult()));
    }

    if (source.hasntStartedYet()) {
      target.setState(BuildStateDTO.NOT_STARTED);
    } else if (source.isBuilding()) {
      target.setState(BuildStateDTO.BUILDING);
    } else if (source.isLogUpdated()) {
      target.setState(BuildStateDTO.POST_PRODUCTION);
    } else {
      target.setState(BuildStateDTO.COMPLETED);
    }

    // This is really more of a set, though I don't know how to make XJC
    // generate a Set<String>
    List<String> culprits = target.getCulprits();
    for (User user : source.getCulprits()) {
      String uid = user.getId();
      if (!culprits.contains(uid)) {
        culprits.add(uid);
      }
    }

    // This is really more of a set, though I don't know how to make XJC
    // generate a Set<String>
    List<String> participants = target.getParticipants();
    for (ChangeLogSet.Entry entry : source.getChangeSet()) {
      String uid = entry.getAuthor().getId();
      if (!participants.contains(uid)) {
        participants.add(uid);
      }
    }

    target.setKept(source.isKeepLog());
    target.getCauses().addAll(causex.convert(source.getCauses()));

    // XXX: source.getChangeSet() is currently guaranteed non-null, else
    // the loop above will throw a NullPointerException
    target.setChangesAvailable(
        source.getChangeSet() != null && !source.getChangeSet().isEmptySet());
    target.setTestsAvailable(
        source.getTestResultAction() != null && source.getTestResultAction().getTotalCount() != 0);

    return target;
  }