Skip to content
Open
Show file tree
Hide file tree
Changes from 20 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package uk.ac.cam.cl.dtg.isaac;

import uk.ac.cam.cl.dtg.isaac.dto.AnvilPayloadDTO;

public interface ISkillsAttemptManager {
void registerSkillsAttempt(final AnvilPayloadDTO attempt);
}
95 changes: 95 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,95 @@
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.AnvilMarkingResponseDTO;
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.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 AnvilMarkingResponseDTO markingResponse) {
try {
RegisteredUserDTO currentUser = userManager.getCurrentRegisteredUser(request);
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();
}

if (!skillsManager.isHmacValid(markingResponse)) {
return new SegueErrorResponse(Status.BAD_REQUEST, "Invalid HMAC signature").toResponse();
}

var payloadDTO = skillsManager.parsePayload(markingResponse.getPayload(), currentUser.getId(), appId);
skillsManager.recordAttempt(payloadDTO);

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,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.ISkillsAttemptManager;
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;
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 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
* @param appId - the app ID from the URL, which must match the payload's skill_id
* @throws InvalidMarkingResponseException if the payload is malformed or any validation fails
*/
public AnvilPayloadDTO parsePayload(
final String payloadStr, final long userId, final String appId
) throws InvalidMarkingResponseException {
try {
if (payloadStr.length() > 10 * 1024) {
throw new InvalidMarkingResponseException("Payload too large");
}

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");
}
if (!dto.getSkillId().equals(appId)) {
throw new InvalidMarkingResponseException("Payload skill_id does not match app");
}
return dto;
} catch (final JsonProcessingException e) {
throw new InvalidMarkingResponseException("Invalid payload");
}
}

/**
* Records a validated skills attempt.
*
* @param attempt - the validated payload DTO
*/
public void recordAttempt(final AnvilPayloadDTO attempt) {
skillsAttemptManager.registerSkillsAttempt(attempt);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package uk.ac.cam.cl.dtg.isaac.dao;

import com.google.inject.Inject;
import uk.ac.cam.cl.dtg.isaac.ISkillsAttemptManager;
import uk.ac.cam.cl.dtg.isaac.dto.AnvilPayloadDTO;
import uk.ac.cam.cl.dtg.segue.database.PostgresSqlDb;

import java.sql.SQLException;
import java.sql.Timestamp;

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) {
try (var conn = database.getDatabaseConnection();
var pst = conn.prepareStatement(
"INSERT INTO skills_question_attempts (user_id, timestamp) VALUES (?, ?)")) {
pst.setLong(1, attempt.getUserId());
pst.setTimestamp(2, new Timestamp(attempt.getTimestamp().getTime()));
pst.executeUpdate();
} catch (final SQLException e) {
throw new RuntimeException("Failed to record skills attempt", e);
}
}
}
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;
}
}
79 changes: 79 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,79 @@
package uk.ac.cam.cl.dtg.isaac.dto;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.Nulls;
import org.apache.commons.lang3.Validate;

import java.util.Date;
import java.util.UUID;
import java.util.stream.Stream;

/**
* DTO representing the signed payload content from the external Anvil marking server.
*/
public class AnvilPayloadDTO {
private final UUID id;
private final Long userId;
private final String skillAssignmentId;
private final String skillId;
private final String subskillId;
private final Question question;
private final String questionAttempt;
private final Number marks;
private final Date timestamp;

/**
* Constructor.
*
* @param id - UUID identifying this attempt
* @param userId - the ID of the user who answered the question
* @param skillAssignmentId - the skill assignment ID (currently always null)
* @param skillId - the skill ID, must match the app ID from the URL
* @param subskillId - the subskill ID
* @param question - the question content
* @param questionAttempt - the student's answer
* @param marks - the marks awarded (0 or 1)
* @param timestamp - the datetime at which the response was signed
*/
@JsonCreator
public AnvilPayloadDTO(
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "id", required = true) final UUID id,
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "user_id", required = true) final Long userId,
@JsonProperty(value = "skill_assignment_id", required = true) final String skillAssignmentId,
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "skill_id", required = true) final String skillId,
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "subskill_id", required = true) final String subskillId,
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "question", required = true) final Question question,
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "question_attempt", required = true) final String questionAttempt,
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "marks", required = true) final Number marks,
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "timestamp", required = true) final Date timestamp) {
Validate.isTrue(userId != 0);
Validate.isTrue(skillAssignmentId == null);
Validate.isTrue((marks instanceof Integer n) && (n == 0 || n == 1));
Stream.of(skillId, subskillId, question.answer, question.text).forEach(Validate::notEmpty);

this.id = id;
this.userId = userId;
this.skillAssignmentId = skillAssignmentId;
this.skillId = skillId;
this.subskillId = subskillId;
this.question = question;
this.questionAttempt = questionAttempt;
this.marks = marks;
this.timestamp = timestamp;
}

public Long getUserId() { return userId; }
public String getSkillAssignmentId() { return skillAssignmentId; }
public String getSkillId() { return skillId; }
public String getSubskillId() { return subskillId; }
public String getQuestionAttempt() { return questionAttempt; }
public Number getMarks() { return marks; }
public Date getTimestamp() { return timestamp; }

public record Question(
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "text", required = true) String text,
@JsonSetter(nulls = Nulls.FAIL) @JsonProperty(value = "answer", required = true) String answer
) {}
}
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,6 @@
CREATE TABLE public.skills_question_attempts (
user_id INTEGER NOT NULL,
timestamp TIMESTAMP WITH TIME ZONE NOT NULL
);

ALTER TABLE public.skills_question_attempts OWNER to rutherford;
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,16 @@ CREATE TABLE public.user_bookmarks (

ALTER TABLE public.user_bookmarks OWNER TO rutherford;

--
-- Name: skill_question_attempts; Type: TABLE; Schema: public; Owner: rutherford
--
CREATE TABLE public.skills_question_attempts (
user_id INTEGER NOT NULL,
timestamp TIMESTAMP WITH TIME ZONE NOT NULL
);

ALTER TABLE public.skills_question_attempts OWNER to rutherford;

--
-- Name: user_credentials; Type: TABLE; Schema: public; Owner: rutherford
--
Expand Down
Loading
Loading