-
Notifications
You must be signed in to change notification settings - Fork 6
WIP: Skills question endpoint #798
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
barna-isaac
wants to merge
31
commits into
main
Choose a base branch
from
feature/skills-questions-endpoint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
33bd6da
initial commit with empty endpoint
barna-isaac 6278774
check that app exists
barna-isaac 7a434ed
clean up comments
barna-isaac 45018e8
check that app_id is a valid AnvilApp
barna-isaac 767fd0a
extract ElasticSearchHelper
barna-isaac db449c7
add test stub for happy path
barna-isaac 220cf77
introduce validation for payload
barna-isaac b0b2d76
add two test cases for request payload validation
barna-isaac e567f8a
validate HMAC
barna-isaac c8d4df2
validate payload contents
barna-isaac ab2cd29
fix checkstyle
barna-isaac f79f4e5
use data provider for tests
barna-isaac c3444f2
minor refactor
barna-isaac 35421fc
simplify a few test cases
barna-isaac 7890d39
actually record answers
barna-isaac d60bd9b
minor changes
barna-isaac 13aab68
WIP: validate all payload fields
barna-isaac 3bdfae8
finish validating payload content
barna-isaac eb8d3e2
disallow large payloads
barna-isaac d9f141e
use framework to parse request body
barna-isaac dd50245
attach skills facade
barna-isaac 7e66d85
just require anvil child, root is always page
barna-isaac 642d247
record answers to database
barna-isaac 273a7a9
treat 2 question fields as opaque json
barna-isaac 914be99
use skill attempt id as a nonce
barna-isaac 8eb0544
use UUID type for the id
barna-isaac f7fdb61
add foreign key constraint for user id
barna-isaac 298816e
endpoint echoes back dto
barna-isaac b230adc
fix checkstyle problems
barna-isaac 8bf13c7
only allow endpoint if HMAC_SECRET is set
barna-isaac 4191922
add logging, minor refactors
barna-isaac File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
119 changes: 119 additions & 0 deletions
119
src/main/java/uk/ac/cam/cl/dtg/isaac/api/SkillsFacade.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| package uk.ac.cam.cl.dtg.isaac.api; | ||
|
|
||
| import com.google.inject.Inject; | ||
| import io.swagger.v3.oas.annotations.tags.Tag; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import uk.ac.cam.cl.dtg.isaac.api.managers.InvalidAnvilMarkingRequestException; | ||
| import uk.ac.cam.cl.dtg.isaac.api.managers.SkillsManager; | ||
| import uk.ac.cam.cl.dtg.isaac.dos.content.AnvilApp; | ||
| import uk.ac.cam.cl.dtg.isaac.dos.content.Content; | ||
| import uk.ac.cam.cl.dtg.isaac.dto.AnvilMarkingRequestDTO; | ||
| import uk.ac.cam.cl.dtg.isaac.dto.AnvilPayloadDTO; | ||
| import uk.ac.cam.cl.dtg.isaac.dto.SegueErrorResponse; | ||
| import uk.ac.cam.cl.dtg.isaac.dto.users.RegisteredUserDTO; | ||
| import uk.ac.cam.cl.dtg.segue.api.managers.UserAccountManager; | ||
| import uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserLoggedInException; | ||
| import uk.ac.cam.cl.dtg.segue.dao.ILogManager; | ||
| import uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException; | ||
| import uk.ac.cam.cl.dtg.segue.dao.content.ContentManagerException; | ||
| import uk.ac.cam.cl.dtg.segue.dao.content.GitContentManager; | ||
| import uk.ac.cam.cl.dtg.util.AbstractConfigLoader; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.ws.rs.Consumes; | ||
| import jakarta.ws.rs.POST; | ||
| import jakarta.ws.rs.Path; | ||
| import jakarta.ws.rs.PathParam; | ||
| import jakarta.ws.rs.Produces; | ||
| import jakarta.ws.rs.core.Context; | ||
| import jakarta.ws.rs.core.MediaType; | ||
| import jakarta.ws.rs.core.Response; | ||
| import jakarta.ws.rs.core.Response.Status; | ||
|
|
||
| /** Skills Facade, supports interaction related to the Isaac Skill Practice apps. */ | ||
| @Path("/skills") | ||
| @Tag(name = "SkillsFacade", description = "/skills") | ||
| public class SkillsFacade extends AbstractIsaacFacade { | ||
| private static final Logger log = LoggerFactory.getLogger(SkillsFacade.class); | ||
|
|
||
| private final UserAccountManager userManager; | ||
| private final GitContentManager contentManager; | ||
| private final SkillsManager skillsManager; | ||
|
|
||
| /** | ||
| * Constructor. | ||
| */ | ||
| @Inject | ||
| public SkillsFacade(final AbstractConfigLoader properties, final UserAccountManager userManager, | ||
| final ILogManager logManager, final GitContentManager contentManager, | ||
| final SkillsManager skillsManager) { | ||
| super(properties, logManager); | ||
| this.userManager = userManager; | ||
| this.contentManager = contentManager; | ||
| this.skillsManager = skillsManager; | ||
| } | ||
|
|
||
| /** | ||
| * Endpoint that records when a user has answered a question. | ||
| * | ||
| * @param request | ||
| * - the servlet request so we can find out if it is a known user. | ||
| * @param appId | ||
| * - the app that the attempt belongs to | ||
| */ | ||
| @POST | ||
| @Path("/{appId}/answer") | ||
| @Consumes(MediaType.APPLICATION_JSON) | ||
| @Produces(MediaType.APPLICATION_JSON) | ||
| public Response answerQuestion(@Context final HttpServletRequest request, | ||
| @PathParam("appId") final String appId, | ||
| final AnvilMarkingRequestDTO markingRequest) { | ||
| try { | ||
| RegisteredUserDTO currentUser = userManager.getCurrentRegisteredUser(request); | ||
|
|
||
| if (!(hasAnvilApp(this.contentManager.getContentDOById(appId)))) { | ||
| var error = new SegueErrorResponse(Status.NOT_FOUND, "No app found for given id: " + appId); | ||
| log.warn(error.getErrorMessage()); | ||
Check warningCode scanning / CodeQL Log Injection Medium
This log entry depends on a
user-provided value Error loading related location Loading |
||
|
github-advanced-security[bot] marked this conversation as resolved.
Fixed
|
||
| return error.toResponse(); | ||
| } | ||
|
|
||
| if (!skillsManager.isHmacValid(markingRequest)) { | ||
| var error = new SegueErrorResponse(Status.BAD_REQUEST, "Invalid HMAC signature"); | ||
| log.warn(error.getErrorMessage()); | ||
| return error.toResponse(); | ||
| } | ||
|
|
||
| AnvilPayloadDTO payloadDTO = skillsManager.parsePayload( | ||
| markingRequest.getPayload(), currentUser.getId(), appId); | ||
| skillsManager.recordAttempt(payloadDTO); | ||
|
|
||
| return Response.ok(payloadDTO).build(); | ||
| } catch (final NoUserLoggedInException e) { | ||
| return SegueErrorResponse.getNotLoggedInResponse(); | ||
| } catch (final InvalidAnvilMarkingRequestException e) { | ||
| var error = new SegueErrorResponse(Status.BAD_REQUEST, e.getMessage()); | ||
| log.warn(error.getErrorMessage() + ", " + e.getDetailedProblem()); | ||
| return error.toResponse(); | ||
| } catch (final SegueDatabaseException e) { | ||
| if ("Duplicate attempt ID".equals(e.getMessage())) { | ||
| var error = new SegueErrorResponse(Status.CONFLICT, "Duplicate attempt ID"); | ||
| log.warn(error.getErrorMessage()); | ||
| return error.toResponse(); | ||
| } | ||
| var error = new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Something went wrong"); | ||
| log.error(error.getErrorMessage()); | ||
| return error.toResponse(); | ||
| } catch (final ContentManagerException e) { | ||
| var error = new SegueErrorResponse(Status.NOT_FOUND, "Error locating the version requested", e); | ||
| log.error(error.getErrorMessage(), e); | ||
| return error.toResponse(); | ||
| } | ||
| } | ||
|
|
||
| private boolean hasAnvilApp(final Content content) { | ||
| return content instanceof AnvilApp | ||
| || (content != null | ||
| && content.getChildren().stream().anyMatch(c -> c instanceof Content cc && hasAnvilApp(cc))); | ||
| } | ||
| } | ||
19 changes: 19 additions & 0 deletions
19
src/main/java/uk/ac/cam/cl/dtg/isaac/api/managers/InvalidAnvilMarkingRequestException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| package uk.ac.cam.cl.dtg.isaac.api.managers; | ||
|
|
||
| /** | ||
| * An exception that indicates an invalid marking response was received from the external marking server. | ||
| */ | ||
| public class InvalidAnvilMarkingRequestException extends Exception { | ||
| private final String detailedProblem; | ||
|
|
||
| /** Constructor with message, detailed problem.*/ | ||
| public InvalidAnvilMarkingRequestException(final String message, final String detailedProblem) { | ||
| super(message); | ||
| this.detailedProblem = detailedProblem; | ||
| } | ||
|
|
||
| /** Get detailed problem.*/ | ||
| public String getDetailedProblem() { | ||
| return detailedProblem; | ||
| } | ||
| } |
89 changes: 89 additions & 0 deletions
89
src/main/java/uk/ac/cam/cl/dtg/isaac/api/managers/SkillsManager.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| package uk.ac.cam.cl.dtg.isaac.api.managers; | ||
|
|
||
| import com.fasterxml.jackson.core.JsonProcessingException; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.google.inject.Inject; | ||
| import uk.ac.cam.cl.dtg.isaac.dto.AnvilMarkingRequestDTO; | ||
| import uk.ac.cam.cl.dtg.isaac.dto.AnvilPayloadDTO; | ||
| import uk.ac.cam.cl.dtg.isaac.quiz.ISkillsAttemptManager; | ||
| import uk.ac.cam.cl.dtg.segue.api.managers.UserAuthenticationManager; | ||
| import uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException; | ||
| import uk.ac.cam.cl.dtg.util.AbstractConfigLoader; | ||
|
|
||
| import java.util.Date; | ||
|
|
||
| import static uk.ac.cam.cl.dtg.segue.api.Constants.*; | ||
|
|
||
| /** | ||
| * Manager for Isaac Skills Practice app interactions. | ||
| */ | ||
| public class SkillsManager { | ||
| private static final ObjectMapper objectMapper = new ObjectMapper(); | ||
|
|
||
| private final String hmacSecret; | ||
| private final ISkillsAttemptManager skillsAttemptManager; | ||
|
|
||
| /** | ||
| * Constructor. | ||
| * | ||
| * @param properties - application configuration | ||
| * @param skillsAttemptManager - persistence manager for skills attempts | ||
| */ | ||
| @Inject | ||
| public SkillsManager(final AbstractConfigLoader properties, final ISkillsAttemptManager skillsAttemptManager) { | ||
| this.hmacSecret = properties.getProperty(SKILLS_HMAC_SECRET); | ||
| this.skillsAttemptManager = skillsAttemptManager; | ||
| } | ||
|
|
||
| /** | ||
| * Verifies that the HMAC in the DTO matches the expected signature of the payload. | ||
| * | ||
| * @param dto - the parsed marking request | ||
| * @return whether the hmac was valid | ||
| */ | ||
| public boolean isHmacValid(final AnvilMarkingRequestDTO dto) { | ||
| String expected = UserAuthenticationManager.calculateHMAC(hmacSecret, dto.getPayload()); | ||
| return expected.equals(dto.getHmac()); | ||
| } | ||
|
|
||
| /** | ||
| * Validates the content of the signed payload string. | ||
| * | ||
| * @param payloadStr - the payload string from the marking request | ||
| * @param userId - the ID of the currently authenticated user | ||
| * @param appId - the app ID from the URL, which must match the payload's skill_id | ||
| * @throws InvalidAnvilMarkingRequestException if the payload is malformed or any validation fails | ||
| */ | ||
| public AnvilPayloadDTO parsePayload( | ||
| final String payloadStr, final long userId, final String appId | ||
| ) throws InvalidAnvilMarkingRequestException { | ||
| try { | ||
| if (payloadStr.length() > 10 * 1024) { | ||
| throw new InvalidAnvilMarkingRequestException("Payload too large", null); | ||
| } | ||
|
|
||
| AnvilPayloadDTO dto = objectMapper.readValue(payloadStr, AnvilPayloadDTO.class); | ||
| if (dto.getUserId() != userId) { | ||
| throw new InvalidAnvilMarkingRequestException("Payload user_id does not match session", null); | ||
| } | ||
| if (dto.getTimestamp().before(new Date(System.currentTimeMillis() - 300_000L))) { | ||
| throw new InvalidAnvilMarkingRequestException("Payload timestamp is outside the allowed window", null); | ||
| } | ||
| if (!dto.getSkillId().equals(appId)) { | ||
| throw new InvalidAnvilMarkingRequestException("Payload skill_id does not match app", null); | ||
| } | ||
| return dto; | ||
| } catch (final JsonProcessingException e) { | ||
| throw new InvalidAnvilMarkingRequestException("Invalid payload", e.getMessage()); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Records a validated skills attempt. | ||
| * | ||
| * @param attempt - the validated payload DTO | ||
| */ | ||
| public void recordAttempt(final AnvilPayloadDTO attempt) throws SegueDatabaseException { | ||
| skillsAttemptManager.registerSkillsAttempt(attempt); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
src/main/java/uk/ac/cam/cl/dtg/isaac/dao/PgSkillsAttemptManager.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| package uk.ac.cam.cl.dtg.isaac.dao; | ||
|
|
||
| import com.google.inject.Inject; | ||
| import uk.ac.cam.cl.dtg.isaac.dto.AnvilPayloadDTO; | ||
| import uk.ac.cam.cl.dtg.isaac.quiz.ISkillsAttemptManager; | ||
| import uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException; | ||
| import uk.ac.cam.cl.dtg.segue.database.PostgresSqlDb; | ||
|
|
||
| import java.sql.SQLException; | ||
| import java.sql.Timestamp; | ||
|
|
||
| /** PostgreSQL-backed persistence for Anvil skills question attempts. */ | ||
| public class PgSkillsAttemptManager implements ISkillsAttemptManager { | ||
| private final PostgresSqlDb database; | ||
|
|
||
| @Inject | ||
| public PgSkillsAttemptManager(final PostgresSqlDb database) { | ||
| this.database = database; | ||
| } | ||
|
|
||
| @Override | ||
| public void registerSkillsAttempt(final AnvilPayloadDTO attempt) throws SegueDatabaseException { | ||
| try (var conn = database.getDatabaseConnection(); | ||
| var pst = conn.prepareStatement(""" | ||
| INSERT INTO skills_question_attempts ( | ||
| id, user_id, skill_assignment_id, skill_id, subskill_id, question, question_attempt, marks, | ||
| timestamp | ||
| ) VALUES (?, ?, ?, ?, ?, (?::jsonb), (?::jsonb), ?, ?)""")) { | ||
| pst.setObject(1, attempt.getId()); | ||
| pst.setLong(2, attempt.getUserId()); | ||
| pst.setString(3, attempt.getSkillAssignmentId()); | ||
| pst.setString(4, attempt.getSkillId()); | ||
| pst.setString(5, attempt.getSubskillId()); | ||
| pst.setString(6, attempt.getQuestion().toString()); | ||
| pst.setString(7, attempt.getQuestionAttempt().toString()); | ||
| pst.setInt(8, (Integer) attempt.getMarks()); | ||
| pst.setTimestamp(9, new Timestamp(attempt.getTimestamp().getTime())); | ||
| pst.executeUpdate(); | ||
| } catch (final SQLException e) { | ||
| if ("23505".equals(e.getSQLState())) { | ||
| throw new SegueDatabaseException("Duplicate attempt ID"); | ||
| } | ||
| throw new SegueDatabaseException("Something went wrong saving the attempt."); | ||
| } | ||
| } | ||
| } |
44 changes: 44 additions & 0 deletions
44
src/main/java/uk/ac/cam/cl/dtg/isaac/dto/AnvilMarkingRequestDTO.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| package uk.ac.cam.cl.dtg.isaac.dto; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonCreator; | ||
| import com.fasterxml.jackson.annotation.JsonProperty; | ||
|
|
||
| /** | ||
| * DTO representing the request received from the external Anvil marking server. | ||
| */ | ||
| public class AnvilMarkingRequestDTO { | ||
| private final String payload; | ||
| private final String hmac; | ||
|
|
||
| /** | ||
| * Constructor. | ||
| * | ||
| * @param payload - the signed payload from the marking server | ||
| * @param hmac - the HMAC-SHA256 hex digest authenticating the payload | ||
| */ | ||
| @JsonCreator | ||
| public AnvilMarkingRequestDTO( | ||
| @JsonProperty(value = "payload", required = true) final String payload, | ||
| @JsonProperty(value = "hmac", required = true) final String hmac) { | ||
| this.payload = payload; | ||
| this.hmac = hmac; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the payload. | ||
| * | ||
| * @return the signed payload string | ||
| */ | ||
| public String getPayload() { | ||
| return payload; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the HMAC signature. | ||
| * | ||
| * @return the HMAC-SHA256 hex digest | ||
| */ | ||
| public String getHmac() { | ||
| return hmac; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.