From 1d0c8d5ea852a436fc7e756932d97487b727290b Mon Sep 17 00:00:00 2001 From: kohsuke Date: Fri, 5 Mar 2010 23:13:27 +0000 Subject: [PATCH] [FIXED HUDSON-3796] implemented an extensible authentication scheme for CLI clients. git-svn-id: https://hudson.dev.java.net/svn/hudson/trunk/hudson/main@28296 71c3de6d-444a-0410-be80-ed276b4c234a --- core/src/main/java/hudson/cli/CLICommand.java | 48 ++++++++++++ .../main/java/hudson/cli/CliManagerImpl.java | 15 ++-- .../AbstractPasswordBasedSecurityRealm.java | 36 +++++++++ .../hudson/security/CliAuthenticator.java | 78 +++++++++++++++++++ .../java/hudson/security/SecurityRealm.java | 19 +++++ .../security/CliAuthenticationTest.java | 66 ++++++++++++++++ 6 files changed, 252 insertions(+), 10 deletions(-) create mode 100644 core/src/main/java/hudson/security/CliAuthenticator.java create mode 100644 test/src/test/java/hudson/security/CliAuthenticationTest.java diff --git a/core/src/main/java/hudson/cli/CLICommand.java b/core/src/main/java/hudson/cli/CLICommand.java index c00062e27c..cf542bcff4 100644 --- a/core/src/main/java/hudson/cli/CLICommand.java +++ b/core/src/main/java/hudson/cli/CLICommand.java @@ -32,6 +32,11 @@ import hudson.ExtensionPoint.LegacyInstancesAreScopedToHudson; import hudson.model.Hudson; import hudson.remoting.Callable; import hudson.remoting.Channel; +import hudson.security.CliAuthenticator; +import org.acegisecurity.Authentication; +import org.acegisecurity.context.SecurityContext; +import org.acegisecurity.context.SecurityContextHolder; +import org.kohsuke.args4j.ClassParser; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; @@ -128,6 +133,7 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { public String getName() { String name = getClass().getName(); name = name.substring(name.lastIndexOf('.')+1); // short name + name = name.substring(name.lastIndexOf('$')+1); if(name.endsWith("Command")) name = name.substring(0,name.length()-7); // trim off the command @@ -142,15 +148,35 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { */ public abstract String getShortDescription(); + /** + * @deprecated as of 1.350 + * Use {@link #main(List, Locale, InputStream, PrintStream, PrintStream, Authentication)} + */ public int main(List args, Locale locale, InputStream stdin, PrintStream stdout, PrintStream stderr) { + return main(args,locale,stdin,stdout,stderr,Hudson.ANONYMOUS); + } + + public int main(List args, Locale locale, InputStream stdin, PrintStream stdout, PrintStream stderr, Authentication auth) { this.stdin = new BufferedInputStream(stdin); this.stdout = stdout; this.stderr = stderr; this.locale = locale; this.channel = Channel.current(); CmdLineParser p = new CmdLineParser(this); + + // add options from the authenticator + SecurityContext sc = SecurityContextHolder.getContext(); + Authentication old = sc.getAuthentication(); + + CliAuthenticator authenticator = null; + if (shouldPerformAuthentication(auth)) { + authenticator = Hudson.getInstance().getSecurityRealm().createCliAuthenticator(this); + new ClassParser().parse(authenticator,p); + } + try { p.parseArgument(args.toArray(new String[args.size()])); + sc.setAuthentication(authenticator!=null? authenticator.authenticate() : auth); // run the CLI with the right credential return run(); } catch (CmdLineException e) { stderr.println(e.getMessage()); @@ -163,9 +189,31 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { } catch (Exception e) { e.printStackTrace(stderr); return -1; + } finally { + sc.setAuthentication(old); // restore } } + /** + * Determines if the user authentication is attempted through CLI before running this command. + * + *

+ * If your command doesn't require any authentication whatsoever, and if you don't even want to let the user + * authenticate, then override this method to always return false — doing so will result in all the commands + * running as anonymous user credential. + * + *

+ * Note that even if this method returns true, the user can still skip aut + * + * @param auth + * Always non-null. + * If the underlying transport had already performed authentication, this object is something other than + * {@link Hudson#ANONYMOUS}. + */ + protected boolean shouldPerformAuthentication(Authentication auth) { + return auth==Hudson.ANONYMOUS; + } + /** * Executes the command, and return the exit code. * diff --git a/core/src/main/java/hudson/cli/CliManagerImpl.java b/core/src/main/java/hudson/cli/CliManagerImpl.java index f04fd407d5..7eb6db3575 100644 --- a/core/src/main/java/hudson/cli/CliManagerImpl.java +++ b/core/src/main/java/hudson/cli/CliManagerImpl.java @@ -51,12 +51,13 @@ import java.io.Serializable; */ public class CliManagerImpl implements CliEntryPoint, Serializable { /** - * CLI should be executed under this credential. + * If the transport has already authenticated this CLI command execution, a valid {@link Authentication} object. + * Otherwise {@link Hudson#ANONYMOUS} */ private final Authentication auth; public CliManagerImpl(Authentication auth) { - this.auth = auth; + this.auth = auth!=null ? auth : Hudson.ANONYMOUS; } public int main(List args, Locale locale, InputStream stdin, OutputStream stdout, OutputStream stderr) { @@ -71,14 +72,8 @@ public class CliManagerImpl implements CliEntryPoint, Serializable { String subCmd = args.get(0); CLICommand cmd = CLICommand.clone(subCmd); if(cmd!=null) { - Authentication old = SecurityContextHolder.getContext().getAuthentication(); - SecurityContextHolder.getContext().setAuthentication(auth); - try { - // execute the command, do so with the originator of the request as the principal - return cmd.main(args.subList(1,args.size()),locale, stdin, out, err); - } finally { - SecurityContextHolder.getContext().setAuthentication(old); - } + // execute the command, do so with the originator of the request as the principal + return cmd.main(args.subList(1,args.size()),locale, stdin, out, err,auth); } err.println("No such command: "+subCmd); diff --git a/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java b/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java index 7eb776ff8a..1fdf1385f7 100644 --- a/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java +++ b/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java @@ -1,19 +1,26 @@ package hudson.security; import groovy.lang.Binding; +import hudson.FilePath; +import hudson.cli.CLICommand; import hudson.model.Hudson; import hudson.tasks.MailAddressResolver; import hudson.util.spring.BeanBuilder; +import org.acegisecurity.Authentication; import org.acegisecurity.AuthenticationException; import org.acegisecurity.AuthenticationManager; +import org.acegisecurity.BadCredentialsException; import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UserDetailsService; import org.acegisecurity.userdetails.UsernameNotFoundException; +import org.kohsuke.args4j.Option; import org.springframework.dao.DataAccessException; import org.springframework.web.context.WebApplicationContext; +import java.io.IOException; + /** * Partial implementation of {@link SecurityRealm} for username/password based authentication. * This is a convenience base class if all you are trying to do is to check the given username @@ -40,6 +47,35 @@ public abstract class AbstractPasswordBasedSecurityRealm extends SecurityRealm i findBean(AuthenticationManager.class, context),this); } + @Override + public CliAuthenticator createCliAuthenticator(final CLICommand command) { + return new CliAuthenticator() { + @Option(name="--username",usage="User name to authenticate yourself to Hudson") + public String userName; + + @Option(name="--password",usage="Password for authentication. Note that passing a password in arguments is insecure.") + public String password; + + @Option(name="--password-file",usage="File that contains the password") + public String passwordFile; + + public Authentication authenticate() throws AuthenticationException { + if (userName==null) + return Hudson.ANONYMOUS; // no authentication parameter. run as anonymous + + if (passwordFile!=null) + try { + password = new FilePath(command.channel,passwordFile).readToString().trim(); + } catch (IOException e) { + throw new BadCredentialsException("Failed to read "+passwordFile,e); + } + + UserDetails d = AbstractPasswordBasedSecurityRealm.this.authenticate(userName, password); + return new UsernamePasswordAuthenticationToken(d, password, d.getAuthorities()); + } + }; + } + /** * Authenticate a login attempt. * This method is the heart of a {@link AbstractPasswordBasedSecurityRealm}. diff --git a/core/src/main/java/hudson/security/CliAuthenticator.java b/core/src/main/java/hudson/security/CliAuthenticator.java new file mode 100644 index 0000000000..385e679973 --- /dev/null +++ b/core/src/main/java/hudson/security/CliAuthenticator.java @@ -0,0 +1,78 @@ +/* + * The MIT License + * + * Copyright (c) 2004-2010, Oracle Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package hudson.security; + +import hudson.cli.CLICommand; +import hudson.model.Hudson; +import org.acegisecurity.Authentication; +import org.acegisecurity.AuthenticationException; +import org.kohsuke.args4j.Argument; +import org.kohsuke.args4j.CmdLineParser; +import org.kohsuke.args4j.Option; + +/** + * Handles authentication for CLI commands. + * + *

+ * {@link CliAuthenticator} is used to authenticate an invocation of the CLI command, so that + * the thread carries the correct {@link Authentication} that represents the user who's invoking the command. + * + *

Lifecycle

+ *

+ * Each time a CLI command is invoked, {@link SecurityRealm#createCliAuthenticator(CLICommand)} is called + * to allocate a fresh {@link CliAuthenticator} object. + * + *

+ * The {@link Option} and {@link Argument} annotations on the returned {@link CliAuthenticator} instance are + * scanned and added into the {@link CmdLineParser}, then that parser is used to parse command line arguments. + * This means subtypes can define fields/setters with those annotations to define authentication-specific options + * to CLI commands. + * + *

+ * Once the arguments and options are parsed and populated, {@link #authenticate()} method is called to + * perform the authentications. If the authentication succeeds, this method returns an {@link Authentication} + * instance that represents the user. If the authentication fails, this method throws {@link AuthenticationException}. + * To authenticate, the method can use parsed argument/option values, as well as interacting with the client + * via {@link CLICommand} by using its stdin/stdout and its channel (for example, if you want to interactively prompt + * a password, you can do so by using {@link CLICommand#channel}.) + * + *

+ * Many commands do not require any authentication (for example, the "help" command), and still more commands + * can be run successfully with the anonymous permission. So the authenticator should normally allow unauthenticated + * CLI command invocations. For those, return {@link Hudson#ANONYMOUS} from the {@link #authenticate()} method. + * + *

Example

+ *

+ * For a complete example, see the implementation of + * {@link AbstractPasswordBasedSecurityRealm#createCliAuthenticator(CLICommand)} + * + * @author Kohsuke Kawaguchi + * @since 1.350 + */ +public abstract class CliAuthenticator { + /** + * Authenticates the CLI invocation. See class javadoc for the semantics. + */ + public abstract Authentication authenticate() throws AuthenticationException; +} diff --git a/core/src/main/java/hudson/security/SecurityRealm.java b/core/src/main/java/hudson/security/SecurityRealm.java index 228a64f9d6..24c7e1bf94 100644 --- a/core/src/main/java/hudson/security/SecurityRealm.java +++ b/core/src/main/java/hudson/security/SecurityRealm.java @@ -29,6 +29,7 @@ import groovy.lang.Binding; import hudson.ExtensionPoint; import hudson.DescriptorExtensionList; import hudson.Extension; +import hudson.cli.CLICommand; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Hudson; @@ -141,6 +142,24 @@ public abstract class SecurityRealm implements Describable, Exten */ public abstract SecurityComponents createSecurityComponents(); + /** + * Creates a {@link CliAuthenticator} object that authenticates an invocation of a CLI command. + * See {@link CliAuthenticator} for more details. + * + * @param command + * The command about to be executed. + * @return + * never null. By default, this method returns a no-op authenticator that always authenticates + * the session as an anonymous user. + */ + public CliAuthenticator createCliAuthenticator(CLICommand command) { + return new CliAuthenticator() { + public Authentication authenticate() { + return Hudson.ANONYMOUS; + } + }; + } + /** * {@inheritDoc} * diff --git a/test/src/test/java/hudson/security/CliAuthenticationTest.java b/test/src/test/java/hudson/security/CliAuthenticationTest.java new file mode 100644 index 0000000000..7cc013c2bf --- /dev/null +++ b/test/src/test/java/hudson/security/CliAuthenticationTest.java @@ -0,0 +1,66 @@ +package hudson.security; + +import hudson.cli.CLICommand; +import hudson.cli.CliManagerImpl; +import hudson.model.Hudson; +import org.acegisecurity.Authentication; +import org.acegisecurity.AuthenticationException; +import org.acegisecurity.BadCredentialsException; +import org.acegisecurity.GrantedAuthority; +import org.acegisecurity.userdetails.User; +import org.acegisecurity.userdetails.UserDetails; +import org.acegisecurity.userdetails.UsernameNotFoundException; +import org.jvnet.hudson.test.HudsonTestCase; +import org.jvnet.hudson.test.TestExtension; +import org.springframework.dao.DataAccessException; +import junit.framework.Assert; + +import java.util.Arrays; +import java.util.Locale; + +/** + * @author Kohsuke Kawaguchi + */ +public class CliAuthenticationTest extends HudsonTestCase { + public void test1() throws Exception { + // dummy security realm that authenticates when username==password + hudson.setSecurityRealm(new AbstractPasswordBasedSecurityRealm() { + @Override + protected UserDetails authenticate(String username, String password) throws AuthenticationException { + if (username.equals(password)) + return new User(username,password,true,true,true,true,new GrantedAuthority[]{AUTHENTICATED_AUTHORITY}); + throw new BadCredentialsException(username); + } + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { + throw new UsernameNotFoundException(username); + } + + @Override + public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException { + throw new UsernameNotFoundException(groupname); + } + }); + + assertEquals(0,new CliManagerImpl(null).main(Arrays.asList("test","--username","abc","--password","abc"), + Locale.ENGLISH, System.in, System.out, System.err)); + } + + @TestExtension + public static class TestCommand extends CLICommand { + @Override + public String getShortDescription() { + return "test command"; + } + + @Override + protected int run() throws Exception { + Authentication auth = Hudson.getInstance().getAuthentication(); + Assert.assertNotSame(Hudson.ANONYMOUS,auth); + Assert.assertEquals("abc", auth.getName()); + return 0; + } + } + +}