/** * Creates an {@link Authentication} object that represents this user. * <p> * This method checks with {@link SecurityRealm} if the user is a valid user that can login to the security realm. * If {@link SecurityRealm} is a kind that does not support querying information about other users, this will * use {@link LastGrantedAuthoritiesProperty} to pick up the granted authorities as of the last time the user has * logged in. * * @throws UsernameNotFoundException If this user is not a valid user in the backend {@link SecurityRealm}. * @since 1.419 */ public @Nonnull Authentication impersonate() throws UsernameNotFoundException { return this.impersonate(this.getUserDetailsForImpersonation()); }
/** * Changes the {@link Authentication} associated with the current thread to the specified one and returns an * {@link AutoCloseable} that restores the previous security context. * * <p> * This makes impersonation much easier within code as it can now be used using the try with resources construct: * <pre> * try (ACLContext ctx = ACL.as(auth)) { * ... * } * </pre> * * @param user the user to impersonate. * @return the previous authentication context * @since 2.14 */ @Nonnull public static ACLContext as(@CheckForNull User user) { return as(user == null ? Jenkins.ANONYMOUS : user.impersonate()); }
/** * Note: if the token does not exist or does not match, we do not use {@link SecurityListener#fireFailedToAuthenticate(String)} * because it will be done in the {@link BasicHeaderRealPasswordAuthenticator} in the case the password is not valid either */ @Override public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException { User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password); if(u != null) { Authentication auth; try { UserDetails userDetails = u.getUserDetailsForImpersonation(); auth = u.impersonate(userDetails); SecurityListener.fireAuthenticated(userDetails); } catch (UsernameNotFoundException x) { // The token was valid, but the impersonation failed. This token is clearly not his real password, // so there's no point in continuing the request processing. Report this error and abort. LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x); throw new ServletException(x); } catch (DataAccessException x) { throw new ServletException(x); } req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true); return auth; } return null; }
Authentication authentication; try { authentication = impersonate(); } catch (UsernameNotFoundException x) { LOGGER.log(Level.FINE, "cannot look up authorities for " + id, x);
if(u != null){ UserDetails userDetails = u.getUserDetailsForImpersonation(); Authentication auth = u.impersonate(userDetails);
@Override public Authentication getAuthentication() { if (user == null) { return ACL.SYSTEM; } try { User u = User.getById(user, true); if (u == null) { return Jenkins.ANONYMOUS; } else { return u.impersonate(); } } catch (UsernameNotFoundException x) { LOGGER.log(Level.WARNING, "could not restore authentication", x); // Should not expose this to callers. return Jenkins.ANONYMOUS; } }
/** * Changes the {@link Authentication} associated with the current thread to the specified one and returns an * {@link AutoCloseable} that restores the previous security context. * * <p> * This makes impersonation much easier within code as it can now be used using the try with resources construct: * <pre> * try (ACLContext ctx = ACL.as(auth)) { * ... * } * </pre> * * @param user the user to impersonate. * @return the previous authentication context * @since 2.14 */ @Nonnull public static ACLContext as(@CheckForNull User user) { return as(user == null ? Jenkins.ANONYMOUS : user.impersonate()); }
@Override public Authentication getAuthentication() { if (authentication != null) { return authentication; } User u = User.get(descriptor.getHudsonUserName()); return u.impersonate(); } };
/** * Run the command as a given username. * Test setup should have first defined a meaningful security realm and authorization strategy. * @see Jenkins#setSecurityRealm * @see JenkinsRule#createDummySecurityRealm * @see Jenkins#setAuthorizationStrategy * @see MockAuthorizationStrategy */ public CLICommandInvoker asUser(String user) { command.setTransportAuth(User.get(user).impersonate()); return this; }
@Override public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException { // attempt to authenticate as API token User u = User.getById(username, true); ApiTokenProperty t = u.getProperty(ApiTokenProperty.class); if (t!=null && t.matchesPassword(password)) { try { return u.impersonate(); } catch (UsernameNotFoundException x) { // The token was valid, but the impersonation failed. This token is clearly not his real password, // so there's no point in continuing the request processing. Report this error and abort. LOGGER.log(WARNING, "API token matched for user "+username+" but the impersonation failed",x); throw new ServletException(x); } catch (DataAccessException x) { throw new ServletException(x); } } return null; }
@Override public void forRow(User user, Runnable runnable) { final Authentication auth; try { auth = user.impersonate(); } catch (UsernameNotFoundException ex) { fillRowByResult(user, Boolean.FALSE); return; } SecurityContext initialContext = null; try { initialContext = hudson.security.ACL.impersonate(auth); runnable.run(); } finally { if (initialContext != null) { SecurityContextHolder.setContext(initialContext); } } }
private void assertCredentials(String user, final Job<?,?> owner, Credentials... expected) { final List<String> expectedNames = new ArrayList<String>(); for (Credentials c : expected) { expectedNames.add(CredentialsNameProvider.name(c)); } ACL.impersonate(User.get(user).impersonate(), new Runnable() { @Override public void run() { List<String> actualNames = new ArrayList<String>(); for (ListBoxModel.Option o : r.jenkins.getDescriptorByType(MercurialSCM.DescriptorImpl.class).doFillCredentialsIdItems(owner, "http://nowhere.net/")) { if (o.value.isEmpty()) { continue; // AbstractIdCredentialsListBoxModel.EmptySelection } actualNames.add(o.name); } assertEquals(expectedNames, actualNames); } }); }
private static boolean canRestart(WorkflowRun b, String user) { final RestartDeclarativePipelineAction a = b.getAction(RestartDeclarativePipelineAction.class); return ACL.impersonate(User.get(user).impersonate(), new NotReallyRoleSensitiveCallable<Boolean,RuntimeException>() { @Override public Boolean call() throws RuntimeException { return a.isRestartEnabled(); } }); }
private static boolean canReplay(WorkflowRun b, String user) { final ReplayAction a = b.getAction(ReplayAction.class); return ACL.impersonate(User.get(user).impersonate(), new NotReallyRoleSensitiveCallable<Boolean,RuntimeException>() { @Override public Boolean call() throws RuntimeException { return a.isEnabled(); } }); }
private void setAuth() { if (permissions.isEmpty()) return; JenkinsRule.DummySecurityRealm realm = rule.createDummySecurityRealm(); realm.addGroups(username, "group"); originalSecurityRealm = rule.jenkins.getSecurityRealm(); rule.jenkins.setSecurityRealm(realm); originalAuthorizationStrategy = rule.jenkins.getAuthorizationStrategy(); rule.jenkins.setAuthorizationStrategy(new GrantPermissions(username, permissions)); command.setTransportAuth(user().impersonate()); // Otherwise it is SYSTEM, which would be relevant for a command overriding main: originalSecurityContext = ACL.impersonate(Jenkins.ANONYMOUS); }
@Override protected Boolean getEntryReport(Computer column, Permission item) { final Authentication auth; try { auth = user4report.impersonate(); } catch (UsernameNotFoundException ex) { return Boolean.FALSE; } SecurityContext initialContext = null; AuthorizationStrategy strategy = JenkinsHelper.getInstanceOrFail().getAuthorizationStrategy(); try { initialContext = hudson.security.ACL.impersonate(auth); return strategy.getACL(column).hasPermission(item); } finally { if (initialContext != null) { SecurityContextHolder.setContext(initialContext); } } }
@Test public void doFillCredentialsIdItemsWithoutJobWhenAdmin() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); ProjectMatrixAuthorizationStrategy as = new ProjectMatrixAuthorizationStrategy(); as.add(Jenkins.ADMINISTER, "alice"); r.jenkins.setAuthorizationStrategy(as); final UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "test", "bob", "s3cr3t"); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c); ACL.impersonate(User.get("alice").impersonate(), new Runnable() { @Override public void run() { ListBoxModel options = r.jenkins.getDescriptorByType(MercurialSCM.DescriptorImpl.class).doFillCredentialsIdItems(null, "http://nowhere.net/"); assertEquals(CredentialsNameProvider.name(c), options.get(1).name); } }); }
@Test public void invalidUser() throws Exception { File testPath = writeJenkinsfileToTmpFile("simplePipeline"); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() .grant(Jenkins.ADMINISTER).everywhere().to("bob") .grant(Jenkins.READ, Item.READ, Item.EXTENDED_READ).everywhere().to("alice")); final CLICommandInvoker.Result result = command.withStdin(FileUtils.openInputStream(testPath)).invoke(); assertThat(result, not(succeeded())); assertThat(result.stderr(), containsString("ERROR: anonymous is missing the Overall/Read permission")); declarativeLinterCommand.setTransportAuth(User.get("alice").impersonate()); final CLICommandInvoker.Result result2 = command.withStdin(FileUtils.openInputStream(testPath)).invoke(); assertThat(result2, succeeded()); assertThat(result2, hasNoErrorOutput()); assertThat(result2.stdout(), containsString("Jenkinsfile successfully validated.")); }
@Override public void evaluate() throws Throwable { jenkins().setSecurityRealm(story.j.createDummySecurityRealm()); jenkins().save(); QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap("demo", User.getById("someone", true).impersonate()))); p = jenkins().createProject(WorkflowJob.class, "demo"); p.setDefinition(new CpsFlowDefinition("echo \"ran as ${auth()}\"", true)); b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0)); story.j.assertLogContains("ran as someone", b); } });
@Override public void evaluate() throws Throwable { jenkins().setSecurityRealm(story.j.createDummySecurityRealm()); jenkins().save(); QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap("demo", User.getById("someone", true).impersonate()))); p = jenkins().createProject(WorkflowJob.class, "demo"); p.setDefinition(new CpsFlowDefinition("checkAuth()", false)); ScriptApproval.get().preapproveAll(); startBuilding(); waitForWorkflowToSuspend(); assertTrue(b.isBuilding()); story.j.waitForMessage("running as someone", b); CheckAuth.finish(false); waitForWorkflowToSuspend(); assertTrue(b.isBuilding()); story.j.waitForMessage("still running as someone", b); } });