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

@@ -0,0 +1,37 @@
-- A C1 revocation creates a durable request for the account-deletion workflow.
-- The API records the request and its outbox intent atomically; processing and
-- deleting the account are separate operations.
-- +goose Up
CREATE TABLE account_deletion_requests (
id uuid NOT NULL,
subject_id uuid,
status text NOT NULL,
requested_at timestamptz NOT NULL,
completed_at timestamptz,
CONSTRAINT account_deletion_requests_pkey PRIMARY KEY (id),
CONSTRAINT account_deletion_requests_subject_id_fkey FOREIGN KEY (subject_id)
REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT account_deletion_requests_status_known CHECK (
status IN ('requested', 'processing', 'completed')
),
CONSTRAINT account_deletion_requests_state_shape CHECK (
(status = 'completed') = (completed_at IS NOT NULL)
),
CONSTRAINT account_deletion_requests_subject_retained_until_complete CHECK (
subject_id IS NOT NULL OR status = 'completed'
),
CONSTRAINT account_deletion_requests_completed_after_request CHECK (
completed_at IS NULL OR completed_at >= requested_at
)
);
CREATE UNIQUE INDEX account_deletion_requests_one_active_per_subject
ON account_deletion_requests (subject_id)
WHERE subject_id IS NOT NULL AND status IN ('requested', 'processing');
CREATE INDEX account_deletion_requests_processing_idx
ON account_deletion_requests (requested_at, id)
WHERE status IN ('requested', 'processing');
-- +goose Down
DROP TABLE account_deletion_requests;
@@ -0,0 +1,25 @@
-- +goose Up
-- Replay follows the generic record's 24-hour retention. Expired records are
-- removed by bounded opportunistic purges, so physical deletion may happen
-- later; this foreign key removes the snapshot with its record. The snapshot
-- is separate from the live organization so later profile edits cannot change
-- a replay. It contains bounded profile and owner-membership data, never a
-- request key.
CREATE TABLE organization_creation_results (
scope_hash bytea NOT NULL,
snapshot jsonb NOT NULL,
CONSTRAINT organization_creation_results_pkey PRIMARY KEY (scope_hash),
CONSTRAINT organization_creation_results_idempotency_fkey FOREIGN KEY (
scope_hash
) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
CONSTRAINT organization_creation_results_scope_hash_sha256 CHECK (
octet_length(scope_hash) = 32
),
CONSTRAINT organization_creation_results_snapshot_bounded CHECK (
jsonb_typeof(snapshot) = 'object'
AND octet_length(snapshot::text) <= 65536
)
);
-- +goose Down
DROP TABLE organization_creation_results;
+27 -2
View File
@@ -25,6 +25,10 @@ var directPublicationReaders = []string{
"UpdateCandidatePublication",
}
var ownerScopedPublicationQueries = []string{
"LockCandidatePublicationForConsentRevocation",
}
var (
// sqlc accepts both comment forms and tolerates trailing whitespace.
queryHeaderPattern = regexp.MustCompile(`(?m)^(?:--|/\*)[ \t]*name:[ \t]+(\w+)[ \t]+:\w+[ \t]*(?:\*/)?[ \t]*$`)
@@ -43,6 +47,7 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
t.Fatalf("list the query files = %v, %v", files, err)
}
var found []string
statements := make(map[string]string)
for _, file := range files {
content, err := os.ReadFile(file)
if err != nil {
@@ -63,6 +68,7 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
name := text[header[2]:header[3]]
if publicationTableName.MatchString(statement) {
found = append(found, name)
statements[name] = strings.Join(strings.Fields(statement), " ")
}
if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) {
t.Errorf("%s reads candidate_effective_publications without excluding candidate_hidden_organizations", name)
@@ -70,12 +76,31 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
}
}
slices.Sort(found)
want := slices.Clone(directPublicationReaders)
want := slices.Concat(slices.Clone(directPublicationReaders), ownerScopedPublicationQueries)
slices.Sort(want)
if !slices.Equal(found, want) {
t.Fatalf("queries that name candidate_publications = %v, want only %v: organization-facing reads use candidate_effective_publications", found, want)
t.Fatalf("queries that name candidate_publications = %v, want only settings queries and owner-scoped consent revocation: %v", found, want)
}
if strings.Contains(strings.Join(found, ","), "Visible") {
t.Fatal("the organization-facing read names the table directly")
}
closeQuery := strings.ToLower(statements["LockCandidatePublicationForConsentRevocation"])
for _, required := range []string{
"select greatest(candidate_publications.published_at, consent_records.revoked_at)",
"inner join consent_records",
"candidate_publications.user_id = sqlc.arg(user_id)",
"candidate_publications.state = 'published'",
"consent_records.id = any(sqlc.arg(consent_record_ids)::uuid [])",
"consent_records.subject_id = candidate_publications.user_id",
"consent_records.purpose = 'c2'",
"consent_records.revoked_at is not null",
"for update of candidate_publications",
} {
if !strings.Contains(closeQuery, required) {
t.Errorf("consent revocation query lacks %q: %s", required, closeQuery)
}
}
if strings.Contains(closeQuery, "update candidate_publications") || strings.Contains(closeQuery, "set state = 'closed'") {
t.Fatalf("consent revocation query rewrites the stored publication instead of preserving its ledger link: %s", closeQuery)
}
}
+30
View File
@@ -417,3 +417,33 @@ WHERE
)
ORDER BY ledger.granted_at DESC, ledger.id DESC
LIMIT sqlc.arg(row_limit);
-- 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.
-- name: CreateAccountDeletionRequest :one
INSERT INTO account_deletion_requests (
id,
subject_id,
status,
requested_at
) VALUES (
sqlc.arg(id),
sqlc.arg(subject_id),
'requested',
sqlc.arg(requested_at)
)
ON CONFLICT (subject_id)
WHERE subject_id IS NOT NULL AND status IN ('requested', 'processing')
DO NOTHING
RETURNING id, subject_id, status, requested_at;
-- Reads the durable active deletion request when an earlier request already
-- exists. A completed request does not suppress a later explicit request.
-- name: GetActiveAccountDeletionRequest :one
SELECT id, subject_id, status, requested_at
FROM account_deletion_requests
WHERE subject_id = sqlc.arg(subject_id)
AND status IN ('requested', 'processing')
ORDER BY requested_at, id
LIMIT 1;
+17
View File
@@ -222,3 +222,20 @@ FROM memberships
WHERE
organization_id = sqlc.arg(organization_id)
AND user_id = sqlc.arg(user_id);
-- 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.
-- name: SaveOrganizationCreationResult :exec
INSERT INTO organization_creation_results (scope_hash, snapshot)
VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot))
ON CONFLICT (scope_hash) DO UPDATE
SET snapshot = excluded.snapshot;
-- Reads only the historical result. It intentionally does not join the live
-- organization or membership, whose profile and state may have since changed.
-- name: GetOrganizationCreationResult :one
SELECT snapshot
FROM organization_creation_results
WHERE scope_hash = sqlc.arg(scope_hash);
+19
View File
@@ -280,6 +280,25 @@ ORDER BY granted_at DESC, id DESC
LIMIT 1
FOR SHARE;
-- 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.
-- 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 = sqlc.arg(user_id)
AND candidate_publications.state = 'published'
AND consent_records.id = ANY(sqlc.arg(consent_record_ids)::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;
-- The organization-facing read of a candidate's publication: the effective
-- view (published and backed by an unrevoked C2) and no hiding of the reading
-- organization. No row means the organization reads nothing, whichever of