feat(consent): add versioned append-only consent ledger C1-C5

This commit is contained in:
shira committed 2026-10-06 14:52:33 +03:00
1 parent 008254e44a
commit de49f93b0b
64 files changed
+9244 -132

No files matched your search

@@ -5223,6 +5223,237 @@ func (s *Server) handleGetSpecializationCatalogRequest(args [0]string, argsEscap
}
}
// handleListMyConsentsRequest handles ListMyConsents operation.
//
// Requires the session cookie of a candidate or an employer account. The subject comes from the
// session, never from a request parameter, so the response holds only the caller's own consents: no
// request can name another account, and records of other accounts are never listed. Returns a page of
// the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with
// cursor pagination.
//
// The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the
// source, and the grant time; the server also stores the hash of exactly the text the subject saw. A
// newer text version of the same purpose is a new record, and the earlier one becomes `superseded`
// without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one
// organization, once; a later grant is a new record. Purposes are independent.
//
// Without `state` the page lists the whole history; `state=active` lists the consents that hold now,
// one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the
// organization with the name its consent text showed (a snapshot that a later rename does not change),
// the selected contact fields, and the invitation with its terms version; it never carries a contact
// value. A c2 record proves the consent to the publication text; the published field set and its
// changes are evidence of the publication history (TASK-088).
//
// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations
// of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed
// `limit`, `cursor`, or `state` answers 400 validation_failed.
//
// GET /api/v1/me/consents
func (s *Server) handleListMyConsentsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListMyConsents"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/consents"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyConsentsOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ListMyConsentsOperation,
ID: "ListMyConsents",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListMyConsentsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeListMyConsentsParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response ListMyConsentsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListMyConsentsOperation,
OperationSummary: "List the consents of the current account with their history.",
OperationID: "ListMyConsents",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "state",
In: "query",
}: params.State,
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListMyConsentsParams
Response = ListMyConsentsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListMyConsentsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListMyConsents(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListMyConsents(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeListMyConsentsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMyInvitationsRequest handles ListMyInvitations operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -85,6 +85,10 @@ type GetOrganizationNeedRes interface {
getOrganizationNeedRes()
}
type ListMyConsentsRes interface {
listMyConsentsRes()
}
type ListMyInvitationsRes interface {
listMyInvitationsRes()
}
@@ -7165,6 +7165,119 @@ func (s *ConfirmEmailForbidden) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ConsentOrganization) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ConsentOrganization) encodeFields(e *jx.Encoder) {
{
e.FieldStart("id")
json.EncodeUUID(e, s.ID)
}
{
e.FieldStart("name")
e.Str(s.Name)
}
}
var jsonFieldsNameOfConsentOrganization = [2]string{
0: "id",
1: "name",
}
// Decode decodes ConsentOrganization from json.
func (s *ConsentOrganization) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentOrganization to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "id":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := json.DecodeUUID(d)
s.ID = v
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"id\"")
}
case "name":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Str()
s.Name = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"name\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ConsentOrganization")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000011,
} {
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(jsonFieldsNameOfConsentOrganization) {
name = jsonFieldsNameOfConsentOrganization[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 *ConsentOrganization) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentOrganization) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConsentPurpose as json.
func (s ConsentPurpose) Encode(e *jx.Encoder) {
e.Str(string(s))
@@ -7203,6 +7316,582 @@ func (s *ConsentPurpose) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes ConsentPurposeCode as json.
func (s ConsentPurposeCode) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ConsentPurposeCode from json.
func (s *ConsentPurposeCode) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentPurposeCode to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ConsentPurposeCode(v) {
case ConsentPurposeCodeC1:
*s = ConsentPurposeCodeC1
case ConsentPurposeCodeC2:
*s = ConsentPurposeCodeC2
case ConsentPurposeCodeC3:
*s = ConsentPurposeCodeC3
case ConsentPurposeCodeC4:
*s = ConsentPurposeCodeC4
case ConsentPurposeCodeC5:
*s = ConsentPurposeCodeC5
default:
*s = ConsentPurposeCode(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s ConsentPurposeCode) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentPurposeCode) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ConsentRecord) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ConsentRecord) encodeFields(e *jx.Encoder) {
{
e.FieldStart("id")
json.EncodeUUID(e, s.ID)
}
{
e.FieldStart("purpose")
s.Purpose.Encode(e)
}
{
e.FieldStart("state")
s.State.Encode(e)
}
{
e.FieldStart("text_version")
s.TextVersion.Encode(e)
}
{
e.FieldStart("source")
s.Source.Encode(e)
}
{
e.FieldStart("granted_at")
s.GrantedAt.Encode(e)
}
{
e.FieldStart("revoked_at")
s.RevokedAt.Encode(e)
}
{
e.FieldStart("revocation_source")
s.RevocationSource.Encode(e)
}
{
e.FieldStart("organization")
s.Organization.Encode(e)
}
{
e.FieldStart("fields")
if s.Fields == nil {
e.Null()
} else {
e.ArrStart()
for _, elem := range s.Fields {
elem.Encode(e)
}
e.ArrEnd()
}
}
{
e.FieldStart("invitation_id")
s.InvitationID.Encode(e)
}
{
e.FieldStart("invitation_terms_version")
s.InvitationTermsVersion.Encode(e)
}
}
var jsonFieldsNameOfConsentRecord = [12]string{
0: "id",
1: "purpose",
2: "state",
3: "text_version",
4: "source",
5: "granted_at",
6: "revoked_at",
7: "revocation_source",
8: "organization",
9: "fields",
10: "invitation_id",
11: "invitation_terms_version",
}
// Decode decodes ConsentRecord from json.
func (s *ConsentRecord) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentRecord to nil")
}
var requiredBitSet [2]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "id":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := json.DecodeUUID(d)
s.ID = v
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"id\"")
}
case "purpose":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.Purpose.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"purpose\"")
}
case "state":
requiredBitSet[0] |= 1 << 2
if err := func() error {
if err := s.State.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"state\"")
}
case "text_version":
requiredBitSet[0] |= 1 << 3
if err := func() error {
if err := s.TextVersion.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"text_version\"")
}
case "source":
requiredBitSet[0] |= 1 << 4
if err := func() error {
if err := s.Source.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"source\"")
}
case "granted_at":
requiredBitSet[0] |= 1 << 5
if err := func() error {
if err := s.GrantedAt.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"granted_at\"")
}
case "revoked_at":
requiredBitSet[0] |= 1 << 6
if err := func() error {
if err := s.RevokedAt.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"revoked_at\"")
}
case "revocation_source":
requiredBitSet[0] |= 1 << 7
if err := func() error {
if err := s.RevocationSource.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"revocation_source\"")
}
case "organization":
requiredBitSet[1] |= 1 << 0
if err := func() error {
if err := s.Organization.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"organization\"")
}
case "fields":
requiredBitSet[1] |= 1 << 1
if err := func() error {
switch tt := d.Next(); tt {
case jx.Null:
if err := d.Skip(); err != nil {
return err
}
default:
s.Fields = make([]ContactFieldKind, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem ContactFieldKind
if err := elem.Decode(d); err != nil {
return err
}
s.Fields = append(s.Fields, elem)
return nil
}); err != nil {
return err
}
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"fields\"")
}
case "invitation_id":
requiredBitSet[1] |= 1 << 2
if err := func() error {
if err := s.InvitationID.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"invitation_id\"")
}
case "invitation_terms_version":
requiredBitSet[1] |= 1 << 3
if err := func() error {
if err := s.InvitationTermsVersion.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"invitation_terms_version\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ConsentRecord")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [2]uint8{
0b11111111,
0b00001111,
} {
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(jsonFieldsNameOfConsentRecord) {
name = jsonFieldsNameOfConsentRecord[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 *ConsentRecord) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentRecord) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ConsentRecordList) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ConsentRecordList) encodeFields(e *jx.Encoder) {
{
e.FieldStart("items")
e.ArrStart()
for _, elem := range s.Items {
elem.Encode(e)
}
e.ArrEnd()
}
{
e.FieldStart("page")
s.Page.Encode(e)
}
}
var jsonFieldsNameOfConsentRecordList = [2]string{
0: "items",
1: "page",
}
// Decode decodes ConsentRecordList from json.
func (s *ConsentRecordList) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentRecordList to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "items":
requiredBitSet[0] |= 1 << 0
if err := func() error {
s.Items = make([]ConsentRecord, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem ConsentRecord
if err := elem.Decode(d); err != nil {
return err
}
s.Items = append(s.Items, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"items\"")
}
case "page":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.Page.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"page\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ConsentRecordList")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000011,
} {
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(jsonFieldsNameOfConsentRecordList) {
name = jsonFieldsNameOfConsentRecordList[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 *ConsentRecordList) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentRecordList) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConsentRevocationSource as json.
func (s ConsentRevocationSource) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ConsentRevocationSource from json.
func (s *ConsentRevocationSource) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentRevocationSource to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ConsentRevocationSource(v) {
case ConsentRevocationSourceConsentSettings:
*s = ConsentRevocationSourceConsentSettings
case ConsentRevocationSourceSupportRequest:
*s = ConsentRevocationSourceSupportRequest
default:
*s = ConsentRevocationSource(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s ConsentRevocationSource) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentRevocationSource) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConsentSource as json.
func (s ConsentSource) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ConsentSource from json.
func (s *ConsentSource) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentSource to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ConsentSource(v) {
case ConsentSourceRegistration:
*s = ConsentSourceRegistration
case ConsentSourceConsentSettings:
*s = ConsentSourceConsentSettings
case ConsentSourceInvitationAcceptance:
*s = ConsentSourceInvitationAcceptance
default:
*s = ConsentSource(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s ConsentSource) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentSource) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConsentState as json.
func (s ConsentState) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ConsentState from json.
func (s *ConsentState) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentState to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ConsentState(v) {
case ConsentStateActive:
*s = ConsentStateActive
case ConsentStateSuperseded:
*s = ConsentStateSuperseded
case ConsentStateRevoked:
*s = ConsentStateRevoked
default:
*s = ConsentState(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s ConsentState) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentState) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ConsentText) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -15058,6 +15747,82 @@ func (s *ItemContent) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes ListMyConsentsBadRequest as json.
func (s *ListMyConsentsBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ListMyConsentsBadRequest from json.
func (s *ListMyConsentsBadRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ListMyConsentsBadRequest to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = ListMyConsentsBadRequest(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ListMyConsentsBadRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ListMyConsentsBadRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ListMyConsentsUnauthorized as json.
func (s *ListMyConsentsUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ListMyConsentsUnauthorized from json.
func (s *ListMyConsentsUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ListMyConsentsUnauthorized to nil")
}
var unwrapped Problem
if err := func() error {
if err := unwrapped.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
}
*s = ListMyConsentsUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ListMyConsentsUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ListMyConsentsUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ListMyInvitationsBadRequest as json.
func (s *ListMyInvitationsBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
@@ -21368,6 +22133,94 @@ func (s *NilCandidateExperience) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes ConsentOrganization as json.
func (o NilConsentOrganization) Encode(e *jx.Encoder) {
if o.Null {
e.Null()
return
}
o.Value.Encode(e)
}
// Decode decodes ConsentOrganization from json.
func (o *NilConsentOrganization) Decode(d *jx.Decoder) error {
if o == nil {
return errors.New("invalid: unable to decode NilConsentOrganization to nil")
}
if d.Next() == jx.Null {
if err := d.Null(); err != nil {
return err
}
var v ConsentOrganization
o.Value = v
o.Null = true
return nil
}
o.Null = false
if err := o.Value.Decode(d); err != nil {
return err
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s NilConsentOrganization) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *NilConsentOrganization) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConsentRevocationSource as json.
func (o NilConsentRevocationSource) Encode(e *jx.Encoder) {
if o.Null {
e.Null()
return
}
e.Str(string(o.Value))
}
// Decode decodes ConsentRevocationSource from json.
func (o *NilConsentRevocationSource) Decode(d *jx.Decoder) error {
if o == nil {
return errors.New("invalid: unable to decode NilConsentRevocationSource to nil")
}
if d.Next() == jx.Null {
if err := d.Null(); err != nil {
return err
}
var v ConsentRevocationSource
o.Value = v
o.Null = true
return nil
}
o.Null = false
if err := o.Value.Decode(d); err != nil {
return err
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s NilConsentRevocationSource) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *NilConsentRevocationSource) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ContactAccessBlock as json.
func (o NilContactAccessBlock) Encode(e *jx.Encoder) {
if o.Null {
@@ -22076,6 +22929,50 @@ func (s *NilInvitationNeedReference) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes InvitationTermsVersion as json.
func (o NilInvitationTermsVersion) Encode(e *jx.Encoder) {
if o.Null {
e.Null()
return
}
o.Value.Encode(e)
}
// Decode decodes InvitationTermsVersion from json.
func (o *NilInvitationTermsVersion) Decode(d *jx.Decoder) error {
if o == nil {
return errors.New("invalid: unable to decode NilInvitationTermsVersion to nil")
}
if d.Next() == jx.Null {
if err := d.Null(); err != nil {
return err
}
var v InvitationTermsVersion
o.Value = v
o.Null = true
return nil
}
o.Null = false
if err := o.Value.Decode(d); err != nil {
return err
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s NilInvitationTermsVersion) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *NilInvitationTermsVersion) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes NeedDomainName as json.
func (o NilNeedDomainName) Encode(e *jx.Encoder) {
if o.Null {
@@ -29,6 +29,7 @@ const (
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
ListMyConsentsOperation OperationName = "ListMyConsents"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
@@ -1819,6 +1819,249 @@ func decodeGetOrganizationNeedParams(args [2]string, argsEscaped bool, r *http.R
return params, nil
}
// ListMyConsentsParams is parameters of ListMyConsents operation.
type ListMyConsentsParams struct {
// Lists only the records in this state; omit it for the whole history.
State OptConsentState `json:",omitempty,omitzero"`
// Maximum number of items in the page. The server may return fewer items even when more remain; use
// `page.has_more` to detect the end.
Limit OptInt32 `json:",omitempty,omitzero"`
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
Cursor OptString `json:",omitempty,omitzero"`
}
func unpackListMyConsentsParams(packed middleware.Parameters) (params ListMyConsentsParams) {
{
key := middleware.ParameterKey{
Name: "state",
In: "query",
}
if v, ok := packed[key]; ok {
params.State = v.(OptConsentState)
}
}
{
key := middleware.ParameterKey{
Name: "limit",
In: "query",
}
if v, ok := packed[key]; ok {
params.Limit = v.(OptInt32)
}
}
{
key := middleware.ParameterKey{
Name: "cursor",
In: "query",
}
if v, ok := packed[key]; ok {
params.Cursor = v.(OptString)
}
}
return params
}
func decodeListMyConsentsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyConsentsParams, _ error) {
q := uri.NewQueryDecoder(r.URL.Query())
// Decode query: state.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "state",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotStateVal ConsentState
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotStateVal = ConsentState(c)
return nil
}(); err != nil {
return err
}
params.State.SetTo(paramsDotStateVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.State.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "state",
In: "query",
Err: err,
}
}
// Set default value for query: limit.
{
val := int32(20)
params.Limit.SetTo(val)
}
// Decode query: limit.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "limit",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotLimitVal int32
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt32(val)
if err != nil {
return err
}
paramsDotLimitVal = c
return nil
}(); err != nil {
return err
}
params.Limit.SetTo(paramsDotLimitVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Limit.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 100,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "limit",
In: "query",
Err: err,
}
}
// Decode query: cursor.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "cursor",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotCursorVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotCursorVal = c
return nil
}(); err != nil {
return err
}
params.Cursor.SetTo(paramsDotCursorVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Cursor.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 512,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "cursor",
In: "query",
Err: err,
}
}
return params, nil
}
// ListMyInvitationsParams is parameters of ListMyInvitations operation.
type ListMyInvitationsParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
@@ -2031,6 +2031,65 @@ func encodeGetSpecializationCatalogResponse(response *SpecializationCatalog, w h
return nil
}
func encodeListMyConsentsResponse(response ListMyConsentsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ConsentRecordListHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyConsentsBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyConsentsUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateInvitationListHeaders:
@@ -11,16 +11,16 @@ import (
)
var (
rn45AllowedHeaders = map[string]string{
rn46AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn7AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn43AllowedHeaders = map[string]string{
rn44AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn40AllowedHeaders = map[string]string{
rn41AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn24AllowedHeaders = map[string]string{
@@ -29,7 +29,7 @@ var (
rn9AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn48AllowedHeaders = map[string]string{
rn49AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn19AllowedHeaders = map[string]string{
@@ -44,7 +44,7 @@ var (
rn16AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn49AllowedHeaders = map[string]string{
rn50AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn30AllowedHeaders = map[string]string{
@@ -59,13 +59,13 @@ var (
rn34AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn42AllowedHeaders = map[string]string{
rn43AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn47AllowedHeaders = map[string]string{
rn48AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn50AllowedHeaders = map[string]string{
rn51AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn15AllowedHeaders = map[string]string{
@@ -228,7 +228,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn45AllowedHeaders,
allowedHeaders: rn46AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -305,7 +305,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn43AllowedHeaders,
allowedHeaders: rn44AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -329,7 +329,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn40AllowedHeaders,
allowedHeaders: rn41AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -482,7 +482,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn48AllowedHeaders,
allowedHeaders: rn49AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -578,6 +578,31 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
case 'c': // Prefix: "consents"
if l := len("consents"); len(elem) >= l && elem[0:l] == "consents" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleListMyConsentsRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 'i': // Prefix: "invitations"
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
@@ -748,7 +773,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn49AllowedHeaders,
allowedHeaders: rn50AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1031,7 +1056,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn42AllowedHeaders,
allowedHeaders: rn43AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1059,7 +1084,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn47AllowedHeaders,
allowedHeaders: rn48AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1089,7 +1114,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn50AllowedHeaders,
allowedHeaders: rn51AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1755,6 +1780,31 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
case 'c': // Prefix: "consents"
if l := len("consents"); len(elem) >= l && elem[0:l] == "consents" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = ListMyConsentsOperation
r.summary = "List the consents of the current account with their history."
r.operationID = "ListMyConsents"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/consents"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 'i': // Prefix: "invitations"
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
@@ -3353,6 +3353,39 @@ type ConfirmEmailForbidden Problem
func (*ConfirmEmailForbidden) confirmEmailRes() {}
// Organization of a c4 consent as the consent recorded it. `name` is a snapshot of the name that the
// shown consent text carried at the time of the consent, and the stored text hash proves that text
// with this name; a later rename of the organization does not change it, so it can differ from the
// current name.
// Ref: #/components/schemas/ConsentOrganization
type ConsentOrganization struct {
// Identifier of the organization.
ID uuid.UUID `json:"id"`
// Name of the organization in the consent text at the time of the consent. Plain text; clients show it
// as text, never as HTML.
Name string `json:"name"`
}
// GetID returns the value of ID.
func (s *ConsentOrganization) GetID() uuid.UUID {
return s.ID
}
// GetName returns the value of Name.
func (s *ConsentOrganization) GetName() string {
return s.Name
}
// SetID sets the value of ID.
func (s *ConsentOrganization) SetID(val uuid.UUID) {
s.ID = val
}
// SetName sets the value of Name.
func (s *ConsentOrganization) SetName(val string) {
s.Name = val
}
// Consent whose text the client may read before an account exists. Only the consents given at
// registration are listed: `c1` is the consent to the processing of personal data.
// Ref: #/components/schemas/ConsentPurpose
@@ -3390,6 +3423,452 @@ func (s *ConsentPurpose) UnmarshalText(data []byte) error {
}
}
// One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes
// another.
//
// - c1: processing of personal data, given at registration.
// - c2: publication of the candidate card. The record proves the consent to the published text; which
// fields were published and when is evidence of the publication history (TASK-088), not of this
// record. Adding a field scope to c2 records later is an additive change.
// - c3: automatic categorization. Without it the candidate can request a manual assessment by the
// same rubric.
// - c4: transfer of the selected contact data to one organization, currently given only in an
// invitation acceptance.
// - c5: import of FSP results.
//
// ConsentPurpose lists the subset whose text the client may read before an account exists.
// Ref: #/components/schemas/ConsentPurposeCode
type ConsentPurposeCode string
const (
ConsentPurposeCodeC1 ConsentPurposeCode = "c1"
ConsentPurposeCodeC2 ConsentPurposeCode = "c2"
ConsentPurposeCodeC3 ConsentPurposeCode = "c3"
ConsentPurposeCodeC4 ConsentPurposeCode = "c4"
ConsentPurposeCodeC5 ConsentPurposeCode = "c5"
)
// AllValues returns all ConsentPurposeCode values.
func (ConsentPurposeCode) AllValues() []ConsentPurposeCode {
return []ConsentPurposeCode{
ConsentPurposeCodeC1,
ConsentPurposeCodeC2,
ConsentPurposeCodeC3,
ConsentPurposeCodeC4,
ConsentPurposeCodeC5,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s ConsentPurposeCode) MarshalText() ([]byte, error) {
switch s {
case ConsentPurposeCodeC1:
return []byte(s), nil
case ConsentPurposeCodeC2:
return []byte(s), nil
case ConsentPurposeCodeC3:
return []byte(s), nil
case ConsentPurposeCodeC4:
return []byte(s), nil
case ConsentPurposeCodeC5:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *ConsentPurposeCode) UnmarshalText(data []byte) error {
switch ConsentPurposeCode(data) {
case ConsentPurposeCodeC1:
*s = ConsentPurposeCodeC1
return nil
case ConsentPurposeCodeC2:
*s = ConsentPurposeCodeC2
return nil
case ConsentPurposeCodeC3:
*s = ConsentPurposeCodeC3
return nil
case ConsentPurposeCodeC4:
*s = ConsentPurposeCodeC4
return nil
case ConsentPurposeCodeC5:
*s = ConsentPurposeCodeC5
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// One record of the consent ledger as its subject reads it: the purpose, the text version the subject
// accepted, where and when the consent was given, its state, and the revocation. A c4 record also
// names the organization, the contact fields, and the invitation with its terms version; these fields
// are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the
// subject saw, which a client never sends or receives.
// Ref: #/components/schemas/ConsentRecord
type ConsentRecord struct {
// Identifier of the record.
ID uuid.UUID `json:"id"`
Purpose ConsentPurposeCode `json:"purpose"`
State ConsentState `json:"state"`
// Version of the consent text that the subject accepted.
TextVersion ConsentTextVersion `json:"text_version"`
Source ConsentSource `json:"source"`
GrantedAt Timestamp `json:"granted_at"`
// Moment of the revocation, or null unless `state` is `revoked`.
RevokedAt NilTimestamp `json:"revoked_at"`
// Who recorded the revocation, or null unless `state` is `revoked`.
RevocationSource NilConsentRevocationSource `json:"revocation_source"`
// Organization that a c4 consent allows to read the fields, with the name the consent text showed, or
// null for every other purpose.
Organization NilConsentOrganization `json:"organization"`
// Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies
// another.
Fields []ContactFieldKind `json:"fields"`
// Invitation whose acceptance gave a c4 consent, or null for every other purpose.
InvitationID NilUUID `json:"invitation_id"`
// Terms version that the acceptance accepted, or null for every other purpose.
InvitationTermsVersion NilInvitationTermsVersion `json:"invitation_terms_version"`
}
// GetID returns the value of ID.
func (s *ConsentRecord) GetID() uuid.UUID {
return s.ID
}
// GetPurpose returns the value of Purpose.
func (s *ConsentRecord) GetPurpose() ConsentPurposeCode {
return s.Purpose
}
// GetState returns the value of State.
func (s *ConsentRecord) GetState() ConsentState {
return s.State
}
// GetTextVersion returns the value of TextVersion.
func (s *ConsentRecord) GetTextVersion() ConsentTextVersion {
return s.TextVersion
}
// GetSource returns the value of Source.
func (s *ConsentRecord) GetSource() ConsentSource {
return s.Source
}
// GetGrantedAt returns the value of GrantedAt.
func (s *ConsentRecord) GetGrantedAt() Timestamp {
return s.GrantedAt
}
// GetRevokedAt returns the value of RevokedAt.
func (s *ConsentRecord) GetRevokedAt() NilTimestamp {
return s.RevokedAt
}
// GetRevocationSource returns the value of RevocationSource.
func (s *ConsentRecord) GetRevocationSource() NilConsentRevocationSource {
return s.RevocationSource
}
// GetOrganization returns the value of Organization.
func (s *ConsentRecord) GetOrganization() NilConsentOrganization {
return s.Organization
}
// GetFields returns the value of Fields.
func (s *ConsentRecord) GetFields() []ContactFieldKind {
return s.Fields
}
// GetInvitationID returns the value of InvitationID.
func (s *ConsentRecord) GetInvitationID() NilUUID {
return s.InvitationID
}
// GetInvitationTermsVersion returns the value of InvitationTermsVersion.
func (s *ConsentRecord) GetInvitationTermsVersion() NilInvitationTermsVersion {
return s.InvitationTermsVersion
}
// SetID sets the value of ID.
func (s *ConsentRecord) SetID(val uuid.UUID) {
s.ID = val
}
// SetPurpose sets the value of Purpose.
func (s *ConsentRecord) SetPurpose(val ConsentPurposeCode) {
s.Purpose = val
}
// SetState sets the value of State.
func (s *ConsentRecord) SetState(val ConsentState) {
s.State = val
}
// SetTextVersion sets the value of TextVersion.
func (s *ConsentRecord) SetTextVersion(val ConsentTextVersion) {
s.TextVersion = val
}
// SetSource sets the value of Source.
func (s *ConsentRecord) SetSource(val ConsentSource) {
s.Source = val
}
// SetGrantedAt sets the value of GrantedAt.
func (s *ConsentRecord) SetGrantedAt(val Timestamp) {
s.GrantedAt = val
}
// SetRevokedAt sets the value of RevokedAt.
func (s *ConsentRecord) SetRevokedAt(val NilTimestamp) {
s.RevokedAt = val
}
// SetRevocationSource sets the value of RevocationSource.
func (s *ConsentRecord) SetRevocationSource(val NilConsentRevocationSource) {
s.RevocationSource = val
}
// SetOrganization sets the value of Organization.
func (s *ConsentRecord) SetOrganization(val NilConsentOrganization) {
s.Organization = val
}
// SetFields sets the value of Fields.
func (s *ConsentRecord) SetFields(val []ContactFieldKind) {
s.Fields = val
}
// SetInvitationID sets the value of InvitationID.
func (s *ConsentRecord) SetInvitationID(val NilUUID) {
s.InvitationID = val
}
// SetInvitationTermsVersion sets the value of InvitationTermsVersion.
func (s *ConsentRecord) SetInvitationTermsVersion(val NilInvitationTermsVersion) {
s.InvitationTermsVersion = val
}
// One page of the consent ledger of the current account, newest grant first.
// Ref: #/components/schemas/ConsentRecordList
type ConsentRecordList struct {
// Records of the page.
Items []ConsentRecord `json:"items"`
Page PageInfo `json:"page"`
}
// GetItems returns the value of Items.
func (s *ConsentRecordList) GetItems() []ConsentRecord {
return s.Items
}
// GetPage returns the value of Page.
func (s *ConsentRecordList) GetPage() PageInfo {
return s.Page
}
// SetItems sets the value of Items.
func (s *ConsentRecordList) SetItems(val []ConsentRecord) {
s.Items = val
}
// SetPage sets the value of Page.
func (s *ConsentRecordList) SetPage(val PageInfo) {
s.Page = val
}
// ConsentRecordListHeaders wraps ConsentRecordList with response headers.
type ConsentRecordListHeaders struct {
CacheControl CacheControlNoStore
Response ConsentRecordList
}
// GetCacheControl returns the value of CacheControl.
func (s *ConsentRecordListHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *ConsentRecordListHeaders) GetResponse() ConsentRecordList {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *ConsentRecordListHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *ConsentRecordListHeaders) SetResponse(val ConsentRecordList) {
s.Response = val
}
func (*ConsentRecordListHeaders) listMyConsentsRes() {}
// Who recorded a revocation.
//
// - consent_settings: the subject revoked the consent in the product.
// - support_request: an operator recorded a revocation that the subject requested through support.
//
// Ref: #/components/schemas/ConsentRevocationSource
type ConsentRevocationSource string
const (
ConsentRevocationSourceConsentSettings ConsentRevocationSource = "consent_settings"
ConsentRevocationSourceSupportRequest ConsentRevocationSource = "support_request"
)
// AllValues returns all ConsentRevocationSource values.
func (ConsentRevocationSource) AllValues() []ConsentRevocationSource {
return []ConsentRevocationSource{
ConsentRevocationSourceConsentSettings,
ConsentRevocationSourceSupportRequest,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s ConsentRevocationSource) MarshalText() ([]byte, error) {
switch s {
case ConsentRevocationSourceConsentSettings:
return []byte(s), nil
case ConsentRevocationSourceSupportRequest:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *ConsentRevocationSource) UnmarshalText(data []byte) error {
switch ConsentRevocationSource(data) {
case ConsentRevocationSourceConsentSettings:
*s = ConsentRevocationSourceConsentSettings
return nil
case ConsentRevocationSourceSupportRequest:
*s = ConsentRevocationSourceSupportRequest
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// Where the subject gave the consent.
//
// - registration: the c1 acceptance of RegisterAccount.
// - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063
// and TASK-064).
// - invitation_acceptance: the c4 acceptance of AcceptMyInvitation.
//
// A c4 given when sending an application (PRD Q9) is planned as an additional value.
// Ref: #/components/schemas/ConsentSource
type ConsentSource string
const (
ConsentSourceRegistration ConsentSource = "registration"
ConsentSourceConsentSettings ConsentSource = "consent_settings"
ConsentSourceInvitationAcceptance ConsentSource = "invitation_acceptance"
)
// AllValues returns all ConsentSource values.
func (ConsentSource) AllValues() []ConsentSource {
return []ConsentSource{
ConsentSourceRegistration,
ConsentSourceConsentSettings,
ConsentSourceInvitationAcceptance,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s ConsentSource) MarshalText() ([]byte, error) {
switch s {
case ConsentSourceRegistration:
return []byte(s), nil
case ConsentSourceConsentSettings:
return []byte(s), nil
case ConsentSourceInvitationAcceptance:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *ConsentSource) UnmarshalText(data []byte) error {
switch ConsentSource(data) {
case ConsentSourceRegistration:
*s = ConsentSourceRegistration
return nil
case ConsentSourceConsentSettings:
*s = ConsentSourceConsentSettings
return nil
case ConsentSourceInvitationAcceptance:
*s = ConsentSourceInvitationAcceptance
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// State of a consent record, computed from the ledger.
//
// - active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its
// purpose; every unrevoked c4 record is active, one per accepted invitation.
// - superseded: the subject later accepted another text version of the same purpose and has not
// revoked either. The record stays as evidence for its own time; it never applies to c4.
// - revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later
// grant is a new record and never reopens it.
//
// Ref: #/components/schemas/ConsentState
type ConsentState string
const (
ConsentStateActive ConsentState = "active"
ConsentStateSuperseded ConsentState = "superseded"
ConsentStateRevoked ConsentState = "revoked"
)
// AllValues returns all ConsentState values.
func (ConsentState) AllValues() []ConsentState {
return []ConsentState{
ConsentStateActive,
ConsentStateSuperseded,
ConsentStateRevoked,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s ConsentState) MarshalText() ([]byte, error) {
switch s {
case ConsentStateActive:
return []byte(s), nil
case ConsentStateSuperseded:
return []byte(s), nil
case ConsentStateRevoked:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *ConsentState) UnmarshalText(data []byte) error {
switch ConsentState(data) {
case ConsentStateActive:
*s = ConsentStateActive
return nil
case ConsentStateSuperseded:
*s = ConsentStateSuperseded
return nil
case ConsentStateRevoked:
*s = ConsentStateRevoked
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// Currently published consent text. The server stores an acceptance with `text_version` and the hash
// of exactly this text.
// Ref: #/components/schemas/ConsentText
@@ -6367,6 +6846,14 @@ func NewPracticeItemContentItemContent(v PracticeItemContent) ItemContent {
return s
}
type ListMyConsentsBadRequest Problem
func (*ListMyConsentsBadRequest) listMyConsentsRes() {}
type ListMyConsentsUnauthorized Problem
func (*ListMyConsentsUnauthorized) listMyConsentsRes() {}
type ListMyInvitationsBadRequest Problem
func (*ListMyInvitationsBadRequest) listMyInvitationsRes() {}
@@ -9105,6 +9592,96 @@ func (o NilCandidateExperience) Or(d CandidateExperience) CandidateExperience {
return d
}
// NewNilConsentOrganization returns new NilConsentOrganization with value set to v.
func NewNilConsentOrganization(v ConsentOrganization) NilConsentOrganization {
return NilConsentOrganization{
Value: v,
}
}
// NilConsentOrganization is nullable ConsentOrganization.
type NilConsentOrganization struct {
Value ConsentOrganization
Null bool
}
// SetTo sets value to v.
func (o *NilConsentOrganization) SetTo(v ConsentOrganization) {
o.Null = false
o.Value = v
}
// IsNull returns true if value is Null.
func (o NilConsentOrganization) IsNull() bool { return o.Null }
// SetToNull sets value to null.
func (o *NilConsentOrganization) SetToNull() {
o.Null = true
var v ConsentOrganization
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o NilConsentOrganization) Get() (v ConsentOrganization, ok bool) {
if o.Null {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o NilConsentOrganization) Or(d ConsentOrganization) ConsentOrganization {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewNilConsentRevocationSource returns new NilConsentRevocationSource with value set to v.
func NewNilConsentRevocationSource(v ConsentRevocationSource) NilConsentRevocationSource {
return NilConsentRevocationSource{
Value: v,
}
}
// NilConsentRevocationSource is nullable ConsentRevocationSource.
type NilConsentRevocationSource struct {
Value ConsentRevocationSource
Null bool
}
// SetTo sets value to v.
func (o *NilConsentRevocationSource) SetTo(v ConsentRevocationSource) {
o.Null = false
o.Value = v
}
// IsNull returns true if value is Null.
func (o NilConsentRevocationSource) IsNull() bool { return o.Null }
// SetToNull sets value to null.
func (o *NilConsentRevocationSource) SetToNull() {
o.Null = true
var v ConsentRevocationSource
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o NilConsentRevocationSource) Get() (v ConsentRevocationSource, ok bool) {
if o.Null {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o NilConsentRevocationSource) Or(d ConsentRevocationSource) ConsentRevocationSource {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewNilContactAccessBlock returns new NilContactAccessBlock with value set to v.
func NewNilContactAccessBlock(v ContactAccessBlock) NilContactAccessBlock {
return NilContactAccessBlock{
@@ -9825,6 +10402,51 @@ func (o NilInvitationNeedReference) Or(d InvitationNeedReference) InvitationNeed
return d
}
// NewNilInvitationTermsVersion returns new NilInvitationTermsVersion with value set to v.
func NewNilInvitationTermsVersion(v InvitationTermsVersion) NilInvitationTermsVersion {
return NilInvitationTermsVersion{
Value: v,
}
}
// NilInvitationTermsVersion is nullable InvitationTermsVersion.
type NilInvitationTermsVersion struct {
Value InvitationTermsVersion
Null bool
}
// SetTo sets value to v.
func (o *NilInvitationTermsVersion) SetTo(v InvitationTermsVersion) {
o.Null = false
o.Value = v
}
// IsNull returns true if value is Null.
func (o NilInvitationTermsVersion) IsNull() bool { return o.Null }
// SetToNull sets value to null.
func (o *NilInvitationTermsVersion) SetToNull() {
o.Null = true
var v InvitationTermsVersion
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o NilInvitationTermsVersion) Get() (v InvitationTermsVersion, ok bool) {
if o.Null {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o NilInvitationTermsVersion) Or(d InvitationTermsVersion) InvitationTermsVersion {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewNilNeedDomainName returns new NilNeedDomainName with value set to v.
func NewNilNeedDomainName(v NeedDomainName) NilNeedDomainName {
return NilNeedDomainName{
@@ -11114,6 +11736,52 @@ func (s *OnboardingStep) UnmarshalText(data []byte) error {
}
}
// NewOptConsentState returns new OptConsentState with value set to v.
func NewOptConsentState(v ConsentState) OptConsentState {
return OptConsentState{
Value: v,
Set: true,
}
}
// OptConsentState is optional ConsentState.
type OptConsentState struct {
Value ConsentState
Set bool
}
// IsSet returns true if OptConsentState was set.
func (o OptConsentState) IsSet() bool { return o.Set }
// Reset unsets value.
func (o *OptConsentState) Reset() {
var v ConsentState
o.Value = v
o.Set = false
}
// SetTo sets value to v.
func (o *OptConsentState) SetTo(v ConsentState) {
o.Set = true
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o OptConsentState) Get() (v ConsentState, 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 OptConsentState) Or(d ConsentState) ConsentState {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewOptInt32 returns new OptInt32 with value set to v.
func NewOptInt32(v int32) OptInt32 {
return OptInt32{
@@ -75,6 +75,7 @@ var operationRolesSessionCookie = map[string][]string{
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
ListMyConsentsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
@@ -718,6 +718,35 @@ type Handler interface {
//
// GET /api/v1/specializations
GetSpecializationCatalog(ctx context.Context) (*SpecializationCatalog, error)
// ListMyConsents implements ListMyConsents operation.
//
// Requires the session cookie of a candidate or an employer account. The subject comes from the
// session, never from a request parameter, so the response holds only the caller's own consents: no
// request can name another account, and records of other accounts are never listed. Returns a page of
// the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with
// cursor pagination.
//
// The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the
// source, and the grant time; the server also stores the hash of exactly the text the subject saw. A
// newer text version of the same purpose is a new record, and the earlier one becomes `superseded`
// without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one
// organization, once; a later grant is a new record. Purposes are independent.
//
// Without `state` the page lists the whole history; `state=active` lists the consents that hold now,
// one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the
// organization with the name its consent text showed (a snapshot that a later rename does not change),
// the selected contact fields, and the invitation with its terms version; it never carries a contact
// value. A c2 record proves the consent to the publication text; the published field set and its
// changes are evidence of the publication history (TASK-088).
//
// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations
// of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed
// `limit`, `cursor`, or `state` answers 400 validation_failed.
//
// GET /api/v1/me/consents
ListMyConsents(ctx context.Context, params ListMyConsentsParams) (ListMyConsentsRes, error)
// ListMyInvitations implements ListMyInvitations operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -792,6 +792,38 @@ func (UnimplementedHandler) GetSpecializationCatalog(ctx context.Context) (r *Sp
return r, ht.ErrNotImplemented
}
// ListMyConsents implements ListMyConsents operation.
//
// Requires the session cookie of a candidate or an employer account. The subject comes from the
// session, never from a request parameter, so the response holds only the caller's own consents: no
// request can name another account, and records of other accounts are never listed. Returns a page of
// the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with
// cursor pagination.
//
// The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the
// source, and the grant time; the server also stores the hash of exactly the text the subject saw. A
// newer text version of the same purpose is a new record, and the earlier one becomes `superseded`
// without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one
// organization, once; a later grant is a new record. Purposes are independent.
//
// Without `state` the page lists the whole history; `state=active` lists the consents that hold now,
// one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the
// organization with the name its consent text showed (a snapshot that a later rename does not change),
// the selected contact fields, and the invitation with its terms version; it never carries a contact
// value. A c2 record proves the consent to the publication text; the published field set and its
// changes are evidence of the publication history (TASK-088).
//
// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations
// of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed
// `limit`, `cursor`, or `state` answers 400 validation_failed.
//
// GET /api/v1/me/consents
func (UnimplementedHandler) ListMyConsents(ctx context.Context, params ListMyConsentsParams) (r ListMyConsentsRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMyInvitations implements ListMyInvitations operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -3405,6 +3405,41 @@ func (s *ConfirmEmailForbidden) Validate() error {
return nil
}
func (s *ConsentOrganization) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 200,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Name)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "name",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ConsentPurpose) Validate() error {
switch s {
case "c1":
@@ -3414,6 +3449,302 @@ func (s ConsentPurpose) Validate() error {
}
}
func (s ConsentPurposeCode) Validate() error {
switch s {
case "c1":
return nil
case "c2":
return nil
case "c3":
return nil
case "c4":
return nil
case "c5":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *ConsentRecord) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Purpose.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "purpose",
Error: err,
})
}
if err := func() error {
if err := s.State.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "state",
Error: err,
})
}
if err := func() error {
if err := s.TextVersion.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "text_version",
Error: err,
})
}
if err := func() error {
if err := s.Source.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "source",
Error: err,
})
}
if err := func() error {
if value, ok := s.RevocationSource.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: "revocation_source",
Error: err,
})
}
if err := func() error {
if value, ok := s.Organization.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: "organization",
Error: err,
})
}
if err := func() error {
if s.Fields == nil {
return nil // null
}
if err := (validate.Array{
MinLength: 1,
MinLengthSet: true,
MaxLength: 4,
MaxLengthSet: true,
}).ValidateLength(len(s.Fields)); err != nil {
return errors.Wrap(err, "array")
}
if err := validate.UniqueItems(s.Fields); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Fields {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "fields",
Error: err,
})
}
if err := func() error {
if value, ok := s.InvitationTermsVersion.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: "invitation_terms_version",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ConsentRecordList) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if s.Items == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 100,
MaxLengthSet: true,
}).ValidateLength(len(s.Items)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Items {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "items",
Error: err,
})
}
if err := func() error {
if err := s.Page.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "page",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ConsentRecordListHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ConsentRevocationSource) Validate() error {
switch s {
case "consent_settings":
return nil
case "support_request":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s ConsentSource) Validate() error {
switch s {
case "registration":
return nil
case "consent_settings":
return nil
case "invitation_acceptance":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s ConsentState) Validate() error {
switch s {
case "active":
return nil
case "superseded":
return nil
case "revoked":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *ConsentText) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -6139,6 +6470,22 @@ func (s ItemContent) Validate() error {
}
}
func (s *ListMyConsentsBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyConsentsUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyInvitationsBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -9,6 +9,7 @@ import (
"log/slog"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
@@ -1884,6 +1885,94 @@ func TestInvitationDTOsCarryNoContactOrMinimum(t *testing.T) {
}
}
// myConsentsPath is the consent ledger of the session account.
const myConsentsPath = "/api/v1/me/consents"
// The schema alone must accept the read of the own ledger with an optional
// state filter and reject an unknown state and malformed page parameters.
// Security accepts the session here, so the request reaches validation; a
// valid request then answers 501 until the ledger read is implemented.
func TestConsentSchemaValidationPrecedesImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie}
for _, test := range []struct {
name string
query string
pointer string
}{
{name: "the whole history", query: ""},
{name: "the active consents", query: "?state=active"},
{name: "the revoked consents of the next page", query: "?state=revoked&limit=50&cursor=b3BhcXVlLWN1cnNvcg"},
{name: "an unknown state", query: "?state=granted", pointer: "/state"},
{name: "a purpose instead of a state", query: "?state=c4", pointer: "/state"},
{name: "a limit over 100", query: "?limit=101", pointer: "/limit"},
{name: "a malformed cursor", query: "?cursor=not%20a%20cursor", pointer: "/cursor"},
} {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := serveIdentityRequest(t, router, identityRequest{method: http.MethodGet, path: myConsentsPath + test.query, headers: session})
if test.pointer == "" {
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
return
}
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: api.ProblemFieldLocationQuery, Pointer: test.pointer, Code: "invalid"}
for _, field := range body.Errors {
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
return
}
}
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
})
}
}
// The ledger read requires a session; DenyAllSecurity grants none, with or
// without a cookie, and a request cannot name another subject instead.
func TestConsentAccessBeforeImplementation(t *testing.T) {
for _, test := range []identityRequest{
{method: http.MethodGet, path: myConsentsPath},
{method: http.MethodGet, path: myConsentsPath + "?state=active", headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodGet, path: myConsentsPath + "?subject_id=01928f7a-0000-7000-8000-00000000c0de", headers: map[string]string{"Cookie": testSessionCookie}},
} {
t.Run(test.method+" "+test.path, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
})
}
}
// The read model never carries the stored text hash, a subject, or a contact
// value, and its parameters cannot select a subject.
func TestConsentDTOsCarryNoHashSubjectOrContact(t *testing.T) {
private := []string{"text_hash", "hash", "body_sha256", "subject_id", "user_id", "account_id", "email", "phone", "telegram", "full_name"}
for _, dto := range []any{api.ConsentRecord{}, api.ConsentRecordList{}, api.ConsentOrganization{}} {
assertNoJSONFields(t, dto, private)
}
params := reflect.TypeFor[api.ListMyConsentsParams]()
names := make([]string, 0, params.NumField())
for i := range params.NumField() {
names = append(names, params.Field(i).Name)
}
if got := strings.Join(names, ","); got != "State,Limit,Cursor" {
t.Fatalf("ListMyConsentsParams fields = %s, want only the state filter and the page", got)
}
// The documented example is a valid response of the generated server.
var page api.ConsentRecordList
if err := page.UnmarshalJSON(supportCaseExample(t, "ConsentRecordListPage")); err != nil {
t.Fatalf("decode the ConsentRecordListPage example: %v", err)
}
if err := page.Validate(); err != nil {
t.Fatalf("validate the ConsentRecordListPage example: %v", err)
}
}
func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) {
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
@@ -0,0 +1,376 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// consentConstraintErrors maps the consent constraints whose violation is a
// caller-visible outcome to port sentinels by SQLSTATE and constraint name,
// never by text. The duplicate grants of the ledger are no errors: the
// inserts use ON CONFLICT DO NOTHING.
var consentConstraintErrors = map[constraintViolation]error{
{foreignKeyViolationCode, "consent_records_subject_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "consent_records_text_fkey"}: outbound.ErrConsentTextNotFound,
{foreignKeyViolationCode, "consent_records_published_text_fkey"}: outbound.ErrConsentTextMismatch,
{checkViolationCode, "consent_records_text_published"}: outbound.ErrConsentTextNotPublished,
{checkViolationCode, "consent_records_c4_text_hash"}: outbound.ErrConsentTextMismatch,
// The revoke queries clamp the time to the grant, so this stays a
// backstop for a revocation written around them.
{checkViolationCode, "consent_records_revocation_stamp"}: domain.ErrInvalidConsent,
{integrityConstraintViolationCode, "consent_records_retained"}: outbound.ErrConsentRecordImmutable,
{integrityConstraintViolationCode, "consent_records_immutable"}: outbound.ErrConsentRecordImmutable,
}
// mapConsentError turns a known consent constraint or trigger error into its
// port sentinel and keeps the constraint name. Any other PostgreSQL error is
// replaced by its SQLSTATE and constraint name, because its detail can quote
// the subject, the organization, or the field set. Deadlocks and
// serialization failures also match ErrTransactionConflict. A connection
// error loses the pgx prefix that names the database user and database.
func mapConsentError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := consentConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapConsentError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
// ConsentStore provides the consent repositories outside a transaction.
// Every call runs as its own statement on a pool connection. Called with a
// context that belongs to a Transactor callback, it fails with
// outbound.ErrNestedTransaction; use the UnitOfWork accessors there.
type ConsentStore struct {
queries *sqlc.Queries
}
func NewConsentStore(pool *pgxpool.Pool) *ConsentStore {
return &ConsentStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
var (
_ outbound.ConsentRepositories = (*ConsentStore)(nil)
_ outbound.ConsentRepositories = (*UnitOfWork)(nil)
)
func (store *ConsentStore) ConsentTexts() outbound.ConsentTextRepository {
return consentTextRepository{queries: store.queries}
}
func (store *ConsentStore) ConsentLedger() outbound.ConsentLedger {
return consentLedger{queries: store.queries}
}
func (unit *UnitOfWork) ConsentTexts() outbound.ConsentTextRepository {
return consentTextRepository{queries: unit.queries}
}
func (unit *UnitOfWork) ConsentLedger() outbound.ConsentLedger {
return consentLedger{queries: unit.queries}
}
type consentTextRepository struct {
queries *sqlc.Queries
}
func (repository consentTextRepository) Get(
ctx context.Context,
purpose domain.ConsentPurpose,
version domain.ConsentTextVersion,
) (domain.ConsentText, error) {
row, err := repository.queries.GetConsentText(ctx, sqlc.GetConsentTextParams{Purpose: string(purpose), Version: string(version)})
if err != nil {
return domain.ConsentText{}, fmt.Errorf("consentTextRepository.Get - select consent text: %w", mapConsentNoRows(err, outbound.ErrConsentTextNotFound))
}
return consentTextFromRow(row)
}
func (repository consentTextRepository) Current(ctx context.Context, purpose domain.ConsentPurpose, at time.Time) (domain.ConsentText, error) {
if err := requireTime("consentTextRepository.Current", at, domain.ErrInvalidConsentText); err != nil {
return domain.ConsentText{}, err
}
row, err := repository.queries.GetCurrentConsentText(ctx, sqlc.GetCurrentConsentTextParams{Purpose: string(purpose), At: pgTime(at)})
if err != nil {
return domain.ConsentText{}, fmt.Errorf("consentTextRepository.Current - select consent text: %w", mapConsentNoRows(err, outbound.ErrConsentTextNotFound))
}
return consentTextFromRow(row)
}
func consentTextFromRow(row sqlc.ConsentText) (domain.ConsentText, error) {
text, err := domain.RestoreConsentText(domain.StoredConsentText{
Purpose: row.Purpose,
Version: row.Version,
Body: row.Body,
Hash: row.BodySha256,
Kind: row.Kind,
PublishedAt: row.PublishedAt.Time,
})
if err != nil {
return domain.ConsentText{}, fmt.Errorf("postgres.consentTextFromRow - restore consent text: %w", err)
}
return text, nil
}
type consentLedger struct {
queries *sqlc.Queries
}
var _ outbound.ConsentLedger = consentLedger{}
func (ledger consentLedger) Grant(ctx context.Context, grant domain.ConsentGrant) (domain.ConsentRecord, bool, error) {
if grant.IsZero() {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - grant was not built by domain.NewConsentGrant: %w", domain.ErrInvalidConsent)
}
hash := grant.TextHash()
row, err := ledger.queries.InsertConsentRecord(ctx, sqlc.InsertConsentRecordParams{
ID: pgUUID(grant.ID()),
SubjectID: pgUUID(grant.SubjectID()),
Purpose: string(grant.Purpose()),
TextVersion: string(grant.TextVersion()),
TextHash: hash[:],
Source: string(grant.Source()),
GrantedAt: pgTime(grant.GrantedAt()),
})
if err == nil {
record, err := consentRecordFromRow(consentRecordRow(row))
return record, err == nil, err
}
if !errors.Is(err, pgx.ErrNoRows) {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - insert consent record: %w", mapConsentError(err))
}
existing, err := ledger.queries.GetUnrevokedConsentRecordByVersion(ctx, sqlc.GetUnrevokedConsentRecordByVersionParams{
SubjectID: pgUUID(grant.SubjectID()),
Purpose: string(grant.Purpose()),
TextVersion: string(grant.TextVersion()),
})
if errors.Is(err, pgx.ErrNoRows) {
// The conflicting record was revoked between the two statements. A
// retry of the operation inserts a new record.
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - conflicting record was revoked concurrently: %w", outbound.ErrTransactionConflict)
}
if err != nil {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - select existing consent record: %w", mapConsentError(err))
}
record, err := consentRecordFromRow(consentRecordRow(existing))
return record, false, err
}
func (ledger consentLedger) GrantContact(ctx context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) {
if grant.IsZero() {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - grant was not built by domain.NewContactConsentGrant: %w", domain.ErrInvalidConsent)
}
hash := grant.TextHash()
row, err := ledger.queries.InsertContactConsentRecord(ctx, sqlc.InsertContactConsentRecordParams{
ID: pgUUID(grant.ID()),
SubjectID: pgUUID(grant.SubjectID()),
TextVersion: string(grant.TextVersion()),
TextHash: hash[:],
OrganizationID: pgUUID(grant.OrganizationID()),
OrganizationName: pgtype.Text{String: grant.OrganizationName(), Valid: true},
FieldSet: contactFieldStrings(grant.Fields()),
InvitationID: pgUUID(grant.InvitationID()),
InvitationTermsVersion: pgtype.Int8{Int64: grant.InvitationTermsVersion(), Valid: true},
GrantedAt: pgTime(grant.GrantedAt()),
})
if err == nil {
record, err := consentRecordFromRow(consentRecordRow(row))
return record, err == nil, err
}
if !errors.Is(err, pgx.ErrNoRows) {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - insert consent record: %w", mapConsentError(err))
}
existing, err := ledger.queries.GetContactConsentRecordByInvitation(ctx, sqlc.GetContactConsentRecordByInvitationParams{
SubjectID: pgUUID(grant.SubjectID()),
InvitationID: pgUUID(grant.InvitationID()),
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - select existing consent record: %w", outbound.ErrConsentInvitationTaken)
}
if err != nil {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - select existing consent record: %w", mapConsentError(err))
}
record, err := consentRecordFromRow(consentRecordRow(existing))
return record, false, err
}
func (ledger consentLedger) Revoke(ctx context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error) {
if revocation.IsZero() {
return nil, fmt.Errorf("consentLedger.Revoke - revocation was not built by domain.NewConsentRevocation: %w", domain.ErrInvalidConsent)
}
source := pgtype.Text{String: string(revocation.Source()), Valid: true}
if revocation.Purpose().OrganizationScoped() {
rows, err := ledger.queries.RevokeContactConsentRecords(ctx, sqlc.RevokeContactConsentRecordsParams{
RevokedAt: pgTime(revocation.RevokedAt()),
RevocationSource: source,
SubjectID: pgUUID(revocation.SubjectID()),
OrganizationID: pgUUID(revocation.OrganizationID()),
})
if err != nil {
return nil, fmt.Errorf("consentLedger.Revoke - revoke contact consent records: %w", mapConsentError(err))
}
return consentRecordsFromRows(rows, func(row sqlc.RevokeContactConsentRecordsRow) consentRecordRow { return consentRecordRow(row) })
}
rows, err := ledger.queries.RevokeConsentRecords(ctx, sqlc.RevokeConsentRecordsParams{
RevokedAt: pgTime(revocation.RevokedAt()),
RevocationSource: source,
SubjectID: pgUUID(revocation.SubjectID()),
Purpose: string(revocation.Purpose()),
})
if err != nil {
return nil, fmt.Errorf("consentLedger.Revoke - revoke consent records: %w", mapConsentError(err))
}
return consentRecordsFromRows(rows, func(row sqlc.RevokeConsentRecordsRow) consentRecordRow { return consentRecordRow(row) })
}
func (ledger consentLedger) Current(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) {
if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil {
return domain.ConsentRecord{}, fmt.Errorf("consentLedger.Current - validate purpose: %w", err)
}
if purpose.OrganizationScoped() {
return domain.ConsentRecord{}, fmt.Errorf("consentLedger.Current - C4 is read per organization with CurrentContact: %w", domain.ErrInvalidConsent)
}
row, err := ledger.queries.GetCurrentConsentRecord(ctx, sqlc.GetCurrentConsentRecordParams{SubjectID: pgUUID(subjectID), Purpose: string(purpose)})
if err != nil {
return domain.ConsentRecord{}, fmt.Errorf("consentLedger.Current - select consent record: %w", mapConsentNoRows(err, outbound.ErrConsentNotFound))
}
return consentRecordFromRow(consentRecordRow(row))
}
func (ledger consentLedger) CurrentContact(ctx context.Context, subjectID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) {
rows, err := ledger.queries.ListCurrentContactConsentRecords(ctx, sqlc.ListCurrentContactConsentRecordsParams{
SubjectID: pgUUID(subjectID),
OrganizationID: pgUUID(organizationID),
})
if err != nil {
return nil, fmt.Errorf("consentLedger.CurrentContact - select consent records: %w", mapConsentError(err))
}
return consentRecordsFromRows(rows, func(row sqlc.ListCurrentContactConsentRecordsRow) consentRecordRow { return consentRecordRow(row) })
}
func (ledger consentLedger) List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) {
const location = "consentLedger.List"
if query.SubjectID == uuid.Nil {
return outbound.ConsentPage{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, domain.ErrInvalidConsent)
}
if query.Limit < 1 || query.Limit > outbound.MaxConsentPageSize {
return outbound.ConsentPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxConsentPageSize, domain.ErrInvalidConsent)
}
params := sqlc.ListConsentRecordsParams{
SubjectID: pgUUID(query.SubjectID),
// One extra row tells whether another page follows.
RowLimit: query.Limit + 1,
}
if query.State != "" {
if _, err := domain.ParseConsentState(string(query.State)); err != nil {
return outbound.ConsentPage{}, fmt.Errorf("%s - validate state: %w", location, err)
}
params.State = pgtype.Text{String: string(query.State), Valid: true}
}
if query.After != nil {
if err := requireTime(location, query.After.GrantedAt, domain.ErrInvalidConsent); err != nil {
return outbound.ConsentPage{}, err
}
params.AfterGrantedAt = pgTime(query.After.GrantedAt)
params.AfterID = pgUUID(query.After.ID)
}
rows, err := ledger.queries.ListConsentRecords(ctx, params)
if err != nil {
return outbound.ConsentPage{}, fmt.Errorf("%s - select consent records: %w", location, mapConsentError(err))
}
page := outbound.ConsentPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Records, err = consentRecordsFromRows(rows, func(row sqlc.ListConsentRecordsRow) consentRecordRow { return consentRecordRow(row) })
if err != nil {
return outbound.ConsentPage{}, err
}
return page, nil
}
// consentRecordRow has the columns that every record query returns. The
// generated row types of those queries convert to it.
type consentRecordRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
func consentRecordFromRow(row consentRecordRow) (domain.ConsentRecord, error) {
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: optionalUUID(row.ID),
SubjectID: optionalUUID(row.SubjectID),
Purpose: row.Purpose,
TextVersion: row.TextVersion,
TextHash: row.TextHash,
Source: row.Source,
State: row.State,
GrantedAt: row.GrantedAt.Time,
RevokedAt: optionalTime(row.RevokedAt),
RevocationSource: row.RevocationSource.String,
OrganizationID: optionalUUID(row.OrganizationID),
OrganizationName: row.OrganizationName.String,
FieldSet: row.FieldSet,
InvitationID: optionalUUID(row.InvitationID),
InvitationTermsVersion: row.InvitationTermsVersion.Int64,
})
if err != nil {
return domain.ConsentRecord{}, fmt.Errorf("postgres.consentRecordFromRow - restore consent record: %w", err)
}
return record, nil
}
func consentRecordsFromRows[Row any](rows []Row, convert func(Row) consentRecordRow) ([]domain.ConsentRecord, error) {
records := make([]domain.ConsentRecord, 0, len(rows))
for _, row := range rows {
record, err := consentRecordFromRow(convert(row))
if err != nil {
return nil, err
}
records = append(records, record)
}
return records, nil
}
func contactFieldStrings(set domain.ContactFieldSet) []string {
fields := set.Fields()
values := make([]string, 0, len(fields))
for _, field := range fields {
values = append(values, string(field))
}
return values
}
func mapConsentNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapConsentError(err)
}
@@ -0,0 +1,211 @@
package postgres
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// consentDetailMarker stands for a row value that a PostgreSQL detail can
// quote, such as the subject or the field set.
const consentDetailMarker = "Key (subject_id)=(01928f7a-0000-7000-8000-00000000c0de)"
func TestMapConsentErrorRecognizesLedgerConstraints(t *testing.T) {
for _, test := range []struct {
code string
constraint string
want error
}{
{code: foreignKeyViolationCode, constraint: "consent_records_subject_id_fkey", want: outbound.ErrUserNotFound},
{code: foreignKeyViolationCode, constraint: "consent_records_text_fkey", want: outbound.ErrConsentTextNotFound},
{code: foreignKeyViolationCode, constraint: "consent_records_published_text_fkey", want: outbound.ErrConsentTextMismatch},
{code: checkViolationCode, constraint: "consent_records_text_published", want: outbound.ErrConsentTextNotPublished},
{code: checkViolationCode, constraint: "consent_records_c4_text_hash", want: outbound.ErrConsentTextMismatch},
{code: checkViolationCode, constraint: "consent_records_revocation_stamp", want: domain.ErrInvalidConsent},
{code: integrityConstraintViolationCode, constraint: "consent_records_retained", want: outbound.ErrConsentRecordImmutable},
{code: integrityConstraintViolationCode, constraint: "consent_records_immutable", want: outbound.ErrConsentRecordImmutable},
} {
err := mapConsentError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: consentDetailMarker})
if !errors.Is(err, test.want) {
t.Fatalf("mapConsentError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
}
if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "subject_id)=") {
t.Fatalf("mapConsentError(%s) = %v, want the constraint name and no detail", test.constraint, err)
}
}
}
func TestMapConsentErrorDropsDetailOfOtherErrors(t *testing.T) {
// A CHECK violation that the domain should have prevented keeps only the
// SQLSTATE and the constraint, never the failing row.
original := &pgconn.PgError{Code: checkViolationCode, ConstraintName: "consent_records_c4_scope", Detail: "Failing row contains (" + consentDetailMarker + ", {email,phone})."}
err := mapConsentError(original)
var stateError sqlStateError
if !errors.As(err, &stateError) || stateError.SQLState() != checkViolationCode {
t.Fatalf("mapConsentError() = %v, want SQLSTATE %s", err, checkViolationCode)
}
if strings.Contains(err.Error(), "Failing row") || strings.Contains(err.Error(), "phone") {
t.Fatalf("mapConsentError() = %v, want no row values", err)
}
if err := mapConsentError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) {
t.Fatalf("mapConsentError(deadlock) = %v, want ErrTransactionConflict", err)
}
if err := mapConsentError(context.Canceled); !errors.Is(err, context.Canceled) {
t.Fatalf("mapConsentError(context.Canceled) = %v, want the original error", err)
}
}
func TestConsentLedgerRejectsInvalidInputBeforeQuerying(t *testing.T) {
// A ledger without queries proves that no statement runs.
ledger := consentLedger{}
ctx := t.Context()
subject := uuid.Must(uuid.NewV7())
if _, _, err := ledger.Grant(ctx, domain.ConsentGrant{}); !errors.Is(err, domain.ErrInvalidConsent) {
t.Fatalf("Grant(zero grant) error = %v, want ErrInvalidConsent", err)
}
if _, _, err := ledger.GrantContact(ctx, domain.ContactConsentGrant{}); !errors.Is(err, domain.ErrInvalidConsent) {
t.Fatalf("GrantContact(zero grant) error = %v, want ErrInvalidConsent", err)
}
if _, err := ledger.Revoke(ctx, domain.ConsentRevocation{}); !errors.Is(err, domain.ErrInvalidConsent) {
t.Fatalf("Revoke(zero revocation) error = %v, want ErrInvalidConsent", err)
}
if _, err := ledger.Current(ctx, subject, domain.ConsentPurposeContactDisclosure); !errors.Is(err, domain.ErrInvalidConsent) {
t.Fatalf("Current(C4) error = %v, want ErrInvalidConsent", err)
}
if _, err := ledger.Current(ctx, subject, "c9"); !errors.Is(err, domain.ErrInvalidConsent) {
t.Fatalf("Current(unknown purpose) error = %v, want ErrInvalidConsent", err)
}
for _, query := range []outbound.ConsentListQuery{
{Limit: 10},
{SubjectID: subject, Limit: 0},
{SubjectID: subject, Limit: outbound.MaxConsentPageSize + 1},
{SubjectID: subject, Limit: 10, State: "pending"},
{SubjectID: subject, Limit: 10, After: &outbound.ConsentListPosition{ID: subject}},
} {
if _, err := ledger.List(ctx, query); !errors.Is(err, domain.ErrInvalidConsent) {
t.Fatalf("List(%+v) error = %v, want ErrInvalidConsent", query, err)
}
}
if _, err := (consentTextRepository{}).Current(ctx, domain.ConsentPurposePersonalData, time.Time{}); !errors.Is(err, domain.ErrInvalidConsentText) {
t.Fatalf("ConsentTexts.Current(zero time) error = %v, want ErrInvalidConsentText", err)
}
}
// Every record query returns the same columns, so each generated row type
// converts to consentRecordRow. A query that changes its columns breaks this
// test at compile time instead of mapping a column wrongly.
var (
_ = consentRecordRow(sqlc.InsertConsentRecordRow{})
_ = consentRecordRow(sqlc.InsertContactConsentRecordRow{})
_ = consentRecordRow(sqlc.GetUnrevokedConsentRecordByVersionRow{})
_ = consentRecordRow(sqlc.GetContactConsentRecordByInvitationRow{})
_ = consentRecordRow(sqlc.GetCurrentConsentRecordRow{})
_ = consentRecordRow(sqlc.ListCurrentContactConsentRecordsRow{})
_ = consentRecordRow(sqlc.RevokeConsentRecordsRow{})
_ = consentRecordRow(sqlc.RevokeContactConsentRecordsRow{})
_ = consentRecordRow(sqlc.ListConsentRecordsRow{})
)
func TestConsentRecordFromRowMapsNullableScope(t *testing.T) {
grantedAt := time.Date(2026, 10, 6, 9, 30, 0, 0, time.UTC)
hash := domain.HashConsentText("shown text")
subject := uuid.Must(uuid.NewV7())
organization := uuid.Must(uuid.NewV7())
invitation := uuid.Must(uuid.NewV7())
contact, err := consentRecordFromRow(consentRecordRow{
ID: pgUUID(uuid.Must(uuid.NewV7())),
SubjectID: pgUUID(subject),
Purpose: "c4",
TextVersion: "c4-2026-10-01",
TextHash: hash[:],
Source: "invitation_acceptance",
OrganizationID: pgUUID(organization),
OrganizationName: pgtype.Text{String: "Acme", Valid: true},
FieldSet: []string{"email", "phone"},
InvitationID: pgUUID(invitation),
InvitationTermsVersion: pgtype.Int8{Int64: 3, Valid: true},
GrantedAt: pgTime(grantedAt),
RevokedAt: pgTime(grantedAt.Add(time.Hour)),
RevocationSource: pgtype.Text{String: "consent_settings", Valid: true},
State: "revoked",
})
if err != nil {
t.Fatalf("consentRecordFromRow(C4) error = %v", err)
}
if contact.OrganizationID() != organization || contact.OrganizationName() != "Acme" || contact.InvitationID() != invitation || contact.InvitationTermsVersion() != 3 ||
!contact.Fields().Contains(domain.ContactFieldPhone) || contact.Fields().Contains(domain.ContactFieldFullName) {
t.Fatalf("C4 scope = %s, %s, %d, %v; want the stored scope", contact.OrganizationID(), contact.InvitationID(), contact.InvitationTermsVersion(), contact.Fields().Fields())
}
if revokedAt, revoked := contact.RevokedAt(); !revoked || !revokedAt.Equal(grantedAt.Add(time.Hour)) || contact.RevocationSource() != domain.ConsentRevocationSourceConsentSettings {
t.Fatalf("revocation = %v %v %q, want the stored stamp", revokedAt, revoked, contact.RevocationSource())
}
personalData, err := consentRecordFromRow(consentRecordRow{
ID: pgUUID(uuid.Must(uuid.NewV7())),
SubjectID: pgUUID(subject),
Purpose: "c1",
TextVersion: "c1-2026-10-01",
TextHash: hash[:],
Source: "registration",
GrantedAt: pgTime(grantedAt),
State: "active",
})
if err != nil {
t.Fatalf("consentRecordFromRow(C1) error = %v", err)
}
if personalData.OrganizationID() != uuid.Nil || !personalData.Fields().IsZero() || personalData.InvitationID() != uuid.Nil {
t.Fatalf("C1 scope = %s %v %s, want none", personalData.OrganizationID(), personalData.Fields().Fields(), personalData.InvitationID())
}
if _, revoked := personalData.RevokedAt(); revoked || personalData.State() != domain.ConsentStateActive {
t.Fatalf("C1 state = %s, want active and unrevoked", personalData.State())
}
// A row changed outside the application fails instead of producing a
// record that breaks the ledger rules.
if _, err := consentRecordFromRow(consentRecordRow{
ID: pgUUID(uuid.Must(uuid.NewV7())), SubjectID: pgUUID(subject), Purpose: "c2", TextVersion: "c2-2026-10-01",
TextHash: hash[:], Source: "consent_settings", OrganizationID: pgUUID(organization), GrantedAt: pgTime(grantedAt), State: "active",
}); !errors.Is(err, domain.ErrInvalidConsent) {
t.Fatalf("consentRecordFromRow(C2 with an organization) error = %v, want ErrInvalidConsent", err)
}
}
func TestContactFieldStringsKeepsCanonicalOrder(t *testing.T) {
set, err := domain.NewContactFieldSet(domain.ContactFieldTelegram, domain.ContactFieldFullName, domain.ContactFieldEmail)
if err != nil {
t.Fatalf("NewContactFieldSet() error = %v", err)
}
// The migration's consent_field_set_is_canonical accepts only ascending
// byte order, the order of PostgreSQL's "C" collation.
if got, want := strings.Join(contactFieldStrings(set), ","), "email,full_name,telegram"; got != want {
t.Fatalf("contactFieldStrings() = %s, want %s", got, want)
}
}
func TestMapCleanupErrorReportsAConcurrentConsentAsARetryableConflict(t *testing.T) {
concurrent := mapCleanupError(&pgconn.PgError{Code: restrictViolationCode, ConstraintName: consentSubjectForeignKey, Detail: consentDetailMarker})
if !errors.Is(concurrent, outbound.ErrTransactionConflict) || strings.Contains(concurrent.Error(), "subject_id)=") {
t.Fatalf("mapCleanupError(restrict) = %v, want ErrTransactionConflict without the detail", concurrent)
}
// Another restricting key, or the same key with another code, is no
// conflict.
for _, original := range []*pgconn.PgError{
{Code: restrictViolationCode, ConstraintName: "other_fkey"},
{Code: foreignKeyViolationCode, ConstraintName: consentSubjectForeignKey},
} {
if err := mapCleanupError(original); errors.Is(err, outbound.ErrTransactionConflict) {
t.Fatalf("mapCleanupError(%s %s) = %v, want no conflict", original.Code, original.ConstraintName, err)
}
}
}
@@ -22,6 +22,11 @@ import (
const (
foreignKeyViolationCode = "23503"
// restrictViolationCode is raised by an ON DELETE RESTRICT foreign key.
restrictViolationCode = "23001"
// consentSubjectForeignKey restricts the delete of an account with
// consent records.
consentSubjectForeignKey = "consent_records_subject_id_fkey"
// sessionTouchInterval is the minimum age of last_seen_at before Touch
// writes it again. It bounds session writes to one per minute per session
@@ -216,7 +221,9 @@ func (repository userRepository) UpdateRegistration(ctx context.Context, user do
if err != nil {
return domain.User{}, fmt.Errorf("userRepository.UpdateRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict))
}
return userFromRow(row)
// The statement returns the users columns through a CTE, so sqlc gives
// it its own row type with the same fields.
return userFromRow(sqlc.User(row))
}
func (repository userRepository) MarkEmailVerified(
@@ -251,11 +258,26 @@ func (repository userRepository) DeleteUnverifiedRegisteredBefore(ctx context.Co
BatchLimit: limit,
})
if err != nil {
return 0, fmt.Errorf("userRepository.DeleteUnverifiedRegisteredBefore - delete users: %w", mapIdentityError(err))
return 0, fmt.Errorf("userRepository.DeleteUnverifiedRegisteredBefore - delete users: %w", mapCleanupError(err))
}
return deleted, nil
}
// mapCleanupError reports the restricting consent foreign key as a
// transaction conflict. The cleanup checks consent rows in its statement
// snapshot, so a consent committed for a candidate account after the
// snapshot but before the account lock passes that check and then fails
// the foreign key at the end of the statement. Nothing was deleted, and the
// next run sees the consent and skips or removes the account.
func mapCleanupError(err error) error {
var pgError *pgconn.PgError
if errors.As(err, &pgError) && pgError.Code == restrictViolationCode && pgError.ConstraintName == consentSubjectForeignKey {
return fmt.Errorf("postgres.mapCleanupError - consent recorded concurrently: %w: %w",
outbound.ErrTransactionConflict, &databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
return mapIdentityError(err)
}
func userFromRow(row sqlc.User) (domain.User, error) {
email, err := domain.RestoreEmailAddress(row.Email, row.EmailNormalized)
if err != nil {
@@ -0,0 +1,961 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: consents.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getConsentText = `-- name: GetConsentText :one
SELECT
purpose,
version,
body,
body_sha256,
kind,
published_at
FROM consent_texts
WHERE
purpose = $1
AND version = $2
`
type GetConsentTextParams struct {
Purpose string
Version string
}
func (q *Queries) GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error) {
row := q.db.QueryRow(ctx, getConsentText, arg.Purpose, arg.Version)
var i ConsentText
err := row.Scan(
&i.Purpose,
&i.Version,
&i.Body,
&i.BodySha256,
&i.Kind,
&i.PublishedAt,
)
return i, err
}
const getContactConsentRecordByInvitation = `-- name: GetContactConsentRecordByInvitation :one
SELECT
id,
subject_id,
purpose,
text_version,
text_hash,
source,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at,
revoked_at,
revocation_source,
(
CASE WHEN revoked_at IS NULL THEN 'active' ELSE 'revoked' END
)::text AS state
FROM consent_records
WHERE
subject_id = $1
AND invitation_id = $2
`
type GetContactConsentRecordByInvitationParams struct {
SubjectID pgtype.UUID
InvitationID pgtype.UUID
}
type GetContactConsentRecordByInvitationRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
func (q *Queries) GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error) {
row := q.db.QueryRow(ctx, getContactConsentRecordByInvitation, arg.SubjectID, arg.InvitationID)
var i GetContactConsentRecordByInvitationRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
)
return i, err
}
const getCurrentConsentRecord = `-- name: GetCurrentConsentRecord :one
SELECT
id,
subject_id,
purpose,
text_version,
text_hash,
source,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at,
revoked_at,
revocation_source,
'active'::text AS state
FROM consent_records
WHERE
subject_id = $1
AND purpose = $2
AND purpose <> 'c4'
AND revoked_at IS NULL
ORDER BY granted_at DESC, id DESC
LIMIT 1
`
type GetCurrentConsentRecordParams struct {
SubjectID pgtype.UUID
Purpose string
}
type GetCurrentConsentRecordRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
// The newest unrevoked record of a purpose other than C4.
func (q *Queries) GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error) {
row := q.db.QueryRow(ctx, getCurrentConsentRecord, arg.SubjectID, arg.Purpose)
var i GetCurrentConsentRecordRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
)
return i, err
}
const getCurrentConsentText = `-- name: GetCurrentConsentText :one
SELECT
purpose,
version,
body,
body_sha256,
kind,
published_at
FROM consent_texts
WHERE
purpose = $1
AND published_at <= $2
ORDER BY published_at DESC
LIMIT 1
`
type GetCurrentConsentTextParams struct {
Purpose string
At pgtype.Timestamptz
}
// The text of a purpose that applies at a time: the latest publication not
// after it.
func (q *Queries) GetCurrentConsentText(ctx context.Context, arg GetCurrentConsentTextParams) (ConsentText, error) {
row := q.db.QueryRow(ctx, getCurrentConsentText, arg.Purpose, arg.At)
var i ConsentText
err := row.Scan(
&i.Purpose,
&i.Version,
&i.Body,
&i.BodySha256,
&i.Kind,
&i.PublishedAt,
)
return i, err
}
const getUnrevokedConsentRecordByVersion = `-- name: GetUnrevokedConsentRecordByVersion :one
SELECT
record.id,
record.subject_id,
record.purpose,
record.text_version,
record.text_hash,
record.source,
record.organization_id,
record.organization_name,
record.field_set,
record.invitation_id,
record.invitation_terms_version,
record.granted_at,
record.revoked_at,
record.revocation_source,
(
CASE
WHEN exists(
SELECT 1 FROM consent_records AS newer
WHERE
newer.subject_id = record.subject_id
AND newer.purpose = record.purpose
AND newer.revoked_at IS NULL
AND (newer.granted_at, newer.id)
> (record.granted_at, record.id)
) THEN 'superseded'
ELSE 'active'
END
)::text AS state
FROM consent_records AS record
WHERE
record.subject_id = $1
AND record.purpose = $2
AND record.text_version = $3
AND record.revoked_at IS NULL
`
type GetUnrevokedConsentRecordByVersionParams struct {
SubjectID pgtype.UUID
Purpose string
TextVersion string
}
type GetUnrevokedConsentRecordByVersionRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
func (q *Queries) GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error) {
row := q.db.QueryRow(ctx, getUnrevokedConsentRecordByVersion, arg.SubjectID, arg.Purpose, arg.TextVersion)
var i GetUnrevokedConsentRecordByVersionRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
)
return i, err
}
const insertConsentRecord = `-- name: InsertConsentRecord :one
INSERT INTO consent_records (
id,
subject_id,
purpose,
text_version,
text_hash,
source,
granted_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
ON CONFLICT (subject_id, purpose, text_version)
WHERE revoked_at IS NULL AND purpose <> 'c4'
DO NOTHING
RETURNING
id,
subject_id,
purpose,
text_version,
text_hash,
source,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at,
revoked_at,
revocation_source,
(
CASE
WHEN exists(
SELECT 1 FROM consent_records AS newer
WHERE
newer.subject_id = consent_records.subject_id
AND newer.purpose = consent_records.purpose
AND newer.revoked_at IS NULL
AND (newer.granted_at, newer.id)
> (consent_records.granted_at, consent_records.id)
) THEN 'superseded'
ELSE 'active'
END
)::text AS state
`
type InsertConsentRecordParams struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
GrantedAt pgtype.Timestamptz
}
type InsertConsentRecordRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
// subject, purpose, and text version already exists when no row returns;
// the insert then changes nothing and does not abort the transaction.
func (q *Queries) InsertConsentRecord(ctx context.Context, arg InsertConsentRecordParams) (InsertConsentRecordRow, error) {
row := q.db.QueryRow(ctx, insertConsentRecord,
arg.ID,
arg.SubjectID,
arg.Purpose,
arg.TextVersion,
arg.TextHash,
arg.Source,
arg.GrantedAt,
)
var i InsertConsentRecordRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
)
return i, err
}
const insertContactConsentRecord = `-- name: InsertContactConsentRecord :one
INSERT INTO consent_records (
id,
subject_id,
purpose,
text_version,
text_hash,
source,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at
) VALUES (
$1,
$2,
'c4',
$3,
$4,
'invitation_acceptance',
$5,
$6,
$7::text [],
$8,
$9,
$10
)
ON CONFLICT (invitation_id) WHERE invitation_id IS NOT NULL
DO NOTHING
RETURNING
id,
subject_id,
purpose,
text_version,
text_hash,
source,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at,
revoked_at,
revocation_source,
'active'::text AS state
`
type InsertContactConsentRecordParams struct {
ID pgtype.UUID
SubjectID pgtype.UUID
TextVersion string
TextHash []byte
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
}
type InsertContactConsentRecordRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
// Records a C4 grant with its scope. The invitation already has a C4 record
// when no row returns; the insert then changes nothing and does not abort
// the transaction.
func (q *Queries) InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error) {
row := q.db.QueryRow(ctx, insertContactConsentRecord,
arg.ID,
arg.SubjectID,
arg.TextVersion,
arg.TextHash,
arg.OrganizationID,
arg.OrganizationName,
arg.FieldSet,
arg.InvitationID,
arg.InvitationTermsVersion,
arg.GrantedAt,
)
var i InsertContactConsentRecordRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
)
return i, err
}
const listConsentRecords = `-- name: ListConsentRecords :many
WITH ledger AS (
SELECT
record.id,
record.subject_id,
record.purpose,
record.text_version,
record.text_hash,
record.source,
record.organization_id,
record.organization_name,
record.field_set,
record.invitation_id,
record.invitation_terms_version,
record.granted_at,
record.revoked_at,
record.revocation_source,
(
CASE
WHEN record.revoked_at IS NOT NULL THEN 'revoked'
WHEN record.purpose <> 'c4' AND exists(
SELECT 1 FROM consent_records AS newer
WHERE
newer.subject_id = record.subject_id
AND newer.purpose = record.purpose
AND newer.revoked_at IS NULL
AND (newer.granted_at, newer.id)
> (record.granted_at, record.id)
) THEN 'superseded'
ELSE 'active'
END
)::text AS state
FROM consent_records AS record
WHERE record.subject_id = $5
)
SELECT
ledger.id,
ledger.subject_id,
ledger.purpose,
ledger.text_version,
ledger.text_hash,
ledger.source,
ledger.organization_id,
ledger.organization_name,
ledger.field_set,
ledger.invitation_id,
ledger.invitation_terms_version,
ledger.granted_at,
ledger.revoked_at,
ledger.revocation_source,
ledger.state
FROM ledger
WHERE
($1::text IS NULL OR ledger.state = $1::text)
AND (
$2::timestamptz IS NULL
OR (ledger.granted_at, ledger.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY ledger.granted_at DESC, ledger.id DESC
LIMIT $4
`
type ListConsentRecordsParams struct {
State pgtype.Text
AfterGrantedAt pgtype.Timestamptz
AfterID pgtype.UUID
RowLimit int32
SubjectID pgtype.UUID
}
type ListConsentRecordsRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
// One page of the subject's ledger, newest grant first, optionally limited
// to one state. Every record query is scoped by the subject, so a caller
// never reads or revokes another subject's consent. The state is computed,
// never stored: revoked once revoked_at is set; superseded when a newer
// unrevoked record of the same subject and purpose exists (never for C4,
// whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of
// the last record of the previous page.
func (q *Queries) ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error) {
rows, err := q.db.Query(ctx, listConsentRecords,
arg.State,
arg.AfterGrantedAt,
arg.AfterID,
arg.RowLimit,
arg.SubjectID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListConsentRecordsRow
for rows.Next() {
var i ListConsentRecordsRow
if err := rows.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCurrentContactConsentRecords = `-- name: ListCurrentContactConsentRecords :many
SELECT
id,
subject_id,
purpose,
text_version,
text_hash,
source,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at,
revoked_at,
revocation_source,
'active'::text AS state
FROM consent_records
WHERE
subject_id = $1
AND purpose = 'c4'
AND organization_id = $2
AND revoked_at IS NULL
ORDER BY granted_at DESC, id DESC
`
type ListCurrentContactConsentRecordsParams struct {
SubjectID pgtype.UUID
OrganizationID pgtype.UUID
}
type ListCurrentContactConsentRecordsRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error) {
rows, err := q.db.Query(ctx, listCurrentContactConsentRecords, arg.SubjectID, arg.OrganizationID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCurrentContactConsentRecordsRow
for rows.Next() {
var i ListCurrentContactConsentRecordsRow
if err := rows.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const revokeConsentRecords = `-- name: RevokeConsentRecords :many
UPDATE consent_records
SET
revoked_at = greatest($1::timestamptz, granted_at),
revocation_source = $2
WHERE
subject_id = $3
AND purpose = $4
AND purpose <> 'c4'
AND revoked_at IS NULL
RETURNING
id,
subject_id,
purpose,
text_version,
text_hash,
source,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at,
revoked_at,
revocation_source,
'revoked'::text AS state
`
type RevokeConsentRecordsParams struct {
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
SubjectID pgtype.UUID
Purpose string
}
type RevokeConsentRecordsRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
// Revokes every unrevoked record of a purpose other than C4, superseded ones
// included, and returns them. A revocation time before the grant time, from
// clock skew between instances, is stamped at the grant time instead.
func (q *Queries) RevokeConsentRecords(ctx context.Context, arg RevokeConsentRecordsParams) ([]RevokeConsentRecordsRow, error) {
rows, err := q.db.Query(ctx, revokeConsentRecords,
arg.RevokedAt,
arg.RevocationSource,
arg.SubjectID,
arg.Purpose,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []RevokeConsentRecordsRow
for rows.Next() {
var i RevokeConsentRecordsRow
if err := rows.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const revokeContactConsentRecords = `-- name: RevokeContactConsentRecords :many
UPDATE consent_records
SET
revoked_at = greatest($1::timestamptz, granted_at),
revocation_source = $2
WHERE
subject_id = $3
AND purpose = 'c4'
AND organization_id = $4
AND revoked_at IS NULL
RETURNING
id,
subject_id,
purpose,
text_version,
text_hash,
source,
organization_id,
organization_name,
field_set,
invitation_id,
invitation_terms_version,
granted_at,
revoked_at,
revocation_source,
'revoked'::text AS state
`
type RevokeContactConsentRecordsParams struct {
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
SubjectID pgtype.UUID
OrganizationID pgtype.UUID
}
type RevokeContactConsentRecordsRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
// Revokes every unrevoked C4 record of the subject for one organization and
// returns them, with the same clamp of the revocation time as above.
func (q *Queries) RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error) {
rows, err := q.db.Query(ctx, revokeContactConsentRecords,
arg.RevokedAt,
arg.RevocationSource,
arg.SubjectID,
arg.OrganizationID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []RevokeContactConsentRecordsRow
for rows.Next() {
var i RevokeContactConsentRecordsRow
if err := rows.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -107,6 +107,13 @@ locked_delivery AS (
FOR UPDATE SKIP LOCKED
),
locked_consent AS (
SELECT consent.subject_id
FROM consent_records AS consent
WHERE consent.subject_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
deletable AS (
SELECT candidate.id
FROM candidate
@@ -139,6 +146,19 @@ deletable AS (
SELECT count(*) FROM locked_delivery
WHERE locked_delivery.recipient_user_id = candidate.id
)
AND (
SELECT count(*) FROM consent_records AS consent
WHERE consent.subject_id = candidate.id
) = (
SELECT count(*) FROM locked_consent
WHERE locked_consent.subject_id = candidate.id
)
),
deleted_consent AS (
DELETE FROM consent_records
USING deletable
WHERE consent_records.subject_id = deletable.id
)
DELETE FROM users
@@ -152,18 +172,23 @@ type DeleteUnverifiedUsersRegisteredBeforeParams struct {
}
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens, sessions, mail requests, and mail
// deliveries (and through the deliveries their attempts). Every lock is taken
// oldest first, with their tokens, sessions, mail requests, mail deliveries
// (and through the deliveries their attempts), and consent records. The
// consent records reference the account with ON DELETE RESTRICT, so they are
// deleted explicitly in the same statement: a registration never confirmed
// by its email owner is not kept as consent evidence. Every lock is taken
// with SKIP LOCKED, so the statement never waits: an account whose row is
// locked, for example by a re-registration, a token insert, or a delivery
// insert, is skipped, and so is an account with any token, session, mail
// request, or delivery row locked, for example by a confirmation that
// consumed a token, the delivery consumer, or a worker recording an attempt.
// Skipped accounts stay for the next run.
// locked, for example by a re-registration, a token insert, a delivery
// insert, or a consent insert, is skipped, and so is an account with any
// token, session, mail request, delivery, or consent row locked, for example
// by a confirmation that consumed a token, the delivery consumer, or a
// worker recording an attempt. Skipped accounts stay for the next run.
// Taking the account lock before the token locks is the reverse of the
// documented order, which is safe only because no lock here waits.
// An account qualifies only when every token, session, mail request, and
// delivery row visible to the statement was locked above.
// An account qualifies only when every token, session, mail request,
// delivery, and consent row visible to the statement was locked above.
// The restricting foreign key is checked at the end of the statement, after
// these rows are gone.
func (q *Queries) DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteUnverifiedUsersRegisteredBefore, arg.Cutoff, arg.BatchLimit)
if err != nil {
@@ -646,33 +671,59 @@ func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) (Tou
}
const updateUserRegistration = `-- name: UpdateUserRegistration :one
UPDATE users
SET
email = $1,
password_hash = $2,
scenario = $3,
onboarding_step = $4,
registration_version = registration_version + 1,
last_registered_at = $5,
updated_at = $6,
version = version + 1
WHERE
id = $7
AND version = $8
AND email_verified_at IS NULL
RETURNING
id,
email,
email_normalized,
password_hash,
scenario,
onboarding_step,
email_verified_at,
registration_version,
last_registered_at,
version,
created_at,
updated_at
WITH updated AS (
UPDATE users
SET
email = $1,
password_hash = $2,
scenario = $3,
onboarding_step = $4,
registration_version = registration_version + 1,
last_registered_at = $5,
updated_at = $6,
version = version + 1
WHERE
users.id = $7
AND users.version = $8
AND users.email_verified_at IS NULL
RETURNING
users.id,
users.email,
users.email_normalized,
users.password_hash,
users.scenario,
users.onboarding_step,
users.email_verified_at,
users.registration_version,
users.last_registered_at,
users.version,
users.created_at,
users.updated_at
),
discarded_consent AS (
DELETE FROM consent_records
USING updated
WHERE
consent_records.subject_id = updated.id
AND consent_records.purpose = 'c1'
AND consent_records.source = 'registration'
)
SELECT
updated.id,
updated.email,
updated.email_normalized,
updated.password_hash,
updated.scenario,
updated.onboarding_step,
updated.email_verified_at,
updated.registration_version,
updated.last_registered_at,
updated.version,
updated.created_at,
updated.updated_at
FROM updated
`
type UpdateUserRegistrationParams struct {
@@ -686,11 +737,29 @@ type UpdateUserRegistrationParams struct {
ExpectedVersion int64
}
type UpdateUserRegistrationRow struct {
ID pgtype.UUID
Email string
EmailNormalized string
PasswordHash string
Scenario string
OnboardingStep string
EmailVerifiedAt pgtype.Timestamptz
RegistrationVersion int64
LastRegisteredAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Replaces the registration of an unverified account and advances the
// registration version in the same statement, so no caller can choose it.
// The version check rejects a writer that read an older row; a verified
// account never changes.
func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error) {
// account never changes. The same statement deletes the C1 that the earlier
// registration of this account recorded, so the consent of an earlier
// registrant never stands for the new one; the new registration records its
// own C1 in the same transaction. A version conflict deletes nothing.
func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (UpdateUserRegistrationRow, error) {
row := q.db.QueryRow(ctx, updateUserRegistration,
arg.Email,
arg.PasswordHash,
@@ -701,7 +770,7 @@ func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegi
arg.ID,
arg.ExpectedVersion,
)
var i User
var i UpdateUserRegistrationRow
err := row.Scan(
&i.ID,
&i.Email,
@@ -8,6 +8,33 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
type ConsentRecord struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
PublishedTextHash []byte
Source string
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
}
type ConsentText struct {
Purpose string
Version string
Body string
BodySha256 []byte
Kind string
PublishedAt pgtype.Timestamptz
}
type ConsumerDeadLetter struct {
ID int64
ConsumerName string
@@ -50,18 +50,23 @@ type Querier interface {
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens, sessions, mail requests, and mail
// deliveries (and through the deliveries their attempts). Every lock is taken
// oldest first, with their tokens, sessions, mail requests, mail deliveries
// (and through the deliveries their attempts), and consent records. The
// consent records reference the account with ON DELETE RESTRICT, so they are
// deleted explicitly in the same statement: a registration never confirmed
// by its email owner is not kept as consent evidence. Every lock is taken
// with SKIP LOCKED, so the statement never waits: an account whose row is
// locked, for example by a re-registration, a token insert, or a delivery
// insert, is skipped, and so is an account with any token, session, mail
// request, or delivery row locked, for example by a confirmation that
// consumed a token, the delivery consumer, or a worker recording an attempt.
// Skipped accounts stay for the next run.
// locked, for example by a re-registration, a token insert, a delivery
// insert, or a consent insert, is skipped, and so is an account with any
// token, session, mail request, delivery, or consent row locked, for example
// by a confirmation that consumed a token, the delivery consumer, or a
// worker recording an attempt. Skipped accounts stay for the next run.
// Taking the account lock before the token locks is the reverse of the
// documented order, which is safe only because no lock here waits.
// An account qualifies only when every token, session, mail request, and
// delivery row visible to the statement was locked above.
// An account qualifies only when every token, session, mail request,
// delivery, and consent row visible to the statement was locked above.
// The restricting foreign key is checked at the end of the statement, after
// these rows are gone.
DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error)
// Lock order. Every transaction that writes mail_quota_usage first creates
// and locks all the usage rows it will touch with EnsureMailQuotaRows and
@@ -85,6 +90,13 @@ type Querier interface {
// provider's idempotency window reuses it instead of counting again.
FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error)
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error)
GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error)
// The newest unrevoked record of a purpose other than C4.
GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error)
// The text of a purpose that applies at a time: the latest publication not
// after it.
GetCurrentConsentText(ctx context.Context, arg GetCurrentConsentTextParams) (ConsentText, error)
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
// Among the versions of a family already effective at a time, the newest
// publication wins. A version scheduled for later therefore never undoes a
@@ -116,13 +128,22 @@ type Querier interface {
// the handler transaction that holds its row lock: only that transaction
// can have changed it, for example by canceling its own job.
GetScheduledJobStatus(ctx context.Context, id int64) (string, error)
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
// subject, purpose, and text version already exists when no row returns;
// the insert then changes nothing and does not abort the transaction.
InsertConsentRecord(ctx context.Context, arg InsertConsentRecordParams) (InsertConsentRecordRow, error)
// Stores a record that a consumer could not apply. A second delivery of the
// same record (same position and value) refreshes the outcome of its row:
// after a rewind the handler may fail differently. A different value at a
// reused position, after the topic was recreated, gets its own row.
InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error
// Records a C4 grant with its scope. The invitation already has a C4 record
// when no row returns; the insert then changes nothing and does not abort
// the transaction.
InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error)
// Stores a new delivery. A delivery with the same ID already exists when the
// same request is handled again; the statement then inserts nothing and
// returns 0 rows, and the stored content stays as it was. While another
@@ -158,6 +179,15 @@ type Querier interface {
InsertSession(ctx context.Context, arg InsertSessionParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
// One page of the subject's ledger, newest grant first, optionally limited
// to one state. Every record query is scoped by the subject, so a caller
// never reads or revokes another subject's consent. The state is computed,
// never stored: revoked once revoked_at is set; superseded when a newer
// unrevoked record of the same subject and purpose exists (never for C4,
// whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of
// the last record of the previous page.
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// Lists the other accounts of a provider that have usage in a month, so
// startup can warn about a renamed EMAIL_ACCOUNT.
@@ -228,6 +258,13 @@ type Querier interface {
// the job did not cause the failure. The same guard as the completion
// applies, one (id, attempt) pair per job. It returns the IDs it released.
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
// Revokes every unrevoked record of a purpose other than C4, superseded ones
// included, and returns them. A revocation time before the grant time, from
// clock skew between instances, is stamped at the grant time instead.
RevokeConsentRecords(ctx context.Context, arg RevokeConsentRecordsParams) ([]RevokeConsentRecordsRow, error)
// Revokes every unrevoked C4 record of the subject for one organization and
// returns them, with the same clamp of the revocation time as above.
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
// Bounds a consumer transaction on the server, local to the transaction.
@@ -270,8 +307,11 @@ type Querier interface {
// Replaces the registration of an unverified account and advances the
// registration version in the same statement, so no caller can choose it.
// The version check rejects a writer that read an older row; a verified
// account never changes.
UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error)
// account never changes. The same statement deletes the C1 that the earlier
// registration of this account recorded, so the consent of an earlier
// registrant never stands for the new one; the new registration records its
// own C1 in the same transaction. A version conflict deletes nothing.
UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (UpdateUserRegistrationRow, error)
}
var _ Querier = (*Queries)(nil)
+865
View File
@@ -0,0 +1,865 @@
package domain
import (
"crypto/sha256"
"errors"
"fmt"
"log/slog"
"regexp"
"slices"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
)
var (
// ErrInvalidConsent reports a grant, revocation, or stored record that
// breaks a consent ledger rule.
ErrInvalidConsent = errors.New("invalid consent")
// ErrInvalidConsentText reports a consent text, version, or hash that
// breaks a rule, including a stored text whose hash does not match its
// body.
ErrInvalidConsentText = errors.New("invalid consent text")
)
const (
// ConsentTextHashSize is the size of a SHA-256 digest.
ConsentTextHashSize = sha256.Size
// ConsentTextOrganizationPlaceholder marks where the C4 text names the
// organization. Only the C4 text contains it.
ConsentTextOrganizationPlaceholder = "{organization}"
// maxConsentTextRunes matches the contract bound of ConsentText.text.
maxConsentTextRunes = 100000
// maxOrganizationNameRunes matches InvitationOrganization.name.
maxOrganizationNameRunes = 200
// maxContactFields is the number of ContactField kinds.
maxContactFields = 4
)
// consentTextVersionPattern is the contract pattern of ConsentTextVersion
// with its length bound of 1 to 64 characters.
var consentTextVersionPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
// ConsentPurpose is one of the independent consents C1-C5 of PRD FR01. A
// grant or revocation of one purpose never changes another.
type ConsentPurpose string
const (
// ConsentPurposePersonalData is C1, the processing of personal data,
// given at registration.
ConsentPurposePersonalData ConsentPurpose = "c1"
// ConsentPurposePublication is C2, the publication of the candidate card.
ConsentPurposePublication ConsentPurpose = "c2"
// ConsentPurposeAutoCategorization is C3, the automatic categorization.
ConsentPurposeAutoCategorization ConsentPurpose = "c3"
// ConsentPurposeContactDisclosure is C4, the transfer of selected contact
// data to one organization. It is always scoped; see ContactConsentGrant.
ConsentPurposeContactDisclosure ConsentPurpose = "c4"
// ConsentPurposeFSPImport is C5, the import of FSP results.
ConsentPurposeFSPImport ConsentPurpose = "c5"
)
// ParseConsentPurpose accepts a known purpose.
func ParseConsentPurpose(value string) (ConsentPurpose, error) {
purpose := ConsentPurpose(value)
switch purpose {
case ConsentPurposePersonalData, ConsentPurposePublication, ConsentPurposeAutoCategorization,
ConsentPurposeContactDisclosure, ConsentPurposeFSPImport:
return purpose, nil
default:
return "", fmt.Errorf("domain.ParseConsentPurpose - unknown purpose: %w", ErrInvalidConsent)
}
}
// OrganizationScoped reports whether a grant of the purpose names an
// organization and a contact field set. Only C4 does.
func (purpose ConsentPurpose) OrganizationScoped() bool {
return purpose == ConsentPurposeContactDisclosure
}
// ConsentTextVersion identifies a published consent text, such as
// "c1-2026-10-01".
type ConsentTextVersion string
// ParseConsentTextVersion accepts 1 to 64 characters A-Z, a-z, 0-9, ".",
// "_", and "-".
func ParseConsentTextVersion(value string) (ConsentTextVersion, error) {
if !consentTextVersionPattern.MatchString(value) {
return "", fmt.Errorf("domain.ParseConsentTextVersion - version must have 1 to 64 characters A-Z a-z 0-9 . _ -: %w", ErrInvalidConsentText)
}
return ConsentTextVersion(value), nil
}
// ConsentTextHash is the SHA-256 digest of the UTF-8 bytes of exactly the
// text a subject saw.
type ConsentTextHash [ConsentTextHashSize]byte
// HashConsentText returns the digest of text.
func HashConsentText(text string) ConsentTextHash {
return sha256.Sum256([]byte(text))
}
// ConsentTextHashFromBytes accepts a stored 32-byte digest. An empty, short,
// long, or all-zero value is refused.
func ConsentTextHashFromBytes(value []byte) (ConsentTextHash, error) {
var hash ConsentTextHash
if len(value) != len(hash) {
return hash, fmt.Errorf("domain.ConsentTextHashFromBytes - hash must have %d bytes: %w", ConsentTextHashSize, ErrInvalidConsentText)
}
copy(hash[:], value)
if hash.IsZero() {
return hash, fmt.Errorf("domain.ConsentTextHashFromBytes - hash must not be all zero: %w", ErrInvalidConsentText)
}
return hash, nil
}
// IsZero reports the all-zero value, which marks a missing hash.
func (hash ConsentTextHash) IsZero() bool { return hash == ConsentTextHash{} }
// ConsentTextKind tells a demonstration text from a text of the operator.
type ConsentTextKind string
const (
// ConsentTextKindDemo is a synthetic text for the demonstration on
// synthetic data, without a legal review.
ConsentTextKindDemo ConsentTextKind = "demo"
// ConsentTextKindOperator is a text published by the personal data
// operator, required before real data are accepted (PRD 7.3).
ConsentTextKindOperator ConsentTextKind = "operator"
)
// ConsentText is one immutable published version of the text of a purpose.
type ConsentText struct {
purpose ConsentPurpose
version ConsentTextVersion
body string
hash ConsentTextHash
kind ConsentTextKind
publishedAt time.Time
}
// StoredConsentText carries the columns of a stored text.
type StoredConsentText struct {
Purpose string
Version string
Body string
Hash []byte
Kind string
PublishedAt time.Time
}
// RestoreConsentText validates a stored text, including that its hash is the
// digest of its body, so a row changed outside the application fails with
// ErrInvalidConsentText.
func RestoreConsentText(stored StoredConsentText) (ConsentText, error) {
const location = "domain.RestoreConsentText"
purpose, err := ParseConsentPurpose(stored.Purpose)
if err != nil {
return ConsentText{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
version, err := ParseConsentTextVersion(stored.Version)
if err != nil {
return ConsentText{}, fmt.Errorf("%s - validate version: %w", location, err)
}
hash, err := ConsentTextHashFromBytes(stored.Hash)
if err != nil {
return ConsentText{}, fmt.Errorf("%s - validate hash: %w", location, err)
}
kind := ConsentTextKind(stored.Kind)
switch {
case stored.Body == "" || !utf8.ValidString(stored.Body) || utf8.RuneCountInString(stored.Body) > maxConsentTextRunes:
return ConsentText{}, fmt.Errorf("%s - body must be valid UTF-8 of 1 to %d characters: %w", location, maxConsentTextRunes, ErrInvalidConsentText)
case HashConsentText(stored.Body) != hash:
return ConsentText{}, fmt.Errorf("%s - hash does not match the body: %w", location, ErrInvalidConsentText)
case purpose.OrganizationScoped() != strings.Contains(stored.Body, ConsentTextOrganizationPlaceholder):
return ConsentText{}, fmt.Errorf("%s - only the C4 text names the organization: %w", location, ErrInvalidConsentText)
case kind != ConsentTextKindDemo && kind != ConsentTextKindOperator:
return ConsentText{}, fmt.Errorf("%s - unknown kind: %w", location, ErrInvalidConsentText)
case stored.PublishedAt.IsZero():
return ConsentText{}, fmt.Errorf("%s - publication time must be set: %w", location, ErrInvalidConsentText)
}
return ConsentText{
purpose: purpose,
version: version,
body: stored.Body,
hash: hash,
kind: kind,
publishedAt: stored.PublishedAt,
}, nil
}
func (text ConsentText) Purpose() ConsentPurpose { return text.purpose }
func (text ConsentText) Version() ConsentTextVersion { return text.version }
func (text ConsentText) Body() string { return text.body }
func (text ConsentText) Kind() ConsentTextKind { return text.kind }
func (text ConsentText) PublishedAt() time.Time { return text.publishedAt }
// Hash is the digest of Body. A grant of C1-C3 or C5 records exactly this
// hash; a C4 grant records the hash of RenderForOrganization instead.
func (text ConsentText) Hash() ConsentTextHash { return text.hash }
// IsZero reports a ConsentText not built by RestoreConsentText.
func (text ConsentText) IsZero() bool { return text.purpose == "" }
// RenderForOrganization returns the C4 text as the candidate sees it: the
// body with every placeholder replaced by the organization name. The C4
// grant records HashConsentText of this result. The name must be one line
// of 1 to 200 characters without surrounding spaces.
func (text ConsentText) RenderForOrganization(organizationName string) (string, error) {
const location = "ConsentText.RenderForOrganization"
if !text.purpose.OrganizationScoped() {
return "", fmt.Errorf("%s - only the C4 text names an organization: %w", location, ErrInvalidConsentText)
}
if !validOrganizationName(organizationName) {
return "", fmt.Errorf("%s - organization name must be one line of 1 to %d characters: %w", location, maxOrganizationNameRunes, ErrInvalidConsentText)
}
return strings.ReplaceAll(text.body, ConsentTextOrganizationPlaceholder, organizationName), nil
}
func validOrganizationName(name string) bool {
if name == "" || !utf8.ValidString(name) || utf8.RuneCountInString(name) > maxOrganizationNameRunes {
return false
}
if strings.TrimSpace(name) != name {
return false
}
return !strings.ContainsFunc(name, unicode.IsControl)
}
// ConsentSource tells where a grant was given.
type ConsentSource string
const (
// ConsentSourceRegistration is the C1 acceptance in the registration.
ConsentSourceRegistration ConsentSource = "registration"
// ConsentSourceConsentSettings is a grant in the consent settings of the
// account, for C1-C3 and C5.
ConsentSourceConsentSettings ConsentSource = "consent_settings"
// ConsentSourceInvitationAcceptance is the C4 grant in the acceptance of
// an invitation.
ConsentSourceInvitationAcceptance ConsentSource = "invitation_acceptance"
)
// allowedFor reports whether a grant of purpose may come from the source.
func (source ConsentSource) allowedFor(purpose ConsentPurpose) bool {
switch source {
case ConsentSourceRegistration:
return purpose == ConsentPurposePersonalData
case ConsentSourceConsentSettings:
return !purpose.OrganizationScoped()
case ConsentSourceInvitationAcceptance:
return purpose.OrganizationScoped()
default:
return false
}
}
// ConsentRevocationSource tells who recorded a revocation.
type ConsentRevocationSource string
const (
// ConsentRevocationSourceConsentSettings is a revocation by the subject in
// the product.
ConsentRevocationSourceConsentSettings ConsentRevocationSource = "consent_settings"
// ConsentRevocationSourceSupportRequest is a revocation that an operator
// recorded on the subject's request through support.
ConsentRevocationSourceSupportRequest ConsentRevocationSource = "support_request"
)
func (source ConsentRevocationSource) known() bool {
return source == ConsentRevocationSourceConsentSettings || source == ConsentRevocationSourceSupportRequest
}
// ContactField is a kind of contact data that C4 can disclose to one
// organization; the values match the contract enum ContactFieldKind.
type ContactField string
const (
ContactFieldFullName ContactField = "full_name"
ContactFieldEmail ContactField = "email"
ContactFieldPhone ContactField = "phone"
ContactFieldTelegram ContactField = "telegram"
)
// ParseContactField accepts a known kind.
func ParseContactField(value string) (ContactField, error) {
field := ContactField(value)
switch field {
case ContactFieldFullName, ContactFieldEmail, ContactFieldPhone, ContactFieldTelegram:
return field, nil
default:
return "", fmt.Errorf("domain.ParseContactField - unknown contact field: %w", ErrInvalidConsent)
}
}
// ContactFieldSet is a non-empty set of distinct contact fields in canonical
// ascending byte order, the form the ledger stores. One kind never implies
// another.
type ContactFieldSet struct {
fields []ContactField
}
// NewContactFieldSet accepts one to four distinct known fields in any order.
// A repeated field is refused, as the contract's uniqueItems refuses it,
// rather than merged.
func NewContactFieldSet(fields ...ContactField) (ContactFieldSet, error) {
const location = "domain.NewContactFieldSet"
if len(fields) == 0 || len(fields) > maxContactFields {
return ContactFieldSet{}, fmt.Errorf("%s - set must have 1 to %d fields: %w", location, maxContactFields, ErrInvalidConsent)
}
canonical := make([]ContactField, 0, len(fields))
for _, field := range fields {
if _, err := ParseContactField(string(field)); err != nil {
return ContactFieldSet{}, fmt.Errorf("%s - validate field: %w", location, err)
}
if slices.Contains(canonical, field) {
return ContactFieldSet{}, fmt.Errorf("%s - fields must be distinct: %w", location, ErrInvalidConsent)
}
canonical = append(canonical, field)
}
slices.Sort(canonical)
return ContactFieldSet{fields: canonical}, nil
}
// Fields returns a copy of the fields in canonical order.
func (set ContactFieldSet) Fields() []ContactField { return slices.Clone(set.fields) }
// Contains reports whether the set covers field.
func (set ContactFieldSet) Contains(field ContactField) bool {
return slices.Contains(set.fields, field)
}
// Equal reports whether both sets cover the same fields.
func (set ContactFieldSet) Equal(other ContactFieldSet) bool {
return slices.Equal(set.fields, other.fields)
}
// IsZero reports a set not built by NewContactFieldSet.
func (set ContactFieldSet) IsZero() bool { return len(set.fields) == 0 }
// ConsentState is the state of a ledger record as the read model computes
// it from the ledger.
type ConsentState string
const (
// ConsentStateActive is an unrevoked record that is the newest of its
// purpose; every unrevoked C4 record is active, since each covers its
// own invitation.
ConsentStateActive ConsentState = "active"
// ConsentStateSuperseded is an unrevoked record of C1-C3 or C5 with a
// newer unrevoked record of the same purpose, typically for a newer
// text version. It stays valid evidence for its own time.
ConsentStateSuperseded ConsentState = "superseded"
// ConsentStateRevoked is a revoked record.
ConsentStateRevoked ConsentState = "revoked"
)
// ParseConsentState accepts a known state.
func ParseConsentState(value string) (ConsentState, error) {
state := ConsentState(value)
switch state {
case ConsentStateActive, ConsentStateSuperseded, ConsentStateRevoked:
return state, nil
default:
return "", fmt.Errorf("domain.ParseConsentState - unknown state: %w", ErrInvalidConsent)
}
}
// ConsentGrantInput describes a grant of C1, C2, C3, or C5. TextVersion and
// TextHash come from the ConsentText that the subject saw.
type ConsentGrantInput struct {
SubjectID uuid.UUID
Purpose ConsentPurpose
TextVersion ConsentTextVersion
TextHash ConsentTextHash
Source ConsentSource
GrantedAt time.Time
}
// ConsentGrant is a validated grant of C1, C2, C3, or C5, ready for the
// ledger. C4 is never a ConsentGrant: it needs its organization scope, see
// ContactConsentGrant.
type ConsentGrant struct {
id uuid.UUID
subjectID uuid.UUID
purpose ConsentPurpose
textVersion ConsentTextVersion
textHash ConsentTextHash
source ConsentSource
grantedAt time.Time
}
// NewConsentGrant validates input and assigns a UUIDv7 identifier.
func NewConsentGrant(input ConsentGrantInput) (ConsentGrant, error) {
const location = "domain.NewConsentGrant"
if _, err := ParseConsentPurpose(string(input.Purpose)); err != nil {
return ConsentGrant{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
if input.Purpose.OrganizationScoped() {
return ConsentGrant{}, fmt.Errorf("%s - C4 is granted only with its organization scope: %w", location, ErrInvalidConsent)
}
if err := validateGrantText(location, input.TextVersion, input.TextHash); err != nil {
return ConsentGrant{}, err
}
switch {
case input.SubjectID == uuid.Nil:
return ConsentGrant{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent)
case !input.Source.allowedFor(input.Purpose):
return ConsentGrant{}, fmt.Errorf("%s - source does not allow the purpose: %w", location, ErrInvalidConsent)
case input.GrantedAt.IsZero():
return ConsentGrant{}, fmt.Errorf("%s - grant time must be set: %w", location, ErrInvalidConsent)
}
id, err := uuid.NewV7()
if err != nil {
return ConsentGrant{}, fmt.Errorf("%s - generate record ID: %w", location, err)
}
return ConsentGrant{
id: id,
subjectID: input.SubjectID,
purpose: input.Purpose,
textVersion: input.TextVersion,
textHash: input.TextHash,
source: input.Source,
grantedAt: input.GrantedAt,
}, nil
}
func (grant ConsentGrant) ID() uuid.UUID { return grant.id }
func (grant ConsentGrant) SubjectID() uuid.UUID { return grant.subjectID }
func (grant ConsentGrant) Purpose() ConsentPurpose { return grant.purpose }
func (grant ConsentGrant) TextVersion() ConsentTextVersion { return grant.textVersion }
func (grant ConsentGrant) TextHash() ConsentTextHash { return grant.textHash }
func (grant ConsentGrant) Source() ConsentSource { return grant.source }
func (grant ConsentGrant) GrantedAt() time.Time { return grant.grantedAt }
// IsZero reports a grant not built by NewConsentGrant.
func (grant ConsentGrant) IsZero() bool { return grant.id == uuid.Nil }
func (grant ConsentGrant) String() string {
return fmt.Sprintf("[consent grant %s %s]", grant.id, grant.purpose)
}
func (grant ConsentGrant) GoString() string { return grant.String() }
// Format applies String to every verb; without it %+v would print the
// subject.
func (grant ConsentGrant) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(grant.String()))
}
// LogValue carries only the record ID and purpose.
func (grant ConsentGrant) LogValue() slog.Value { return consentLogValue(grant.id, grant.purpose) }
// ContactConsentGrantInput describes the C4 grant of an invitation
// acceptance: the organization and its name as the candidate saw it, the
// selected fields, the invitation and the terms version it accepts, and the
// published C4 text. The grant computes the hash of the shown text itself;
// a caller never supplies hash bytes.
type ContactConsentGrantInput struct {
SubjectID uuid.UUID
OrganizationID uuid.UUID
OrganizationName string
Fields ContactFieldSet
InvitationID uuid.UUID
InvitationTermsVersion int64
Text ConsentText
GrantedAt time.Time
}
// ContactConsentGrant is a validated C4 grant with its scope. String,
// GoString, Format, and LogValue show only the record ID and purpose.
type ContactConsentGrant struct {
id uuid.UUID
subjectID uuid.UUID
organizationID uuid.UUID
organizationName string
fields ContactFieldSet
invitationID uuid.UUID
invitationTermsVersion int64
textVersion ConsentTextVersion
textHash ConsentTextHash
grantedAt time.Time
}
// NewContactConsentGrant validates input, renders the C4 text for the
// organization name, records the hash of that shown text, and assigns a
// UUIDv7 identifier. The database checks the same hash against the
// published text and the stored name.
func NewContactConsentGrant(input ContactConsentGrantInput) (ContactConsentGrant, error) {
const location = "domain.NewContactConsentGrant"
if input.Text.IsZero() || !input.Text.Purpose().OrganizationScoped() {
return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires the published C4 text: %w", location, ErrInvalidConsentText)
}
shown, err := input.Text.RenderForOrganization(input.OrganizationName)
if err != nil {
return ContactConsentGrant{}, fmt.Errorf("%s - render the shown text: %w", location, err)
}
switch {
case input.SubjectID == uuid.Nil:
return ContactConsentGrant{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent)
case input.OrganizationID == uuid.Nil:
return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires an organization: %w", location, ErrInvalidConsent)
case input.Fields.IsZero():
return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires a field set built by NewContactFieldSet: %w", location, ErrInvalidConsent)
case input.InvitationID == uuid.Nil:
return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires an invitation: %w", location, ErrInvalidConsent)
case input.InvitationTermsVersion <= 0:
return ContactConsentGrant{}, fmt.Errorf("%s - invitation terms version must be positive: %w", location, ErrInvalidConsent)
case input.GrantedAt.IsZero():
return ContactConsentGrant{}, fmt.Errorf("%s - grant time must be set: %w", location, ErrInvalidConsent)
}
id, err := uuid.NewV7()
if err != nil {
return ContactConsentGrant{}, fmt.Errorf("%s - generate record ID: %w", location, err)
}
return ContactConsentGrant{
id: id,
subjectID: input.SubjectID,
organizationID: input.OrganizationID,
organizationName: input.OrganizationName,
fields: input.Fields,
invitationID: input.InvitationID,
invitationTermsVersion: input.InvitationTermsVersion,
textVersion: input.Text.Version(),
textHash: HashConsentText(shown),
grantedAt: input.GrantedAt,
}, nil
}
func (grant ContactConsentGrant) ID() uuid.UUID { return grant.id }
func (grant ContactConsentGrant) SubjectID() uuid.UUID { return grant.subjectID }
func (grant ContactConsentGrant) OrganizationID() uuid.UUID { return grant.organizationID }
func (grant ContactConsentGrant) OrganizationName() string { return grant.organizationName }
func (grant ContactConsentGrant) Fields() ContactFieldSet { return grant.fields }
func (grant ContactConsentGrant) InvitationID() uuid.UUID { return grant.invitationID }
func (grant ContactConsentGrant) InvitationTermsVersion() int64 { return grant.invitationTermsVersion }
func (grant ContactConsentGrant) TextVersion() ConsentTextVersion { return grant.textVersion }
func (grant ContactConsentGrant) TextHash() ConsentTextHash { return grant.textHash }
func (grant ContactConsentGrant) GrantedAt() time.Time { return grant.grantedAt }
// IsZero reports a grant not built by NewContactConsentGrant.
func (grant ContactConsentGrant) IsZero() bool { return grant.id == uuid.Nil }
func (grant ContactConsentGrant) String() string {
return fmt.Sprintf("[consent grant %s %s]", grant.id, ConsentPurposeContactDisclosure)
}
func (grant ContactConsentGrant) GoString() string { return grant.String() }
// Format applies String to every verb; without it %+v would print the
// subject, the organization, and the fields.
func (grant ContactConsentGrant) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(grant.String()))
}
// LogValue carries only the record ID and purpose.
func (grant ContactConsentGrant) LogValue() slog.Value {
return consentLogValue(grant.id, ConsentPurposeContactDisclosure)
}
func validateGrantText(location string, version ConsentTextVersion, hash ConsentTextHash) error {
if _, err := ParseConsentTextVersion(string(version)); err != nil {
return fmt.Errorf("%s - validate text version: %w", location, err)
}
if hash.IsZero() {
return fmt.Errorf("%s - text hash must be set: %w", location, ErrInvalidConsentText)
}
return nil
}
// ConsentRevocationInput describes a revocation of every unrevoked record of
// a purpose. OrganizationID is required for C4, which is revoked per
// organization, and must be uuid.Nil for every other purpose.
type ConsentRevocationInput struct {
SubjectID uuid.UUID
Purpose ConsentPurpose
OrganizationID uuid.UUID
Source ConsentRevocationSource
RevokedAt time.Time
}
// ConsentRevocation is a validated revocation.
type ConsentRevocation struct {
subjectID uuid.UUID
purpose ConsentPurpose
organizationID uuid.UUID
source ConsentRevocationSource
revokedAt time.Time
}
// NewConsentRevocation validates input.
func NewConsentRevocation(input ConsentRevocationInput) (ConsentRevocation, error) {
const location = "domain.NewConsentRevocation"
if _, err := ParseConsentPurpose(string(input.Purpose)); err != nil {
return ConsentRevocation{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
switch {
case input.SubjectID == uuid.Nil:
return ConsentRevocation{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent)
case input.Purpose.OrganizationScoped() != (input.OrganizationID != uuid.Nil):
return ConsentRevocation{}, fmt.Errorf("%s - only C4 is revoked per organization, and always so: %w", location, ErrInvalidConsent)
case !input.Source.known():
return ConsentRevocation{}, fmt.Errorf("%s - unknown revocation source: %w", location, ErrInvalidConsent)
case input.RevokedAt.IsZero():
return ConsentRevocation{}, fmt.Errorf("%s - revocation time must be set: %w", location, ErrInvalidConsent)
}
return ConsentRevocation{
subjectID: input.SubjectID,
purpose: input.Purpose,
organizationID: input.OrganizationID,
source: input.Source,
revokedAt: input.RevokedAt,
}, nil
}
func (revocation ConsentRevocation) SubjectID() uuid.UUID { return revocation.subjectID }
func (revocation ConsentRevocation) Purpose() ConsentPurpose { return revocation.purpose }
func (revocation ConsentRevocation) OrganizationID() uuid.UUID { return revocation.organizationID }
func (revocation ConsentRevocation) Source() ConsentRevocationSource { return revocation.source }
func (revocation ConsentRevocation) RevokedAt() time.Time { return revocation.revokedAt }
func (revocation ConsentRevocation) IsZero() bool { return revocation.subjectID == uuid.Nil }
func (revocation ConsentRevocation) String() string {
return fmt.Sprintf("[consent revocation %s]", revocation.purpose)
}
func (revocation ConsentRevocation) GoString() string { return revocation.String() }
// Format applies String to every verb; without it %+v would print the
// subject and the organization.
func (revocation ConsentRevocation) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(revocation.String()))
}
// LogValue carries only the purpose and the source.
func (revocation ConsentRevocation) LogValue() slog.Value {
return slog.GroupValue(
slog.String("purpose", string(revocation.purpose)),
slog.String("revocation_source", string(revocation.source)),
)
}
// ConsentRecord is one row of the consent ledger as read back, with the
// state the read model computed. It is personal data of the subject:
// String, GoString, Format, and LogValue show only the record ID, purpose,
// and state, never the subject, the organization, or the fields.
type ConsentRecord struct {
id uuid.UUID
subjectID uuid.UUID
purpose ConsentPurpose
textVersion ConsentTextVersion
textHash ConsentTextHash
source ConsentSource
state ConsentState
grantedAt time.Time
revokedAt time.Time
revocationSource ConsentRevocationSource
organizationID uuid.UUID
organizationName string
fields ContactFieldSet
invitationID uuid.UUID
invitationTermsVersion int64
}
// StoredConsentRecord carries the columns of a stored record. Absent C4
// scope values are uuid.Nil, nil, and 0; an unrevoked record has a nil
// RevokedAt and an empty RevocationSource.
type StoredConsentRecord struct {
ID uuid.UUID
SubjectID uuid.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
State string
GrantedAt time.Time
RevokedAt *time.Time
RevocationSource string
OrganizationID uuid.UUID
OrganizationName string
FieldSet []string
InvitationID uuid.UUID
InvitationTermsVersion int64
}
// RestoreConsentRecord validates a stored record against the rules the
// database enforces, so a row changed outside the application fails with
// ErrInvalidConsent or ErrInvalidConsentText.
func RestoreConsentRecord(stored StoredConsentRecord) (ConsentRecord, error) {
const location = "domain.RestoreConsentRecord"
purpose, err := ParseConsentPurpose(stored.Purpose)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
version, err := ParseConsentTextVersion(stored.TextVersion)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate text version: %w", location, err)
}
hash, err := ConsentTextHashFromBytes(stored.TextHash)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate text hash: %w", location, err)
}
state, err := ParseConsentState(stored.State)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate state: %w", location, err)
}
record := ConsentRecord{
id: stored.ID,
subjectID: stored.SubjectID,
purpose: purpose,
textVersion: version,
textHash: hash,
source: ConsentSource(stored.Source),
state: state,
grantedAt: stored.GrantedAt,
revocationSource: ConsentRevocationSource(stored.RevocationSource),
organizationID: stored.OrganizationID,
organizationName: stored.OrganizationName,
invitationID: stored.InvitationID,
invitationTermsVersion: stored.InvitationTermsVersion,
}
if stored.RevokedAt != nil {
record.revokedAt = *stored.RevokedAt
}
if purpose.OrganizationScoped() {
fields, err := restoreContactFields(stored.FieldSet)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate field set: %w", location, err)
}
record.fields = fields
}
if err := record.validate(stored.FieldSet != nil); err != nil {
return ConsentRecord{}, fmt.Errorf("%s - %w", location, err)
}
return record, nil
}
func restoreContactFields(stored []string) (ContactFieldSet, error) {
fields := make([]ContactField, 0, len(stored))
for _, value := range stored {
field, err := ParseContactField(value)
if err != nil {
return ContactFieldSet{}, err
}
fields = append(fields, field)
}
return NewContactFieldSet(fields...)
}
// validate checks the invariants that RestoreConsentRecord cannot express
// while parsing single values.
func (record ConsentRecord) validate(hasFieldSet bool) error {
switch {
case record.id == uuid.Nil || record.subjectID == uuid.Nil:
return fmt.Errorf("record and subject IDs must not be nil: %w", ErrInvalidConsent)
case !record.source.allowedFor(record.purpose):
return fmt.Errorf("source does not allow the purpose: %w", ErrInvalidConsent)
case record.grantedAt.IsZero():
return fmt.Errorf("grant time must be set: %w", ErrInvalidConsent)
}
if err := record.validateRevocation(); err != nil {
return err
}
return record.validateScope(hasFieldSet)
}
// validateRevocation mirrors consent_records_revocation_stamp and ties the
// computed state to the stamp.
func (record ConsentRecord) validateRevocation() error {
revoked := !record.revokedAt.IsZero()
switch {
case revoked != (record.revocationSource != ""):
return fmt.Errorf("revocation time and source must be set together: %w", ErrInvalidConsent)
case revoked && (!record.revocationSource.known() || record.revokedAt.Before(record.grantedAt)):
return fmt.Errorf("revocation must have a known source and follow the grant: %w", ErrInvalidConsent)
case revoked != (record.state == ConsentStateRevoked):
return fmt.Errorf("state must match the revocation: %w", ErrInvalidConsent)
}
return nil
}
// validateScope mirrors consent_records_c4_scope.
func (record ConsentRecord) validateScope(hasFieldSet bool) error {
if !record.purpose.OrganizationScoped() {
if record.organizationID != uuid.Nil || record.organizationName != "" || hasFieldSet ||
record.invitationID != uuid.Nil || record.invitationTermsVersion != 0 {
return fmt.Errorf("only a C4 record has an organization scope: %w", ErrInvalidConsent)
}
return nil
}
switch {
case record.state == ConsentStateSuperseded:
return fmt.Errorf("a C4 record is never superseded: %w", ErrInvalidConsent)
case record.organizationID == uuid.Nil || record.invitationID == uuid.Nil || record.invitationTermsVersion <= 0:
return fmt.Errorf("a C4 record must have its organization and invitation: %w", ErrInvalidConsent)
case !validOrganizationName(record.organizationName):
return fmt.Errorf("a C4 record must have the organization name it was shown with: %w", ErrInvalidConsent)
}
return nil
}
func (record ConsentRecord) ID() uuid.UUID { return record.id }
func (record ConsentRecord) SubjectID() uuid.UUID { return record.subjectID }
func (record ConsentRecord) Purpose() ConsentPurpose { return record.purpose }
func (record ConsentRecord) TextVersion() ConsentTextVersion { return record.textVersion }
func (record ConsentRecord) TextHash() ConsentTextHash { return record.textHash }
func (record ConsentRecord) Source() ConsentSource { return record.source }
func (record ConsentRecord) State() ConsentState { return record.state }
func (record ConsentRecord) GrantedAt() time.Time { return record.grantedAt }
// RevokedAt returns the revocation time and true for a revoked record.
func (record ConsentRecord) RevokedAt() (time.Time, bool) {
return record.revokedAt, !record.revokedAt.IsZero()
}
// RevocationSource is empty for an unrevoked record.
func (record ConsentRecord) RevocationSource() ConsentRevocationSource {
return record.revocationSource
}
// OrganizationID, OrganizationName, Fields, InvitationID, and
// InvitationTermsVersion hold the C4 scope and are zero for every other
// purpose. OrganizationName is the name the shown text carried at the time
// of the consent, not the current name of the organization.
func (record ConsentRecord) OrganizationID() uuid.UUID { return record.organizationID }
func (record ConsentRecord) OrganizationName() string { return record.organizationName }
func (record ConsentRecord) Fields() ContactFieldSet { return record.fields }
func (record ConsentRecord) InvitationID() uuid.UUID { return record.invitationID }
func (record ConsentRecord) InvitationTermsVersion() int64 { return record.invitationTermsVersion }
// IsZero reports a record not built by RestoreConsentRecord.
func (record ConsentRecord) IsZero() bool { return record.id == uuid.Nil }
func (record ConsentRecord) String() string {
return fmt.Sprintf("[consent %s %s %s]", record.id, record.purpose, record.state)
}
func (record ConsentRecord) GoString() string { return record.String() }
// Format applies String to every verb; without it %+v would print the
// subject and the scope.
func (record ConsentRecord) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(record.String()))
}
// LogValue carries only the record ID, purpose, and state.
func (record ConsentRecord) LogValue() slog.Value {
return slog.GroupValue(
slog.String("consent_record_id", record.id.String()),
slog.String("purpose", string(record.purpose)),
slog.String("state", string(record.state)),
)
}
func consentLogValue(id uuid.UUID, purpose ConsentPurpose) slog.Value {
return slog.GroupValue(
slog.String("consent_record_id", id.String()),
slog.String("purpose", string(purpose)),
)
}
+437
View File
@@ -0,0 +1,437 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var consentTestTime = time.Date(2026, 10, 6, 9, 30, 0, 0, time.UTC)
const consentTestVersion ConsentTextVersion = "c1-2026-10-01"
func TestParseConsentPurposeAcceptsOnlyC1ToC5(t *testing.T) {
for _, value := range []string{"c1", "c2", "c3", "c4", "c5"} {
purpose, err := ParseConsentPurpose(value)
if err != nil {
t.Fatalf("ParseConsentPurpose(%q) error = %v", value, err)
}
if purpose.OrganizationScoped() != (value == "c4") {
t.Fatalf("%s.OrganizationScoped() = %v, want true only for c4", value, purpose.OrganizationScoped())
}
}
for _, value := range []string{"", "C1", "c0", "c6", "c1 "} {
if _, err := ParseConsentPurpose(value); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("ParseConsentPurpose(%q) error = %v, want ErrInvalidConsent", value, err)
}
}
}
func TestParseConsentTextVersionFollowsTheContractPattern(t *testing.T) {
for _, value := range []string{"c1-2026-10-01", "v1.2_rc", strings.Repeat("a", 64)} {
if _, err := ParseConsentTextVersion(value); err != nil {
t.Fatalf("ParseConsentTextVersion(%q) error = %v", value, err)
}
}
for _, value := range []string{"", " ", "c1 2026", "c1/2026", "версия", strings.Repeat("a", 65)} {
if _, err := ParseConsentTextVersion(value); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("ParseConsentTextVersion(%q) error = %v, want ErrInvalidConsentText", value, err)
}
}
}
func TestConsentTextHashFromBytesRefusesEmptyAndMalformedDigests(t *testing.T) {
valid := HashConsentText("text")
if hash, err := ConsentTextHashFromBytes(valid[:]); err != nil || hash != valid {
t.Fatalf("ConsentTextHashFromBytes(valid) = %x, %v", hash, err)
}
for name, value := range map[string][]byte{
"nil": nil,
"empty": {},
"short": valid[:31],
"long": append(valid[:], 0),
"all zero": make([]byte, ConsentTextHashSize),
} {
if _, err := ConsentTextHashFromBytes(value); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("ConsentTextHashFromBytes(%s) error = %v, want ErrInvalidConsentText", name, err)
}
}
}
func storedText(purpose, body string) StoredConsentText {
hash := HashConsentText(body)
return StoredConsentText{
Purpose: purpose,
Version: purpose + "-2026-10-01",
Body: body,
Hash: hash[:],
Kind: string(ConsentTextKindDemo),
PublishedAt: consentTestTime,
}
}
func TestRestoreConsentTextChecksTheHashAndThePlaceholder(t *testing.T) {
text, err := RestoreConsentText(storedText("c1", "I consent."))
if err != nil {
t.Fatalf("RestoreConsentText(c1) error = %v", err)
}
if text.Hash() != HashConsentText("I consent.") || text.Purpose() != ConsentPurposePersonalData {
t.Fatalf("restored text = %s %x, want the stored purpose and hash", text.Purpose(), text.Hash())
}
tampered := storedText("c1", "I consent.")
tampered.Body = "I consent to more."
changedKind := storedText("c1", "I consent.")
changedKind.Kind = "draft"
for name, stored := range map[string]StoredConsentText{
"body changed after hashing": tampered,
"C4 without the placeholder": storedText("c4", "I consent to the transfer."),
"C2 with the placeholder": storedText("c2", "I consent for {organization}."),
"unknown kind": changedKind,
"empty body": storedText("c3", ""),
} {
if _, err := RestoreConsentText(stored); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("RestoreConsentText(%s) error = %v, want ErrInvalidConsentText", name, err)
}
}
}
func TestRenderForOrganizationNamesTheOrganizationOnlyInC4(t *testing.T) {
contact, err := RestoreConsentText(storedText("c4", "I consent to the transfer to {organization}."))
if err != nil {
t.Fatalf("RestoreConsentText(c4) error = %v", err)
}
shown, err := contact.RenderForOrganization("ООО Пример")
if err != nil {
t.Fatalf("RenderForOrganization() error = %v", err)
}
if shown != "I consent to the transfer to ООО Пример." {
t.Fatalf("RenderForOrganization() = %q", shown)
}
// The ledger stores the hash of the shown text, which differs per
// organization and from the hash of the published template.
other, err := contact.RenderForOrganization("Other LLC")
if err != nil {
t.Fatalf("RenderForOrganization(other) error = %v", err)
}
if HashConsentText(shown) == contact.Hash() || HashConsentText(shown) == HashConsentText(other) {
t.Fatal("the shown C4 text must hash differently per organization and from the template")
}
for _, name := range []string{"", " Leading", "Trailing ", "Two\nlines", strings.Repeat("я", 201)} {
if _, err := contact.RenderForOrganization(name); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("RenderForOrganization(%q) error = %v, want ErrInvalidConsentText", name, err)
}
}
personalData, err := RestoreConsentText(storedText("c1", "I consent."))
if err != nil {
t.Fatalf("RestoreConsentText(c1) error = %v", err)
}
if _, err := personalData.RenderForOrganization("Acme"); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("RenderForOrganization(C1) error = %v, want ErrInvalidConsentText", err)
}
}
func TestNewContactFieldSetIsCanonicalAndRefusesDuplicates(t *testing.T) {
set, err := NewContactFieldSet(ContactFieldTelegram, ContactFieldEmail, ContactFieldFullName)
if err != nil {
t.Fatalf("NewContactFieldSet() error = %v", err)
}
reordered, err := NewContactFieldSet(ContactFieldFullName, ContactFieldTelegram, ContactFieldEmail)
if err != nil {
t.Fatalf("NewContactFieldSet(reordered) error = %v", err)
}
if !set.Equal(reordered) || fmt.Sprint(set.Fields()) != "[email full_name telegram]" {
t.Fatalf("Fields() = %v, want the canonical order for any input order", set.Fields())
}
if set.Contains(ContactFieldPhone) {
t.Fatal("one field must never imply another")
}
fields := set.Fields()
fields[0] = ContactFieldPhone
if set.Contains(ContactFieldPhone) {
t.Fatal("Fields() must return a copy")
}
for name, input := range map[string][]ContactField{
"empty": nil,
"duplicate": {ContactFieldEmail, ContactFieldEmail},
"unknown": {ContactFieldEmail, "address"},
"too many": {ContactFieldEmail, ContactFieldPhone, ContactFieldTelegram, ContactFieldFullName, ContactFieldEmail},
} {
if _, err := NewContactFieldSet(input...); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("NewContactFieldSet(%s) error = %v, want ErrInvalidConsent", name, err)
}
}
}
func validGrantInput() ConsentGrantInput {
return ConsentGrantInput{
SubjectID: uuid.Must(uuid.NewV7()),
Purpose: ConsentPurposePersonalData,
TextVersion: consentTestVersion,
TextHash: HashConsentText("I consent."),
Source: ConsentSourceRegistration,
GrantedAt: consentTestTime,
}
}
func TestNewConsentGrantValidatesEveryField(t *testing.T) {
grant, err := NewConsentGrant(validGrantInput())
if err != nil {
t.Fatalf("NewConsentGrant() error = %v", err)
}
if grant.ID().Version() != 7 || grant.Purpose() != ConsentPurposePersonalData || grant.IsZero() {
t.Fatalf("grant = %s %s, want a UUIDv7 C1 grant", grant.ID(), grant.Purpose())
}
for name, change := range map[string]func(*ConsentGrantInput){
"C4 without its scope": func(input *ConsentGrantInput) {
input.Purpose, input.Source = ConsentPurposeContactDisclosure, ConsentSourceInvitationAcceptance
},
"unknown purpose": func(input *ConsentGrantInput) { input.Purpose = "c9" },
"empty text version": func(input *ConsentGrantInput) { input.TextVersion = "" },
"malformed text version": func(input *ConsentGrantInput) { input.TextVersion = "c1 v2" },
"missing text hash": func(input *ConsentGrantInput) { input.TextHash = ConsentTextHash{} },
"missing subject": func(input *ConsentGrantInput) { input.SubjectID = uuid.Nil },
"registration of C2": func(input *ConsentGrantInput) { input.Purpose = ConsentPurposePublication },
"invitation acceptance of C3": func(input *ConsentGrantInput) {
input.Purpose, input.Source = ConsentPurposeAutoCategorization, ConsentSourceInvitationAcceptance
},
"unknown source": func(input *ConsentGrantInput) { input.Source = "import" },
"missing grant time": func(input *ConsentGrantInput) { input.GrantedAt = time.Time{} },
} {
input := validGrantInput()
change(&input)
_, err := NewConsentGrant(input)
if !errors.Is(err, ErrInvalidConsent) && !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("NewConsentGrant(%s) error = %v, want a validation error", name, err)
}
}
}
const consentTestC4Body = "I consent to the transfer to {organization}."
func contactText(t *testing.T) ConsentText {
t.Helper()
text, err := RestoreConsentText(storedText("c4", consentTestC4Body))
if err != nil {
t.Fatalf("RestoreConsentText(c4) error = %v", err)
}
return text
}
func validContactGrantInput(t *testing.T) ContactConsentGrantInput {
t.Helper()
fields, err := NewContactFieldSet(ContactFieldEmail)
if err != nil {
t.Fatalf("NewContactFieldSet() error = %v", err)
}
return ContactConsentGrantInput{
SubjectID: uuid.Must(uuid.NewV7()),
OrganizationID: uuid.Must(uuid.NewV7()),
OrganizationName: "Acme",
Fields: fields,
InvitationID: uuid.Must(uuid.NewV7()),
InvitationTermsVersion: 2,
Text: contactText(t),
GrantedAt: consentTestTime,
}
}
func TestNewContactConsentGrantRequiresItsScope(t *testing.T) {
grant, err := NewContactConsentGrant(validContactGrantInput(t))
if err != nil {
t.Fatalf("NewContactConsentGrant() error = %v", err)
}
if grant.IsZero() || !grant.Fields().Contains(ContactFieldEmail) || grant.InvitationTermsVersion() != 2 ||
grant.OrganizationName() != "Acme" || grant.TextVersion() != "c4-2026-10-01" {
t.Fatalf("grant = %s, want the given scope", grant.ID())
}
// The grant hashes the text as shown for the organization; a caller
// never supplies hash bytes.
if grant.TextHash() != HashConsentText("I consent to the transfer to Acme.") {
t.Fatalf("TextHash() = %x, want the hash of the shown text", grant.TextHash())
}
personalData, err := RestoreConsentText(storedText("c1", "I consent."))
if err != nil {
t.Fatalf("RestoreConsentText(c1) error = %v", err)
}
for name, change := range map[string]func(*ContactConsentGrantInput){
"missing organization": func(input *ContactConsentGrantInput) { input.OrganizationID = uuid.Nil },
"missing organization name": func(input *ContactConsentGrantInput) { input.OrganizationName = "" },
"multi-line name": func(input *ContactConsentGrantInput) { input.OrganizationName = "Acme\nLLC" },
"missing field set": func(input *ContactConsentGrantInput) { input.Fields = ContactFieldSet{} },
"missing invitation": func(input *ContactConsentGrantInput) { input.InvitationID = uuid.Nil },
"non-positive terms version": func(input *ContactConsentGrantInput) { input.InvitationTermsVersion = 0 },
"missing subject": func(input *ContactConsentGrantInput) { input.SubjectID = uuid.Nil },
"missing text": func(input *ContactConsentGrantInput) { input.Text = ConsentText{} },
"text of another purpose": func(input *ContactConsentGrantInput) { input.Text = personalData },
"missing grant time": func(input *ContactConsentGrantInput) { input.GrantedAt = time.Time{} },
} {
input := validContactGrantInput(t)
change(&input)
_, err := NewContactConsentGrant(input)
if !errors.Is(err, ErrInvalidConsent) && !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("NewContactConsentGrant(%s) error = %v, want a validation error", name, err)
}
}
}
func TestGrantsAndRevocationsShowNoSubjectOrScope(t *testing.T) {
input := validContactGrantInput(t)
contact, err := NewContactConsentGrant(input)
if err != nil {
t.Fatalf("NewContactConsentGrant() error = %v", err)
}
personalInput := validGrantInput()
personal, err := NewConsentGrant(personalInput)
if err != nil {
t.Fatalf("NewConsentGrant() error = %v", err)
}
revocation, err := NewConsentRevocation(ConsentRevocationInput{
SubjectID: input.SubjectID, Purpose: ConsentPurposeContactDisclosure, OrganizationID: input.OrganizationID,
Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime,
})
if err != nil {
t.Fatalf("NewConsentRevocation() error = %v", err)
}
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
logger.Info("consent", "contact", contact, "personal", personal, "revocation", revocation)
output := logs.String() + fmt.Sprintf("%v %+v %#v %+v %+v", contact, contact, personal, revocation, struct{ Grant ContactConsentGrant }{contact})
for _, private := range []string{
input.SubjectID.String(), input.OrganizationID.String(), input.InvitationID.String(),
personalInput.SubjectID.String(), "Acme", "email",
} {
if strings.Contains(output, private) {
t.Fatalf("output %q contains %q", output, private)
}
}
}
func TestNewConsentRevocationScopesOnlyC4ByOrganization(t *testing.T) {
subject, organization := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
valid := []ConsentRevocationInput{
{SubjectID: subject, Purpose: ConsentPurposePublication, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime},
{SubjectID: subject, Purpose: ConsentPurposeContactDisclosure, OrganizationID: organization, Source: ConsentRevocationSourceSupportRequest, RevokedAt: consentTestTime},
}
for _, input := range valid {
if _, err := NewConsentRevocation(input); err != nil {
t.Fatalf("NewConsentRevocation(%s) error = %v", input.Purpose, err)
}
}
for name, input := range map[string]ConsentRevocationInput{
"C4 without an organization": {SubjectID: subject, Purpose: ConsentPurposeContactDisclosure, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime},
"C1 with an organization": {SubjectID: subject, Purpose: ConsentPurposePersonalData, OrganizationID: organization, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime},
"unknown source": {SubjectID: subject, Purpose: ConsentPurposePersonalData, Source: "admin", RevokedAt: consentTestTime},
"missing subject": {Purpose: ConsentPurposePersonalData, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime},
"missing time": {SubjectID: subject, Purpose: ConsentPurposePersonalData, Source: ConsentRevocationSourceConsentSettings},
} {
if _, err := NewConsentRevocation(input); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("NewConsentRevocation(%s) error = %v, want ErrInvalidConsent", name, err)
}
}
}
func storedRecord(purpose string) StoredConsentRecord {
hash := HashConsentText("shown text")
record := StoredConsentRecord{
ID: uuid.Must(uuid.NewV7()),
SubjectID: uuid.Must(uuid.NewV7()),
Purpose: purpose,
TextVersion: purpose + "-2026-10-01",
TextHash: hash[:],
Source: string(ConsentSourceConsentSettings),
State: string(ConsentStateActive),
GrantedAt: consentTestTime,
}
if purpose == "c4" {
record.Source = string(ConsentSourceInvitationAcceptance)
record.OrganizationID = uuid.Must(uuid.NewV7())
record.OrganizationName = "Acme"
record.FieldSet = []string{"phone", "email"}
record.InvitationID = uuid.Must(uuid.NewV7())
record.InvitationTermsVersion = 1
}
return record
}
func TestRestoreConsentRecordMirrorsTheLedgerConstraints(t *testing.T) {
for _, purpose := range []string{"c1", "c2", "c3", "c4", "c5"} {
if _, err := RestoreConsentRecord(storedRecord(purpose)); err != nil {
t.Fatalf("RestoreConsentRecord(%s) error = %v", purpose, err)
}
}
revokedAt := consentTestTime.Add(time.Hour)
earlier := consentTestTime.Add(-time.Hour)
for name, change := range map[string]func(*StoredConsentRecord){
"C4 without an organization": func(record *StoredConsentRecord) { record.OrganizationID = uuid.Nil },
"C4 without its name snapshot": func(record *StoredConsentRecord) { record.OrganizationName = "" },
"C4 with an empty field set": func(record *StoredConsentRecord) { record.FieldSet = []string{} },
"C4 superseded": func(record *StoredConsentRecord) {
record.State = string(ConsentStateSuperseded)
},
"C4 from the settings": func(record *StoredConsentRecord) { record.Source = string(ConsentSourceConsentSettings) },
"revoked state without a stamp": func(record *StoredConsentRecord) {
record.State = string(ConsentStateRevoked)
},
"stamp without a source": func(record *StoredConsentRecord) {
record.RevokedAt, record.State = &revokedAt, string(ConsentStateRevoked)
},
"revocation before the grant": func(record *StoredConsentRecord) {
record.RevokedAt, record.RevocationSource, record.State = &earlier, string(ConsentRevocationSourceConsentSettings), string(ConsentStateRevoked)
},
"empty hash": func(record *StoredConsentRecord) { record.TextHash = nil },
"empty version": func(record *StoredConsentRecord) { record.TextVersion = "" },
"unknown state": func(record *StoredConsentRecord) { record.State = "pending" },
} {
record := storedRecord("c4")
change(&record)
_, err := RestoreConsentRecord(record)
if !errors.Is(err, ErrInvalidConsent) && !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("RestoreConsentRecord(%s) error = %v, want a validation error", name, err)
}
}
scoped := storedRecord("c3")
scoped.FieldSet = []string{"email"}
if _, err := RestoreConsentRecord(scoped); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("RestoreConsentRecord(C3 with fields) error = %v, want ErrInvalidConsent", err)
}
named := storedRecord("c1")
named.OrganizationName = "Acme"
if _, err := RestoreConsentRecord(named); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("RestoreConsentRecord(C1 with an organization name) error = %v, want ErrInvalidConsent", err)
}
}
func TestConsentRecordOutputShowsNoSubjectOrScope(t *testing.T) {
stored := storedRecord("c4")
record, err := RestoreConsentRecord(stored)
if err != nil {
t.Fatalf("RestoreConsentRecord() error = %v", err)
}
var logs bytes.Buffer
for _, logger := range []*slog.Logger{
slog.New(slog.NewTextHandler(&logs, nil)),
slog.New(slog.NewJSONHandler(&logs, nil)),
} {
logger.Info("consent", "record", record)
}
output := strings.Join([]string{
logs.String(),
fmt.Sprintf("%v %+v %#v %s", record, record, record, record),
fmt.Sprintf("%+v", struct{ Record ConsentRecord }{record}),
}, "\n")
for _, private := range []string{stored.SubjectID.String(), stored.OrganizationID.String(), stored.InvitationID.String(), "phone", "Acme"} {
if strings.Contains(output, private) {
t.Fatalf("output %q contains %q", output, private)
}
}
if !strings.Contains(output, record.ID().String()) || !strings.Contains(output, "c4") {
t.Fatalf("output %q, want the record ID and purpose", output)
}
}
+160
View File
@@ -0,0 +1,160 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrConsentTextNotFound reports that no text has the purpose and
// version, or no text of the purpose is published at the time.
ErrConsentTextNotFound = errors.New("consent text not found")
// ErrConsentTextMismatch reports a grant whose hash is not the hash of
// the published text of its version: for C1-C3 and C5 the text itself,
// for C4 the text with the stored organization name filled in.
ErrConsentTextMismatch = errors.New("consent text hash does not match the published text")
// ErrConsentTextNotPublished reports a grant for a text version whose
// publication time is after the grant time.
ErrConsentTextNotPublished = errors.New("consent text not published at the grant time")
// ErrConsentNotFound reports that the subject has no unrevoked record of
// the purpose.
ErrConsentNotFound = errors.New("consent not found")
// ErrConsentInvitationTaken reports a C4 grant for an invitation whose C4
// record belongs to another subject. Nothing was stored.
ErrConsentInvitationTaken = errors.New("invitation consent belongs to another subject")
// ErrConsentRecordImmutable reports an attempt to change a record other
// than by its one revocation stamp, or to delete a record of a confirmed
// account. The database refuses both.
ErrConsentRecordImmutable = errors.New("consent record is immutable")
)
// ConsentRepositories exposes the consent texts and the consent ledger.
// UnitOfWork binds them to one transaction, so a business operation records
// a consent atomically with its own changes: the registration with C1, the
// invitation acceptance with C4. An adapter may also provide them outside a
// transaction, where every call is its own statement. Every method that
// takes a time rejects the zero time.
type ConsentRepositories interface {
ConsentTexts() ConsentTextRepository
ConsentLedger() ConsentLedger
}
// ConsentTextRepository reads the immutable published consent texts. It has
// no write method: texts are published by migrations.
type ConsentTextRepository interface {
// Get returns the text with the purpose and version, published or
// scheduled, or ErrConsentTextNotFound.
Get(ctx context.Context, purpose domain.ConsentPurpose, version domain.ConsentTextVersion) (domain.ConsentText, error)
// Current returns the text of the purpose with the latest publication
// time not after at, or ErrConsentTextNotFound.
Current(ctx context.Context, purpose domain.ConsentPurpose, at time.Time) (domain.ConsentText, error)
}
// ConsentLedger stores the append-only consent ledger. A grant is a new
// record; history is never rewritten except for the one revocation stamp of
// a record. Every read and every revocation is scoped by the subject, so a
// caller cannot reach another subject's records through it.
//
// A grant binds the record to a stored text version: an unknown version
// fails with ErrConsentTextNotFound, a version published after the grant
// time with ErrConsentTextNotPublished, and, for C1-C3 and C5, a hash other
// than the hash of that text with ErrConsentTextMismatch. An unknown subject
// fails with ErrUserNotFound. These failures come from the database and
// abort a surrounding transaction.
type ConsentLedger interface {
// Grant records a grant of C1, C2, C3, or C5 and returns the record
// with created true. When the subject already has an unrevoked record of
// the purpose and text version, it returns that record with created
// false and stores nothing, without aborting a surrounding transaction.
// A grant of another version is a new record next to the earlier one.
// Superseded is decided by granted_at, then the record ID: the
// unrevoked record granted last is active, whatever its text version,
// so Grant accepts any published version. The grant usecase (TASK-063)
// must check that the version is the current text of the purpose,
// ConsentTexts().Current at the grant time, before it calls Grant.
Grant(ctx context.Context, grant domain.ConsentGrant) (record domain.ConsentRecord, created bool, err error)
// GrantContact records the C4 grant of an invitation acceptance with its
// organization, the organization name as the shown text named it, the
// field set, the invitation, and the terms version. The database checks
// that the hash is the hash of the published text with that name, so the
// stored name is the snapshot a later rename never changes. It is meant to
// run in the acceptance transaction next to the state change, the grant,
// and the audit event, so all of them commit or roll back together.
// When the invitation already has a C4 record of the same subject, it
// returns that record, revoked or not, with created false and stores
// nothing; the caller compares its scope to decide between a repeat and
// a conflict. When the record belongs to another subject it returns
// ErrConsentInvitationTaken. Neither case aborts the transaction.
GrantContact(ctx context.Context, grant domain.ContactConsentGrant) (record domain.ConsentRecord, created bool, err error)
// Revoke stamps every unrevoked record of the revocation's purpose, and
// for C4 of its organization only, with the revocation time and source,
// and returns the revoked records. Superseded records of the purpose are
// revoked too. Records that are already revoked keep their first stamp;
// with nothing to revoke the result is empty, so a repeat is harmless.
// A later grant is a new record. A revocation time before the grant
// time of a record, from clock skew between instances, is stamped at
// the grant time.
Revoke(ctx context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error)
// Current returns the newest unrevoked record of C1, C2, C3, or C5, or
// ErrConsentNotFound. C4 fails with domain.ErrInvalidConsent; use
// CurrentContact.
Current(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error)
// CurrentContact returns the unrevoked C4 records of the subject for the
// organization, newest first, one per accepted invitation. The result
// is empty when there is none.
CurrentContact(ctx context.Context, subjectID uuid.UUID, organizationID uuid.UUID) ([]domain.ConsentRecord, error)
// List returns one page of the subject's records, newest grant first,
// with the state of each record. It is the read model of the subject's
// own consents and history.
List(ctx context.Context, query ConsentListQuery) (ConsentPage, error)
}
// ConsentListQuery selects one page of a subject's ledger.
type ConsentListQuery struct {
SubjectID uuid.UUID
// State limits the page to one state; empty selects every record.
State domain.ConsentState
// After continues after the position of the last record of the previous
// page; nil reads the first page.
After *ConsentListPosition
// Limit is the page size, from 1 to MaxConsentPageSize.
Limit int32
}
// MaxConsentPageSize matches the largest page of the contract.
const MaxConsentPageSize = 100
// ConsentListPosition is the ordering key of a record in List.
type ConsentListPosition struct {
GrantedAt time.Time
ID uuid.UUID
}
// ConsentPositionOf returns the ordering key of record for the next page.
func ConsentPositionOf(record domain.ConsentRecord) ConsentListPosition {
return ConsentListPosition{GrantedAt: record.GrantedAt(), ID: record.ID()}
}
// ConsentPage is one page of List.
type ConsentPage struct {
Records []domain.ConsentRecord
// HasMore reports that another page follows; read it with After set to
// the position of the last record.
HasMore bool
}
+15 -5
View File
@@ -88,6 +88,13 @@ type UserRepository interface {
// RegistrationVersion by one, so callers never choose the registration
// version; the returned account carries the new values. Otherwise it
// returns ErrUserVersionConflict.
//
// The same statement deletes the C1 records with the source
// registration that the earlier registration of this account stored,
// because the earlier registrant's consent must never stand for the new
// one. The registration usecase (TASK-053) must record the new C1 with
// ConsentLedger().Grant in the same transaction; a version conflict
// deletes nothing.
UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error)
// MarkEmailVerified sets the verification time when the account is still
@@ -99,11 +106,14 @@ type UserRepository interface {
// DeleteUnverifiedRegisteredBefore deletes at most limit accounts that are
// unverified and were last registered before cutoff, oldest first, with
// their tokens, sessions, and mail deliveries, and returns how many it
// deleted. It never waits for a lock: an account whose row, token,
// session, or delivery is locked by another transaction is skipped and
// stays for the next run. A cleanup job
// repeats it until the result is below limit and runs again later.
// their tokens, sessions, mail deliveries, and consent records, and
// returns how many it deleted. It never waits for a lock: an account
// whose row, token, session, delivery, or consent record is locked by
// another transaction is skipped and stays for the next run. A consent
// recorded for a candidate account after the statement started fails the
// restricting foreign key; the run then returns an error matching
// ErrTransactionConflict, deletes nothing, and may be repeated. A cleanup
// job repeats it until the result is below limit and runs again later.
DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error)
}
@@ -49,6 +49,7 @@ type Transactor interface {
// repositories are added here as their usecases appear.
type UnitOfWork interface {
IdentityRepositories
ConsentRepositories
Policies() PolicyRepository
Deliveries() DeliveryRepository
MailRequests() MailRequestRepository