Files

136 lines
5.3 KiB
Go

// 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\nextra_agents: %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"+
"client_screenshot_keys: %d\nclient_devtools_opens: %d\n"+
"note: a hint for a manual check; it changes no result, category, or quota, and browser signals can be forged; "+
"a screenshot or a phone photo cannot be prevented or seen by the page\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.ExtraAgents, measures.MatchedIntegerItems, measures.MatchedSequenceItems,
measures.DuplicateEvidenceBits, measures.ClientFocusLossMS, measures.ClientClipboardEvents,
measures.ClientFullscreenExits, measures.ClientScreenshotKeys, measures.ClientDevtoolsOpens,
); 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")
}
}