Files
lincodex/backend/integration_test/assessment_practice_http_test.go

489 lines
22 KiB
Go

//go:build integration
package integration_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/practice"
)
const (
assessmentPracticeTimeout = 6 * time.Minute
// practiceHiddenMarker is part of every hidden test text, so a response
// that leaks hidden content is found by a substring search.
practiceHiddenMarker = "hidden-secret"
practiceSource = "print(sum(map(int, input().split())))\n"
)
func TestAssessmentPracticeSubmissionStorage(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), assessmentPracticeTimeout)
defer cancel()
harness := newPracticeHarness(ctx, t, env, func(parts assessmentHarnessParts) (*practice.Service, error) {
return practice.NewService(parts.transactor, parts.keyring, parts.clock.Now, true)
})
owner := newPracticeCandidate(ctx, t, harness, "practice-owner", 10)
other := newPracticeCandidate(ctx, t, harness, "practice-other", 20)
// firstRun is the debug run that the first case stores; it stays queued,
// as no worker runs here, until a later case gives it a result.
var firstRun uuid.UUID
t.Run("debug run is stored with its job and shows no hidden content", func(t *testing.T) {
body := practiceRunBody(t, owner.practiceID, "python", practiceSource, []domain.PracticeTest{{Input: "4 5\n", ExpectedOutput: "9\n"}})
created := practiceRunRequest(t, harness, owner, body, "run-first")
if created.Code != http.StatusAccepted {
t.Fatalf("create run = %d %s", created.Code, created.Body.String())
}
if created.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("run Cache-Control = %q, want no-store", created.Header().Get("Cache-Control"))
}
run := decodePracticeRun(t, created)
if run.ItemID != owner.practiceID || run.State != "queued" || run.Result != nil || run.FailureReason != nil || run.FinishedAt != nil {
t.Fatalf("created run = %+v, want a queued run of the practice", run)
}
assertPracticeResponseIsPublic(t, created)
assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1)
firstRun = run.ID
replay := practiceRunRequest(t, harness, owner, body, "run-first")
if replay.Code != http.StatusAccepted || decodePracticeRun(t, replay).ID != run.ID {
t.Fatalf("same-key replay = %d %s, want the stored run %s", replay.Code, replay.Body.String(), run.ID)
}
assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1)
changed := practiceRunBody(t, owner.practiceID, "python", practiceSource+"# changed\n", nil)
requireSessionProblem(t, practiceRunRequest(t, harness, owner, changed, "run-first"), http.StatusUnprocessableEntity, "idempotency_key_reused")
assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1)
read := practiceRunRead(t, harness, owner, owner.attemptID, run.ID)
if read.Code != http.StatusOK || decodePracticeRun(t, read).ID != run.ID {
t.Fatalf("read run = %d %s", read.Code, read.Body.String())
}
requireSessionProblem(t, practiceRunRead(t, harness, other, owner.attemptID, run.ID), http.StatusNotFound, "not_found")
requireSessionProblem(t, practiceRunRead(t, harness, owner, owner.attemptID, uuid.New()), http.StatusNotFound, "not_found")
requireSessionProblem(t, practiceRunRead(t, harness, owner, other.attemptID, run.ID), http.StatusNotFound, "not_found")
})
t.Run("refusals store nothing", func(t *testing.T) {
foreign := practiceRunBody(t, owner.practiceID, "python", practiceSource, nil)
requireSessionProblem(t, practiceRunRequest(t, harness, other, foreign, "run-foreign"), http.StatusNotFound, "not_found")
closed := practiceRunBody(t, owner.additionalID, "python", practiceSource, nil)
requireSessionProblem(t, practiceRunRequest(t, harness, owner, closed, "run-closed"), http.StatusConflict, "state_conflict")
tooLong := practiceRunBody(t, owner.practiceID, "python", strings.Repeat("x", 1001), nil)
requireSessionProblem(t, practiceRunRequest(t, harness, owner, tooLong, "run-too-long"), http.StatusBadRequest, "validation_failed")
assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1)
assertPracticeRows(t, ctx, harness.pool, owner.additionalID, "public", 0)
})
t.Run("a stored result is shown without hidden groups", func(t *testing.T) {
// A result that holds a hidden group, which a debug run never gets,
// proves that the presentation drops it.
storePracticeResult(t, ctx, harness.pool, firstRun, domain.PracticeRunResult{
Outcome: domain.PracticeOutcomeWrongAnswer, DurationMs: 42,
Groups: []domain.PracticeGroupOutcome{
{ID: practice.PublicGroupID, Outcome: domain.PracticeOutcomeWrongAnswer, PassedTests: 1, TotalTests: 2, Tests: []domain.PracticeTestOutcome{
{ID: "1", Outcome: domain.PracticeOutcomeAccepted, TimeMs: 3, MemoryKB: 900},
{ID: "2", Outcome: domain.PracticeOutcomeWrongAnswer, TimeMs: 4, MemoryKB: 901},
}},
{ID: "hidden-1", Hidden: true, Outcome: domain.PracticeOutcomeAccepted, PassedTests: 1, TotalTests: 1},
},
})
read := practiceRunRead(t, harness, owner, owner.attemptID, firstRun)
finished := decodePracticeRun(t, read)
if read.Code != http.StatusOK || finished.State != "finished" || finished.Result == nil || len(finished.Result.Tests) != 2 {
t.Fatalf("finished run = %d %s", read.Code, read.Body.String())
}
for _, test := range finished.Result.Tests {
if test.Source != "example" {
t.Fatalf("finished run lists a test from %q", test.Source)
}
}
assertPracticeResponseIsPublic(t, read)
})
t.Run("final source is stored once and never replaced", func(t *testing.T) {
service := harness.service
command := practice.FinalCommand{
ActorID: owner.userID, AttemptID: domain.AssessmentAttemptID(owner.attemptID), PracticeID: owner.practiceID,
IdempotencyKey: "final-first", Language: languagePointer(domain.TaskLanguagePython), Source: practiceSource,
}
first, err := service.SubmitFinal(ctx, command)
if err != nil || first.Replayed || first.Unchanged || first.Practice.Status != domain.AssessmentPracticePending ||
first.Practice.SubmittedAt == nil || first.Practice.ItemID != owner.practiceID {
t.Fatalf("first final submission = %+v, error %v", first, err)
}
assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "final", 1)
replay, err := service.SubmitFinal(ctx, command)
if err != nil || !replay.Replayed || replay.Practice.Status != domain.AssessmentPracticePending {
t.Fatalf("final replay = %+v, error %v", replay, err)
}
repeat := command
repeat.IdempotencyKey = "final-same-source"
same, err := service.SubmitFinal(ctx, repeat)
if err != nil || !same.Unchanged {
t.Fatalf("same final solution under a new key = %+v, error %v", same, err)
}
other := command
other.IdempotencyKey = "final-other-source"
other.Source = practiceSource + "# another solution\n"
if _, err := service.SubmitFinal(ctx, other); !errors.Is(err, practice.ErrStateConflict) {
t.Fatalf("another final solution error = %v, want state conflict", err)
}
reused := command
reused.Source = other.Source
if _, err := service.SubmitFinal(ctx, reused); !errors.Is(err, practice.ErrKeyReused) {
t.Fatalf("final key reused error = %v, want key reused", err)
}
assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "final", 1)
assertFinalSourceIsImmutable(t, ctx, harness.pool, owner.practiceID)
// A practice that failed in the sandbox accepts a solution again; the
// first one stays stored as it was.
if _, err := harness.pool.Exec(ctx, `UPDATE assessment_practices
SET status = 'failed', failure_reason = 'sandbox_error' WHERE id = $1`, owner.practiceID); err != nil {
t.Fatalf("mark practice failed: %v", err)
}
retry := other
retry.IdempotencyKey = "final-after-failure"
again, err := service.SubmitFinal(ctx, retry)
if err != nil || again.Practice.Status != domain.AssessmentPracticePending || again.Practice.FailureReason != "" {
t.Fatalf("final submission after a sandbox failure = %+v, error %v", again, err)
}
assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "final", 2)
})
t.Run("disabled runner stores nothing", func(t *testing.T) {
disabled, err := practice.NewService(postgresadapter.NewTransactor(harness.pool), harness.keyring, time.Now, false)
if err != nil {
t.Fatalf("NewService() error = %v", err)
}
_, err = disabled.SubmitRun(ctx, practice.RunCommand{
ActorID: other.userID, AttemptID: domain.AssessmentAttemptID(other.attemptID), PracticeID: other.practiceID,
IdempotencyKey: "disabled-run", Source: practiceSource, Language: languagePointer(domain.TaskLanguagePython),
})
if !errors.Is(err, practice.ErrUnavailable) {
t.Fatalf("run with a disabled runner error = %v, want unavailable", err)
}
assertPracticeRows(t, ctx, harness.pool, other.practiceID, "public", 0)
})
assertEverySubmissionHasOneJob(t, ctx, harness.pool)
}
// practiceHarness is the attempt router with the practice operations.
type practiceHarness struct {
*assessmentAttemptHTTPHarness
service *practice.Service
passwordHash domain.PasswordHash
// databaseURL names the isolated database of the harness.
databaseURL string
}
// newPracticeHarness builds the router on an isolated, migrated database with
// the reviewed fixture bank, and the practice service that build returns.
func newPracticeHarness(
ctx context.Context,
t *testing.T,
env *testEnvironment,
build func(assessmentHarnessParts) (*practice.Service, error),
) *practiceHarness {
t.Helper()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
var service *practice.Service
attemptHarness := newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, &isolatedEnv, assessment.AssessmentCategoryDecisionSettings{}, func(parts assessmentHarnessParts) []v1.HandlerOption {
built, err := build(parts)
if err != nil {
t.Fatalf("build practice service: %v", err)
}
service = built
return []v1.HandlerOption{v1.WithPractice(v1.NewPracticeHandler(built))}
})
seedAssessmentAttemptHTTPBank(ctx, t, attemptHarness.pool)
passwordHash, err := attemptHarness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
return &practiceHarness{
assessmentAttemptHTTPHarness: attemptHarness, service: service, passwordHash: passwordHash, databaseURL: databaseURL,
}
}
// practiceCandidate is a candidate whose real attempt is at its main practice.
type practiceCandidate struct {
userID uuid.UUID
cookie string
csrf string
remoteAddr string
attemptID uuid.UUID
// practiceID is the main practice, the current item of the attempt.
practiceID uuid.UUID
// additionalID is the additional practice, which is not open while the
// attempt is at the main one.
additionalID uuid.UUID
}
// newPracticeCandidate registers a candidate, starts a real attempt, moves it
// to practice_pending, and assigns its two practices. hostIndex keeps the
// client addresses of candidates apart.
func newPracticeCandidate(ctx context.Context, t *testing.T, harness *practiceHarness, name string, hostIndex int) practiceCandidate {
t.Helper()
address := func(port int) string { return fmt.Sprintf("192.0.2.%d:%d", hostIndex, port) }
user := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, name+"@example.test", harness.passwordHash, true)
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", user.ID); err != nil {
t.Fatalf("set candidate onboarding step: %v", err)
}
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, user.Email.Address(), address(1))
if response := assessmentAttemptQuestionnaireRequest(t, harness.assessmentAttemptHTTPHarness, cookie.Value, csrf, address(2)); response.Code != http.StatusOK {
t.Fatalf("save questionnaire = %d %s", response.Code, response.Body.String())
}
grantCurrentAttemptConsent(t, harness.assessmentAttemptHTTPHarness, cookie, csrf, address(3))
created := assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, name+"-attempt", address(4))
if created.Code != http.StatusCreated {
t.Fatalf("create attempt = %d %s", created.Code, created.Body.String())
}
attemptID := assessmentAttemptIDOf(t, created)
// No flow serves practice items yet, so the fixture moves the attempt to
// its main practice the way the item part will end.
if _, err := harness.pool.Exec(ctx, `UPDATE assessment_attempts
SET state = 'practice_pending', version = version + 1, updated_at = greatest(updated_at, clock_timestamp())
WHERE id = $1`, attemptID); err != nil {
t.Fatalf("move attempt to its practice: %v", err)
}
candidate := practiceCandidate{
userID: user.ID, cookie: cookie.Value, csrf: csrf, remoteAddr: address(5), attemptID: attemptID,
practiceID: createPractice(ctx, t, harness.pool, user.ID, attemptID, domain.AssessmentPracticeMain),
}
candidate.additionalID = createPractice(ctx, t, harness.pool, user.ID, attemptID, domain.AssessmentPracticeAdditional)
return candidate
}
func createPractice(
ctx context.Context,
t *testing.T,
pool *pgxpool.Pool,
userID, attemptID uuid.UUID,
kind domain.AssessmentPracticeKind,
) uuid.UUID {
t.Helper()
id, err := uuid.NewV7()
if err != nil {
t.Fatalf("generate practice ID: %v", err)
}
// A submission is stamped with the database time, so the practice is
// created with it too: a database clock slightly behind the test host
// would otherwise put the first submission before its practice.
var createdAt time.Time
if err := pool.QueryRow(ctx, `SELECT clock_timestamp()`).Scan(&createdAt); err != nil {
t.Fatalf("read database time: %v", err)
}
transactor := postgresadapter.NewTransactor(pool)
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.AssessmentPractices().Create(ctx, domain.AssessmentPractice{
ID: id, AttemptID: domain.AssessmentAttemptID(attemptID), UserID: userID, Kind: kind, Task: practiceTestTask(),
Status: domain.AssessmentPracticeNotStarted, CreatedAt: createdAt.UTC().Truncate(time.Microsecond),
})
})
if err != nil {
t.Fatalf("create %s practice: %v", kind, err)
}
return id
}
// practiceTestTask is a synthetic task whose hidden texts carry
// practiceHiddenMarker.
func practiceTestTask() domain.PracticeTask {
hidden := make([]domain.PracticeTestGroup, 0, domain.PracticeHiddenGroups)
for group := 1; group <= domain.PracticeHiddenGroups; group++ {
hidden = append(hidden, domain.PracticeTestGroup{Tests: []domain.PracticeTest{{
Input: fmt.Sprintf("%s-input-%d\n", practiceHiddenMarker, group),
ExpectedOutput: fmt.Sprintf("%s-output-%d\n", practiceHiddenMarker, group),
}}})
}
return domain.PracticeTask{
Languages: []domain.TaskLanguageCode{domain.TaskLanguagePython, domain.TaskLanguageGo},
MaxSourceLength: 1000, TimeLimitMs: 1000, MemoryLimitMB: 64, OutputLimitKB: 64,
Checker: domain.PracticeChecker{Kind: domain.PracticeCheckerTokens},
PublicTests: []domain.PracticeTest{{Input: "1 2\n", ExpectedOutput: "3\n"}, {Input: "2 2\n", ExpectedOutput: "4\n"}},
HiddenGroups: hidden,
}
}
func practiceRunBody(t *testing.T, itemID uuid.UUID, language, source string, tests []domain.PracticeTest) string {
t.Helper()
body := map[string]any{"item_id": itemID, "language": language, "source_code": source}
if tests != nil {
body["tests"] = tests
}
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal practice run body: %v", err)
}
return string(encoded)
}
func practiceRunRequest(t *testing.T, harness *practiceHarness, candidate practiceCandidate, body, key string) *httptest.ResponseRecorder {
t.Helper()
return assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+candidate.attemptID.String()+"/practice-runs", body,
sessionHTTPTestOrigin, candidate.cookie, candidate.csrf, key, candidate.remoteAddr)
}
func practiceRunRead(t *testing.T, harness *practiceHarness, candidate practiceCandidate, attemptID, runID uuid.UUID) *httptest.ResponseRecorder {
t.Helper()
return assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, http.MethodGet,
"/api/v1/me/assessment-attempts/"+attemptID.String()+"/practice-runs/"+runID.String(), "",
"", candidate.cookie, "", "", candidate.remoteAddr)
}
type practiceRunResponse struct {
ID uuid.UUID `json:"id"`
ItemID uuid.UUID `json:"item_id"`
State string `json:"state"`
FinishedAt *time.Time `json:"finished_at"`
FailureReason *string `json:"failure_reason"`
Result *struct {
Outcome string `json:"outcome"`
Tests []struct {
Source string `json:"source"`
Index int `json:"index"`
Outcome string `json:"outcome"`
} `json:"tests"`
} `json:"result"`
}
func decodePracticeRun(t *testing.T, response *httptest.ResponseRecorder) practiceRunResponse {
t.Helper()
var run practiceRunResponse
if err := json.Unmarshal(response.Body.Bytes(), &run); err != nil || run.ID == uuid.Nil {
t.Fatalf("practice run response %d %s: %v", response.Code, response.Body.String(), err)
}
return run
}
// assertPracticeResponseIsPublic checks that a run response holds only the
// fields of the contract and nothing of the hidden groups or the source.
func assertPracticeResponseIsPublic(t *testing.T, response *httptest.ResponseRecorder) {
t.Helper()
text := response.Body.String()
for _, secret := range []string{practiceHiddenMarker, "hidden-1", "hidden", "print(sum", "expected_output", "input"} {
if strings.Contains(text, secret) {
t.Fatalf("practice run response exposes %q: %s", secret, text)
}
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(response.Body.Bytes(), &fields); err != nil {
t.Fatalf("decode practice run fields: %v", err)
}
allowed := map[string]bool{"id": true, "item_id": true, "state": true, "created_at": true, "finished_at": true, "failure_reason": true, "result": true}
for name := range fields {
if !allowed[name] {
t.Fatalf("practice run response has field %q", name)
}
}
}
func assertPracticeRows(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, mode string, want int) {
t.Helper()
var submissions, jobs int
if err := pool.QueryRow(ctx, `SELECT count(*), count(job.submission_id)
FROM assessment_practice_submissions AS submission
LEFT JOIN assessment_practice_jobs AS job ON job.submission_id = submission.id
WHERE submission.practice_id = $1 AND submission.mode = $2`, practiceID, mode).Scan(&submissions, &jobs); err != nil {
t.Fatalf("count practice rows: %v", err)
}
if submissions != want || jobs != want {
t.Fatalf("%s submissions = %d with %d jobs, want %d of each", mode, submissions, jobs, want)
}
}
func assertEverySubmissionHasOneJob(t *testing.T, ctx context.Context, pool *pgxpool.Pool) {
t.Helper()
var orphans int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions AS submission
WHERE NOT EXISTS (SELECT 1 FROM assessment_practice_jobs AS job WHERE job.submission_id = submission.id)`).Scan(&orphans); err != nil {
t.Fatalf("count submissions without a job: %v", err)
}
if orphans != 0 {
t.Fatalf("%d submissions have no execution job", orphans)
}
}
// assertFinalSourceIsImmutable proves that the database refuses to replace or
// delete a stored final solution, and accepts its result only once.
func assertFinalSourceIsImmutable(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID) {
t.Helper()
var submissionID uuid.UUID
if err := pool.QueryRow(ctx, `SELECT id FROM assessment_practice_submissions WHERE practice_id = $1 AND mode = 'final'`,
practiceID).Scan(&submissionID); err != nil {
t.Fatalf("read final submission: %v", err)
}
statements := map[string]string{
`UPDATE assessment_practice_submissions SET source = 'print(42)' WHERE id = $1`: "assessment_practice_submission_immutable",
`UPDATE assessment_practice_submissions SET language = 'go' WHERE id = $1`: "assessment_practice_submission_immutable",
`DELETE FROM assessment_practice_submissions WHERE id = $1`: "assessment_practice_submission_delete_forbidden",
}
for statement, constraint := range statements {
_, err := pool.Exec(ctx, statement, submissionID)
requireConstraintViolation(t, err, constraint)
}
setResult := `UPDATE assessment_practice_submissions
SET result = '{"outcome":"accepted","groups":[],"duration_ms":1}', result_at = created_at WHERE id = $1`
if _, err := pool.Exec(ctx, setResult, submissionID); err != nil {
t.Fatalf("store the first result: %v", err)
}
_, err := pool.Exec(ctx, setResult, submissionID)
requireConstraintViolation(t, err, "assessment_practice_submission_immutable")
}
func requireConstraintViolation(t *testing.T, err error, constraint string) {
t.Helper()
var databaseError *pgconn.PgError
if !errors.As(err, &databaseError) || databaseError.ConstraintName != constraint {
t.Fatalf("statement error = %v, want a violation of %s", err, constraint)
}
}
func storePracticeResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool, submissionID uuid.UUID, result domain.PracticeRunResult) {
t.Helper()
encoded, err := json.Marshal(result)
if err != nil {
t.Fatalf("marshal practice result: %v", err)
}
if _, err := pool.Exec(ctx, `UPDATE assessment_practice_submissions SET result = $2, result_at = created_at WHERE id = $1`,
submissionID, encoded); err != nil {
t.Fatalf("store practice result: %v", err)
}
if _, err := pool.Exec(ctx, `UPDATE assessment_practice_jobs
SET state = 'finished', finished_at = greatest(created_at, clock_timestamp()), updated_at = greatest(updated_at, clock_timestamp())
WHERE submission_id = $1`, submissionID); err != nil {
t.Fatalf("finish practice job: %v", err)
}
}
func languagePointer(language domain.TaskLanguageCode) *domain.TaskLanguageCode {
return &language
}