| 1 | package edu.ucsb.cs156.frontiers.services; | |
| 2 | ||
| 3 | import edu.ucsb.cs156.frontiers.config.ApiKeyToken; | |
| 4 | import edu.ucsb.cs156.frontiers.entities.Course; | |
| 5 | import edu.ucsb.cs156.frontiers.entities.CourseApiKey; | |
| 6 | import edu.ucsb.cs156.frontiers.entities.CourseOption; | |
| 7 | import edu.ucsb.cs156.frontiers.entities.User; | |
| 8 | import edu.ucsb.cs156.frontiers.enums.CourseOptions; | |
| 9 | import edu.ucsb.cs156.frontiers.models.CourseApiKeyView; | |
| 10 | import edu.ucsb.cs156.frontiers.repositories.CourseApiKeyRepository; | |
| 11 | import edu.ucsb.cs156.frontiers.repositories.CourseOptionRepository; | |
| 12 | import jakarta.transaction.Transactional; | |
| 13 | import java.security.SecureRandom; | |
| 14 | import java.time.ZonedDateTime; | |
| 15 | import java.util.Base64; | |
| 16 | import java.util.Comparator; | |
| 17 | import java.util.HashSet; | |
| 18 | import java.util.List; | |
| 19 | import java.util.Objects; | |
| 20 | import java.util.Optional; | |
| 21 | import org.apache.commons.codec.digest.DigestUtils; | |
| 22 | import org.hibernate.Hibernate; | |
| 23 | import org.springframework.data.auditing.DateTimeProvider; | |
| 24 | import org.springframework.security.access.AccessDeniedException; | |
| 25 | import org.springframework.security.core.GrantedAuthority; | |
| 26 | import org.springframework.security.core.authority.SimpleGrantedAuthority; | |
| 27 | import org.springframework.stereotype.Service; | |
| 28 | ||
| 29 | @Service | |
| 30 | public class ApiKeyService { | |
| 31 | private final DateTimeProvider dateTimeProvider; | |
| 32 | private final CourseApiKeyRepository courseApiKeyRepository; | |
| 33 | private final CurrentUserService currentUserService; | |
| 34 | private final SecureRandom secureRandom; | |
| 35 | private final CourseOptionRepository courseOptionRepository; | |
| 36 | ||
| 37 | public ApiKeyService( | |
| 38 | DateTimeProvider dateTimeProvider, | |
| 39 | CourseApiKeyRepository courseApiKeyRepository, | |
| 40 | CurrentUserService currentUserService, | |
| 41 | SecureRandom secureRandom, | |
| 42 | CourseOptionRepository courseOptionRepository) { | |
| 43 | this.dateTimeProvider = dateTimeProvider; | |
| 44 | this.courseApiKeyRepository = courseApiKeyRepository; | |
| 45 | this.currentUserService = currentUserService; | |
| 46 | this.secureRandom = secureRandom; | |
| 47 | this.courseOptionRepository = courseOptionRepository; | |
| 48 | } | |
| 49 | ||
| 50 | /** | |
| 51 | * Whether the ENABLE_API_KEYS course option is on for the course. Keys can only be created for, | |
| 52 | * and used with, a course that has the option on; turning it off disables every key of the course | |
| 53 | * at once. | |
| 54 | * | |
| 55 | * @param courseId the id of the course | |
| 56 | * @return true if the option is enabled, false if it is disabled or has never been set | |
| 57 | */ | |
| 58 | public boolean apiKeysEnabled(Long courseId) { | |
| 59 |
2
1. apiKeysEnabled : replaced boolean return with false for edu/ucsb/cs156/frontiers/services/ApiKeyService::apiKeysEnabled → KILLED 2. apiKeysEnabled : replaced boolean return with true for edu/ucsb/cs156/frontiers/services/ApiKeyService::apiKeysEnabled → KILLED |
return courseOptionRepository |
| 60 | .findByCourseIdAndOption(courseId, CourseOptions.ENABLE_API_KEYS.name()) | |
| 61 | .map(CourseOption::getEnabled) | |
| 62 | .orElse(false); | |
| 63 | } | |
| 64 | ||
| 65 | /** | |
| 66 | * A freshly created key. This is the only time the key itself is available; only its hash is | |
| 67 | * stored. | |
| 68 | */ | |
| 69 | public record IssuedCourseApiKey( | |
| 70 | String key, Long courseId, ZonedDateTime issuedAt, ZonedDateTime expiresAt, String label) {} | |
| 71 | ||
| 72 | public enum ExpirationChoice { | |
| 73 | DAYS_90, | |
| 74 | MONTHS_6 | |
| 75 | } | |
| 76 | ||
| 77 | /** | |
| 78 | * Creates a key for the course. | |
| 79 | * | |
| 80 | * @param course the course the key is for | |
| 81 | * @param choice how long the key lasts | |
| 82 | * @param label an optional short name for the key; blank is stored as null | |
| 83 | * @return the key and its metadata | |
| 84 | */ | |
| 85 | @Transactional | |
| 86 | public IssuedCourseApiKey createApiKey(Course course, ExpirationChoice choice, String label) { | |
| 87 |
2
1. createApiKey : negated conditional → KILLED 2. createApiKey : negated conditional → KILLED |
String trimmedLabel = label == null || label.isBlank() ? null : label.strip(); |
| 88 | byte[] nextBytes = new byte[16]; | |
| 89 |
1
1. createApiKey : removed call to java/security/SecureRandom::nextBytes → KILLED |
secureRandom.nextBytes(nextBytes); |
| 90 | String key = Base64.getUrlEncoder().withoutPadding().encodeToString(nextBytes); | |
| 91 | ||
| 92 | ZonedDateTime currentTime = ZonedDateTime.from(dateTimeProvider.getNow().get()); | |
| 93 | ||
| 94 | CourseApiKey keyEntity = | |
| 95 | CourseApiKey.builder() | |
| 96 | .course(course) | |
| 97 | .createdAt(currentTime) | |
| 98 | .expiresAt( | |
| 99 |
1
1. createApiKey : negated conditional → KILLED |
choice == ExpirationChoice.DAYS_90 |
| 100 | ? currentTime.plusDays(90) | |
| 101 | : currentTime.plusMonths(6)) | |
| 102 | .keyHash(DigestUtils.sha256Hex(key)) | |
| 103 |
1
1. createApiKey : Replaced integer subtraction with addition → KILLED |
.keySuffix(key.substring(key.length() - 6)) |
| 104 | .createdBy(currentUserService.getUser()) | |
| 105 | .label(trimmedLabel) | |
| 106 | .build(); | |
| 107 | ||
| 108 | courseApiKeyRepository.save(keyEntity); | |
| 109 | ||
| 110 |
1
1. createApiKey : replaced return value with null for edu/ucsb/cs156/frontiers/services/ApiKeyService::createApiKey → KILLED |
return new IssuedCourseApiKey( |
| 111 | key, course.getId(), currentTime, keyEntity.getExpiresAt(), trimmedLabel); | |
| 112 | } | |
| 113 | ||
| 114 | @Transactional | |
| 115 | public ApiKeyToken authenticateKey(String key) { | |
| 116 | CourseApiKey foundKey = | |
| 117 | courseApiKeyRepository | |
| 118 | .findByKeyHash(DigestUtils.sha256Hex(key)) | |
| 119 |
1
1. lambda$authenticateKey$0 : replaced return value with null for edu/ucsb/cs156/frontiers/services/ApiKeyService::lambda$authenticateKey$0 → KILLED |
.orElseThrow(() -> new AccessDeniedException("Invalid API key")); |
| 120 |
1
1. authenticateKey : negated conditional → KILLED |
if (foundKey.getRevoked()) { |
| 121 | throw new AccessDeniedException("API key has been revoked"); | |
| 122 | } | |
| 123 |
1
1. authenticateKey : negated conditional → KILLED |
if (foundKey.getExpiresAt().isBefore(ZonedDateTime.from(dateTimeProvider.getNow().get()))) { |
| 124 | throw new AccessDeniedException("API key has expired"); | |
| 125 | } | |
| 126 |
1
1. authenticateKey : negated conditional → KILLED |
if (!apiKeysEnabled(foundKey.getCourse().getId())) { |
| 127 | throw new AccessDeniedException("API keys are not enabled for this course"); | |
| 128 | } | |
| 129 | /* Forcibly load key owner for auth purposes */ | |
| 130 | User owner = Hibernate.unproxy(foundKey.getCreatedBy(), User.class); | |
| 131 |
1
1. authenticateKey : removed call to edu/ucsb/cs156/frontiers/entities/CourseApiKey::setCreatedBy → KILLED |
foundKey.setCreatedBy(owner); |
| 132 |
2
1. authenticateKey : Replaced long addition with subtraction → KILLED 2. authenticateKey : removed call to edu/ucsb/cs156/frontiers/entities/CourseApiKey::setUsageCount → KILLED |
foundKey.setUsageCount(foundKey.getUsageCount() + 1); |
| 133 |
1
1. authenticateKey : removed call to edu/ucsb/cs156/frontiers/entities/CourseApiKey::setLastUsedAt → KILLED |
foundKey.setLastUsedAt(ZonedDateTime.from(dateTimeProvider.getNow().get())); |
| 134 | courseApiKeyRepository.save(foundKey); | |
| 135 | HashSet<GrantedAuthority> authority = new HashSet<>(); | |
| 136 | authority.add(new SimpleGrantedAuthority("ROLE_API_KEY")); | |
| 137 |
1
1. authenticateKey : replaced return value with null for edu/ucsb/cs156/frontiers/services/ApiKeyService::authenticateKey → KILLED |
return new ApiKeyToken(foundKey, owner, authority); |
| 138 | } | |
| 139 | ||
| 140 | public List<CourseApiKey> getApiKeysForCourse(Long courseId) { | |
| 141 |
1
1. getApiKeysForCourse : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/ApiKeyService::getApiKeysForCourse → KILLED |
return courseApiKeyRepository.findByCourseId(courseId); |
| 142 | } | |
| 143 | ||
| 144 | /** | |
| 145 | * The keys of a course as an instructor may see them (never the key itself), newest first. | |
| 146 | * | |
| 147 | * @param courseId the id of the course | |
| 148 | * @return one view per key, including revoked and expired ones | |
| 149 | */ | |
| 150 | @Transactional | |
| 151 | public List<CourseApiKeyView> listApiKeys(Long courseId) { | |
| 152 | ZonedDateTime now = ZonedDateTime.from(dateTimeProvider.getNow().get()); | |
| 153 |
1
1. listApiKeys : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/ApiKeyService::listApiKeys → KILLED |
return courseApiKeyRepository.findByCourseId(courseId).stream() |
| 154 | .sorted(Comparator.comparing(CourseApiKey::getCreatedAt).reversed()) | |
| 155 |
1
1. lambda$listApiKeys$0 : replaced return value with null for edu/ucsb/cs156/frontiers/services/ApiKeyService::lambda$listApiKeys$0 → KILLED |
.map(key -> CourseApiKeyView.from(key, now)) |
| 156 | .toList(); | |
| 157 | } | |
| 158 | ||
| 159 | /** | |
| 160 | * Revokes a key by id, for the instructor's key table. The course id must match the key's, so | |
| 161 | * that an instructor of one course cannot revoke another course's keys by guessing ids. | |
| 162 | * | |
| 163 | * @param id the key's id | |
| 164 | * @param courseId the course the key is expected to belong to | |
| 165 | * @return true if the key was found in that course (and is now revoked), false otherwise | |
| 166 | */ | |
| 167 | @Transactional | |
| 168 | public boolean revokeApiKeyById(Long id, Long courseId) { | |
| 169 | Optional<CourseApiKey> found = courseApiKeyRepository.findById(id); | |
| 170 |
2
1. revokeApiKeyById : negated conditional → KILLED 2. revokeApiKeyById : negated conditional → KILLED |
if (found.isEmpty() || !Objects.equals(found.get().getCourse().getId(), courseId)) { |
| 171 |
1
1. revokeApiKeyById : replaced boolean return with true for edu/ucsb/cs156/frontiers/services/ApiKeyService::revokeApiKeyById → KILLED |
return false; |
| 172 | } | |
| 173 |
1
1. revokeApiKeyById : removed call to edu/ucsb/cs156/frontiers/entities/CourseApiKey::setRevoked → KILLED |
found.get().setRevoked(true); |
| 174 | courseApiKeyRepository.save(found.get()); | |
| 175 |
1
1. revokeApiKeyById : replaced boolean return with false for edu/ucsb/cs156/frontiers/services/ApiKeyService::revokeApiKeyById → KILLED |
return true; |
| 176 | } | |
| 177 | ||
| 178 | public List<CourseApiKey> getApiKeysForUser(User user) { | |
| 179 |
1
1. getApiKeysForUser : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/ApiKeyService::getApiKeysForUser → KILLED |
return courseApiKeyRepository.findByCreatedBy(user); |
| 180 | } | |
| 181 | ||
| 182 | public boolean revokeApiKey(String key) { | |
| 183 | CourseApiKey foundKey = | |
| 184 | courseApiKeyRepository.findByKeyHash(DigestUtils.sha256Hex(key)).orElse(null); | |
| 185 |
1
1. revokeApiKey : negated conditional → KILLED |
if (foundKey != null) { |
| 186 |
1
1. revokeApiKey : removed call to edu/ucsb/cs156/frontiers/entities/CourseApiKey::setRevoked → KILLED |
foundKey.setRevoked(true); |
| 187 | courseApiKeyRepository.save(foundKey); | |
| 188 |
1
1. revokeApiKey : replaced boolean return with false for edu/ucsb/cs156/frontiers/services/ApiKeyService::revokeApiKey → KILLED |
return true; |
| 189 | } else { | |
| 190 |
1
1. revokeApiKey : replaced boolean return with true for edu/ucsb/cs156/frontiers/services/ApiKeyService::revokeApiKey → KILLED |
return false; |
| 191 | } | |
| 192 | } | |
| 193 | } | |
Mutations | ||
| 59 |
1.1 2.2 |
|
| 87 |
1.1 2.2 |
|
| 89 |
1.1 |
|
| 99 |
1.1 |
|
| 103 |
1.1 |
|
| 110 |
1.1 |
|
| 119 |
1.1 |
|
| 120 |
1.1 |
|
| 123 |
1.1 |
|
| 126 |
1.1 |
|
| 131 |
1.1 |
|
| 132 |
1.1 2.2 |
|
| 133 |
1.1 |
|
| 137 |
1.1 |
|
| 141 |
1.1 |
|
| 153 |
1.1 |
|
| 155 |
1.1 |
|
| 170 |
1.1 2.2 |
|
| 171 |
1.1 |
|
| 173 |
1.1 |
|
| 175 |
1.1 |
|
| 179 |
1.1 |
|
| 185 |
1.1 |
|
| 186 |
1.1 |
|
| 188 |
1.1 |
|
| 190 |
1.1 |