feat(consent): add versioned append-only consent ledger C1-C5
This commit is contained in:
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)
|
||||
Reference in new issue
Block a user