diff --git a/.github/workflows/artist-onboarding.yml b/.github/workflows/artist-onboarding.yml new file mode 100644 index 0000000..feefe25 --- /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-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: Install PostgreSQL + run: | + sudo apt-get update + sudo apt-get install -y postgresql-16 + - name: Test isolated artist onboarding + run: | + export PATH="/usr/lib/postgresql/16/bin:$PATH" + python3 -m unittest discover -s tests -p 'test_spotify_onboarding.py' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/supabase/migrations/20261008020000_onboard_artists_atomically.sql b/supabase/migrations/20261008020000_onboard_artists_atomically.sql new file mode 100644 index 0000000..0b38510 --- /dev/null +++ b/supabase/migrations/20261008020000_onboard_artists_atomically.sql @@ -0,0 +1,114 @@ +-- 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; + 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.'; + +-- 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/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/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 new file mode 100644 index 0000000..e4eb455 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,23 @@ +# 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 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, execute privileges, normalized social persistence, and atomic name-only creation. GitHub Actions runs this suite on each PR. + +## 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`, 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 new file mode 100644 index 0000000..08b4566 --- /dev/null +++ b/tests/test_spotify_onboarding.py @@ -0,0 +1,211 @@ +"""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 json +import pathlib +import subprocess +import tempfile +import time +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[1] +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' +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, 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), 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 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(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): + 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_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)) + 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'); 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') + + 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') + + def test_membership_lock_does_not_grant_identity_mutation(self): + 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')