Skip to content
Open
Show file tree
Hide file tree
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 Jun 9, 2026
6278774
check that app exists
barna-isaac Jun 10, 2026
7a434ed
clean up comments
barna-isaac Jun 10, 2026
45018e8
check that app_id is a valid AnvilApp
barna-isaac Jun 10, 2026
767fd0a
extract ElasticSearchHelper
barna-isaac Jun 10, 2026
db449c7
add test stub for happy path
barna-isaac Jun 10, 2026
220cf77
introduce validation for payload
barna-isaac Jun 10, 2026
b0b2d76
add two test cases for request payload validation
barna-isaac Jun 10, 2026
e567f8a
validate HMAC
barna-isaac Jun 15, 2026
c8d4df2
validate payload contents
barna-isaac Jun 15, 2026
ab2cd29
fix checkstyle
barna-isaac Jun 15, 2026
f79f4e5
use data provider for tests
barna-isaac Jun 15, 2026
c3444f2
minor refactor
barna-isaac Jun 15, 2026
35421fc
simplify a few test cases
barna-isaac Jun 15, 2026
7890d39
actually record answers
barna-isaac Jun 15, 2026
d60bd9b
minor changes
barna-isaac Jun 16, 2026
13aab68
WIP: validate all payload fields
barna-isaac Jun 17, 2026
3bdfae8
finish validating payload content
barna-isaac Jun 17, 2026
eb8d3e2
disallow large payloads
barna-isaac Jun 17, 2026
d9f141e
use framework to parse request body
barna-isaac Jun 17, 2026
dd50245
attach skills facade
barna-isaac Jun 17, 2026
7e66d85
just require anvil child, root is always page
barna-isaac Jun 17, 2026
642d247
record answers to database
barna-isaac Jun 17, 2026
273a7a9
treat 2 question fields as opaque json
barna-isaac Jun 18, 2026
914be99
use skill attempt id as a nonce
barna-isaac Jun 18, 2026
8eb0544
use UUID type for the id
barna-isaac Jun 18, 2026
f7fdb61
add foreign key constraint for user id
barna-isaac Jun 18, 2026
298816e
endpoint echoes back dto
barna-isaac Jun 18, 2026
b230adc
fix checkstyle problems
barna-isaac Jun 18, 2026
8bf13c7
only allow endpoint if HMAC_SECRET is set
barna-isaac Jun 19, 2026
4191922
add logging, minor refactors
barna-isaac Jun 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions src/main/java/uk/ac/cam/cl/dtg/isaac/api/SkillsFacade.java
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 warning

Code scanning / CodeQL

Log Injection Medium

This log entry depends on a
user-provided value
.
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment thread
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();
}
}
}
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);
}
}
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");
}
}
}
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 src/main/java/uk/ac/cam/cl/dtg/isaac/dto/AnvilPayloadDTO.java
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;
}
}
1 change: 1 addition & 0 deletions src/main/java/uk/ac/cam/cl/dtg/segue/api/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ public enum AuthenticationCaveat {
* Constant representing the key for the HMAC Salt - used in HMAC calculations.
*/
public static final String HMAC_SALT = "HMAC_SALT";
public static final String SKILLS_HMAC_SECRET = "SKILLS_HMAC_SECRET";
public static final int TRUNCATED_TOKEN_LENGTH = 8;

// Search stuff
Expand Down
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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
* interacting with the server. As the server runs in-process, mocking and debugging still work.
*/
public class IsaacIntegrationTestWithREST extends AbstractIsaacIntegrationTest {
static final ElasticSearchTestHelper elasticHelper =
new ElasticSearchTestHelper(elasticSearchProvider, contentManager, contentMapper);

private final Set<Executable> cleanups = new HashSet<>();

@SuppressWarnings({"checkstyle:EmptyCatchBlock", "checkstyle:MissingJavadocMethod"})
Expand Down Expand Up @@ -154,7 +157,8 @@ public TestResponse get(final String url) {

public TestResponse post(final String url, final Object body) {
Invocation.Builder request = client.target(baseUrl + url).request(MediaType.APPLICATION_JSON);
Response response = builder.apply(request).post(Entity.json(body));
Object serializable = body instanceof JSONObject j ? j.toString() : body;
Response response = builder.apply(request).post(Entity.json(serializable));
registerCleanup.accept(response::close);
return new TestResponse(response);
}
Expand Down
Loading
Loading