feat(accounts): add consent settings and organization management

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 13:00:39 +03:00
1 parent 24638d46d2
commit 391af7a1ef
83 files changed
+10198 -613

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -69,6 +69,10 @@ type GetMyCardPreviewRes interface {
getMyCardPreviewRes()
}
type GetMyConsentTextRes interface {
getMyConsentTextRes()
}
type GetMyInvitationRes interface {
getMyInvitationRes()
}
@@ -105,6 +109,10 @@ type GetOrganizationRes interface {
getOrganizationRes()
}
type GrantMyConsentRes interface {
grantMyConsentRes()
}
type HideOrganizationRes interface {
hideOrganizationRes()
}
@@ -161,10 +169,22 @@ type RegisterAccountRes interface {
registerAccountRes()
}
type RequestMyAccountDeletionRes interface {
requestMyAccountDeletionRes()
}
type ResendEmailVerificationRes interface {
resendEmailVerificationRes()
}
type RevokeMyConsentRes interface {
revokeMyConsentRes()
}
type RevokeMyOrganizationContactConsentRes interface {
revokeMyOrganizationContactConsentRes()
}
type SaveMyProfileRes interface {
saveMyProfileRes()
}
@@ -12492,6 +12492,172 @@ func (s *ConfirmEmailForbidden) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ConsentDeletionRequest) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ConsentDeletionRequest) encodeFields(e *jx.Encoder) {
{
e.FieldStart("id")
json.EncodeUUID(e, s.ID)
}
{
e.FieldStart("status")
s.Status.Encode(e)
}
{
e.FieldStart("requested_at")
s.RequestedAt.Encode(e)
}
}
var jsonFieldsNameOfConsentDeletionRequest = [3]string{
0: "id",
1: "status",
2: "requested_at",
}
// Decode decodes ConsentDeletionRequest from json.
func (s *ConsentDeletionRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentDeletionRequest 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 "status":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.Status.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"status\"")
}
case "requested_at":
requiredBitSet[0] |= 1 << 2
if err := func() error {
if err := s.RequestedAt.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"requested_at\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ConsentDeletionRequest")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000111,
} {
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(jsonFieldsNameOfConsentDeletionRequest) {
name = jsonFieldsNameOfConsentDeletionRequest[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 *ConsentDeletionRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentDeletionRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConsentDeletionRequestStatus as json.
func (s ConsentDeletionRequestStatus) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ConsentDeletionRequestStatus from json.
func (s *ConsentDeletionRequestStatus) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentDeletionRequestStatus to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ConsentDeletionRequestStatus(v) {
case ConsentDeletionRequestStatusRequested:
*s = ConsentDeletionRequestStatusRequested
case ConsentDeletionRequestStatusProcessing:
*s = ConsentDeletionRequestStatusProcessing
default:
*s = ConsentDeletionRequestStatus(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s ConsentDeletionRequestStatus) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentDeletionRequestStatus) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ConsentOrganization) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -12605,44 +12771,6 @@ func (s *ConsentOrganization) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes ConsentPurpose as json.
func (s ConsentPurpose) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ConsentPurpose from json.
func (s *ConsentPurpose) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentPurpose to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ConsentPurpose(v) {
case ConsentPurposeC1:
*s = ConsentPurposeC1
default:
*s = ConsentPurpose(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s ConsentPurpose) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentPurpose) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConsentPurposeCode as json.
func (s ConsentPurposeCode) Encode(e *jx.Encoder) {
e.Str(string(s))
@@ -13135,6 +13263,147 @@ func (s *ConsentRevocationSource) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ConsentSettingsGrantRequest) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ConsentSettingsGrantRequest) encodeFields(e *jx.Encoder) {
{
e.FieldStart("text_version")
s.TextVersion.Encode(e)
}
{
e.FieldStart("accepted")
s.Accepted.Encode(e)
}
}
var jsonFieldsNameOfConsentSettingsGrantRequest = [2]string{
0: "text_version",
1: "accepted",
}
// Decode decodes ConsentSettingsGrantRequest from json.
func (s *ConsentSettingsGrantRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentSettingsGrantRequest to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "text_version":
requiredBitSet[0] |= 1 << 0
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 "accepted":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.Accepted.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"accepted\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ConsentSettingsGrantRequest")
}
// 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(jsonFieldsNameOfConsentSettingsGrantRequest) {
name = jsonFieldsNameOfConsentSettingsGrantRequest[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 *ConsentSettingsGrantRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentSettingsGrantRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ConsentSettingsGrantRequestAccepted as json.
func (s ConsentSettingsGrantRequestAccepted) Encode(e *jx.Encoder) {
e.Bool(bool(s))
}
// Decode decodes ConsentSettingsGrantRequestAccepted from json.
func (s *ConsentSettingsGrantRequestAccepted) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ConsentSettingsGrantRequestAccepted to nil")
}
v, err := d.Bool()
if err != nil {
return err
}
*s = ConsentSettingsGrantRequestAccepted(v)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s ConsentSettingsGrantRequestAccepted) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ConsentSettingsGrantRequestAccepted) 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))
@@ -17436,6 +17705,82 @@ func (s *GetMyCardPreviewUnauthorized) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes GetMyConsentTextBadRequest as json.
func (s *GetMyConsentTextBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes GetMyConsentTextBadRequest from json.
func (s *GetMyConsentTextBadRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode GetMyConsentTextBadRequest 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 = GetMyConsentTextBadRequest(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *GetMyConsentTextBadRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *GetMyConsentTextBadRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes GetMyConsentTextUnauthorized as json.
func (s *GetMyConsentTextUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes GetMyConsentTextUnauthorized from json.
func (s *GetMyConsentTextUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode GetMyConsentTextUnauthorized 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 = GetMyConsentTextUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *GetMyConsentTextUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *GetMyConsentTextUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes GetMyInvitationBadRequest as json.
func (s *GetMyInvitationBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
@@ -18582,6 +18927,120 @@ func (s *GradeCode) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes GrantMyConsentBadRequest as json.
func (s *GrantMyConsentBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes GrantMyConsentBadRequest from json.
func (s *GrantMyConsentBadRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode GrantMyConsentBadRequest 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 = GrantMyConsentBadRequest(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *GrantMyConsentBadRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *GrantMyConsentBadRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes GrantMyConsentForbidden as json.
func (s *GrantMyConsentForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes GrantMyConsentForbidden from json.
func (s *GrantMyConsentForbidden) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode GrantMyConsentForbidden 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 = GrantMyConsentForbidden(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *GrantMyConsentForbidden) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *GrantMyConsentForbidden) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes GrantMyConsentUnauthorized as json.
func (s *GrantMyConsentUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes GrantMyConsentUnauthorized from json.
func (s *GrantMyConsentUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode GrantMyConsentUnauthorized 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 = GrantMyConsentUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *GrantMyConsentUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *GrantMyConsentUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *HealthResponse) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -43764,6 +44223,82 @@ func (s *RegistrationRequest) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes RequestMyAccountDeletionForbidden as json.
func (s *RequestMyAccountDeletionForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes RequestMyAccountDeletionForbidden from json.
func (s *RequestMyAccountDeletionForbidden) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode RequestMyAccountDeletionForbidden 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 = RequestMyAccountDeletionForbidden(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *RequestMyAccountDeletionForbidden) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *RequestMyAccountDeletionForbidden) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes RequestMyAccountDeletionUnauthorized as json.
func (s *RequestMyAccountDeletionUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes RequestMyAccountDeletionUnauthorized from json.
func (s *RequestMyAccountDeletionUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode RequestMyAccountDeletionUnauthorized 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 = RequestMyAccountDeletionUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *RequestMyAccountDeletionUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *RequestMyAccountDeletionUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ResendEmailVerificationBadRequest as json.
func (s *ResendEmailVerificationBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
@@ -43840,6 +44375,158 @@ func (s *ResendEmailVerificationForbidden) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes RevokeMyConsentForbidden as json.
func (s *RevokeMyConsentForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes RevokeMyConsentForbidden from json.
func (s *RevokeMyConsentForbidden) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode RevokeMyConsentForbidden 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 = RevokeMyConsentForbidden(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *RevokeMyConsentForbidden) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *RevokeMyConsentForbidden) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes RevokeMyConsentUnauthorized as json.
func (s *RevokeMyConsentUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes RevokeMyConsentUnauthorized from json.
func (s *RevokeMyConsentUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode RevokeMyConsentUnauthorized 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 = RevokeMyConsentUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *RevokeMyConsentUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *RevokeMyConsentUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes RevokeMyOrganizationContactConsentForbidden as json.
func (s *RevokeMyOrganizationContactConsentForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes RevokeMyOrganizationContactConsentForbidden from json.
func (s *RevokeMyOrganizationContactConsentForbidden) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode RevokeMyOrganizationContactConsentForbidden 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 = RevokeMyOrganizationContactConsentForbidden(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *RevokeMyOrganizationContactConsentForbidden) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *RevokeMyOrganizationContactConsentForbidden) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes RevokeMyOrganizationContactConsentUnauthorized as json.
func (s *RevokeMyOrganizationContactConsentUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes RevokeMyOrganizationContactConsentUnauthorized from json.
func (s *RevokeMyOrganizationContactConsentUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode RevokeMyOrganizationContactConsentUnauthorized 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 = RevokeMyOrganizationContactConsentUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *RevokeMyOrganizationContactConsentUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *RevokeMyOrganizationContactConsentUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes RubAmount as json.
func (s RubAmount) Encode(e *jx.Encoder) {
unwrapped := int64(s)
@@ -6,60 +6,65 @@ package api
type OperationName = string
const (
AcceptMyInvitationOperation OperationName = "AcceptMyInvitation"
CancelMyInvitationOperation OperationName = "CancelMyInvitation"
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt"
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyCardPreviewOperation OperationName = "GetMyCardPreview"
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyPrivacySettingsOperation OperationName = "GetMyPrivacySettings"
GetMyProfileOperation OperationName = "GetMyProfile"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
HideOrganizationOperation OperationName = "HideOrganization"
ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory"
ListMyConsentsOperation OperationName = "ListMyConsents"
ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RegisterAccountOperation OperationName = "RegisterAccount"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
SaveMyProfileOperation OperationName = "SaveMyProfile"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SetMyPublicationOperation OperationName = "SetMyPublication"
SetMySearchStatusOperation OperationName = "SetMySearchStatus"
StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UnhideOrganizationOperation OperationName = "UnhideOrganization"
UpdateOrganizationOperation OperationName = "UpdateOrganization"
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
WithdrawOrganizationInvitationOperation OperationName = "WithdrawOrganizationInvitation"
AcceptMyInvitationOperation OperationName = "AcceptMyInvitation"
CancelMyInvitationOperation OperationName = "CancelMyInvitation"
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt"
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyCardPreviewOperation OperationName = "GetMyCardPreview"
GetMyConsentTextOperation OperationName = "GetMyConsentText"
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyPrivacySettingsOperation OperationName = "GetMyPrivacySettings"
GetMyProfileOperation OperationName = "GetMyProfile"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
GrantMyConsentOperation OperationName = "GrantMyConsent"
HideOrganizationOperation OperationName = "HideOrganization"
ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory"
ListMyConsentsOperation OperationName = "ListMyConsents"
ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RegisterAccountOperation OperationName = "RegisterAccount"
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
RevokeMyConsentOperation OperationName = "RevokeMyConsent"
RevokeMyOrganizationContactConsentOperation OperationName = "RevokeMyOrganizationContactConsent"
SaveMyProfileOperation OperationName = "SaveMyProfile"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SetMyPublicationOperation OperationName = "SetMyPublication"
SetMySearchStatusOperation OperationName = "SetMySearchStatus"
StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UnhideOrganizationOperation OperationName = "UnhideOrganization"
UpdateOrganizationOperation OperationName = "UpdateOrganization"
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
WithdrawOrganizationInvitationOperation OperationName = "WithdrawOrganizationInvitation"
)
@@ -1498,6 +1498,80 @@ func decodeGetMyAssessmentResultParams(args [1]string, argsEscaped bool, r *http
return params, nil
}
// GetMyConsentTextParams is parameters of GetMyConsentText operation.
type GetMyConsentTextParams struct {
// Consent whose current text is requested.
Purpose ConsentSettingsPurpose
}
func unpackGetMyConsentTextParams(packed middleware.Parameters) (params GetMyConsentTextParams) {
{
key := middleware.ParameterKey{
Name: "purpose",
In: "path",
}
params.Purpose = packed[key].(ConsentSettingsPurpose)
}
return params
}
func decodeGetMyConsentTextParams(args [1]string, argsEscaped bool, r *http.Request) (params GetMyConsentTextParams, _ error) {
// Decode path: purpose.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "purpose",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.Purpose = ConsentSettingsPurpose(c)
return nil
}(); err != nil {
return err
}
if err := func() error {
if err := params.Purpose.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "purpose",
In: "path",
Err: err,
}
}
return params, nil
}
// GetMyInvitationParams is parameters of GetMyInvitation operation.
type GetMyInvitationParams struct {
// Identifier of an invitation addressed to the current candidate. A draft, an invitation addressed to
@@ -2074,6 +2148,80 @@ func decodeGetOrganizationNeedParams(args [2]string, argsEscaped bool, r *http.R
return params, nil
}
// GrantMyConsentParams is parameters of GrantMyConsent operation.
type GrantMyConsentParams struct {
// Independent consent being granted. C4 is not available here.
Purpose ConsentSettingsPurpose
}
func unpackGrantMyConsentParams(packed middleware.Parameters) (params GrantMyConsentParams) {
{
key := middleware.ParameterKey{
Name: "purpose",
In: "path",
}
params.Purpose = packed[key].(ConsentSettingsPurpose)
}
return params
}
func decodeGrantMyConsentParams(args [1]string, argsEscaped bool, r *http.Request) (params GrantMyConsentParams, _ error) {
// Decode path: purpose.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "purpose",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.Purpose = ConsentSettingsPurpose(c)
return nil
}(); err != nil {
return err
}
if err := func() error {
if err := params.Purpose.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "purpose",
In: "path",
Err: err,
}
}
return params, nil
}
// HideOrganizationParams is parameters of HideOrganization operation.
type HideOrganizationParams struct {
// Identifier of the organization that the current candidate hides or stops hiding the profile from. It
@@ -4209,6 +4357,147 @@ func decodeRegisterAccountParams(args [0]string, argsEscaped bool, r *http.Reque
return params, nil
}
// RevokeMyConsentParams is parameters of RevokeMyConsent operation.
type RevokeMyConsentParams struct {
// Consent being revoked. C1 has a deletion-request operation and C4 requires an organization scope.
Purpose ConsentSettingsRevokePurpose
}
func unpackRevokeMyConsentParams(packed middleware.Parameters) (params RevokeMyConsentParams) {
{
key := middleware.ParameterKey{
Name: "purpose",
In: "path",
}
params.Purpose = packed[key].(ConsentSettingsRevokePurpose)
}
return params
}
func decodeRevokeMyConsentParams(args [1]string, argsEscaped bool, r *http.Request) (params RevokeMyConsentParams, _ error) {
// Decode path: purpose.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "purpose",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.Purpose = ConsentSettingsRevokePurpose(c)
return nil
}(); err != nil {
return err
}
if err := func() error {
if err := params.Purpose.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "purpose",
In: "path",
Err: err,
}
}
return params, nil
}
// RevokeMyOrganizationContactConsentParams is parameters of RevokeMyOrganizationContactConsent operation.
type RevokeMyOrganizationContactConsentParams struct {
// Organization whose stored C4 grants this account revokes. A well-formed identifier outside the
// account's stored records changes nothing and does not reveal whether that organization exists.
OrgID uuid.UUID
}
func unpackRevokeMyOrganizationContactConsentParams(packed middleware.Parameters) (params RevokeMyOrganizationContactConsentParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
return params
}
func decodeRevokeMyOrganizationContactConsentParams(args [1]string, argsEscaped bool, r *http.Request) (params RevokeMyOrganizationContactConsentParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
return params, nil
}
// SendOrganizationInvitationParams is parameters of SendOrganizationInvitation operation.
type SendOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -804,6 +804,85 @@ func (s *Server) decodeFinalizeMyAssessmentAttemptRequest(r *http.Request) (
}
}
func (s *Server) decodeGrantMyConsentRequest(r *http.Request) (
req *ConsentSettingsGrantRequest,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request ConsentSettingsGrantRequest
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeLoginRequest(r *http.Request) (
req *LoginRequest,
rawBody []byte,
@@ -1742,6 +1742,65 @@ func encodeGetMyCardPreviewResponse(response GetMyCardPreviewRes, w http.Respons
}
}
func encodeGetMyConsentTextResponse(response GetMyConsentTextRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ConsentTextHeaders:
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 *GetMyConsentTextBadRequest:
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 *GetMyConsentTextUnauthorized:
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 encodeGetMyInvitationResponse(response GetMyInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateInvitationHeaders:
@@ -2418,6 +2477,77 @@ func encodeGetSpecializationCatalogResponse(response *SpecializationCatalog, w h
return nil
}
func encodeGrantMyConsentResponse(response GrantMyConsentRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ConsentRecordHeaders:
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 *GrantMyConsentBadRequest:
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 *GrantMyConsentUnauthorized:
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
case *GrantMyConsentForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
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 encodeHideOrganizationResponse(response HideOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *HiddenOrganizationHeaders:
@@ -3620,6 +3750,65 @@ func encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseW
}
}
func encodeRequestMyAccountDeletionResponse(response RequestMyAccountDeletionRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ConsentDeletionRequestHeaders:
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(202)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *RequestMyAccountDeletionUnauthorized:
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
case *RequestMyAccountDeletionForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
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 encodeResendEmailVerificationResponse(response ResendEmailVerificationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *IdentityRequestAccepted:
@@ -3695,6 +3884,78 @@ func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes,
}
}
func encodeRevokeMyConsentResponse(response RevokeMyConsentRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *RevokeMyConsentNoContent:
w.WriteHeader(204)
return nil
case *RevokeMyConsentUnauthorized:
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
case *RevokeMyConsentForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
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 encodeRevokeMyOrganizationContactConsentResponse(response RevokeMyOrganizationContactConsentRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *RevokeMyOrganizationContactConsentNoContent:
w.WriteHeader(204)
return nil
case *RevokeMyOrganizationContactConsentUnauthorized:
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
case *RevokeMyOrganizationContactConsentForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
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 encodeSaveMyProfileResponse(response SaveMyProfileRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateProfileHeaders:
File diff suppressed because it is too large. Load diff
@@ -6261,6 +6261,117 @@ type ConfirmEmailForbidden Problem
func (*ConfirmEmailForbidden) confirmEmailRes() {}
// Durable request to delete the account and its personal data. The request is recorded before
// asynchronous processing starts; it does not mean deletion has completed.
// Ref: #/components/schemas/ConsentDeletionRequest
type ConsentDeletionRequest struct {
// Identifier of the durable deletion request.
ID uuid.UUID `json:"id"`
// Current state of the deletion request.
Status ConsentDeletionRequestStatus `json:"status"`
RequestedAt Timestamp `json:"requested_at"`
}
// GetID returns the value of ID.
func (s *ConsentDeletionRequest) GetID() uuid.UUID {
return s.ID
}
// GetStatus returns the value of Status.
func (s *ConsentDeletionRequest) GetStatus() ConsentDeletionRequestStatus {
return s.Status
}
// GetRequestedAt returns the value of RequestedAt.
func (s *ConsentDeletionRequest) GetRequestedAt() Timestamp {
return s.RequestedAt
}
// SetID sets the value of ID.
func (s *ConsentDeletionRequest) SetID(val uuid.UUID) {
s.ID = val
}
// SetStatus sets the value of Status.
func (s *ConsentDeletionRequest) SetStatus(val ConsentDeletionRequestStatus) {
s.Status = val
}
// SetRequestedAt sets the value of RequestedAt.
func (s *ConsentDeletionRequest) SetRequestedAt(val Timestamp) {
s.RequestedAt = val
}
// ConsentDeletionRequestHeaders wraps ConsentDeletionRequest with response headers.
type ConsentDeletionRequestHeaders struct {
CacheControl CacheControlNoStore
Response ConsentDeletionRequest
}
// GetCacheControl returns the value of CacheControl.
func (s *ConsentDeletionRequestHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *ConsentDeletionRequestHeaders) GetResponse() ConsentDeletionRequest {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *ConsentDeletionRequestHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *ConsentDeletionRequestHeaders) SetResponse(val ConsentDeletionRequest) {
s.Response = val
}
func (*ConsentDeletionRequestHeaders) requestMyAccountDeletionRes() {}
// Current state of the deletion request.
type ConsentDeletionRequestStatus string
const (
ConsentDeletionRequestStatusRequested ConsentDeletionRequestStatus = "requested"
ConsentDeletionRequestStatusProcessing ConsentDeletionRequestStatus = "processing"
)
// AllValues returns all ConsentDeletionRequestStatus values.
func (ConsentDeletionRequestStatus) AllValues() []ConsentDeletionRequestStatus {
return []ConsentDeletionRequestStatus{
ConsentDeletionRequestStatusRequested,
ConsentDeletionRequestStatusProcessing,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s ConsentDeletionRequestStatus) MarshalText() ([]byte, error) {
switch s {
case ConsentDeletionRequestStatusRequested:
return []byte(s), nil
case ConsentDeletionRequestStatusProcessing:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *ConsentDeletionRequestStatus) UnmarshalText(data []byte) error {
switch ConsentDeletionRequestStatus(data) {
case ConsentDeletionRequestStatusRequested:
*s = ConsentDeletionRequestStatusRequested
return nil
case ConsentDeletionRequestStatusProcessing:
*s = ConsentDeletionRequestStatusProcessing
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// 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
@@ -6559,6 +6670,34 @@ func (s *ConsentRecord) SetInvitationTermsVersion(val NilInvitationTermsVersion)
s.InvitationTermsVersion = val
}
// ConsentRecordHeaders wraps ConsentRecord with response headers.
type ConsentRecordHeaders struct {
CacheControl CacheControlNoStore
Response ConsentRecord
}
// GetCacheControl returns the value of CacheControl.
func (s *ConsentRecordHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *ConsentRecordHeaders) GetResponse() ConsentRecord {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *ConsentRecordHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *ConsentRecordHeaders) SetResponse(val ConsentRecord) {
s.Response = val
}
func (*ConsentRecordHeaders) grantMyConsentRes() {}
// One page of the consent ledger of the current account, newest grant first.
// Ref: #/components/schemas/ConsentRecordList
type ConsentRecordList struct {
@@ -6662,6 +6801,158 @@ func (s *ConsentRevocationSource) UnmarshalText(data []byte) error {
}
}
// Accept the current published text shown by GetMyConsentText. The server checks its version again
// before recording the grant.
// Ref: #/components/schemas/ConsentSettingsGrantRequest
type ConsentSettingsGrantRequest struct {
TextVersion ConsentTextVersion `json:"text_version"`
// Must be true to record an explicit acceptance.
Accepted ConsentSettingsGrantRequestAccepted `json:"accepted"`
}
// GetTextVersion returns the value of TextVersion.
func (s *ConsentSettingsGrantRequest) GetTextVersion() ConsentTextVersion {
return s.TextVersion
}
// GetAccepted returns the value of Accepted.
func (s *ConsentSettingsGrantRequest) GetAccepted() ConsentSettingsGrantRequestAccepted {
return s.Accepted
}
// SetTextVersion sets the value of TextVersion.
func (s *ConsentSettingsGrantRequest) SetTextVersion(val ConsentTextVersion) {
s.TextVersion = val
}
// SetAccepted sets the value of Accepted.
func (s *ConsentSettingsGrantRequest) SetAccepted(val ConsentSettingsGrantRequestAccepted) {
s.Accepted = val
}
// Must be true to record an explicit acceptance.
type ConsentSettingsGrantRequestAccepted bool
const (
ConsentSettingsGrantRequestAcceptedTrue ConsentSettingsGrantRequestAccepted = true
)
// AllValues returns all ConsentSettingsGrantRequestAccepted values.
func (ConsentSettingsGrantRequestAccepted) AllValues() []ConsentSettingsGrantRequestAccepted {
return []ConsentSettingsGrantRequestAccepted{
ConsentSettingsGrantRequestAcceptedTrue,
}
}
// Consent text that an authenticated account can read and accept in settings. C4 is scoped to an
// invitation and organization, so it is not available through the general settings flow.
// Ref: #/components/schemas/ConsentSettingsPurpose
type ConsentSettingsPurpose string
const (
ConsentSettingsPurposeC1 ConsentSettingsPurpose = "c1"
ConsentSettingsPurposeC2 ConsentSettingsPurpose = "c2"
ConsentSettingsPurposeC3 ConsentSettingsPurpose = "c3"
ConsentSettingsPurposeC5 ConsentSettingsPurpose = "c5"
)
// AllValues returns all ConsentSettingsPurpose values.
func (ConsentSettingsPurpose) AllValues() []ConsentSettingsPurpose {
return []ConsentSettingsPurpose{
ConsentSettingsPurposeC1,
ConsentSettingsPurposeC2,
ConsentSettingsPurposeC3,
ConsentSettingsPurposeC5,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s ConsentSettingsPurpose) MarshalText() ([]byte, error) {
switch s {
case ConsentSettingsPurposeC1:
return []byte(s), nil
case ConsentSettingsPurposeC2:
return []byte(s), nil
case ConsentSettingsPurposeC3:
return []byte(s), nil
case ConsentSettingsPurposeC5:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *ConsentSettingsPurpose) UnmarshalText(data []byte) error {
switch ConsentSettingsPurpose(data) {
case ConsentSettingsPurposeC1:
*s = ConsentSettingsPurposeC1
return nil
case ConsentSettingsPurposeC2:
*s = ConsentSettingsPurposeC2
return nil
case ConsentSettingsPurposeC3:
*s = ConsentSettingsPurposeC3
return nil
case ConsentSettingsPurposeC5:
*s = ConsentSettingsPurposeC5
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// Consent that can be revoked through the general settings flow. C1 uses the account deletion request,
// and C4 must be revoked for one organization.
// Ref: #/components/schemas/ConsentSettingsRevokePurpose
type ConsentSettingsRevokePurpose string
const (
ConsentSettingsRevokePurposeC2 ConsentSettingsRevokePurpose = "c2"
ConsentSettingsRevokePurposeC3 ConsentSettingsRevokePurpose = "c3"
ConsentSettingsRevokePurposeC5 ConsentSettingsRevokePurpose = "c5"
)
// AllValues returns all ConsentSettingsRevokePurpose values.
func (ConsentSettingsRevokePurpose) AllValues() []ConsentSettingsRevokePurpose {
return []ConsentSettingsRevokePurpose{
ConsentSettingsRevokePurposeC2,
ConsentSettingsRevokePurposeC3,
ConsentSettingsRevokePurposeC5,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s ConsentSettingsRevokePurpose) MarshalText() ([]byte, error) {
switch s {
case ConsentSettingsRevokePurposeC2:
return []byte(s), nil
case ConsentSettingsRevokePurposeC3:
return []byte(s), nil
case ConsentSettingsRevokePurposeC5:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *ConsentSettingsRevokePurpose) UnmarshalText(data []byte) error {
switch ConsentSettingsRevokePurpose(data) {
case ConsentSettingsRevokePurposeC2:
*s = ConsentSettingsRevokePurposeC2
return nil
case ConsentSettingsRevokePurposeC3:
*s = ConsentSettingsRevokePurposeC3
return nil
case ConsentSettingsRevokePurposeC5:
*s = ConsentSettingsRevokePurposeC5
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// Where the subject gave the consent.
//
// - registration: the c1 acceptance of RegisterAccount.
@@ -6780,7 +7071,7 @@ func (s *ConsentState) UnmarshalText(data []byte) error {
// of exactly this text.
// Ref: #/components/schemas/ConsentText
type ConsentText struct {
Purpose ConsentPurpose `json:"purpose"`
Purpose ConsentPurposeCode `json:"purpose"`
TextVersion ConsentTextVersion `json:"text_version"`
// Full consent text in plain UTF-8; paragraphs are separated by an empty line. The client shows it as
// text, never as HTML.
@@ -6789,7 +7080,7 @@ type ConsentText struct {
}
// GetPurpose returns the value of Purpose.
func (s *ConsentText) GetPurpose() ConsentPurpose {
func (s *ConsentText) GetPurpose() ConsentPurposeCode {
return s.Purpose
}
@@ -6809,7 +7100,7 @@ func (s *ConsentText) GetPublishedAt() Timestamp {
}
// SetPurpose sets the value of Purpose.
func (s *ConsentText) SetPurpose(val ConsentPurpose) {
func (s *ConsentText) SetPurpose(val ConsentPurposeCode) {
s.Purpose = val
}
@@ -6830,6 +7121,34 @@ func (s *ConsentText) SetPublishedAt(val Timestamp) {
func (*ConsentText) getConsentTextRes() {}
// ConsentTextHeaders wraps ConsentText with response headers.
type ConsentTextHeaders struct {
CacheControl CacheControlNoStore
Response ConsentText
}
// GetCacheControl returns the value of CacheControl.
func (s *ConsentTextHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *ConsentTextHeaders) GetResponse() ConsentText {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *ConsentTextHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *ConsentTextHeaders) SetResponse(val ConsentText) {
s.Response = val
}
func (*ConsentTextHeaders) getMyConsentTextRes() {}
type ConsentTextVersion string
// Why an active grant does not allow a read now, shown only to the candidate.
@@ -8046,6 +8365,14 @@ type GetMyCardPreviewUnauthorized Problem
func (*GetMyCardPreviewUnauthorized) getMyCardPreviewRes() {}
type GetMyConsentTextBadRequest Problem
func (*GetMyConsentTextBadRequest) getMyConsentTextRes() {}
type GetMyConsentTextUnauthorized Problem
func (*GetMyConsentTextUnauthorized) getMyConsentTextRes() {}
type GetMyInvitationBadRequest Problem
func (*GetMyInvitationBadRequest) getMyInvitationRes() {}
@@ -8222,6 +8549,18 @@ func (s *GradeCode) UnmarshalText(data []byte) error {
}
}
type GrantMyConsentBadRequest Problem
func (*GrantMyConsentBadRequest) grantMyConsentRes() {}
type GrantMyConsentForbidden Problem
func (*GrantMyConsentForbidden) grantMyConsentRes() {}
type GrantMyConsentUnauthorized Problem
func (*GrantMyConsentUnauthorized) grantMyConsentRes() {}
// Ref: #/components/schemas/HealthResponse
type HealthResponse struct {
Status HealthResponseStatus `json:"status"`
@@ -21991,6 +22330,14 @@ func (s *RegistrationRequest) SetConsentC1(val PersonalDataConsentAcceptance) {
s.ConsentC1 = val
}
type RequestMyAccountDeletionForbidden Problem
func (*RequestMyAccountDeletionForbidden) requestMyAccountDeletionRes() {}
type RequestMyAccountDeletionUnauthorized Problem
func (*RequestMyAccountDeletionUnauthorized) requestMyAccountDeletionRes() {}
type ResendEmailVerificationBadRequest Problem
func (*ResendEmailVerificationBadRequest) resendEmailVerificationRes() {}
@@ -21999,6 +22346,32 @@ type ResendEmailVerificationForbidden Problem
func (*ResendEmailVerificationForbidden) resendEmailVerificationRes() {}
type RevokeMyConsentForbidden Problem
func (*RevokeMyConsentForbidden) revokeMyConsentRes() {}
// RevokeMyConsentNoContent is response for RevokeMyConsent operation.
type RevokeMyConsentNoContent struct{}
func (*RevokeMyConsentNoContent) revokeMyConsentRes() {}
type RevokeMyConsentUnauthorized Problem
func (*RevokeMyConsentUnauthorized) revokeMyConsentRes() {}
type RevokeMyOrganizationContactConsentForbidden Problem
func (*RevokeMyOrganizationContactConsentForbidden) revokeMyOrganizationContactConsentRes() {}
// RevokeMyOrganizationContactConsentNoContent is response for RevokeMyOrganizationContactConsent operation.
type RevokeMyOrganizationContactConsentNoContent struct{}
func (*RevokeMyOrganizationContactConsentNoContent) revokeMyOrganizationContactConsentRes() {}
type RevokeMyOrganizationContactConsentUnauthorized Problem
func (*RevokeMyOrganizationContactConsentUnauthorized) revokeMyOrganizationContactConsentRes() {}
type RubAmount int64
// Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.
@@ -56,55 +56,60 @@ func findAuthorization(h http.Header, prefix string) (string, bool) {
// operationRolesSessionCookie is a private map storing roles per operation.
var operationRolesSessionCookie = map[string][]string{
AcceptMyInvitationOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
GetMyAssessmentAttemptOperation: []string{},
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyCardPreviewOperation: []string{},
GetMyInvitationOperation: []string{},
GetMyPrivacySettingsOperation: []string{},
GetMyProfileOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
HideOrganizationOperation: []string{},
ListMyCardAccessHistoryOperation: []string{},
ListMyConsentsOperation: []string{},
ListMyHiddenOrganizationsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMyPrivacyHistoryOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SetMyPublicationOperation: []string{},
SetMySearchStatusOperation: []string{},
StartMyAssessmentAttemptSessionOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UnhideOrganizationOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
AcceptMyInvitationOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
GetMyAssessmentAttemptOperation: []string{},
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyCardPreviewOperation: []string{},
GetMyConsentTextOperation: []string{},
GetMyInvitationOperation: []string{},
GetMyPrivacySettingsOperation: []string{},
GetMyProfileOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
ListMyCardAccessHistoryOperation: []string{},
ListMyConsentsOperation: []string{},
ListMyHiddenOrganizationsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMyPrivacyHistoryOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SetMyPublicationOperation: []string{},
SetMySearchStatusOperation: []string{},
StartMyAssessmentAttemptSessionOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UnhideOrganizationOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
}
// GetRolesForSessionCookie returns the required roles for the given operation.
@@ -130,31 +135,35 @@ func GetRolesForSessionCookie(operation string) []string {
// operationRolesSessionCsrf is a private map storing roles per operation.
var operationRolesSessionCsrf = map[string][]string{
AcceptMyInvitationOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
HideOrganizationOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SetMyPublicationOperation: []string{},
SetMySearchStatusOperation: []string{},
StartMyAssessmentAttemptSessionOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UnhideOrganizationOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
AcceptMyInvitationOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SetMyPublicationOperation: []string{},
SetMySearchStatusOperation: []string{},
StartMyAssessmentAttemptSessionOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UnhideOrganizationOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
}
// GetRolesForSessionCsrf returns the required roles for the given operation.
@@ -621,6 +621,15 @@ type Handler interface {
//
// GET /api/v1/me/privacy/preview
GetMyCardPreview(ctx context.Context) (GetMyCardPreviewRes, error)
// GetMyConsentText implements GetMyConsentText operation.
//
// Requires a verified session. Returns the current published text and version of c1, c2, c3, or c5 so
// the user can read the exact text before an explicit settings grant. C4 is excluded: its text
// includes an organization snapshot and it is granted only during invitation acceptance. The response
// is private and is not cached.
//
// GET /api/v1/me/consent-texts/{purpose}
GetMyConsentText(ctx context.Context, params GetMyConsentTextParams) (GetMyConsentTextRes, error)
// GetMyInvitation implements GetMyInvitation operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session; the
@@ -864,6 +873,20 @@ type Handler interface {
//
// GET /api/v1/specializations
GetSpecializationCatalog(ctx context.Context) (*SpecializationCatalog, error)
// GrantMyConsent implements GrantMyConsent operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
// subject comes from the session. The body names the current text version the user read and requires
// `accepted: true`; the server verifies that version is still current and stores the hash of the exact
// text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant.
//
// C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate
// accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the
// same current version returns the existing record; after revocation a grant creates a new record and
// never reopens a publication or restores an older grant.
//
// PUT /api/v1/me/consents/{purpose}
GrantMyConsent(ctx context.Context, req *ConsentSettingsGrantRequest, params GrantMyConsentParams) (GrantMyConsentRes, error)
// HideOrganization implements HideOrganization operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -945,8 +968,9 @@ type Handler interface {
// value. A c2 record proves the consent to the publication text; the published field set and its
// changes are evidence of the publication history.
//
// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations
// of this tag; c1 is given at registration and c4 only in AcceptMyInvitation.
// Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit
// acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion
// request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed
// `limit`, `cursor`, or `state` answers 400 validation_failed.
@@ -1210,6 +1234,16 @@ type Handler interface {
//
// POST /api/v1/identity/registrations
RegisterAccount(ctx context.Context, req *RegistrationRequest, params RegisterAccountParams) (RegisterAccountRes, error)
// RequestMyAccountDeletion implements RequestMyAccountDeletion operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
// subject comes from the session. In one transaction, revokes any active C1 record, creates or returns
// the subject's active durable deletion request, and writes the outbox intent. The API does not delete
// the account synchronously. Repeating the request returns the same active request; a later C1 grant
// never cancels it.
//
// POST /api/v1/me/account-deletion-requests
RequestMyAccountDeletion(ctx context.Context) (RequestMyAccountDeletionRes, error)
// ResendEmailVerification implements ResendEmailVerification operation.
//
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
@@ -1226,6 +1260,31 @@ type Handler interface {
//
// POST /api/v1/identity/email-verification-requests
ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (ResendEmailVerificationRes, error)
// RevokeMyConsent implements RevokeMyConsent operation.
//
// Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured
// Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5,
// including superseded records, and never changes another purpose. Repeating a revocation is harmless
// and creates no duplicate event.
//
// Revoking c2 immediately closes the stored publication and records privacy history in the same
// transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not
// reopen publication or restore old grants. Revoking c3 does not block the manual assessment path.
// Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent;
// an external FSP deletion adapter is not available yet.
//
// DELETE /api/v1/me/consents/{purpose}
RevokeMyConsent(ctx context.Context, params RevokeMyConsentParams) (RevokeMyConsentRes, error)
// RevokeMyOrganizationContactConsent implements RevokeMyOrganizationContactConsent operation.
//
// Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured
// Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The
// server revokes every unrevoked C4 record for this subject and organization, using the fields stored
// on those records to request downstream grant revocation. It does not affect another organization.
// Repeating the request is harmless and creates no duplicate event.
//
// DELETE /api/v1/me/consents/c4/organizations/{org_id}
RevokeMyOrganizationContactConsent(ctx context.Context, params RevokeMyOrganizationContactConsentParams) (RevokeMyOrganizationContactConsentRes, error)
// SaveMyProfile implements SaveMyProfile operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -680,6 +680,18 @@ func (UnimplementedHandler) GetMyCardPreview(ctx context.Context) (r GetMyCardPr
return r, ht.ErrNotImplemented
}
// GetMyConsentText implements GetMyConsentText operation.
//
// Requires a verified session. Returns the current published text and version of c1, c2, c3, or c5 so
// the user can read the exact text before an explicit settings grant. C4 is excluded: its text
// includes an organization snapshot and it is granted only during invitation acceptance. The response
// is private and is not cached.
//
// GET /api/v1/me/consent-texts/{purpose}
func (UnimplementedHandler) GetMyConsentText(ctx context.Context, params GetMyConsentTextParams) (r GetMyConsentTextRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetMyInvitation implements GetMyInvitation operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session; the
@@ -953,6 +965,23 @@ func (UnimplementedHandler) GetSpecializationCatalog(ctx context.Context) (r *Sp
return r, ht.ErrNotImplemented
}
// GrantMyConsent implements GrantMyConsent operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
// subject comes from the session. The body names the current text version the user read and requires
// `accepted: true`; the server verifies that version is still current and stores the hash of the exact
// text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant.
//
// C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate
// accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the
// same current version returns the existing record; after revocation a grant creates a new record and
// never reopens a publication or restores an older grant.
//
// PUT /api/v1/me/consents/{purpose}
func (UnimplementedHandler) GrantMyConsent(ctx context.Context, req *ConsentSettingsGrantRequest, params GrantMyConsentParams) (r GrantMyConsentRes, _ error) {
return r, ht.ErrNotImplemented
}
// HideOrganization implements HideOrganization operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -1040,8 +1069,9 @@ func (UnimplementedHandler) ListMyCardAccessHistory(ctx context.Context, params
// value. A c2 record proves the consent to the publication text; the published field set and its
// changes are evidence of the publication history.
//
// Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations
// of this tag; c1 is given at registration and c4 only in AcceptMyInvitation.
// Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit
// acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion
// request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed
// `limit`, `cursor`, or `state` answers 400 validation_failed.
@@ -1341,6 +1371,19 @@ func (UnimplementedHandler) RegisterAccount(ctx context.Context, req *Registrati
return r, ht.ErrNotImplemented
}
// RequestMyAccountDeletion implements RequestMyAccountDeletion operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
// subject comes from the session. In one transaction, revokes any active C1 record, creates or returns
// the subject's active durable deletion request, and writes the outbox intent. The API does not delete
// the account synchronously. Repeating the request returns the same active request; a later C1 grant
// never cancels it.
//
// POST /api/v1/me/account-deletion-requests
func (UnimplementedHandler) RequestMyAccountDeletion(ctx context.Context) (r RequestMyAccountDeletionRes, _ error) {
return r, ht.ErrNotImplemented
}
// ResendEmailVerification implements ResendEmailVerification operation.
//
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
@@ -1360,6 +1403,37 @@ func (UnimplementedHandler) ResendEmailVerification(ctx context.Context, req *Em
return r, ht.ErrNotImplemented
}
// RevokeMyConsent implements RevokeMyConsent operation.
//
// Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured
// Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5,
// including superseded records, and never changes another purpose. Repeating a revocation is harmless
// and creates no duplicate event.
//
// Revoking c2 immediately closes the stored publication and records privacy history in the same
// transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not
// reopen publication or restore old grants. Revoking c3 does not block the manual assessment path.
// Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent;
// an external FSP deletion adapter is not available yet.
//
// DELETE /api/v1/me/consents/{purpose}
func (UnimplementedHandler) RevokeMyConsent(ctx context.Context, params RevokeMyConsentParams) (r RevokeMyConsentRes, _ error) {
return r, ht.ErrNotImplemented
}
// RevokeMyOrganizationContactConsent implements RevokeMyOrganizationContactConsent operation.
//
// Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured
// Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The
// server revokes every unrevoked C4 record for this subject and organization, using the fields stored
// on those records to request downstream grant revocation. It does not affect another organization.
// Repeating the request is harmless and creates no duplicate event.
//
// DELETE /api/v1/me/consents/c4/organizations/{org_id}
func (UnimplementedHandler) RevokeMyOrganizationContactConsent(ctx context.Context, params RevokeMyOrganizationContactConsentParams) (r RevokeMyOrganizationContactConsentRes, _ error) {
return r, ht.ErrNotImplemented
}
// SaveMyProfile implements SaveMyProfile operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -5934,6 +5934,74 @@ func (s *ConfirmEmailForbidden) Validate() error {
return nil
}
func (s *ConsentDeletionRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Status.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "status",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ConsentDeletionRequestHeaders) 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 ConsentDeletionRequestStatus) Validate() error {
switch s {
case "requested":
return nil
case "processing":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *ConsentOrganization) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -6144,6 +6212,40 @@ func (s *ConsentRecord) Validate() error {
return nil
}
func (s *ConsentRecordHeaders) 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 *ConsentRecordList) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -6248,6 +6350,77 @@ func (s ConsentRevocationSource) Validate() error {
}
}
func (s *ConsentSettingsGrantRequest) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
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.Accepted.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "accepted",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ConsentSettingsGrantRequestAccepted) Validate() error {
switch s {
case true:
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s ConsentSettingsPurpose) Validate() error {
switch s {
case "c1":
return nil
case "c2":
return nil
case "c3":
return nil
case "c5":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s ConsentSettingsRevokePurpose) Validate() error {
switch s {
case "c2":
return nil
case "c3":
return nil
case "c5":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s ConsentSource) Validate() error {
switch s {
case "registration":
@@ -6331,6 +6504,40 @@ func (s *ConsentText) Validate() error {
return nil
}
func (s *ConsentTextHeaders) 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 ConsentTextVersion) Validate() error {
alias := (string)(s)
if err := (validate.String{
@@ -7773,6 +7980,22 @@ func (s *GetMyCardPreviewUnauthorized) Validate() error {
return nil
}
func (s *GetMyConsentTextBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GetMyConsentTextUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GetMyInvitationBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -8020,6 +8243,30 @@ func (s GradeCode) Validate() error {
}
}
func (s *GrantMyConsentBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GrantMyConsentForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GrantMyConsentUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *HealthResponse) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -17451,6 +17698,22 @@ func (s *RegistrationRequest) Validate() error {
return nil
}
func (s *RequestMyAccountDeletionForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RequestMyAccountDeletionUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ResendEmailVerificationBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -17467,6 +17730,38 @@ func (s *ResendEmailVerificationForbidden) Validate() error {
return nil
}
func (s *RevokeMyConsentForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RevokeMyConsentUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RevokeMyOrganizationContactConsentForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RevokeMyOrganizationContactConsentUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s RubAmount) Validate() error {
alias := (int64)(s)
if err := (validate.Int{
@@ -17,9 +17,11 @@ import (
type Handler struct {
api.UnimplementedHandler
health *HealthHandler
identity *IdentityHandler
problems *problem.Responder
health *HealthHandler
identity *IdentityHandler
consent *ConsentHandler
organization *OrganizationHandler
problems *problem.Responder
}
var _ api.Handler = (*Handler)(nil)
@@ -32,6 +34,16 @@ func WithIdentity(identity *IdentityHandler) HandlerOption {
return func(handler *Handler) { handler.identity = identity }
}
// WithConsent serves the published texts and ledger operations.
func WithConsent(consent *ConsentHandler) HandlerOption {
return func(handler *Handler) { handler.consent = consent }
}
// WithOrganization serves company profiles and owner operations.
func WithOrganization(organization *OrganizationHandler) HandlerOption {
return func(handler *Handler) { handler.organization = organization }
}
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
handler := &Handler{health: health, problems: problems}
for _, option := range options {
@@ -0,0 +1,432 @@
package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
)
const (
defaultConsentPageLimit = 20
consentCursorVersion = 1
consentCursorBytes = 42
maxConsentCursorNanos = int64(1<<63 - 1)
minConsentCursorNanos = -maxConsentCursorNanos - 1
)
// ConsentQueries reads current texts and a subject's own consent history.
type ConsentQueries interface {
CurrentText(ctx context.Context, purpose domain.ConsentPurpose) (domain.ConsentText, error)
List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error)
}
// ConsentCommands records grants, revocations, and deletion requests.
type ConsentCommands interface {
GrantInSettingsInNewTransaction(ctx context.Context, input consent.SettingsGrantInput) (consent.GrantResult, error)
RevokeInSettingsInNewTransaction(ctx context.Context, input consent.SettingsRevocationInput) (consent.RevocationResult, error)
RequestAccountDeletionInNewTransaction(ctx context.Context, subjectID uuid.UUID) (domain.AccountDeletionRequest, error)
}
// ConsentHandler serves consent text and ledger operations.
type ConsentHandler struct {
queries ConsentQueries
commands ConsentCommands
}
func NewConsentHandler(queries ConsentQueries, commands ConsentCommands) *ConsentHandler {
if queries == nil || commands == nil {
panic("v1.NewConsentHandler - query and command services must not be nil")
}
return &ConsentHandler{queries: queries, commands: commands}
}
func (handler *Handler) GetConsentText(ctx context.Context, params api.GetConsentTextParams) (api.GetConsentTextRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.GetConsentText(ctx, params)
}
return handler.consent.GetConsentText(ctx, params)
}
func (handler *Handler) GetMyConsentText(ctx context.Context, params api.GetMyConsentTextParams) (api.GetMyConsentTextRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.GetMyConsentText(ctx, params)
}
return handler.consent.GetMyConsentText(ctx, params)
}
func (handler *Handler) ListMyConsents(ctx context.Context, params api.ListMyConsentsParams) (api.ListMyConsentsRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.ListMyConsents(ctx, params)
}
return handler.consent.ListMyConsents(ctx, params)
}
func (handler *Handler) GrantMyConsent(ctx context.Context, request *api.ConsentSettingsGrantRequest, params api.GrantMyConsentParams) (api.GrantMyConsentRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.GrantMyConsent(ctx, request, params)
}
return handler.consent.GrantMyConsent(ctx, request, params)
}
func (handler *Handler) RevokeMyConsent(ctx context.Context, params api.RevokeMyConsentParams) (api.RevokeMyConsentRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.RevokeMyConsent(ctx, params)
}
return handler.consent.RevokeMyConsent(ctx, params)
}
func (handler *Handler) RevokeMyOrganizationContactConsent(ctx context.Context, params api.RevokeMyOrganizationContactConsentParams) (api.RevokeMyOrganizationContactConsentRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.RevokeMyOrganizationContactConsent(ctx, params)
}
return handler.consent.RevokeMyOrganizationContactConsent(ctx, params)
}
func (handler *Handler) RequestMyAccountDeletion(ctx context.Context) (api.RequestMyAccountDeletionRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.RequestMyAccountDeletion(ctx)
}
return handler.consent.RequestMyAccountDeletion(ctx)
}
func (handler *ConsentHandler) GetConsentText(ctx context.Context, params api.GetConsentTextParams) (api.GetConsentTextRes, error) {
purpose := domain.ConsentPurpose(params.Purpose)
if purpose != domain.ConsentPurposePersonalData {
response := problem.New(ctx, api.ProblemCodeValidationFailed).Response
return &response, nil
}
text, err := handler.queries.CurrentText(ctx, purpose)
if err != nil {
return nil, err
}
response := consentTextResponse(text)
return &response, nil
}
func (handler *ConsentHandler) GetMyConsentText(ctx context.Context, params api.GetMyConsentTextParams) (api.GetMyConsentTextRes, error) {
if _, ok := currentConsentPrincipal(ctx); !ok {
return (*api.GetMyConsentTextUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
text, err := handler.queries.CurrentText(ctx, domain.ConsentPurpose(params.Purpose))
if err != nil {
return nil, err
}
return &api.ConsentTextHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: consentTextResponse(text),
}, nil
}
func (handler *ConsentHandler) ListMyConsents(ctx context.Context, params api.ListMyConsentsParams) (api.ListMyConsentsRes, error) {
principal, ok := currentConsentPrincipal(ctx)
if !ok {
return (*api.ListMyConsentsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
query, err := consentListQuery(principal.UserID, params)
if err != nil {
return consentListInvalid(ctx, err), nil
}
page, err := handler.queries.List(ctx, query)
if err != nil {
if errors.Is(err, domain.ErrInvalidConsent) {
return consentListInvalid(ctx, err), nil
}
return nil, err
}
items := make([]api.ConsentRecord, 0, len(page.Records))
for _, record := range page.Records {
items = append(items, consentRecordResponse(record))
}
var nextCursor api.NilString
nextCursor.SetToNull()
if page.HasMore && len(page.Records) > 0 {
last := page.Records[len(page.Records)-1]
cursor, err := encodeConsentCursor(principal.UserID, query.State, outbound.ConsentPositionOf(last))
if err != nil {
return nil, fmt.Errorf("ConsentHandler.ListMyConsents - encode cursor: %w", err)
}
nextCursor.SetTo(cursor)
}
return &api.ConsentRecordListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.ConsentRecordList{
Items: items,
Page: api.PageInfo{HasMore: page.HasMore, NextCursor: nextCursor},
},
}, nil
}
func (handler *ConsentHandler) GrantMyConsent(ctx context.Context, request *api.ConsentSettingsGrantRequest, params api.GrantMyConsentParams) (api.GrantMyConsentRes, error) {
principal, session, ok := currentConsentSession(ctx)
if !ok {
return (*api.GrantMyConsentUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
purpose := domain.ConsentPurpose(params.Purpose)
if candidateOnlyConsent(purpose) && session.User.Scenario != domain.ScenarioCandidate {
return (*api.GrantMyConsentForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
if request == nil || !bool(request.Accepted) {
return consentGrantInvalid(ctx, "/accepted"), nil
}
result, err := handler.commands.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{
SubjectID: principal.UserID, Purpose: purpose, TextVersion: domain.ConsentTextVersion(request.TextVersion),
})
if err != nil {
if errors.Is(err, consent.ErrStaleConsentText) {
return consentGrantInvalid(ctx, "/text_version"), nil
}
return nil, err
}
return &api.ConsentRecordHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: consentRecordResponse(result.Record),
}, nil
}
func (handler *ConsentHandler) RevokeMyConsent(ctx context.Context, params api.RevokeMyConsentParams) (api.RevokeMyConsentRes, error) {
principal, session, ok := currentConsentSession(ctx)
if !ok {
return (*api.RevokeMyConsentUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if session.User.Scenario != domain.ScenarioCandidate {
return (*api.RevokeMyConsentForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
_, err := handler.commands.RevokeInSettingsInNewTransaction(ctx, consent.SettingsRevocationInput{
SubjectID: principal.UserID, Purpose: domain.ConsentPurpose(params.Purpose),
})
if err != nil {
return nil, err
}
return &api.RevokeMyConsentNoContent{}, nil
}
func (handler *ConsentHandler) RevokeMyOrganizationContactConsent(ctx context.Context, params api.RevokeMyOrganizationContactConsentParams) (api.RevokeMyOrganizationContactConsentRes, error) {
principal, session, ok := currentConsentSession(ctx)
if !ok {
return (*api.RevokeMyOrganizationContactConsentUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if session.User.Scenario != domain.ScenarioCandidate {
return (*api.RevokeMyOrganizationContactConsentForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
_, err := handler.commands.RevokeInSettingsInNewTransaction(ctx, consent.SettingsRevocationInput{
SubjectID: principal.UserID, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: params.OrgID,
})
if err != nil {
return nil, err
}
return &api.RevokeMyOrganizationContactConsentNoContent{}, nil
}
func (handler *ConsentHandler) RequestMyAccountDeletion(ctx context.Context) (api.RequestMyAccountDeletionRes, error) {
principal, ok := currentConsentPrincipal(ctx)
if !ok {
return (*api.RequestMyAccountDeletionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
request, err := handler.commands.RequestAccountDeletionInNewTransaction(ctx, principal.UserID)
if err != nil {
return nil, err
}
return &api.ConsentDeletionRequestHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.ConsentDeletionRequest{
ID: request.ID(), Status: api.ConsentDeletionRequestStatus(request.Status()), RequestedAt: api.Timestamp(request.RequestedAt()),
},
}, nil
}
func currentConsentPrincipal(ctx context.Context) (Principal, bool) {
principal, ok := PrincipalFromContext(ctx)
if !ok || !principal.EmailVerified {
return Principal{}, false
}
session, ok := sessionFromContext(ctx)
if !ok || session.Principal != principal || session.User.ID != principal.UserID || !session.User.EmailVerified() {
return Principal{}, false
}
return principal, true
}
func currentConsentSession(ctx context.Context) (Principal, authenticatedSession, bool) {
principal, ok := currentConsentPrincipal(ctx)
if !ok {
return Principal{}, authenticatedSession{}, false
}
session, ok := sessionFromContext(ctx)
return principal, session, ok
}
func candidateOnlyConsent(purpose domain.ConsentPurpose) bool {
return purpose == domain.ConsentPurposePublication || purpose == domain.ConsentPurposeAutoCategorization ||
purpose == domain.ConsentPurposeFSPImport
}
func consentTextResponse(text domain.ConsentText) api.ConsentText {
return api.ConsentText{
Purpose: api.ConsentPurposeCode(text.Purpose()), TextVersion: api.ConsentTextVersion(text.Version()),
Text: text.Body(), PublishedAt: api.Timestamp(text.PublishedAt()),
}
}
func consentRecordResponse(record domain.ConsentRecord) api.ConsentRecord {
response := api.ConsentRecord{
ID: record.ID(), Purpose: api.ConsentPurposeCode(record.Purpose()), State: api.ConsentState(record.State()),
TextVersion: api.ConsentTextVersion(record.TextVersion()), Source: api.ConsentSource(record.Source()),
GrantedAt: api.Timestamp(record.GrantedAt()), Fields: mapContactFields(record.Fields().Fields()),
}
if revokedAt, ok := record.RevokedAt(); ok {
response.RevokedAt.SetTo(api.Timestamp(revokedAt))
response.RevocationSource.SetTo(api.ConsentRevocationSource(record.RevocationSource()))
} else {
response.RevokedAt.SetToNull()
response.RevocationSource.SetToNull()
}
if record.Purpose().OrganizationScoped() {
response.Organization.SetTo(api.ConsentOrganization{ID: record.OrganizationID(), Name: record.OrganizationName()})
response.InvitationID.SetTo(record.InvitationID())
response.InvitationTermsVersion.SetTo(api.InvitationTermsVersion(record.InvitationTermsVersion()))
} else {
response.Organization.SetToNull()
response.InvitationID.SetToNull()
response.InvitationTermsVersion.SetToNull()
}
return response
}
func mapContactFields(fields []domain.ContactField) []api.ContactFieldKind {
if fields == nil {
return nil
}
mapped := make([]api.ContactFieldKind, 0, len(fields))
for _, field := range fields {
mapped = append(mapped, api.ContactFieldKind(field))
}
return mapped
}
func consentListQuery(subjectID uuid.UUID, params api.ListMyConsentsParams) (outbound.ConsentListQuery, error) {
query := outbound.ConsentListQuery{SubjectID: subjectID, Limit: defaultConsentPageLimit}
if state, ok := params.State.Get(); ok {
query.State = domain.ConsentState(state)
}
if limit, ok := params.Limit.Get(); ok {
query.Limit = limit
}
if cursor, ok := params.Cursor.Get(); ok {
position, state, err := decodeConsentCursor(cursor, subjectID)
if err != nil || state != query.State {
return outbound.ConsentListQuery{}, errors.New("consent cursor is invalid")
}
query.After = &position
}
return query, nil
}
func encodeConsentCursor(subjectID uuid.UUID, state domain.ConsentState, position outbound.ConsentListPosition) (string, error) {
nanos, inRange := consentCursorNanos(position.GrantedAt)
if subjectID == uuid.Nil || position.ID == uuid.Nil || !inRange {
return "", fmt.Errorf("encodeConsentCursor - subject and position are required: %w", domain.ErrInvalidConsent)
}
stateCode, ok := consentCursorStateCode(state)
if !ok {
return "", fmt.Errorf("encodeConsentCursor - state is invalid: %w", domain.ErrInvalidConsent)
}
var value [consentCursorBytes]byte
value[0] = consentCursorVersion
copy(value[1:17], subjectID[:])
value[17] = stateCode
binary.BigEndian.PutUint64(value[18:26], encodeConsentCursorNanos(nanos))
copy(value[26:], position.ID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodeConsentCursor(cursor string, subjectID uuid.UUID) (outbound.ConsentListPosition, domain.ConsentState, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != consentCursorBytes || subjectID == uuid.Nil || value[0] != consentCursorVersion ||
base64.RawURLEncoding.EncodeToString(value) != cursor || uuid.UUID(value[1:17]) != subjectID {
return outbound.ConsentListPosition{}, "", errors.New("consent cursor is invalid")
}
state, ok := consentCursorState(value[17])
if !ok {
return outbound.ConsentListPosition{}, "", errors.New("consent cursor is invalid")
}
grantedAt := time.Unix(0, decodeConsentCursorNanos(binary.BigEndian.Uint64(value[18:26]))).UTC()
positionID := uuid.UUID(value[26:42])
if positionID == uuid.Nil || grantedAt.IsZero() {
return outbound.ConsentListPosition{}, "", errors.New("consent cursor is invalid")
}
return outbound.ConsentListPosition{GrantedAt: grantedAt, ID: positionID}, state, nil
}
func consentCursorNanos(at time.Time) (int64, bool) {
if at.IsZero() || at.Before(time.Unix(0, minConsentCursorNanos)) || at.After(time.Unix(0, maxConsentCursorNanos)) {
return 0, false
}
return at.UnixNano(), true
}
func decodeConsentCursorNanos(encoded uint64) int64 {
if encoded <= uint64(maxConsentCursorNanos) {
return int64(encoded)
}
complement := ^encoded & uint64(maxConsentCursorNanos)
if complement == uint64(maxConsentCursorNanos) {
return minConsentCursorNanos
}
return -int64(complement) - 1
}
func encodeConsentCursorNanos(nanos int64) uint64 {
if nanos >= 0 {
return uint64(nanos)
}
return uint64(nanos&maxConsentCursorNanos) | uint64(1)<<63
}
func consentCursorStateCode(state domain.ConsentState) (byte, bool) {
switch state {
case "":
return 0, true
case domain.ConsentStateActive:
return 1, true
case domain.ConsentStateSuperseded:
return 2, true
case domain.ConsentStateRevoked:
return 3, true
default:
return 0, false
}
}
func consentCursorState(code byte) (domain.ConsentState, bool) {
switch code {
case 0:
return "", true
case 1:
return domain.ConsentStateActive, true
case 2:
return domain.ConsentStateSuperseded, true
case 3:
return domain.ConsentStateRevoked, true
default:
return "", false
}
}
func consentListInvalid(ctx context.Context, _ error) *api.ListMyConsentsBadRequest {
return (*api.ListMyConsentsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/cursor").Response)
}
func consentGrantInvalid(ctx context.Context, pointer string) *api.GrantMyConsentBadRequest {
return (*api.GrantMyConsentBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, pointer).Response)
}
@@ -0,0 +1,46 @@
package v1
import (
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestConsentCursorTimeBounds(t *testing.T) {
subjectID := uuid.New()
positionID := uuid.New()
for _, grantedAt := range []time.Time{
time.Unix(0, minConsentCursorNanos).UTC(),
time.Unix(0, -1).UTC(),
time.Unix(0, 0).UTC(),
time.Unix(0, maxConsentCursorNanos).UTC(),
} {
t.Run(grantedAt.String(), func(t *testing.T) {
cursor, err := encodeConsentCursor(subjectID, domain.ConsentStateActive, outbound.ConsentListPosition{
GrantedAt: grantedAt, ID: positionID,
})
if err != nil {
t.Fatalf("encode cursor at %s: %v", grantedAt, err)
}
position, state, err := decodeConsentCursor(cursor, subjectID)
if err != nil || !position.GrantedAt.Equal(grantedAt) || position.ID != positionID || state != domain.ConsentStateActive {
t.Fatalf("decode cursor = %#v, %q, %v; want time %s and matching position", position, state, err, grantedAt)
}
})
}
for _, grantedAt := range []time.Time{
time.Unix(0, minConsentCursorNanos).Add(-time.Nanosecond),
time.Unix(0, maxConsentCursorNanos).Add(time.Nanosecond),
} {
if _, err := encodeConsentCursor(subjectID, domain.ConsentStateActive, outbound.ConsentListPosition{
GrantedAt: grantedAt, ID: positionID,
}); err == nil {
t.Fatalf("encode cursor outside Unix-nanosecond range at %s: got nil error", grantedAt)
}
}
}
@@ -0,0 +1,358 @@
package v1
import (
"context"
"encoding/json"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/organization"
)
// OrganizationOperations are the organization commands and reads served by
// this HTTP adapter.
type OrganizationOperations interface {
Create(ctx context.Context, command organization.CreateCommand) (organization.CreateResult, error)
Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error)
Update(ctx context.Context, command organization.UpdateCommand) (domain.Organization, error)
}
// CreateOrganization delegates company creation to its business-area handler.
func (handler *Handler) CreateOrganization(
ctx context.Context,
request *api.OrganizationCreate,
params api.CreateOrganizationParams,
) (api.CreateOrganizationRes, error) {
if handler.organization == nil {
return handler.UnimplementedHandler.CreateOrganization(ctx, request, params)
}
return handler.organization.CreateOrganization(ctx, request, params)
}
// GetOrganization delegates company reads to their business-area handler.
func (handler *Handler) GetOrganization(
ctx context.Context,
params api.GetOrganizationParams,
) (api.GetOrganizationRes, error) {
if handler.organization == nil {
return handler.UnimplementedHandler.GetOrganization(ctx, params)
}
return handler.organization.GetOrganization(ctx, params)
}
// UpdateOrganization delegates company edits to their business-area handler.
func (handler *Handler) UpdateOrganization(
ctx context.Context,
request *api.OrganizationUpdate,
params api.UpdateOrganizationParams,
) (api.UpdateOrganizationRes, error) {
if handler.organization == nil {
return handler.UnimplementedHandler.UpdateOrganization(ctx, request, params)
}
return handler.organization.UpdateOrganization(ctx, request, params)
}
// OrganizationHandler serves organization create, read, and profile update
// operations.
type OrganizationHandler struct {
operations OrganizationOperations
publicOrigin string
}
func NewOrganizationHandler(operations OrganizationOperations, publicOrigin string) *OrganizationHandler {
return &OrganizationHandler{operations: operations, publicOrigin: publicOrigin}
}
func (handler *OrganizationHandler) CreateOrganization(
ctx context.Context,
request *api.OrganizationCreate,
params api.CreateOrganizationParams,
) (api.CreateOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.CreateOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.CreateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if request == nil {
return (*api.CreateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
canonicalBody, err := json.Marshal(request)
if err != nil {
return nil, err
}
result, err := handler.operations.Create(ctx, organization.CreateCommand{
ActorID: principal.UserID, IdempotencyKey: params.IdempotencyKey, CanonicalBody: canonicalBody,
Profile: createProfileInput(request),
})
if err != nil {
return createOrganizationFailure(ctx, err)
}
return &api.OrganizationHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: organizationFromDomain(result.Organization),
}, nil
}
func (handler *OrganizationHandler) GetOrganization(
ctx context.Context,
params api.GetOrganizationParams,
) (api.GetOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
company, err := handler.operations.Get(ctx, principal.UserID, params.OrgID)
if err != nil {
return getOrganizationFailure(ctx, err)
}
return &api.OrganizationHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: organizationFromDomain(company),
}, nil
}
func (handler *OrganizationHandler) UpdateOrganization(
ctx context.Context,
request *api.OrganizationUpdate,
params api.UpdateOrganizationParams,
) (api.UpdateOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.UpdateOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.UpdateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if request == nil {
return (*api.UpdateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
company, err := handler.operations.Update(ctx, organization.UpdateCommand{
ActorID: principal.UserID, OrganizationID: params.OrgID,
ExpectedVersion: int64(request.ExpectedVersion), Patch: updateProfilePatch(request),
})
if err != nil {
return updateOrganizationFailure(ctx, err)
}
return &api.OrganizationHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: organizationFromDomain(company),
}, nil
}
func createProfileInput(request *api.OrganizationCreate) domain.OrganizationProfileInput {
contacts := request.Contacts.Or(api.OrganizationContactChannels{})
description, _ := request.Description.Get()
sphere, _ := request.Sphere.Get()
representatives := make([]domain.OrganizationRepresentativeInput, 0, len(request.Representatives))
for _, representative := range request.Representatives {
representatives = append(representatives, domain.OrganizationRepresentativeInput{
Name: representative.Name, JobTitle: representative.JobTitle,
})
}
return domain.OrganizationProfileInput{
Name: string(request.Name), Description: string(description), Sphere: string(sphere),
Contacts: contactsToDomain(contacts), Representatives: representatives,
}
}
func updateProfilePatch(request *api.OrganizationUpdate) organization.ProfilePatch {
var patch organization.ProfilePatch
if request.Name.Set {
patch.Name = organization.OptionalString{Set: true, Value: string(request.Name.Value)}
}
if request.Description.Set {
value := ""
if !request.Description.Null {
value = string(request.Description.Value)
}
patch.Description = organization.OptionalString{Set: true, Value: value}
}
if request.Sphere.Set {
value := ""
if !request.Sphere.Null {
value = string(request.Sphere.Value)
}
patch.Sphere = organization.OptionalString{Set: true, Value: value}
}
if request.Contacts.Set {
contacts, _ := request.Contacts.Get()
input := contactsToDomain(contacts)
patch.Contacts = &input
}
if request.Representatives != nil {
representatives := make([]domain.OrganizationRepresentativeInput, 0, len(request.Representatives))
for _, representative := range request.Representatives {
representatives = append(representatives, domain.OrganizationRepresentativeInput{
Name: representative.Name, JobTitle: representative.JobTitle,
})
}
patch.Representatives = &representatives
}
return patch
}
func contactsToDomain(contacts api.OrganizationContactChannels) domain.OrganizationContactsInput {
website, _ := contacts.Website.Get()
email, _ := contacts.Email.Get()
phone, _ := contacts.Phone.Get()
telegram, _ := contacts.Telegram.Get()
return domain.OrganizationContactsInput{
Website: string(website), Email: string(email), Phone: string(phone), Telegram: string(telegram),
}
}
func organizationFromDomain(company domain.Organization) api.Organization {
profile := company.Profile()
verification := company.Verification()
representatives := representativesFromDomain(profile.Representatives())
card := company.CandidateCard()
return api.Organization{
ID: company.ID(), Version: api.OrganizationVersion(company.Version()),
Name: api.OrganizationName(profile.Name()), Description: nullableDescription(profile.Description()),
Sphere: nullableSphere(profile.Sphere()), Contacts: contactsFromDomain(profile.Contacts()),
Representatives: representatives,
Verification: api.OrganizationVerification{
Level: api.OrganizationVerificationLevel(verification.Level()),
Basis: api.OrganizationVerificationBasis(verification.Basis()),
ChangedAt: api.Timestamp(verification.ChangedAt()),
},
CandidateCard: candidateCardFromDomain(card),
CreatedAt: api.Timestamp(company.CreatedAt()),
UpdatedAt: api.Timestamp(company.UpdatedAt()),
}
}
func candidateCardFromDomain(card domain.OrganizationCandidateCard) api.CandidateOrganizationCard {
profile := card.Profile()
representatives := representativesFromDomain(profile.Representatives())
optionalRepresentatives := api.NewOptNilOrganizationRepresentativeArray(representatives)
return api.CandidateOrganizationCard{
ID: card.ID(), Name: api.OrganizationName(profile.Name()),
Description: nullableDescription(profile.Description()), Sphere: nullableSphere(profile.Sphere()),
Contacts: contactsFromDomain(profile.Contacts()), Representatives: optionalRepresentatives,
VerificationLevel: api.OrganizationVerificationLevel(card.VerificationLevel()),
}
}
func representativesFromDomain(source []domain.OrganizationRepresentative) []api.OrganizationRepresentative {
representatives := make([]api.OrganizationRepresentative, 0, len(source))
for _, representative := range source {
representatives = append(representatives, api.OrganizationRepresentative{
Name: representative.Name(), JobTitle: representative.JobTitle(),
})
}
return representatives
}
func nullableDescription(value string) api.NilOrganizationDescription {
if value == "" {
return api.NilOrganizationDescription{Null: true}
}
return api.NewNilOrganizationDescription(api.OrganizationDescription(value))
}
func nullableSphere(value string) api.NilOrganizationSphere {
if value == "" {
return api.NilOrganizationSphere{Null: true}
}
return api.NewNilOrganizationSphere(api.OrganizationSphere(value))
}
func contactsFromDomain(contacts domain.OrganizationContacts) api.OrganizationContactChannels {
return api.OrganizationContactChannels{
Website: nullableWebsite(contacts.Website()), Email: nullableEmail(contacts.Email()),
Phone: nullablePhone(contacts.Phone()), Telegram: nullableTelegram(contacts.Telegram()),
}
}
func nullableWebsite(value string) api.NilOrganizationWebsite {
if value == "" {
return api.NilOrganizationWebsite{Null: true}
}
return api.NewNilOrganizationWebsite(api.OrganizationWebsite(value))
}
func nullableEmail(value string) api.NilEmailAddress {
if value == "" {
return api.NilEmailAddress{Null: true}
}
return api.NewNilEmailAddress(api.EmailAddress(value))
}
func nullablePhone(value string) api.NilContactPhoneNumber {
if value == "" {
return api.NilContactPhoneNumber{Null: true}
}
return api.NewNilContactPhoneNumber(api.ContactPhoneNumber(value))
}
func nullableTelegram(value string) api.NilContactTelegramUsername {
if value == "" {
return api.NilContactTelegramUsername{Null: true}
}
return api.NewNilContactTelegramUsername(api.ContactTelegramUsername(value))
}
func createOrganizationFailure(ctx context.Context, err error) (api.CreateOrganizationRes, error) {
switch {
case errors.Is(err, organization.ErrForbidden):
return (*api.CreateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.CreateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, organization.ErrIdempotencyKeyReused):
return (*api.CreateOrganizationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, organization.ErrInvalidIdempotencyKey):
return (*api.CreateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case errors.Is(err, organization.ErrInvalidCreateRequest):
return (*api.CreateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
case errors.Is(err, domain.ErrInvalidOrganization):
return (*api.CreateOrganizationBadRequest)(&organizationFieldProblem(ctx, err).Response), nil
default:
return nil, err
}
}
func getOrganizationFailure(ctx context.Context, err error) (api.GetOrganizationRes, error) {
switch {
case errors.Is(err, organization.ErrForbidden):
return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.GetOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
func updateOrganizationFailure(ctx context.Context, err error) (api.UpdateOrganizationRes, error) {
switch {
case errors.Is(err, organization.ErrForbidden), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.UpdateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.UpdateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.UpdateOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, outbound.ErrOrganizationVersionConflict):
return (*api.UpdateOrganizationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, domain.ErrInvalidOrganization):
return (*api.UpdateOrganizationBadRequest)(&organizationFieldProblem(ctx, err).Response), nil
default:
return nil, err
}
}
func organizationFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode {
field, ok := errors.AsType[*domain.OrganizationFieldError](err)
if !ok {
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
}
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer)
}
@@ -0,0 +1,211 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type accountDeletionRequestRepository struct {
queries *sqlc.Queries
}
func (unit *UnitOfWork) AccountDeletionRequests() outbound.AccountDeletionRequests {
return accountDeletionRequestRepository{queries: unit.queries}
}
func (repository accountDeletionRequestRepository) CreateOrGet(
ctx context.Context,
request domain.AccountDeletionRequest,
) (domain.AccountDeletionRequest, bool, error) {
if request.IsZero() {
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - request is not initialized: %w", domain.ErrInvalidConsent)
}
row, err := repository.queries.CreateAccountDeletionRequest(ctx, sqlc.CreateAccountDeletionRequestParams{
ID: pgUUID(request.ID()),
SubjectID: pgUUID(request.SubjectID()),
RequestedAt: pgTime(request.RequestedAt()),
})
if err == nil {
stored, err := accountDeletionRequestFromRow(row.ID, row.SubjectID, row.Status, row.RequestedAt)
return stored, err == nil, err
}
if !errors.Is(err, pgx.ErrNoRows) {
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - insert request: %w", mapConsentError(err))
}
activeRow, err := repository.queries.GetActiveAccountDeletionRequest(ctx, pgUUID(request.SubjectID()))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - concurrent request was not readable: %w", outbound.ErrTransactionConflict)
}
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - select active request: %w", mapConsentError(err))
}
stored, err := accountDeletionRequestFromRow(activeRow.ID, activeRow.SubjectID, activeRow.Status, activeRow.RequestedAt)
return stored, false, err
}
func accountDeletionRequestFromRow(id, subjectID pgtype.UUID, status string, requestedAt pgtype.Timestamptz) (domain.AccountDeletionRequest, error) {
if !id.Valid || !subjectID.Valid || !requestedAt.Valid {
return domain.AccountDeletionRequest{}, fmt.Errorf("postgres.accountDeletionRequestFromRow - required column is null: %w", domain.ErrInvalidConsent)
}
request, err := domain.RestoreAccountDeletionRequest(id.Bytes, subjectID.Bytes, status, requestedAt.Time)
if err != nil {
return domain.AccountDeletionRequest{}, fmt.Errorf("postgres.accountDeletionRequestFromRow - restore request: %w", err)
}
return request, nil
}
type consentRevocationEffects struct {
queries *sqlc.Queries
}
func (unit *UnitOfWork) ConsentRevocationEffects() outbound.ConsentRevocationEffects {
return consentRevocationEffects{queries: unit.queries}
}
var _ outbound.ConsentRevocationEffects = consentRevocationEffects{}
func (effects consentRevocationEffects) Apply(
ctx context.Context,
revocation domain.ConsentRevocation,
records []domain.ConsentRecord,
) error {
if revocation.IsZero() || len(records) == 0 {
return fmt.Errorf("consentRevocationEffects.Apply - revocation and affected records are required: %w", domain.ErrInvalidConsent)
}
for _, record := range records {
if record.IsZero() || record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() ||
(revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) {
return fmt.Errorf("consentRevocationEffects.Apply - record scope does not match revocation: %w", domain.ErrInvalidConsent)
}
}
if revocation.Purpose() == domain.ConsentPurposePublication {
if err := effects.closePublication(ctx, revocation, records); err != nil {
return fmt.Errorf("consentRevocationEffects.Apply - close publication: %w", err)
}
}
if err := effects.appendRevocationIntent(ctx, revocation, records); err != nil {
return fmt.Errorf("consentRevocationEffects.Apply - append outbox intent: %w", err)
}
return nil
}
func (effects consentRevocationEffects) closePublication(
ctx context.Context,
revocation domain.ConsentRevocation,
records []domain.ConsentRecord,
) error {
const location = "consentRevocationEffects.closePublication"
recordIDs := make([]pgtype.UUID, 0, len(records))
for _, record := range records {
if record.Purpose() == domain.ConsentPurposePublication {
recordIDs = append(recordIDs, pgUUID(record.ID()))
}
}
if len(recordIDs) == 0 {
return fmt.Errorf("%s - revoked C2 record IDs are required: %w", location, domain.ErrInvalidConsent)
}
row, err := effects.queries.LockCandidatePublicationForConsentRevocation(ctx, sqlc.LockCandidatePublicationForConsentRevocationParams{
UserID: pgUUID(revocation.SubjectID()), ConsentRecordIds: recordIDs,
})
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return fmt.Errorf("%s - close publication: %w", location, mapConsentError(err))
}
if !row.Valid {
return fmt.Errorf("%s - query returned no closing time: %w", location, domain.ErrInvalidVisibility)
}
event, err := domain.NewConsentRevokedPublicationEvent(revocation.SubjectID(), row.Time)
if err != nil {
return fmt.Errorf("%s - build publication privacy event: %w", location, err)
}
if err := effects.queries.InsertCandidatePrivacyEvent(ctx, sqlc.InsertCandidatePrivacyEventParams{
ID: pgUUID(event.ID()),
UserID: pgUUID(event.UserID()),
Kind: string(event.Kind()),
OccurredAt: pgTime(event.OccurredAt()),
Fields: event.Fields().Codes(),
ConsentRecordID: pgtype.UUID{},
OrganizationID: pgtype.UUID{},
}); err != nil {
return fmt.Errorf("%s - record publication privacy event: %w", location, mapConsentError(err))
}
return nil
}
type consentRevocationPayload struct {
RevocationID uuid.UUID `json:"revocation_id"`
RecordID uuid.UUID `json:"record_id"`
SubjectID uuid.UUID `json:"subject_id"`
Purpose domain.ConsentPurpose `json:"purpose"`
Source domain.ConsentRevocationSource `json:"source"`
RevokedAt time.Time `json:"revoked_at"`
OrganizationID *uuid.UUID `json:"organization_id,omitempty"`
Fields []domain.ContactField `json:"fields,omitempty"`
}
func (effects consentRevocationEffects) appendRevocationIntent(
ctx context.Context,
revocation domain.ConsentRevocation,
records []domain.ConsentRecord,
) error {
events, err := newConsentRevocationEvents(revocation, records)
if err != nil {
return fmt.Errorf("consentRevocationEffects.appendRevocationIntent - build events: %w", err)
}
if err := outboxWriter(effects).Append(ctx, events...); err != nil {
return fmt.Errorf("consentRevocationEffects.appendRevocationIntent - append events: %w", err)
}
return nil
}
func newConsentRevocationEvents(revocation domain.ConsentRevocation, records []domain.ConsentRecord) ([]domain.DomainEvent, error) {
if revocation.IsZero() || len(records) == 0 {
return nil, fmt.Errorf("newConsentRevocationEvents - revocation and records are required: %w", domain.ErrInvalidConsent)
}
revocationID, err := uuid.NewV7()
if err != nil {
return nil, fmt.Errorf("newConsentRevocationEvents - generate revocation ID: %w", err)
}
events := make([]domain.DomainEvent, 0, len(records))
for _, record := range records {
if record.IsZero() || record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() ||
(revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) {
return nil, fmt.Errorf("newConsentRevocationEvents - record scope does not match revocation: %w", domain.ErrInvalidConsent)
}
payload := consentRevocationPayload{
RevocationID: revocationID, RecordID: record.ID(), SubjectID: revocation.SubjectID(),
Purpose: revocation.Purpose(), Source: revocation.Source(), RevokedAt: revocation.RevokedAt(),
}
if revocation.Purpose().OrganizationScoped() {
organizationID := record.OrganizationID()
payload.OrganizationID = &organizationID
payload.Fields = record.Fields().Fields()
}
body, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("newConsentRevocationEvents - marshal payload: %w", err)
}
event, err := domain.NewDomainEvent(domain.DomainEventInput{
EventType: "consent.revoked", SchemaVersion: 1, AggregateType: "consent_record",
AggregateID: record.ID(), AggregateVersion: 2, Payload: body,
})
if err != nil {
return nil, fmt.Errorf("newConsentRevocationEvents - build event: %w", err)
}
events = append(events, event)
}
return events, nil
}
@@ -0,0 +1,91 @@
package postgres
import (
"encoding/json"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
func TestConsentRevocationEventsStayBoundedForLargeContactHistory(t *testing.T) {
const historySize = 500
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
organization := uuid.New()
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
SubjectID: subject, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: organization,
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: now,
})
if err != nil {
t.Fatal(err)
}
fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone)
if err != nil {
t.Fatal(err)
}
fieldCodes := make([]string, 0, len(fields.Fields()))
for _, field := range fields.Fields() {
fieldCodes = append(fieldCodes, string(field))
}
hash := domain.HashConsentText("c4 text with the stored organization snapshot")
records := make([]domain.ConsentRecord, 0, historySize)
legacyFacts := make([]uuid.UUID, 0, historySize)
for index := 0; index < historySize; index++ {
id := uuid.New()
legacyFacts = append(legacyFacts, id)
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: id, SubjectID: subject, Purpose: string(domain.ConsentPurposeContactDisclosure),
TextVersion: "c4-2026-10-01", TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance),
State: string(domain.ConsentStateActive), GrantedAt: now.Add(-time.Duration(index+1) * time.Minute),
OrganizationID: organization, OrganizationName: "Acme Synthetic LLC", FieldSet: fieldCodes,
InvitationID: uuid.New(), InvitationTermsVersion: 1,
})
if err != nil {
t.Fatalf("RestoreConsentRecord() error = %v", err)
}
records = append(records, record)
}
legacyPayload, err := json.Marshal(map[string]any{"records": legacyFacts})
if err != nil {
t.Fatal(err)
}
if len(legacyPayload) <= domain.MaxDomainEventPayloadBytes {
t.Fatalf("legacy aggregate fixture has %d bytes; expected it to exceed %d", len(legacyPayload), domain.MaxDomainEventPayloadBytes)
}
events, err := newConsentRevocationEvents(revocation, records)
if err != nil {
t.Fatalf("newConsentRevocationEvents() error = %v", err)
}
if len(events) != historySize {
t.Fatalf("event count = %d, want one for every revoked record (%d)", len(events), historySize)
}
seen := make(map[uuid.UUID]bool, historySize)
for _, event := range events {
if event.AggregateType() != "consent_record" || event.AggregateVersion() != 2 || event.EventType() != "consent.revoked" {
t.Fatalf("event identity = %s/%s/%d, want one revoked record version", event.EventType(), event.AggregateType(), event.AggregateVersion())
}
if len(event.Payload()) > domain.MaxDomainEventPayloadBytes {
t.Fatalf("event payload has %d bytes, above the limit", len(event.Payload()))
}
var payload struct {
RecordID uuid.UUID `json:"record_id"`
SubjectID uuid.UUID `json:"subject_id"`
Purpose domain.ConsentPurpose `json:"purpose"`
OrganizationID uuid.UUID `json:"organization_id"`
Fields []domain.ContactField `json:"fields"`
}
if err := json.Unmarshal(event.Payload(), &payload); err != nil {
t.Fatalf("decode event payload: %v", err)
}
if event.AggregateID() != payload.RecordID || payload.RecordID == uuid.Nil || seen[payload.RecordID] ||
payload.SubjectID != subject || payload.Purpose != domain.ConsentPurposeContactDisclosure ||
payload.OrganizationID != organization || len(payload.Fields) != 1 || payload.Fields[0] != domain.ContactFieldPhone {
t.Fatalf("event payload lost or changed a stored revocation fact: %+v", payload)
}
seen[payload.RecordID] = true
}
}
@@ -22,11 +22,12 @@ import (
// 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,
{foreignKeyViolationCode, "account_deletion_requests_subject_id_fkey"}: outbound.ErrUserNotFound,
{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,
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
@@ -59,6 +60,8 @@ type organizationRepository struct {
var _ outbound.OrganizationRepository = organizationRepository{}
const maxOrganizationCreationSnapshotBytes = 65536
func (repository organizationRepository) CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error {
const location = "organizationRepository.CreateWithOwner"
switch {
@@ -100,6 +103,158 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or
return nil
}
func (repository organizationRepository) SaveCreationResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
result outbound.OrganizationCreationResult,
) error {
const location = "organizationRepository.SaveCreationResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) || result.Organization.IsZero() || result.Owner.IsZero() ||
result.Owner.OrganizationID() != result.Organization.ID() || result.Owner.Role() != domain.OrganizationRoleOwner ||
!result.Owner.GrantsAccess() {
return fmt.Errorf("%s - scope and active owner result must be set: %w", location, domain.ErrInvalidOrganization)
}
snapshot := creationSnapshotFromDomain(result)
encoded, err := json.Marshal(snapshot)
if err != nil {
return fmt.Errorf("%s - encode domain snapshot", location)
}
if len(encoded) > maxOrganizationCreationSnapshotBytes {
return fmt.Errorf("%s - domain snapshot exceeds its storage bound: %w", location, domain.ErrInvalidOrganization)
}
if err := repository.queries.SaveOrganizationCreationResult(ctx, sqlc.SaveOrganizationCreationResultParams{
ScopeHash: scope[:],
Snapshot: encoded,
}); err != nil {
return fmt.Errorf("%s - store domain snapshot: %w", location, mapOrganizationError(err))
}
return nil
}
func (repository organizationRepository) GetCreationResult(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (outbound.OrganizationCreationResult, error) {
const location = "organizationRepository.GetCreationResult"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - scope must be set: %w", location, domain.ErrInvalidOrganization)
}
encoded, err := repository.queries.GetOrganizationCreationResult(ctx, scope[:])
if err != nil {
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - read domain snapshot: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationCreationResultNotFound))
}
if len(encoded) > maxOrganizationCreationSnapshotBytes {
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - stored domain snapshot exceeds its bound", location)
}
var snapshot organizationCreationSnapshot
if err := json.Unmarshal(encoded, &snapshot); err != nil {
// The snapshot contains company profile data and representative names.
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - stored domain snapshot is invalid", location)
}
result, err := snapshot.domainResult()
if err != nil {
return outbound.OrganizationCreationResult{}, fmt.Errorf("%s - restore domain snapshot: %w", location, err)
}
return result, nil
}
type organizationCreationSnapshot struct {
Organization organizationCreationOrganizationSnapshot `json:"organization"`
Owner organizationCreationMembershipSnapshot `json:"owner"`
}
type organizationCreationOrganizationSnapshot struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Sphere string `json:"sphere"`
Website string `json:"website"`
Email string `json:"email"`
Phone string `json:"phone"`
Telegram string `json:"telegram"`
Representatives []organizationCreationRepresentativeSnapshot `json:"representatives"`
VerificationLevel string `json:"verification_level"`
VerificationBasis string `json:"verification_basis"`
VerificationChangedAt time.Time `json:"verification_changed_at"`
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type organizationCreationRepresentativeSnapshot struct {
Name string `json:"name"`
JobTitle string `json:"job_title"`
}
type organizationCreationMembershipSnapshot struct {
ID uuid.UUID `json:"id"`
OrganizationID uuid.UUID `json:"organization_id"`
UserID uuid.UUID `json:"user_id"`
Role string `json:"role"`
State string `json:"state"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func creationSnapshotFromDomain(result outbound.OrganizationCreationResult) organizationCreationSnapshot {
organization := result.Organization
profile := organization.Profile()
contacts := profile.Contacts()
representatives := profile.Representatives()
snapshotRepresentatives := make([]organizationCreationRepresentativeSnapshot, 0, len(representatives))
for _, representative := range representatives {
snapshotRepresentatives = append(snapshotRepresentatives, organizationCreationRepresentativeSnapshot{
Name: representative.Name(), JobTitle: representative.JobTitle(),
})
}
verification := organization.Verification()
owner := result.Owner
return organizationCreationSnapshot{
Organization: organizationCreationOrganizationSnapshot{
ID: organization.ID(), Name: profile.Name(), Description: profile.Description(), Sphere: profile.Sphere(),
Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(),
Representatives: snapshotRepresentatives, VerificationLevel: string(verification.Level()),
VerificationBasis: string(verification.Basis()), VerificationChangedAt: verification.ChangedAt(),
Version: organization.Version(), CreatedAt: organization.CreatedAt(), UpdatedAt: organization.UpdatedAt(),
},
Owner: organizationCreationMembershipSnapshot{
ID: owner.ID(), OrganizationID: owner.OrganizationID(), UserID: owner.UserID(), Role: string(owner.Role()),
State: string(owner.State()), CreatedAt: owner.CreatedAt(), UpdatedAt: owner.UpdatedAt(),
},
}
}
func (snapshot organizationCreationSnapshot) domainResult() (outbound.OrganizationCreationResult, error) {
stored := snapshot.Organization
representatives := make([]domain.StoredRepresentative, 0, len(stored.Representatives))
for _, representative := range stored.Representatives {
representatives = append(representatives, domain.StoredRepresentative{
Name: representative.Name, JobTitle: representative.JobTitle,
})
}
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
ID: stored.ID, Name: stored.Name, Description: stored.Description, Sphere: stored.Sphere,
Website: stored.Website, Email: stored.Email, Phone: stored.Phone, Telegram: stored.Telegram,
Representatives: representatives, VerificationLevel: stored.VerificationLevel, VerificationBasis: stored.VerificationBasis,
VerificationChangedAt: stored.VerificationChangedAt, Version: stored.Version, CreatedAt: stored.CreatedAt, UpdatedAt: stored.UpdatedAt,
})
if err != nil {
return outbound.OrganizationCreationResult{}, err
}
owner := snapshot.Owner
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: owner.ID, OrganizationID: owner.OrganizationID, UserID: owner.UserID,
Role: owner.Role, State: owner.State, CreatedAt: owner.CreatedAt, UpdatedAt: owner.UpdatedAt,
})
if err != nil {
return outbound.OrganizationCreationResult{}, err
}
if membership.OrganizationID() != organization.ID() || membership.Role() != domain.OrganizationRoleOwner || !membership.GrantsAccess() {
return outbound.OrganizationCreationResult{}, domain.ErrInvalidMembership
}
return outbound.OrganizationCreationResult{Organization: organization, Owner: membership}, nil
}
func (repository organizationRepository) insertRepresentatives(
ctx context.Context,
organizationID uuid.UUID,
@@ -2,9 +2,11 @@ package postgres
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
@@ -81,3 +83,50 @@ func TestManagerRoleNamesFollowTheDomainRule(t *testing.T) {
t.Fatalf("managerRoleNames() = %v, want only the owner", got)
}
}
func TestOrganizationCreationSnapshotRoundTripsDomainResult(t *testing.T) {
at := time.Date(2026, 8, 15, 10, 30, 0, 123456789, time.UTC)
profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{
Name: "ООО Пример", Description: "Описание", Sphere: "Платежи",
Contacts: domain.OrganizationContactsInput{
Website: "https://example.com", Email: "careers@example.com", Phone: "+74951234567", Telegram: "@example",
},
Representatives: []domain.OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Директор"}},
})
if err != nil {
t.Fatalf("NewOrganizationProfile() error = %v", err)
}
company, err := domain.NewOrganization(profile, at)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
owner, err := domain.NewOwnerMembership(company.ID(), uuid.New(), at)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
result := outbound.OrganizationCreationResult{Organization: company, Owner: owner}
snapshot := creationSnapshotFromDomain(result)
encoded, err := json.Marshal(snapshot)
if err != nil {
t.Fatalf("Marshal(snapshot) error = %v", err)
}
var decoded organizationCreationSnapshot
if err := json.Unmarshal(encoded, &decoded); err != nil {
t.Fatalf("Unmarshal(snapshot) error = %v", err)
}
got, err := decoded.domainResult()
if err != nil {
t.Fatalf("domainResult() error = %v", err)
}
if got.Organization.ID() != company.ID() || got.Organization.Version() != company.Version() ||
!got.Organization.Profile().Equal(company.Profile()) ||
got.Organization.Verification().Level() != domain.OrganizationVerificationE0 ||
got.Organization.Verification().Basis() != domain.OrganizationBasisConfirmedEmail ||
!got.Organization.CreatedAt().Equal(at) || got.Owner.ID() != owner.ID() || got.Owner.UserID() != owner.UserID() ||
got.Owner.OrganizationID() != company.ID() || got.Owner.Role() != domain.OrganizationRoleOwner || !got.Owner.GrantsAccess() {
t.Fatal("creation snapshot did not preserve the original organization and owner result")
}
if len(encoded) > maxOrganizationCreationSnapshotBytes {
t.Fatalf("snapshot size = %d, want at most %d bytes", len(encoded), maxOrganizationCreationSnapshotBytes)
}
}
@@ -11,6 +11,82 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const createAccountDeletionRequest = `-- name: CreateAccountDeletionRequest :one
INSERT INTO account_deletion_requests (
id,
subject_id,
status,
requested_at
) VALUES (
$1,
$2,
'requested',
$3
)
ON CONFLICT (subject_id)
WHERE subject_id IS NOT NULL AND status IN ('requested', 'processing')
DO NOTHING
RETURNING id, subject_id, status, requested_at
`
type CreateAccountDeletionRequestParams struct {
ID pgtype.UUID
SubjectID pgtype.UUID
RequestedAt pgtype.Timestamptz
}
type CreateAccountDeletionRequestRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Status string
RequestedAt pgtype.Timestamptz
}
// Creates one durable deletion request per subject until a worker completes it.
// The caller appends the matching outbox intent in the same transaction only
// when this insert returns a row.
func (q *Queries) CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error) {
row := q.db.QueryRow(ctx, createAccountDeletionRequest, arg.ID, arg.SubjectID, arg.RequestedAt)
var i CreateAccountDeletionRequestRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Status,
&i.RequestedAt,
)
return i, err
}
const getActiveAccountDeletionRequest = `-- name: GetActiveAccountDeletionRequest :one
SELECT id, subject_id, status, requested_at
FROM account_deletion_requests
WHERE subject_id = $1
AND status IN ('requested', 'processing')
ORDER BY requested_at, id
LIMIT 1
`
type GetActiveAccountDeletionRequestRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Status string
RequestedAt pgtype.Timestamptz
}
// Reads the durable active deletion request when an earlier request already
// exists. A completed request does not suppress a later explicit request.
func (q *Queries) GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error) {
row := q.db.QueryRow(ctx, getActiveAccountDeletionRequest, subjectID)
var i GetActiveAccountDeletionRequestRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Status,
&i.RequestedAt,
)
return i, err
}
const getConsentText = `-- name: GetConsentText :one
SELECT
purpose,
@@ -8,6 +8,14 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
type AccountDeletionRequest struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Status string
RequestedAt pgtype.Timestamptz
CompletedAt pgtype.Timestamptz
}
type AssessmentCategoryOpening struct {
ID pgtype.UUID
Category string
@@ -315,6 +323,11 @@ type Organization struct {
UpdatedAt pgtype.Timestamptz
}
type OrganizationCreationResult struct {
ScopeHash []byte
Snapshot []byte
}
type OrganizationRepresentative struct {
OrganizationID pgtype.UUID
Ordinal int16
@@ -57,6 +57,21 @@ func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (M
return i, err
}
const getOrganizationCreationResult = `-- name: GetOrganizationCreationResult :one
SELECT snapshot
FROM organization_creation_results
WHERE scope_hash = $1
`
// Reads only the historical result. It intentionally does not join the live
// organization or membership, whose profile and state may have since changed.
func (q *Queries) GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error) {
row := q.db.QueryRow(ctx, getOrganizationCreationResult, scopeHash)
var snapshot []byte
err := row.Scan(&snapshot)
return snapshot, err
}
const getOrganizationForMember = `-- name: GetOrganizationForMember :one
SELECT
organization.id,
@@ -390,6 +405,27 @@ func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganiza
return items, nil
}
const saveOrganizationCreationResult = `-- name: SaveOrganizationCreationResult :exec
INSERT INTO organization_creation_results (scope_hash, snapshot)
VALUES ($1, $2)
ON CONFLICT (scope_hash) DO UPDATE
SET snapshot = excluded.snapshot
`
type SaveOrganizationCreationResultParams struct {
ScopeHash []byte
Snapshot []byte
}
// Stores the immutable domain snapshot of a successful create command. The
// generic idempotency row and this result are committed with the organization
// and owner membership. A reused expired scope replaces the snapshot in the
// same transaction as the new organization.
func (q *Queries) SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error {
_, err := q.db.Exec(ctx, saveOrganizationCreationResult, arg.ScopeHash, arg.Snapshot)
return err
}
const updateOrganizationProfile = `-- name: UpdateOrganizationProfile :one
WITH target AS (
SELECT id FROM organizations
@@ -421,6 +421,38 @@ func (q *Queries) ListCandidatePrivacyEvents(ctx context.Context, arg ListCandid
return items, nil
}
const lockCandidatePublicationForConsentRevocation = `-- name: LockCandidatePublicationForConsentRevocation :one
SELECT greatest(candidate_publications.published_at, consent_records.revoked_at)::timestamptz AS closed_at
FROM candidate_publications
INNER JOIN consent_records
ON consent_records.id = candidate_publications.consent_record_id
WHERE
candidate_publications.user_id = $1
AND candidate_publications.state = 'published'
AND consent_records.id = ANY($2::uuid [])
AND consent_records.subject_id = candidate_publications.user_id
AND consent_records.purpose = 'c2'
AND consent_records.revoked_at IS NOT NULL
FOR UPDATE OF candidate_publications
`
type LockCandidatePublicationForConsentRevocationParams struct {
UserID pgtype.UUID
ConsentRecordIds []pgtype.UUID
}
// Locks the candidate's published row only when it refers to a C2 record
// revoked by this transaction. The setting remains linked to that immutable
// record; ReadCandidatePublication computes the effective closed state and
// keeps the consent-revoked reason after later grants. The returned time is
// the effective close time used by the privacy history event.
func (q *Queries) LockCandidatePublicationForConsentRevocation(ctx context.Context, arg LockCandidatePublicationForConsentRevocationParams) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, lockCandidatePublicationForConsentRevocation, arg.UserID, arg.ConsentRecordIds)
var closed_at pgtype.Timestamptz
err := row.Scan(&closed_at)
return closed_at, err
}
const lockCurrentC2Record = `-- name: LockCurrentC2Record :one
SELECT id
FROM consent_records
@@ -107,6 +107,10 @@ type Querier interface {
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
// Creates one durable deletion request per subject until a worker completes it.
// The caller appends the matching outbox intent in the same transaction only
// when this insert returns a row.
CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error)
// Lifts one hiding. No row returns when the organization was not hidden, so
// the caller writes the history event only for a real deletion and answers
// 204 either way.
@@ -156,6 +160,9 @@ type Querier interface {
// made at or after reserved_since. A retry of the delivery inside the
// provider's idempotency window reuses it instead of counting again.
FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error)
// Reads the durable active deletion request when an earlier request already
// exists. A completed request does not suppress a later explicit request.
GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error)
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
@@ -207,6 +214,9 @@ type Querier interface {
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
// Reads the membership of one account in one organization, in any state.
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
// Reads only the historical result. It intentionally does not join the live
// organization or membership, whose profile and state may have since changed.
GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error)
// Reads an organization together with the membership of one account in it
// and its representatives in list order, as one statement, so the profile and
// the list come from one snapshot. Only an active membership matches, so an
@@ -377,6 +387,12 @@ type Querier interface {
// published or open the category, until the transaction ends. The key is
// namespaced, so it cannot collide with another use of advisory locks.
LockAssessmentCategory(ctx context.Context, category string) error
// Locks the candidate's published row only when it refers to a C2 record
// revoked by this transaction. The setting remains linked to that immutable
// record; ReadCandidatePublication computes the effective closed state and
// keeps the consent-revoked reason after later grants. The returned time is
// the effective close time used by the privacy history event.
LockCandidatePublicationForConsentRevocation(ctx context.Context, arg LockCandidatePublicationForConsentRevocationParams) (pgtype.Timestamptz, error)
// Locks the delivery row of the lease holder until the transaction ends, so
// every path that settles a send takes the delivery lock before the quota
// rows, the same order as the claim. No row means that owner no longer holds
@@ -542,6 +558,11 @@ type Querier interface {
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
// Stores the immutable domain snapshot of a successful create command. The
// generic idempotency row and this result are committed with the organization
// and owner membership. A reused expired scope replaces the snapshot in the
// same transaction as the new organization.
SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error
// Bounds a consumer transaction on the server, local to the transaction.
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
// ends the session of a process that froze or lost the network inside the
+27
View File
@@ -0,0 +1,27 @@
package bootstrap
import (
"context"
"time"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/usecase/consent"
)
const consentPoolMaxConns = 4
func newConsentHandler(ctx context.Context, settings config.Config) (*v1.ConsentHandler, func(), error) {
if settings.DatabaseURL == "" {
return nil, func() {}, nil
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, consentPoolMaxConns)
if err != nil {
return nil, nil, err
}
store := postgres.NewConsentStore(pool)
reader := consent.NewQueryService(store, time.Now)
commands := consent.NewService(postgres.NewTransactor(pool), time.Now)
return v1.NewConsentHandler(reader, commands), pool.Close, nil
}
+16 -6
View File
@@ -31,8 +31,18 @@ func newTrustedProxies(settings config.Config) []netip.Prefix { return settings.
// newAPIHandler composes the handler of the public API from the business
// areas that are built. An area without a handler answers 501.
func newAPIHandler(health *v1.HealthHandler, problems *problem.Responder, identityHandler *v1.IdentityHandler) *v1.Handler {
return v1.NewHandler(health, problems, v1.WithIdentity(identityHandler))
func newAPIHandler(
health *v1.HealthHandler,
problems *problem.Responder,
identityHandler *v1.IdentityHandler,
consentHandler *v1.ConsentHandler,
organizationHandler *v1.OrganizationHandler,
) *v1.Handler {
return v1.NewHandler(health, problems,
v1.WithIdentity(identityHandler),
v1.WithConsent(consentHandler),
v1.WithOrganization(organizationHandler),
)
}
// newIdentityHandler builds the registration and session operations and the
@@ -45,15 +55,12 @@ func newIdentityHandler(
logger *slog.Logger,
cache *redisadapter.Cache,
metrics *prometheus.Metrics,
keyring *identity.Keyring,
) (*v1.IdentityHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("identity operations are not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
keyring, err := newIdentityKeyring(settings, logger)
if err != nil {
return nil, nil, err
}
renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create mail renderer: %w", err)
@@ -146,6 +153,9 @@ func newIdentityHandler(
// counters no longer match after restart, and CSRF tokens differ between
// restarts and instances.
func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.Keyring, error) {
if settings.DatabaseURL == "" {
return nil, nil
}
secret := []byte(settings.IdentityKeySecret)
if len(secret) == 0 {
secret = make([]byte, identity.MinKeySecretBytes)
@@ -0,0 +1,48 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/organization"
)
const organizationPoolMaxConns = 8
// newOrganizationHandler builds company reads and writes from the PostgreSQL
// transaction boundary. Without DATABASE_URL the composite handler keeps the
// operations on its 501 fallback.
func newOrganizationHandler(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
keyring *identity.Keyring,
) (*v1.OrganizationHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("organization operations are not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
if keyring == nil {
return nil, nil, fmt.Errorf("bootstrap.newOrganizationHandler - identity keyring must be set")
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, organizationPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newOrganizationHandler - create pool: %w", err)
}
service, err := organization.NewService(organization.Dependencies{
Transactor: postgres.NewTransactor(pool),
Keyring: keyring,
Clock: time.Now,
})
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newOrganizationHandler - create service: %w", err)
}
return v1.NewOrganizationHandler(service, settings.AppPublicURL), pool.Close, nil
}
+3
View File
@@ -47,6 +47,9 @@ func initialize(
newAPIHandler,
newTrustedProxies,
newIdentityHandler,
newIdentityKeyring,
newConsentHandler,
newOrganizationHandler,
newSessionSecurity,
httpadapter.NewRouter,
newOutboxRelay,
+55 -17
View File
@@ -46,17 +46,21 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
healthHandler := newHealthHandler(readiness, config2)
responder := problem.NewResponder(logger)
metrics := prometheus.New()
identityHandler, cleanup4, err := newIdentityHandler(ctx, config2, logger, cache, metrics)
keyring, err := newIdentityKeyring(config2, logger)
if err != nil {
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v)
identityHandler, cleanup4, err := newIdentityHandler(ctx, config2, logger, cache, metrics, keyring)
if err != nil {
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
consentHandler, cleanup5, err := newConsentHandler(ctx, config2)
if err != nil {
cleanup4()
cleanup3()
@@ -64,15 +68,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
relay, cleanup5, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup6, err := newEventConsumers(ctx, config2, logger, metrics)
organizationHandler, cleanup6, err := newOrganizationHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup5()
cleanup4()
@@ -81,7 +77,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
worker, cleanup7, err := newJobWorker(ctx, config2, logger, metrics)
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, organizationHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v)
if err != nil {
cleanup6()
cleanup5()
@@ -91,7 +90,17 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup8, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
relay, cleanup7, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup8, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup7()
cleanup6()
@@ -102,7 +111,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup9, err := newDeliveryMetrics(ctx, config2, logger, metrics)
worker, cleanup9, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup8()
cleanup7()
@@ -114,8 +123,37 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup10, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
sampler, cleanup11, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
return application, func() {
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
@@ -0,0 +1,55 @@
package domain
import (
"fmt"
"time"
"github.com/google/uuid"
)
type AccountDeletionRequestStatus string
const (
AccountDeletionRequestStatusRequested AccountDeletionRequestStatus = "requested"
AccountDeletionRequestStatusProcessing AccountDeletionRequestStatus = "processing"
)
type AccountDeletionRequest struct {
id uuid.UUID
subjectID uuid.UUID
status AccountDeletionRequestStatus
requestedAt time.Time
}
func NewAccountDeletionRequest(subjectID uuid.UUID, requestedAt time.Time) (AccountDeletionRequest, error) {
if subjectID == uuid.Nil || requestedAt.IsZero() {
return AccountDeletionRequest{}, fmt.Errorf("domain.NewAccountDeletionRequest - subject and request time must be set: %w", ErrInvalidConsent)
}
id, err := uuid.NewV7()
if err != nil {
return AccountDeletionRequest{}, fmt.Errorf("domain.NewAccountDeletionRequest - generate ID: %w", err)
}
return AccountDeletionRequest{
id: id, subjectID: subjectID, status: AccountDeletionRequestStatusRequested, requestedAt: requestedAt,
}, nil
}
func RestoreAccountDeletionRequest(id, subjectID uuid.UUID, status string, requestedAt time.Time) (AccountDeletionRequest, error) {
if id == uuid.Nil || subjectID == uuid.Nil || requestedAt.IsZero() ||
(status != string(AccountDeletionRequestStatusRequested) && status != string(AccountDeletionRequestStatusProcessing)) {
return AccountDeletionRequest{}, fmt.Errorf("domain.RestoreAccountDeletionRequest - stored request is invalid: %w", ErrInvalidConsent)
}
return AccountDeletionRequest{
id: id, subjectID: subjectID, status: AccountDeletionRequestStatus(status), requestedAt: requestedAt,
}, nil
}
func (request AccountDeletionRequest) ID() uuid.UUID { return request.id }
func (request AccountDeletionRequest) SubjectID() uuid.UUID { return request.subjectID }
func (request AccountDeletionRequest) Status() AccountDeletionRequestStatus { return request.status }
func (request AccountDeletionRequest) RequestedAt() time.Time { return request.requestedAt }
func (request AccountDeletionRequest) IsZero() bool { return request.id == uuid.Nil }
+11
View File
@@ -692,6 +692,17 @@ func NewPublicationEvent(change PublicationChange, at time.Time) (PrivacyEvent,
return completeEvent(location, event)
}
// NewConsentRevokedPublicationEvent records the closure caused by revoking
// C2. The event deliberately carries neither published fields nor a consent
// identifier; the consent ledger and publication table remain the sources of
// the detailed history.
func NewConsentRevokedPublicationEvent(userID uuid.UUID, at time.Time) (PrivacyEvent, error) {
const location = "domain.NewConsentRevokedPublicationEvent"
return completeEvent(location, PrivacyEvent{
userID: userID, kind: PrivacyEventPublicationClosed, occurredAt: at,
})
}
// NewSearchStatusEvent records a change of the search status.
func NewSearchStatusEvent(change SearchStatusChange, at time.Time) (PrivacyEvent, error) {
const location = "domain.NewSearchStatusEvent"
@@ -49,6 +49,36 @@ type ConsentRepositories interface {
ConsentLedger() ConsentLedger
}
// AccountDeletionRequests stores the durable request created when a subject
// revokes C1. The active request is independent of later consent grants.
type AccountDeletionRequests interface {
// CreateOrGet returns the current requested record when one exists, or
// stores request as the subject's active deletion request.
CreateOrGet(ctx context.Context, request domain.AccountDeletionRequest) (record domain.AccountDeletionRequest, created bool, err error)
}
// ConsentRevocationEffects applies every currently available local privacy
// change and records downstream revocation intents in the same transaction as
// the ledger stamps. Future C2 and C4 grant adapters must bind each downstream
// grant to its source consent record ID and synchronously close grants for
// revoked record IDs before returning; a later consent record may create a
// new grant, but must never reactivate an older record's grant. Future C5
// readers and importers must check the current consent ledger before reading
// or synchronizing data and fail closed on a missing grant or ledger error.
// An outbox event communicates a committed change; it is never an
// authorization check and cannot make a revoked grant current again. This
// release has no external FSP or downstream contact-grant adapter, so those
// external effects are not claimed as complete.
type ConsentRevocationEffects interface {
// Apply synchronously closes and records a C2 publication when present,
// then appends one bounded durable outbox intent per affected consent record
// with its stored scope. It must not truncate or omit affected records. A
// future local C2/C4 grant adapter must implement record-bound closure in
// this same UnitOfWork before the outbox intent is appended. An empty record
// set is not a valid call.
Apply(ctx context.Context, revocation domain.ConsentRevocation, records []domain.ConsentRecord) error
}
// ConsentTextRepository reads the immutable published consent texts. It has
// no write method: texts are published by migrations.
type ConsentTextRepository interface {
@@ -33,6 +33,10 @@ var (
// ErrMembershipNotFound reports that the account has no membership in the
// organization, in any state.
ErrMembershipNotFound = errors.New("membership not found")
// ErrOrganizationCreationResultNotFound reports a missing immutable result
// snapshot for a live organization creation idempotency record.
ErrOrganizationCreationResultNotFound = errors.New("organization creation result not found")
)
// MaxOrganizationPageSize matches the largest page of the contract.
@@ -65,6 +69,16 @@ type OrganizationRepository interface {
// ErrUserNotFound, and the caller's transaction is aborted.
CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error
// SaveCreationResult stores the immutable domain snapshot returned by the
// original create command. The scope is the HMAC key of a live generic
// idempotency record. The snapshot is bounded and expires with that record;
// it does not follow later profile edits or membership changes.
SaveCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result OrganizationCreationResult) error
// GetCreationResult returns the original snapshot for a live idempotency
// scope. It never reads the current organization or membership rows.
GetCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (OrganizationCreationResult, error)
// GetForMember returns the organization with its representatives and the
// active membership of the account in it, read from one snapshot in one
// statement, so the profile and the list never come from two states. It
@@ -100,6 +114,14 @@ type OrganizationRepository interface {
UpdateProfile(ctx context.Context, actorID uuid.UUID, organization domain.Organization) (domain.Organization, error)
}
// OrganizationCreationResult is the original business result of creating an
// organization. Keeping the domain values lets storage replay the response
// without depending on generated HTTP types or a later profile state.
type OrganizationCreationResult struct {
Organization domain.Organization
Owner domain.Membership
}
// MembershipRepository stores memberships. A membership is unique per account
// and organization.
type MembershipRepository interface {
@@ -50,6 +50,8 @@ type Transactor interface {
type UnitOfWork interface {
IdentityRepositories
ConsentRepositories
AccountDeletionRequests() AccountDeletionRequests
ConsentRevocationEffects() ConsentRevocationEffects
OrganizationRepositories
AssessmentBankRepositories
Policies() PolicyRepository
+90
View File
@@ -0,0 +1,90 @@
package consent
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// QueryService reads published consent texts and the current account's ledger.
// The repository is a PostgreSQL adapter outside a transaction; history reads
// always receive the subject ID selected by the authenticated HTTP boundary.
type QueryService struct {
repositories outbound.ConsentRepositories
clock func() time.Time
}
func NewQueryService(repositories outbound.ConsentRepositories, clock func() time.Time) *QueryService {
if repositories == nil {
panic("consent.NewQueryService - repositories must not be nil")
}
if clock == nil {
panic("consent.NewQueryService - clock must not be nil")
}
return &QueryService{repositories: repositories, clock: clock}
}
func (service *QueryService) CurrentText(ctx context.Context, purpose domain.ConsentPurpose) (domain.ConsentText, error) {
if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil {
return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - validate purpose: %w", err)
}
if purpose.OrganizationScoped() {
return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - c4 text requires an organization snapshot: %w", ErrScopedConsentRequired)
}
text, err := service.repositories.ConsentTexts().Current(ctx, purpose, service.clock())
if err != nil {
return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - read current text: %w", err)
}
return text, nil
}
func (service *QueryService) List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) {
if query.SubjectID == uuid.Nil {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - subject is required: %w", domain.ErrInvalidConsent)
}
if query.Limit < 1 || query.Limit > outbound.MaxConsentPageSize {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - limit is out of range: %w", domain.ErrInvalidConsent)
}
if query.State != "" {
if _, err := domain.ParseConsentState(string(query.State)); err != nil {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - validate state: %w", err)
}
}
if query.After != nil && (query.After.ID == uuid.Nil || query.After.GrantedAt.IsZero()) {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - cursor position is invalid: %w", domain.ErrInvalidConsent)
}
page, err := service.repositories.ConsentLedger().List(ctx, query)
if err != nil {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - read ledger: %w", err)
}
return page, nil
}
// HasCurrentConsent is the fail-closed check used by consumers that must not
// proceed without a current grant. A missing record is a denial; a storage
// failure is returned so the caller must also deny instead of assuming consent.
func (service *QueryService) HasCurrentConsent(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (bool, error) {
if subjectID == uuid.Nil {
return false, fmt.Errorf("QueryService.HasCurrentConsent - subject is required: %w", domain.ErrInvalidConsent)
}
if purpose.OrganizationScoped() {
return false, fmt.Errorf("QueryService.HasCurrentConsent - c4 needs an organization scope: %w", domain.ErrInvalidConsent)
}
if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil {
return false, fmt.Errorf("QueryService.HasCurrentConsent - validate purpose: %w", err)
}
_, err := service.repositories.ConsentLedger().Current(ctx, subjectID, purpose)
if errors.Is(err, outbound.ErrConsentNotFound) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("QueryService.HasCurrentConsent - read current consent: %w", err)
}
return true, nil
}
@@ -0,0 +1,126 @@
package consent
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestQueryServiceReadsCurrentTextAndOwnLedgerPosition(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
body := "Current c2 text."
hash := domain.HashConsentText(body)
text, err := domain.RestoreConsentText(domain.StoredConsentText{
Purpose: string(domain.ConsentPurposePublication), Version: "c2-current", Body: body,
Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), PublishedAt: now.Add(-time.Hour),
})
if err != nil {
t.Fatal(err)
}
accountID := uuid.New()
position := outbound.ConsentListPosition{GrantedAt: now.Add(-time.Minute), ID: uuid.New()}
ledger := &queryTestLedger{current: domain.ConsentRecord{}, page: outbound.ConsentPage{HasMore: true}}
reader := NewQueryService(&queryTestRepositories{
texts: queryTestTexts{text: text},
ledger: ledger,
}, func() time.Time { return now })
gotText, err := reader.CurrentText(context.Background(), domain.ConsentPurposePublication)
if err != nil || gotText.Version() != text.Version() || gotText.Body() != body {
t.Fatalf("CurrentText() = %#v, %v", gotText, err)
}
query := outbound.ConsentListQuery{
SubjectID: accountID, State: domain.ConsentStateActive,
After: &position, Limit: 25,
}
page, err := reader.List(context.Background(), query)
if err != nil || !page.HasMore {
t.Fatalf("List() = %#v, %v", page, err)
}
if ledger.listQuery.SubjectID != accountID || ledger.listQuery.State != query.State ||
ledger.listQuery.After == nil || *ledger.listQuery.After != position || ledger.listQuery.Limit != 25 {
t.Fatalf("List query = %#v", ledger.listQuery)
}
}
func TestQueryServiceHasCurrentConsentFailsClosed(t *testing.T) {
accountID := uuid.New()
for _, test := range []struct {
name string
current error
want bool
wantErr bool
}{
{name: "missing grant denies", current: outbound.ErrConsentNotFound},
{name: "current grant allows", want: true},
{name: "storage failure denies", current: errors.New("storage unavailable"), wantErr: true},
} {
t.Run(test.name, func(t *testing.T) {
ledger := &queryTestLedger{currentErr: test.current}
reader := NewQueryService(&queryTestRepositories{ledger: ledger}, time.Now)
allowed, err := reader.HasCurrentConsent(context.Background(), accountID, domain.ConsentPurposeFSPImport)
if allowed != test.want || (err != nil) != test.wantErr {
t.Fatalf("HasCurrentConsent() = %v, %v", allowed, err)
}
})
}
}
func TestQueryServiceRejectsC4TextWithoutOrganizationSnapshot(t *testing.T) {
reader := NewQueryService(&queryTestRepositories{}, time.Now)
if _, err := reader.CurrentText(context.Background(), domain.ConsentPurposeContactDisclosure); !errors.Is(err, ErrScopedConsentRequired) {
t.Fatalf("CurrentText(c4) error = %v, want ErrScopedConsentRequired", err)
}
}
type queryTestRepositories struct {
outbound.ConsentRepositories
texts outbound.ConsentTextRepository
ledger outbound.ConsentLedger
}
func (repositories *queryTestRepositories) ConsentTexts() outbound.ConsentTextRepository {
return repositories.texts
}
func (repositories *queryTestRepositories) ConsentLedger() outbound.ConsentLedger {
return repositories.ledger
}
type queryTestTexts struct {
outbound.ConsentTextRepository
text domain.ConsentText
}
func (texts queryTestTexts) Current(context.Context, domain.ConsentPurpose, time.Time) (domain.ConsentText, error) {
return texts.text, nil
}
type queryTestLedger struct {
outbound.ConsentLedger
currentErr error
current domain.ConsentRecord
listQuery outbound.ConsentListQuery
page outbound.ConsentPage
}
func (ledger *queryTestLedger) Current(context.Context, uuid.UUID, domain.ConsentPurpose) (domain.ConsentRecord, error) {
if ledger.currentErr != nil {
return domain.ConsentRecord{}, ledger.currentErr
}
return ledger.current, nil
}
func (ledger *queryTestLedger) List(_ context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) {
ledger.listQuery = query
return ledger.page, nil
}
+135
View File
@@ -0,0 +1,135 @@
package consent
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type SettingsRevocationInput struct {
SubjectID uuid.UUID
Purpose domain.ConsentPurpose
OrganizationID uuid.UUID
}
type RevocationResult struct {
Records []domain.ConsentRecord
}
func (service *Service) RevokeInSettingsInNewTransaction(ctx context.Context, input SettingsRevocationInput) (RevocationResult, error) {
const location = "Service.RevokeInSettingsInNewTransaction"
if input.Purpose == domain.ConsentPurposePersonalData {
return RevocationResult{}, fmt.Errorf("%s - c1 uses the account deletion request: %w", location, domain.ErrInvalidConsent)
}
if input.Purpose == domain.ConsentPurposeContactDisclosure && input.OrganizationID == uuid.Nil {
return RevocationResult{}, fmt.Errorf("%s - c4 organization is required: %w", location, domain.ErrInvalidConsent)
}
if input.Purpose != domain.ConsentPurposeContactDisclosure && input.OrganizationID != uuid.Nil {
return RevocationResult{}, fmt.Errorf("%s - organization scope is only valid for c4: %w", location, domain.ErrInvalidConsent)
}
if _, err := domain.ParseConsentPurpose(string(input.Purpose)); err != nil {
return RevocationResult{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
SubjectID: input.SubjectID, Purpose: input.Purpose, OrganizationID: input.OrganizationID,
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: service.clock(),
})
if err != nil {
return RevocationResult{}, fmt.Errorf("%s - create revocation: %w", location, err)
}
var result RevocationResult
err = service.inNewTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
records, err := unit.ConsentLedger().Revoke(ctx, revocation)
if err != nil {
return fmt.Errorf("%s - revoke consent ledger: %w", location, err)
}
if len(records) == 0 {
result = RevocationResult{}
return nil
}
if err := unit.ConsentRevocationEffects().Apply(ctx, revocation, records); err != nil {
return fmt.Errorf("%s - apply revocation effects: %w", location, err)
}
result = RevocationResult{Records: records}
return nil
})
if err != nil {
return RevocationResult{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
func (service *Service) RequestAccountDeletionInNewTransaction(ctx context.Context, subjectID uuid.UUID) (domain.AccountDeletionRequest, error) {
const location = "Service.RequestAccountDeletionInNewTransaction"
request, err := domain.NewAccountDeletionRequest(subjectID, service.clock())
if err != nil {
return domain.AccountDeletionRequest{}, fmt.Errorf("%s - create request: %w", location, err)
}
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
SubjectID: subjectID, Purpose: domain.ConsentPurposePersonalData,
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: request.RequestedAt(),
})
if err != nil {
return domain.AccountDeletionRequest{}, fmt.Errorf("%s - create c1 revocation: %w", location, err)
}
var result domain.AccountDeletionRequest
err = service.inNewTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
storedRequest, created, err := unit.AccountDeletionRequests().CreateOrGet(ctx, request)
if err != nil {
return fmt.Errorf("%s - store account deletion request: %w", location, err)
}
records, err := unit.ConsentLedger().Revoke(ctx, revocation)
if err != nil {
return fmt.Errorf("%s - revoke c1 consent: %w", location, err)
}
if len(records) > 0 {
if err := unit.ConsentRevocationEffects().Apply(ctx, revocation, records); err != nil {
return fmt.Errorf("%s - apply c1 revocation effects: %w", location, err)
}
}
if created {
if err := appendDeletionRequestedEvent(ctx, unit, storedRequest); err != nil {
return fmt.Errorf("%s - append deletion request event: %w", location, err)
}
}
result = storedRequest
return nil
})
if err != nil {
return domain.AccountDeletionRequest{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
type accountDeletionRequestedPayload struct {
RequestID uuid.UUID `json:"request_id"`
SubjectID uuid.UUID `json:"subject_id"`
RequestedAt time.Time `json:"requested_at"`
}
func appendDeletionRequestedEvent(ctx context.Context, unit outbound.UnitOfWork, request domain.AccountDeletionRequest) error {
const location = "appendDeletionRequestedEvent"
body, err := json.Marshal(accountDeletionRequestedPayload{
RequestID: request.ID(), SubjectID: request.SubjectID(), RequestedAt: request.RequestedAt(),
})
if err != nil {
return fmt.Errorf("%s - marshal payload: %w", location, err)
}
event, err := domain.NewDomainEvent(domain.DomainEventInput{
EventType: "privacy.account_deletion_requested", SchemaVersion: 1,
AggregateType: "account_deletion_request", AggregateID: request.ID(), AggregateVersion: 1, Payload: body,
})
if err != nil {
return fmt.Errorf("%s - build event: %w", location, err)
}
if err := unit.Outbox().Append(ctx, event); err != nil {
return fmt.Errorf("%s - append event: %w", location, err)
}
return nil
}
@@ -0,0 +1,501 @@
package consent
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestSettingsRevocationAppliesEffectsOnce(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
revocationTestRecord(t, subject, domain.ConsentPurposePublication, uuid.Nil, now.Add(-time.Hour)),
}}
harness := newRevocationTestService(now, ledger)
input := SettingsRevocationInput{SubjectID: subject, Purpose: domain.ConsentPurposePublication}
first, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), input)
if err != nil || len(first.Records) != 1 || first.Records[0].State() != domain.ConsentStateRevoked {
t.Fatalf("first revoke = %#v, %v; want one revoked record", first, err)
}
if len(harness.effects.calls) != 1 || harness.effects.calls[0].SubjectID() != subject {
t.Fatalf("revocation effects = %v; want one effect for the caller", harness.effects.calls)
}
second, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), input)
if err != nil || len(second.Records) != 0 {
t.Fatalf("repeat revoke = %#v, %v; want no changed records", second, err)
}
if len(harness.effects.calls) != 1 {
t.Fatalf("repeat revoke applied effects again: %d calls", len(harness.effects.calls))
}
}
func TestDownstreamGrantClosureIsRecordBoundAcrossRegrant(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
for _, purpose := range []domain.ConsentPurpose{domain.ConsentPurposePublication, domain.ConsentPurposeContactDisclosure} {
t.Run(string(purpose), func(t *testing.T) {
subject := uuid.New()
organization := uuid.Nil
if purpose.OrganizationScoped() {
organization = uuid.New()
}
oldRecord := revocationTestRecord(t, subject, purpose, organization, now.Add(-time.Hour))
ledger := &revocationTestLedger{records: []domain.ConsentRecord{oldRecord}}
harness := newRevocationTestService(now, ledger)
text := revocationTestConsentText(t, purpose, now.Add(-time.Minute))
harness.transactor.unit.texts = revocationTestTexts{text: text}
harness.effects.activeDownstreamGrants = map[uuid.UUID]bool{oldRecord.ID(): true}
_, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{
SubjectID: subject, Purpose: purpose, OrganizationID: organization,
})
if err != nil {
t.Fatalf("revoke %s: %v", purpose, err)
}
if harness.effects.activeDownstreamGrants[oldRecord.ID()] || !harness.effects.closedConsentRecords[oldRecord.ID()] {
t.Fatalf("revocation did not synchronously close downstream grant for consent record %s", oldRecord.ID())
}
var newRecord domain.ConsentRecord
if purpose == domain.ConsentPurposeContactDisclosure {
fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone)
if err != nil {
t.Fatal(err)
}
grant, err := harness.service.GrantContact(context.Background(), harness.transactor.unit, ContactGrantInput{
SubjectID: subject, OrganizationID: organization, OrganizationName: "Acme Synthetic LLC", Fields: fields,
InvitationID: uuid.New(), InvitationTermsVersion: 1, TextVersion: text.Version(),
})
if err != nil || !grant.Created {
t.Fatalf("grant new C4 invitation = %#v, %v", grant, err)
}
newRecord = grant.Record
} else {
grant, err := harness.service.GrantInSettingsInNewTransaction(context.Background(), SettingsGrantInput{
SubjectID: subject, Purpose: purpose, TextVersion: text.Version(),
})
if err != nil || !grant.Created {
t.Fatalf("grant new C2 version = %#v, %v", grant, err)
}
newRecord = grant.Record
}
if newRecord.ID() == oldRecord.ID() || newRecord.State() != domain.ConsentStateActive {
t.Fatalf("new consent record = %s/%s, want a distinct active record", newRecord.ID(), newRecord.State())
}
if harness.effects.closedConsentRecords[newRecord.ID()] || harness.effects.activeDownstreamGrants[oldRecord.ID()] {
t.Fatalf("new consent reopened the old downstream grant: old=%s new=%s", oldRecord.ID(), newRecord.ID())
}
if !harness.effects.tryOpenForCurrentConsent(context.Background(), newRecord, ledger) ||
!harness.effects.activeDownstreamGrants[newRecord.ID()] {
t.Fatal("test adapter did not open a downstream grant for the new current consent record")
}
if harness.effects.tryOpenForCurrentConsent(context.Background(), oldRecord, ledger) {
t.Fatal("test adapter reopened a grant bound to the revoked consent record")
}
})
}
}
func TestContactRevocationStaysWithinStoredOrganizationScope(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
organization := uuid.New()
otherOrganization := uuid.New()
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
revocationTestRecord(t, subject, domain.ConsentPurposeContactDisclosure, organization, now.Add(-time.Hour)),
revocationTestRecord(t, subject, domain.ConsentPurposeContactDisclosure, otherOrganization, now.Add(-30*time.Minute)),
}}
harness := newRevocationTestService(now, ledger)
result, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{
SubjectID: subject, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: organization,
})
if err != nil || len(result.Records) != 1 || result.Records[0].OrganizationID() != organization {
t.Fatalf("scoped revoke = %#v, %v; want only organization %s", result, err, organization)
}
if len(harness.effects.records) != 1 || harness.effects.records[0].OrganizationID() != organization ||
harness.effects.records[0].Fields().Fields()[0] != domain.ContactFieldPhone {
t.Fatalf("revocation effect records = %v; want stored organization and field scope", harness.effects.records)
}
if ledger.records[1].State() != domain.ConsentStateActive {
t.Fatalf("record for another organization changed to %s", ledger.records[1].State())
}
}
func TestAccountDeletionRequestIsDurableAndIdempotent(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
revocationTestRecord(t, subject, domain.ConsentPurposePersonalData, uuid.Nil, now.Add(-time.Hour)),
}}
harness := newRevocationTestService(now, ledger)
first, err := harness.service.RequestAccountDeletionInNewTransaction(context.Background(), subject)
if err != nil || first.IsZero() || first.SubjectID() != subject {
t.Fatalf("first deletion request = %#v, %v", first, err)
}
if len(harness.deletions.requests) != 1 || len(harness.outbox.events) != 1 ||
harness.outbox.events[0].EventType() != "privacy.account_deletion_requested" {
t.Fatalf("request/outbox counts = %d/%d; want one durable request and one event", len(harness.deletions.requests), len(harness.outbox.events))
}
if ledger.records[0].State() != domain.ConsentStateRevoked || len(harness.effects.calls) != 1 {
t.Fatalf("C1 revocation = %s, effects=%d; want revoked with one intent", ledger.records[0].State(), len(harness.effects.calls))
}
second, err := harness.service.RequestAccountDeletionInNewTransaction(context.Background(), subject)
if err != nil || second.ID() != first.ID() {
t.Fatalf("repeat deletion request = %#v, %v; want same durable request", second, err)
}
if len(harness.deletions.requests) != 1 || len(harness.outbox.events) != 1 || len(harness.effects.calls) != 1 {
t.Fatalf("repeat request duplicated effects: requests=%d events=%d revocations=%d",
len(harness.deletions.requests), len(harness.outbox.events), len(harness.effects.calls))
}
}
func TestRevocationFailureReturnsToTheTransactionBoundary(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
revocationTestRecord(t, subject, domain.ConsentPurposeFSPImport, uuid.Nil, now.Add(-time.Hour)),
}}
harness := newRevocationTestService(now, ledger)
harness.effects.err = errors.New("outbox unavailable")
_, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{
SubjectID: subject, Purpose: domain.ConsentPurposeFSPImport,
})
if err == nil || !errors.Is(harness.transactor.lastErr, harness.effects.err) {
t.Fatalf("revoke error = %v, transaction error = %v; want the effect failure", err, harness.transactor.lastErr)
}
}
type revocationTestHarness struct {
service *Service
transactor *revocationTestTransactor
deletions *revocationTestDeletions
effects *revocationTestEffects
outbox *revocationTestOutbox
}
func newRevocationTestService(now time.Time, ledger *revocationTestLedger) *revocationTestHarness {
harness := &revocationTestHarness{
deletions: &revocationTestDeletions{}, effects: &revocationTestEffects{}, outbox: &revocationTestOutbox{},
}
unit := &revocationTestUnit{
ledger: ledger, deletions: harness.deletions, effects: harness.effects, outbox: harness.outbox,
}
harness.transactor = &revocationTestTransactor{unit: unit}
harness.service = NewService(harness.transactor, func() time.Time { return now })
return harness
}
func revocationTestConsentText(t *testing.T, purpose domain.ConsentPurpose, publishedAt time.Time) domain.ConsentText {
t.Helper()
body := "I consent to this test purpose."
if purpose == domain.ConsentPurposeContactDisclosure {
body = "I consent to share selected contacts with {organization}."
}
hash := domain.HashConsentText(body)
text, err := domain.RestoreConsentText(domain.StoredConsentText{
Purpose: string(purpose), Version: string(purpose) + "-2026-10-01", Body: body,
Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), PublishedAt: publishedAt,
})
if err != nil {
t.Fatalf("RestoreConsentText() error = %v", err)
}
return text
}
func revocationTestRecord(t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose, organization uuid.UUID, grantedAt time.Time) domain.ConsentRecord {
t.Helper()
version := domain.ConsentTextVersion(string(purpose) + "-2026-10-01")
hash := domain.HashConsentText("consent text")
source := domain.ConsentSourceConsentSettings
if purpose == domain.ConsentPurposeContactDisclosure {
source = domain.ConsentSourceInvitationAcceptance
}
stored := domain.StoredConsentRecord{
ID: uuid.New(), SubjectID: subject, Purpose: string(purpose), TextVersion: string(version), TextHash: hash[:],
Source: string(source), State: string(domain.ConsentStateActive), GrantedAt: grantedAt,
}
if purpose == domain.ConsentPurposeContactDisclosure {
fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone)
if err != nil {
t.Fatal(err)
}
stored.OrganizationID = organization
stored.OrganizationName = "Acme Synthetic LLC"
stored.FieldSet = contactFieldCodes(fields.Fields())
stored.InvitationID = uuid.New()
stored.InvitationTermsVersion = 1
}
record, err := domain.RestoreConsentRecord(stored)
if err != nil {
t.Fatalf("RestoreConsentRecord() error = %v", err)
}
return record
}
type revocationTestLedger struct {
outbound.ConsentLedger
records []domain.ConsentRecord
}
type revocationTestTexts struct {
outbound.ConsentTextRepository
text domain.ConsentText
}
func (texts revocationTestTexts) Current(_ context.Context, purpose domain.ConsentPurpose, _ time.Time) (domain.ConsentText, error) {
if texts.text.IsZero() || texts.text.Purpose() != purpose {
return domain.ConsentText{}, outbound.ErrConsentTextNotFound
}
return texts.text, nil
}
func (ledger *revocationTestLedger) Grant(_ context.Context, grant domain.ConsentGrant) (domain.ConsentRecord, bool, error) {
for _, existing := range ledger.records {
if existing.SubjectID() == grant.SubjectID() && existing.Purpose() == grant.Purpose() &&
existing.TextVersion() == grant.TextVersion() && existing.State() != domain.ConsentStateRevoked {
return existing, false, nil
}
}
hash := grant.TextHash()
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(grant.Purpose()),
TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(grant.Source()),
RegistrationVersion: grant.RegistrationVersion(), State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(),
})
if err != nil {
return domain.ConsentRecord{}, false, err
}
ledger.records = append(ledger.records, record)
return record, true, nil
}
func (ledger *revocationTestLedger) GrantContact(_ context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) {
for _, existing := range ledger.records {
if existing.InvitationID() == grant.InvitationID() {
if existing.SubjectID() != grant.SubjectID() {
return domain.ConsentRecord{}, false, outbound.ErrConsentInvitationTaken
}
return existing, false, nil
}
}
hash := grant.TextHash()
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(domain.ConsentPurposeContactDisclosure),
TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance),
State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(), OrganizationID: grant.OrganizationID(),
OrganizationName: grant.OrganizationName(), FieldSet: contactFieldCodes(grant.Fields().Fields()),
InvitationID: grant.InvitationID(), InvitationTermsVersion: grant.InvitationTermsVersion(),
})
if err != nil {
return domain.ConsentRecord{}, false, err
}
ledger.records = append(ledger.records, record)
return record, true, nil
}
func (ledger *revocationTestLedger) Current(_ context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) {
var current domain.ConsentRecord
for _, record := range ledger.records {
if record.SubjectID() != subjectID || record.Purpose() != purpose || record.State() == domain.ConsentStateRevoked {
continue
}
if current.IsZero() || record.GrantedAt().After(current.GrantedAt()) ||
(record.GrantedAt().Equal(current.GrantedAt()) && record.ID().String() > current.ID().String()) {
current = record
}
}
if current.IsZero() {
return domain.ConsentRecord{}, outbound.ErrConsentNotFound
}
return current, nil
}
func (ledger *revocationTestLedger) CurrentContact(_ context.Context, subjectID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) {
var current []domain.ConsentRecord
for _, record := range ledger.records {
if record.SubjectID() == subjectID && record.Purpose() == domain.ConsentPurposeContactDisclosure &&
record.OrganizationID() == organizationID && record.State() != domain.ConsentStateRevoked {
current = append(current, record)
}
}
return current, nil
}
func (ledger *revocationTestLedger) Revoke(_ context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error) {
var revoked []domain.ConsentRecord
for index, record := range ledger.records {
if record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() ||
record.State() == domain.ConsentStateRevoked ||
(revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) {
continue
}
revokedAt := revocation.RevokedAt()
if revokedAt.Before(record.GrantedAt()) {
revokedAt = record.GrantedAt()
}
hash := record.TextHash()
var contactFields []string
if revocation.Purpose().OrganizationScoped() {
contactFields = contactFieldCodes(record.Fields().Fields())
}
stored := domain.StoredConsentRecord{
ID: record.ID(), SubjectID: record.SubjectID(), Purpose: string(record.Purpose()),
TextVersion: string(record.TextVersion()), TextHash: hash[:], Source: string(record.Source()),
RegistrationVersion: record.RegistrationVersion(), State: string(domain.ConsentStateRevoked), GrantedAt: record.GrantedAt(),
RevokedAt: &revokedAt, RevocationSource: string(revocation.Source()), OrganizationID: record.OrganizationID(),
OrganizationName: record.OrganizationName(), FieldSet: contactFields, InvitationID: record.InvitationID(),
InvitationTermsVersion: record.InvitationTermsVersion(),
}
updated, err := domain.RestoreConsentRecord(stored)
if err != nil {
return nil, err
}
ledger.records[index] = updated
revoked = append(revoked, updated)
}
return revoked, nil
}
func contactFieldCodes(fields []domain.ContactField) []string {
codes := make([]string, 0, len(fields))
for _, field := range fields {
codes = append(codes, string(field))
}
return codes
}
type revocationTestDeletions struct {
outbound.AccountDeletionRequests
requests []domain.AccountDeletionRequest
}
func (repository *revocationTestDeletions) CreateOrGet(_ context.Context, request domain.AccountDeletionRequest) (domain.AccountDeletionRequest, bool, error) {
for _, existing := range repository.requests {
if existing.SubjectID() == request.SubjectID() {
return existing, false, nil
}
}
repository.requests = append(repository.requests, request)
return request, true, nil
}
type revocationTestEffects struct {
outbound.ConsentRevocationEffects
calls []domain.ConsentRevocation
records []domain.ConsentRecord
activeDownstreamGrants map[uuid.UUID]bool
closedConsentRecords map[uuid.UUID]bool
err error
}
func (effects *revocationTestEffects) Apply(_ context.Context, revocation domain.ConsentRevocation, records []domain.ConsentRecord) error {
if effects.err != nil {
return effects.err
}
effects.calls = append(effects.calls, revocation)
effects.records = append(effects.records, records...)
if effects.activeDownstreamGrants == nil {
effects.activeDownstreamGrants = make(map[uuid.UUID]bool)
}
if effects.closedConsentRecords == nil {
effects.closedConsentRecords = make(map[uuid.UUID]bool)
}
for _, record := range records {
effects.activeDownstreamGrants[record.ID()] = false
effects.closedConsentRecords[record.ID()] = true
}
return nil
}
func (effects *revocationTestEffects) tryOpenForCurrentConsent(
ctx context.Context,
record domain.ConsentRecord,
ledger outbound.ConsentLedger,
) bool {
if record.IsZero() || effects.closedConsentRecords[record.ID()] {
return false
}
if record.Purpose().OrganizationScoped() {
current, err := ledger.CurrentContact(ctx, record.SubjectID(), record.OrganizationID())
if err != nil {
return false
}
for _, candidate := range current {
if candidate.ID() == record.ID() {
effects.activeDownstreamGrants[record.ID()] = true
return true
}
}
return false
}
current, err := ledger.Current(ctx, record.SubjectID(), record.Purpose())
if err != nil || current.ID() != record.ID() {
return false
}
if effects.activeDownstreamGrants == nil {
effects.activeDownstreamGrants = make(map[uuid.UUID]bool)
}
effects.activeDownstreamGrants[record.ID()] = true
return true
}
type revocationTestOutbox struct {
outbound.OutboxWriter
events []domain.DomainEvent
}
func (outbox *revocationTestOutbox) Append(_ context.Context, events ...domain.DomainEvent) error {
outbox.events = append(outbox.events, events...)
return nil
}
type revocationTestUnit struct {
outbound.UnitOfWork
ledger *revocationTestLedger
texts outbound.ConsentTextRepository
deletions *revocationTestDeletions
effects *revocationTestEffects
outbox *revocationTestOutbox
}
func (unit *revocationTestUnit) ConsentLedger() outbound.ConsentLedger { return unit.ledger }
func (unit *revocationTestUnit) ConsentTexts() outbound.ConsentTextRepository { return unit.texts }
func (unit *revocationTestUnit) AccountDeletionRequests() outbound.AccountDeletionRequests {
return unit.deletions
}
func (unit *revocationTestUnit) ConsentRevocationEffects() outbound.ConsentRevocationEffects {
return unit.effects
}
func (unit *revocationTestUnit) Outbox() outbound.OutboxWriter { return unit.outbox }
type revocationTestTransactor struct {
unit *revocationTestUnit
lastErr error
}
func (transactor *revocationTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
transactor.lastErr = work(ctx, transactor.unit)
return transactor.lastErr
}
+8 -4
View File
@@ -1,4 +1,4 @@
// Package consent grants the consents C1-C5 of the consent ledger.
// Package consent manages consent grants, revocations, and the C1 deletion request.
//
// A grant is checked against the current published text of its purpose and
// is recorded with the application clock; the client names the text version
@@ -9,9 +9,13 @@
// product function; a subject without C3 simply has no C3 record, and
// Current reports ErrConsentNotFound for it.
//
// Revocation is not part of this package. Its downstream effects (closing
// publication and grants, the deletion request, the manual path, stopping
// the import) belong to consent revocation, which calls ConsentLedger().Revoke.
// C1 revocation creates a durable account-deletion request and never deletes
// the account synchronously. Other revocations update the ledger and apply
// transaction-bound effects. C2 closes local publication, C3 leaves the
// manual assessment path available, and C5 denies future import through the
// current-consent gate. Outbox events are notifications rather than access
// checks; external FSP deletion and downstream contact-grant adapters are not
// implemented here.
package consent
import (
@@ -0,0 +1,22 @@
package organization
import "errors"
var (
// ErrForbidden reports an account that cannot create or manage an
// organization.
ErrForbidden = errors.New("organization operation forbidden")
// ErrEmailNotVerified reports an account whose current email is not
// confirmed.
ErrEmailNotVerified = errors.New("organization requires a confirmed email")
// ErrIdempotencyKeyReused reports a live key first used with another body.
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
// ErrInvalidIdempotencyKey reports a key outside the public contract bound.
ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
// ErrInvalidCreateRequest reports an oversized canonical request body.
ErrInvalidCreateRequest = errors.New("invalid organization create request")
)
@@ -0,0 +1,376 @@
// Package organization creates organizations and lets their owners edit the
// company profile.
package organization
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
createOperation = "organization.create"
createLocation = "organization.Service.Create"
maxIdempotencyKeySize = 255
maxCanonicalBodySize = 1 << 20
purgeExpiredBatch = 100
)
// Keyring computes scoped idempotency digests. identity.Keyring implements
// this interface so the feature uses the existing server secret and storage.
type Keyring interface {
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
}
// Dependencies are the collaborators of Service.
type Dependencies struct {
Transactor outbound.Transactor
Keyring Keyring
Clock func() time.Time
}
// Service applies organization commands. It stores no request state.
type Service struct {
transactor outbound.Transactor
keyring Keyring
clock func() time.Time
}
// NewService fails at startup when a required dependency is missing.
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil {
return nil, errors.New("organization.NewService - every dependency must be set")
}
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil
}
// CreateCommand is the caller and profile content of one create request.
type CreateCommand struct {
ActorID uuid.UUID
IdempotencyKey string
CanonicalBody []byte
Profile domain.OrganizationProfileInput
}
// CreateResult is the organization and owner membership created by a request.
// Replayed marks an identical request answered from the immutable result
// snapshot; it does not change the public status or body.
type CreateResult struct {
Organization domain.Organization
Owner domain.Membership
Replayed bool
}
type createRequest struct {
command CreateCommand
fingerprint [outbound.IdempotencyDigestSize]byte
scope [outbound.IdempotencyDigestSize]byte
record outbound.IdempotencyRecord
now time.Time
}
// Create creates a company and its active owner membership in one
// transaction. An identical key and body returns the original creation
// snapshot, even if the live profile has since changed.
func (service *Service) Create(ctx context.Context, command CreateCommand) (CreateResult, error) {
request, err := service.prepareCreateRequest(command)
if err != nil {
return CreateResult{}, err
}
var result CreateResult
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
created, err := service.createInTransaction(ctx, unit, request)
if err != nil {
return err
}
result = created
return nil
})
if err != nil {
return CreateResult{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
}
return result, nil
}
func (service *Service) prepareCreateRequest(command CreateCommand) (createRequest, error) {
switch {
case command.ActorID == uuid.Nil:
return createRequest{}, fmt.Errorf("%s - actor ID must be set: %w", createLocation, ErrForbidden)
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", createLocation, ErrInvalidIdempotencyKey)
}
canonical := command.CanonicalBody
if len(canonical) == 0 {
var err error
canonical, err = canonicalCreateBody(command.Profile)
if err != nil {
return createRequest{}, fmt.Errorf("%s - encode canonical profile", createLocation)
}
}
if len(canonical) > maxCanonicalBodySize {
return createRequest{}, fmt.Errorf("%s - request body exceeds its bound: %w", createLocation, ErrInvalidCreateRequest)
}
fingerprint := service.keyring.Fingerprint(canonical)
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, command.ActorID.String())
now := service.clock()
if now.IsZero() {
return createRequest{}, fmt.Errorf("%s - application time must be set", createLocation)
}
record := outbound.IdempotencyRecord{
Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention),
}
return createRequest{command: command, fingerprint: fingerprint, scope: scope, record: record, now: now}, nil
}
func (service *Service) createInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
) (CreateResult, error) {
if err := requireEmployer(ctx, unit, request.command.ActorID, createLocation); err != nil {
return CreateResult{}, fmt.Errorf("%s - authorize creator: %w", createLocation, err)
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
}
if !created {
return replayCreation(ctx, unit, request, stored)
}
return service.createOrganization(ctx, unit, request)
}
func replayCreation(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
stored outbound.IdempotencyRecord,
) (CreateResult, error) {
if stored.Fingerprint != request.fingerprint {
return CreateResult{}, ErrIdempotencyKeyReused
}
snapshot, err := unit.Organizations().GetCreationResult(ctx, request.scope)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - read creation snapshot: %w", createLocation, err)
}
if !validCreationSnapshot(snapshot, request.command.ActorID) {
return CreateResult{}, fmt.Errorf("%s - stored creation snapshot does not match the actor: %w", createLocation, domain.ErrInvalidMembership)
}
return CreateResult{Organization: snapshot.Organization, Owner: snapshot.Owner, Replayed: true}, nil
}
func validCreationSnapshot(snapshot outbound.OrganizationCreationResult, actorID uuid.UUID) bool {
if snapshot.Organization.IsZero() || snapshot.Owner.IsZero() {
return false
}
return snapshot.Owner.UserID() == actorID &&
snapshot.Owner.OrganizationID() == snapshot.Organization.ID() &&
snapshot.Owner.Role() == domain.OrganizationRoleOwner && snapshot.Owner.GrantsAccess()
}
func (service *Service) createOrganization(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
) (CreateResult, error) {
profile, err := domain.NewOrganizationProfile(request.command.Profile)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - validate profile: %w", createLocation, err)
}
company, err := domain.NewOrganization(profile, request.now)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - build organization: %w", createLocation, err)
}
owner, err := domain.NewOwnerMembership(company.ID(), request.command.ActorID, request.now)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - build owner membership: %w", createLocation, err)
}
if err := unit.Organizations().CreateWithOwner(ctx, company, owner); err != nil {
return CreateResult{}, fmt.Errorf("%s - store organization and owner: %w", createLocation, err)
}
creation := outbound.OrganizationCreationResult{Organization: company, Owner: owner}
if err := unit.Organizations().SaveCreationResult(ctx, request.scope, creation); err != nil {
return CreateResult{}, fmt.Errorf("%s - store creation snapshot: %w", createLocation, err)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
return CreateResult{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
}
return CreateResult{Organization: company, Owner: owner}, nil
}
func canonicalCreateBody(profile domain.OrganizationProfileInput) ([]byte, error) {
// An ordered array makes the fingerprint stable for non-HTTP callers.
return json.Marshal([]any{
profile.Name,
profile.Description,
profile.Sphere,
profile.Contacts.Website,
profile.Contacts.Email,
profile.Contacts.Phone,
profile.Contacts.Telegram,
profile.Representatives,
})
}
// OptionalString distinguishes an absent field from a present value. An empty
// value clears nullable description and sphere fields.
type OptionalString struct {
Set bool
Value string
}
// ProfilePatch is the set of editable fields present in an update request.
// Contacts and representatives replace their complete value when set.
type ProfilePatch struct {
Name OptionalString
Description OptionalString
Sphere OptionalString
Contacts *domain.OrganizationContactsInput
Representatives *[]domain.OrganizationRepresentativeInput
}
// UpdateCommand describes a versioned profile edit.
type UpdateCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
ExpectedVersion int64
Patch ProfilePatch
}
// Update merges the patch over the current profile, preserves verification,
// and checks that the acting account is the active owner.
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.Organization, error) {
const location = "organization.Service.Update"
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
if command.ExpectedVersion < 1 {
return domain.Organization{}, fmt.Errorf("%s - expected version must be positive: %w", location, domain.ErrInvalidOrganization)
}
var result domain.Organization
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, command.ActorID, location); err != nil {
return fmt.Errorf("%s - authorize editor: %w", location, err)
}
current, membership, err := unit.Organizations().GetForMember(ctx, command.OrganizationID, command.ActorID)
if err != nil {
return fmt.Errorf("%s - read organization for member: %w", location, err)
}
if !membership.CanManageOrganization() {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
profile, err := applyPatch(current.Profile(), command.Patch)
if err != nil {
if command.ExpectedVersion != current.Version() {
return fmt.Errorf("%s - expected version %d, current version %d: %w", location,
command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict)
}
return fmt.Errorf("%s - validate profile: %w", location, err)
}
if current.Profile().Equal(profile) {
result = current
return nil
}
if command.ExpectedVersion != current.Version() {
return fmt.Errorf("%s - expected version %d, current version %d: %w", location,
command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict)
}
updated, err := current.ApplyProfile(profile, service.clock())
if err != nil {
return fmt.Errorf("%s - apply profile: %w", location, err)
}
result, err = unit.Organizations().UpdateProfile(ctx, command.ActorID, updated)
if err != nil {
return fmt.Errorf("%s - store profile: %w", location, err)
}
return nil
})
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// Get reads an organization only for an active member of the employer
// account. The membership is checked in the same transaction as the account.
func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error) {
const location = "organization.Service.Get"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
var result domain.Organization
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
return fmt.Errorf("%s - authorize reader: %w", location, err)
}
organization, membership, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
if err != nil {
return fmt.Errorf("%s - read organization for member: %w", location, err)
}
if !membership.GrantsAccess() {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
result = organization
return nil
})
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
func applyPatch(current domain.OrganizationProfile, patch ProfilePatch) (domain.OrganizationProfile, error) {
contacts := current.Contacts()
input := domain.OrganizationProfileInput{
Name: current.Name(), Description: current.Description(), Sphere: current.Sphere(),
Contacts: domain.OrganizationContactsInput{
Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(),
},
}
for _, representative := range current.Representatives() {
input.Representatives = append(input.Representatives, domain.OrganizationRepresentativeInput{
Name: representative.Name(), JobTitle: representative.JobTitle(),
})
}
if patch.Name.Set {
input.Name = patch.Name.Value
}
if patch.Description.Set {
input.Description = patch.Description.Value
}
if patch.Sphere.Set {
input.Sphere = patch.Sphere.Value
}
if patch.Contacts != nil {
input.Contacts = *patch.Contacts
}
if patch.Representatives != nil {
input.Representatives = append([]domain.OrganizationRepresentativeInput(nil), (*patch.Representatives)...)
}
return domain.NewOrganizationProfile(input)
}
func requireEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID, location string) error {
user, err := unit.Users().GetByID(ctx, actorID)
if err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
return ErrForbidden
}
return fmt.Errorf("%s - read account: %w", location, err)
}
if !user.EmailVerified() {
return ErrEmailNotVerified
}
if user.Scenario != domain.ScenarioEmployer {
return ErrForbidden
}
return nil
}
@@ -0,0 +1,628 @@
package organization
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/identity"
)
type organizationTestState struct {
users map[uuid.UUID]domain.User
organizations map[uuid.UUID]domain.Organization
memberships map[organizationTestMembershipKey]domain.Membership
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
results map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult
}
type organizationTestMembershipKey struct {
organizationID uuid.UUID
userID uuid.UUID
}
func newOrganizationTestState() organizationTestState {
return organizationTestState{
users: map[uuid.UUID]domain.User{},
organizations: map[uuid.UUID]domain.Organization{},
memberships: map[organizationTestMembershipKey]domain.Membership{},
idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{},
results: map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult{},
}
}
func (state organizationTestState) clone() organizationTestState {
cloned := newOrganizationTestState()
for id, user := range state.users {
cloned.users[id] = user
}
for id, company := range state.organizations {
cloned.organizations[id] = company
}
for key, membership := range state.memberships {
cloned.memberships[key] = membership
}
for scope, record := range state.idempotency {
cloned.idempotency[scope] = record
}
for scope, result := range state.results {
cloned.results[scope] = result
}
return cloned
}
type organizationTestTransactor struct {
mu sync.Mutex
state organizationTestState
failOwnerInsert bool
}
func newOrganizationTestTransactor() *organizationTestTransactor {
return &organizationTestTransactor{state: newOrganizationTestState()}
}
func (transactor *organizationTestTransactor) WithinTransaction(
ctx context.Context,
work func(context.Context, outbound.UnitOfWork) error,
) error {
transactor.mu.Lock()
defer transactor.mu.Unlock()
working := transactor.state.clone()
unit := &organizationTestUnit{state: &working, failOwnerInsert: transactor.failOwnerInsert}
if err := work(ctx, unit); err != nil {
return err
}
transactor.state = working
return nil
}
func (transactor *organizationTestTransactor) snapshot() organizationTestState {
transactor.mu.Lock()
defer transactor.mu.Unlock()
return transactor.state.clone()
}
type organizationTestUnit struct {
outbound.UnitOfWork
state *organizationTestState
failOwnerInsert bool
}
func (unit *organizationTestUnit) Users() outbound.UserRepository {
return organizationTestUsers{state: unit.state}
}
func (unit *organizationTestUnit) IdempotencyRecords() outbound.IdempotencyRepository {
return organizationTestIdempotency{state: unit.state}
}
func (unit *organizationTestUnit) Organizations() outbound.OrganizationRepository {
return organizationTestOrganizations{state: unit.state, failOwnerInsert: unit.failOwnerInsert}
}
type organizationTestUsers struct {
outbound.UserRepository
state *organizationTestState
}
func (repository organizationTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
user, ok := repository.state.users[id]
if !ok {
return domain.User{}, outbound.ErrUserNotFound
}
return user, nil
}
type organizationTestIdempotency struct {
outbound.IdempotencyRepository
state *organizationTestState
}
func (repository organizationTestIdempotency) Reserve(
_ context.Context,
record outbound.IdempotencyRecord,
) (outbound.IdempotencyRecord, bool, error) {
if stored, ok := repository.state.idempotency[record.Scope]; ok && stored.ExpiresAt.After(record.CreatedAt) {
return stored, false, nil
}
repository.state.idempotency[record.Scope] = record
return record, true, nil
}
func (repository organizationTestIdempotency) Find(
_ context.Context,
scope [outbound.IdempotencyDigestSize]byte,
at time.Time,
) (outbound.IdempotencyRecord, error) {
record, ok := repository.state.idempotency[scope]
if !ok || !record.ExpiresAt.After(at) {
return outbound.IdempotencyRecord{}, outbound.ErrIdempotencyRecordNotFound
}
return record, nil
}
func (repository organizationTestIdempotency) PurgeExpired(
_ context.Context,
at time.Time,
limit int32,
) (int64, error) {
var deleted int64
for scope, record := range repository.state.idempotency {
if deleted >= int64(limit) {
break
}
if !record.ExpiresAt.After(at) {
delete(repository.state.idempotency, scope)
delete(repository.state.results, scope)
deleted++
}
}
return deleted, nil
}
type organizationTestOrganizations struct {
outbound.OrganizationRepository
state *organizationTestState
failOwnerInsert bool
}
func (repository organizationTestOrganizations) CreateWithOwner(
_ context.Context,
company domain.Organization,
owner domain.Membership,
) error {
repository.state.organizations[company.ID()] = company
if repository.failOwnerInsert {
return errors.New("simulated owner membership insert failure")
}
repository.state.memberships[organizationTestMembershipKey{company.ID(), owner.UserID()}] = owner
return nil
}
func (repository organizationTestOrganizations) SaveCreationResult(
_ context.Context,
scope [outbound.IdempotencyDigestSize]byte,
result outbound.OrganizationCreationResult,
) error {
if _, ok := repository.state.idempotency[scope]; !ok {
return outbound.ErrIdempotencyRecordNotFound
}
repository.state.results[scope] = result
return nil
}
func (repository organizationTestOrganizations) GetCreationResult(
_ context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (outbound.OrganizationCreationResult, error) {
result, ok := repository.state.results[scope]
if !ok {
return outbound.OrganizationCreationResult{}, outbound.ErrOrganizationCreationResultNotFound
}
return result, nil
}
func (repository organizationTestOrganizations) GetForMember(
_ context.Context,
organizationID, userID uuid.UUID,
) (domain.Organization, domain.Membership, error) {
company, companyOK := repository.state.organizations[organizationID]
membership, memberOK := repository.state.memberships[organizationTestMembershipKey{organizationID, userID}]
if !companyOK || !memberOK || !membership.GrantsAccess() {
return domain.Organization{}, domain.Membership{}, outbound.ErrOrganizationNotFound
}
return company, membership, nil
}
func (repository organizationTestOrganizations) ListForUser(
context.Context,
outbound.OrganizationListQuery,
) (outbound.OrganizationPage, error) {
return outbound.OrganizationPage{}, nil
}
func (repository organizationTestOrganizations) UpdateProfile(
_ context.Context,
actorID uuid.UUID,
updated domain.Organization,
) (domain.Organization, error) {
current, ok := repository.state.organizations[updated.ID()]
if !ok {
return domain.Organization{}, outbound.ErrOrganizationNotFound
}
membership, ok := repository.state.memberships[organizationTestMembershipKey{updated.ID(), actorID}]
if !ok || !membership.GrantsAccess() {
return domain.Organization{}, outbound.ErrOrganizationNotFound
}
if !membership.CanManageOrganization() {
return domain.Organization{}, outbound.ErrOrganizationManagerRequired
}
if current.Version() != updated.Version() {
return domain.Organization{}, outbound.ErrOrganizationVersionConflict
}
company, err := restoreOrganizationVersion(updated, current.Version()+1)
if err != nil {
return domain.Organization{}, err
}
repository.state.organizations[updated.ID()] = company
return company, nil
}
func restoreOrganizationVersion(company domain.Organization, version int64) (domain.Organization, error) {
profile := company.Profile()
contacts := profile.Contacts()
representatives := profile.Representatives()
storedRepresentatives := make([]domain.StoredRepresentative, 0, len(representatives))
for _, representative := range representatives {
storedRepresentatives = append(storedRepresentatives, domain.StoredRepresentative{
Name: representative.Name(), JobTitle: representative.JobTitle(),
})
}
verification := company.Verification()
return domain.RestoreOrganization(domain.StoredOrganization{
ID: company.ID(), Name: profile.Name(), Description: profile.Description(), Sphere: profile.Sphere(),
Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(),
Representatives: storedRepresentatives, VerificationLevel: string(verification.Level()),
VerificationBasis: string(verification.Basis()), VerificationChangedAt: verification.ChangedAt(),
Version: version, CreatedAt: company.CreatedAt(), UpdatedAt: company.UpdatedAt(),
})
}
func newOrganizationTestService(t *testing.T, tx *organizationTestTransactor, clock func() time.Time) *Service {
t.Helper()
keyring, err := identity.NewKeyring([]byte(strings.Repeat("k", identity.MinKeySecretBytes)))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
service, err := NewService(Dependencies{Transactor: tx, Keyring: keyring, Clock: clock})
if err != nil {
t.Fatalf("NewService() error = %v", err)
}
return service
}
func verifiedEmployer(id uuid.UUID, at time.Time) domain.User {
verifiedAt := at
return domain.User{ID: id, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt}
}
func organizationProfile(name, description string) domain.OrganizationProfileInput {
return domain.OrganizationProfileInput{
Name: name, Description: description, Sphere: "Payments",
Contacts: domain.OrganizationContactsInput{
Website: "https://example.com", Email: "careers@example.com", Phone: "+74951234567", Telegram: "@example",
},
Representatives: []domain.OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Директор"}},
}
}
func canonicalBodyForTest(t *testing.T, profile domain.OrganizationProfileInput) []byte {
t.Helper()
body, err := canonicalCreateBody(profile)
if err != nil {
t.Fatalf("canonicalCreateBody() error = %v", err)
}
return body
}
func TestCreateStoresOwnerAtE0AndReplaysOriginalSnapshotAfterEdit(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 123456000, time.UTC)
currentTime := now
tx := newOrganizationTestTransactor()
ownerID := uuid.New()
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
service := newOrganizationTestService(t, tx, func() time.Time { return currentTime })
profile := organizationProfile("ООО Пример", "Первоначальные данные")
command := CreateCommand{
ActorID: ownerID, IdempotencyKey: "company-create-01", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
}
created, err := service.Create(ctx, command)
if err != nil {
t.Fatalf("Create() error = %v", err)
}
if created.Replayed || created.Organization.Version() != 1 || created.Owner.UserID() != ownerID ||
created.Owner.Role() != domain.OrganizationRoleOwner || !created.Owner.GrantsAccess() {
t.Fatalf("Create() = %+v, want a new version 1 organization and its active owner", created)
}
verification := created.Organization.Verification()
if verification.Level() != domain.OrganizationVerificationE0 || verification.Basis() != domain.OrganizationBasisConfirmedEmail {
t.Fatalf("verification = %s %s, want e0 from confirmed email", verification.Level(), verification.Basis())
}
if card := created.Organization.CandidateCard(); card.ID() != created.Organization.ID() || card.VerificationLevel() != domain.OrganizationVerificationE0 {
t.Fatalf("CandidateCard() = %+v, want the safe organization card", card)
}
currentTime = now.Add(time.Minute)
updated, err := service.Update(ctx, UpdateCommand{
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Измененные данные"}},
})
if err != nil {
t.Fatalf("Update() error = %v", err)
}
if updated.Profile().Description() != "Измененные данные" || updated.Version() != 2 ||
updated.Verification().Level() != domain.OrganizationVerificationE0 {
t.Fatalf("Update() = %+v, want version 2 with the edited profile and e0", updated)
}
replayed, err := service.Create(ctx, command)
if err != nil {
t.Fatalf("Create(retry) error = %v", err)
}
if !replayed.Replayed || replayed.Organization.ID() != created.Organization.ID() ||
!replayed.Organization.Profile().Equal(created.Organization.Profile()) ||
replayed.Organization.Version() != 1 || replayed.Owner.ID() != created.Owner.ID() {
t.Fatalf("Create(retry) = %+v, want the original immutable result", replayed)
}
state := tx.snapshot()
if len(state.organizations) != 1 || len(state.memberships) != 1 || len(state.results) != 1 {
t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 1/1/1", len(state.organizations), len(state.memberships), len(state.results))
}
}
func TestCreateRejectsChangedBodyAndAllowsReuseAfterExpiration(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
currentTime := now
tx := newOrganizationTestTransactor()
ownerID := uuid.New()
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
service := newOrganizationTestService(t, tx, func() time.Time { return currentTime })
firstProfile := organizationProfile("ООО Пример", "Первоначальные данные")
first := CreateCommand{
ActorID: ownerID, IdempotencyKey: "company-create-02", CanonicalBody: canonicalBodyForTest(t, firstProfile), Profile: firstProfile,
}
created, err := service.Create(ctx, first)
if err != nil {
t.Fatalf("Create() error = %v", err)
}
changedProfile := organizationProfile("ООО Другое", "Первоначальные данные")
changed := CreateCommand{
ActorID: ownerID, IdempotencyKey: first.IdempotencyKey,
CanonicalBody: canonicalBodyForTest(t, changedProfile), Profile: changedProfile,
}
if _, err := service.Create(ctx, changed); !errors.Is(err, ErrIdempotencyKeyReused) {
t.Fatalf("Create(changed body) error = %v, want ErrIdempotencyKeyReused", err)
}
if count := len(tx.snapshot().organizations); count != 1 {
t.Fatalf("organization count after changed-body retry = %d, want 1", count)
}
currentTime = now.Add(outbound.IdempotencyRetention + time.Second)
reused, err := service.Create(ctx, first)
if err != nil {
t.Fatalf("Create(expired key) error = %v", err)
}
if reused.Replayed || reused.Organization.ID() == created.Organization.ID() {
t.Fatalf("Create(expired key) = %+v, want a new organization", reused)
}
state := tx.snapshot()
if len(state.organizations) != 2 || len(state.memberships) != 2 || len(state.results) != 1 {
t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 2/2/1", len(state.organizations), len(state.memberships), len(state.results))
}
}
func TestCreateRollsBackOrganizationOwnerIdempotencyAndSnapshot(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
tx := newOrganizationTestTransactor()
tx.failOwnerInsert = true
ownerID := uuid.New()
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
service := newOrganizationTestService(t, tx, func() time.Time { return now })
profile := organizationProfile("ООО Пример", "Данные")
_, err := service.Create(ctx, CreateCommand{
ActorID: ownerID, IdempotencyKey: "company-create-03", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
})
if err == nil || !strings.Contains(err.Error(), "run transaction") {
t.Fatalf("Create(owner insert failure) error = %v, want transaction failure", err)
}
state := tx.snapshot()
if len(state.organizations) != 0 || len(state.memberships) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
t.Fatalf("state after failed transaction = companies:%d memberships:%d idempotency:%d results:%d, want all zero",
len(state.organizations), len(state.memberships), len(state.idempotency), len(state.results))
}
}
func TestCreateRequiresVerifiedEmployer(t *testing.T) {
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
for _, test := range []struct {
name string
user domain.User
want error
}{
{name: "candidate", user: domain.User{ID: uuid.New(), Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}, want: ErrForbidden},
{name: "unverified employer", user: domain.User{ID: uuid.New(), Scenario: domain.ScenarioEmployer}, want: ErrEmailNotVerified},
} {
t.Run(test.name, func(t *testing.T) {
tx := newOrganizationTestTransactor()
tx.state.users[test.user.ID] = test.user
service := newOrganizationTestService(t, tx, func() time.Time { return now })
profile := organizationProfile("ООО Пример", "Данные")
_, err := service.Create(t.Context(), CreateCommand{
ActorID: test.user.ID, IdempotencyKey: "company-create-04", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
})
if !errors.Is(err, test.want) {
t.Fatalf("Create() error = %v, want %v", err, test.want)
}
if state := tx.snapshot(); len(state.organizations) != 0 || len(state.idempotency) != 0 {
t.Fatalf("state after denied create = companies:%d idempotency:%d, want both zero", len(state.organizations), len(state.idempotency))
}
})
}
}
func TestUpdateRequiresOwnerAndPreservesVerification(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
currentTime := now
tx := newOrganizationTestTransactor()
ownerID := uuid.New()
foreignID := uuid.New()
memberID := uuid.New()
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
tx.state.users[foreignID] = verifiedEmployer(foreignID, now)
tx.state.users[memberID] = verifiedEmployer(memberID, now)
service := newOrganizationTestService(t, tx, func() time.Time { return currentTime })
profile := organizationProfile("ООО Пример", "Данные")
created, err := service.Create(ctx, CreateCommand{
ActorID: ownerID, IdempotencyKey: "company-create-05", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
if _, err := service.Update(ctx, UpdateCommand{
ActorID: foreignID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
Patch: ProfilePatch{Name: OptionalString{Set: true, Value: "Чужое изменение"}},
}); !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("Update(foreign user) error = %v, want ErrOrganizationNotFound", err)
}
member, err := domain.NewMembership(domain.MembershipInput{
OrganizationID: created.Organization.ID(), UserID: memberID,
Role: domain.OrganizationRoleRecruiter, At: now.Add(time.Second),
})
if err != nil {
t.Fatalf("NewMembership() error = %v", err)
}
tx.mu.Lock()
tx.state.memberships[organizationTestMembershipKey{created.Organization.ID(), memberID}] = member
tx.mu.Unlock()
if _, err := service.Update(ctx, UpdateCommand{
ActorID: memberID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
Patch: ProfilePatch{Name: OptionalString{Set: true, Value: "Чужое изменение"}},
}); !errors.Is(err, outbound.ErrOrganizationManagerRequired) {
t.Fatalf("Update(non-owner member) error = %v, want ErrOrganizationManagerRequired", err)
}
currentTime = now.Add(time.Minute)
updated, err := service.Update(ctx, UpdateCommand{
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Новый текст"}},
})
if err != nil {
t.Fatalf("Update(owner) error = %v", err)
}
if updated.Version() != 2 || updated.Profile().Description() != "Новый текст" ||
updated.Verification().Level() != domain.OrganizationVerificationE0 ||
updated.Verification().Basis() != domain.OrganizationBasisConfirmedEmail {
t.Fatalf("Update(owner) = %+v, want profile version 2 with unchanged e0 verification", updated)
}
if _, err := service.Update(ctx, UpdateCommand{
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Другая версия"}},
}); !errors.Is(err, outbound.ErrOrganizationVersionConflict) {
t.Fatalf("Update(stale version) error = %v, want ErrOrganizationVersionConflict", err)
}
noOp, err := service.Update(ctx, UpdateCommand{
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
Patch: ProfilePatch{Description: OptionalString{Set: true, Value: "Новый текст"}},
})
if err != nil || noOp.Version() != 2 {
t.Fatalf("Update(stale no-op) = %v, %v, want current version 2", noOp, err)
}
invalidContacts := domain.OrganizationContactsInput{Website: "http://invalid.example"}
if _, err := service.Update(ctx, UpdateCommand{
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 1,
Patch: ProfilePatch{Contacts: &invalidContacts},
}); !errors.Is(err, outbound.ErrOrganizationVersionConflict) {
t.Fatalf("Update(stale invalid website) error = %v, want version conflict", err)
}
if _, err := service.Update(ctx, UpdateCommand{
ActorID: ownerID, OrganizationID: created.Organization.ID(), ExpectedVersion: 2,
Patch: ProfilePatch{Contacts: &invalidContacts},
}); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("Update(current invalid website) error = %v, want domain validation error", err)
}
}
func TestConcurrentCreateWithSameKeyReturnsOneCompany(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
tx := newOrganizationTestTransactor()
ownerID := uuid.New()
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
service := newOrganizationTestService(t, tx, func() time.Time { return now })
profile := organizationProfile("ООО Пример", "Данные")
command := CreateCommand{
ActorID: ownerID, IdempotencyKey: "company-create-06", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
}
const requests = 12
results := make(chan CreateResult, requests)
errorsFound := make(chan error, requests)
var wait sync.WaitGroup
for range requests {
wait.Add(1)
go func() {
defer wait.Done()
result, err := service.Create(ctx, command)
if err != nil {
errorsFound <- err
return
}
results <- result
}()
}
wait.Wait()
close(results)
close(errorsFound)
for err := range errorsFound {
t.Fatalf("Create(concurrent) error = %v", err)
}
var organizationID uuid.UUID
createdCount := 0
for result := range results {
if organizationID == uuid.Nil {
organizationID = result.Organization.ID()
}
if result.Organization.ID() != organizationID || result.Owner.UserID() != ownerID {
t.Fatalf("concurrent result = %+v, want the same company and owner", result)
}
if !result.Replayed {
createdCount++
}
}
if createdCount != 1 {
t.Fatalf("non-replayed results = %d, want one", createdCount)
}
state := tx.snapshot()
if len(state.organizations) != 1 || len(state.memberships) != 1 || len(state.results) != 1 {
t.Fatalf("stored organizations/memberships/results = %d/%d/%d, want 1/1/1", len(state.organizations), len(state.memberships), len(state.results))
}
}
func TestCreateInputCanonicalizationIsStable(t *testing.T) {
profile := organizationProfile("ООО Пример", "Данные")
one := canonicalBodyForTest(t, profile)
two := canonicalBodyForTest(t, profile)
if string(one) != string(two) {
t.Fatalf("canonical bodies differ: %q and %q", one, two)
}
changed := profile
changed.Representatives = append([]domain.OrganizationRepresentativeInput(nil), profile.Representatives...)
changed.Representatives[0].Name = "Другой человек"
three := canonicalBodyForTest(t, changed)
if string(one) == string(three) {
t.Fatalf("canonical body did not change with representative name: %q", one)
}
}
func ExampleOptionalString() {
patch := ProfilePatch{Description: OptionalString{Set: true, Value: ""}}
fmt.Println(patch.Description.Set, patch.Description.Value == "")
// Output: true true
}