Skip to content

Commit

Permalink
Merge pull request #217 from slide/authentication_tests
Browse files Browse the repository at this point in the history
Authentication tests
  • Loading branch information
slide authored Sep 18, 2020
2 parents 18191e9 + d0cb6f5 commit f995fa0
Show file tree
Hide file tree
Showing 12 changed files with 335 additions and 196 deletions.
12 changes: 12 additions & 0 deletions src/main/java/hudson/plugins/emailext/ExtendedEmailPublisher.java
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,10 @@ private boolean _perform(AbstractBuild<?, ?> build, Launcher launcher, BuildList
boolean sendMail(ExtendedEmailPublisherContext context) {
try {
MimeMessage msg = createMail(context);
if(msg == null) {
context.getListener().getLogger().println("Could not create MimeMessage");
return false;
}
debug(context.getListener().getLogger(), "Successfully created MimeMessage");
Address[] allRecipients = msg.getAllRecipients();
int retries = 0;
Expand All @@ -473,6 +477,10 @@ boolean sendMail(ExtendedEmailPublisherContext context) {

ExtendedEmailPublisherDescriptor descriptor = getDescriptor();
Session session = descriptor.createSession(from);
if(session == null) {
context.getListener().getLogger().println("Could not create session");
return false;
}
// emergency reroute might have modified recipients:
allRecipients = msg.getAllRecipients();
// all email addresses are of type "rfc822", so just take first one:
Expand Down Expand Up @@ -718,6 +726,10 @@ private MimeMessage createMail(ExtendedEmailPublisherContext context) throws Mes
String charset = descriptor.getCharset();

Session session = descriptor.createSession(from);
if(session == null) {
context.getListener().getLogger().println("Could not create session");
return null;
}
MimeMessage msg = new MimeMessage(session);

InternetAddress fromAddress = new InternetAddress(descriptor.getAdminAddress());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand Down Expand Up @@ -177,6 +178,13 @@ public final class ExtendedEmailPublisherDescriptor extends BuildStepDescriptor<
private transient Secret smtpAuthPassword;
private transient boolean useSsl = false;

private Function<MailAccount, Authenticator> authenticatorProvider = (acc) -> new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(acc.getSmtpUsername(), Secret.toString(acc.getSmtpPassword()));
}
};

private Object readResolve(){
if(smtpHost != null) mailAccount.setSmtpHost(smtpHost);
if(smtpPort != null) mailAccount.setSmtpPort(smtpPort);
Expand All @@ -195,15 +203,15 @@ public ExtendedEmailPublisherDescriptor() {
defaultSubject = ExtendedEmailPublisher.DEFAULT_SUBJECT_TEXT;
emergencyReroute = ExtendedEmailPublisher.DEFAULT_EMERGENCY_REROUTE_TEXT;
}

if(mailAccount == null) {
mailAccount = new MailAccount();
mailAccount.setAddress(getAdminAddress());
}

mailAccount.setDefaultAccount(true);
}

@Initializer(after = InitMilestone.EXTENSIONS_AUGMENTED, before = InitMilestone.JOB_LOADED)
public static void autoConfigure() {
ExtendedEmailPublisherDescriptor descriptor = ExtendedEmailPublisher.descriptor();
Expand Down Expand Up @@ -275,7 +283,7 @@ public Session createSession(String from) throws MessagingException {
}

if(!acc.isValid()) {
// what do we want to do here?
return null;
}

if (acc.getSmtpHost() != null) {
Expand Down Expand Up @@ -332,13 +340,7 @@ private Authenticator getAuthenticator(final MailAccount acc) {
if (acc == null || StringUtils.isBlank(acc.getSmtpUsername())) {
return null;
}
return new Authenticator() {

@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(acc.getSmtpUsername(), Secret.toString(acc.getSmtpPassword()));
}
};
return authenticatorProvider.apply(acc);
}

public String getHudsonUrl() {
Expand Down Expand Up @@ -630,6 +632,7 @@ public void setAllowUnregisteredEnabled(boolean enabled) {
this.enableAllowUnregistered = enabled;
}

@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
Expand Down Expand Up @@ -804,4 +807,12 @@ Permission getJenkinsManageOrAdmin() {
}
return manage;
}

Function<MailAccount, Authenticator> getAuthenticatorProvider() {
return authenticatorProvider;
}

void setAuthenticatorProvider(Function<MailAccount, Authenticator> authenticatorProvider) {
this.authenticatorProvider = authenticatorProvider;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,14 @@ public class AttachmentUtilsTest {
public final JenkinsRule j = new JenkinsRule() {
@Override
public void before() throws Throwable {
Mailbox.clearAll();
super.before();
Mailbox.clearAll();
ExtendedEmailPublisherDescriptor descriptor = ExtendedEmailPublisher.descriptor();
descriptor.setMailAccount(new MailAccount() {
{
setSmtpHost("smtp.notreal.com");
}
});
}
};

Expand Down
6 changes: 6 additions & 0 deletions src/test/java/hudson/plugins/emailext/EmailExtStepTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ public class EmailExtStepTest {
@Override
public void before() throws Throwable {
super.before();
ExtendedEmailPublisherDescriptor descriptor = ExtendedEmailPublisher.descriptor();
descriptor.setMailAccount(new MailAccount() {
{
setSmtpHost("smtp.notreal.com");
}
});
Mailbox.clearAll();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,19 @@
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;

import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.mail.Authenticator;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.oneOf;
Expand Down Expand Up @@ -85,7 +91,7 @@ public void testGlobalConfigDefaultState() throws Exception {

HtmlTextInput allowedDomains = page.getElementByName("_.allowedDomains");
assertNotNull("Allowed Domains should be present", allowedDomains);
assertEquals("Allowed Domains should be blang by default",
assertEquals("Allowed Domains should be blank by default",
"", allowedDomains.getText());

HtmlTextInput excludedRecipients = page.getElementByName("_.excludedCommitters");
Expand Down Expand Up @@ -349,4 +355,64 @@ private Permission getJenkinsManage() throws NoSuchMethodException, IllegalAcces
return (Permission) ReflectionUtils.getPublicProperty(Jenkins.get(), "MANAGE");
}

@Test
@Issue("JENKINS-63311")
public void authenticatorIsCreatedWhenUsernameAndPasswordAreFilledOut() throws Exception {
ExtendedEmailPublisherDescriptor descriptor = j.jenkins.getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
String from = "test@example.com";
MailAccount ma = new MailAccount();
ma.setAddress(from);
ma.setSmtpHost("smtp.example.com");
ma.setSmtpPort("25");
ma.setSmtpUsername("mail_user");
ma.setSmtpPassword("smtpPassword");
assertTrue(ma.isValid());
descriptor.setAddAccounts(Collections.singletonList(ma));
Function<MailAccount, Authenticator> authenticatorProvider = Mockito.mock(Function.class);
descriptor.setAuthenticatorProvider(authenticatorProvider);
descriptor.createSession(from);
ArgumentCaptor<MailAccount> mailAccountCaptor = ArgumentCaptor.forClass(MailAccount.class);
Mockito.verify(authenticatorProvider, Mockito.times(1)).apply(mailAccountCaptor.capture());
assertNotNull(mailAccountCaptor.getValue());
}

@Test
@Issue("JENKINS-63311")
public void authenticatorIsCreatedWhenUsernameIsFilledOutButPasswordIsNull() throws Exception {
ExtendedEmailPublisherDescriptor descriptor = j.jenkins.getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
String from = "test@example.com";
MailAccount ma = new MailAccount();
ma.setAddress(from);
ma.setSmtpHost("smtp.example.com");
ma.setSmtpPort("25");
ma.setSmtpUsername("mail_user");
ma.setSmtpPassword((String) null);
descriptor.setAddAccounts(Collections.singletonList(ma));
Function<MailAccount, Authenticator> authenticatorProvider = Mockito.mock(Function.class);
descriptor.setAuthenticatorProvider(authenticatorProvider);
descriptor.createSession(from);
ArgumentCaptor<MailAccount> mailAccountCaptor = ArgumentCaptor.forClass(MailAccount.class);
Mockito.verify(authenticatorProvider, Mockito.times(1)).apply(mailAccountCaptor.capture());
assertNotNull(mailAccountCaptor.getValue());
}

@Test
@Issue("JENKINS-63311")
public void noAuthenticatorIsCreatedWhenUsernameIsBlank() throws Exception {
ExtendedEmailPublisherDescriptor descriptor = j.jenkins.getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
String from = "test@example.com";
MailAccount ma = new MailAccount();
ma.setAddress(from);
ma.setSmtpHost("smtp.example.com");
ma.setSmtpPort("25");
ma.setSmtpUsername(" ");
ma.setSmtpPassword("smtpPassword");
descriptor.setAddAccounts(Collections.singletonList(ma));
Function<MailAccount, Authenticator> authenticatorProvider = Mockito.mock(Function.class);
descriptor.setAuthenticatorProvider(authenticatorProvider);
descriptor.createSession(from);
ArgumentCaptor<MailAccount> mailAccountCaptor = ArgumentCaptor.forClass(MailAccount.class);
Mockito.verify(authenticatorProvider, Mockito.never()).apply(mailAccountCaptor.capture());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -35,31 +35,38 @@ public class ExtendedEmailPublisherMatrixTest {

private ExtendedEmailPublisher publisher;
private MatrixProject project;
private List<DumbSlave> slaves;
private List<DumbSlave> agents;

@Rule
public JenkinsRule j = new JenkinsRule() {
@Override
public void before() throws Throwable {
super.before();

ExtendedEmailPublisherDescriptor descriptor = ExtendedEmailPublisher.descriptor();
descriptor.setMailAccount(new MailAccount() {
{
setSmtpHost("smtp.notreal.com");
}
});

publisher = new ExtendedEmailPublisher();
publisher.defaultSubject = "%DEFAULT_SUBJECT";
publisher.defaultContent = "%DEFAULT_CONTENT";
publisher.attachBuildLog = false;

project = j.jenkins.createProject(MatrixProject.class, "Foo");
project.getPublishersList().add( publisher );
slaves = new ArrayList<>();
slaves.add(createOnlineSlave(new LabelAtom("success-slave1")));
slaves.add(createOnlineSlave(new LabelAtom("success-slave2")));
slaves.add(createOnlineSlave(new LabelAtom("success-slave3")));
agents = new ArrayList<>();
agents.add(createOnlineSlave(new LabelAtom("success-agent1")));
agents.add(createOnlineSlave(new LabelAtom("success-agent2")));
agents.add(createOnlineSlave(new LabelAtom("success-agent3")));
}

@Override
public void after() throws Exception {
super.after();
slaves.clear();
agents.clear();
Mailbox.clearAll();
}
};
Expand All @@ -81,8 +88,8 @@ public void testPreBuildMatrixBuildSendParentOnly() throws Exception {
}

@Test
public void testPreBuildMatrixBuildSendSlavesOnly() throws Exception{
addSlaveToProject(0,1,2);
public void testPreBuildMatrixBuildSendAgentsOnly() throws Exception{
addAgentToProject(0,1,2);
List<RecipientProvider> recProviders = Collections.emptyList();
publisher.setMatrixTriggerMode(MatrixTriggerMode.ONLY_CONFIGURATIONS);
PreBuildTrigger trigger = new PreBuildTrigger(recProviders, "$DEFAULT_RECIPIENTS",
Expand All @@ -97,8 +104,8 @@ public void testPreBuildMatrixBuildSendSlavesOnly() throws Exception{
}

@Test
public void testPreBuildMatrixBuildSendSlavesAndParent() throws Exception {
addSlaveToProject(0,1);
public void testPreBuildMatrixBuildSendAgentsAndParent() throws Exception {
addAgentToProject(0,1);
List<RecipientProvider> recProviders = Collections.emptyList();
publisher.setMatrixTriggerMode(MatrixTriggerMode.BOTH);
PreBuildTrigger trigger = new PreBuildTrigger(recProviders, "$DEFAULT_RECIPIENTS",
Expand All @@ -116,7 +123,7 @@ public void testPreBuildMatrixBuildSendSlavesAndParent() throws Exception {
public void testAttachBuildLogForAllAxes() throws Exception {
publisher.setMatrixTriggerMode(MatrixTriggerMode.ONLY_PARENT);
publisher.attachBuildLog = true;
addSlaveToProject(0,1,2);
addAgentToProject(0,1,2);
List<RecipientProvider> recProviders = Collections.emptyList();
AlwaysTrigger trigger = new AlwaysTrigger(recProviders, "$DEFAULT_RECIPIENTS",
"$DEFAULT_REPLYTO", "$DEFAULT_SUBJECT", "$DEFAULT_CONTENT", "", 0, "project");
Expand Down Expand Up @@ -157,11 +164,11 @@ private void addEmailType( EmailTrigger trigger ) {
}} );
}

private void addSlaveToProject(int ... slaveInxes ) throws IOException {
private void addAgentToProject(int ... agentInxes) throws IOException {
AxisList list = new AxisList();
List<String> values = new LinkedList<>();
for (int slaveInx : slaveInxes) {
values.add(slaves.get(slaveInx).getLabelString());
for (int agentInx : agentInxes) {
values.add(agents.get(agentInx).getLabelString());
}
list.add(new Axis("label",values));
project.setAxes(list);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,13 @@ public class ExtendedEmailPublisherTest {

@Before
public void before() throws Throwable {
ExtendedEmailPublisherDescriptor descriptor = ExtendedEmailPublisher.descriptor();
descriptor.setMailAccount(new MailAccount() {
{
setSmtpHost("smtp.notreal.com");
}
});

publisher = new ExtendedEmailPublisher();
publisher.defaultSubject = "%DEFAULT_SUBJECT";
publisher.defaultContent = "%DEFAULT_CONTENT";
Expand Down Expand Up @@ -1146,7 +1153,7 @@ public void testAttachBuildLog() throws Exception {
public void testAdditionalAccounts() throws Exception {
j.createWebClient().executeOnServer(new Callable<Object>() {
public Void call() throws Exception {
ExtendedEmailPublisherDescriptor descriptor = new ExtendedEmailPublisherDescriptor();
ExtendedEmailPublisherDescriptor descriptor = ExtendedEmailPublisher.descriptor();
descriptor.setSmtpServer("smtp.test0.com");
descriptor.setSmtpPort("587");
descriptor.setAdvProperties("mail.smtp.ssl.trust=test0.com");
Expand Down
1 change: 0 additions & 1 deletion src/test/java/hudson/plugins/emailext/MailAccountTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,4 @@ public void testIsValidAuthConfig() {
MailAccount account = new MailAccount(obj);
assertTrue(account.isValid());
}

}
Loading

0 comments on commit f995fa0

Please sign in to comment.