@Test
  @PresetData(PresetData.DataSet.NO_ANONYMOUS_READACCESS)
  public void testRunnableAgainstAllContexts() throws Exception {
    Runnable r =
        new Runnable() {
          public void run() {
            runnableThreadContext = SecurityContextHolder.getContext();
          }
        };
    SecurityContextHolder.setContext(systemContext);
    Future systemResult = wrappedService.submit(r);
    // Assert the runnable completed successfully
    assertNull(systemResult.get());
    // Assert the context inside the runnable thread was set to ACL.SYSTEM
    assertEquals(systemContext, runnableThreadContext);

    SecurityContextHolder.setContext(userContext);
    Future userResult = wrappedService.submit(r);
    // Assert the runnable completed successfully
    assertNull(userResult.get());
    // Assert the context inside the runnable thread was set to the user's context
    assertEquals(userContext, runnableThreadContext);

    SecurityContextHolder.setContext(nullContext);
    Future nullResult = wrappedService.submit(r);
    // Assert the runnable completed successfully
    assertNull(nullResult.get());
    // Assert the context inside the runnable thread was set to the null context
    assertEquals(nullContext, runnableThreadContext);
  }
  private void handlePullRequestEvent(String payload) throws IOException {

    GitHub gitHub = createGitHub(JSONObject.fromObject(payload));

    if (gitHub == null) {
      return;
    }

    GHEventPayload.PullRequest pullRequest =
        gitHub.parseEventPayload(new StringReader(payload), GHEventPayload.PullRequest.class);

    if (SUPPORTED_EVENTS.contains(pullRequest.getAction())) {
      Authentication old = SecurityContextHolder.getContext().getAuthentication();
      SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
      try {
        for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
          PullRequestBuildTrigger trigger = job.getTrigger(PullRequestBuildTrigger.class);
          if (trigger != null && trigger.getBuildHandler() instanceof PullRequestBuildHandler) {
            ((PullRequestBuildHandler) trigger.getBuildHandler()).handle(pullRequest, gitHub);
          }
        }
      } finally {
        SecurityContextHolder.getContext().setAuthentication(old);
      }
    } else {
      LOGGER.warning(
          MessageFormat.format(
              "Unsupported pull request action: ''{0}''", pullRequest.getAction()));
    }
  }
  @Test
  @PresetData(PresetData.DataSet.NO_ANONYMOUS_READACCESS)
  public void testFailedRunnableResetsContext() throws Exception {
    Runnable r =
        new Runnable() {
          public void run() {
            SecurityContextHolder.setContext(nullContext);
            throw new RuntimeException("Simulate a failure");
          }
        };

    SecurityContextHolder.setContext(systemContext);
    try {
      wrappedService.execute(r);
    } catch (AssertionError expectedException) {
      // Assert the current context is once again ACL.SYSTEM
      assertEquals(systemContext, SecurityContextHolder.getContext());
    }

    SecurityContextHolder.setContext(userContext);
    try {
      wrappedService.execute(r);
    } catch (AssertionError expectedException) {
      // Assert the current context is once again the userContext
      assertEquals(userContext, SecurityContextHolder.getContext());
    }
  }
Exemplo n.º 4
0
  public void generateMergeRequestBuild(
      String json, Job project, StaplerRequest req, StaplerResponse rsp) {
    GitLabMergeRequest request = GitLabMergeRequest.create(json);
    if ("closed".equals(request.getObjectAttribute().getState())) {
      LOGGER.log(Level.INFO, "Closed Merge Request, no build started");
      return;
    }
    if ("merged".equals(request.getObjectAttribute().getState())) {
      LOGGER.log(Level.INFO, "Accepted Merge Request, no build started");
      return;
    }
    if ("update".equals(request.getObjectAttribute().getAction())) {
      LOGGER.log(
          Level.INFO,
          "Existing Merge Request, build will be trigged by buildOpenMergeRequests instead");
      return;
    }
    if (request.getObjectAttribute().getLastCommit() != null) {
      Run mergeBuild =
          getBuildBySHA1(project, request.getObjectAttribute().getLastCommit().getId(), true);
      if (mergeBuild != null) {
        LOGGER.log(
            Level.INFO,
            "Last commit in Merge Request has already been built in build #" + mergeBuild.getId());
        return;
      }
    }
    if (request.getObjectAttribute().getDescription().contains("[ci-skip]")) {
      LOGGER.log(
          Level.INFO,
          "Skipping MR " + request.getObjectAttribute().getTitle() + " due to ci-skip.");
      return;
    }

    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    try {
      GitLabPushTrigger trigger = null;
      if (project instanceof ParameterizedJobMixIn.ParameterizedJob) {
        ParameterizedJobMixIn.ParameterizedJob p = (ParameterizedJobMixIn.ParameterizedJob) project;
        for (Trigger t : p.getTriggers().values()) {
          if (t instanceof GitLabPushTrigger) {
            trigger = (GitLabPushTrigger) t;
          }
        }
      }
      if (trigger == null) {
        return;
      }
      trigger.onPost(request);
    } finally {
      SecurityContextHolder.getContext().setAuthentication(old);
    }
  }
Exemplo n.º 5
0
  public UMOSecurityContext create(UMOAuthentication authentication) {
    SecurityContext context = new SecurityContextImpl();
    context.setAuthentication(((AcegiAuthenticationAdapter) authentication).getDelegate());

    if (authentication.getProperties() != null) {
      if ((authentication.getProperties().containsKey("securityMode"))) {
        SecurityContextHolder.setStrategyName(
            (String) authentication.getProperties().get("securityMode"));
      }
    }
    SecurityContextHolder.setContext(context);
    return new AcegiSecurityContext(context);
  }
Exemplo n.º 6
0
    @Override
    public List<GitStatus.ResponseContributor> onNotifyCommit(URIish uri, String... branches) {
      List<GitStatus.ResponseContributor> result = new ArrayList<GitStatus.ResponseContributor>();
      boolean notified = false;
      // run in high privilege to see all the projects anonymous users don't see.
      // this is safe because when we actually schedule a build, it's a build that can
      // happen at some random time anyway.
      Authentication old = SecurityContextHolder.getContext().getAuthentication();
      SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
      try {
        for (final SCMSourceOwner owner : SCMSourceOwners.all()) {
          for (SCMSource source : owner.getSCMSources()) {
            if (source instanceof GitSCMSource) {
              GitSCMSource git = (GitSCMSource) source;
              URIish remote;
              try {
                remote = new URIish(git.getRemote());
              } catch (URISyntaxException e) {
                // ignore
                continue;
              }
              if (GitStatus.looselyMatches(uri, remote)) {
                LOGGER.info("Triggering the indexing of " + owner.getFullDisplayName());
                owner.onSCMSourceUpdated(source);
                result.add(
                    new GitStatus.ResponseContributor() {
                      @Override
                      public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
                        rsp.addHeader("Triggered", owner.getAbsoluteUrl());
                      }

                      @Override
                      public void writeBody(PrintWriter w) {
                        w.println("Scheduled indexing of " + owner.getFullDisplayName());
                      }
                    });
                notified = true;
              }
            }
          }
        }
      } finally {
        SecurityContextHolder.getContext().setAuthentication(old);
      }
      if (!notified) {
        result.add(
            new GitStatus.MessageResponseContributor("No git consumers for URI " + uri.toString()));
      }
      return result;
    }
 /**
  * Test that a user is prevented from bypassing permissions on other jobs when configuring a
  * copyartifact build step.
  */
 @LocalData
 public void testPermission() throws Exception {
   SecurityContextHolder.clearContext();
   assertNull("Job should not be accessible to anonymous", hudson.getItem("testJob"));
   assertEquals(
       "Should ignore/clear value for inaccessible project",
       "",
       new CopyArtifact("testJob", null, null, null, false, false).getProjectName());
   // Login as user with access to testJob:
   SecurityContextHolder.getContext()
       .setAuthentication(new UsernamePasswordAuthenticationToken("joe", "joe"));
   assertEquals(
       "Should allow use of testJob for joe",
       "testJob",
       new CopyArtifact("testJob", null, null, null, false, false).getProjectName());
 }
  /** This is where the user comes back to at the end of the OpenID redirect ping-pong. */
  public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {

    String code = request.getParameter("code");

    if (code == null || code.trim().length() == 0) {
      Log.info("doFinishLogin: missing code.");
      return HttpResponses.redirectToContextRoot();
    }

    Log.info("test");

    HttpPost httpost =
        new HttpPost(
            githubUri
                + "/login/oauth/access_token?"
                + "client_id="
                + clientID
                + "&"
                + "client_secret="
                + clientSecret
                + "&"
                + "code="
                + code);

    DefaultHttpClient httpclient = new DefaultHttpClient();

    org.apache.http.HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();

    String accessToken = extractToken(content);

    if (accessToken != null && accessToken.trim().length() > 0) {

      String githubServer = githubUri.replaceFirst("http.*\\/\\/", "");

      // only set the access token if it exists.
      GithubAuthenticationToken auth = new GithubAuthenticationToken(accessToken, githubServer);
      SecurityContextHolder.getContext().setAuthentication(auth);

      GHUser self = auth.getGitHub().getMyself();
      User u = User.current();
      u.setFullName(self.getName());
      u.addProperty(new Mailer.UserProperty(self.getEmail()));
    } else {
      Log.info("Github did not return an access token.");
    }

    String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
    if (referer != null) return HttpResponses.redirectTo(referer);
    return HttpResponses
        .redirectToContextRoot(); // referer should be always there, but be defensive
  }
  public String checkEmployer() {

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    //	employerSearchList = searchService.findAllEmployer(search);
    employerSearchList1 = searchService.findAllEmployerList(search);
    profiles = searchService.findListOfEmployeeProfiles(profile, user.getId());
    if (profiles.size() != 0) {
      currentProfile = employeeProfileService.getDefaultProfileForUser(user.getId());
      contactTypesList = privacygroupService.loadAllPrivacyGroupsOfUser(currentProfile.getId());
    }
    Iterator<Employer> it = employerSearchList1.iterator();
    try {
      while (it.hasNext()) {
        // Get element
        emplrProfileImages = it.next();

        if (emplrProfileImages.getPicture() != null) {
          image = (String) emplrProfileImages.getAmazonFileURL().get(0);
        }
        if (emplrProfileImages.getResizedMidPicture() != null) {
          resizedMidPicture = (String) emplrProfileImages.getAmazonFileURL().get(1);
          emplrProfileImages.setResizedMidPicture(resizedMidPicture);
        }
        if (emplrProfileImages.getResizedMinPicture() != null) {
          resizedMinPicture = (String) emplrProfileImages.getAmazonFileURL().get(2);
          emplrProfileImages.setResizedMinPicture(resizedMinPicture);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "success";
  }
  /**
   * @param username
   * @return
   * @throws UsernameNotFoundException
   * @throws DataAccessException
   */
  @Override
  public UserDetails loadUserByUsername(String username)
      throws UsernameNotFoundException, DataAccessException {
    GHUser user = null;

    GithubAuthenticationToken authToken =
        (GithubAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

    if (authToken == null) throw new UsernameNotFoundException("No known user: "******"user(" + username + ") is also an organization");
      }

      user = authToken.loadUser(username);

      if (user != null) return new GithubOAuthUserDetails(user);
      else throw new UsernameNotFoundException("No known user: "******"loadUserByUsername (username="******")", e);
    }
  }
Exemplo n.º 11
0
 /** For internal use. */
 @SuppressWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
 public final void start() {
   final SecurityContext securityContext = SecurityContextHolder.getContext();
   executorService()
       .submit(
           new Runnable() {
             public void run() {
               lastNewsTime = start = System.currentTimeMillis();
               SecurityContext orig = SecurityContextHolder.getContext();
               try {
                 SecurityContextHolder.setContext(securityContext);
                 compute();
                 if (status != CANCELED && status != ERROR) {
                   status = 1;
                 }
               } catch (Exception x) {
                 LOG.log(Level.WARNING, "failed to compute " + uri, x);
                 status = ERROR;
               } finally {
                 SecurityContextHolder.setContext(orig);
                 LOG.log(
                     Level.FINE,
                     "{0} finished in {1}msec with status {2}",
                     new Object[] {uri, System.currentTimeMillis() - start, status});
               }
             }
           });
 }
  /** The login process starts from here. */
  public HttpResponse doCommenceLogin(
      StaplerRequest req,
      StaplerResponse rsp,
      @QueryParameter String from,
      @QueryParameter String ticket)
      throws ServletException, IOException {

    // TODO write login method
    String puid = authenticateInWwpass(ticket, certFile, keyFile);

    WwpassIdentity u;
    try {
      u = loadUserByUsername(puid);
    } catch (UsernameNotFoundException e) {
      if (allowsSignup()) {
        req.setAttribute("errorMessage", Messages.WwpassSecurityRealm_NoSuchUserAllowsSignup());
      } else {
        req.setAttribute("errorMessage", Messages.WwpassSecurityRealm_NoSuchUserDisableSignup());
      }
      req.getView(this, "login.jelly").forward(req, rsp);
      throw e;
    }
    if (!u.isAccountNonLocked() || !u.isEnabled()) {
      // throw new LockedException("Account is not activated for " + puid);
      throw new Failure(Messages.WwpassSecurityRealm_AccountNotActivated());
    }

    Authentication a = new WwpassAuthenticationToken(u.getNickname());
    a = this.getSecurityComponents().manager.authenticate(a);
    SecurityContextHolder.getContext().setAuthentication(a);

    return new HttpRedirect(Jenkins.getInstance().getRootUrl());
  }
  @Override
  @SuppressWarnings("unchecked")
  public GroupDetails loadGroupByGroupname(String groupname)
      throws UsernameNotFoundException, DataAccessException {

    final Set<String> groups;

    if (getLDAPURL() != null) {
      // TODO: obtain a DN instead so that we can obtain multiple attributes later
      String searchBase = groupSearchBase != null ? groupSearchBase : "";
      String searchFilter = groupSearchFilter != null ? groupSearchFilter : GROUP_SEARCH;
      groups =
          ldapTemplate.searchForSingleAttributeValues(
              searchBase, searchFilter, new String[] {groupname}, "cn");
    } else {
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      GrantedAuthority[] authorities = authContext.get(auth.getName());

      SearchTemplate searchTemplate = new GroupSearchTemplate(groupname);

      groups = proxyTemplate.searchForSingleAttributeValues(searchTemplate, authorities);
    }

    if (groups.isEmpty()) throw new UsernameNotFoundException(groupname);

    return new GroupDetails() {
      @Override
      public String getName() {
        return groups.iterator().next();
      }
    };
  }
 /** {@inheritDoc} */
 @Override
 public boolean onNotify(UUID uuid, long revision, Set<String> paths) {
   final String id = uuid.toString();
   synchronized (recentUpdates) {
     Long recentUpdate = recentUpdates.get(id);
     if (recentUpdate != null && revision == recentUpdate) {
       LOGGER.log(
           Level.FINE,
           "Received duplicate post-commit hook from {0} for revision {1} on paths {2}",
           new Object[] {uuid, revision, paths});
       return false;
     }
     recentUpdates.put(id, revision);
   }
   LOGGER.log(
       Level.INFO,
       "Received post-commit hook from {0} for revision {1} on paths {2}",
       new Object[] {uuid, revision, paths});
   boolean notified = false;
   // run in high privilege to see all the projects anonymous users don't see.
   // this is safe because when we actually schedule a build, it's a build that can
   // happen at some random time anyway.
   Authentication old = SecurityContextHolder.getContext().getAuthentication();
   SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
   try {
     for (SCMSourceOwner owner : SCMSourceOwners.all()) {
       for (SCMSource source : owner.getSCMSources()) {
         if (source instanceof SubversionSCMSource) {
           if (id.equals(((SubversionSCMSource) source).getUuid())) {
             LOGGER.log(
                 Level.INFO,
                 "SCM changes detected relevant to {0}. Notifying update",
                 owner.getFullDisplayName());
             owner.onSCMSourceUpdated(source);
             notified = true;
           }
         }
       }
     }
   } finally {
     SecurityContextHolder.getContext().setAuthentication(old);
   }
   if (!notified) {
     LOGGER.log(Level.INFO, "No subversion consumers for UUID {0}", uuid);
   }
   return notified;
 }
Exemplo n.º 15
0
  public String listAllProfileFeedbacks() {

    user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    allProfilesFeedback = feedbackService.findAllProfilesFeedback(feedback, user.getId());
    allProfilesFeedbackCount = allProfilesFeedback.size();

    return "success";
  }
Exemplo n.º 16
0
  public void generatePushBuild(String json, Job project, StaplerRequest req, StaplerResponse rsp) {
    GitLabPushRequest request = GitLabPushRequest.create(json);
    String repositoryUrl = request.getRepository().getUrl();
    if (repositoryUrl == null) {

      LOGGER.log(Level.WARNING, "No repository url found.");
      return;
    }

    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    try {

      GitLabPushTrigger trigger = null;
      if (project instanceof ParameterizedJobMixIn.ParameterizedJob) {
        ParameterizedJobMixIn.ParameterizedJob p = (ParameterizedJobMixIn.ParameterizedJob) project;
        for (Trigger t : p.getTriggers().values()) {

          if (t instanceof GitLabPushTrigger) {
            trigger = (GitLabPushTrigger) t;
          }
        }
      }

      if (trigger == null) {
        return;
      }

      if (trigger.getCiSkip() && request.getLastCommit() != null) {
        if (request.getLastCommit().getMessage().contains("[ci-skip]")) {
          LOGGER.log(Level.INFO, "Skipping due to ci-skip.");
          return;
        }
      }

      trigger.onPost(request);

      if (!trigger.getTriggerOpenMergeRequestOnPush().equals("never")) {
        // Fetch and build open merge requests with the same source branch
        buildOpenMergeRequests(trigger, request.getProject_id(), request.getRef());
      }
    } finally {
      SecurityContextHolder.getContext().setAuthentication(old);
    }
  }
    /**
     * 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);
    }
        public void before() throws Throwable {
          setPluginManager(null);
          super.before();

          ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(NUM_THREADS);
          // Create a system level context with ACL.SYSTEM
          systemContext = ACL.impersonate(ACL.SYSTEM);

          User u = User.get("bob");
          // Create a sample user context
          userContext = new NonSerializableSecurityContext(u.impersonate());

          // Create a null context
          SecurityContextHolder.clearContext();
          nullContext = SecurityContextHolder.getContext();

          // Create a wrapped service
          wrappedService = new SecurityContextExecutorService(service);
        }
Exemplo n.º 19
0
  public synchronized <T> T run(SessionCallable<T> callable) throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    try {
      SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
      Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

      T result = callable.call(session);

      save();

      return result;
    } catch (Exception e) {
      LOGGER.log(Level.WARNING, "Exception while running " + callable + " on " + processId, e);
      throw e;
    } finally {
      SecurityContextHolder.getContext().setAuthentication(auth);
      Thread.currentThread().setContextClassLoader(cl);
    }
  }
  /** 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);
  }
Exemplo n.º 21
0
  private void fail(
      ServletRequest request, ServletResponse response, AuthenticationException failed)
      throws IOException, ServletException {
    SecurityContextHolder.getContext().setAuthentication(null);

    if (logger.isDebugEnabled()) {
      logger.debug(failed);
    }

    authenticationEntryPoint.commence(request, response, failed);
  }
Exemplo n.º 22
0
  public void doIndex(StaplerRequest req) throws IOException {
    String payload = IOUtils.toString(req.getReader());
    LOGGER.fine("Full details of the POST was " + payload);

    JSONObject o = JSONObject.fromObject(payload);
    String repoUrl = o.getString("repository_ssl_path");
    LOGGER.info("Received POST for " + repoUrl);

    // run in high privilege to see all the projects anonymous users don't see.
    // this is safe because when we actually schedule a build, it's a build that can
    // happen at some random time anyway.

    // TODO replace with ACL.impersonate as LTS is > 1.461
    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    try {
      for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
        boolean found = false;
        SCM scm = job.getScm();
        if (scm instanceof SubversionSCM) {
          found = hasRepository(repoUrl, (SubversionSCM) scm);
        } else if (scm instanceof GitSCM) {
          found = hasRepository(repoUrl, (GitSCM) scm);
        } else if (scm instanceof MercurialSCM) {
          found = hasRepository(repoUrl, (MercurialSCM) scm);
        }

        if (found) {
          LOGGER.info(job.getFullDisplayName() + " triggered by web hook.");
          job.scheduleBuild(new WebHookCause());
        }

        LOGGER.fine(
            "Skipped "
                + job.getFullDisplayName()
                + " because it doesn't have a matching repository.");
      }
    } finally {
      SecurityContextHolder.getContext().setAuthentication(old);
    }
  }
  private void deleteInstances(GHPullRequest pullRequest) throws IOException {
    PullRequestManager pullRequestManager = PullRequestManager.getInstance();
    List<PullRequestData> pullRequestDataList = new ArrayList<PullRequestData>();
    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    try {
      for (AbstractProject<?, ?> project :
          Jenkins.getInstance().getAllItems(AbstractProject.class)) {

        PullRequestData data =
            pullRequestManager.removePullRequestData(pullRequest.getHtmlUrl().toString(), project);

        if (data != null) {
          pullRequestDataList.add(data);
        }
      }
    } finally {
      SecurityContextHolder.getContext().setAuthentication(old);
    }
    PullRequestCleanup.deleteInstances(pullRequestDataList, pullRequest);
  }
  private void handleIssueCommentEvent(String payload) throws IOException {

    GitHub gitHub = createGitHub(JSONObject.fromObject(payload));

    if (gitHub == null) {
      return;
    }

    GHEventPayload.IssueComment issueComment =
        gitHub.parseEventPayload(new StringReader(payload), GHEventPayload.IssueComment.class);

    if (LOGGER.isLoggable(Level.FINER)) {
      LOGGER.finer(
          MessageFormat.format(
              "Comment on {0} from {1}: {2}",
              issueComment.getIssue().getUrl(),
              issueComment.getComment().getUser(),
              issueComment.getComment().getBody()));
    }

    if (!"created".equals(issueComment.getAction())) {
      if (LOGGER.isLoggable(Level.FINER)) {
        LOGGER.finer("Unsupported issue_comment action: " + issueComment.getAction());
      }
      return;
    }

    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    try {
      for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
        PullRequestBuildTrigger trigger = job.getTrigger(PullRequestBuildTrigger.class);
        if (trigger != null && trigger.getBuildHandler() instanceof PullRequestBuildHandler) {
          ((PullRequestBuildHandler) trigger.getBuildHandler()).handle(issueComment, gitHub);
        }
      }
    } finally {
      SecurityContextHolder.getContext().setAuthentication(old);
    }
  }
 /**
  * When the source project name is parameterized, cannot check at configure time whether the
  * project is accessible. In this case, permission check is done when the build runs. Only jobs
  * accessible to all authenticated users are allowed.
  */
 @LocalData
 public void testPermissionWhenParameterized() throws Exception {
   FreeStyleProject p = createProject("test$JOB", "", "", false, false, false);
   // Build step should succeed when this parameter expands to a job accessible
   // to authenticated users (even if triggered by anonymous, as in this case):
   SecurityContextHolder.clearContext();
   FreeStyleBuild b =
       p.scheduleBuild2(
               0, new UserCause(), new ParametersAction(new StringParameterValue("JOB", "Job2")))
           .get();
   assertFile(true, "foo2.txt", b);
   assertBuildStatusSuccess(b);
   // Build step should fail for a job not accessible to all authenticated users,
   // even when accessible to the user starting the job, as in this case:
   SecurityContextHolder.getContext()
       .setAuthentication(new UsernamePasswordAuthenticationToken("joe", "joe"));
   b =
       p.scheduleBuild2(
               0, new UserCause(), new ParametersAction(new StringParameterValue("JOB", "Job")))
           .get();
   assertFile(false, "foo.txt", b);
   assertBuildStatus(Result.FAILURE, b);
 }
  private Set<GhprbRepository> getRepos(String repo) {
    final Set<GhprbRepository> ret = new HashSet<GhprbRepository>();

    // We need this to get access to list of repositories
    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);

    try {
      for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
        GhprbTrigger trigger = job.getTrigger(GhprbTrigger.class);
        if (trigger == null || trigger.getRepository() == null) {
          continue;
        }
        GhprbRepository r = trigger.getRepository();
        if (repo.equals(r.getName())) {
          ret.add(r);
        }
      }
    } finally {
      SecurityContextHolder.getContext().setAuthentication(old);
    }
    return ret;
  }
  public void setUp() {
    GrantedAuthority[] roles =
        new GrantedAuthority[] {
          new GrantedAuthorityImpl("manager"), new GrantedAuthorityImpl("vp")
        };

    Authentication authentication =
        new UsernamePasswordAuthenticationToken(new Object(), new Object(), roles);

    SecurityContext context = new SecurityContextImpl();
    context.setAuthentication(authentication);

    SecurityContextHolder.setContext(context);
  }
Exemplo n.º 28
0
 public void put(String url) throws IOException {
   DBObject token = getToken(url);
   GithubAuthenticationToken auth =
       (GithubAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
   GitHub gh = auth.getGitHub();
   if (token != null) {
     delete(token);
   }
   String accessToken = Secret.fromString(auth.getAccessToken()).getEncryptedValue();
   BasicDBObject doc =
       new BasicDBObject("user", gh.getMyself().getLogin())
           .append("access_token", accessToken)
           .append("repo_url", url);
   save(doc);
 }
Exemplo n.º 29
0
  public String searchAllEmployers() {
    LOGGER.info("Entered searchAllEmployers");

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    employerSearchList = searchService.findListOfEmployers(employerName, employerLocation);

    profiles = searchService.findListOfEmployeeProfiles(profile, user.getId());

    if (profiles.size() != 0) {
      currentProfile = employeeProfileService.getDefaultProfileForUser(user.getId());
      contactTypesList = privacygroupService.loadAllPrivacyGroupsOfUser(currentProfile.getId());
    }
    return "success";
  }
  @Test
  @PresetData(PresetData.DataSet.NO_ANONYMOUS_READACCESS)
  public void testCallableCollectionAgainstAllContexts() throws Exception {
    Collection<Callable<SecurityContext>> callables = new LinkedList<Callable<SecurityContext>>();
    Callable<SecurityContext> c =
        new Callable<SecurityContext>() {
          public SecurityContext call() throws Exception {
            return SecurityContextHolder.getContext();
          }
        };
    callables.add(c);
    callables.add(c);
    callables.add(c);

    SecurityContextHolder.setContext(systemContext);
    Collection<Future<SecurityContext>> results = wrappedService.invokeAll(callables);
    for (Future<SecurityContext> result : results) {
      // Assert each thread context was identical to the initial service context
      SecurityContext value = result.get();
      assertEquals(systemContext, value);
    }

    SecurityContextHolder.setContext(userContext);
    results = wrappedService.invokeAll(callables);
    for (Future<SecurityContext> result : results) {
      // Assert each thread context was identical to the initial service context
      assertEquals(userContext, result.get());
    }

    SecurityContextHolder.setContext(nullContext);
    results = wrappedService.invokeAll(callables);
    for (Future<SecurityContext> result : results) {
      // Assert each thread context was identical to the initial service context
      assertEquals(nullContext, result.get());
    }
  }