feat(assessment): add the review band of attempt signals and the disclosed collector

This commit is contained in:
shira committed 2026-10-08 23:04:57 +03:00
1 parent 68286af8b7
commit b3c6dc870b
124 files changed
+13522 -633

No files matched your search

@@ -0,0 +1,133 @@
// Package assessmentreview implements the local operator command that prints
// the stored manual-review band of an assessment attempt. The band is never
// served over HTTP; this command is the only reader until staff roles exist.
package assessmentreview
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strings"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
)
const usage = "usage: assessment-review inspect --attempt <uuid> --actor operator:<handle>"
// Command is a parsed, validated review inspection.
type Command struct {
AttemptID domain.AssessmentAttemptID
Actor string
}
// Operator reads a review and records the read.
type Operator interface {
Inspect(ctx context.Context, attemptID domain.AssessmentAttemptID, actor string) (domain.AssessmentAttemptReview, error)
}
// Parse validates every argument before Run reads configuration or connects
// to PostgreSQL.
func Parse(args []string) (Command, error) {
if len(args) == 0 || args[0] != "inspect" {
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("assessment-review inspect", flag.ContinueOnError)
flags.SetOutput(io.Discard)
attempt := flags.String("attempt", "", "attempt UUID")
actor := flags.String("actor", "", "operator handle")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
return Command{}, errors.New(usage)
}
attemptID, err := uuid.Parse(strings.TrimSpace(*attempt))
if err != nil || attemptID == uuid.Nil {
return Command{}, errors.New("attempt must be a non-zero UUID")
}
if _, err := domain.ParseAssessmentReviewActor(strings.TrimSpace(*actor)); err != nil {
return Command{}, errors.New("actor must be operator:<handle>")
}
return Command{AttemptID: domain.AssessmentAttemptID(attemptID), Actor: strings.TrimSpace(*actor)}, nil
}
// Run parses the command, loads only DATABASE_URL from the supplied
// environment, and executes the operator usecase. It does not load dotenv
// files.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil {
return errors.New("assessment review command dependencies are required")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return errors.New("DATABASE_URL is not set")
}
pool, err := postgres.NewPool(ctx, databaseURL)
if err != nil {
return errors.New("database configuration is invalid")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("database is unavailable")
}
operator, err := assessment.NewReviewOperator(postgres.NewTransactor(pool))
if err != nil {
return errors.New("assessment review is unavailable")
}
return Execute(ctx, command, operator, output)
}
// Execute prints the review. The output holds counts, durations, the band, the
// reason codes, and the policy version; it holds no answer, address, session,
// candidate, or contact data.
func Execute(ctx context.Context, command Command, operator Operator, output io.Writer) error {
if operator == nil || output == nil {
return errors.New("assessment review command dependencies are required")
}
review, err := operator.Inspect(ctx, command.AttemptID, command.Actor)
if err != nil {
return safeOperationError(err)
}
reasons := make([]string, 0, len(review.Outcome.Reasons))
for _, reason := range review.Outcome.Reasons {
reasons = append(reasons, string(reason))
}
measures := review.Measures
if _, err := fmt.Fprintf(output,
"attempt: %s\nband: %s\nreasons: %s\npolicy_version: %d\nevaluated_at: %s\nupdated_at: %s\n"+
"answered_items: %d\nfast_answers: %d\ndeviating_answers: %d\nparallel_alternations: %d\nextra_networks: %d\n"+
"matched_integer_items: %d\nmatched_sequence_items: %d\nduplicate_evidence_bits: %d\n"+
"client_focus_loss_ms: %d\nclient_clipboard_events: %d\nclient_fullscreen_exits: %d\n"+
"note: a hint for a manual check; it changes no result, category, or quota, and browser signals can be forged\n",
review.AttemptID, review.Outcome.Band, strings.Join(reasons, ","), review.PolicyVersion,
review.EvaluatedAt.UTC().Format(time.RFC3339), review.UpdatedAt.UTC().Format(time.RFC3339),
measures.AnsweredItems, measures.FastAnswers, measures.DeviatingAnswers, measures.ParallelAlternations,
measures.ExtraNetworks, measures.MatchedIntegerItems, measures.MatchedSequenceItems,
measures.DuplicateEvidenceBits, measures.ClientFocusLossMS, measures.ClientClipboardEvents,
measures.ClientFullscreenExits,
); err != nil {
return errors.New("could not write the review")
}
return nil
}
func safeOperationError(err error) error {
switch {
case errors.Is(err, outbound.ErrAssessmentReviewNotFound):
return errors.New("attempt has no review (the read was recorded)")
case errors.Is(err, domain.ErrInvalidAssessmentReview):
return errors.New("attempt or actor is invalid")
default:
return errors.New("assessment review operation failed")
}
}
@@ -0,0 +1,113 @@
package assessmentreview
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type operatorFake struct {
review domain.AssessmentAttemptReview
err error
calls int
actor string
}
func (operator *operatorFake) Inspect(_ context.Context, _ domain.AssessmentAttemptID, actor string) (domain.AssessmentAttemptReview, error) {
operator.calls++
operator.actor = actor
return operator.review, operator.err
}
func TestParseRequiresAnAttemptAndAnOperatorHandle(t *testing.T) {
id := uuid.New().String()
command, err := Parse([]string{"inspect", "--attempt", id, "--actor", "operator:night"})
if err != nil || command.AttemptID.String() != id || command.Actor != "operator:night" {
t.Fatalf("Parse(valid) = %+v, %v", command, err)
}
for _, args := range [][]string{
nil,
{"list"},
{"inspect"},
{"inspect", "--attempt", id},
{"inspect", "--attempt", id, "--actor", "alice"},
{"inspect", "--attempt", "not-a-uuid", "--actor", "operator:night"},
{"inspect", "--attempt", uuid.Nil.String(), "--actor", "operator:night"},
{"inspect", "--attempt", id, "--actor", "operator:night", "extra"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%v) accepted invalid arguments", args)
}
}
}
func TestRunValidatesArgumentsBeforeReadingTheEnvironment(t *testing.T) {
lookup := func(string) (string, bool) {
t.Fatal("environment read before arguments were validated")
return "", false
}
if err := Run(context.Background(), []string{"inspect"}, lookup, &bytes.Buffer{}); err == nil {
t.Fatal("Run(invalid arguments) succeeded")
}
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
err := Run(context.Background(), []string{"inspect", "--attempt", uuid.New().String(), "--actor", "operator:night"}, noDatabase, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
}
}
func TestExecutePrintsOnlyBandCountsAndReasons(t *testing.T) {
attemptID := domain.AssessmentAttemptID(uuid.New())
operator := &operatorFake{review: domain.AssessmentAttemptReview{
AttemptID: attemptID, PolicyVersion: 4,
Measures: domain.AssessmentReviewMeasures{AnsweredItems: 9, FastAnswers: 5, ParallelAlternations: 2, ExtraNetworks: 1, MatchedIntegerItems: 3, DuplicateEvidenceBits: 9},
Outcome: domain.AssessmentReviewOutcome{
Band: domain.AssessmentReviewBandAttention,
Reasons: []domain.AssessmentReviewReason{domain.AssessmentReviewReasonFastAnswers, domain.AssessmentReviewReasonParallelSessions},
},
EvaluatedAt: time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC), UpdatedAt: time.Date(2026, time.October, 2, 10, 0, 0, 0, time.UTC),
}}
var output bytes.Buffer
command := Command{AttemptID: attemptID, Actor: "operator:night"}
if err := Execute(context.Background(), command, operator, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
for _, want := range []string{"attempt: " + attemptID.String(), "band: attention", "reasons: fast_answers,parallel_sessions", "policy_version: 4", "fast_answers: 5", "matched_integer_items: 3", "extra_networks: 1", "duplicate_evidence_bits: 9", "a hint for a manual check"} {
if !strings.Contains(output.String(), want) {
t.Errorf("output lacks %q:\n%s", want, output.String())
}
}
for _, forbidden := range []string{"user", "email", "address", "session", "answer:", "fingerprint"} {
if strings.Contains(output.String(), forbidden+":") {
t.Errorf("output has a %q line:\n%s", forbidden, output.String())
}
}
if operator.calls != 1 || operator.actor != "operator:night" {
t.Fatalf("operator calls/actor = %d/%q, want one call with the handle", operator.calls, operator.actor)
}
}
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
for _, test := range []struct {
err error
want string
}{
{outbound.ErrAssessmentReviewNotFound, "no review"},
{domain.ErrInvalidAssessmentReview, "invalid"},
{errors.New("pq: password authentication failed for user lincodex at 10.0.0.5"), "operation failed"},
} {
err := Execute(context.Background(), Command{}, &operatorFake{err: test.err}, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "10.0.0.5") {
t.Errorf("Execute(%v) error = %v, want a safe %q message", test.err, err, test.want)
}
}
}