From 1f41d497e9cf6f800b93d014630636fa1d3d85c8 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:59:17 -0400 Subject: [PATCH 1/8] Make Spotify artist onboarding and roster attachment atomic --- .gitignore | 2 + .../20261008010000_onboard_spotify_artist.sql | 77 ++++++++++ tests/README.md | 19 +++ tests/test_spotify_onboarding.py | 137 ++++++++++++++++++ 4 files changed, 235 insertions(+) create mode 100644 .gitignore create mode 100644 supabase/migrations/20261008010000_onboard_spotify_artist.sql create mode 100644 tests/README.md create mode 100644 tests/test_spotify_onboarding.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0a95527 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ + +/tests/__pycache__/ diff --git a/supabase/migrations/20261008010000_onboard_spotify_artist.sql b/supabase/migrations/20261008010000_onboard_spotify_artist.sql new file mode 100644 index 0000000..5257eb0 --- /dev/null +++ b/supabase/migrations/20261008010000_onboard_spotify_artist.sql @@ -0,0 +1,77 @@ +-- Atomic Spotify onboarding for POST /artists. No cleanup or identity reassignment. +-- Deploy before the API consumer. Only the trusted API may supply p_account_id. +CREATE OR REPLACE FUNCTION public.onboard_spotify_artist( + p_account_id uuid, + p_organization_id uuid, + p_name text, + p_spotify_artist_id text +) RETURNS TABLE (artist_id uuid, created boolean) +LANGUAGE plpgsql +SECURITY INVOKER +SET search_path = public, pg_temp +AS $$ +#variable_conflict use_column +DECLARE + v_artist_id uuid; + v_candidates uuid[]; + v_social_id uuid; + v_created boolean := false; +BEGIN + IF p_account_id IS NULL OR p_name IS NULL OR btrim(p_name) = '' + OR p_spotify_artist_id IS NULL OR p_spotify_artist_id !~ '^[A-Za-z0-9]{22}$' THEN + RAISE EXCEPTION 'Invalid artist onboarding input' USING ERRCODE = '22023'; + END IF; + + -- Cross-process serialization, preserving case. A hash collision only causes + -- extra waiting; identity matching below always uses the complete provider ID. + PERFORM pg_advisory_xact_lock(hashtextextended('spotify-artist:' || p_spotify_artist_id, 0)); + + -- Recheck after waiting. Lock membership until commit so revocation cannot + -- pass between the permission check and the organization relationship write. + IF p_organization_id IS NOT NULL AND p_account_id <> p_organization_id THEN + PERFORM 1 FROM public.account_organization_ids aoi + WHERE aoi.account_id = p_account_id AND aoi.organization_id = p_organization_id + FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Access denied to specified organization_id' USING ERRCODE = '42501'; + END IF; + END IF; + + -- Match complete Spotify artist resources only. Never lower-case provider IDs, + -- match name/substring, or silently pick an account when existing links conflict. + SELECT array_agg(DISTINCT a.account_id) INTO v_candidates + FROM public.socials s + JOIN public.account_socials a ON a.social_id = s.id + WHERE substring(s.profile_url FROM '^(?:https?://open[.]spotify[.]com/(?:intl-[a-z]{2}/)?artist/|spotify:artist:)([A-Za-z0-9]{22})(?:[/?#].*)?$') = p_spotify_artist_id; + IF cardinality(v_candidates) > 1 THEN + RAISE EXCEPTION 'Spotify artist identity is ambiguous; resolve the conflicting links before retrying' + USING ERRCODE = '21000'; + END IF; + v_artist_id := v_candidates[1]; + + IF v_artist_id IS NULL THEN + INSERT INTO public.accounts(name) VALUES (p_name) RETURNING id INTO v_artist_id; + INSERT INTO public.account_info(account_id) VALUES (v_artist_id); + INSERT INTO public.socials(username, profile_url) + VALUES (p_spotify_artist_id, 'https://open.spotify.com/artist/' || p_spotify_artist_id) + ON CONFLICT (profile_url) DO NOTHING; + SELECT id INTO STRICT v_social_id FROM public.socials + WHERE profile_url = 'https://open.spotify.com/artist/' || p_spotify_artist_id; + INSERT INTO public.account_socials(account_id, social_id) VALUES (v_artist_id, v_social_id); + v_created := true; + END IF; + + INSERT INTO public.account_artist_ids(account_id, artist_id) VALUES (p_account_id, v_artist_id) + ON CONFLICT (account_id, artist_id) DO NOTHING; + IF p_organization_id IS NOT NULL THEN + INSERT INTO public.artist_organization_ids(artist_id, organization_id) VALUES (v_artist_id, p_organization_id) + ON CONFLICT (artist_id, organization_id) DO NOTHING; + END IF; + RETURN QUERY SELECT v_artist_id, v_created; +END; +$$; + +REVOKE ALL ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) TO service_role; +COMMENT ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) IS + 'API-only atomic resolve/create and roster attachment by exact Spotify artist ID. Rejects ambiguity; grants no catalog rights.'; diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..9fc90ac --- /dev/null +++ b/tests/README.md @@ -0,0 +1,19 @@ +# Spotify onboarding transaction tests + +Run against disposable local PostgreSQL, without hosted credentials: + +```sh +python3 -m unittest discover -s tests -p 'test_spotify_onboarding.py' +``` + +`initdb`, `pg_ctl`, and `psql` must be on PATH from the same installation. The runner creates a temporary cluster with a Unix socket and no TCP listener, then stops and removes it. It uses synthetic records and a minimal fixture schema for the tables touched by the migration; this is not a full Supabase migration replay or hosted verification. + +Coverage: new/existing exact identity, case-sensitive namesakes, retries, 16 concurrent requests, ambiguous mappings, non-admin membership/revocation, lookup failure, attachment rollback, personal-to-organization attachment, supported Spotify URI and URL forms, unrelated hosts, and execute privileges. + +## Release order and boundary + +Apply `20261008010000_onboard_spotify_artist.sql` before deploying the API consumer. It adds a service-role-only, security-invoker function. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. + +Before rollout, verify the target has the existing unique roster-pair constraints, test the function with the service role in an isolated environment, and confirm the API's normal membership authorization. Concurrent requests through this function are serialized; unrelated legacy writers do not acquire this lock and remain part of the broader identity work in recoupable/app#2119. + +Hosted acceptance remains: authenticated UI request, API response, persisted organization membership readback, refresh/new-session/workspace switching, and a denied non-admin account. Local fixture success does not establish that the migration has been applied or that production is fixed. diff --git a/tests/test_spotify_onboarding.py b/tests/test_spotify_onboarding.py new file mode 100644 index 0000000..760172e --- /dev/null +++ b/tests/test_spotify_onboarding.py @@ -0,0 +1,137 @@ +"""Disposable PostgreSQL fixture tests; no hosted database or credentials used. +Run: python3 -m unittest discover -s tests -p 'test_spotify_onboarding.py' +Requires PostgreSQL initdb, pg_ctl and psql on PATH. +""" +import concurrent.futures +import pathlib +import subprocess +import tempfile +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[1] +MIGRATION = ROOT / 'supabase/migrations/20261008010000_onboard_spotify_artist.sql' +ACTOR = '10000000-0000-4000-8000-000000000001' +ORG = '10000000-0000-4000-8000-000000000002' +ARTIST = '10000000-0000-4000-8000-000000000003' +SPOTIFY = 'AbCdEfGhIjKlMnOpQrStUv' + +class SpotifyOnboarding(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory(prefix='recoup-onboarding-') + cls.cluster = pathlib.Path(cls.tmp.name) / 'pg' + subprocess.run(['initdb', '-D', str(cls.cluster), '-A', 'trust'], check=True, capture_output=True) + subprocess.run(['pg_ctl', '-D', str(cls.cluster), '-l', str(pathlib.Path(cls.tmp.name) / 'pg.log'), + '-o', f"-k {cls.tmp.name} -p 55439 -c listen_addresses=''", '-w', 'start'], check=True, capture_output=True) + cls.addClassCleanup(cls.stop) + cls.sql(''' + CREATE ROLE service_role; CREATE ROLE anon; CREATE ROLE authenticated; + CREATE TABLE accounts (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), name text); + CREATE TABLE account_info (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, account_id uuid REFERENCES accounts(id)); + CREATE TABLE account_organization_ids (account_id uuid REFERENCES accounts(id), organization_id uuid REFERENCES accounts(id)); + CREATE TABLE socials (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), username text NOT NULL, profile_url text NOT NULL UNIQUE); + CREATE TABLE account_socials (account_id uuid REFERENCES accounts(id), social_id uuid REFERENCES socials(id), UNIQUE(account_id, social_id)); + CREATE TABLE account_artist_ids (account_id uuid REFERENCES accounts(id), artist_id uuid REFERENCES accounts(id), UNIQUE(account_id, artist_id)); + CREATE TABLE artist_organization_ids (artist_id uuid REFERENCES accounts(id), organization_id uuid REFERENCES accounts(id), UNIQUE(artist_id, organization_id)); + GRANT USAGE ON SCHEMA public TO service_role; + GRANT ALL ON ALL TABLES IN SCHEMA public TO service_role; + GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO service_role; + ''') + if MIGRATION.exists(): + cls.sql(MIGRATION.read_text()) + + @classmethod + def stop(cls): + subprocess.run(['pg_ctl', '-D', str(cls.cluster), '-m', 'immediate', '-w', 'stop'], check=True, capture_output=True) + cls.tmp.cleanup() + + @classmethod + def sql(cls, sql, fails=False): + result = subprocess.run(['psql', '-h', cls.tmp.name, '-p', '55439', '-d', 'postgres', '-XAt', '-v', 'ON_ERROR_STOP=1', '-c', sql], text=True, capture_output=True) + if fails: + if result.returncode == 0: + raise AssertionError('Expected SQL failure') + return result.stderr + if result.returncode: + raise AssertionError(result.stderr) + return result.stdout.strip() + + def setUp(self): + self.sql(f"TRUNCATE accounts, socials CASCADE; INSERT INTO accounts(id,name) VALUES ('{ACTOR}','Operator'), ('{ORG}','Label'); INSERT INTO account_organization_ids VALUES ('{ACTOR}','{ORG}');") + + def call(self, spotify=SPOTIFY, fails=False): + result = self.sql(f"SET ROLE service_role; SELECT artist_id, created FROM onboard_spotify_artist('{ACTOR}', '{ORG}', 'Same name', '{spotify}');", fails=fails) + return result if fails else result.splitlines()[-1] + + def test_new_existing_and_retries(self): + first = self.call().split('|') + self.assertEqual(first[1], 't') + self.assertEqual(self.call(), first[0] + '|f') + self.assertEqual(self.sql('SELECT count(*) FROM artist_organization_ids'), '1') + self.assertEqual(self.sql('SELECT count(*) FROM account_artist_ids'), '1') + + def test_existing_exact_identity(self): + self.sql(f"INSERT INTO accounts VALUES ('{ARTIST}','Original name'); INSERT INTO socials(username,profile_url) VALUES ('{SPOTIFY}','https://open.spotify.com/artist/{SPOTIFY}?si=fixture'); INSERT INTO account_socials SELECT '{ARTIST}',id FROM socials;") + self.assertEqual(self.call(), ARTIST + '|f') + self.assertEqual(self.sql(f"SELECT name FROM accounts WHERE id='{ARTIST}'"), 'Original name') + self.assertEqual(self.sql('SELECT count(*) FROM artist_organization_ids'), '1') + + def test_same_name_case_distinct_provider_ids(self): + one = self.call().split('|')[0] + two = self.call(SPOTIFY.lower()).split('|')[0] + self.assertNotEqual(one, two) + + def test_concurrent_new_submissions(self): + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map(lambda _: self.call(), range(16))) + self.assertEqual(len({r.split('|')[0] for r in results}), 1) + self.assertEqual(sum(r.endswith('|t') for r in results), 1) + self.assertEqual(self.sql('SELECT count(*) FROM artist_organization_ids'), '1') + + def test_revoked_and_unauthorized(self): + self.sql('DELETE FROM account_organization_ids') + self.assertIn('Access denied', self.call(fails=True)) + self.assertEqual(self.sql('SELECT count(*) FROM accounts'), '2') + + def test_ambiguous_mapping_fails_without_mutation(self): + self.call() + self.sql(f"INSERT INTO accounts VALUES ('{ARTIST}','Same name'); INSERT INTO account_socials SELECT '{ARTIST}', id FROM socials;") + self.assertIn('ambiguous', self.call(fails=True)) + self.assertEqual(self.sql('SELECT count(*) FROM account_artist_ids'), '1') + + def test_attachment_failure_rolls_back_then_retry(self): + self.sql("ALTER TABLE artist_organization_ids ADD CONSTRAINT fixture_failure CHECK (false) NOT VALID") + try: + self.assertIn('fixture_failure', self.call(fails=True)) + self.assertEqual(self.sql('SELECT count(*) FROM accounts'), '2') + self.assertEqual(self.sql('SELECT count(*) FROM socials'), '0') + finally: + self.sql('ALTER TABLE artist_organization_ids DROP CONSTRAINT fixture_failure') + self.assertTrue(self.call().endswith('|t')) + + def test_untrusted_database_roles_cannot_execute(self): + for role in ('anon', 'authenticated'): + error = self.sql(f"SET ROLE {role}; SELECT * FROM onboard_spotify_artist('{ACTOR}', '{ORG}', 'Same name', '{SPOTIFY}');", fails=True) + self.assertIn('permission denied', error) + + def test_lookup_failure_never_creates(self): + self.sql('REVOKE SELECT ON account_socials FROM service_role') + try: + self.assertIn('permission denied', self.call(fails=True)) + self.assertEqual(self.sql('SELECT count(*) FROM accounts'), '2') + finally: + self.sql('GRANT SELECT ON account_socials TO service_role') + + def test_personal_then_organization_retry_reuses_identity(self): + result = self.sql(f"SET ROLE service_role; SELECT artist_id FROM onboard_spotify_artist('{ACTOR}', NULL, 'Same name', '{SPOTIFY}');").splitlines()[-1] + self.assertEqual(self.sql('SELECT count(*) FROM artist_organization_ids'), '0') + self.assertEqual(self.call(), result + '|f') + self.assertEqual(self.sql('SELECT count(*) FROM artist_organization_ids'), '1') + + def test_spotify_uri_reuses_verified_resource(self): + self.sql(f"INSERT INTO accounts VALUES ('{ARTIST}','Original name'); INSERT INTO socials(username,profile_url) VALUES ('{SPOTIFY}','spotify:artist:{SPOTIFY}'); INSERT INTO account_socials SELECT '{ARTIST}',id FROM socials;") + self.assertEqual(self.call(), ARTIST + '|f') + + def test_non_spotify_host_is_not_identity_evidence(self): + self.sql(f"INSERT INTO accounts VALUES ('{ARTIST}','Same name'); INSERT INTO socials(username,profile_url) VALUES ('{SPOTIFY}','https://example.invalid/artist/{SPOTIFY}'); INSERT INTO account_socials SELECT '{ARTIST}',id FROM socials;") + self.assertNotEqual(self.call().split('|')[0], ARTIST) From b171f36a370c1c1b28b8599aef75ee75233eee38 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:16:34 -0400 Subject: [PATCH 2/8] fix: honor social normalization and atomically create name-only artists --- .github/workflows/artist-onboarding.yml | 25 +++++++++++ .gitignore | 3 +- ...1008020000_onboard_artists_atomically.sql} | 45 +++++++++++++++++-- tests/README.md | 6 +-- tests/test_spotify_onboarding.py | 26 ++++++++++- 5 files changed, 94 insertions(+), 11 deletions(-) create mode 100644 .github/workflows/artist-onboarding.yml rename supabase/migrations/{20261008010000_onboard_spotify_artist.sql => 20261008020000_onboard_artists_atomically.sql} (61%) diff --git a/.github/workflows/artist-onboarding.yml b/.github/workflows/artist-onboarding.yml new file mode 100644 index 0000000..1aeff08 --- /dev/null +++ b/.github/workflows/artist-onboarding.yml @@ -0,0 +1,25 @@ +name: Artist onboarding transactions + +on: + pull_request: + branches: [main] + push: + branches: [main] + +permissions: + contents: read + +jobs: + onboarding: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: Install PostgreSQL + run: | + sudo apt-get update + sudo apt-get install -y postgresql + - name: Test isolated artist onboarding + run: | + export PATH="$(pg_config --bindir):$PATH" + python3 -m unittest discover -s tests -p 'test_spotify_onboarding.py' diff --git a/.gitignore b/.gitignore index 0a95527..c18dd8d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ - -/tests/__pycache__/ +__pycache__/ diff --git a/supabase/migrations/20261008010000_onboard_spotify_artist.sql b/supabase/migrations/20261008020000_onboard_artists_atomically.sql similarity index 61% rename from supabase/migrations/20261008010000_onboard_spotify_artist.sql rename to supabase/migrations/20261008020000_onboard_artists_atomically.sql index 5257eb0..0b38510 100644 --- a/supabase/migrations/20261008010000_onboard_spotify_artist.sql +++ b/supabase/migrations/20261008020000_onboard_artists_atomically.sql @@ -42,7 +42,7 @@ BEGIN SELECT array_agg(DISTINCT a.account_id) INTO v_candidates FROM public.socials s JOIN public.account_socials a ON a.social_id = s.id - WHERE substring(s.profile_url FROM '^(?:https?://open[.]spotify[.]com/(?:intl-[a-z]{2}/)?artist/|spotify:artist:)([A-Za-z0-9]{22})(?:[/?#].*)?$') = p_spotify_artist_id; + WHERE substring(s.profile_url FROM '^(?:(?:https?://)?open[.]spotify[.]com/(?:intl-[a-z]{2}/)?artist/|spotify:artist:)([A-Za-z0-9]{22})(?:[/?#].*)?$') = p_spotify_artist_id; IF cardinality(v_candidates) > 1 THEN RAISE EXCEPTION 'Spotify artist identity is ambiguous; resolve the conflicting links before retrying' USING ERRCODE = '21000'; @@ -54,9 +54,8 @@ BEGIN INSERT INTO public.account_info(account_id) VALUES (v_artist_id); INSERT INTO public.socials(username, profile_url) VALUES (p_spotify_artist_id, 'https://open.spotify.com/artist/' || p_spotify_artist_id) - ON CONFLICT (profile_url) DO NOTHING; - SELECT id INTO STRICT v_social_id FROM public.socials - WHERE profile_url = 'https://open.spotify.com/artist/' || p_spotify_artist_id; + ON CONFLICT (profile_url) DO UPDATE SET profile_url = EXCLUDED.profile_url + RETURNING id INTO v_social_id; INSERT INTO public.account_socials(account_id, social_id) VALUES (v_artist_id, v_social_id); v_created := true; END IF; @@ -75,3 +74,41 @@ REVOKE ALL ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) FRO GRANT EXECUTE ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) TO service_role; COMMENT ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) IS 'API-only atomic resolve/create and roster attachment by exact Spotify artist ID. Rejects ambiguity; grants no catalog rights.'; + +-- Legacy name-only artist creation must not leave partial records on failure. +-- This does not infer person identity, professional roles, or deduplicate by name. +CREATE OR REPLACE FUNCTION public.create_artist_with_roster( + p_account_id uuid, p_organization_id uuid, p_name text +) RETURNS jsonb +LANGUAGE plpgsql SECURITY INVOKER SET search_path = public, pg_temp +AS $$ +DECLARE + v_account public.accounts; + v_info public.account_info; +BEGIN + IF p_account_id IS NULL OR p_name IS NULL OR btrim(p_name) = '' THEN + RAISE EXCEPTION 'Invalid artist onboarding input' USING ERRCODE = '22023'; + END IF; + IF p_organization_id IS NOT NULL AND p_account_id <> p_organization_id THEN + PERFORM 1 FROM public.account_organization_ids aoi + WHERE aoi.account_id = p_account_id AND aoi.organization_id = p_organization_id + FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Access denied to specified organization_id' USING ERRCODE = '42501'; + END IF; + END IF; + INSERT INTO public.accounts(name) VALUES (p_name) RETURNING * INTO v_account; + INSERT INTO public.account_info(account_id) VALUES (v_account.id) RETURNING * INTO v_info; + INSERT INTO public.account_artist_ids(account_id,artist_id) VALUES (p_account_id,v_account.id); + IF p_organization_id IS NOT NULL THEN + INSERT INTO public.artist_organization_ids(artist_id,organization_id) VALUES (v_account.id,p_organization_id); + END IF; + RETURN to_jsonb(v_account) || jsonb_build_object( + 'account_id', v_account.id, 'account_info', jsonb_build_array(to_jsonb(v_info)), + 'account_socials', '[]'::jsonb, 'created_at', to_jsonb(v_account)->'timestamp', + 'updated_at', to_jsonb(v_info)->'updated_at' + ); +END; +$$; +REVOKE ALL ON FUNCTION public.create_artist_with_roster(uuid, uuid, text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.create_artist_with_roster(uuid, uuid, text) TO service_role; diff --git a/tests/README.md b/tests/README.md index 9fc90ac..bd0b227 100644 --- a/tests/README.md +++ b/tests/README.md @@ -6,13 +6,13 @@ Run against disposable local PostgreSQL, without hosted credentials: python3 -m unittest discover -s tests -p 'test_spotify_onboarding.py' ``` -`initdb`, `pg_ctl`, and `psql` must be on PATH from the same installation. The runner creates a temporary cluster with a Unix socket and no TCP listener, then stops and removes it. It uses synthetic records and a minimal fixture schema for the tables touched by the migration; this is not a full Supabase migration replay or hosted verification. +`initdb`, `pg_ctl`, and `psql` must be on PATH from the same installation. The runner creates a temporary cluster with a Unix socket and no TCP listener, then stops and removes it. It uses synthetic records and a minimal fixture schema plus the actual profile-normalization trigger migrations; this is not a full Supabase migration replay or hosted verification. -Coverage: new/existing exact identity, case-sensitive namesakes, retries, 16 concurrent requests, ambiguous mappings, non-admin membership/revocation, lookup failure, attachment rollback, personal-to-organization attachment, supported Spotify URI and URL forms, unrelated hosts, and execute privileges. +Coverage: new/existing exact identity, case-sensitive namesakes, retries, 16 concurrent requests, ambiguous mappings, non-admin membership/revocation, lookup failure, attachment rollback, personal-to-organization attachment, supported Spotify URI and URL forms, unrelated hosts, execute privileges, normalized social persistence, and atomic name-only creation. GitHub Actions runs this suite on each PR. ## Release order and boundary -Apply `20261008010000_onboard_spotify_artist.sql` before deploying the API consumer. It adds a service-role-only, security-invoker function. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. +Apply `20261008020000_onboard_artists_atomically.sql` before deploying the API consumer. It adds service-role-only, security-invoker functions. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. Before rollout, verify the target has the existing unique roster-pair constraints, test the function with the service role in an isolated environment, and confirm the API's normal membership authorization. Concurrent requests through this function are serialized; unrelated legacy writers do not acquire this lock and remain part of the broader identity work in recoupable/app#2119. diff --git a/tests/test_spotify_onboarding.py b/tests/test_spotify_onboarding.py index 760172e..829fea9 100644 --- a/tests/test_spotify_onboarding.py +++ b/tests/test_spotify_onboarding.py @@ -9,7 +9,7 @@ import unittest ROOT = pathlib.Path(__file__).resolve().parents[1] -MIGRATION = ROOT / 'supabase/migrations/20261008010000_onboard_spotify_artist.sql' +MIGRATION = ROOT / 'supabase/migrations/20261008020000_onboard_artists_atomically.sql' ACTOR = '10000000-0000-4000-8000-000000000001' ORG = '10000000-0000-4000-8000-000000000002' ARTIST = '10000000-0000-4000-8000-000000000003' @@ -37,6 +37,8 @@ def setUpClass(cls): GRANT ALL ON ALL TABLES IN SCHEMA public TO service_role; GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO service_role; ''') + cls.sql((ROOT / 'supabase/migrations/20250528095512_socials_profile_url_clean_trigger.sql').read_text()) + cls.sql((ROOT / 'supabase/migrations/20260805190000_preserve_youtube_channel_url_case.sql').read_text()) if MIGRATION.exists(): cls.sql(MIGRATION.read_text()) @@ -129,9 +131,29 @@ def test_personal_then_organization_retry_reuses_identity(self): self.assertEqual(self.sql('SELECT count(*) FROM artist_organization_ids'), '1') def test_spotify_uri_reuses_verified_resource(self): - self.sql(f"INSERT INTO accounts VALUES ('{ARTIST}','Original name'); INSERT INTO socials(username,profile_url) VALUES ('{SPOTIFY}','spotify:artist:{SPOTIFY}'); INSERT INTO account_socials SELECT '{ARTIST}',id FROM socials;") + self.sql(f"INSERT INTO accounts VALUES ('{ARTIST}','Original name'); ALTER TABLE socials DISABLE TRIGGER trigger_clean_socials_profile_url; INSERT INTO socials(username,profile_url) VALUES ('{SPOTIFY}','spotify:artist:{SPOTIFY}'); ALTER TABLE socials ENABLE TRIGGER trigger_clean_socials_profile_url; INSERT INTO account_socials SELECT '{ARTIST}',id FROM socials;") self.assertEqual(self.call(), ARTIST + '|f') def test_non_spotify_host_is_not_identity_evidence(self): self.sql(f"INSERT INTO accounts VALUES ('{ARTIST}','Same name'); INSERT INTO socials(username,profile_url) VALUES ('{SPOTIFY}','https://example.invalid/artist/{SPOTIFY}'); INSERT INTO account_socials SELECT '{ARTIST}',id FROM socials;") self.assertNotEqual(self.call().split('|')[0], ARTIST) + + def test_committed_spotify_social_is_persisted(self): + artist = self.call().split('|')[0] + self.assertEqual(self.sql(f"SELECT s.profile_url FROM socials s JOIN account_socials a ON a.social_id=s.id WHERE a.account_id='{artist}'"), f'open.spotify.com/artist/{SPOTIFY}') + + def test_name_only_creation_rolls_back_on_attachment_failure(self): + self.sql("ALTER TABLE artist_organization_ids ADD CONSTRAINT fixture_failure CHECK (false) NOT VALID") + try: + self.sql(f"SET ROLE service_role; SELECT create_artist_with_roster('{ACTOR}', '{ORG}', 'Manual Artist');", fails=True) + self.assertEqual(self.sql('SELECT count(*) FROM accounts'), '2') + finally: + self.sql('ALTER TABLE artist_organization_ids DROP CONSTRAINT fixture_failure') + self.sql(f"SET ROLE service_role; SELECT create_artist_with_roster('{ACTOR}', '{ORG}', 'Manual Artist');") + self.assertEqual(self.sql('SELECT count(*) FROM artist_organization_ids'), '1') + + def test_name_only_creation_rejects_nonmember(self): + self.sql('DELETE FROM account_organization_ids') + error = self.sql(f"SET ROLE service_role; SELECT create_artist_with_roster('{ACTOR}', '{ORG}', 'Manual Artist');", fails=True) + self.assertIn('Access denied', error) + self.assertEqual(self.sql('SELECT count(*) FROM accounts'), '2') From e858860347df4054da175dbf03948137b4b6ce93 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:19:13 -0400 Subject: [PATCH 3/8] fix: preserve deployed preview migration history --- .../20261008010000_onboard_spotify_artist.sql | 77 +++++++++++++++++++ tests/README.md | 2 +- tests/test_spotify_onboarding.py | 4 +- 3 files changed, 80 insertions(+), 3 deletions(-) create mode 100644 supabase/migrations/20261008010000_onboard_spotify_artist.sql diff --git a/supabase/migrations/20261008010000_onboard_spotify_artist.sql b/supabase/migrations/20261008010000_onboard_spotify_artist.sql new file mode 100644 index 0000000..5257eb0 --- /dev/null +++ b/supabase/migrations/20261008010000_onboard_spotify_artist.sql @@ -0,0 +1,77 @@ +-- Atomic Spotify onboarding for POST /artists. No cleanup or identity reassignment. +-- Deploy before the API consumer. Only the trusted API may supply p_account_id. +CREATE OR REPLACE FUNCTION public.onboard_spotify_artist( + p_account_id uuid, + p_organization_id uuid, + p_name text, + p_spotify_artist_id text +) RETURNS TABLE (artist_id uuid, created boolean) +LANGUAGE plpgsql +SECURITY INVOKER +SET search_path = public, pg_temp +AS $$ +#variable_conflict use_column +DECLARE + v_artist_id uuid; + v_candidates uuid[]; + v_social_id uuid; + v_created boolean := false; +BEGIN + IF p_account_id IS NULL OR p_name IS NULL OR btrim(p_name) = '' + OR p_spotify_artist_id IS NULL OR p_spotify_artist_id !~ '^[A-Za-z0-9]{22}$' THEN + RAISE EXCEPTION 'Invalid artist onboarding input' USING ERRCODE = '22023'; + END IF; + + -- Cross-process serialization, preserving case. A hash collision only causes + -- extra waiting; identity matching below always uses the complete provider ID. + PERFORM pg_advisory_xact_lock(hashtextextended('spotify-artist:' || p_spotify_artist_id, 0)); + + -- Recheck after waiting. Lock membership until commit so revocation cannot + -- pass between the permission check and the organization relationship write. + IF p_organization_id IS NOT NULL AND p_account_id <> p_organization_id THEN + PERFORM 1 FROM public.account_organization_ids aoi + WHERE aoi.account_id = p_account_id AND aoi.organization_id = p_organization_id + FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Access denied to specified organization_id' USING ERRCODE = '42501'; + END IF; + END IF; + + -- Match complete Spotify artist resources only. Never lower-case provider IDs, + -- match name/substring, or silently pick an account when existing links conflict. + SELECT array_agg(DISTINCT a.account_id) INTO v_candidates + FROM public.socials s + JOIN public.account_socials a ON a.social_id = s.id + WHERE substring(s.profile_url FROM '^(?:https?://open[.]spotify[.]com/(?:intl-[a-z]{2}/)?artist/|spotify:artist:)([A-Za-z0-9]{22})(?:[/?#].*)?$') = p_spotify_artist_id; + IF cardinality(v_candidates) > 1 THEN + RAISE EXCEPTION 'Spotify artist identity is ambiguous; resolve the conflicting links before retrying' + USING ERRCODE = '21000'; + END IF; + v_artist_id := v_candidates[1]; + + IF v_artist_id IS NULL THEN + INSERT INTO public.accounts(name) VALUES (p_name) RETURNING id INTO v_artist_id; + INSERT INTO public.account_info(account_id) VALUES (v_artist_id); + INSERT INTO public.socials(username, profile_url) + VALUES (p_spotify_artist_id, 'https://open.spotify.com/artist/' || p_spotify_artist_id) + ON CONFLICT (profile_url) DO NOTHING; + SELECT id INTO STRICT v_social_id FROM public.socials + WHERE profile_url = 'https://open.spotify.com/artist/' || p_spotify_artist_id; + INSERT INTO public.account_socials(account_id, social_id) VALUES (v_artist_id, v_social_id); + v_created := true; + END IF; + + INSERT INTO public.account_artist_ids(account_id, artist_id) VALUES (p_account_id, v_artist_id) + ON CONFLICT (account_id, artist_id) DO NOTHING; + IF p_organization_id IS NOT NULL THEN + INSERT INTO public.artist_organization_ids(artist_id, organization_id) VALUES (v_artist_id, p_organization_id) + ON CONFLICT (artist_id, organization_id) DO NOTHING; + END IF; + RETURN QUERY SELECT v_artist_id, v_created; +END; +$$; + +REVOKE ALL ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) TO service_role; +COMMENT ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) IS + 'API-only atomic resolve/create and roster attachment by exact Spotify artist ID. Rejects ambiguity; grants no catalog rights.'; diff --git a/tests/README.md b/tests/README.md index bd0b227..1a3868b 100644 --- a/tests/README.md +++ b/tests/README.md @@ -12,7 +12,7 @@ Coverage: new/existing exact identity, case-sensitive namesakes, retries, 16 con ## Release order and boundary -Apply `20261008020000_onboard_artists_atomically.sql` before deploying the API consumer. It adds service-role-only, security-invoker functions. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. +Retain the original `20261008010000` migration already recorded by the preview, then apply the corrective `20261008020000_onboard_artists_atomically.sql` before deploying the API consumer. It adds service-role-only, security-invoker functions. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. Before rollout, verify the target has the existing unique roster-pair constraints, test the function with the service role in an isolated environment, and confirm the API's normal membership authorization. Concurrent requests through this function are serialized; unrelated legacy writers do not acquire this lock and remain part of the broader identity work in recoupable/app#2119. diff --git a/tests/test_spotify_onboarding.py b/tests/test_spotify_onboarding.py index 829fea9..e1673e2 100644 --- a/tests/test_spotify_onboarding.py +++ b/tests/test_spotify_onboarding.py @@ -39,8 +39,8 @@ def setUpClass(cls): ''') cls.sql((ROOT / 'supabase/migrations/20250528095512_socials_profile_url_clean_trigger.sql').read_text()) cls.sql((ROOT / 'supabase/migrations/20260805190000_preserve_youtube_channel_url_case.sql').read_text()) - if MIGRATION.exists(): - cls.sql(MIGRATION.read_text()) + cls.sql((ROOT / 'supabase/migrations/20261008010000_onboard_spotify_artist.sql').read_text()) + cls.sql(MIGRATION.read_text()) @classmethod def stop(cls): From 9e55e1b89bf1d6239ffc8e8e056a11e67e7abf66 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:26:50 -0400 Subject: [PATCH 4/8] test: verify atomic onboarding profile response shape --- tests/test_spotify_onboarding.py | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/tests/test_spotify_onboarding.py b/tests/test_spotify_onboarding.py index e1673e2..714a1a6 100644 --- a/tests/test_spotify_onboarding.py +++ b/tests/test_spotify_onboarding.py @@ -3,6 +3,7 @@ Requires PostgreSQL initdb, pg_ctl and psql on PATH. """ import concurrent.futures +import json import pathlib import subprocess import tempfile @@ -26,8 +27,12 @@ def setUpClass(cls): cls.addClassCleanup(cls.stop) cls.sql(''' CREATE ROLE service_role; CREATE ROLE anon; CREATE ROLE authenticated; - CREATE TABLE accounts (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), name text); - CREATE TABLE account_info (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, account_id uuid REFERENCES accounts(id)); + CREATE TABLE accounts (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), name text, timestamp bigint DEFAULT extract(epoch from now())); + CREATE TABLE account_info ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid REFERENCES accounts(id), + updated_at timestamptz NOT NULL DEFAULT now(), image text, knowledges jsonb DEFAULT '[]'::jsonb, + label text, instruction text, organization text, job_title text, role_type text, company_name text + ); CREATE TABLE account_organization_ids (account_id uuid REFERENCES accounts(id), organization_id uuid REFERENCES accounts(id)); CREATE TABLE socials (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), username text NOT NULL, profile_url text NOT NULL UNIQUE); CREATE TABLE account_socials (account_id uuid REFERENCES accounts(id), social_id uuid REFERENCES socials(id), UNIQUE(account_id, social_id)); @@ -157,3 +162,17 @@ def test_name_only_creation_rejects_nonmember(self): error = self.sql(f"SET ROLE service_role; SELECT create_artist_with_roster('{ACTOR}', '{ORG}', 'Manual Artist');", fails=True) self.assertIn('Access denied', error) self.assertEqual(self.sql('SELECT count(*) FROM accounts'), '2') + + def test_name_only_response_preserves_profile_shape(self): + response = self.sql(f"SET ROLE service_role; SELECT create_artist_with_roster('{ACTOR}', '{ORG}', 'Manual Artist');").splitlines()[-1] + artist = json.loads(response) + self.assertEqual(artist['account_id'], artist['id']) + self.assertEqual(artist['name'], 'Manual Artist') + self.assertIsInstance(artist['timestamp'], int) + self.assertEqual(artist['account_socials'], []) + info = artist['account_info'][0] + self.assertIsInstance(info['id'], str) + self.assertEqual(info['account_id'], artist['id']) + self.assertIsInstance(info['updated_at'], str) + self.assertEqual(info['knowledges'], []) + self.assertEqual(self.sql(f"SELECT count(*) FROM artist_organization_ids WHERE artist_id='{artist['id']}' AND organization_id='{ORG}'"), '1') From d508cd12f41edf774cc7a561b66afc5a60e752f6 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:37:34 -0400 Subject: [PATCH 5/8] fix: grant only the metadata privilege required for membership locks --- ...08030000_onboarding_membership_lock_privilege.sql | 5 +++++ tests/README.md | 4 +++- tests/test_spotify_onboarding.py | 12 ++++++++++-- 3 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 supabase/migrations/20261008030000_onboarding_membership_lock_privilege.sql diff --git a/supabase/migrations/20261008030000_onboarding_membership_lock_privilege.sql b/supabase/migrations/20261008030000_onboarding_membership_lock_privilege.sql new file mode 100644 index 0000000..24f0742 --- /dev/null +++ b/supabase/migrations/20261008030000_onboarding_membership_lock_privilege.sql @@ -0,0 +1,5 @@ +-- SECURITY INVOKER onboarding checks lock membership with SELECT ... FOR SHARE. +-- PostgreSQL requires UPDATE on at least one column for that lock. The preview +-- role has SELECT but no UPDATE; grant only the metadata column, not either +-- membership identity column. This adds no client-role, INSERT, DELETE, or identity-column grant. +GRANT UPDATE (updated_at) ON public.account_organization_ids TO service_role; diff --git a/tests/README.md b/tests/README.md index 1a3868b..092f314 100644 --- a/tests/README.md +++ b/tests/README.md @@ -12,8 +12,10 @@ Coverage: new/existing exact identity, case-sensitive namesakes, retries, 16 con ## Release order and boundary -Retain the original `20261008010000` migration already recorded by the preview, then apply the corrective `20261008020000_onboard_artists_atomically.sql` before deploying the API consumer. It adds service-role-only, security-invoker functions. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. +Retain the original `20261008010000` migration already recorded by the preview, then apply the corrective `20261008020000_onboard_artists_atomically.sql` and `20261008030000_onboarding_membership_lock_privilege.sql` before deploying the API consumer. It adds service-role-only, security-invoker functions. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. Before rollout, verify the target has the existing unique roster-pair constraints, test the function with the service role in an isolated environment, and confirm the API's normal membership authorization. Concurrent requests through this function are serialized; unrelated legacy writers do not acquire this lock and remain part of the broader identity work in recoupable/app#2119. Hosted acceptance remains: authenticated UI request, API response, persisted organization membership readback, refresh/new-session/workspace switching, and a denied non-admin account. Local fixture success does not establish that the migration has been applied or that production is fixed. + +The hosted preview initially rejected `FOR SHARE` because its service role had SELECT but no UPDATE privilege on memberships. The final migration grants UPDATE only on `updated_at`, which is sufficient for row locking. Tests mirror the observed table grants and verify that changing either membership identity is not permitted. No manual dashboard grant is required. diff --git a/tests/test_spotify_onboarding.py b/tests/test_spotify_onboarding.py index 714a1a6..72943bb 100644 --- a/tests/test_spotify_onboarding.py +++ b/tests/test_spotify_onboarding.py @@ -33,19 +33,22 @@ def setUpClass(cls): updated_at timestamptz NOT NULL DEFAULT now(), image text, knowledges jsonb DEFAULT '[]'::jsonb, label text, instruction text, organization text, job_title text, role_type text, company_name text ); - CREATE TABLE account_organization_ids (account_id uuid REFERENCES accounts(id), organization_id uuid REFERENCES accounts(id)); + CREATE TABLE account_organization_ids (account_id uuid REFERENCES accounts(id), organization_id uuid REFERENCES accounts(id), updated_at timestamptz DEFAULT now()); CREATE TABLE socials (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), username text NOT NULL, profile_url text NOT NULL UNIQUE); CREATE TABLE account_socials (account_id uuid REFERENCES accounts(id), social_id uuid REFERENCES socials(id), UNIQUE(account_id, social_id)); CREATE TABLE account_artist_ids (account_id uuid REFERENCES accounts(id), artist_id uuid REFERENCES accounts(id), UNIQUE(account_id, artist_id)); CREATE TABLE artist_organization_ids (artist_id uuid REFERENCES accounts(id), organization_id uuid REFERENCES accounts(id), UNIQUE(artist_id, organization_id)); GRANT USAGE ON SCHEMA public TO service_role; - GRANT ALL ON ALL TABLES IN SCHEMA public TO service_role; + GRANT SELECT, INSERT, UPDATE ON accounts, account_info, socials, account_artist_ids TO service_role; + GRANT SELECT, INSERT ON account_socials, artist_organization_ids TO service_role; + GRANT SELECT ON account_organization_ids TO service_role; GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO service_role; ''') cls.sql((ROOT / 'supabase/migrations/20250528095512_socials_profile_url_clean_trigger.sql').read_text()) cls.sql((ROOT / 'supabase/migrations/20260805190000_preserve_youtube_channel_url_case.sql').read_text()) cls.sql((ROOT / 'supabase/migrations/20261008010000_onboard_spotify_artist.sql').read_text()) cls.sql(MIGRATION.read_text()) + cls.sql((ROOT / 'supabase/migrations/20261008030000_onboarding_membership_lock_privilege.sql').read_text()) @classmethod def stop(cls): @@ -176,3 +179,8 @@ def test_name_only_response_preserves_profile_shape(self): self.assertIsInstance(info['updated_at'], str) self.assertEqual(info['knowledges'], []) self.assertEqual(self.sql(f"SELECT count(*) FROM artist_organization_ids WHERE artist_id='{artist['id']}' AND organization_id='{ORG}'"), '1') + + def test_membership_lock_does_not_grant_identity_mutation(self): + error = self.sql(f"SET ROLE service_role; UPDATE account_organization_ids SET account_id='{ORG}' WHERE account_id='{ACTOR}';", fails=True) + self.assertIn('permission denied', error) + self.assertEqual(self.sql(f"SELECT count(*) FROM account_organization_ids WHERE account_id='{ACTOR}' AND organization_id='{ORG}'"), '1') From 36416cc2fefb89baa98c945a1325d38febc98c96 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:41:21 -0400 Subject: [PATCH 6/8] test: enforce all membership identity grant boundaries --- tests/test_spotify_onboarding.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/test_spotify_onboarding.py b/tests/test_spotify_onboarding.py index 72943bb..412a3c7 100644 --- a/tests/test_spotify_onboarding.py +++ b/tests/test_spotify_onboarding.py @@ -181,6 +181,9 @@ def test_name_only_response_preserves_profile_shape(self): self.assertEqual(self.sql(f"SELECT count(*) FROM artist_organization_ids WHERE artist_id='{artist['id']}' AND organization_id='{ORG}'"), '1') def test_membership_lock_does_not_grant_identity_mutation(self): - error = self.sql(f"SET ROLE service_role; UPDATE account_organization_ids SET account_id='{ORG}' WHERE account_id='{ACTOR}';", fails=True) - self.assertIn('permission denied', error) + for column in ('account_id', 'organization_id'): + error = self.sql(f"SET ROLE service_role; UPDATE account_organization_ids SET {column}='{ORG}' WHERE account_id='{ACTOR}';", fails=True) + self.assertIn('permission denied', error) + for statement in (f"INSERT INTO account_organization_ids(account_id,organization_id) VALUES('{ORG}','{ACTOR}')", f"DELETE FROM account_organization_ids WHERE account_id='{ACTOR}'"): + self.assertIn('permission denied', self.sql('SET ROLE service_role; ' + statement, fails=True)) self.assertEqual(self.sql(f"SELECT count(*) FROM account_organization_ids WHERE account_id='{ACTOR}' AND organization_id='{ORG}'"), '1') From 52b7763558d24697dac763911425a00a7041b12c Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:49:23 -0400 Subject: [PATCH 7/8] fix: preserve production OAuth migration version --- .../20261008010000_onboard_spotify_artist.sql | 77 ------------------- tests/README.md | 2 +- tests/test_spotify_onboarding.py | 1 - 3 files changed, 1 insertion(+), 79 deletions(-) delete mode 100644 supabase/migrations/20261008010000_onboard_spotify_artist.sql diff --git a/supabase/migrations/20261008010000_onboard_spotify_artist.sql b/supabase/migrations/20261008010000_onboard_spotify_artist.sql deleted file mode 100644 index 5257eb0..0000000 --- a/supabase/migrations/20261008010000_onboard_spotify_artist.sql +++ /dev/null @@ -1,77 +0,0 @@ --- Atomic Spotify onboarding for POST /artists. No cleanup or identity reassignment. --- Deploy before the API consumer. Only the trusted API may supply p_account_id. -CREATE OR REPLACE FUNCTION public.onboard_spotify_artist( - p_account_id uuid, - p_organization_id uuid, - p_name text, - p_spotify_artist_id text -) RETURNS TABLE (artist_id uuid, created boolean) -LANGUAGE plpgsql -SECURITY INVOKER -SET search_path = public, pg_temp -AS $$ -#variable_conflict use_column -DECLARE - v_artist_id uuid; - v_candidates uuid[]; - v_social_id uuid; - v_created boolean := false; -BEGIN - IF p_account_id IS NULL OR p_name IS NULL OR btrim(p_name) = '' - OR p_spotify_artist_id IS NULL OR p_spotify_artist_id !~ '^[A-Za-z0-9]{22}$' THEN - RAISE EXCEPTION 'Invalid artist onboarding input' USING ERRCODE = '22023'; - END IF; - - -- Cross-process serialization, preserving case. A hash collision only causes - -- extra waiting; identity matching below always uses the complete provider ID. - PERFORM pg_advisory_xact_lock(hashtextextended('spotify-artist:' || p_spotify_artist_id, 0)); - - -- Recheck after waiting. Lock membership until commit so revocation cannot - -- pass between the permission check and the organization relationship write. - IF p_organization_id IS NOT NULL AND p_account_id <> p_organization_id THEN - PERFORM 1 FROM public.account_organization_ids aoi - WHERE aoi.account_id = p_account_id AND aoi.organization_id = p_organization_id - FOR SHARE; - IF NOT FOUND THEN - RAISE EXCEPTION 'Access denied to specified organization_id' USING ERRCODE = '42501'; - END IF; - END IF; - - -- Match complete Spotify artist resources only. Never lower-case provider IDs, - -- match name/substring, or silently pick an account when existing links conflict. - SELECT array_agg(DISTINCT a.account_id) INTO v_candidates - FROM public.socials s - JOIN public.account_socials a ON a.social_id = s.id - WHERE substring(s.profile_url FROM '^(?:https?://open[.]spotify[.]com/(?:intl-[a-z]{2}/)?artist/|spotify:artist:)([A-Za-z0-9]{22})(?:[/?#].*)?$') = p_spotify_artist_id; - IF cardinality(v_candidates) > 1 THEN - RAISE EXCEPTION 'Spotify artist identity is ambiguous; resolve the conflicting links before retrying' - USING ERRCODE = '21000'; - END IF; - v_artist_id := v_candidates[1]; - - IF v_artist_id IS NULL THEN - INSERT INTO public.accounts(name) VALUES (p_name) RETURNING id INTO v_artist_id; - INSERT INTO public.account_info(account_id) VALUES (v_artist_id); - INSERT INTO public.socials(username, profile_url) - VALUES (p_spotify_artist_id, 'https://open.spotify.com/artist/' || p_spotify_artist_id) - ON CONFLICT (profile_url) DO NOTHING; - SELECT id INTO STRICT v_social_id FROM public.socials - WHERE profile_url = 'https://open.spotify.com/artist/' || p_spotify_artist_id; - INSERT INTO public.account_socials(account_id, social_id) VALUES (v_artist_id, v_social_id); - v_created := true; - END IF; - - INSERT INTO public.account_artist_ids(account_id, artist_id) VALUES (p_account_id, v_artist_id) - ON CONFLICT (account_id, artist_id) DO NOTHING; - IF p_organization_id IS NOT NULL THEN - INSERT INTO public.artist_organization_ids(artist_id, organization_id) VALUES (v_artist_id, p_organization_id) - ON CONFLICT (artist_id, organization_id) DO NOTHING; - END IF; - RETURN QUERY SELECT v_artist_id, v_created; -END; -$$; - -REVOKE ALL ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) FROM PUBLIC, anon, authenticated; -GRANT EXECUTE ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) TO service_role; -COMMENT ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) IS - 'API-only atomic resolve/create and roster attachment by exact Spotify artist ID. Rejects ambiguity; grants no catalog rights.'; diff --git a/tests/README.md b/tests/README.md index 092f314..7307d1e 100644 --- a/tests/README.md +++ b/tests/README.md @@ -12,7 +12,7 @@ Coverage: new/existing exact identity, case-sensitive namesakes, retries, 16 con ## Release order and boundary -Retain the original `20261008010000` migration already recorded by the preview, then apply the corrective `20261008020000_onboard_artists_atomically.sql` and `20261008030000_onboarding_membership_lock_privilege.sql` before deploying the API consumer. It adds service-role-only, security-invoker functions. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. +Preserve the existing `20261008010000_oauth_persistent_connections.sql` migration from main. Apply `20261008020000_onboard_artists_atomically.sql` and `20261008030000_onboarding_membership_lock_privilege.sql` before deploying the API consumer. It adds service-role-only, security-invoker functions. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. Before rollout, verify the target has the existing unique roster-pair constraints, test the function with the service role in an isolated environment, and confirm the API's normal membership authorization. Concurrent requests through this function are serialized; unrelated legacy writers do not acquire this lock and remain part of the broader identity work in recoupable/app#2119. diff --git a/tests/test_spotify_onboarding.py b/tests/test_spotify_onboarding.py index 412a3c7..11cd559 100644 --- a/tests/test_spotify_onboarding.py +++ b/tests/test_spotify_onboarding.py @@ -46,7 +46,6 @@ def setUpClass(cls): ''') cls.sql((ROOT / 'supabase/migrations/20250528095512_socials_profile_url_clean_trigger.sql').read_text()) cls.sql((ROOT / 'supabase/migrations/20260805190000_preserve_youtube_channel_url_case.sql').read_text()) - cls.sql((ROOT / 'supabase/migrations/20261008010000_onboard_spotify_artist.sql').read_text()) cls.sql(MIGRATION.read_text()) cls.sql((ROOT / 'supabase/migrations/20261008030000_onboarding_membership_lock_privilege.sql').read_text()) From a3f891ca7ae15e746ee07c27cb54883860039f53 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 7 Oct 2026 21:55:10 -0400 Subject: [PATCH 8/8] fix: reject Spotify social ownership races --- .github/workflows/artist-onboarding.yml | 6 +- ...008040000_recheck_spotify_social_owner.sql | 83 +++++++++++++++++++ tests/README.md | 4 +- tests/test_spotify_onboarding.py | 23 +++++ 4 files changed, 112 insertions(+), 4 deletions(-) create mode 100644 supabase/migrations/20261008040000_recheck_spotify_social_owner.sql diff --git a/.github/workflows/artist-onboarding.yml b/.github/workflows/artist-onboarding.yml index 1aeff08..feefe25 100644 --- a/.github/workflows/artist-onboarding.yml +++ b/.github/workflows/artist-onboarding.yml @@ -11,15 +11,15 @@ permissions: jobs: onboarding: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 10 steps: - uses: actions/checkout@v4 - name: Install PostgreSQL run: | sudo apt-get update - sudo apt-get install -y postgresql + sudo apt-get install -y postgresql-16 - name: Test isolated artist onboarding run: | - export PATH="$(pg_config --bindir):$PATH" + export PATH="/usr/lib/postgresql/16/bin:$PATH" python3 -m unittest discover -s tests -p 'test_spotify_onboarding.py' diff --git a/supabase/migrations/20261008040000_recheck_spotify_social_owner.sql b/supabase/migrations/20261008040000_recheck_spotify_social_owner.sql new file mode 100644 index 0000000..de5b925 --- /dev/null +++ b/supabase/migrations/20261008040000_recheck_spotify_social_owner.sql @@ -0,0 +1,83 @@ +-- Atomic Spotify onboarding for POST /artists. No cleanup or identity reassignment. +-- Deploy before the API consumer. Only the trusted API may supply p_account_id. +CREATE OR REPLACE FUNCTION public.onboard_spotify_artist( + p_account_id uuid, + p_organization_id uuid, + p_name text, + p_spotify_artist_id text +) RETURNS TABLE (artist_id uuid, created boolean) +LANGUAGE plpgsql +SECURITY INVOKER +SET search_path = public, pg_temp +AS $$ +#variable_conflict use_column +DECLARE + v_artist_id uuid; + v_candidates uuid[]; + v_social_id uuid; + v_created boolean := false; +BEGIN + IF p_account_id IS NULL OR p_name IS NULL OR btrim(p_name) = '' + OR p_spotify_artist_id IS NULL OR p_spotify_artist_id !~ '^[A-Za-z0-9]{22}$' THEN + RAISE EXCEPTION 'Invalid artist onboarding input' USING ERRCODE = '22023'; + END IF; + + -- Cross-process serialization, preserving case. A hash collision only causes + -- extra waiting; identity matching below always uses the complete provider ID. + PERFORM pg_advisory_xact_lock(hashtextextended('spotify-artist:' || p_spotify_artist_id, 0)); + + -- Recheck after waiting. Lock membership until commit so revocation cannot + -- pass between the permission check and the organization relationship write. + IF p_organization_id IS NOT NULL AND p_account_id <> p_organization_id THEN + PERFORM 1 FROM public.account_organization_ids aoi + WHERE aoi.account_id = p_account_id AND aoi.organization_id = p_organization_id + FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Access denied to specified organization_id' USING ERRCODE = '42501'; + END IF; + END IF; + + -- Match complete Spotify artist resources only. Never lower-case provider IDs, + -- match name/substring, or silently pick an account when existing links conflict. + SELECT array_agg(DISTINCT a.account_id) INTO v_candidates + FROM public.socials s + JOIN public.account_socials a ON a.social_id = s.id + WHERE substring(s.profile_url FROM '^(?:(?:https?://)?open[.]spotify[.]com/(?:intl-[a-z]{2}/)?artist/|spotify:artist:)([A-Za-z0-9]{22})(?:[/?#].*)?$') = p_spotify_artist_id; + IF cardinality(v_candidates) > 1 THEN + RAISE EXCEPTION 'Spotify artist identity is ambiguous; resolve the conflicting links before retrying' + USING ERRCODE = '21000'; + END IF; + v_artist_id := v_candidates[1]; + + IF v_artist_id IS NULL THEN + INSERT INTO public.accounts(name) VALUES (p_name) RETURNING id INTO v_artist_id; + INSERT INTO public.account_info(account_id) VALUES (v_artist_id); + INSERT INTO public.socials(username, profile_url) + VALUES (p_spotify_artist_id, 'https://open.spotify.com/artist/' || p_spotify_artist_id) + ON CONFLICT (profile_url) DO UPDATE SET profile_url = EXCLUDED.profile_url + RETURNING id INTO v_social_id; + -- The upsert can wait for a legacy writer that does not take our advisory + -- lock. Recheck its committed mapping before attaching the new account. + IF EXISTS (SELECT 1 FROM public.account_socials WHERE social_id = v_social_id) THEN + RAISE EXCEPTION 'Spotify identity changed during onboarding; please retry' + USING ERRCODE = '40001'; + END IF; + INSERT INTO public.account_socials(account_id, social_id) VALUES (v_artist_id, v_social_id); + v_created := true; + END IF; + + INSERT INTO public.account_artist_ids(account_id, artist_id) VALUES (p_account_id, v_artist_id) + ON CONFLICT (account_id, artist_id) DO NOTHING; + IF p_organization_id IS NOT NULL THEN + INSERT INTO public.artist_organization_ids(artist_id, organization_id) VALUES (v_artist_id, p_organization_id) + ON CONFLICT (artist_id, organization_id) DO NOTHING; + END IF; + RETURN QUERY SELECT v_artist_id, v_created; +END; +$$; + +REVOKE ALL ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) TO service_role; +COMMENT ON FUNCTION public.onboard_spotify_artist(uuid, uuid, text, text) IS + 'API-only atomic resolve/create and roster attachment by exact Spotify artist ID. Rejects ambiguity; grants no catalog rights.'; + diff --git a/tests/README.md b/tests/README.md index 7307d1e..e4eb455 100644 --- a/tests/README.md +++ b/tests/README.md @@ -12,10 +12,12 @@ Coverage: new/existing exact identity, case-sensitive namesakes, retries, 16 con ## Release order and boundary -Preserve the existing `20261008010000_oauth_persistent_connections.sql` migration from main. Apply `20261008020000_onboard_artists_atomically.sql` and `20261008030000_onboarding_membership_lock_privilege.sql` before deploying the API consumer. It adds service-role-only, security-invoker functions. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. +Preserve the existing `20261008010000_oauth_persistent_connections.sql` migration from main. Apply `20261008020000_onboard_artists_atomically.sql` and `20261008030000_onboarding_membership_lock_privilege.sql`, then `20261008040000_recheck_spotify_social_owner.sql` before deploying the API consumer. It adds service-role-only, security-invoker functions. It does not clean up existing data, add global identity constraints, change canonical mappings, or assign catalog/publishing rights. Existing ambiguous mappings are rejected for review. Before rollout, verify the target has the existing unique roster-pair constraints, test the function with the service role in an isolated environment, and confirm the API's normal membership authorization. Concurrent requests through this function are serialized; unrelated legacy writers do not acquire this lock and remain part of the broader identity work in recoupable/app#2119. Hosted acceptance remains: authenticated UI request, API response, persisted organization membership readback, refresh/new-session/workspace switching, and a denied non-admin account. Local fixture success does not establish that the migration has been applied or that production is fixed. The hosted preview initially rejected `FOR SHARE` because its service role had SELECT but no UPDATE privilege on memberships. The final migration grants UPDATE only on `updated_at`, which is sufficient for row locking. Tests mirror the observed table grants and verify that changing either membership identity is not permitted. No manual dashboard grant is required. + +CI pins Ubuntu 24.04 and PostgreSQL 16; local validation also covers PostgreSQL 17. The final migration rejects a social row claimed by a legacy writer between lookup and insertion; a retry resolves the committed owner. It cannot serialize all future writes by unrelated legacy code. diff --git a/tests/test_spotify_onboarding.py b/tests/test_spotify_onboarding.py index 11cd559..08b4566 100644 --- a/tests/test_spotify_onboarding.py +++ b/tests/test_spotify_onboarding.py @@ -7,6 +7,7 @@ import pathlib import subprocess import tempfile +import time import unittest ROOT = pathlib.Path(__file__).resolve().parents[1] @@ -48,6 +49,7 @@ def setUpClass(cls): cls.sql((ROOT / 'supabase/migrations/20260805190000_preserve_youtube_channel_url_case.sql').read_text()) cls.sql(MIGRATION.read_text()) cls.sql((ROOT / 'supabase/migrations/20261008030000_onboarding_membership_lock_privilege.sql').read_text()) + cls.sql((ROOT / 'supabase/migrations/20261008040000_recheck_spotify_social_owner.sql').read_text()) @classmethod def stop(cls): @@ -97,6 +99,27 @@ def test_concurrent_new_submissions(self): self.assertEqual(sum(r.endswith('|t') for r in results), 1) self.assertEqual(self.sql('SELECT count(*) FROM artist_organization_ids'), '1') + def test_legacy_writer_race_rolls_back_then_resolves_existing_owner(self): + self.sql(f"INSERT INTO accounts VALUES ('{ARTIST}','Legacy artist')") + sql = f"""BEGIN; SET application_name = 'onboarding_legacy_race'; + INSERT INTO socials(username,profile_url) VALUES ('{SPOTIFY}','https://open.spotify.com/artist/{SPOTIFY}'); + INSERT INTO account_socials SELECT '{ARTIST}',id FROM socials; + SELECT pg_sleep(2); COMMIT;""" + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: + writer = pool.submit(self.sql, sql) + deadline = time.monotonic() + 5 + while self.sql("SELECT count(*) FROM pg_stat_activity WHERE application_name='onboarding_legacy_race' AND wait_event='PgSleep'") != '1': + if time.monotonic() > deadline: + self.fail('Legacy writer never reached concurrent insert window') + time.sleep(0.02) + self.assertIn('identity changed', self.call(fails=True)) + writer.result() + self.assertEqual(self.sql('SELECT count(*) FROM accounts'), '3') + self.assertEqual(self.sql('SELECT count(*) FROM account_info'), '0') + self.assertEqual(self.sql('SELECT count(*) FROM account_socials'), '1') + self.assertEqual(self.sql('SELECT count(*) FROM artist_organization_ids'), '0') + self.assertEqual(self.call(), ARTIST + '|f') + def test_revoked_and_unauthorized(self): self.sql('DELETE FROM account_organization_ids') self.assertIn('Access denied', self.call(fails=True))