-
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 12 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
90 changes: 90 additions & 0 deletions
90
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,90 @@ | ||
| 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.InvalidMarkingResponseException; | ||
| 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.dto.SegueErrorResponse; | ||
| 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.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.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) | ||
| public Response answerQuestion(@Context final HttpServletRequest request, | ||
| @PathParam("appId") final String appId, | ||
| final String body) { | ||
| try { | ||
| var currentUser = userManager.getCurrentRegisteredUser(request); | ||
| var markingResponse = skillsManager.parseResponse(body); | ||
| if (!skillsManager.isHmacValid(markingResponse)) { | ||
| return new SegueErrorResponse(Status.BAD_REQUEST, "Invalid HMAC signature").toResponse(); | ||
| } | ||
| skillsManager.validatePayload(markingResponse.getPayload(), currentUser.getId()); | ||
| if (!(this.contentManager.getContentDOById(appId) instanceof AnvilApp)) { | ||
| 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(); | ||
| } | ||
| return Response.ok().build(); | ||
| } catch (final NoUserLoggedInException e) { | ||
| return SegueErrorResponse.getNotLoggedInResponse(); | ||
| } catch (final InvalidMarkingResponseException e) { | ||
| return new SegueErrorResponse(Status.BAD_REQUEST, e.getMessage()).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(); | ||
| } | ||
| } | ||
| } | ||
13 changes: 13 additions & 0 deletions
13
src/main/java/uk/ac/cam/cl/dtg/isaac/api/managers/InvalidMarkingResponseException.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,13 @@ | ||
| 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 InvalidMarkingResponseException extends Exception { | ||
| /** | ||
| * Constructor with message. | ||
| */ | ||
| public InvalidMarkingResponseException(final String message) { | ||
| super(message); | ||
| } | ||
| } |
81 changes: 81 additions & 0 deletions
81
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,81 @@ | ||
| 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.AnvilMarkingResponseDTO; | ||
| import uk.ac.cam.cl.dtg.isaac.dto.AnvilPayloadDTO; | ||
| import uk.ac.cam.cl.dtg.segue.api.managers.UserAuthenticationManager; | ||
| 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; | ||
|
|
||
| /** | ||
| * Constructor. | ||
| * | ||
| * @param properties - application configuration | ||
| */ | ||
| @Inject | ||
| public SkillsManager(final AbstractConfigLoader properties) { | ||
| this.hmacSecret = properties.getProperty(SKILLS_HMAC_SECRET); | ||
| } | ||
|
|
||
| /** | ||
| * Parses and validates the raw JSON body from the external marking server. | ||
| * | ||
| * @param body - the raw JSON request body | ||
| * @return the deserialised marking response | ||
| * @throws InvalidMarkingResponseException if the body is missing or malformed | ||
| */ | ||
| public AnvilMarkingResponseDTO parseResponse(final String body) throws InvalidMarkingResponseException { | ||
| try { | ||
| return objectMapper.readValue(body, AnvilMarkingResponseDTO.class); | ||
| } catch (final JsonProcessingException e) { | ||
| throw new InvalidMarkingResponseException("Invalid JSON object submitted"); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Verifies that the HMAC in the DTO matches the expected signature of the payload. | ||
| * | ||
| * @param dto - the parsed marking response | ||
| * @return whether the hmac was valid | ||
| */ | ||
| public boolean isHmacValid(final AnvilMarkingResponseDTO 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 response | ||
| * @param userId - the ID of the currently authenticated user | ||
| * @throws InvalidMarkingResponseException if the payload is malformed, the user ID does not match, | ||
| * or the timestamp is outside the allowed window | ||
| */ | ||
| public void validatePayload(final String payloadStr, final long userId) throws InvalidMarkingResponseException { | ||
| try { | ||
| AnvilPayloadDTO dto = objectMapper.readValue(payloadStr, AnvilPayloadDTO.class); | ||
| if (dto.getUserId() != userId) { | ||
| throw new InvalidMarkingResponseException("Payload user_id does not match session"); | ||
| } | ||
| if (dto.getTimestamp().before(new Date(System.currentTimeMillis() - 300_000L))) { | ||
| throw new InvalidMarkingResponseException("Payload timestamp is outside the allowed window"); | ||
| } | ||
| } catch (final JsonProcessingException e) { | ||
| throw new InvalidMarkingResponseException("Invalid payload"); | ||
| } | ||
| } | ||
| } |
44 changes: 44 additions & 0 deletions
44
src/main/java/uk/ac/cam/cl/dtg/isaac/dto/AnvilMarkingResponseDTO.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 response received from the external Anvil marking server. | ||
| */ | ||
| public class AnvilMarkingResponseDTO { | ||
| 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 AnvilMarkingResponseDTO( | ||
| @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; | ||
| } | ||
| } |
46 changes: 46 additions & 0 deletions
46
src/main/java/uk/ac/cam/cl/dtg/isaac/dto/AnvilPayloadDTO.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.dto; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonCreator; | ||
| import com.fasterxml.jackson.annotation.JsonProperty; | ||
|
|
||
| import java.util.Date; | ||
|
|
||
| /** | ||
| * DTO representing the signed payload content from the external Anvil marking server. | ||
| */ | ||
| public class AnvilPayloadDTO { | ||
| private final long userId; | ||
| private final Date timestamp; | ||
|
|
||
| /** | ||
| * Constructor. | ||
| * | ||
| * @param userId - the ID of the user who answered the question | ||
| * @param timestamp - the datetime at which the response was signed | ||
| */ | ||
| @JsonCreator | ||
| public AnvilPayloadDTO( | ||
| @JsonProperty(value = "user_id", required = true) final long userId, | ||
| @JsonProperty(value = "timestamp", required = true) final Date timestamp) { | ||
| this.userId = userId; | ||
| this.timestamp = timestamp; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the user ID. | ||
| * | ||
| * @return the user ID | ||
| */ | ||
| public long getUserId() { | ||
| return userId; | ||
| } | ||
|
|
||
| /** | ||
| * Gets the timestamp. | ||
| * | ||
| * @return the signing timestamp | ||
| */ | ||
| public Date getTimestamp() { | ||
| return timestamp; | ||
| } | ||
| } |
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
47 changes: 47 additions & 0 deletions
47
src/test/java/uk/ac/cam/cl/dtg/isaac/api/ElasticSearchTestHelper.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,47 @@ | ||
| package uk.ac.cam.cl.dtg.isaac.api; | ||
|
|
||
| import org.json.JSONObject; | ||
| import uk.ac.cam.cl.dtg.isaac.dos.content.Content; | ||
| import uk.ac.cam.cl.dtg.segue.dao.content.ContentSubclassMapper; | ||
| import uk.ac.cam.cl.dtg.segue.dao.content.GitContentManager; | ||
| import uk.ac.cam.cl.dtg.segue.etl.ElasticSearchIndexer; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| import static org.testcontainers.shaded.com.google.common.collect.Maps.immutableEntry; | ||
|
|
||
| @SuppressWarnings("checkstyle:MissingJavadocType") | ||
| public class ElasticSearchTestHelper { | ||
| private final ElasticSearchIndexer elasticSearchProvider; | ||
| private final GitContentManager contentManager; | ||
| private final ContentSubclassMapper contentMapper; | ||
|
|
||
| public ElasticSearchTestHelper(final ElasticSearchIndexer elasticSearchProvider, | ||
| final GitContentManager contentManager, | ||
| final ContentSubclassMapper contentMapper) { | ||
| this.elasticSearchProvider = elasticSearchProvider; | ||
| this.contentManager = contentManager; | ||
| this.contentMapper = contentMapper; | ||
| } | ||
|
|
||
| public <T extends Content> T persist(final T content) throws Exception { | ||
| elasticSearchProvider.bulkIndexWithIDs( | ||
| contentManager.getCurrentContentSHA(), | ||
| "content", | ||
| List.of(immutableEntry( | ||
| content.getId(), contentMapper.getSharedContentObjectMapper().writeValueAsString(content)) | ||
| ) | ||
| ); | ||
| return content; | ||
| } | ||
|
|
||
| public JSONObject persistJSON(final JSONObject contentJSON) throws Exception { | ||
| contentJSON.put("id", "i1"); | ||
| elasticSearchProvider.bulkIndexWithIDs( | ||
| contentManager.getCurrentContentSHA(), | ||
| "content", | ||
| List.of(immutableEntry("i1", contentJSON.toString())) | ||
| ); | ||
| return contentJSON; | ||
| } | ||
| } |
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
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.