feat(assessment): watermark the task text of real attempts

This commit is contained in:
shira committed 2026-10-11 10:44:30 +03:00
1 parent 24b64d698a
commit c975a0d506
57 files changed
+2429 -92

No files matched your search

@@ -17,26 +17,27 @@ import (
)
var regexMap = map[string]ogenregex.Regexp{
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^/[A-Za-z0-9/_-]{0,255}$": ogenregex.MustCompile("^/[A-Za-z0-9/_-]{0,255}$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"),
"^[0-9]{6}$": ogenregex.MustCompile("^[0-9]{6}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^/[A-Za-z0-9/_-]{0,255}$": ogenregex.MustCompile("^/[A-Za-z0-9/_-]{0,255}$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$": ogenregex.MustCompile("^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$"),
"^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"),
"^[0-9]{6}$": ogenregex.MustCompile("^[0-9]{6}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
"^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$": ogenregex.MustCompile("^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$"),
}
var (
@@ -1496,6 +1496,12 @@ func (s AssessmentAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
case AssessmentCorrectiveAttemptAssessmentAttempt:
e.FieldStart("kind")
@@ -1574,6 +1580,12 @@ func (s AssessmentAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
case AssessmentExpressAttemptAssessmentAttempt:
e.FieldStart("kind")
@@ -1652,6 +1664,12 @@ func (s AssessmentAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
}
}
@@ -2712,9 +2730,15 @@ func (s *AssessmentCorrectiveAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
var jsonFieldsNameOfAssessmentCorrectiveAttempt = [18]string{
var jsonFieldsNameOfAssessmentCorrectiveAttempt = [19]string{
0: "id",
1: "version",
2: "specialization",
@@ -2733,6 +2757,7 @@ var jsonFieldsNameOfAssessmentCorrectiveAttempt = [18]string{
15: "progress",
16: "current_item",
17: "practices",
18: "watermark",
}
// Decode decodes AssessmentCorrectiveAttempt from json.
@@ -2934,6 +2959,16 @@ func (s *AssessmentCorrectiveAttempt) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"practices\"")
}
case "watermark":
if err := func() error {
s.Watermark.Reset()
if err := s.Watermark.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"watermark\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
@@ -4031,9 +4066,15 @@ func (s *AssessmentExpressAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
var jsonFieldsNameOfAssessmentExpressAttempt = [18]string{
var jsonFieldsNameOfAssessmentExpressAttempt = [19]string{
0: "id",
1: "version",
2: "specialization",
@@ -4052,6 +4093,7 @@ var jsonFieldsNameOfAssessmentExpressAttempt = [18]string{
15: "progress",
16: "current_item",
17: "practices",
18: "watermark",
}
// Decode decodes AssessmentExpressAttempt from json.
@@ -4253,6 +4295,16 @@ func (s *AssessmentExpressAttempt) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"practices\"")
}
case "watermark":
if err := func() error {
s.Watermark.Reset()
if err := s.Watermark.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"watermark\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
@@ -7488,9 +7540,15 @@ func (s *AssessmentQualifiedAttempt) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.Watermark.Set {
e.FieldStart("watermark")
s.Watermark.Encode(e)
}
}
}
var jsonFieldsNameOfAssessmentQualifiedAttempt = [18]string{
var jsonFieldsNameOfAssessmentQualifiedAttempt = [19]string{
0: "id",
1: "version",
2: "specialization",
@@ -7509,6 +7567,7 @@ var jsonFieldsNameOfAssessmentQualifiedAttempt = [18]string{
15: "progress",
16: "current_item",
17: "practices",
18: "watermark",
}
// Decode decodes AssessmentQualifiedAttempt from json.
@@ -7710,6 +7769,16 @@ func (s *AssessmentQualifiedAttempt) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"practices\"")
}
case "watermark":
if err := func() error {
s.Watermark.Reset()
if err := s.Watermark.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"watermark\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
@@ -10838,6 +10907,102 @@ func (s *AssessmentVersions) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *AssessmentWatermark) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *AssessmentWatermark) encodeFields(e *jx.Encoder) {
{
e.FieldStart("code")
e.Str(s.Code)
}
}
var jsonFieldsNameOfAssessmentWatermark = [1]string{
0: "code",
}
// Decode decodes AssessmentWatermark from json.
func (s *AssessmentWatermark) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode AssessmentWatermark to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "code":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Str()
s.Code = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"code\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode AssessmentWatermark")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000001,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfAssessmentWatermark) {
name = jsonFieldsNameOfAssessmentWatermark[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *AssessmentWatermark) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *AssessmentWatermark) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *BasicScore) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -43534,6 +43699,39 @@ func (s *OptAssessmentCategoryDecisionView) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes AssessmentWatermark as json.
func (o OptAssessmentWatermark) Encode(e *jx.Encoder) {
if !o.Set {
return
}
o.Value.Encode(e)
}
// Decode decodes AssessmentWatermark from json.
func (o *OptAssessmentWatermark) Decode(d *jx.Decoder) error {
if o == nil {
return errors.New("invalid: unable to decode OptAssessmentWatermark to nil")
}
o.Set = true
if err := o.Value.Decode(d); err != nil {
return err
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s OptAssessmentWatermark) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *OptAssessmentWatermark) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes CandidateSalaryCompatibility as json.
func (o OptCandidateSalaryCompatibility) Encode(e *jx.Encoder) {
if !o.Set {
@@ -1387,7 +1387,8 @@ type AssessmentCorrectiveAttempt struct {
// otherwise.
CurrentItem NilAssessmentItem `json:"current_item"`
// Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.
Practices []AssessmentPractice `json:"practices"`
Practices []AssessmentPractice `json:"practices"`
Watermark OptAssessmentWatermark `json:"watermark"`
}
// GetID returns the value of ID.
@@ -1480,6 +1481,11 @@ func (s *AssessmentCorrectiveAttempt) GetPractices() []AssessmentPractice {
return s.Practices
}
// GetWatermark returns the value of Watermark.
func (s *AssessmentCorrectiveAttempt) GetWatermark() OptAssessmentWatermark {
return s.Watermark
}
// SetID sets the value of ID.
func (s *AssessmentCorrectiveAttempt) SetID(val uuid.UUID) {
s.ID = val
@@ -1570,6 +1576,11 @@ func (s *AssessmentCorrectiveAttempt) SetPractices(val []AssessmentPractice) {
s.Practices = val
}
// SetWatermark sets the value of Watermark.
func (s *AssessmentCorrectiveAttempt) SetWatermark(val OptAssessmentWatermark) {
s.Watermark = val
}
// Start a corrective real assessment at a lower target grade in the chain rooted at root_attempt_id.
// The server validates that this grade is strictly below the preceding grade and that the chain
// remains within its existing deadline and quota. chain_deadline is derived from the root attempt and
@@ -2172,7 +2183,8 @@ type AssessmentExpressAttempt struct {
// otherwise.
CurrentItem NilAssessmentItem `json:"current_item"`
// Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.
Practices []AssessmentPractice `json:"practices"`
Practices []AssessmentPractice `json:"practices"`
Watermark OptAssessmentWatermark `json:"watermark"`
}
// GetID returns the value of ID.
@@ -2265,6 +2277,11 @@ func (s *AssessmentExpressAttempt) GetPractices() []AssessmentPractice {
return s.Practices
}
// GetWatermark returns the value of Watermark.
func (s *AssessmentExpressAttempt) GetWatermark() OptAssessmentWatermark {
return s.Watermark
}
// SetID sets the value of ID.
func (s *AssessmentExpressAttempt) SetID(val uuid.UUID) {
s.ID = val
@@ -2355,6 +2372,11 @@ func (s *AssessmentExpressAttempt) SetPractices(val []AssessmentPractice) {
s.Practices = val
}
// SetWatermark sets the value of Watermark.
func (s *AssessmentExpressAttempt) SetWatermark(val OptAssessmentWatermark) {
s.Watermark = val
}
// Explicitly start the short training run. It has no specialization or target grade, uses its separate
// demo policy, and does not consume a real-assessment attempt.
// Ref: #/components/schemas/AssessmentExpressAttemptCreate
@@ -4003,7 +4025,8 @@ type AssessmentQualifiedAttempt struct {
// otherwise.
CurrentItem NilAssessmentItem `json:"current_item"`
// Practices in the order assigned by the mode policy. The list exposes verdicts only after submission.
Practices []AssessmentPractice `json:"practices"`
Practices []AssessmentPractice `json:"practices"`
Watermark OptAssessmentWatermark `json:"watermark"`
}
// GetID returns the value of ID.
@@ -4096,6 +4119,11 @@ func (s *AssessmentQualifiedAttempt) GetPractices() []AssessmentPractice {
return s.Practices
}
// GetWatermark returns the value of Watermark.
func (s *AssessmentQualifiedAttempt) GetWatermark() OptAssessmentWatermark {
return s.Watermark
}
// SetID sets the value of ID.
func (s *AssessmentQualifiedAttempt) SetID(val uuid.UUID) {
s.ID = val
@@ -4186,6 +4214,11 @@ func (s *AssessmentQualifiedAttempt) SetPractices(val []AssessmentPractice) {
s.Practices = val
}
// SetWatermark sets the value of Watermark.
func (s *AssessmentQualifiedAttempt) SetWatermark(val OptAssessmentWatermark) {
s.Watermark = val
}
// Start a real assessment for a specialization and target grade, with the task language. The candidate
// comes from the session. The server chooses demo_basic or adaptive and fixes the policy, bank, and
// algorithm versions. Unknown fields such as `mode`, `seed`, or `score` are rejected.
@@ -5611,6 +5644,30 @@ func (s *AssessmentVersions) SetAlgorithmVersion(val AssessmentVersionLabel) {
s.AlgorithmVersion = val
}
// Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over
// the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by
// an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or
// identifier of the account, and it cannot be computed without the server secret. The task text of
// such an attempt also carries an invisible mark and interchangeable wordings chosen by the same
// secret; they change neither the meaning of a task nor its reference answer, and the client keeps the
// invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no
// watermark. It is evidence for a manual review and an appeal, never an automatic decision.
// Ref: #/components/schemas/AssessmentWatermark
type AssessmentWatermark struct {
// Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`.
Code string `json:"code"`
}
// GetCode returns the value of Code.
func (s *AssessmentWatermark) GetCode() string {
return s.Code
}
// SetCode sets the value of Code.
func (s *AssessmentWatermark) SetCode(val string) {
s.Code = val
}
// Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass
// mark comes from that policy version and never from the handler.
// Ref: #/components/schemas/BasicScore
@@ -21811,6 +21868,52 @@ func (o OptAssessmentCategoryDecisionView) Or(d AssessmentCategoryDecisionView)
return d
}
// NewOptAssessmentWatermark returns new OptAssessmentWatermark with value set to v.
func NewOptAssessmentWatermark(v AssessmentWatermark) OptAssessmentWatermark {
return OptAssessmentWatermark{
Value: v,
Set: true,
}
}
// OptAssessmentWatermark is optional AssessmentWatermark.
type OptAssessmentWatermark struct {
Value AssessmentWatermark
Set bool
}
// IsSet returns true if OptAssessmentWatermark was set.
func (o OptAssessmentWatermark) IsSet() bool { return o.Set }
// Reset unsets value.
func (o *OptAssessmentWatermark) Reset() {
var v AssessmentWatermark
o.Value = v
o.Set = false
}
// SetTo sets value to v.
func (o *OptAssessmentWatermark) SetTo(v AssessmentWatermark) {
o.Set = true
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o OptAssessmentWatermark) Get() (v AssessmentWatermark, ok bool) {
if !o.Set {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o OptAssessmentWatermark) Or(d AssessmentWatermark) AssessmentWatermark {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewOptCandidateSalaryCompatibility returns new OptCandidateSalaryCompatibility with value set to v.
func NewOptCandidateSalaryCompatibility(v CandidateSalaryCompatibility) OptCandidateSalaryCompatibility {
return OptCandidateSalaryCompatibility{
@@ -1186,6 +1186,24 @@ func (s *AssessmentCorrectiveAttempt) Validate() error {
Error: err,
})
}
if err := func() error {
if value, ok := s.Watermark.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "watermark",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
@@ -1954,6 +1972,24 @@ func (s *AssessmentExpressAttempt) Validate() error {
Error: err,
})
}
if err := func() error {
if value, ok := s.Watermark.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "watermark",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
@@ -3460,6 +3496,24 @@ func (s *AssessmentQualifiedAttempt) Validate() error {
Error: err,
})
}
if err := func() error {
if value, ok := s.Watermark.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "watermark",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
@@ -4735,6 +4789,41 @@ func (s *AssessmentVersions) Validate() error {
return nil
}
func (s *AssessmentWatermark) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 10,
MinLengthSet: true,
MaxLength: 11,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Code)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "code",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *BasicScore) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -23,9 +23,16 @@ type AssessmentOperations interface {
StartSession(ctx context.Context, command assessmentusecase.StartAttemptSessionCommand) (outbound.AssessmentAttemptSessionResult, error)
}
// AssessmentPresenter turns a stored attempt projection into what the candidate
// receives. It is the one place that marks the task text of a real attempt.
type AssessmentPresenter interface {
Present(snapshot domain.AssessmentAttemptPublicSnapshot) (domain.AssessmentAttemptPublicSnapshot, error)
}
// AssessmentHandler serves the candidate's frozen assessment attempts.
type AssessmentHandler struct {
operations AssessmentOperations
presenter AssessmentPresenter
}
func NewAssessmentHandler(operations AssessmentOperations) *AssessmentHandler {
@@ -35,6 +42,26 @@ func NewAssessmentHandler(operations AssessmentOperations) *AssessmentHandler {
return &AssessmentHandler{operations: operations}
}
// WithPresenter sets the presenter that every attempt response passes through.
// Without one the responses carry the stored projection unchanged.
func (handler *AssessmentHandler) WithPresenter(presenter AssessmentPresenter) *AssessmentHandler {
handler.presenter = presenter
return handler
}
// attemptResponse presents the snapshot and maps it to the response. Every
// operation that returns an attempt goes through it.
func (handler *AssessmentHandler) attemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot) (api.AssessmentAttempt, error) {
if handler.presenter != nil {
presented, err := handler.presenter.Present(snapshot)
if err != nil {
return api.AssessmentAttempt{}, fmt.Errorf("AssessmentHandler.attemptResponse - present attempt: %w", err)
}
snapshot = presented
}
return assessmentAttemptResponse(snapshot)
}
func (handler *Handler) CreateMyAssessmentAttempt(
ctx context.Context,
request api.AssessmentAttemptCreate,
@@ -131,7 +158,7 @@ func (handler *AssessmentHandler) CreateMyAssessmentAttempt(
if result.Outcome.StatusCode != 201 {
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - unexpected stored status %d", result.Outcome.StatusCode)
}
response, err := assessmentAttemptResponse(result.Outcome.Response)
response, err := handler.attemptResponse(result.Outcome.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - map response: %w", err)
}
@@ -150,7 +177,7 @@ func (handler *AssessmentHandler) GetMyAssessmentAttempt(
if err != nil {
return assessmentAttemptReadFailure(ctx, err)
}
response, err := assessmentAttemptResponse(snapshot)
response, err := handler.attemptResponse(snapshot)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentAttempt - map response: %w", err)
}
@@ -176,7 +203,7 @@ func (handler *AssessmentHandler) StartMyAssessmentAttemptSession(
if err != nil {
return assessmentSessionFailure(ctx, err)
}
response, err := assessmentAttemptResponse(result.Response)
response, err := handler.attemptResponse(result.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.StartMyAssessmentAttemptSession - map response: %w", err)
}
@@ -216,7 +243,7 @@ func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
if result.Outcome.StatusCode != 200 {
return assessmentAnswerCommandProblem(ctx, result.Outcome)
}
response, err := assessmentAttemptResponse(result.Outcome.Response)
response, err := handler.attemptResponse(result.Outcome.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.SubmitMyAssessmentAnswer - map response: %w", err)
}
@@ -251,7 +278,7 @@ func (handler *AssessmentHandler) FinalizeMyAssessmentAttempt(
if result.Outcome.StatusCode != 200 {
return assessmentFinalizeCommandProblem(ctx, result.Outcome)
}
response, err := assessmentAttemptResponse(result.Outcome.Response)
response, err := handler.attemptResponse(result.Outcome.Response)
if err != nil {
return nil, fmt.Errorf("AssessmentHandler.FinalizeMyAssessmentAttempt - map response: %w", err)
}
@@ -714,7 +741,7 @@ func assessmentAttemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot)
Mode: api.AssessmentQualifiedAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{}, Watermark: fields.watermark,
}), nil
case domain.AssessmentAttemptKindCorrective:
return api.NewAssessmentCorrectiveAttemptAssessmentAttempt(api.AssessmentCorrectiveAttempt{
@@ -724,7 +751,7 @@ func assessmentAttemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot)
Mode: api.AssessmentCorrectiveAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{}, Watermark: fields.watermark,
}), nil
case domain.AssessmentAttemptKindDemoExpress:
return api.NewAssessmentExpressAttemptAssessmentAttempt(api.AssessmentExpressAttempt{
@@ -734,7 +761,7 @@ func assessmentAttemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot)
Mode: api.AssessmentExpressAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{}, Watermark: fields.watermark,
}), nil
default:
return api.AssessmentAttempt{}, errors.New("unknown assessment attempt kind")
@@ -754,6 +781,7 @@ type assessmentAttemptResponseFields struct {
finishedAt api.NilTimestamp
progress api.AssessmentProgress
currentItem api.NilAssessmentItem
watermark api.OptAssessmentWatermark
}
func assessmentAttemptFields(snapshot domain.AssessmentAttemptPublicSnapshot, currentItem api.NilAssessmentItem) assessmentAttemptResponseFields {
@@ -766,6 +794,9 @@ func assessmentAttemptFields(snapshot domain.AssessmentAttemptPublicSnapshot, cu
progress: api.AssessmentProgress{AnsweredItems: snapshot.AnsweredItems, MaxItems: snapshot.MaxItems},
currentItem: currentItem,
}
if snapshot.Watermark != nil {
fields.watermark.SetTo(api.AssessmentWatermark{Code: snapshot.Watermark.Code})
}
setAttemptTrackFields(&fields, snapshot)
setAttemptSessionFields(&fields, snapshot)
setAttemptEndFields(&fields, snapshot)
@@ -235,3 +235,73 @@ func assessmentPublicSnapshot() domain.AssessmentAttemptPublicSnapshot {
func domainCodePointer[T ~string](value T) *T {
return &value
}
type presenterStub struct{ err error }
func (stub presenterStub) Present(snapshot domain.AssessmentAttemptPublicSnapshot) (domain.AssessmentAttemptPublicSnapshot, error) {
if stub.err != nil {
return domain.AssessmentAttemptPublicSnapshot{}, stub.err
}
snapshot.Watermark = &domain.AssessmentAttemptPublicWatermark{Code: "7K3QD-9XM2T"}
item := *snapshot.CurrentItem
item.Prompt += "\u200b"
snapshot.CurrentItem = &item
return snapshot, nil
}
func TestEveryAttemptResponsePassesThroughThePresenter(t *testing.T) {
snapshot := assessmentPublicSnapshot()
operations := &assessmentOperationsStub{read: snapshot, start: outbound.AssessmentAttemptSessionResult{Response: snapshot}}
handler := NewAssessmentHandler(operations).WithPresenter(presenterStub{})
ctx := principalForTest(uuid.New())
read, err := handler.GetMyAssessmentAttempt(ctx, api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()})
if err != nil {
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
}
started, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{ExpectedVersion: 7},
api.StartMyAssessmentAttemptSessionParams{AttemptID: snapshot.ID.UUID(), IdempotencyKey: "session-key"})
if err != nil {
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
}
for name, response := range map[string]any{"read": read, "start": started} {
headers, ok := response.(*api.AssessmentAttemptHeaders)
if !ok {
t.Fatalf("%s response = %T, want attempt headers", name, response)
}
qualified, ok := headers.Response.GetAssessmentQualifiedAttempt()
if !ok {
t.Fatalf("%s response is not a qualified attempt", name)
}
code, hasCode := qualified.Watermark.Get()
item, _ := qualified.CurrentItem.Get()
if !hasCode || code.Code != "7K3QD-9XM2T" || item.Prompt != "Choose the number\u200b" {
t.Fatalf("%s response watermark = %+v/%v and prompt %q, want the presented values", name, code, hasCode, item.Prompt)
}
}
}
func TestAnAttemptWithoutAPresenterCarriesNoWatermark(t *testing.T) {
snapshot := assessmentPublicSnapshot()
handler := NewAssessmentHandler(&assessmentOperationsStub{read: snapshot})
read, err := handler.GetMyAssessmentAttempt(principalForTest(uuid.New()), api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()})
if err != nil {
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
}
headers, ok := read.(*api.AssessmentAttemptHeaders)
if !ok {
t.Fatalf("read response = %T, want attempt headers", read)
}
qualified, _ := headers.Response.GetAssessmentQualifiedAttempt()
if qualified.Watermark.IsSet() {
t.Fatal("an attempt served without a presenter carries a watermark")
}
}
func TestAPresenterFailureIsAServerErrorNotAnUnmarkedAttempt(t *testing.T) {
snapshot := assessmentPublicSnapshot()
handler := NewAssessmentHandler(&assessmentOperationsStub{read: snapshot}).WithPresenter(presenterStub{err: errors.New("seed unavailable")})
if _, err := handler.GetMyAssessmentAttempt(principalForTest(uuid.New()), api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()}); err == nil {
t.Fatal("GetMyAssessmentAttempt() succeeded, want an error so that the task text is never served unmarked")
}
}
+8 -1
View File
@@ -56,5 +56,12 @@ func newAssessmentHandler(
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create signal observer: %w", err)
}
service.WithSignalObserver(observer)
return v1.NewAssessmentHandler(service), pool.Close, nil
// The watermark is derived from the identity keyring like the signal
// digests: the same secret, a key of its own, and no new setting.
watermarker, err := assessment.NewWatermarker(keyring)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create watermarker: %w", err)
}
return v1.NewAssessmentHandler(service).WithPresenter(watermarker), pool.Close, nil
}
@@ -318,6 +318,16 @@ type AssessmentAttemptPublicSnapshot struct {
IdleTimeout int32 `json:"idle_timeout_seconds"`
CurrentItem *AssessmentAttemptPublicItem `json:"current_item"`
Practices []AssessmentAttemptPublicPractice `json:"practices"`
// Watermark is set when a response is presented, never when it is stored:
// the retained idempotent response stays free of it, and every presentation
// derives the same value from the attempt.
Watermark *AssessmentAttemptPublicWatermark `json:"watermark,omitempty"`
}
// AssessmentAttemptPublicWatermark is the visible pseudonymous code that the
// task screen shows next to the time. It reveals nothing about the candidate.
type AssessmentAttemptPublicWatermark struct {
Code string `json:"code"`
}
// AssessmentAttemptPublicPractice is the empty, explicit practice projection
@@ -0,0 +1,321 @@
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))
}
@@ -0,0 +1,343 @@
package domain
import (
"strings"
"testing"
"unicode"
)
// rateLimitTemplate is the statement template of the rate limit family of the demo
// bank. It holds several interchangeable phrases, as real statements do.
const rateLimitTemplate = "A gateway protects an endpoint with a sliding-window limiter. A request arriving at second t is accepted only when fewer than {{.limit}} previously accepted requests have an arrival time in the half-open interval (t - {{.window}}, t]. A rejected request is not remembered and does not count against later requests. The gateway receives {{.requests}} requests at these arrival times, in seconds and in non-decreasing order: {{.timestamps}}. How many requests does the gateway reject?"
func watermarkSeed(first byte) AssessmentWatermarkSeed {
var seed AssessmentWatermarkSeed
for index := range seed {
seed[index] = first + byte(index*7)
}
return seed
}
func testWatermark(t *testing.T, first byte) AssessmentWatermark {
t.Helper()
watermark, err := NewAssessmentWatermark(watermarkSeed(first))
if err != nil {
t.Fatalf("NewAssessmentWatermark() error = %v", err)
}
return watermark
}
func rateLimitVariant(t *testing.T) AssessmentVariant {
t.Helper()
input := testAssessmentInput()
input.Generator = AssessmentSeedGenerator{
Algorithm: "rate_limit_window.v1",
Parameters: map[string]AssessmentParameterRange{
"requests": {Min: 8, Max: 12}, "window": {Min: 3, Max: 5}, "limit": {Min: 2, Max: 3}, "max_gap": {Min: 0, Max: 3},
},
StatementTemplate: rateLimitTemplate,
}
input.AnswerKey.AnswerFormat = assessmentAlgorithms["rate_limit_window.v1"].answerFormat
variant, err := restoreAssessment(t, input).NewVariant(4242)
if err != nil {
t.Fatalf("NewVariant() error = %v", err)
}
return variant
}
func hasInvisible(text string) bool {
return strings.IndexFunc(text, func(r rune) bool { return unicode.Is(unicode.Cf, r) }) >= 0
}
func TestTheSameVariantOfTwoAttemptsDiffersOnlyByTheWatermark(t *testing.T) {
variant := rateLimitVariant(t)
first, second := testWatermark(t, 1), testWatermark(t, 9)
markedFirst, markedSecond := first.Mark(variant.Statement), second.Mark(variant.Statement)
if markedFirst == markedSecond {
t.Fatal("two attempts got the same marked statement, want a mark of their own")
}
if !hasInvisible(markedFirst) || !hasInvisible(markedSecond) {
t.Fatal("a marked statement has no invisible mark")
}
// Whatever the attempt, the statement says the same: only the mark and the
// interchangeable phrases differ, and both disappear in the canonical text.
want := CanonicalAssessmentText(variant.Statement)
for name, marked := range map[string]string{"first": markedFirst, "second": markedSecond} {
if got := CanonicalAssessmentText(marked); got != want {
t.Fatalf("canonical text of the %s attempt =\n%q\nwant\n%q", name, got, want)
}
}
// The mark is outside the variant: the reference answer, the rubric, and the
// options that grading reads are the ones of the variant.
if variant.ReferenceAnswer == "" {
t.Fatal("the variant has no reference answer to compare")
}
if again := rateLimitVariant(t); again.ReferenceAnswer != variant.ReferenceAnswer || again.Statement != variant.Statement {
t.Fatal("marking changed the variant, want the unmarked statement and the same reference answer")
}
}
func TestMarkingIsDeterministicAndIdempotent(t *testing.T) {
statement := rateLimitVariant(t).Statement
watermark := testWatermark(t, 3)
marked := watermark.Mark(statement)
if again := watermark.Mark(statement); again != marked {
t.Fatal("marking the same statement twice gave two results")
}
if again := watermark.Mark(marked); again != marked {
t.Fatal("marking a marked statement changed it, want the same text")
}
if other := testWatermark(t, 3).Mark(statement); other != marked {
t.Fatal("equal seeds gave different marks")
}
}
func TestInvisibleMarkRoundTripsAndSurvivesCopiedSentences(t *testing.T) {
statement := rateLimitVariant(t).Statement
watermark := testWatermark(t, 5)
marked := watermark.Mark(statement)
codes := ExtractAssessmentWatermarkCodes(marked)
if len(codes) < 3 {
t.Fatalf("ExtractAssessmentWatermarkCodes() found %d copies, want one in each of several sentences", len(codes))
}
for _, code := range codes {
if code != watermark.Code() {
t.Fatalf("a copy decoded to %s, want %s", code, watermark.Code())
}
}
// A paragraph taken from the middle keeps a whole run.
sentences := strings.SplitAfter(marked, ". ")
if got := ExtractAssessmentWatermarkCodes(sentences[2] + sentences[3]); len(got) == 0 || got[0] != watermark.Code() {
t.Fatalf("two copied sentences decoded to %v, want %s", got, watermark.Code())
}
// Removing the invisible characters removes the mark and nothing else.
if codes := ExtractAssessmentWatermarkCodes(VisibleAssessmentText(marked)); len(codes) != 0 {
t.Fatalf("a text without invisible characters decoded to %v", codes)
}
}
func TestDamagedInvisibleMarkIsNotRead(t *testing.T) {
watermark := testWatermark(t, 5)
run := watermark.zeroWidthRun()
runes := []rune(run)
tests := map[string]string{
"a run cut short": "a " + string(runes[:len(runes)-1]) + " b",
"a run with an extra": "a " + run + string(watermarkZeroWidth[1]) + " b",
"a wrong check digit": "a " + string(runes[:len(runes)-1]) + string(watermarkZeroWidth[(watermarkDigit(runes[len(runes)-1])+1)%4]) + " b",
"two runs run together": "a " + run + run + " b",
}
for name, text := range tests {
t.Run(name, func(t *testing.T) {
if codes := ExtractAssessmentWatermarkCodes(text); len(codes) != 0 {
t.Fatalf("ExtractAssessmentWatermarkCodes() = %v, want nothing from a damaged mark", codes)
}
})
}
if codes := ExtractAssessmentWatermarkCodes("a " + run + " b"); len(codes) != 1 || codes[0] != watermark.Code() {
t.Fatalf("ExtractAssessmentWatermarkCodes(intact run) = %v, want one code", codes)
}
}
func TestAccessibleTextOfAMarkedStatementIsTheStatement(t *testing.T) {
variant := rateLimitVariant(t)
watermark := testWatermark(t, 7)
marked := watermark.Mark(variant.Statement)
visible := VisibleAssessmentText(marked)
if hasInvisible(visible) {
t.Fatal("the accessible text still holds an invisible character")
}
// What assistive technology reads is the statement with the phrases the
// attempt picked: the same words in the same order, nothing added.
if got, want := CanonicalAssessmentText(visible), CanonicalAssessmentText(variant.Statement); got != want {
t.Fatalf("accessible text differs in meaning:\n%q\nwant\n%q", got, want)
}
if len(visible) > len(variant.Statement)+32 {
t.Fatalf("accessible text grew from %d to %d bytes, want only a different choice of phrases", len(variant.Statement), len(visible))
}
// The numbers and data of the task are untouched.
for _, token := range strings.Fields(variant.Statement) {
if strings.ContainsAny(token, "0123456789") && !strings.Contains(visible, strings.Trim(token, ".,:;")) {
t.Fatalf("data token %q is missing from the accessible text", token)
}
}
}
func TestWordingAgreementReadsOnlyTheAlignedPhrasesOfTheStatement(t *testing.T) {
statement := rateLimitVariant(t).Statement
first := testWatermark(t, 1)
own := first.Mark(statement)
// The statement as the attempt showed it, alone and among other words that
// hold phrases of their own, agrees with every phrase of its attempt.
surrounded := "He wrote: it isn't hard, and we don't know. " + VisibleAssessmentText(own) + " Thanks, it isn't clear."
for name, leak := range map[string]string{"alone": VisibleAssessmentText(own), "with the marks": own, "surrounded": surrounded} {
agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, leak))
if slots < 4 || agreeing != slots {
t.Fatalf("%s: WordingAgreement() = %d of %d, want every one of at least four phrase groups to agree", name, agreeing, slots)
}
}
// Some other attempt picked other phrases for at least one group, and it
// disagrees with the leak of the first one.
disagreeing := 0
for seed := byte(2); seed < 40; seed++ {
if agreeing, slots := testWatermark(t, seed).WordingAgreement(AssessmentLeakAlignment(statement, VisibleAssessmentText(own))); agreeing < slots {
disagreeing++
}
}
if disagreeing == 0 {
t.Fatal("no other seed disagrees with the phrases of the first attempt")
}
// A leak of a fragment yields the phrases of the fragment only.
piece := VisibleAssessmentText(own)
start := strings.Index(piece, "A rejected")
if start < 0 {
t.Fatal("the statement has no sentence that starts with A rejected")
}
fragment := piece[start:]
if agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, fragment)); slots == 0 || slots >= 5 || agreeing != slots {
t.Fatalf("fragment: WordingAgreement() = %d of %d, want fewer groups than the whole statement, all agreeing", agreeing, slots)
}
// A text that is not the statement has nothing to align.
if agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, "It is not what it is. It does not matter, as it isn't related.")); slots != 0 || agreeing != 0 {
t.Fatalf("unrelated text: WordingAgreement() = %d of %d, want nothing aligned", agreeing, slots)
}
// A group written in two forms is edited text and agrees with no group.
edited := strings.Replace(VisibleAssessmentText(own), "does not", "doesn't", 1) + " " + strings.Replace(VisibleAssessmentText(own), "doesn't", "does not", 1)
if agreeing, slots := first.WordingAgreement(AssessmentLeakAlignment(statement, edited)); agreeing > slots {
t.Fatalf("edited text: %d of %d", agreeing, slots)
}
}
func TestAlignmentIsLongestForTheVariantThatWasLeakedAndShorterForOtherVariants(t *testing.T) {
input := testAssessmentInput()
input.Generator = AssessmentSeedGenerator{
Algorithm: "rate_limit_window.v1",
Parameters: map[string]AssessmentParameterRange{
"requests": {Min: 8, Max: 12}, "window": {Min: 3, Max: 5}, "limit": {Min: 2, Max: 3}, "max_gap": {Min: 0, Max: 3},
},
StatementTemplate: rateLimitTemplate,
}
input.AnswerKey.AnswerFormat = assessmentAlgorithms["rate_limit_window.v1"].answerFormat
family := restoreAssessment(t, input)
leaked, err := family.NewVariant(4242)
if err != nil {
t.Fatalf("NewVariant(4242) error = %v", err)
}
other, err := family.NewVariant(99)
if err != nil || other.Statement == leaked.Statement {
t.Fatalf("NewVariant(99) = %v, %v, want another statement", other.Statement, err)
}
leak := "Someone asked: " + VisibleAssessmentText(testWatermark(t, 1).Mark(leaked.Statement)) + " thanks"
own, foreign := AssessmentLeakAlignment(leaked.Statement, leak), AssessmentLeakAlignment(other.Statement, leak)
if own.Runes <= foreign.Runes {
t.Fatalf("aligned %d characters for the leaked variant and %d for another variant of the family, want the leaked one longer", own.Runes, foreign.Runes)
}
// The leak is a copy of the leaked variant, and the other variant shares only
// the text of its family and then diverges, so it is not the source.
if !own.Complete || !own.Follows() || foreign.Follows() {
t.Fatalf("leaked variant: %+v, other variant: %+v, want the leaked one followed to its end and the other one diverged", own, foreign)
}
// A leak cut inside the statement ends there; a leak with other words in the
// middle of it has diverged.
cut := VisibleAssessmentText(testWatermark(t, 1).Mark(leaked.Statement))
cut = cut[:len(cut)*2/3]
if got := AssessmentLeakAlignment(leaked.Statement, cut); got.Complete || !got.Ended || !got.Follows() {
t.Fatalf("a cut leak aligned %+v, want it to end inside the statement", got)
}
if got := AssessmentLeakAlignment(leaked.Statement, cut+" and some other words that the statement does not have"); got.Follows() {
t.Fatalf("a leak with other words inside the statement aligned %+v, want it to have diverged", got)
}
total := 0
for _, piece := range AssessmentTextPiecesBetweenPhrases(NormalizedAssessmentText(leaked.Statement)) {
total += len([]rune(piece))
}
if own.Runes != total {
t.Fatalf("the leaked variant aligned %d characters, want all %d characters of its pieces", own.Runes, total)
}
if got := AssessmentLeakAlignment(leaked.Statement, "nothing in common with it at all"); got.Runes != 0 || len(got.Phrases) != 0 {
t.Fatalf("unrelated text aligned %+v, want nothing", got)
}
}
func TestSplittingATextAtItsPhrasesLeavesPiecesThatEveryCopyShares(t *testing.T) {
statement := rateLimitVariant(t).Statement
// Whatever phrases an attempt picked, the pieces between them are the same.
want := AssessmentTextPiecesBetweenPhrases(NormalizedAssessmentText(statement))
for seed := byte(1); seed < 20; seed++ {
got := AssessmentTextPiecesBetweenPhrases(NormalizedAssessmentText(testWatermark(t, seed).Mark(statement)))
if len(got) != len(want) {
t.Fatalf("seed %d: %d pieces, want %d", seed, len(got), len(want))
}
for index := range want {
if got[index] != want[index] {
t.Fatalf("seed %d: piece %d = %q, want %q", seed, index, got[index], want[index])
}
}
}
}
func TestInterchangeablePhrasesStayWithinTheirGuards(t *testing.T) {
watermark := testWatermark(t, 1)
// At the end of a sentence "at most" is not followed by a number, so the
// alternative form would not read the same and is not used.
tail := "How many requests per minute can it serve at most?"
if got := VisibleAssessmentText(watermark.Mark(tail)); got != tail {
t.Fatalf("Mark(%q) = %q, want the phrase before a question mark kept", tail, got)
}
// Inside a longer word nothing is replaced.
inside := "This is nothing, and scannotes stays."
if got := VisibleAssessmentText(watermark.Mark(inside)); !strings.Contains(got, "scannotes") || !strings.Contains(got, "This is nothing") {
t.Fatalf("Mark(%q) = %q, want words that contain a phrase left alone", inside, got)
}
// Both forms of a group map to the canonical one.
for want, texts := range map[string][]string{
"holds at most 5 entries": {"holds at most 5 entries", "holds no more than 5 entries"},
"хранит не более 5 записей": {"хранит не более 5 записей", "хранит не больше 5 записей"},
"it isn't empty": {"it isn't empty", "it is not empty", "it isn\u2019t empty"},
} {
for _, text := range texts {
if got := CanonicalAssessmentText(text); got != strings.ReplaceAll(want, "isn't", "is not") {
t.Fatalf("CanonicalAssessmentText(%q) = %q", text, got)
}
}
}
}
func TestWatermarkCodeIsStableReadableAndParsesWhatOCRReads(t *testing.T) {
watermark := testWatermark(t, 1)
code := watermark.Code()
if len(code) != watermarkCodeLength || len(code.String()) != watermarkCodeLength+1 || code.String()[5] != '-' {
t.Fatalf("Code() = %q, want ten symbols shown as XXXXX-XXXXX", code)
}
if testWatermark(t, 1).Code() != code || testWatermark(t, 2).Code() == code {
t.Fatal("the code must follow the seed")
}
for _, shown := range []string{code.String(), strings.ToLower(code.String()), strings.ReplaceAll(code.String(), "-", " ")} {
parsed, err := ParseAssessmentWatermarkCode(shown)
if err != nil || parsed != code {
t.Fatalf("ParseAssessmentWatermarkCode(%q) = %q, %v, want %q", shown, parsed, err, code)
}
}
// The letters that OCR confuses read as the digits and letters of the alphabet.
read, err := ParseAssessmentWatermarkCode("OIL0O-1U123")
if err != nil {
t.Fatalf("ParseAssessmentWatermarkCode(OCR errors) error = %v", err)
}
if got, want := read.String(), "01100-1V123"; got != want {
t.Fatalf("ParseAssessmentWatermarkCode(OCR errors) = %q, want %q", got, want)
}
for _, bad := range []string{"", "ABCDE", "ABCDE-FGHJK-M", "ABCD!-FGHJK", "ABCDE-FGHJ#"} {
if _, err := ParseAssessmentWatermarkCode(bad); err == nil {
t.Fatalf("ParseAssessmentWatermarkCode(%q) succeeded, want an error", bad)
}
}
if code.Distance(code) != 0 || code.Distance(testWatermark(t, 2).Code()) == 0 {
t.Fatal("Distance must be zero for equal codes only")
}
if _, err := NewAssessmentWatermark(AssessmentWatermarkSeed{}); err == nil {
t.Fatal("NewAssessmentWatermark(zero seed) succeeded, want an error")
}
}
@@ -0,0 +1,262 @@
package domain
import (
"strings"
"unicode"
"unicode/utf8"
)
// wordingGroup lists interchangeable ways to write one phrase of a statement.
// Every form means exactly the same, so choosing one never changes the task or
// its reference answer. forms[0] is the canonical form: the attempt marker
// replaces every form of a group in a statement by the form it picked for the
// attempt, and the leak trace maps every form back to forms[0] before it
// compares texts.
//
// The list is append-only. Reordering or removing a form, or inserting a group
// before another, changes the choice of every attempt already served, and the
// marks of those attempts could no longer be read back. A new group goes to the
// end.
type wordingGroup struct {
forms []string
// beforeNumber limits the group to places where the phrase is followed by a
// space and a digit ("at most 5"). The forms read the same only there: "at
// most" ends a sentence in "how many can it serve at most?", where "no more
// than" would not.
beforeNumber bool
}
// assessmentWordingGroups are phrases of plain connective prose in the
// statements: comparisons of counts, negations that can be contracted, and
// spelling variants. They avoid the terms a statement defines and then reuses
// ("processed", "dropped", "accepted"), because rewording one of several uses of
// a defined term would confuse the task.
//
//nolint:gochecknoglobals // A fixed, append-only table that is read-only after initialization.
var assessmentWordingGroups = []wordingGroup{
{forms: []string{"at most", "no more than"}, beforeNumber: true},
{forms: []string{"at least", "no fewer than"}, beforeNumber: true},
{forms: []string{"fewer than", "less than"}, beforeNumber: true},
{forms: []string{"is not", "isn't"}},
{forms: []string{"are not", "aren't"}},
{forms: []string{"does not", "doesn't"}},
{forms: []string{"do not", "don't"}},
{forms: []string{"cannot", "can't"}},
{forms: []string{"non-decreasing", "nondecreasing"}},
{forms: []string{"only when", "only if"}},
{forms: []string{"half-open interval", "half open interval"}},
{forms: []string{"one at a time", "one by one"}},
{forms: []string{"Among all", "Of all"}},
{forms: []string{"не более", "не больше"}, beforeNumber: true},
{forms: []string{"не менее", "не меньше"}, beforeNumber: true},
{forms: []string{"только если", "лишь если"}},
{forms: []string{"в порядке неубывания", "в неубывающем порядке"}},
{forms: []string{"Найдите", "Определите"}},
}
// wordingOccurrence is one phrase found in a text.
type wordingOccurrence struct {
group int
form int
start int
end int
}
// findWordingOccurrences scans the text left to right and returns the
// non-overlapping phrases of the table. Where several forms start at the same
// place the longest wins.
func findWordingOccurrences(text string) []wordingOccurrence {
var found []wordingOccurrence
for position := 0; position < len(text); {
best := wordingOccurrence{group: -1}
for groupIndex, group := range assessmentWordingGroups {
for formIndex, form := range group.forms {
if !wordingFormAt(text, position, form, group.beforeNumber) {
continue
}
if best.group < 0 || len(form) > best.end-best.start {
best = wordingOccurrence{group: groupIndex, form: formIndex, start: position, end: position + len(form)}
}
}
}
if best.group < 0 {
_, size := utf8.DecodeRuneInString(text[position:])
position += size
continue
}
found = append(found, best)
position = best.end
}
return found
}
// wordingFormAt reports whether the form stands at the position as whole
// words: not inside a longer word and, for a number group, before a number.
func wordingFormAt(text string, position int, form string, beforeNumber bool) bool {
if !strings.HasPrefix(text[position:], form) {
return false
}
if previous, _ := utf8.DecodeLastRuneInString(text[:position]); position > 0 && wordRune(previous) {
return false
}
end := position + len(form)
if next, _ := utf8.DecodeRuneInString(text[end:]); end < len(text) && wordRune(next) {
return false
}
if !beforeNumber {
return true
}
rest := text[end:]
if len(rest) < 2 || rest[0] != ' ' {
return false
}
return rest[1] >= '0' && rest[1] <= '9'
}
// wordRune reports whether the rune continues a word. The apostrophe and the
// hyphen join words in the forms of the table, so a form never starts or ends
// inside a hyphenated or contracted word.
func wordRune(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '\'' || r == '-'
}
// rewriteWording replaces every phrase of the table by the form that choose
// returns for its group.
func rewriteWording(text string, choose func(group int) int) string {
occurrences := findWordingOccurrences(text)
if len(occurrences) == 0 {
return text
}
var builder strings.Builder
builder.Grow(len(text) + 16)
copied := 0
for _, occurrence := range occurrences {
builder.WriteString(text[copied:occurrence.start])
builder.WriteString(assessmentWordingGroups[occurrence.group].forms[choose(occurrence.group)])
copied = occurrence.end
}
builder.WriteString(text[copied:])
return builder.String()
}
// canonicalWording writes every phrase of the table in its canonical form.
func canonicalWording(text string) string {
return rewriteWording(text, func(int) int { return 0 })
}
// AssessmentTextPiecesBetweenPhrases cuts a text at every interchangeable
// phrase and returns the pieces in between. The pieces read the same in every
// copy of a statement, whichever form each attempt wrote the phrases in, so a
// stored statement can be searched for a piece literally.
func AssessmentTextPiecesBetweenPhrases(text string) []string {
pieces := make([]string, 0, 8)
copied := 0
for _, occurrence := range findWordingOccurrences(text) {
pieces = append(pieces, text[copied:occurrence.start])
copied = occurrence.end
}
return append(pieces, text[copied:])
}
// minAlignedPieceRunes is the shortest piece of a statement that the alignment
// accepts as a landmark in a leak: a shorter one occurs anywhere.
const minAlignedPieceRunes = 8
// LeakPhrase is a phrase of a statement as a leak writes it: the group and the
// index of the form that the leak uses.
type LeakPhrase struct {
Group int
Form int
}
// LeakAlignment is how far a leaked text follows a stored statement: the
// phrases it shows, in the forms it writes them, and the number of characters
// of the statement that it repeats between its phrases.
type LeakAlignment struct {
Phrases []LeakPhrase
// Runes is the length of the pieces of the statement that the leak repeats
// in order. A leak of the whole statement repeats all of them, and the
// statement of another variant of the same family repeats only the text of
// the family up to the first number that differs.
Runes int
// Complete reports that the leak followed the statement to its end. Ended
// reports that the leak stopped inside the statement, exactly where the
// statement continues. A leak that has other words where the statement
// continues does neither: it diverged from the statement, so the statement is
// not its source, however long the text they share.
Complete bool
Ended bool
}
// Follows reports whether the leak is a copy of the statement, whole or cut:
// it either reached the end of the statement or ended inside it.
func (alignment LeakAlignment) Follows() bool { return alignment.Complete || alignment.Ended }
// AssessmentLeakAlignment aligns a leaked text with a stored statement. It finds
// a landmark of the statement in the leak (the first piece between phrases that
// is long enough) and then follows the statement: after each piece, the leak
// must continue with one form of the next phrase and then the next piece. It
// stops at the first place where the leak does not follow the statement, so a
// leak that holds only part of the statement, an edited one, or the statement of
// another variant yields only the part that was aligned.
func AssessmentLeakAlignment(statement, leak string) LeakAlignment {
normalized := NormalizedAssessmentText(statement)
occurrences := findWordingOccurrences(normalized)
pieces := AssessmentTextPiecesBetweenPhrases(normalized)
leak = NormalizedAssessmentText(leak)
start, position := firstLandmark(pieces, leak)
if start < 0 {
return LeakAlignment{}
}
alignment := LeakAlignment{Runes: utf8.RuneCountInString(pieces[start]), Complete: true}
for index := start; index < len(occurrences); index++ {
group := assessmentWordingGroups[occurrences[index].group]
next := pieces[index+1]
matched := false
for form, text := range group.forms {
if strings.HasPrefix(leak[position:], text+next) {
alignment.Phrases = append(alignment.Phrases, LeakPhrase{Group: occurrences[index].group, Form: form})
alignment.Runes += utf8.RuneCountInString(next)
position += len(text) + len(next)
matched = true
break
}
}
if !matched {
alignment.Complete = false
alignment.Ended = leakEndsInside(leak[position:], group.forms, next)
break
}
}
return alignment
}
// leakEndsInside reports whether the rest of the leak is the beginning of what
// the statement has next (a form of the phrase, then the next piece), which is
// how a leak that was cut ends. An empty rest, and a rest that holds only a cut
// phrase or a cut piece, end the leak; any other word does not.
func leakEndsInside(rest string, forms []string, next string) bool {
if rest == "" {
return true
}
for _, form := range forms {
if strings.HasPrefix(form+next, rest) {
return true
}
}
return false
}
// firstLandmark returns the index of the first piece that is long enough and
// occurs in the leak, and the position in the leak just after it.
func firstLandmark(pieces []string, leak string) (index, position int) {
for index, piece := range pieces {
if utf8.RuneCountInString(piece) < minAlignedPieceRunes {
continue
}
if at := strings.Index(leak, piece); at >= 0 {
return index, at + len(piece)
}
}
return -1, 0
}
@@ -18,8 +18,10 @@ import (
// every candidate acknowledges the new wording. Acknowledgements are stored per
// version, so one given for an earlier version never counts for this one.
//
// Version 2 added the attempt measures to the text; version 1 listed signals only.
const CurrentSignalNoticeVersion int32 = 2
// Version 3 describes the watermark of the task screen and text, which version
// 2 announced as planned; version 2 added the attempt measures to the text;
// version 1 listed signals only.
const CurrentSignalNoticeVersion int32 = 3
// ErrSignalNoticeVersionMismatch reports an acknowledgement for a notice
// version other than the one the server requires.
@@ -0,0 +1,68 @@
package assessment
import (
"errors"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// WatermarkSeeds derives the secret stream that marks the task text of one
// attempt. The seed is computed on the server from the attempt identifier and a
// server key and never leaves it.
type WatermarkSeeds interface {
AssessmentWatermarkSeed(attemptID uuid.UUID) domain.AssessmentWatermarkSeed
}
// Watermarker puts the attempt watermark on the task text of a response. The
// visible code is returned next to the text and the invisible mark is written
// into it, both from the seed of the attempt. The stored attempt, the
// idempotent responses, the reference answer, and the grading are not touched:
// the mark exists only in what is presented.
type Watermarker struct {
seeds WatermarkSeeds
}
// NewWatermarker fails at startup when the seed source is missing.
func NewWatermarker(seeds WatermarkSeeds) (*Watermarker, error) {
if seeds == nil {
return nil, errors.New("assessment.NewWatermarker - seeds must be set")
}
return &Watermarker{seeds: seeds}, nil
}
// Watermark returns the code and the marked statement for one attempt.
func (watermarker *Watermarker) Watermark(attemptID domain.AssessmentAttemptID) (domain.AssessmentWatermark, error) {
const location = "Watermarker.Watermark"
watermark, err := domain.NewAssessmentWatermark(watermarker.seeds.AssessmentWatermarkSeed(attemptID.UUID()))
if err != nil {
return domain.AssessmentWatermark{}, fmt.Errorf("%s - build watermark: %w", location, err)
}
return watermark, nil
}
// Present returns the snapshot as the candidate receives it. A real attempt,
// root or corrective, gets the visible code and the marked statement of its
// current item; a training run is returned unchanged. A nil Watermarker leaves
// every snapshot unchanged, so a deployment without it still serves attempts.
func (watermarker *Watermarker) Present(
snapshot domain.AssessmentAttemptPublicSnapshot,
) (domain.AssessmentAttemptPublicSnapshot, error) {
const location = "Watermarker.Present"
if watermarker == nil || !isRealAttemptKind(snapshot.Kind) {
return snapshot, nil
}
watermark, err := watermarker.Watermark(snapshot.ID)
if err != nil {
return domain.AssessmentAttemptPublicSnapshot{}, fmt.Errorf("%s - watermark attempt: %w", location, err)
}
snapshot.Watermark = &domain.AssessmentAttemptPublicWatermark{Code: watermark.Code().String()}
if snapshot.CurrentItem != nil {
item := *snapshot.CurrentItem
item.Prompt = watermark.Mark(item.Prompt)
snapshot.CurrentItem = &item
}
return snapshot, nil
}
@@ -0,0 +1,95 @@
package assessment
import (
"crypto/sha256"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// hashedSeeds stands in for the keyring: a seed that follows the attempt.
type hashedSeeds struct{}
func (hashedSeeds) AssessmentWatermarkSeed(attemptID uuid.UUID) domain.AssessmentWatermarkSeed {
return sha256.Sum256(append([]byte("test-watermark:"), attemptID[:]...))
}
const watermarkTestPrompt = "A cache holds at most 3 entries. A read of a missing key is not a hit. How many reads are hits?"
func presentedSnapshot(kind domain.AssessmentAttemptKind) domain.AssessmentAttemptPublicSnapshot {
return domain.AssessmentAttemptPublicSnapshot{
ID: domain.AssessmentAttemptID(uuid.New()), Kind: kind,
CurrentItem: &domain.AssessmentAttemptPublicItem{
ID: uuid.New(), Sequence: 1, Prompt: watermarkTestPrompt,
Content: domain.AssessmentAttemptPublicItemContent{Format: "number"},
},
}
}
func TestPresentMarksRealAttemptsOnlyAndLeavesTheStoredSnapshotAlone(t *testing.T) {
watermarker, err := NewWatermarker(hashedSeeds{})
if err != nil {
t.Fatalf("NewWatermarker() error = %v", err)
}
for _, kind := range []domain.AssessmentAttemptKind{domain.AssessmentAttemptKindRoot, domain.AssessmentAttemptKindCorrective} {
stored := presentedSnapshot(kind)
presented, err := watermarker.Present(stored)
if err != nil {
t.Fatalf("Present(%s) error = %v", kind, err)
}
if presented.Watermark == nil || len(presented.Watermark.Code) != 11 {
t.Fatalf("Present(%s) watermark = %+v, want the visible code", kind, presented.Watermark)
}
if presented.CurrentItem.Prompt == watermarkTestPrompt || domain.CanonicalAssessmentText(presented.CurrentItem.Prompt) != domain.CanonicalAssessmentText(watermarkTestPrompt) {
t.Fatalf("Present(%s) prompt = %q, want the same statement with a mark", kind, presented.CurrentItem.Prompt)
}
if stored.CurrentItem.Prompt != watermarkTestPrompt || stored.Watermark != nil {
t.Fatalf("Present(%s) changed the stored snapshot", kind)
}
if again, _ := watermarker.Present(stored); again.CurrentItem.Prompt != presented.CurrentItem.Prompt || again.Watermark.Code != presented.Watermark.Code {
t.Fatalf("Present(%s) is not repeatable", kind)
}
}
training := presentedSnapshot(domain.AssessmentAttemptKindDemoExpress)
if got, err := watermarker.Present(training); err != nil || got.Watermark != nil || got.CurrentItem.Prompt != watermarkTestPrompt {
t.Fatalf("Present(training) = %+v, %v, want the unchanged snapshot", got, err)
}
}
func TestTwoAttemptsGetTheSameStatementWithTheirOwnMark(t *testing.T) {
watermarker, err := NewWatermarker(hashedSeeds{})
if err != nil {
t.Fatalf("NewWatermarker() error = %v", err)
}
first, _ := watermarker.Present(presentedSnapshot(domain.AssessmentAttemptKindRoot))
second, _ := watermarker.Present(presentedSnapshot(domain.AssessmentAttemptKindRoot))
if first.Watermark.Code == second.Watermark.Code || first.CurrentItem.Prompt == second.CurrentItem.Prompt {
t.Fatal("two attempts got the same code or the same marked statement")
}
if domain.CanonicalAssessmentText(first.CurrentItem.Prompt) != domain.CanonicalAssessmentText(second.CurrentItem.Prompt) {
t.Fatal("the statements of two attempts differ beyond the mark")
}
// The code on the screen is the code of the invisible mark.
codes := domain.ExtractAssessmentWatermarkCodes(first.CurrentItem.Prompt)
if len(codes) == 0 || codes[0].String() != first.Watermark.Code {
t.Fatalf("invisible mark = %v, want the visible code %s", codes, first.Watermark.Code)
}
if strings.ContainsAny(first.Watermark.Code, "@ ") {
t.Fatalf("visible code %q holds more than a code", first.Watermark.Code)
}
}
func TestAnUnsetWatermarkerLeavesSnapshotsAsTheyAre(t *testing.T) {
var watermarker *Watermarker
stored := presentedSnapshot(domain.AssessmentAttemptKindRoot)
got, err := watermarker.Present(stored)
if err != nil || got.Watermark != nil || got.CurrentItem.Prompt != watermarkTestPrompt {
t.Fatalf("Present() on a nil Watermarker = %+v, %v, want the unchanged snapshot", got, err)
}
if _, err := NewWatermarker(nil); err == nil {
t.Fatal("NewWatermarker(nil) succeeded, want an error")
}
}
@@ -33,6 +33,7 @@ const (
labelSignalSession = "lincodex/assessment/signal-session/v1"
labelSignalNetwork = "lincodex/assessment/signal-network/v1"
labelResultCursor = "lincodex/assessment/result-history-cursor/v1"
labelWatermark = "lincodex/assessment/watermark/v1"
)
// Keyring computes the keyed digests of the anonymous identity operations:
@@ -53,6 +54,7 @@ type Keyring struct {
signalSessionKey []byte
signalNetworkKey []byte
resultCursorKey []byte
watermarkKey []byte
}
// NewKeyring derives the purpose keys from secret.
@@ -73,6 +75,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
signalSessionKey: derive(secret, labelSignalSession),
signalNetworkKey: derive(secret, labelSignalNetwork),
resultCursorKey: derive(secret, labelResultCursor),
watermarkKey: derive(secret, labelWatermark),
}, nil
}
@@ -229,3 +232,13 @@ func (keyring *Keyring) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey s
mac.Write([]byte(clientKey))
return domain.AssessmentDigest(mac.Sum(nil))
}
// AssessmentWatermarkSeed is the secret stream that marks the task text of one
// attempt. It is derived under a key of its own, so it cannot be computed from
// an idempotency scope or a digest, and it is never sent to a client: the
// visible code and the invisible mark are read from it on the server.
func (keyring *Keyring) AssessmentWatermarkSeed(attemptID uuid.UUID) domain.AssessmentWatermarkSeed {
mac := hmac.New(sha256.New, keyring.watermarkKey)
mac.Write(attemptID[:])
return domain.AssessmentWatermarkSeed(mac.Sum(nil))
}
@@ -125,6 +125,33 @@ func TestAssessmentSessionAndNetworkDigestsAreBoundToTheAttempt(t *testing.T) {
}
}
func TestAssessmentWatermarkSeedIsKeyedBoundToTheAttemptAndSeparateFromTheDigests(t *testing.T) {
keyring, err := NewKeyring(bytes.Repeat([]byte{1}, MinKeySecretBytes))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
other, err := NewKeyring(bytes.Repeat([]byte{2}, MinKeySecretBytes))
if err != nil {
t.Fatalf("NewKeyring(other secret) error = %v", err)
}
attempt, otherAttempt := uuid.New(), uuid.New()
seed := keyring.AssessmentWatermarkSeed(attempt)
if seed.IsZero() || seed != keyring.AssessmentWatermarkSeed(attempt) {
t.Fatal("the watermark seed is empty or not deterministic")
}
if seed == keyring.AssessmentWatermarkSeed(otherAttempt) {
t.Fatal("two attempts have the same watermark seed")
}
if seed == other.AssessmentWatermarkSeed(attempt) {
t.Fatal("the watermark seed does not depend on the server secret, so it could be computed by anyone")
}
// The purpose key is its own: no other digest of the attempt equals the seed.
if seed == domain.AssessmentWatermarkSeed(keyring.AssessmentSessionDigest(attempt, attempt)) ||
seed == domain.AssessmentWatermarkSeed(keyring.AssessmentNetworkDigest(attempt, string(attempt[:]))) {
t.Fatal("the watermark seed shares a key with another assessment digest")
}
}
func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t *testing.T) {
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
if err != nil {