|
| 1 | +-- Copyright 2025 New Vector Ltd. |
| 2 | +-- |
| 3 | +-- SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial |
| 4 | +-- Please see LICENSE in the repository root for full details. |
| 5 | + |
| 6 | +-- We may be running an older version of the app that doesn't fill in the |
| 7 | +-- id_token_claims column when the id_token column is populated. So we add a |
| 8 | +-- trigger to fill in the id_token_claims column if it's NULL. |
| 9 | +-- |
| 10 | +-- We will be able to remove this trigger in a future version of the app. |
| 11 | +-- |
| 12 | +-- We backfill in a second migration after this one to make sure we don't miss |
| 13 | +-- any rows, and don't lock the table for too long. |
| 14 | +CREATE OR REPLACE FUNCTION fill_id_token_claims() |
| 15 | +RETURNS TRIGGER AS $$ |
| 16 | +BEGIN |
| 17 | + -- Only process if id_token_claims is NULL but id_token is not NULL |
| 18 | + IF NEW.id_token_claims IS NULL AND NEW.id_token IS NOT NULL AND NEW.id_token != '' THEN |
| 19 | + BEGIN |
| 20 | + -- Decode JWT payload inline |
| 21 | + NEW.id_token_claims := ( |
| 22 | + CASE |
| 23 | + WHEN split_part(NEW.id_token, '.', 2) = '' THEN NULL |
| 24 | + ELSE |
| 25 | + (convert_from( |
| 26 | + decode( |
| 27 | + replace(replace(split_part(NEW.id_token, '.', 2), '-', '+'), '_', '/') || |
| 28 | + repeat('=', (4 - length(split_part(NEW.id_token, '.', 2)) % 4) % 4), |
| 29 | + 'base64' |
| 30 | + ), |
| 31 | + 'UTF8' |
| 32 | + ))::JSONB |
| 33 | + END |
| 34 | + ); |
| 35 | + EXCEPTION |
| 36 | + WHEN OTHERS THEN |
| 37 | + -- If JWT decoding fails, leave id_token_claims as NULL |
| 38 | + NEW.id_token_claims := NULL; |
| 39 | + END; |
| 40 | + END IF; |
| 41 | + |
| 42 | + RETURN NEW; |
| 43 | +END; |
| 44 | +$$ LANGUAGE plpgsql; |
| 45 | + |
| 46 | +-- Create the trigger |
| 47 | +CREATE TRIGGER trg_fill_id_token_claims |
| 48 | + BEFORE INSERT OR UPDATE ON upstream_oauth_authorization_sessions |
| 49 | + FOR EACH ROW |
| 50 | + WHEN (NEW.id_token_claims IS NULL AND NEW.id_token IS NOT NULL AND NEW.id_token <> '') |
| 51 | + EXECUTE FUNCTION fill_id_token_claims(); |
0 commit comments