| 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. | |
| 27 | * | |
| 28 | * <p>The email is sent through the Gmail API from the Google account of the logged-in user who | |
| 29 | * submitted the review, using the OAuth access token they got when they logged in. This requires | |
| 30 | * the gmail.send scope (see docs/oauth.md). | |
| 31 | * | |
| 32 | * <p>Sending is best effort: every failure is logged, and {@link #notifyModerators(Review)} never | |
| 33 | * throws, so a problem with email can never stop a review from being saved. | |
| 34 | */ | |
| 35 | @Slf4j | |
| 36 | @Service | |
| 37 | public class ModeratorNotificationService { | |
| 38 | ||
| 39 | public static final String GMAIL_SEND_URL = | |
| 40 | "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"; | |
| 41 | ||
| 42 | public static final String GMAIL_SEND_SCOPE = "https://www.googleapis.com/auth/gmail.send"; | |
| 43 | ||
| 44 | public static final String SUBJECT = "A new dining review needs moderation"; | |
| 45 | ||
| 46 | private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(5); | |
| 47 | private static final Duration READ_TIMEOUT = Duration.ofSeconds(10); | |
| 48 | ||
| 49 | private final OAuth2AuthorizedClientService authorizedClientService; | |
| 50 | private final ModeratorRepository moderatorRepository; | |
| 51 | private final RestTemplate restTemplate; | |
| 52 | ||
| 53 | // On dokku the app's address is <app name>.<dokku host>, e.g. dining-qa.dokku-00.cs.ucsb.edu | |
| 54 | @Value("${app.name}") | |
| 55 | private String appName; | |
| 56 | ||
| 57 | @Value("${app.hostname}") | |
| 58 | private String appHostname; | |
| 59 | ||
| 60 | public ModeratorNotificationService( | |
| 61 | OAuth2AuthorizedClientService authorizedClientService, | |
| 62 | ModeratorRepository moderatorRepository, | |
| 63 | RestTemplateBuilder restTemplateBuilder) { | |
| 64 | this.authorizedClientService = authorizedClientService; | |
| 65 | this.moderatorRepository = moderatorRepository; | |
| 66 | // Finite timeouts so a slow Gmail API can't hang the review submission request. | |
| 67 | this.restTemplate = | |
| 68 | restTemplateBuilder.connectTimeout(CONNECT_TIMEOUT).readTimeout(READ_TIMEOUT).build(); | |
| 69 | } | |
| 70 | ||
| 71 | /** | |
| 72 | * Emails every moderator that the given review is waiting for moderation. Never throws. | |
| 73 | * | |
| 74 | * @param review the review that needs moderation | |
| 75 | */ | |
| 76 | public void notifyModerators(Review review) { | |
| 77 | try { | |
| 78 | String accessToken = currentUserGoogleAccessToken(); | |
| 79 |
1
1. notifyModerators : negated conditional → KILLED |
if (accessToken == null) { |
| 80 | log.warn( | |
| 81 | "Not emailing moderators about review {}: no usable Google access token for the" | |
| 82 | + " current user (they may need to log out and back in)", | |
| 83 | review.getId()); | |
| 84 | return; | |
| 85 | } | |
| 86 | ||
| 87 | List<String> recipients = | |
| 88 | StreamSupport.stream(moderatorRepository.findAll().spliterator(), false) | |
| 89 | .map(Moderator::getEmail) | |
| 90 | .filter(ModeratorNotificationService::isSafeEmail) | |
| 91 | .toList(); | |
| 92 |
1
1. notifyModerators : negated conditional → KILLED |
if (recipients.isEmpty()) { |
| 93 | log.info( | |
| 94 | "Not emailing moderators about review {}: there are no moderators", review.getId()); | |
| 95 | return; | |
| 96 | } | |
| 97 | ||
| 98 | HttpHeaders headers = new HttpHeaders(); | |
| 99 |
1
1. notifyModerators : removed call to org/springframework/http/HttpHeaders::setBearerAuth → KILLED |
headers.setBearerAuth(accessToken); |
| 100 | Map<String, String> body = Map.of("raw", buildRawMessage(recipients, review)); | |
| 101 | restTemplate.postForEntity(GMAIL_SEND_URL, new HttpEntity<>(body, headers), String.class); | |
| 102 | log.info("Emailed {} moderator(s) about review {}", recipients.size(), review.getId()); | |
| 103 | } catch (Exception e) { | |
| 104 | log.error("Failed to email moderators about review {}", review.getId(), e); | |
| 105 | } | |
| 106 | } | |
| 107 | ||
| 108 | /** | |
| 109 | * Returns the current user's Google access token, or null if there isn't a usable one. | |
| 110 | * | |
| 111 | * @return the access token, or null | |
| 112 | */ | |
| 113 | String currentUserGoogleAccessToken() { | |
| 114 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); | |
| 115 |
1
1. currentUserGoogleAccessToken : negated conditional → KILLED |
if (!(auth instanceof OAuth2AuthenticationToken oauthToken)) { |
| 116 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return null; |
| 117 | } | |
| 118 | // Only the real Google login can call the Gmail API (not the mock provider used in tests). | |
| 119 |
1
1. currentUserGoogleAccessToken : negated conditional → KILLED |
if (!"google".equals(oauthToken.getAuthorizedClientRegistrationId())) { |
| 120 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return null; |
| 121 | } | |
| 122 | OAuth2AuthorizedClient client = | |
| 123 | authorizedClientService.loadAuthorizedClient("google", oauthToken.getName()); | |
| 124 |
1
1. currentUserGoogleAccessToken : negated conditional → KILLED |
if (client == null) { |
| 125 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return null; |
| 126 | } | |
| 127 | // Users who logged in before the scope was added don't have it until they log in again. | |
| 128 |
1
1. currentUserGoogleAccessToken : negated conditional → KILLED |
if (!client.getAccessToken().getScopes().contains(GMAIL_SEND_SCOPE)) { |
| 129 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return null; |
| 130 | } | |
| 131 |
1
1. currentUserGoogleAccessToken : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::currentUserGoogleAccessToken → KILLED |
return client.getAccessToken().getTokenValue(); |
| 132 | } | |
| 133 | ||
| 134 | /** | |
| 135 | * Builds the plain-text RFC 2822 email, before encoding. | |
| 136 | * | |
| 137 | * <p>Moderators go in Bcc so the student who submitted the review doesn't see their addresses. | |
| 138 | * | |
| 139 | * @param recipients moderator email addresses | |
| 140 | * @param review the review that needs moderation | |
| 141 | * @return the email as a string | |
| 142 | */ | |
| 143 | String buildMessage(List<String> recipients, Review review) { | |
| 144 |
1
1. buildMessage : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::buildMessage → KILLED |
return "Bcc: " |
| 145 | + String.join(", ", recipients) | |
| 146 | + "\r\n" | |
| 147 | + "Subject: " | |
| 148 | + SUBJECT | |
| 149 | + "\r\n" | |
| 150 | + "Content-Type: text/plain; charset=UTF-8\r\n" | |
| 151 | + "\r\n" | |
| 152 | + "A new review (id " | |
| 153 | + review.getId() | |
| 154 | + ") was submitted and is waiting for moderation.\r\n\r\n" | |
| 155 | + "Review it here: " | |
| 156 | + moderationPageUrl() | |
| 157 | + "\r\n"; | |
| 158 | } | |
| 159 | ||
| 160 | /** | |
| 161 | * Returns the URL of the moderation page on this deployment. | |
| 162 | * | |
| 163 | * @return e.g. https://dining-qa.dokku-00.cs.ucsb.edu/moderate | |
| 164 | */ | |
| 165 | String moderationPageUrl() { | |
| 166 |
1
1. moderationPageUrl : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::moderationPageUrl → KILLED |
return "https://" + appName + "." + appHostname + "/moderate"; |
| 167 | } | |
| 168 | ||
| 169 | /** Encodes the email as base64url without padding, which is what the Gmail API expects. */ | |
| 170 | private String buildRawMessage(List<String> recipients, Review review) { | |
| 171 |
1
1. buildRawMessage : replaced return value with "" for edu/ucsb/cs156/dining/services/ModeratorNotificationService::buildRawMessage → KILLED |
return Base64.getUrlEncoder() |
| 172 | .withoutPadding() | |
| 173 | .encodeToString(buildMessage(recipients, review).getBytes(StandardCharsets.UTF_8)); | |
| 174 | } | |
| 175 | ||
| 176 | /** | |
| 177 | * Rejects values that would break the email or inject extra headers. | |
| 178 | * | |
| 179 | * @param email a moderator email address | |
| 180 | * @return true if it is safe to put in the Bcc header | |
| 181 | */ | |
| 182 | static boolean isSafeEmail(String email) { | |
| 183 |
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; |
| 184 | } | |
| 185 | } | |
Mutations | ||
| 79 |
1.1 |
|
| 92 |
1.1 |
|
| 99 |
1.1 |
|
| 115 |
1.1 |
|
| 116 |
1.1 |
|
| 119 |
1.1 |
|
| 120 |
1.1 |
|
| 124 |
1.1 |
|
| 125 |
1.1 |
|
| 128 |
1.1 |
|
| 129 |
1.1 |
|
| 131 |
1.1 |
|
| 144 |
1.1 |
|
| 166 |
1.1 |
|
| 171 |
1.1 |
|
| 183 |
1.1 2.2 3.3 4.4 5.5 6.6 7.7 |