feat(assessment): keep real attempts in fullscreen and protect the task text
This commit is contained in:
1 parent
56dcf32f8c
commit
efa41d5967
46 files changed
+1940
-72
No files matched your search
@@ -122,7 +122,7 @@ The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` ac
|
||||
|
||||
The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata: a timestamp outside five minutes before the attempt's creation to five minutes after database time rejects the whole batch with 400, so the client moves its timestamps to server time using the `Date` header; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Interpretation of these signals is separate work.
|
||||
|
||||
The notice about the collected signals is stored separately. `GET` and `PUT /api/v1/me/assessment-signal-notice` read and write the candidate's acknowledgement of a text version (`usecase/assessment/signal_notice.go`, table `assessment_signal_notice_acknowledgements`, migration 34). The server sets the text version; a `PUT` with another version answers 409 and stores nothing, and a repeat keeps the time of the first acknowledgement. The acknowledgement is not a consent: the signal operation does not read it and still requires current C3, so the notice cannot be used to hide a consent. Attempt creation does not check the acknowledgement on the server; the candidate screen enforces the requirement. Rows are deleted by cascade with the user.
|
||||
The notice about the collected signals is stored separately. `GET` and `PUT /api/v1/me/assessment-signal-notice` read and write the candidate's acknowledgement of a text version (`usecase/assessment/signal_notice.go`, table `assessment_signal_notice_acknowledgements`, migration 34). The server sets the text version (`CurrentSignalNoticeVersion`, now 2: version 2 added the measures the page applies during an attempt to the signal list); an acknowledgement is stored per version, so one given for version 1 stays stored but never counts for version 2 and a new text needs no migration. A `PUT` with another version answers 409 and stores nothing, and a repeat keeps the time of the first acknowledgement. The acknowledgement is not a consent: the signal operation does not read it and still requires current C3, so the notice cannot be used to hide a consent. Attempt creation does not check the acknowledgement on the server; the candidate screen enforces the requirement. Rows are deleted by cascade with the user.
|
||||
|
||||
## Anonymous profile projection
|
||||
|
||||
|
||||
+1
-1
@@ -122,7 +122,7 @@
|
||||
|
||||
Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными: метка вне окна от создания попытки минус пять минут до времени БД плюс пять минут отклоняет весь пакет с 400, поэтому клиент приводит метки к серверному времени по заголовку `Date`; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Интерпретация сигналов относится к отдельной работе.
|
||||
|
||||
Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер; `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем.
|
||||
Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер (`CurrentSignalNoticeVersion`, сейчас 2: версия 2 добавила к перечню сигналов меры, которые страница применяет во время попытки); подтверждение хранится для каждой версии отдельно, поэтому данное для версии 1 остается в таблице, но для версии 2 не засчитывается, а новый текст не требует миграции. `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем.
|
||||
|
||||
## Анонимная проекция профиля
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
|
||||
requireSessionProblem(t, anonymous, http.StatusUnauthorized, "unauthenticated")
|
||||
|
||||
before := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, ""))
|
||||
if before.NoticeVersion != 1 || before.Acknowledged || before.AcknowledgedAt != nil {
|
||||
if before.NoticeVersion != 2 || before.Acknowledged || before.AcknowledgedAt != nil {
|
||||
t.Fatalf("notice before acknowledgement = %+v", before)
|
||||
}
|
||||
|
||||
@@ -77,18 +77,21 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
|
||||
if rejected := request(http.MethodPut, `{"notice_version":1,"accepted":true}`, sessionHTTPTestOrigin, cookie.Value, csrf); rejected.Code != http.StatusBadRequest {
|
||||
t.Fatalf("unknown field = %d %s, want 400", rejected.Code, rejected.Body.String())
|
||||
}
|
||||
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf),
|
||||
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":3}`, sessionHTTPTestOrigin, cookie.Value, csrf),
|
||||
http.StatusConflict, "state_conflict")
|
||||
// The previous version is no longer the one the server requires.
|
||||
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf),
|
||||
http.StatusConflict, "state_conflict")
|
||||
if untouched := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, "")); untouched.Acknowledged {
|
||||
t.Fatalf("a refused request stored an acknowledgement: %+v", untouched)
|
||||
}
|
||||
|
||||
first := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf))
|
||||
if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != 1 {
|
||||
first := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf))
|
||||
if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != 2 {
|
||||
t.Fatalf("first acknowledgement = %+v", first)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
repeat := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf))
|
||||
repeat := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf))
|
||||
if repeat.AcknowledgedAt == nil || *repeat.AcknowledgedAt != *first.AcknowledgedAt {
|
||||
t.Fatalf("a repeat changed the first acknowledgement time: first %+v, repeat %+v", first, repeat)
|
||||
}
|
||||
@@ -101,12 +104,16 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_notice_acknowledgements WHERE user_id = $1", candidate.ID).Scan(&rows); err != nil || rows != 1 {
|
||||
t.Fatalf("stored acknowledgement rows = %d, error %v, want exactly one", rows, err)
|
||||
}
|
||||
// An acknowledgement of version 1 stays stored but does not count for version 2.
|
||||
if _, err := harness.pool.Exec(ctx, "INSERT INTO assessment_signal_notice_acknowledgements (user_id, notice_version, acknowledged_at) VALUES ($1, 1, now())", other.ID); err != nil {
|
||||
t.Fatalf("store a version 1 acknowledgement: %v", err)
|
||||
}
|
||||
if foreign := decodeSignalNotice(t, request(http.MethodGet, "", "", otherCookie.Value, "")); foreign.Acknowledged {
|
||||
t.Fatalf("another account inherited the acknowledgement: %+v", foreign)
|
||||
}
|
||||
|
||||
requireSessionProblem(t, request(http.MethodGet, "", "", employerCookie.Value, ""), http.StatusForbidden, "forbidden")
|
||||
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, employerCookie.Value, employerCSRF),
|
||||
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, employerCookie.Value, employerCSRF),
|
||||
http.StatusForbidden, "forbidden")
|
||||
|
||||
// The acknowledgement is a record, not a consent: it creates no ledger row.
|
||||
|
||||
@@ -4495,13 +4495,20 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped
|
||||
// address during the attempt, parallel sessions, and the comparison of answers to variants of the same
|
||||
// task by candidates. The server stores for these only one-way keyed digests: it stores no network
|
||||
// address, no session token, and no answer text. Client signals are stored only while the C3 consent
|
||||
// is current. The client shows it before a real attempt starts and does not start the attempt until
|
||||
// the notice is acknowledged.
|
||||
// is current. The notice also lists the measures that the page applies during a real attempt:
|
||||
// fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window,
|
||||
// blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste
|
||||
// into answer fields (paste into the practice code editor is allowed and recorded as a signal with a
|
||||
// size only). A watermark on the task page is announced as planned. These measures are applied by the
|
||||
// client and never change a score, a category, or a quota. The client shows the notice before a real
|
||||
// attempt starts and does not start the attempt until the notice is acknowledged.
|
||||
//
|
||||
// The acknowledgement is stored on the server per account and notice version, so it survives a reload
|
||||
// and a new browser. It is not a consent and never changes C3: the signal operation still requires a
|
||||
// current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express
|
||||
// training mode collects no signals and needs no acknowledgement.
|
||||
// and a new browser. An acknowledgement of an earlier version never counts for the current one: when
|
||||
// the text gains a version, every candidate acknowledges it again. It is not a consent and never
|
||||
// changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice
|
||||
// does not make that operation fail. The demo_express training mode collects no signals and needs no
|
||||
// acknowledgement.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or
|
||||
// an unconfirmed email answers 403 forbidden.
|
||||
|
||||
@@ -663,13 +663,20 @@ type Handler interface {
|
||||
// address during the attempt, parallel sessions, and the comparison of answers to variants of the same
|
||||
// task by candidates. The server stores for these only one-way keyed digests: it stores no network
|
||||
// address, no session token, and no answer text. Client signals are stored only while the C3 consent
|
||||
// is current. The client shows it before a real attempt starts and does not start the attempt until
|
||||
// the notice is acknowledged.
|
||||
// is current. The notice also lists the measures that the page applies during a real attempt:
|
||||
// fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window,
|
||||
// blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste
|
||||
// into answer fields (paste into the practice code editor is allowed and recorded as a signal with a
|
||||
// size only). A watermark on the task page is announced as planned. These measures are applied by the
|
||||
// client and never change a score, a category, or a quota. The client shows the notice before a real
|
||||
// attempt starts and does not start the attempt until the notice is acknowledged.
|
||||
//
|
||||
// The acknowledgement is stored on the server per account and notice version, so it survives a reload
|
||||
// and a new browser. It is not a consent and never changes C3: the signal operation still requires a
|
||||
// current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express
|
||||
// training mode collects no signals and needs no acknowledgement.
|
||||
// and a new browser. An acknowledgement of an earlier version never counts for the current one: when
|
||||
// the text gains a version, every candidate acknowledges it again. It is not a consent and never
|
||||
// changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice
|
||||
// does not make that operation fail. The demo_express training mode collects no signals and needs no
|
||||
// acknowledgement.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or
|
||||
// an unconfirmed email answers 403 forbidden.
|
||||
|
||||
@@ -725,13 +725,20 @@ func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params Ge
|
||||
// address during the attempt, parallel sessions, and the comparison of answers to variants of the same
|
||||
// task by candidates. The server stores for these only one-way keyed digests: it stores no network
|
||||
// address, no session token, and no answer text. Client signals are stored only while the C3 consent
|
||||
// is current. The client shows it before a real attempt starts and does not start the attempt until
|
||||
// the notice is acknowledged.
|
||||
// is current. The notice also lists the measures that the page applies during a real attempt:
|
||||
// fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window,
|
||||
// blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste
|
||||
// into answer fields (paste into the practice code editor is allowed and recorded as a signal with a
|
||||
// size only). A watermark on the task page is announced as planned. These measures are applied by the
|
||||
// client and never change a score, a category, or a quota. The client shows the notice before a real
|
||||
// attempt starts and does not start the attempt until the notice is acknowledged.
|
||||
//
|
||||
// The acknowledgement is stored on the server per account and notice version, so it survives a reload
|
||||
// and a new browser. It is not a consent and never changes C3: the signal operation still requires a
|
||||
// current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express
|
||||
// training mode collects no signals and needs no acknowledgement.
|
||||
// and a new browser. An acknowledgement of an earlier version never counts for the current one: when
|
||||
// the text gains a version, every candidate acknowledges it again. It is not a consent and never
|
||||
// changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice
|
||||
// does not make that operation fail. The demo_express training mode collects no signals and needs no
|
||||
// acknowledgement.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or
|
||||
// an unconfirmed email answers 403 forbidden.
|
||||
|
||||
@@ -12,9 +12,14 @@ import (
|
||||
)
|
||||
|
||||
// CurrentSignalNoticeVersion is the version of the notice text that lists the
|
||||
// collected assessment signals. Change it together with the client text so that
|
||||
// every candidate acknowledges the new wording.
|
||||
const CurrentSignalNoticeVersion int32 = 1
|
||||
// collected assessment signals and the measures the page applies during an
|
||||
// attempt (fullscreen, hiding the task when the candidate leaves, copy, print,
|
||||
// and paste restrictions). Change it together with the client text so that
|
||||
// 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
|
||||
|
||||
// ErrSignalNoticeVersionMismatch reports an acknowledgement for a notice
|
||||
// version other than the one the server requires.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestAcknowledgeSignalNoticeRefusesEveryVersionButTheCurrentOne(t *testing.T) {
|
||||
// A refused version returns before the service touches storage, so an
|
||||
// acknowledgement of an earlier notice text can never count for this one.
|
||||
service := &SignalService{}
|
||||
for _, version := range []int32{CurrentSignalNoticeVersion - 1, CurrentSignalNoticeVersion + 1} {
|
||||
_, err := service.AcknowledgeSignalNotice(context.Background(), uuid.New(), version)
|
||||
if !errors.Is(err, ErrSignalNoticeVersionMismatch) {
|
||||
t.Fatalf("AcknowledgeSignalNotice(version %d) error = %v, want %v", version, err, ErrSignalNoticeVersionMismatch)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user