433 lines
16 KiB
Go
433 lines
16 KiB
Go
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)
|
|
}
|