Skip to content

Commit 9644a2b

Browse files
committed
Backfill the id_token_claims column in the upstream_oauth_authorization_sessions table
1 parent 7410c2a commit 9644a2b

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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 do this before the backfilling starts, to make sure we don't miss anything
13+
CREATE OR REPLACE FUNCTION fill_id_token_claims()
14+
RETURNS TRIGGER AS $$
15+
BEGIN
16+
-- Only process if id_token_claims is NULL but id_token is not NULL
17+
IF NEW.id_token_claims IS NULL AND NEW.id_token IS NOT NULL AND NEW.id_token != '' THEN
18+
BEGIN
19+
-- Decode JWT payload inline
20+
NEW.id_token_claims := (
21+
CASE
22+
WHEN split_part(NEW.id_token, '.', 2) = '' THEN NULL
23+
ELSE
24+
(convert_from(
25+
decode(
26+
replace(replace(split_part(NEW.id_token, '.', 2), '-', '+'), '_', '/') ||
27+
repeat('=', (4 - length(split_part(NEW.id_token, '.', 2)) % 4) % 4),
28+
'base64'
29+
),
30+
'UTF8'
31+
))::JSONB
32+
END
33+
);
34+
EXCEPTION
35+
WHEN OTHERS THEN
36+
-- If JWT decoding fails, leave id_token_claims as NULL
37+
NEW.id_token_claims := NULL;
38+
END;
39+
END IF;
40+
41+
RETURN NEW;
42+
END;
43+
$$ LANGUAGE plpgsql;
44+
45+
-- Create the trigger
46+
CREATE TRIGGER trg_fill_id_token_claims
47+
BEFORE INSERT OR UPDATE ON upstream_oauth_authorization_sessions
48+
FOR EACH ROW
49+
EXECUTE FUNCTION fill_id_token_claims();
50+
51+
-- This backfills the id_token_claims column in the upstream_oauth_authorization_sessions table
52+
-- by decoding the id_token column and storing the decoded claims in the id_token_claims column.
53+
UPDATE upstream_oauth_authorization_sessions
54+
SET id_token_claims = CASE
55+
WHEN id_token IS NULL OR id_token = '' THEN NULL
56+
WHEN split_part(id_token, '.', 2) = '' THEN NULL
57+
ELSE
58+
(convert_from(
59+
decode(
60+
replace(replace(split_part(id_token, '.', 2), '-', '+'), '_', '/') ||
61+
repeat('=', (4 - length(split_part(id_token, '.', 2)) % 4) % 4),
62+
'base64'
63+
),
64+
'UTF8'
65+
))::JSONB
66+
END
67+
WHERE id_token IS NOT NULL AND id_token_claims IS NULL;

0 commit comments

Comments
 (0)