Skip to content

Commit

Permalink
Adjusting expiration time in expectations
Browse files Browse the repository at this point in the history
  • Loading branch information
johanah29 committed Sep 25, 2024
1 parent a67e575 commit cf3983e
Show file tree
Hide file tree
Showing 21 changed files with 1,056 additions and 901 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,16 @@ private void computeExpectations(@NotNull final List<InjectExpectation> expectat
List<InjectExpectation> expectationAssets = expectations.stream().toList();
expectationAssets.forEach((expectation) -> {
Long userExpirationTime = expectation.getExpirationTime();
if (userExpirationTime != null) {
// Maximum time for detection
if (isExpired(expectation, Math.toIntExact(userExpirationTime / 60))) {
String result = computeFailedMessage(expectation.getType());
this.injectExpectationService.computeExpectation(
expectation,
this.config.getId(),
"collector",
PRODUCT_NAME,
result,
false
);
}
if (isExpired(expectation, Math.toIntExact(userExpirationTime / 60))) {
String result = computeFailedMessage(expectation.getType());
this.injectExpectationService.computeExpectation(
expectation,
this.config.getId(),
"collector",
PRODUCT_NAME,
result,
false
);
}

});
Expand All @@ -62,19 +59,16 @@ private void computeExpectationsForAssets(@NotNull final List<InjectExpectation>
List<InjectExpectation> expectationAssets = expectations.stream().filter(e -> e.getAsset() != null).toList();
expectationAssets.forEach((expectation) -> {
Long userExpirationTime = expectation.getExpirationTime();
if (userExpirationTime != null) {
// Maximum time for detection
if (isExpired(expectation, Math.toIntExact(userExpirationTime / 60))) {
String result = computeFailedMessage(expectation.getType());
this.injectExpectationService.computeExpectation(
expectation,
this.config.getId(),
"collector",
PRODUCT_NAME,
result,
false
);
}
if (isExpired(expectation, Math.toIntExact(userExpirationTime / 60))) {
String result = computeFailedMessage(expectation.getType());
this.injectExpectationService.computeExpectation(
expectation,
this.config.getId(),
"collector",
PRODUCT_NAME,
result,
false
);
}

});
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -32,99 +32,99 @@
@Component(ChallengeContract.TYPE)
public class ChallengeExecutor extends Injector {

@Resource
private OpenBASConfig openBASConfig;
@Resource
private OpenBASConfig openBASConfig;

private ChallengeRepository challengeRepository;
private ChallengeRepository challengeRepository;

private EmailService emailService;
private EmailService emailService;

@Value("${openbas.mail.imap.enabled}")
private boolean imapEnabled;
@Value("${openbas.mail.imap.enabled}")
private boolean imapEnabled;

@Autowired
public void setChallengeRepository(ChallengeRepository challengeRepository) {
this.challengeRepository = challengeRepository;
}
@Autowired
public void setChallengeRepository(ChallengeRepository challengeRepository) {
this.challengeRepository = challengeRepository;
}

@Autowired
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}
@Autowired
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}

private String buildChallengeUri(ExecutionContext context, Exercise exercise, Challenge challenge) {
String userId = context.getUser().getId();
String challengeId = challenge.getId();
String exerciseId = exercise.getId();
return openBASConfig.getBaseUrl() + "/challenges/" + exerciseId + "?user=" + userId + "&challenge=" + challengeId;
}
private String buildChallengeUri(ExecutionContext context, Exercise exercise, Challenge challenge) {
String userId = context.getUser().getId();
String challengeId = challenge.getId();
String exerciseId = exercise.getId();
return openBASConfig.getBaseUrl() + "/challenges/" + exerciseId + "?user=" + userId + "&challenge=" + challengeId;
}

@Override
public ExecutionProcess process(@NotNull final Execution execution, @NotNull final ExecutableInject injection) {
try {
ChallengeContent content = contentConvert(injection, ChallengeContent.class);
List<Challenge> challenges = fromIterable(challengeRepository.findAllById(content.getChallenges()));
String contract = injection
.getInjection()
.getInject()
.getInjectorContract()
.map(InjectorContract::getId)
.orElseThrow(() -> new UnsupportedOperationException("Inject does not have a contract"));
@Override
public ExecutionProcess process(@NotNull final Execution execution, @NotNull final ExecutableInject injection) {
try {
ChallengeContent content = contentConvert(injection, ChallengeContent.class);
List<Challenge> challenges = fromIterable(challengeRepository.findAllById(content.getChallenges()));
String contract = injection
.getInjection()
.getInject()
.getInjectorContract()
.map(InjectorContract::getId)
.orElseThrow(() -> new UnsupportedOperationException("Inject does not have a contract"));

if (contract.equals(CHALLENGE_PUBLISH)) {
// Challenge publishing is only linked to execution date of this inject.
String challengeNames = challenges.stream().map(Challenge::getName).collect(Collectors.joining(","));
String publishedMessage = "Challenges (" + challengeNames + ") marked as published";
execution.addTrace(traceSuccess(publishedMessage));
// Send the publication message.
Exercise exercise = injection.getInjection().getExercise();
String from = exercise.getFrom();
List<String> replyTos = exercise.getReplyTos();
List<ExecutionContext> users = injection.getUsers();
List<Document> documents = injection.getInjection().getInject().getDocuments().stream()
.filter(InjectDocument::isAttached).map(InjectDocument::getDocument).toList();
List<DataAttachment> attachments = resolveAttachments(execution, injection, documents);
String message = content.buildMessage(injection, imapEnabled);
boolean encrypted = content.isEncrypted();
users.forEach(userInjectContext -> {
try {
// Put the challenges variables in the injection context
List<ChallengeVariable> challengeVariables = challenges.stream()
.map(challenge -> new ChallengeVariable(challenge.getId(), challenge.getName(),
buildChallengeUri(userInjectContext, exercise, challenge)))
.toList();
userInjectContext.put("challenges", challengeVariables);
// Send the email.
emailService.sendEmail(execution, userInjectContext, from, replyTos, content.getInReplyTo(), encrypted,
content.getSubject(), message, attachments);
} catch (Exception e) {
execution.addTrace(traceError(e.getMessage()));
}
});
// Return expectations
List<Expectation> expectations = new ArrayList<>();
if (!content.getExpectations().isEmpty()) {
expectations.addAll(
content.getExpectations()
.stream()
.flatMap((entry) -> switch (entry.getType()) {
case MANUAL -> Stream.of(
(Expectation) new ManualExpectation(entry.getScore(), entry.getName(), entry.getDescription(), entry.isExpectationGroup())
);
case CHALLENGE -> challenges.stream()
.map(challenge -> (Expectation) new ChallengeExpectation(entry.getScore(), challenge, entry.isExpectationGroup()));
default -> Stream.of();
})
.toList()
);
}
return new ExecutionProcess(false, expectations);
} else {
throw new UnsupportedOperationException("Unknown contract " + contract);
}
} catch (Exception e) {
if (contract.equals(CHALLENGE_PUBLISH)) {
// Challenge publishing is only linked to execution date of this inject.
String challengeNames = challenges.stream().map(Challenge::getName).collect(Collectors.joining(","));
String publishedMessage = "Challenges (" + challengeNames + ") marked as published";
execution.addTrace(traceSuccess(publishedMessage));
// Send the publication message.
Exercise exercise = injection.getInjection().getExercise();
String from = exercise.getFrom();
List<String> replyTos = exercise.getReplyTos();
List<ExecutionContext> users = injection.getUsers();
List<Document> documents = injection.getInjection().getInject().getDocuments().stream()
.filter(InjectDocument::isAttached).map(InjectDocument::getDocument).toList();
List<DataAttachment> attachments = resolveAttachments(execution, injection, documents);
String message = content.buildMessage(injection, imapEnabled);
boolean encrypted = content.isEncrypted();
users.forEach(userInjectContext -> {
try {
// Put the challenges variables in the injection context
List<ChallengeVariable> challengeVariables = challenges.stream()
.map(challenge -> new ChallengeVariable(challenge.getId(), challenge.getName(),
buildChallengeUri(userInjectContext, exercise, challenge)))
.toList();
userInjectContext.put("challenges", challengeVariables);
// Send the email.
emailService.sendEmail(execution, userInjectContext, from, replyTos, content.getInReplyTo(), encrypted,
content.getSubject(), message, attachments);
} catch (Exception e) {
execution.addTrace(traceError(e.getMessage()));
}
});
// Return expectations
List<Expectation> expectations = new ArrayList<>();
if (!content.getExpectations().isEmpty()) {
expectations.addAll(
content.getExpectations()
.stream()
.flatMap((entry) -> switch (entry.getType()) {
case MANUAL -> Stream.of(
(Expectation) new ManualExpectation(entry)
);
case CHALLENGE -> challenges.stream()
.map(challenge -> (Expectation) new ChallengeExpectation(entry, challenge));
default -> Stream.of();
})
.toList()
);
}
return new ExecutionProcess(false, List.of());
return new ExecutionProcess(false, expectations);
} else {
throw new UnsupportedOperationException("Unknown contract " + contract);
}
} catch (Exception e) {
execution.addTrace(traceError(e.getMessage()));
}
return new ExecutionProcess(false, List.of());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ public ExecutionProcess process(@NotNull final Execution execution, @NotNull fin
.stream()
.flatMap((entry) -> switch (entry.getType()) {
case MANUAL -> Stream.of(
(Expectation) new ManualExpectation(entry.getScore(), entry.getName(), entry.getDescription(), entry.isExpectationGroup())
(Expectation) new ManualExpectation(entry)
);
case ARTICLE -> articles.stream()
.map(article -> (Expectation) new ChannelExpectation(entry.getScore(), article, entry.isExpectationGroup()));
.map(article -> (Expectation) new ChannelExpectation(entry, article));
default -> Stream.of();
})
.toList()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}

private void sendMulti(Execution execution, List<ExecutionContext> users, String from, List<String> replyTos, String inReplyTo,
private void sendMulti(Execution execution, List<ExecutionContext> users, String from, List<String> replyTos,
String inReplyTo,
String subject, String message, List<DataAttachment> attachments) {
try {
emailService.sendEmail(execution, users, from, replyTos, inReplyTo, subject, message, attachments);
Expand All @@ -47,19 +48,22 @@ private void sendMulti(Execution execution, List<ExecutionContext> users, String
}
}

private void sendSingle(Execution execution, List<ExecutionContext> users, String from, List<String> replyTos, String inReplyTo,
private void sendSingle(Execution execution, List<ExecutionContext> users, String from, List<String> replyTos,
String inReplyTo,
boolean mustBeEncrypted, String subject, String message, List<DataAttachment> attachments) {
users.forEach(user -> {
try {
emailService.sendEmail(execution, user, from, replyTos, inReplyTo, mustBeEncrypted, subject, message, attachments);
emailService.sendEmail(execution, user, from, replyTos, inReplyTo, mustBeEncrypted, subject, message,
attachments);
} catch (Exception e) {
execution.addTrace(traceError(e.getMessage()));
}
});
}

@Override
public ExecutionProcess process(@NotNull final Execution execution, @NotNull final ExecutableInject injection) throws Exception {
public ExecutionProcess process(@NotNull final Execution execution, @NotNull final ExecutableInject injection)
throws Exception {
Inject inject = injection.getInjection().getInject();
EmailContent content = contentConvert(injection, EmailContent.class);
List<Document> documents = inject.getDocuments().stream().filter(InjectDocument::isAttached)
Expand All @@ -78,18 +82,20 @@ public ExecutionProcess process(@NotNull final Execution execution, @NotNull fin
String from = exercise != null ? exercise.getFrom() : this.openBASConfig.getDefaultMailer();
List<String> replyTos = exercise != null ? exercise.getReplyTos() : List.of(this.openBASConfig.getDefaultReplyTo());
//noinspection SwitchStatementWithTooFewBranches
switch (inject.getInjectorContract().map(InjectorContract::getId).orElseThrow(() -> new UnsupportedOperationException("Inject does not have a contract"))) {
switch (inject.getInjectorContract().map(InjectorContract::getId)
.orElseThrow(() -> new UnsupportedOperationException("Inject does not have a contract"))) {
case EMAIL_GLOBAL -> sendMulti(execution, users, from, replyTos, inReplyTo, subject, message, attachments);
default -> sendSingle(execution, users, from, replyTos, inReplyTo, mustBeEncrypted, subject, message, attachments);
default ->
sendSingle(execution, users, from, replyTos, inReplyTo, mustBeEncrypted, subject, message, attachments);
}
List<Expectation> expectations = content.getExpectations()
.stream()
.flatMap((entry) -> switch (entry.getType()) {
case MANUAL ->
Stream.of((Expectation) new ManualExpectation(entry.getScore(), entry.getName(), entry.getDescription(), entry.isExpectationGroup()));
default -> Stream.of();
})
.toList();
.stream()
.flatMap((entry) -> switch (entry.getType()) {
case MANUAL -> Stream.of(
(Expectation) new ManualExpectation(entry));
default -> Stream.of();
})
.toList();
return new ExecutionProcess(false, expectations);
}
}
Loading

0 comments on commit cf3983e

Please sign in to comment.