package outbound import ( "context" "errors" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" ) var ( // ErrConsentTextNotFound reports that no text has the purpose and // version, or no text of the purpose is published at the time. ErrConsentTextNotFound = errors.New("consent text not found") // ErrConsentTextMismatch reports a grant whose hash is not the hash of // the published text of its version: for C1-C3 and C5 the text itself, // for C4 the text with the stored organization name filled in. ErrConsentTextMismatch = errors.New("consent text hash does not match the published text") // ErrConsentTextNotPublished reports a grant for a text version whose // publication time is after the grant time. ErrConsentTextNotPublished = errors.New("consent text not published at the grant time") // ErrConsentNotFound reports that the subject has no unrevoked record of // the purpose. ErrConsentNotFound = errors.New("consent not found") // ErrConsentInvitationTaken reports a C4 grant for an invitation whose C4 // record belongs to another subject. Nothing was stored. ErrConsentInvitationTaken = errors.New("invitation consent belongs to another subject") // ErrConsentRecordImmutable reports an attempt to change a record other // than by its one revocation stamp, or to delete a record of a confirmed // account. The database refuses both. ErrConsentRecordImmutable = errors.New("consent record is immutable") ) // ConsentRepositories exposes the consent texts and the consent ledger. // UnitOfWork binds them to one transaction, so a business operation records // a consent atomically with its own changes: the registration with C1, the // invitation acceptance with C4. An adapter may also provide them outside a // transaction, where every call is its own statement. Every method that // takes a time rejects the zero time. type ConsentRepositories interface { ConsentTexts() ConsentTextRepository ConsentLedger() ConsentLedger } // 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 local privacy change of a revocation // and records downstream revocation intents in the same transaction as the // ledger stamps. The local grants are closed synchronously there: a C4 // revocation closes the grants that name the revoked records, and a C2 // revocation closes every grant of the candidate. 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 closes the local grants and the C2 publication when present, in the // caller's transaction, then appends one bounded durable outbox intent per // affected consent record with its stored scope. It must not truncate or // omit affected records. 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 { // Get returns the text with the purpose and version, published or // scheduled, or ErrConsentTextNotFound. Get(ctx context.Context, purpose domain.ConsentPurpose, version domain.ConsentTextVersion) (domain.ConsentText, error) // Current returns the text of the purpose with the latest publication // time not after at, or ErrConsentTextNotFound. Current(ctx context.Context, purpose domain.ConsentPurpose, at time.Time) (domain.ConsentText, error) } // ConsentLedger stores the append-only consent ledger. A grant is a new // record; history is never rewritten except for the one revocation stamp of // a record. Every read and every revocation is scoped by the subject, so a // caller cannot reach another subject's records through it. // // A grant binds the record to a stored text version: an unknown version // fails with ErrConsentTextNotFound, a version published after the grant // time with ErrConsentTextNotPublished, and, for C1-C3 and C5, a hash other // than the hash of that text with ErrConsentTextMismatch. An unknown subject // fails with ErrUserNotFound. These failures come from the database and // abort a surrounding transaction. type ConsentLedger interface { // Grant records a grant of C1, C2, C3, or C5 and returns the record // with created true. When the subject already has an unrevoked record of // the purpose and text version, it returns that record with created // false and stores nothing, without aborting a surrounding transaction. // A grant of another version is a new record next to the earlier one. // Superseded is decided by granted_at, then the record ID: the // unrevoked record granted last is active, whatever its text version, // so Grant accepts any published version. The usecase consent.Service // is the path that checks that the version is the current // text of the purpose, ConsentTexts().Current at the grant time, before // it calls Grant; business code grants through it, not directly. // // A subject may leave any purpose ungranted: the ledger has no rule that // ties one purpose to another, and a subject without C3 has no C3 record, // so Current returns ErrConsentNotFound. That is not an error state of // the account. No caller may treat a missing C3 as a reason to refuse the // profile or the manual assessment path. Grant(ctx context.Context, grant domain.ConsentGrant) (record domain.ConsentRecord, created bool, err error) // GrantContact records the C4 grant of an invitation acceptance with its // organization, the organization name as the shown text named it, the // field set, the invitation, and the terms version. The database checks // that the hash is the hash of the published text with that name, so the // stored name is the snapshot a later rename never changes. It is meant to // run in the acceptance transaction next to the state change, the grant, // and the audit event, so all of them commit or roll back together. // When the invitation already has a C4 record of the same subject, it // returns that record, revoked or not, with created false and stores // nothing; the caller compares its scope to decide between a repeat and // a conflict. When the record belongs to another subject it returns // ErrConsentInvitationTaken. Neither case aborts the transaction. GrantContact(ctx context.Context, grant domain.ContactConsentGrant) (record domain.ConsentRecord, created bool, err error) // Revoke stamps every unrevoked record of the revocation's purpose, and // for C4 of its organization only, with the revocation time and source, // and returns the revoked records. Superseded records of the purpose are // revoked too. Records that are already revoked keep their first stamp; // with nothing to revoke the result is empty, so a repeat is harmless. // A later grant is a new record. A revocation time before the grant // time of a record, from clock skew between instances, is stamped at // the grant time. Revoke(ctx context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error) // Current returns the newest unrevoked record of C1, C2, C3, or C5, or // ErrConsentNotFound. C4 fails with domain.ErrInvalidConsent; use // CurrentContact. Current(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) // LockCurrentForUse returns and share-locks the current C3 record for the // subject. A caller that authorizes a real automated assessment must use it // inside the same transaction that creates or mutates that assessment. The // lock serializes the operation with C3 revocation until commit. Missing C3 // returns ErrConsentNotFound; other purposes return domain.ErrInvalidConsent. LockCurrentForUse(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) // LockRegistration returns and locks the active registration C1 for one // registration version, or ErrConsentNotFound. Email confirmation calls it // inside the same transaction after consuming the token and applying the // pending credentials to the account, in token -> account -> registration C1 // lock order. Keep all confirmation effects in that transaction so they // commit together after this check succeeds or roll back together on error. LockRegistration(ctx context.Context, subjectID uuid.UUID, registrationVersion int64) (domain.ConsentRecord, error) // CurrentContact returns the unrevoked C4 records of the subject for the // organization, newest first, one per accepted invitation. The result // is empty when there is none. CurrentContact(ctx context.Context, subjectID uuid.UUID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) // List returns one page of the subject's records, newest grant first, // with the state of each record. It is the read model of the subject's // own consents and history. List(ctx context.Context, query ConsentListQuery) (ConsentPage, error) } // ConsentListQuery selects one page of a subject's ledger. type ConsentListQuery struct { SubjectID uuid.UUID // State limits the page to one state; empty selects every record. State domain.ConsentState // After continues after the position of the last record of the previous // page; nil reads the first page. After *ConsentListPosition // Limit is the page size, from 1 to MaxConsentPageSize. Limit int32 } // MaxConsentPageSize matches the largest page of the contract. const MaxConsentPageSize = 100 // ConsentListPosition is the ordering key of a record in List. type ConsentListPosition struct { GrantedAt time.Time ID uuid.UUID } // ConsentPositionOf returns the ordering key of record for the next page. func ConsentPositionOf(record domain.ConsentRecord) ConsentListPosition { return ConsentListPosition{GrantedAt: record.GrantedAt(), ID: record.ID()} } // ConsentPage is one page of List. type ConsentPage struct { Records []domain.ConsentRecord // HasMore reports that another page follows; read it with After set to // the position of the last record. HasMore bool }