Files
lincodex/backend/internal/domain/assessment_watermark.go
T

322 lines
11 KiB
Go

package domain
import (
"encoding/binary"
"errors"
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
// ErrInvalidAssessmentWatermark reports a malformed watermark seed or code.
var ErrInvalidAssessmentWatermark = errors.New("invalid assessment watermark")
// AssessmentWatermarkSeed is the secret stream of one attempt: a keyed digest
// of the attempt identifier under a server key. The visible code, the zero-width
// mark, and the choice of wordings are all read from it, so none of them can be
// forged or predicted without the server secret, and none carries the attempt
// identifier or any account data. The seed itself never leaves the server.
type AssessmentWatermarkSeed [32]byte
// IsZero reports an unset seed.
func (seed AssessmentWatermarkSeed) IsZero() bool { return seed == AssessmentWatermarkSeed{} }
const (
// watermarkAlphabet is Crockford base32: no I, L, O, or U, so a code read
// from a screenshot is not confused between 0 and O or 1 and I.
watermarkAlphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
watermarkCodeLength = 10
watermarkCodeBits = 5 * watermarkCodeLength
// watermarkDigits is the number of base-4 digits that carry the code bits
// in the zero-width mark. One more digit is a check.
watermarkDigits = watermarkCodeBits / 2
watermarkRunLength = watermarkDigits + 1
// watermarkMaxCopies bounds how many times the mark is repeated in one text.
watermarkMaxCopies = 8
// watermarkWordingOffset is where the wording choices start in the seed,
// after the 7 bytes that the code reads.
watermarkWordingOffset = 8
)
// watermarkZeroWidth are the four characters of the invisible mark, the digits
// 0 to 3. They are the zero width space, non-joiner, joiner, and word joiner.
//
//nolint:gochecknoglobals // A fixed table that is read-only after initialization.
var watermarkZeroWidth = [4]rune{'\u200b', '\u200c', '\u200d', '\u2060'}
// AssessmentWatermarkCode is the pseudonymous code of an attempt: 10 symbols
// of Crockford base32 held in upper case without separators. It shows on the
// task screen next to the time. It contains no name, contact, or identifier.
type AssessmentWatermarkCode string
// String writes the code in two groups of five, the way it is shown.
func (code AssessmentWatermarkCode) String() string {
if len(code) != watermarkCodeLength {
return string(code)
}
return string(code[:5]) + "-" + string(code[5:])
}
// ParseAssessmentWatermarkCode reads a code as an operator or an OCR gives it:
// any case, with or without the separator, with O read as 0 and I or L as 1.
func ParseAssessmentWatermarkCode(value string) (AssessmentWatermarkCode, error) {
var builder strings.Builder
for _, r := range strings.ToUpper(value) {
switch {
case r == '-' || unicode.IsSpace(r):
continue
case r == 'O':
r = '0'
case r == 'I' || r == 'L':
r = '1'
case r == 'U':
r = 'V'
}
if !strings.ContainsRune(watermarkAlphabet, r) {
return "", fmt.Errorf("domain.ParseAssessmentWatermarkCode - the code has a character outside its alphabet: %w", ErrInvalidAssessmentWatermark)
}
builder.WriteRune(r)
}
if builder.Len() != watermarkCodeLength {
return "", fmt.Errorf("domain.ParseAssessmentWatermarkCode - the code must have %d symbols: %w", watermarkCodeLength, ErrInvalidAssessmentWatermark)
}
return AssessmentWatermarkCode(builder.String()), nil
}
// Distance counts the positions at which two codes differ.
func (code AssessmentWatermarkCode) Distance(other AssessmentWatermarkCode) int {
if len(code) != len(other) {
return max(len(code), len(other))
}
differing := 0
for index := range len(code) {
if code[index] != other[index] {
differing++
}
}
return differing
}
// value is the code as one integer of watermarkCodeBits bits.
func (code AssessmentWatermarkCode) value() uint64 {
var number uint64
for index := range len(code) {
number = number<<5 | uint64(strings.IndexByte(watermarkAlphabet, code[index])) //nolint:gosec // The index is 0 to 31 for a parsed code.
}
return number
}
// AssessmentWatermark marks the task text of one attempt.
type AssessmentWatermark struct {
seed AssessmentWatermarkSeed
}
// NewAssessmentWatermark rejects an unset seed, which would give every attempt
// the same mark.
func NewAssessmentWatermark(seed AssessmentWatermarkSeed) (AssessmentWatermark, error) {
if seed.IsZero() {
return AssessmentWatermark{}, fmt.Errorf("domain.NewAssessmentWatermark - the seed must be set: %w", ErrInvalidAssessmentWatermark)
}
return AssessmentWatermark{seed: seed}, nil
}
// Code returns the visible code of the attempt: the leading bits of the seed.
func (watermark AssessmentWatermark) Code() AssessmentWatermarkCode {
number := binary.BigEndian.Uint64(watermark.seed[:8]) >> (64 - watermarkCodeBits)
symbols := make([]byte, watermarkCodeLength)
for index := watermarkCodeLength - 1; index >= 0; index-- {
symbols[index] = watermarkAlphabet[number&31]
number >>= 5
}
return AssessmentWatermarkCode(symbols)
}
// Mark writes the statement for this attempt. It picks one form for each
// interchangeable phrase and then inserts the invisible mark at the start of
// the sentences. Neither step changes the meaning, the answer, or what a screen
// reader says: see VisibleAssessmentText.
func (watermark AssessmentWatermark) Mark(statement string) string {
reworded := rewriteWording(canonicalWording(VisibleAssessmentText(statement)), watermark.wordingForm)
return insertWatermarkRuns(reworded, watermark.zeroWidthRun())
}
// wordingForm is the index of the form that this attempt uses for a group.
func (watermark AssessmentWatermark) wordingForm(group int) int {
forms := len(assessmentWordingGroups[group].forms)
return int(watermark.seed[watermarkWordingOffset+group%(len(watermark.seed)-watermarkWordingOffset)]) % forms
}
// WordingAgreement compares the phrases of a leaked text with the choices of
// this attempt, reading only the phrases that the leak shows within the stored
// statement (see AssessmentLeakAlignment): words around the statement in the
// leak, such as a quotation or a message, are not read. Slots is the number of
// phrase groups that the leak shows and Agreeing how many of them stand in the
// form this attempt picked. A group counts once however often it occurs, and a
// group that stands in two forms in the leak does not agree. Each group is
// worth about one bit: another attempt agrees with a group by chance in one
// case of two.
func (watermark AssessmentWatermark) WordingAgreement(alignment LeakAlignment) (agreeing, slots int) {
forms := map[int]int{}
conflicting := map[int]bool{}
for _, phrase := range alignment.Phrases {
if previous, seen := forms[phrase.Group]; seen && previous != phrase.Form {
conflicting[phrase.Group] = true
}
forms[phrase.Group] = phrase.Form
}
for group, form := range forms {
if !conflicting[group] && form == watermark.wordingForm(group) {
agreeing++
}
}
return agreeing, len(forms)
}
// zeroWidthRun encodes the code bits as watermarkDigits base-4 digits in the
// invisible characters, followed by a check digit, so a run that was cut or
// mixed with other characters is recognized as damaged.
func (watermark AssessmentWatermark) zeroWidthRun() string {
number := watermark.Code().value()
digits := make([]rune, watermarkDigits+1)
sum := 0
for index := watermarkDigits - 1; index >= 0; index-- {
digit := int(number & 3)
digits[index] = watermarkZeroWidth[digit]
sum += digit
number >>= 2
}
digits[watermarkDigits] = watermarkZeroWidth[sum%4]
return string(digits)
}
// insertWatermarkRuns places the mark after the first space and at the start of
// each following sentence, so that any copy of a sentence or two keeps a whole
// run. Positions are byte offsets in the text.
func insertWatermarkRuns(text, run string) string {
positions := watermarkPositions(text)
if len(positions) == 0 {
return text + run
}
var builder strings.Builder
builder.Grow(len(text) + len(positions)*len(run))
copied := 0
for _, position := range positions {
builder.WriteString(text[copied:position])
builder.WriteString(run)
copied = position
}
builder.WriteString(text[copied:])
return builder.String()
}
func watermarkPositions(text string) []int {
var positions []int
if first := strings.IndexFunc(text, unicode.IsSpace); first >= 0 && first+1 < len(text) {
positions = append(positions, first+1)
}
previous := rune(0)
for offset, r := range text {
if len(positions) >= watermarkMaxCopies {
break
}
next := offset + utf8.RuneLen(r)
if unicode.IsSpace(r) && (previous == '.' || previous == '!' || previous == '?') && next < len(text) {
if len(positions) == 0 || positions[len(positions)-1] != next {
positions = append(positions, next)
}
}
previous = r
}
return positions
}
// ExtractAssessmentWatermarkCodes returns the codes read from the invisible
// marks in a text, in order, one per intact run. A run is a maximal stretch of
// the four mark characters of exactly the right length and a correct check
// digit; anything else is ignored.
func ExtractAssessmentWatermarkCodes(text string) []AssessmentWatermarkCode {
var codes []AssessmentWatermarkCode
var run []int
flush := func() {
if code, ok := decodeWatermarkRun(run); ok {
codes = append(codes, code)
}
run = run[:0]
}
for _, r := range text {
if digit := watermarkDigit(r); digit >= 0 {
run = append(run, digit)
continue
}
flush()
}
flush()
return codes
}
func watermarkDigit(r rune) int {
for digit, candidate := range watermarkZeroWidth {
if r == candidate {
return digit
}
}
return -1
}
func decodeWatermarkRun(digits []int) (AssessmentWatermarkCode, bool) {
if len(digits) != watermarkRunLength {
return "", false
}
var number uint64
sum := 0
for _, digit := range digits[:watermarkDigits] {
number = number<<2 | uint64(digit) //nolint:gosec // A digit is 0 to 3.
sum += digit
}
if sum%4 != digits[watermarkDigits] {
return "", false
}
symbols := make([]byte, watermarkCodeLength)
for index := watermarkCodeLength - 1; index >= 0; index-- {
symbols[index] = watermarkAlphabet[number&31]
number >>= 5
}
return AssessmentWatermarkCode(symbols), true
}
// VisibleAssessmentText removes everything a reader cannot see from a marked
// text: the four mark characters (all of them format characters of Unicode) and
// the other invisible format characters. It
// is the text that assistive technology must read, and the client uses the same
// rule to keep the marks out of the accessibility tree.
func VisibleAssessmentText(text string) string {
return strings.Map(func(r rune) rune {
if invisibleTextRune(r) {
return -1
}
return r
}, text)
}
func invisibleTextRune(r rune) bool {
return unicode.Is(unicode.Cf, r)
}
// NormalizedAssessmentText brings a leaked text to a form in which it can be
// read: the invisible characters are removed, the typographic apostrophe
// becomes a plain one, and runs of white space, non-breaking spaces among them,
// collapse into one space. The wording of the text is kept.
func NormalizedAssessmentText(text string) string {
cleaned := strings.NewReplacer("\u2019", "'", "\u02bc", "'").Replace(VisibleAssessmentText(text))
return strings.Join(strings.Fields(cleaned), " ")
}
// CanonicalAssessmentText is the normalized text with every interchangeable
// phrase written in its canonical form. Two copies of one statement that differ
// only by the watermark have the same canonical text, and so does a stored
// statement, which makes it the form in which a leak is compared.
func CanonicalAssessmentText(text string) string {
return canonicalWording(NormalizedAssessmentText(text))
}