Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 48 additions & 46 deletions core/src/main/java/hudson/cli/CLICommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
import hudson.Functions;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.OptionHandlerExtension;
import hudson.cli.listeners.CliContext;
import hudson.cli.listeners.CliListener;
import hudson.remoting.Channel;
import hudson.security.SecurityRealm;
import java.io.BufferedInputStream;
Expand All @@ -48,9 +50,6 @@
import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import jenkins.util.SystemProperties;
import org.jvnet.hudson.annotation_indexer.Index;
Expand Down Expand Up @@ -239,70 +238,75 @@ public int main(List<String> args, Locale locale, InputStream stdin, PrintStream
this.locale = locale;
CmdLineParser p = getCmdLineParser();

final CliContext context = new CliContext(getName(), args.size(), getTransportAuthentication2());

// add options from the authenticator
SecurityContext sc = null;
Authentication old = null;
Authentication auth;
try {
// TODO as in CLIRegisterer this may be doing too much work
sc = SecurityContextHolder.getContext();
old = sc.getAuthentication();

sc.setAuthentication(auth = getTransportAuthentication2());
sc.setAuthentication(getTransportAuthentication2());

if (!(this instanceof HelpCommand || this instanceof WhoAmICommand))
Jenkins.get().checkPermission(Jenkins.READ);
p.parseArgument(args.toArray(new String[0]));
LOGGER.log(Level.FINE, "Invoking CLI command {0}, with {1} arguments, as user {2}.",
new Object[] {getName(), args.size(), auth.getName()});

CliListener.fireExecution(context);
int res = run();
LOGGER.log(Level.FINE, "Executed CLI command {0}, with {1} arguments, as user {2}, return code {3}",
new Object[] {getName(), args.size(), auth.getName(), res});
CliListener.fireCompleted(context, res);

return res;
} catch (CmdLineException e) {
logFailedCommandAndPrintExceptionErrorMessage(args, e);
printUsage(stderr, p);
return 2;
} catch (IllegalStateException e) {
logFailedCommandAndPrintExceptionErrorMessage(args, e);
return 4;
} catch (IllegalArgumentException e) {
logFailedCommandAndPrintExceptionErrorMessage(args, e);
return 3;
} catch (AbortException e) {
logFailedCommandAndPrintExceptionErrorMessage(args, e);
return 5;
} catch (AccessDeniedException e) {
logFailedCommandAndPrintExceptionErrorMessage(args, e);
return 6;
} catch (BadCredentialsException e) {
// to the caller, we can't reveal whether the user didn't exist or the password didn't match.
// do that to the server log instead
String id = UUID.randomUUID().toString();
logAndPrintError(e, "Bad Credentials. Search the server log for " + id + " for more details.",
"CLI login attempt failed: " + id, Level.INFO);
return 7;
} catch (Throwable e) {
String errorMsg = "Unexpected exception occurred while performing " + getName() + " command.";
logAndPrintError(e, errorMsg, errorMsg, Level.WARNING);
Functions.printStackTrace(e, stderr);
return 1;
int exitCode = handleException(e, context, p);
CliListener.fireError(context, exitCode, e);
return exitCode;
} finally {
if (sc != null)
sc.setAuthentication(old); // restore
}
}

private void logFailedCommandAndPrintExceptionErrorMessage(List<String> args, Throwable e) {
Authentication auth = getTransportAuthentication2();
String logMessage = String.format("Failed call to CLI command %s, with %d arguments, as user %s.",
getName(), args.size(), auth != null ? auth.getName() : "<unknown>");

logAndPrintError(e, e.getMessage(), logMessage, Level.FINE);
/**
* Determines command stderr output and return the exit code as described on {@link #main(List, Locale, InputStream, PrintStream, PrintStream)}
* */
protected int handleException(Throwable e, CliContext context, CmdLineParser p) {
int exitCode;
if (e instanceof CmdLineException) {
exitCode = 2;
printError(e.getMessage());
printUsage(stderr, p);
} else if (e instanceof IllegalArgumentException) {
exitCode = 3;
printError(e.getMessage());
} else if (e instanceof IllegalStateException) {
exitCode = 4;
printError(e.getMessage());
} else if (e instanceof AbortException) {
exitCode = 5;
printError(e.getMessage());
} else if (e instanceof AccessDeniedException) {
exitCode = 6;
printError(e.getMessage());
} else if (e instanceof BadCredentialsException) {
Copy link
Copy Markdown
Contributor Author

@apuig apuig Mar 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like BadCredentialsException is not longer possible inside CLICommand#main, note {set/get}TransportAuth2:

  • for HTTP or WebSocket the BadCredential is thrown/handled in the filters. When using command line -auth user:pass basic auth : BasicHeaderAuthenticator / AbstractUserAuth.

  • for SSH auth errors (not a BadCredentials) is also handled before executing the command (PublicKeyAuthenticatorImpl / UserAuthNamedFactory).

b1803a9 I can't find CliAuthenticationTest, may not apply anymore.

EDIT: this branch is only possible if a CLICommand implementation throws a BadCredentialsException,

exitCode = 7;
// to the caller, we can't reveal whether the user didn't exist or the password didn't match.
// do that to the server log instead
printError(
"Bad Credentials. Search the server log for " + context.getCorrelationId() + " for more details.");
} else {
exitCode = 1;
printError("Unexpected exception occurred while performing " + getName() + " command.");
Functions.printStackTrace(e, stderr);
}
return exitCode;
}

private void logAndPrintError(Throwable e, String errorMessage, String logMessage, Level logLevel) {
LOGGER.log(logLevel, logMessage, e);


private void printError(String errorMessage) {
this.stderr.println();
this.stderr.println("ERROR: " + errorMessage);
}
Expand Down Expand Up @@ -538,8 +542,6 @@ public static CLICommand clone(String name) {
return null;
}

private static final Logger LOGGER = Logger.getLogger(CLICommand.class.getName());

private static final ThreadLocal<CLICommand> CURRENT_COMMAND = new ThreadLocal<>();

/*package*/ static CLICommand setCurrent(CLICommand cmd) {
Expand Down
60 changes: 12 additions & 48 deletions core/src/main/java/hudson/cli/declarative/CLIRegisterer.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@
import static java.util.logging.Level.SEVERE;

import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.AbortException;
import hudson.Extension;
import hudson.ExtensionComponent;
import hudson.ExtensionFinder;
import hudson.Functions;
import hudson.Util;
import hudson.cli.CLICommand;
import hudson.cli.CloneableCLICommand;
import hudson.cli.listeners.CliContext;
import hudson.cli.listeners.CliListener;
import hudson.model.Hudson;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -49,19 +49,14 @@
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Stack;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionRefreshException;
import jenkins.model.Jenkins;
import org.jvnet.hudson.annotation_indexer.Index;
import org.jvnet.localizer.ResourceBundleHolder;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.ParserProperties;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
Expand Down Expand Up @@ -202,6 +197,8 @@ public int main(List<String> args, Locale locale, InputStream stdin, PrintStream

List<MethodBinder> binders = new ArrayList<>();

final CliContext context = new CliContext(getName(), args.size(), getTransportAuthentication2());

CmdLineParser parser = bindMethod(binders);
try {
// TODO this could probably use ACL.as; why is it calling SecurityContext.setAuthentication rather than SecurityContextHolder.setContext?
Expand All @@ -215,15 +212,16 @@ public int main(List<String> args, Locale locale, InputStream stdin, PrintStream
sc.setAuthentication(auth); // run the CLI with the right credential
jenkins.checkPermission(Jenkins.READ);

CliListener.fireExecution(context);

// resolve them
Object instance = null;
for (MethodBinder binder : binders)
instance = binder.call(instance);

if (instance instanceof Integer)
return (Integer) instance;
else
return 0;
Integer exitCode = (instance instanceof Integer) ? (Integer) instance : 0;
CliListener.fireCompleted(context, exitCode);
return exitCode;
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof Exception)
Expand All @@ -232,47 +230,13 @@ public int main(List<String> args, Locale locale, InputStream stdin, PrintStream
} finally {
sc.setAuthentication(old); // restore
}
} catch (CmdLineException e) {
printError(e.getMessage());
printUsage(stderr, parser);
return 2;
} catch (IllegalStateException e) {
printError(e.getMessage());
return 4;
} catch (IllegalArgumentException e) {
printError(e.getMessage());
return 3;
} catch (AbortException e) {
printError(e.getMessage());
return 5;
} catch (AccessDeniedException e) {
printError(e.getMessage());
return 6;
} catch (BadCredentialsException e) {
// to the caller, we can't reveal whether the user didn't exist or the password didn't match.
// do that to the server log instead
String id = UUID.randomUUID().toString();
logAndPrintError(e, "Bad Credentials. Search the server log for " + id + " for more details.",
"CLI login attempt failed: " + id, Level.INFO);
return 7;
} catch (Throwable e) {
final String errorMsg = "Unexpected exception occurred while performing " + getName() + " command.";
logAndPrintError(e, errorMsg, errorMsg, Level.WARNING);
Functions.printStackTrace(e, stderr);
return 1;
int exitCode = handleException(e, context, parser);
CliListener.fireError(context, exitCode, e);
return exitCode;
}
}

private void printError(String errorMessage) {
this.stderr.println();
this.stderr.println("ERROR: " + errorMessage);
}

private void logAndPrintError(Throwable e, String errorMessage, String logMessage, Level logLevel) {
LOGGER.log(logLevel, logMessage, e);
printError(errorMessage);
}

@Override
protected int run() throws Exception {
throw new UnsupportedOperationException();
Expand Down
62 changes: 62 additions & 0 deletions core/src/main/java/hudson/cli/listeners/CliContext.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package hudson.cli.listeners;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import java.util.UUID;
import org.springframework.security.core.Authentication;

/**
* Holds information of a command execution. Same instance is used to all {@link CliListener} invocations.
* Use `correlationId` in order to group related events.
*
* @since TODO
*/
public class CliContext {
private final String correlationId = UUID.randomUUID().toString();
private final String command;
private final int argsSize;
private final Authentication auth;

/**
* @param command The command being executed.
* @param argsSize Number of arguments passed to the command.
* @param auth Authenticated user performing the execution.
*/
public CliContext(@NonNull String command, int argsSize, @Nullable Authentication auth) {
this.command = command;
this.argsSize = argsSize;
this.auth = auth;
}

/**
* @return Correlate this command event to other, related command events.
*/
@NonNull
public String getCorrelationId() {
return correlationId;
}

/**
* @return Command being executed.
*/
@NonNull
public String getCommand() {
return command;
}

/**
* @return Number of arguments passed to the command.
*/
public int getArgsSize() {
return argsSize;
}

/**
* @return Authenticated user performing the execution.
*/
@CheckForNull
public Authentication getAuth() {
return auth;
}
}
Loading