| 1 | package edu.ucsb.cs156.dining.services; | |
| 2 | ||
| 3 | import edu.ucsb.cs156.dining.entities.Moderator; | |
| 4 | import edu.ucsb.cs156.dining.entities.Review; | |
| 5 | import edu.ucsb.cs156.dining.repositories.ModeratorRepository; | |
| 6 | import java.nio.charset.StandardCharsets; | |
| 7 | import java.time.Duration; | |
| 8 | import java.util.Base64; | |
| 9 | import java.util.List; | |
| 10 | import java.util.Map; | |
| 11 | import java.util.stream.StreamSupport; | |
| 12 | import lombok.extern.slf4j.Slf4j; | |
| 13 | import org.springframework.beans.factory.annotation.Value; | |
| 14 | import org.springframework.boot.web.client.RestTemplateBuilder; | |
| 15 | import org.springframework.http.HttpEntity; | |
| 16 | import org.springframework.http.HttpHeaders; | |
| 17 | import org.springframework.security.core.Authentication; | |
| 18 | import org.springframework.security.core.context.SecurityContextHolder; | |
| 19 | import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; | |
| 20 | import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; | |
| 21 | import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; | |
| 22 | import org.springframework.stereotype.Service; | |
| 23 | import org.springframework.web.client.RestTemplate; | |
| 24 | ||
| 25 | /** | |
| 26 | * Emails all moderators when a review needs moderation. The email is sent through the Gmail API | |
| 27 | * from the account of the logged-in user who submitted the review, using their OAuth token (this | |
| 28 | * requires the gmail.send scope). | |
| 29 | * | |
| 30 | * <p>Sending is best effort: any failure is logged and never stops the review from being saved. | |
| 31 | */ | |
| 32 | @Slf4j | |
| 33 | @Service | |
| 34 | public class ModeratorNotificationService { | |
| 35 | ||
| 36 | public static final String GMAIL_SEND_URL = | |
| 37 | "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"; | |
| 38 | ||
| 39 | public static final String GMAIL_SEND_SCOPE = "https://www.googleapis.com/auth/gmail.send"; | |
| 40 | ||
| 41 | private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(5); | |
| 42 | private static final Duration READ_TIMEOUT = Duration.ofSeconds(10); | |
| 43 | ||
| 44 | private final OAuth2AuthorizedClientService authorizedClientService; | |
| 45 | private final ModeratorRepository moderatorRepository; | |
| 46 | private final RestTemplate restTemplate; | |
| 47 | ||
| 48 | // On dokku the app's address is <app name>.<dokku host>, e.g. dining-qa.dokku-00.cs.ucsb.edu | |
| 49 | @Value("${app.name}") | |
| 50 | private String appName; | |
| 51 | ||
| 52 | @Value("${app.hostname}") | |
| 53 | private String appHostname; | |
| 54 | ||
| 55 | public ModeratorNotificationService( | |
| 56 | OAuth2AuthorizedClientService authorizedClientService, | |
| 57 | ModeratorRepository moderatorRepository, | |
| 58 | RestTemplateBuilder restTemplateBuilder) { | |
| 59 | this.authorizedClientService = authorizedClientService; | |
| 60 | this.moderatorRepository = moderatorRepository; | |
| 61 | // Finite timeouts so a slow Gmail API can't hang the review submission request. | |
| 62 | this.restTemplate = | |
| 63 | restTemplateBuilder.connectTimeout(CONNECT_TIMEOUT).readTimeout(READ_TIMEOUT).build(); | |
| 64 | } | |
| 65 | ||
| 66 | /** | |
| 67 | * Emails all moderators that a review needs moderation. Never throws. | |
| 68 | * | |
| 69 | * @param review the review that was just submitted | |
| 70 | */ | |
| 71 | public void notifyModerators(Review review) { | |
| 72 | try { | |
| 73 | String accessToken = currentUserGoogleAccessToken(); | |
| 74 |
1
1. notifyModerators : negated conditional → KILLED |
if (accessToken == null) { |
| 75 | log.warn("Not emailing moderators: no Google access token for the current user"); | |
| 76 | return; | |
| 77 | } | |
| 78 | ||
| 79 | List<String> recipients = | |
| 80 | StreamSupport.stream(moderatorRepository.findAll().spliterator(), false) | |
| 81 | .map(Moderator::getEmail) | |
| 82 | .filter(ModeratorNotificationService::isSafeEmail) | |
| 83 | .toList(); | |
| 84 |
1
1. notifyModerators : negated conditional → KILLED |
if (recipients.isEmpty()) { |
| 85 | log.info("Not emailing moderators: there are no moderators"); | |
| 86 | return; | |
| 87 | } | |
| 88 | ||
| 89 | HttpHeaders headers = new HttpHeaders(); | |
| 90 |
1
1. notifyModerators : removed call to org/springframework/http/HttpHeaders::setBearerAuth → KILLED |
headers.setBearerAuth(accessToken); |
| 91 | Map<String, String> body = Map.of("raw", buildRawMessage(recipients, review)); | |
| 92 | restTemplate.postForEntity(GMAIL_SEND_URL, new HttpEntity<>(body, headers), String.class); | |
| 93 | log.info("Emailed {} moderator(s) about review {}", recipients.size(), review.getId()); | |
| 94 | } catch (Exception e) { | |
| 95 | log.error("Failed to email moderators about review {}", review.getId(), e); | |
| 96 | } | |
| 97 | } | |
| 98 | ||
| 99 | /** Returns the current user's Google access token, or null if there isn't a usable one. */ | |
| 100 | private String currentUserGoogleAccessToken() { | |
| 101 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); | |
| 102 |
1
1. currentUserGoogleAccessToken : negated conditional → KILLED |
if (!(auth instanceof OAuth2AuthenticationToken oauthToken)) { |
| 103 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return null; |
| 104 | } | |
| 105 | // Only the real Google login can call the Gmail API (not the mock provider used in tests). | |
| 106 |
1
1. currentUserGoogleAccessToken : negated conditional → KILLED |
if (!"google".equals(oauthToken.getAuthorizedClientRegistrationId())) { |
| 107 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return null; |
| 108 | } | |
| 109 | OAuth2AuthorizedClient client = | |
| 110 | authorizedClientService.loadAuthorizedClient("google", oauthToken.getName()); | |
| 111 | // An OAuth2AuthorizedClient always has a non-null access token, so only the client is checked. | |
| 112 |
1
1. currentUserGoogleAccessToken : negated conditional → KILLED |
if (client == null) { |
| 113 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return null; |
| 114 | } | |
| 115 |
1
1. currentUserGoogleAccessToken : negated conditional → KILLED |
if (!client.getAccessToken().getScopes().contains(GMAIL_SEND_SCOPE)) { |
| 116 | // User logged in before the scope was added; they need to log out and back in. | |
| 117 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return null; |
| 118 | } | |
| 119 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return client.getAccessToken().getTokenValue(); |
| 120 | } | |
| 121 | ||
| 122 | /** Builds a base64url-encoded RFC 2822 email, as the Gmail API expects. */ | |
| 123 | private String buildRawMessage(List<String> recipients, Review review) { | |
| 124 | // Bcc so the submitting student doesn't see the moderators' addresses. | |
| 125 | String message = | |
| 126 | "Bcc: " | |
| 127 | + String.join(", ", recipients) | |
| 128 | + "\r\n" | |
| 129 | + "Subject: A new dining review needs moderation\r\n" | |
| 130 | + "Content-Type: text/plain; charset=UTF-8\r\n" | |
| 131 | + "\r\n" | |
| 132 | + "A new review (id " | |
| 133 | + review.getId() | |
| 134 | + ") was submitted and is waiting for moderation.\r\n\r\n" | |
| 135 | + "Review it here: https://" | |
| 136 | + appName | |
| 137 | + "." | |
| 138 | + appHostname | |
| 139 | + "/moderate\r\n"; | |
| 140 |
1
1. buildRawMessage : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::buildRawMessage → KILLED |
return Base64.getUrlEncoder() |
| 141 | .withoutPadding() | |
| 142 | .encodeToString(message.getBytes(StandardCharsets.UTF_8)); | |
| 143 | } | |
| 144 | ||
| 145 | /** Rejects values that could inject extra email headers. */ | |
| 146 | private static boolean isSafeEmail(String email) { | |
| 147 |
7
1. isSafeEmail : changed conditional boundary → KILLED 2. isSafeEmail : negated conditional → KILLED 3. isSafeEmail : negated conditional → KILLED 4. isSafeEmail : replaced boolean return with true for edu/ucsb/cs156/dining/services/ModeratorNotificationService::isSafeEmail → KILLED 5. isSafeEmail : negated conditional → KILLED 6. isSafeEmail : negated conditional → KILLED 7. isSafeEmail : changed conditional boundary → KILLED |
return email != null && !email.isBlank() && email.indexOf('\r') < 0 && email.indexOf('\n') < 0; |
| 148 | } | |
| 149 | } | |
Mutations | ||
| 74 |
1.1 |
|
| 84 |
1.1 |
|
| 90 |
1.1 |
|
| 102 |
1.1 |
|
| 103 |
1.1 |
|
| 106 |
1.1 |
|
| 107 |
1.1 |
|
| 112 |
1.1 |
|
| 113 |
1.1 |
|
| 115 |
1.1 |
|
| 117 |
1.1 |
|
| 119 |
1.1 |
|
| 140 |
1.1 |
|
| 147 |
1.1 2.2 3.3 4.4 5.5 6.6 7.7 |