feat(assessment): assign the demonstration category and keep result history

This commit is contained in:
shira committed 2026-10-09 00:35:13 +03:00
1 parent b3c6dc870b
commit 8277133712
61 files changed
+4338 -268

No files matched your search

@@ -21,8 +21,6 @@ type AssessmentCategoryDecisionSettings struct {
SyntheticDemoAssignmentsEnabled bool
}
// AssessmentCategoryReviewPins identify one exact reviewed source. The
// repository must not substitute a current opening or a different manifest.
// AssessmentCategoryDecisionRepository is bound to the finalization
// transaction. Its category lock is acquired after the caller has obtained
// C3, candidate/specialization scope, and the attempt row lock, in that order.
@@ -35,6 +33,9 @@ type AssessmentCategoryDecisionRepository interface {
candidateID uuid.UUID,
specialization domain.SpecializationCode,
) (domain.CandidateAssessmentCategory, bool, error)
// GetSyntheticCategoryReview takes the pins of one exact reviewed source.
// The repository must not substitute a current opening or a different
// manifest.
GetSyntheticCategoryReview(
ctx context.Context,
openingID uuid.UUID,
@@ -0,0 +1,161 @@
package assessment
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// CategoryAttestation describes one stored attestation of a synthetic
// demonstration category. It holds no candidate data.
type CategoryAttestation struct {
ReviewID uuid.UUID
OpeningID uuid.UUID
Category domain.AssessmentCategory
ProductPolicyVersion int32
ReviewedBy domain.AssessmentOperator
// Created is false when an identical attestation already existed.
Created bool
}
// CategoryAttestor lets an operator attest the exact current opening of a
// category, its published manifest, and the product policy now in force as a
// source for synthetic demonstration categories. The attestation row is the
// audit record: it is immutable and keeps the operator handle and the database
// time. It grants nothing by itself; assignment also needs the runtime gate.
type CategoryAttestor struct {
transactor outbound.Transactor
}
func NewCategoryAttestor(transactor outbound.Transactor) (*CategoryAttestor, error) {
if transactor == nil {
return nil, errors.New("assessment.NewCategoryAttestor - transactor must be set")
}
return &CategoryAttestor{transactor: transactor}, nil
}
// Attest resolves the same current selection that a new attempt would pin and
// stores the attestation in one transaction. The policy must be the complete
// explicit demo_basic demonstration policy. Repeating the call for the same
// opening, manifest, and policy returns the stored attestation unchanged.
func (attestor *CategoryAttestor) Attest(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
language *domain.TaskLanguageCode,
actor string,
) (CategoryAttestation, error) {
const location = "CategoryAttestor.Attest"
operator, err := domain.ParseAssessmentOperator(actor)
if err != nil || !specialization.IsKnown() || !grade.IsKnown() || language != nil && !language.IsKnown() {
return CategoryAttestation{}, fmt.Errorf("%s - validate request: %w", location, domain.ErrInvalidAssessmentCategory)
}
reviewID, err := uuid.NewV7()
if err != nil {
return CategoryAttestation{}, fmt.Errorf("%s - generate review ID: %w", location, err)
}
var result CategoryAttestation
err = attestor.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
selection, err := unit.AssessmentBank().ResolveCurrentSelection(ctx, specialization, grade, language)
if err != nil {
return fmt.Errorf("resolve current selection: %w", err)
}
policy, err := unit.Policies().GetByID(ctx, selection.ProductPolicyVersionID)
if err != nil {
return fmt.Errorf("read product policy: %w", err)
}
if err := domain.ValidateSyntheticCategoryPolicy(policy); err != nil {
return err
}
result, err = storeCategoryAttestation(ctx, unit, selection, policy, operator, reviewID)
return err
})
if err != nil {
return CategoryAttestation{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
// storeCategoryAttestation returns the stored attestation of the exact opening,
// manifest, and policy, or creates it.
func storeCategoryAttestation(
ctx context.Context,
unit outbound.UnitOfWork,
selection outbound.AssessmentBankSelection,
policy domain.PolicyVersion,
operator domain.AssessmentOperator,
reviewID uuid.UUID,
) (CategoryAttestation, error) {
repository := unit.AssessmentAttempts()
category := selection.Opening.Category
stored, err := readStoredCategoryAttestation(ctx, repository, selection, policy)
if err == nil {
return stored, nil
}
if !errors.Is(err, errCategoryAttestationMissing) {
return CategoryAttestation{}, err
}
at, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return CategoryAttestation{}, fmt.Errorf("read database time: %w", err)
}
review, err := domain.NewAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{
ID: reviewID, OpeningID: selection.Opening.ID, Category: category,
Source: domain.AssessmentCategorySourceSyntheticDemo, OpeningManifestHash: selection.ManifestSHA,
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
ReviewedBy: operator, ReviewedAt: at.UTC().Truncate(time.Microsecond),
})
if err != nil {
return CategoryAttestation{}, fmt.Errorf("build attestation: %w", err)
}
created, err := repository.CreateSyntheticCategoryReview(ctx, review)
if err != nil {
return CategoryAttestation{}, fmt.Errorf("store attestation: %w", err)
}
if !created {
// A concurrent operator stored the same exact source first.
stored, err := readStoredCategoryAttestation(ctx, repository, selection, policy)
if errors.Is(err, errCategoryAttestationMissing) {
return CategoryAttestation{}, fmt.Errorf("attestation vanished after a conflict: %w", err)
}
return stored, err
}
return CategoryAttestation{
ReviewID: reviewID, OpeningID: selection.Opening.ID, Category: category,
ProductPolicyVersion: policy.Version(), ReviewedBy: operator, Created: true,
}, nil
}
var errCategoryAttestationMissing = errors.New("category attestation is missing")
// readStoredCategoryAttestation reads the attestation of the exact opening,
// manifest, and policy, or reports errCategoryAttestationMissing.
func readStoredCategoryAttestation(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
selection outbound.AssessmentBankSelection,
policy domain.PolicyVersion,
) (CategoryAttestation, error) {
category := selection.Opening.Category
existing, found, err := repository.GetSyntheticCategoryReview(
ctx, selection.Opening.ID, category, selection.ManifestSHA,
policy.ID(), policy.Version(), selection.Opening.PolicyVersionID,
)
if err != nil {
return CategoryAttestation{}, fmt.Errorf("read existing attestation: %w", err)
}
if !found {
return CategoryAttestation{}, errCategoryAttestationMissing
}
snapshot := existing.Snapshot()
return CategoryAttestation{
ReviewID: snapshot.ID, OpeningID: snapshot.OpeningID, Category: category,
ProductPolicyVersion: snapshot.ProductPolicyVersion, ReviewedBy: snapshot.ReviewedBy,
}, nil
}
@@ -4,9 +4,9 @@ import (
"context"
"crypto/hmac"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"strconv"
"strings"
"time"
@@ -48,12 +48,18 @@ type AssessmentResultHistoryPage struct {
NextCursor string
}
type AssessmentResultHistoryService struct {
repository AssessmentResultHistoryRepository
keyring Keyring
// ResultHistoryCursorSigner signs history page positions under a key that no
// other operation uses.
type ResultHistoryCursorSigner interface {
ResultHistoryCursorSignature(position, candidateID string) [outbound.IdempotencyDigestSize]byte
}
func NewAssessmentResultHistoryService(repository AssessmentResultHistoryRepository, keyring Keyring) AssessmentResultHistoryService {
type AssessmentResultHistoryService struct {
repository AssessmentResultHistoryRepository
keyring ResultHistoryCursorSigner
}
func NewAssessmentResultHistoryService(repository AssessmentResultHistoryRepository, keyring ResultHistoryCursorSigner) AssessmentResultHistoryService {
return AssessmentResultHistoryService{repository: repository, keyring: keyring}
}
@@ -99,9 +105,40 @@ func (service AssessmentResultHistoryService) ListMine(
return AssessmentResultHistoryPage{Entries: entries, NextCursor: nextCursor}, nil
}
// ListMyResults serves the candidate's result history. The candidate account
// check and the page read share one read-only snapshot, so a page never mixes
// states of two moments. The page contains only the candidate's own immutable
// root and corrective results; an employer account is refused.
func (service *AttemptService) ListMyResults(
ctx context.Context,
userID uuid.UUID,
cursor string,
limit int32,
) (AssessmentResultHistoryPage, error) {
const location = "AttemptService.ListMyResults"
var page AssessmentResultHistoryPage
err := service.snapshotExecutor.WithinReadOnlySnapshot(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil {
return err
}
var listErr error
signer, ok := service.keyring.(ResultHistoryCursorSigner)
if !ok {
return fmt.Errorf("%s - the keyring cannot sign history cursors", location)
}
page, listErr = NewAssessmentResultHistoryService(unit.AssessmentAttempts(), signer).
ListMine(ctx, userID, cursor, limit)
return listErr
})
if err != nil {
return AssessmentResultHistoryPage{}, fmt.Errorf("%s - read snapshot: %w", location, err)
}
return page, nil
}
func invalidAssessmentResultHistoryRequest(
repository AssessmentResultHistoryRepository,
keyring Keyring,
keyring ResultHistoryCursorSigner,
candidateID uuid.UUID,
cursor string,
limit int32,
@@ -110,12 +147,12 @@ func invalidAssessmentResultHistoryRequest(
len(cursor) > assessmentResultHistoryMaxCursorBytes
}
const assessmentResultHistoryCursorOperation = "assessment.result-history.cursor.v1"
const assessmentResultHistoryCursorPayloadSize = 8 + 4 + 16
// The cursor is base64url(MAC || position). The position is the decimal
// microsecond timestamp and the attempt ID of the last returned row, so the
// token holds only [A-Za-z0-9_-] as the contract requires. The MAC binds the
// position to the candidate and the listing.
func encodeAssessmentResultHistoryCursor(
keyring Keyring,
keyring ResultHistoryCursorSigner,
candidateID uuid.UUID,
cursor outbound.AssessmentAttemptResultCursor,
) (string, error) {
@@ -123,18 +160,13 @@ func encodeAssessmentResultHistoryCursor(
cursor.DecidedAt.Nanosecond()%1000 != 0 {
return "", ErrInvalidAssessmentResultHistoryRequest
}
payload := make([]byte, assessmentResultHistoryCursorPayloadSize)
binary.BigEndian.PutUint64(payload[:8], uint64(cursor.DecidedAt.Unix()))
binary.BigEndian.PutUint32(payload[8:12], uint32(cursor.DecidedAt.Nanosecond()))
attemptID := cursor.AttemptID.UUID()
copy(payload[12:], attemptID[:])
encodedPayload := base64.RawURLEncoding.EncodeToString(payload)
mac := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String())
return encodedPayload + "." + base64.RawURLEncoding.EncodeToString(mac[:]), nil
position := strconv.FormatInt(cursor.DecidedAt.UnixMicro(), 10) + ":" + cursor.AttemptID.String()
mac := keyring.ResultHistoryCursorSignature(position, candidateID.String())
return base64.RawURLEncoding.EncodeToString(append(mac[:], position...)), nil
}
func decodeAssessmentResultHistoryCursor(
keyring Keyring,
keyring ResultHistoryCursorSigner,
candidateID uuid.UUID,
token string,
) (*outbound.AssessmentAttemptResultCursor, error) {
@@ -144,40 +176,26 @@ func decodeAssessmentResultHistoryCursor(
if keyring == nil || candidateID == uuid.Nil || len(token) > assessmentResultHistoryMaxCursorBytes {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
encodedPayload, encodedMAC, found := strings.Cut(token, ".")
if !found || encodedPayload == "" || encodedMAC == "" || strings.Contains(encodedMAC, ".") {
raw, err := base64.RawURLEncoding.DecodeString(token)
if err != nil || len(raw) <= outbound.IdempotencyDigestSize || base64.RawURLEncoding.EncodeToString(raw) != token {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
payload, err := base64.RawURLEncoding.DecodeString(encodedPayload)
if err != nil || len(payload) != assessmentResultHistoryCursorPayloadSize ||
base64.RawURLEncoding.EncodeToString(payload) != encodedPayload {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
suppliedMAC, err := base64.RawURLEncoding.DecodeString(encodedMAC)
if err != nil || len(suppliedMAC) != outbound.IdempotencyDigestSize ||
base64.RawURLEncoding.EncodeToString(suppliedMAC) != encodedMAC {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
expectedMAC := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String())
suppliedMAC, position := raw[:outbound.IdempotencyDigestSize], string(raw[outbound.IdempotencyDigestSize:])
expectedMAC := keyring.ResultHistoryCursorSignature(position, candidateID.String())
if !hmac.Equal(suppliedMAC, expectedMAC[:]) {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
seconds := int64(binary.BigEndian.Uint64(payload[:8]))
nanos := binary.BigEndian.Uint32(payload[8:12])
if nanos >= uint32(time.Second) || nanos%1000 != 0 {
microseconds, attemptText, found := strings.Cut(position, ":")
if !found {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
var attemptUUID uuid.UUID
copy(attemptUUID[:], payload[12:])
decidedMicro, err := strconv.ParseInt(microseconds, 10, 64)
attemptUUID, uuidErr := uuid.Parse(attemptText)
attemptID := domain.AssessmentAttemptID(attemptUUID)
if attemptID.IsZero() {
if err != nil || uuidErr != nil || attemptID.IsZero() {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
decidedAt := time.Unix(seconds, int64(nanos)).UTC()
if decidedAt.Unix() != seconds || uint32(decidedAt.Nanosecond()) != nanos {
return nil, ErrInvalidAssessmentResultHistoryRequest
}
return &outbound.AssessmentAttemptResultCursor{DecidedAt: decidedAt, AttemptID: attemptID}, nil
return &outbound.AssessmentAttemptResultCursor{DecidedAt: time.UnixMicro(decidedMicro).UTC(), AttemptID: attemptID}, nil
}
func restoreAssessmentResultHistoryPage(
@@ -2,7 +2,9 @@ package assessment
import (
"context"
"crypto/sha256"
"errors"
"regexp"
"strings"
"testing"
"time"
@@ -10,32 +12,86 @@ import (
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func legacyHistoryRecord(t *testing.T, ownerID uuid.UUID, result domain.AssessmentAttemptResultSnapshot) outbound.AssessmentAttemptResultRecord {
t.Helper()
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
}
return outbound.AssessmentAttemptResultRecord{UserID: ownerID, Entry: entry}
}
func TestAssessmentResultHistoryReadsOwnerScopedV1WithoutInventingGrade(t *testing.T) {
ownerID := uuid.New()
policy := categoryServiceTestPolicy(t)
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
}
repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{
Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}}, NextCursor: "next-page-token",
record := legacyHistoryRecord(t, ownerID, result)
repository := &assessmentResultHistoryRepositoryFake{page: outbound.AssessmentAttemptResultPage{
Records: []outbound.AssessmentAttemptResultRecord{record}, HasMore: true,
}}
service := NewAssessmentResultHistoryService(repository)
service := NewAssessmentResultHistoryService(repository, historyCursorSigner{})
page, err := service.ListMine(t.Context(), ownerID, "", 0)
if err != nil {
t.Fatalf("ListMine(default limit) error = %v", err)
}
if repository.ownerID != ownerID || repository.cursor != "" || repository.limit != AssessmentResultHistoryDefaultLimit {
t.Fatalf("repository request = owner %s cursor %q limit %d", repository.ownerID, repository.cursor, repository.limit)
if repository.ownerID != ownerID || repository.cursor != nil || repository.limit != AssessmentResultHistoryDefaultLimit {
t.Fatalf("repository request = owner %s cursor %v limit %d", repository.ownerID, repository.cursor, repository.limit)
}
if len(page.Entries) != 1 || page.NextCursor != "next-page-token" ||
if !regexp.MustCompile(`^[A-Za-z0-9_-]{1,512}$`).MatchString(page.NextCursor) {
t.Fatalf("next cursor %q is outside the contract alphabet [A-Za-z0-9_-]", page.NextCursor)
}
if len(page.Entries) != 1 || page.NextCursor == "" ||
page.Entries[0].SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV1 ||
page.Entries[0].CategoryDecision != nil || page.Entries[0].CurrentConfirmedGrade != nil {
t.Fatalf("history page = %+v, want one legacy result with unknown category", page)
t.Fatalf("history page = %+v, want one legacy result with unknown category and a next cursor", page)
}
// The next-page token resumes after the last returned row of the same owner.
repository.page = outbound.AssessmentAttemptResultPage{}
if _, err := service.ListMine(t.Context(), ownerID, page.NextCursor, 5); err != nil {
t.Fatalf("ListMine(next cursor) error = %v", err)
}
last := page.Entries[0].Result
if repository.cursor == nil || !repository.cursor.DecidedAt.Equal(last.DecidedAt) || repository.cursor.AttemptID != last.Attempt.ID || repository.limit != 5 {
t.Fatalf("repository keyset = %+v limit %d, want the last row %s at %s", repository.cursor, repository.limit, last.Attempt.ID, last.DecidedAt)
}
}
func TestAssessmentResultHistoryCursorIsBoundToItsOwner(t *testing.T) {
ownerID := uuid.New()
policy := categoryServiceTestPolicy(t)
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
repository := &assessmentResultHistoryRepositoryFake{page: outbound.AssessmentAttemptResultPage{
Records: []outbound.AssessmentAttemptResultRecord{legacyHistoryRecord(t, ownerID, result)}, HasMore: true,
}}
service := NewAssessmentResultHistoryService(repository, historyCursorSigner{})
page, err := service.ListMine(t.Context(), ownerID, "", 1)
if err != nil {
t.Fatalf("ListMine() error = %v", err)
}
repository.ownerID = uuid.Nil
tampered := page.NextCursor[:len(page.NextCursor)-1] + "A"
if page.NextCursor == tampered {
tampered = page.NextCursor[:len(page.NextCursor)-1] + "B"
}
for name, test := range map[string]struct {
owner uuid.UUID
cursor string
}{
"foreign owner": {owner: uuid.New(), cursor: page.NextCursor},
"tampered token": {owner: ownerID, cursor: tampered},
"not a token": {owner: ownerID, cursor: "cursor"},
} {
if _, err := service.ListMine(t.Context(), test.owner, test.cursor, 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
t.Fatalf("ListMine(%s) error = %v, want invalid request", name, err)
}
}
if repository.ownerID != uuid.Nil {
t.Fatal("a rejected cursor reached the repository")
}
}
@@ -43,25 +99,17 @@ func TestAssessmentResultHistoryRejectsForeignOwnerAndExpressRows(t *testing.T)
ownerID := uuid.New()
policy := categoryServiceTestPolicy(t)
attempt, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
}
service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: uuid.New(), Entry: entry}}},
})
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{legacyHistoryRecord(t, uuid.New(), result)}},
}, historyCursorSigner{})
if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(foreign owner) error = %v, want invalid history", err)
}
express, expressResult := completedExpressCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
expressEntry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(expressResult)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(express) error = %v", err)
}
service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: expressEntry}}},
})
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{legacyHistoryRecord(t, ownerID, expressResult)}},
}, historyCursorSigner{})
if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(express row) error = %v, want invalid history", err)
}
@@ -74,31 +122,32 @@ func TestAssessmentResultHistoryRejectsInvalidBoundsAndDuplicateResults(t *testi
ownerID := uuid.New()
policy := categoryServiceTestPolicy(t)
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
}
repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{
Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}},
record := legacyHistoryRecord(t, ownerID, result)
repository := &assessmentResultHistoryRepositoryFake{page: outbound.AssessmentAttemptResultPage{
Records: []outbound.AssessmentAttemptResultRecord{record},
}}
service := NewAssessmentResultHistoryService(repository)
service := NewAssessmentResultHistoryService(repository, historyCursorSigner{})
if _, err := service.ListMine(t.Context(), ownerID, strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1), 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
t.Fatalf("ListMine(oversized cursor) error = %v, want invalid request", err)
}
if _, err := service.ListMine(t.Context(), ownerID, "", AssessmentResultHistoryMaxLimit+1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
t.Fatalf("ListMine(oversized limit) error = %v, want invalid request", err)
}
repository.page.NextCursor = strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1)
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(oversized next cursor) error = %v, want invalid history", err)
if _, err := service.ListMine(t.Context(), uuid.Nil, "", 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
t.Fatalf("ListMine(nil owner) error = %v, want invalid request", err)
}
repository.page.NextCursor = ""
repository.page.Records = append(repository.page.Records,
AssessmentResultHistoryRecord{CandidateID: ownerID, Entry: entry})
repository.page.Records = append(repository.page.Records, record)
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(more rows than the limit) error = %v, want invalid history", err)
}
if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(duplicate result) error = %v, want invalid history", err)
}
repository.page = outbound.AssessmentAttemptResultPage{HasMore: true}
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(HasMore without rows) error = %v, want invalid history", err)
}
}
func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *testing.T) {
@@ -107,27 +156,20 @@ func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *test
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
decidedAt := time.Date(2026, time.September, 1, 11, 0, 0, 0, time.UTC)
entryForID := func(id string) domain.AssessmentAttemptResultHistoryEntry {
recordForID := func(id string) outbound.AssessmentAttemptResultRecord {
t.Helper()
resultCopy := result
resultCopy.Attempt.ID = domain.AssessmentAttemptID(uuid.MustParse(id))
resultCopy.DecidedAt = decidedAt
resultCopy.Attempt.FinishedAt = &decidedAt
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(resultCopy)
if err != nil {
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(%s) error = %v", id, err)
}
return entry
return legacyHistoryRecord(t, ownerID, resultCopy)
}
higherID := entryForID("ffffffff-ffff-4fff-bfff-ffffffffffff")
lowerID := entryForID("00000000-0000-4000-8000-000000000001")
higherID := recordForID("ffffffff-ffff-4fff-bfff-ffffffffffff")
lowerID := recordForID("00000000-0000-4000-8000-000000000001")
service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{
{CandidateID: ownerID, Entry: higherID},
{CandidateID: ownerID, Entry: lowerID},
}},
})
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{higherID, lowerID}},
}, historyCursorSigner{})
page, err := service.ListMine(t.Context(), ownerID, "", 2)
if err != nil {
t.Fatalf("ListMine(descending tie order) error = %v", err)
@@ -139,20 +181,17 @@ func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *test
}
service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{
{CandidateID: ownerID, Entry: lowerID},
{CandidateID: ownerID, Entry: higherID},
}},
})
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{lowerID, higherID}},
}, historyCursorSigner{})
if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
t.Fatalf("ListMine(ascending tie order) error = %v, want invalid history", err)
}
}
type assessmentResultHistoryRepositoryFake struct {
page AssessmentResultHistoryRepositoryPage
page outbound.AssessmentAttemptResultPage
ownerID uuid.UUID
cursor string
cursor *outbound.AssessmentAttemptResultCursor
limit int32
readErr error
}
@@ -160,9 +199,15 @@ type assessmentResultHistoryRepositoryFake struct {
func (repository *assessmentResultHistoryRepositoryFake) ListCandidateAssessmentResults(
_ context.Context,
ownerID uuid.UUID,
cursor string,
cursor *outbound.AssessmentAttemptResultCursor,
limit int32,
) (AssessmentResultHistoryRepositoryPage, error) {
) (outbound.AssessmentAttemptResultPage, error) {
repository.ownerID, repository.cursor, repository.limit = ownerID, cursor, limit
return repository.page, repository.readErr
}
type historyCursorSigner struct{}
func (historyCursorSigner) ResultHistoryCursorSignature(position, candidateID string) [32]byte {
return sha256.Sum256([]byte("cursor\x00" + position + "\x00" + candidateID))
}
@@ -60,7 +60,8 @@ func TestAssessmentCategoryDecisionServiceAssignsOnlyTheExactReviewedPolicySourc
repository.reviewPins.OpeningID != result.Pins.OpeningID ||
repository.reviewPins.OpeningManifestHash != result.Pins.OpeningManifestHash ||
repository.reviewPins.ProductPolicyVersionID != result.Pins.ProductPolicyVersionID ||
repository.reviewPins.ProductPolicyVersion != result.Pins.ProductPolicyVersion {
repository.reviewPins.ProductPolicyVersion != result.Pins.ProductPolicyVersion ||
repository.reviewPins.GradingPolicyVersionID != result.Pins.GradingPolicyVersionID {
t.Fatalf("review query pins = %+v, want exact finalized source pins", repository.reviewPins)
}
}
@@ -89,7 +90,18 @@ type categoryDecisionRepositoryFake struct {
calls []string
current *domain.CandidateAssessmentCategory
review *domain.AssessmentSyntheticCategoryReview
reviewPins AssessmentCategoryReviewPins
reviewPins categoryReviewQuery
}
// categoryReviewQuery records the pins that the service passes to the
// repository when it looks for a reviewed source.
type categoryReviewQuery struct {
OpeningID uuid.UUID
Category domain.AssessmentCategory
OpeningManifestHash [32]byte
ProductPolicyVersionID domain.PolicyVersionID
ProductPolicyVersion int32
GradingPolicyVersionID domain.PolicyVersionID
}
func (repository *categoryDecisionRepositoryFake) LockCandidateCategory(
@@ -115,8 +127,18 @@ func (repository *categoryDecisionRepositoryFake) GetCandidateCategory(
func (repository *categoryDecisionRepositoryFake) GetSyntheticCategoryReview(
_ context.Context,
pins AssessmentCategoryReviewPins,
openingID uuid.UUID,
category domain.AssessmentCategory,
openingManifestHash [32]byte,
productPolicyID domain.PolicyVersionID,
productPolicyVersion int32,
gradingPolicyID domain.PolicyVersionID,
) (domain.AssessmentSyntheticCategoryReview, bool, error) {
pins := categoryReviewQuery{
OpeningID: openingID, Category: category, OpeningManifestHash: openingManifestHash,
ProductPolicyVersionID: productPolicyID, ProductPolicyVersion: productPolicyVersion,
GradingPolicyVersionID: gradingPolicyID,
}
repository.calls = append(repository.calls, "review")
repository.reviewPins = pins
if repository.review == nil {
@@ -170,13 +170,21 @@ func lockAttemptForFinalize(
}
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
if current.Kind() != kind || current.Snapshot().Specialization == nil && selectedSnapshot.Specialization != nil ||
current.Snapshot().Specialization != nil && (selectedSnapshot.Specialization == nil || *current.Snapshot().Specialization != *selectedSnapshot.Specialization) {
if current.Kind() != kind || !sameAttemptSpecialization(current.Snapshot().Specialization, selectedSnapshot.Specialization) {
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt scope changed: %w", location, domain.ErrInvalidAssessmentAttempt)
}
return current, nil
}
// sameAttemptSpecialization compares the optional specializations of two reads
// of one attempt; training attempts have none.
func sameAttemptSpecialization(left, right *domain.SpecializationCode) bool {
if left == nil || right == nil {
return left == right
}
return *left == *right
}
func storeCompletedFinalize(
ctx context.Context,
repository outbound.AssessmentAttemptRepository,
@@ -394,9 +402,7 @@ func readCompletedAttemptResult(
if err != nil {
return AssessmentAttemptResult{}, fmt.Errorf("%s - restore stored category result: %w", location, err)
}
result := assessmentAttemptResultFromSnapshot(entry.Result)
result.CategoryDecision = entry.CategoryDecision
return result, nil
return AssessmentAttemptResultFromHistoryEntry(entry), nil
}
func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptResult, error) {
@@ -448,3 +454,15 @@ func assessmentAttemptResultFromSnapshot(
Summary: snapshot.Summary, DecidedAt: snapshot.DecidedAt,
}
}
// AssessmentAttemptResultFromHistoryEntry is the candidate-visible form of one
// stored result, with the category decision captured when it was stored. A
// legacy v1 entry has no decision.
func AssessmentAttemptResultFromHistoryEntry(entry domain.AssessmentAttemptResultHistoryEntry) AssessmentAttemptResult {
result := assessmentAttemptResultFromSnapshot(entry.Result)
if entry.CategoryDecision != nil {
decision := *entry.CategoryDecision
result.CategoryDecision = &decision
}
return result
}
@@ -31,6 +31,7 @@ const (
labelAnswerFingerprint = "lincodex/assessment/answer-fingerprint/v1"
labelSignalSession = "lincodex/assessment/signal-session/v1"
labelSignalNetwork = "lincodex/assessment/signal-network/v1"
labelResultCursor = "lincodex/assessment/result-history-cursor/v1"
)
// Keyring computes the keyed digests of the anonymous identity operations:
@@ -49,6 +50,7 @@ type Keyring struct {
answerKey []byte
signalSessionKey []byte
signalNetworkKey []byte
resultCursorKey []byte
}
// NewKeyring derives the purpose keys from secret.
@@ -67,6 +69,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
answerKey: derive(secret, labelAnswerFingerprint),
signalSessionKey: derive(secret, labelSignalSession),
signalNetworkKey: derive(secret, labelSignalNetwork),
resultCursorKey: derive(secret, labelResultCursor),
}, nil
}
@@ -103,6 +106,17 @@ func (keyring *Keyring) IdempotencyScope(operation, key, normalizedEmail string)
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
}
// ResultHistoryCursorSignature signs the position of a result history page for
// one candidate under a key of its own, so a cursor can never be replayed as an
// idempotency scope or the other way round.
func (keyring *Keyring) ResultHistoryCursorSignature(position, candidateID string) [outbound.IdempotencyDigestSize]byte {
mac := hmac.New(sha256.New, keyring.resultCursorKey)
mac.Write([]byte(position))
mac.Write([]byte{0})
mac.Write([]byte(candidateID))
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
}
// Fingerprint identifies a request by its canonical body.
func (keyring *Keyring) Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte {
mac := hmac.New(sha256.New, keyring.fingerprintKey)
@@ -3,6 +3,7 @@ package identity
import (
"bytes"
"crypto/sha256"
"strings"
"testing"
"github.com/google/uuid"
@@ -123,3 +124,22 @@ func TestAssessmentSessionAndNetworkDigestsAreBoundToTheAttempt(t *testing.T) {
t.Fatal("session and network digests share a key")
}
}
func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t *testing.T) {
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
signature := keyring.ResultHistoryCursorSignature("position", "candidate-a")
if signature != keyring.ResultHistoryCursorSignature("position", "candidate-a") {
t.Fatal("the cursor signature is not deterministic")
}
if signature == keyring.ResultHistoryCursorSignature("position", "candidate-b") ||
signature == keyring.ResultHistoryCursorSignature("other", "candidate-a") {
t.Fatal("the cursor signature does not depend on the position and the candidate")
}
if signature == keyring.IdempotencyScope("position", "", "candidate-a") ||
signature == keyring.IdempotencyScope("assessment.result-history.cursor.v1", "position", "candidate-a") {
t.Fatal("the cursor signature shares a key with the idempotency scope")
}
}
@@ -57,7 +57,8 @@ func validInboxText(value string, maxRunes int, allowNewlines bool) bool {
return false
}
for _, character := range value {
if character == 0 || (character < 0x20 && !(allowNewlines && (character == '\n' || character == '\t'))) || character == 0x7f {
allowedControl := allowNewlines && (character == '\n' || character == '\t')
if character == 0 || (character < 0x20 && !allowedControl) || character == 0x7f {
return false
}
}
@@ -173,11 +174,12 @@ func (service *InboxService) List(ctx context.Context, request InboxListRequest)
}
item := InboxItem{Entry: entry}
content, resolveErr := service.resolver.Resolve(ctx, entry)
if errors.Is(resolveErr, ErrInboxContentUnavailable) {
switch {
case errors.Is(resolveErr, ErrInboxContentUnavailable):
item.ContentUnavailable = true
} else if resolveErr != nil {
case resolveErr != nil:
return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
} else {
default:
item.Content = &content
}
page.Items = append(page.Items, item)