Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/artist-onboarding.yml
Original file line number Diff line number Diff line change
@@ -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'
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__pycache__/
114 changes: 114 additions & 0 deletions supabase/migrations/20261008020000_onboard_artists_atomically.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
-- Atomic Spotify onboarding for POST /artists. No cleanup or identity reassignment.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

This migration is 114 lines, exceeding the rule’s 100-line file limit. Split the two onboarding function definitions into separate migration files or otherwise reduce the file below the limit.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At supabase/migrations/20261008020000_onboard_artists_atomically.sql, line 3:

<comment>This migration is 114 lines, exceeding the rule’s 100-line file limit. Split the two onboarding function definitions into separate migration files or otherwise reduce the file below the limit.</comment>

<file context>
@@ -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,
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the already-applied preview migration intact. The applicable repository instructions do not impose a 100-line migration cap. Forward corrections are separate ordered migrations; splitting the recorded migration solely for a line threshold would introduce migration-history drift.

-- 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Exact case-sensitive equality on the extracted id silently misses legacy rows whose stored Spotify id was lowercased by the 2025-05-28 normalization backfill (case variants of the same id exist, per 20260729060000). A miss mints a duplicate artist account + case-variant social, and the next call hard-fails with the ambiguity error. Compare case-insensitively, and when multiple accounts differ only by URL case, raise ambiguity instead of creating.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At supabase/migrations/20261008020000_onboard_artists_atomically.sql, line 45:

<comment>Exact case-sensitive equality on the extracted id silently misses legacy rows whose stored Spotify id was lowercased by the 2025-05-28 normalization backfill (`case variants of the same id exist`, per 20260729060000). A miss mints a duplicate artist account + case-variant social, and the next call hard-fails with the ambiguity error. Compare case-insensitively, and when multiple accounts differ only by URL case, raise ambiguity instead of creating.</comment>

<file context>
@@ -0,0 +1,114 @@
+  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'
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not adopting case-insensitive identity resolution. Spotify IDs are case-sensitive; two valid IDs differing only by case must remain distinct, as the regression verifies. Historical destructive lowercasing cannot establish the original provider identity and needs source-backed repair outside this scoped onboarding fix. Matching those rows by case-insensitive guess could silently attach another artist.

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
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
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;
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
@@ -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.';

23 changes: 23 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading