org.acegisecurity.Authentication Java Examples

The following examples show how to use org.acegisecurity.Authentication. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KualiDistributedSessionFilter.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * This method retrieves the Distributed Session Ticket
 * 
 * @return the Distributed Session Ticket if valid or null
 */
private String getDST() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String sDST = null;
    
    if (authentication != null) {
        GrantedAuthority[] authorities = authentication.getAuthorities();
        if (logger.isDebugEnabled()) {
            logger.debug("Granted Authority Count:" + authorities.length);
        }
        
        for (int i = 0; i < authorities.length; i++) {
            if (logger.isDebugEnabled()) {
                logger.debug("Authority:" + authorities[i]);
            }
            if (authorities[i].toString().startsWith(DistributedSession.getPrefix())) {
                sDST = authorities[0].toString();
            }
        }
    }
    else {
        logger.debug("Authentication is NULL");            
    }
    
    return sDST;
}
 
Example #2
Source File: UserLoginListenerTest.java    From audit-log-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-54087")
@Test
@Parameters({
        "1, alice, alice, alice",
        "1, bob, bob, bob",
        "1, charlie, charlie, charlie",
        "1, debbie, debbie, debbie"
})
public void testValidUserLoginEventsLogged(int expectedCount, String expected, String username, String password) throws Exception {
    assertEventCount(app.getEvents(), 0);

    client.login(username, password);

    assertEventCount(app.getEvents(), expectedCount);

    client.executeOnServer(() -> {
        Authentication a = Jenkins.getAuthentication();
        assertEquals(expected, a.getName());

        return null;
    });
}
 
Example #3
Source File: AcegiUnSafeSessionFilter.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    Authentication old = SecurityContextHolder.getContext().getAuthentication();

    if(1 + 1 == 2) {
        try {
            SecurityContextHolder.getContext().setAuthentication(null);
            super.doFilter(req, res, chain);
        } finally {
            SecurityContextHolder.getContext().setAuthentication(old);
        }
    }
    else {
        super.doFilter(req, res, chain);
    }
}
 
Example #4
Source File: SSHStepExecution.java    From ssh-steps-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public final boolean start() {
  Authentication auth = Jenkins.getAuthentication();
  task = getExecutorService().submit(() -> {
    threadName = Thread.currentThread().getName();
    try {
      MDC.put("execution.id", UUID.randomUUID().toString());
      T ret;
      try (ACLContext acl = ACL.as(auth)) {
        ret = run();
      }
      getContext().onSuccess(ret);
    } catch (Throwable x) {
      if (stopCause == null) {
        getContext().onFailure(x);
      } else {
        stopCause.addSuppressed(x);
      }
    } finally {
      MDC.clear();
    }
  });
  return false;
}
 
Example #5
Source File: JwtAuthenticationServiceImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public static JwtAuthenticationStore getJwtStore(Authentication authentication){
    JwtAuthenticationStore jwtAuthenticationStore=null;
    for(JwtAuthenticationStoreFactory factory: JwtAuthenticationStoreFactory.all()){
        if(factory instanceof SimpleJwtAuthenticationStore){
            jwtAuthenticationStore = factory.getJwtAuthenticationStore(authentication);
            continue;
        }
        JwtAuthenticationStore authenticationStore = factory.getJwtAuthenticationStore(authentication);
        if(authenticationStore != null){
            return authenticationStore;
        }
    }

    //none found, lets use SimpleJwtAuthenticationStore
    return jwtAuthenticationStore;
}
 
Example #6
Source File: SimpleJwtAuthenticationStore.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public Authentication getAuthentication(Map<String,Object> claims) {
    Map context = (Map) claims.get("context");
    if(context != null && context.get("authProvider") != null){
        Map authProvider = (Map) context.get("authProvider");

        if(authProvider.get("id") != null){
            String id = (String) authProvider.get("id");
            Authentication authentication =  authenticationMap.get(id);
            if(authentication != null) {
                // if expired, we clear this id from the map and return null
                long expiryTime = (Long)claims.get("exp");
                if (expiryTime < (System.currentTimeMillis()/1000)) {
                    authenticationMap.remove(id);
                    return null;
                }
            }
            return authentication;
        }
    }
    return null;
}
 
Example #7
Source File: GithubScmTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
    mockStatic(Jenkins.class);

    when(Jenkins.getInstance()).thenReturn(jenkins);
    when(Jenkins.getInstanceOrNull()).thenReturn(jenkins);
    when(Jenkins.getAuthentication()).thenReturn(authentication);
    GrantedAuthority[] grantedAuthorities = Lists.newArrayList(SecurityRealm.AUTHENTICATED_AUTHORITY).toArray(new GrantedAuthority[1]);

    Mockito.when(authentication.getAuthorities()).thenReturn(grantedAuthorities);
    Mockito.when(authentication.getPrincipal()).thenReturn("joe");
    mockStatic(User.class);

    when(user.getId()).thenReturn("joe");
    when(user.getFullName()).thenReturn("joe smith");
    when(user.getDisplayName()).thenReturn("joe smith");
    when(User.class, method(User.class, "get", Authentication.class)).withArguments(authentication).thenReturn(user);
    when(User.current()).thenReturn(user);
}
 
Example #8
Source File: AbstractPipelineCreateRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
protected @Nonnull TopLevelItem createProject(String name, String descriptorName, Class<? extends TopLevelItemDescriptor> descriptorClass, BlueOrganization organization) throws IOException {
    ModifiableTopLevelItemGroup p = getParent(organization);

    final ACL acl = (p instanceof AccessControlled) ? ((AccessControlled) p).getACL() : Jenkins.getInstance().getACL();
    Authentication a = Jenkins.getAuthentication();
    if(!acl.hasPermission(a, Item.CREATE)){
        throw new ServiceException.ForbiddenException(
                String.format("Failed to create pipeline: %s. User %s doesn't have Job create permission", name, a.getName()));
    }
    TopLevelItemDescriptor descriptor = Items.all().findByName(descriptorName);
    if(descriptor == null || !(descriptorClass.isAssignableFrom(descriptor.getClass()))){
        throw new ServiceException.BadRequestException(String.format("Failed to create pipeline: %s, descriptor %s is not found", name, descriptorName));
    }

    if (!descriptor.isApplicableIn(p)) {
        throw new ServiceException.ForbiddenException(
                String.format("Failed to create pipeline: %s. Pipeline can't be created in Jenkins root folder", name));
    }

    if (!acl.hasCreatePermission(a, p, descriptor)) {
        throw new ServiceException.ForbiddenException("Missing permission: " + Item.CREATE.group.title+"/"+Item.CREATE.name + " " + Item.CREATE + "/" + descriptor.getDisplayName());
    }
    return p.createProject(descriptor, name, true);
}
 
Example #9
Source File: ScmResourceImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private @Nonnull User checkPermission(){
    ACL acl;
    if(item.getParent() != null && item.getParent() instanceof OrganizationFolder){
        acl = ((OrganizationFolder) item.getParent()).getACL();
    }else{
        acl = item.getACL();
    }
    Authentication a = Jenkins.getAuthentication();
    User user = User.get(a);
    if(user == null){
        throw new ServiceException.UnauthorizedException("No logged in user found");
    }
    if(!acl.hasPermission(a, Item.CONFIGURE)){
        throw new ServiceException.ForbiddenException(
                String.format("User %s must have Job configure permission to access content", a.getName()));
    }

    return user;
}
 
Example #10
Source File: GeneralNonBlockingStepExecution.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
/**
 * Initiate background work that should not block the CPS VM thread.
 * Call this from a CPS VM thread, such as from {@link #start} or {@link BodyExecutionCallback#onSuccess}.
 * The block may finish by calling {@link BodyInvoker#start}, {@link StepContext#onSuccess}, etc.
 * @param block some code to run in a utility thread
 */
protected final void run(Block block) {
    if (stopping) {
        return;
    }
    final Authentication auth = Jenkins.getAuthentication();
    task = GeneralNonBlockingStepExecutionUtils.getExecutorService().submit(() -> {
        threadName = Thread.currentThread().getName();
        try {
            try (ACLContext acl = ACL.as(auth)) {
                block.run();
            }
        } catch (Throwable e) {
            if (!stopping) {
                getContext().onFailure(e);
            }
        } finally {
            threadName = null;
            task = null;
        }
    });
}
 
Example #11
Source File: KualiCasAuthenticationProvider.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * This overridden method is differs from the super method by 
 * populating the user details by passing the full response
 * 
 * @see org.acegisecurity.providers.cas.CasAuthenticationProvider#authenticateNow(Authentication authentication)
 */
private CasAuthenticationToken authenticateNow(Authentication authentication) throws AuthenticationException {
    // Validate
    KualiTicketResponse response = (KualiTicketResponse)this.getTicketValidator().confirmTicketValid(authentication.getCredentials().toString());

    // Check proxy list is trusted
    this.getCasProxyDecider().confirmProxyListTrusted(response.getProxyList());
    if (logger.isDebugEnabled()) {
        logger.debug("authenticationNOW:" + response);
    }
    // Lookup user details      
    logger.debug("\n\npopulating authorities\n\n");
    UserDetails userDetails = ((KualiCasAuthoritiesPopulator)this.getCasAuthoritiesPopulator()).getUserDetails(response);        

    // Construct CasAuthenticationToken
    return new CasAuthenticationToken(this.getKey(), userDetails, authentication.getCredentials(),
        userDetails.getAuthorities(), userDetails, response.getProxyList(), response.getProxyGrantingTicketIou());
}
 
Example #12
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
@Override
public SecurityComponents createSecurityComponents() {
    return new SecurityComponents(new AuthenticationManager() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            if (authentication instanceof GitLabAuthenticationToken) {
                return authentication;
            }
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                try {
                    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
                    GitLabAuthenticationToken gitlab = new GitLabAuthenticationToken(token.getCredentials().toString(), getGitlabApiUri(), TokenType.PRIVATE_TOKEN);
                    SecurityContextHolder.getContext().setAuthentication(gitlab);
                    return gitlab;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            throw new BadCredentialsException("Unexpected authentication type: " + authentication);
        }
    }, new UserDetailsService() {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
            return GitLabSecurityRealm.this.loadUserByUsername(username);
        }
    });
}
 
Example #13
Source File: RESTRequestParameterProcessingFilter.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private RESTController.ErrorCode authenticate(String username, String password, String salt, String token, Authentication previousAuth) {

        // Previously authenticated and username not overridden?
        if (username == null && previousAuth != null) {
            return null;
        }

        if (salt != null && token != null) {
            User user = securityService.getUserByName(username);
            if (user == null) {
                return RESTController.ErrorCode.NOT_AUTHENTICATED;
            }
            String expectedToken = DigestUtils.md5Hex(user.getPassword() + salt);
            if (!expectedToken.equals(token)) {
                return RESTController.ErrorCode.NOT_AUTHENTICATED;
            }

            password = user.getPassword();
        }

        if (password != null) {
            try {
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                Authentication authResult = authenticationManager.authenticate(authRequest);
                SecurityContextHolder.getContext().setAuthentication(authResult);
                return null;
            } catch (AuthenticationException x) {
                return RESTController.ErrorCode.NOT_AUTHENTICATED;
            }
        }

        return RESTController.ErrorCode.MISSING_PARAMETER;
    }
 
Example #14
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
@Override
protected String getPostLogOutUrl(StaplerRequest req, Authentication auth) {
    // if we just redirect to the root and anonymous does not have Overall read then we will start a login all over again.
    // we are actually anonymous here as the security context has been cleared
    Jenkins jenkins = Jenkins.getInstance();
    assert jenkins != null;
    if (jenkins.hasPermission(Jenkins.READ)) {
        return super.getPostLogOutUrl(req, auth);
    }
    return req.getContextPath() + "/" + GitLabLogoutAction.POST_LOGOUT_URL;
}
 
Example #15
Source File: WCTForcePasswordChange.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/** @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */
public void doFilter(ServletRequest aRequest, ServletResponse aResponse, FilterChain aChain) throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("Checking forced password change action.");
    }
    
    if (!(aRequest instanceof HttpServletRequest)) {
      throw new ServletException("Can only process HttpServletRequest");
  }

  if (!(aResponse instanceof HttpServletResponse)) {
      throw new ServletException("Can only process HttpServletResponse");
  }

  HttpServletRequest httpRequest = (HttpServletRequest) aRequest;
  
  Authentication auth =  SecurityContextHolder.getContext().getAuthentication();      
  if (auth != null) {            
    if (auth.isAuthenticated()) {
        User authUser = (User)auth.getDetails();

        if (authUser != null) {
          if (authUser.isForcePasswordChange() == true && authUser.isExternalAuth() == false) {
                                
              RequestDispatcher reqDisp = httpRequest.getRequestDispatcher("/"+Constants.CNTRL_RESET_PWD);
              reqDisp.forward(aRequest, aResponse);  
              auditor.audit(User.class.getName(),authUser.getOid(),Auditor.ACTION_FORCE_PWD_CHANGE,"User has been forced to change password");
          }
        }
    }
    else {
        throw new AccessControlException("The user is not authenticated correctly.");
    }
  }
 
  aChain.doFilter(aRequest, aResponse);
}
 
Example #16
Source File: PluginTest.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the authentication object from the web client.
 *
 * @return the authentication object
 */
private Authentication getAuthentication() {
    try {
        return webClient.executeOnServer(new Callable<Authentication>() {
            public  Authentication call() throws Exception {
                return jenkins.getAuthentication();
            }
        });
    } catch (Exception e) {
        // safely ignore all exceptions, the method never throws anything
        return null;
    }

}
 
Example #17
Source File: PipelineTriggerService.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
public boolean isUpstreamBuildVisibleByDownstreamBuildAuth(@Nonnull WorkflowJob upstreamPipeline, @Nonnull WorkflowJob downstreamPipeline) {
    Authentication downstreamPipelineAuth = Tasks.getAuthenticationOf(downstreamPipeline);

    // see https://github.com/jenkinsci/jenkins/blob/jenkins-2.176.2/core/src/main/java/jenkins/triggers/ReverseBuildTrigger.java#L132
    // jenkins.triggers.ReverseBuildTrigger#shouldTrigger
    try (ACLContext ignored = ACL.as(downstreamPipelineAuth)) {
        WorkflowJob upstreamPipelineObtainedAsImpersonated = getItemByFullName(upstreamPipeline.getFullName(), WorkflowJob.class);
        boolean result = upstreamPipelineObtainedAsImpersonated != null;
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "isUpstreamBuildVisibleByDownstreamBuildAuth(upstreamPipeline: {0}, downstreamPipeline: {1}): downstreamPipelineAuth: {2}, upstreamPipelineObtainedAsImpersonated:{3}, result: {4}",
                    new Object[]{upstreamPipeline.getFullName(), downstreamPipeline.getFullName(), downstreamPipelineAuth, upstreamPipelineObtainedAsImpersonated, result});
        }
        return result;
    }
}
 
Example #18
Source File: KubernetesComputer.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public ACL getACL() {
    final ACL base = super.getACL();
    return new ACL() {
        @Override
        public boolean hasPermission(Authentication a, Permission permission) {
            return permission == Computer.CONFIGURE ? false : base.hasPermission(a,permission);
        }
    };
}
 
Example #19
Source File: UserCreationListenerTest.java    From audit-log-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-54088")
@Test
public void testUserCreationAndLoginFromRealm() throws Exception {
    assertEventCount(app.getEvents(), 0);

    HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false, false, null);
    j.jenkins.setSecurityRealm(realm);

    User u1 = realm.createAccount("charlie", USERS.get("charlie"));
    u1.save();
    client.login("charlie", USERS.get("charlie"));

    // verify the audit event log messages as user creation and user login events
    StructuredDataMessage logMessageOne = (StructuredDataMessage) app.getEvents().get(0).getMessage();
    StructuredDataMessage logMessageTwo = (StructuredDataMessage) app.getEvents().get(1).getMessage();

    assertTrue(logMessageOne.toString().contains("createUser"));
    assertTrue(logMessageTwo.toString().contains("login"));

    // verify a login event occurred
    client.executeOnServer(() -> {
        Authentication a = Jenkins.getAuthentication();
        assertEquals("charlie", a.getName());

        return null;
    });

    assertEventCount(app.getEvents(), 2);
}
 
Example #20
Source File: CredentialsHelper.java    From git-changelog-plugin with MIT License 5 votes vote down vote up
private static <C extends Credentials> List<C> getAllCredentials(Class<C> type) {
  ItemGroup<?> itemGroup = null;
  Authentication authentication = SYSTEM;
  DomainRequirement domainRequirement = null;

  return lookupCredentials(type, itemGroup, authentication, domainRequirement);
}
 
Example #21
Source File: RegistryEndpointStepTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test
public void stepExecutionWithCredentialsAndQueueItemAuthenticator() throws Exception {
    assumeNotWindows();

    r.getInstance().setSecurityRealm(r.createDummySecurityRealm());
    MockAuthorizationStrategy auth = new MockAuthorizationStrategy()
            .grant(Jenkins.READ).everywhere().to("alice", "bob")
            .grant(Computer.BUILD).everywhere().to("alice", "bob")
            // Item.CONFIGURE implies Credentials.USE_ITEM, which is what CredentialsProvider.findCredentialById
            // uses when determining whether to include item-scope credentials in the search.
            .grant(Item.CONFIGURE).everywhere().to("alice");
    r.getInstance().setAuthorizationStrategy(auth);

    IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass");
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials);

    String script = "node {\n" +
            "  mockDockerLoginWithEcho {\n" +
            "    withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" +
            "    }\n" +
            "  }\n" +
            "}";
    WorkflowJob p1 = r.createProject(WorkflowJob.class, "prj1");
    p1.setDefinition(new CpsFlowDefinition(script, true));
    WorkflowJob p2 = r.createProject(WorkflowJob.class, "prj2");
    p2.setDefinition(new CpsFlowDefinition(script, true));

    Map<String, Authentication> jobsToAuths = new HashMap<>();
    jobsToAuths.put(p1.getFullName(), User.getById("alice", true).impersonate());
    jobsToAuths.put(p2.getFullName(), User.getById("bob", true).impersonate());
    QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(jobsToAuths));

    // Alice has Credentials.USE_ITEM permission and should be able to use the credential.
    WorkflowRun b1 = r.buildAndAssertSuccess(p1);
    r.assertLogContains("docker login -u me -p pass https://my-reg:1234", b1);

    // Bob does not have Credentials.USE_ITEM permission and should not be able to use the credential.
    r.assertBuildStatus(Result.FAILURE, p2.scheduleBuild2(0));
}
 
Example #22
Source File: OrganizationFolderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test(expected = ServiceException.ForbiddenException.class)
public void testOrganizationFolderFactoryNoPermissionsFolder() throws Exception {
    List<OrganizationFolderPipelineImpl.OrganizationFolderFactory> organizationFolderFactoryList = ExtensionList.lookup(OrganizationFolderPipelineImpl.OrganizationFolderFactory.class);
    OrganizationFolderFactoryTestImpl organizationFolderFactoryTest = ((ExtensionList<OrganizationFolderPipelineImpl.OrganizationFolderFactory>) organizationFolderFactoryList).get(OrganizationFolderFactoryTestImpl.class);
    assertNotNull(organizationFolderFactoryTest);

    OrganizationFolderPipelineImpl folderPipeline = organizationFolderFactoryTest.getFolder(orgFolder, new Reachable() {
        @Override
        public Link getLink() {
            return organization.getLink().rel("/pipelines/");
        }
    }, mockOrganization());
    assertNotNull(folderPipeline);

    assertNotNull(folderPipeline.getQueue());
    assertNotNull(folderPipeline.getQueue().iterator());

    //Make sure the user does not have permissions to that folder
    PowerMockito.when(orgFolder.getACL()).thenReturn(new ACL() {
        @Override
        public boolean hasPermission(Authentication arg0, Permission arg1) {
            return false;
        }
    });

    ScmResourceImpl scmResource = new ScmResourceImpl(orgFolder, folderPipeline);
    StaplerRequest staplerRequest = PowerMockito.mock(StaplerRequest.class);
    assertEquals("hello", scmResource.getContent(staplerRequest));
}
 
Example #23
Source File: OrganizationFolderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void testOrganizationFolderFactory() throws Exception{
    List<OrganizationFolderPipelineImpl.OrganizationFolderFactory> organizationFolderFactoryList = ExtensionList.lookup(OrganizationFolderPipelineImpl.OrganizationFolderFactory.class);
    OrganizationFolderFactoryTestImpl organizationFolderFactoryTest = ((ExtensionList<OrganizationFolderPipelineImpl.OrganizationFolderFactory>) organizationFolderFactoryList).get(OrganizationFolderFactoryTestImpl.class);
    assertNotNull(organizationFolderFactoryTest);

    OrganizationFolderPipelineImpl folderPipeline = organizationFolderFactoryTest.getFolder(orgFolder, new Reachable() {
        @Override
        public Link getLink() {
            return organization.getLink().rel("/pipelines/");
        }
    }, mockOrganization());
    assertNotNull(folderPipeline);

    assertNotNull(folderPipeline.getQueue());
    assertNotNull(folderPipeline.getQueue().iterator());

    //Make sure the user does has permissions to that folder
    PowerMockito.when(orgFolder.getACL()).thenReturn(new ACL() {
        @Override
        public boolean hasPermission(Authentication arg0, Permission arg1) {
            return true;
        }
    });

    ScmResourceImpl scmResource = new ScmResourceImpl(orgFolder, folderPipeline);
    StaplerRequest staplerRequest = PowerMockito.mock(StaplerRequest.class);
    assertEquals("hello", scmResource.getContent(staplerRequest));
}
 
Example #24
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public boolean hasPermission(@Nonnull Authentication a, @Nonnull Permission permission) {
    // its read only so for all permissions other than READ, we return false
    if(permission == CREATE || permission == DELETE ||
            permission == MANAGE_DOMAINS || permission == UPDATE){
        return false;
    }
    return owner.getACL().hasPermission(a,permission);
}
 
Example #25
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Nonnull
@Override
public <C extends IdCredentials> ListBoxModel getCredentialIds(@Nonnull Class<C> type,
                                                               @Nullable ItemGroup itemGroup,
                                                               @Nullable Authentication authentication,
                                                               @Nonnull List<DomainRequirement> domainRequirements,
                                                               @Nonnull CredentialsMatcher matcher) {
    ListBoxModel result = new ListBoxModel();
    FolderPropertyImpl prop = propertyOf(itemGroup);
    if (prop != null && prop.domain.test(domainRequirements)) {
        result.add(Messages.BlueOceanCredentialsProvider_DisplayName(), prop.getId());
    }
    return result;
}
 
Example #26
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Nonnull
public <C extends Credentials> List<C> getCredentials(@Nonnull final Class<C> type,
                                                      @Nullable ItemGroup itemGroup,
                                                      @Nullable
                                                          Authentication authentication,
                                                      @Nonnull List<DomainRequirement> domainRequirements) {
    final List<C> result = new ArrayList<>();
    final FolderPropertyImpl prop = propertyOf(itemGroup);
    if (prop != null && prop.domain.test(domainRequirements)) {
        final User proxyUser = User.get(prop.getUser(), false, Collections.emptyMap());
        if (proxyUser != null) {
            try (ACLContext ignored = ACL.as(proxyUser.impersonate())) {
                for (CredentialsStore s : CredentialsProvider.lookupStores(proxyUser)) {
                    for (Domain d : s.getDomains()) {
                        if (d.test(PROXY_REQUIREMENT)) {
                            for (Credentials c : filter(s.getCredentials(d), withId(prop.getId()))) {
                                if (type.isInstance(c)) {
                                    result.add((C) c);
                                }
                            }
                        }
                    }
                }
            } catch (UsernameNotFoundException ex) {
                logger.warn("BlueOceanCredentialsProvider#getCredentials(): Username attached to credentials can not be found");
            }
        }
    }
    return result;
}
 
Example #27
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Nonnull
@Override
public <C extends Credentials> List<C> getCredentials(@Nonnull Class<C> type,
                                                      @Nonnull ItemGroup itemGroup,
                                                      @Nonnull
                                                          Authentication authentication) {
    return getCredentials(type, itemGroup, authentication, Collections.<DomainRequirement>emptyList());
}
 
Example #28
Source File: AbstractPipelineCreateRequest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
protected User checkUserIsAuthenticatedAndHasItemCreatePermission(BlueOrganization organization) {
    ModifiableTopLevelItemGroup p = getParent(organization);

    User authenticatedUser = User.current();
    if (authenticatedUser == null) {
        throw new ServiceException.UnauthorizedException("Must be logged in to create a pipeline");
    }
    Authentication authentication = Jenkins.getAuthentication();
    ACL acl = (p instanceof AccessControlled) ? ((AccessControlled) p).getACL() : Jenkins.getInstance().getACL();
    if(!acl.hasPermission(authentication, Item.CREATE)){
        throw new ServiceException.ForbiddenException(
            String.format("User %s doesn't have Job create permission", authenticatedUser.getId()));
    }
    return authenticatedUser;
}
 
Example #29
Source File: MockQueueItemAuthenticator.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override public Authentication authenticate(Queue.Item item) {
    if (item.task instanceof Item) {
        return jobsToUsers.get(((Item) item.task).getFullName());
    } else {
        return null;
    }
}
 
Example #30
Source File: GerritWebHook.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unused", "deprecation"})
public void doIndex() throws IOException {
  HttpServletRequest req = Stapler.getCurrentRequest();
  getBody(req)
      .ifPresent(
          projectEvent -> {
            String username = "anonymous";
            Authentication authentication = getJenkinsInstance().getAuthentication();
            if (authentication != null) {
              username = authentication.getName();
            }

            log.info("GerritWebHook invoked by user '{}' for event: {}", username, projectEvent);

            try (ACLContext acl = ACL.as(ACL.SYSTEM)) {
              List<WorkflowMultiBranchProject> jenkinsItems =
                  getJenkinsInstance().getAllItems(WorkflowMultiBranchProject.class);
              log.info("Scanning {} Jenkins items", jenkinsItems.size());
              for (SCMSourceOwner scmJob : jenkinsItems) {
                log.info("Scanning job " + scmJob);
                List<SCMSource> scmSources = scmJob.getSCMSources();
                for (SCMSource scmSource : scmSources) {
                  if (scmSource instanceof GerritSCMSource) {
                    GerritSCMSource gerritSCMSource = (GerritSCMSource) scmSource;
                    log.debug("Checking match for SCM source: " + gerritSCMSource.getRemote());
                    if (projectEvent.matches(gerritSCMSource.getRemote())) {
                      log.info(
                          "Triggering SCM event for source "
                              + scmSources.get(0)
                              + " on job "
                              + scmJob);
                      scmJob.onSCMSourceUpdated(scmSource);
                    }
                  }
                }
              }
            }
          });
}