Skip to content

Commit 56e492d

Browse files
fix: Fix enc/dec function to make them trackable by hasura
1 parent 390f34a commit 56e492d

File tree

2 files changed

+44
-12
lines changed

2 files changed

+44
-12
lines changed

memory-store/migrations/000042_add_api_keys.down.sql

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
BEGIN;
22

3-
-- Drop helper functions
3+
-- Drop helper functions (updated signatures due to composite type returns)
44
DROP FUNCTION IF EXISTS decrypt_api_key(BYTEA, TEXT);
55
DROP FUNCTION IF EXISTS encrypt_api_key(TEXT, TEXT);
66

7+
-- Drop composite types
8+
DROP TYPE IF EXISTS decrypted_api_key_result;
9+
DROP TYPE IF EXISTS encrypted_api_key_result;
10+
711
-- Drop trigger and function
812
DROP TRIGGER IF EXISTS update_api_keys_timestamp_trigger ON api_keys;
913
DROP FUNCTION IF EXISTS update_api_keys_timestamp();

memory-store/migrations/000042_add_api_keys.up.sql

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -42,29 +42,57 @@ CREATE INDEX IF NOT EXISTS idx_api_keys_name ON api_keys(name);
4242
CREATE INDEX IF NOT EXISTS idx_api_keys_metadata ON api_keys USING gin(metadata);
4343
CREATE INDEX IF NOT EXISTS idx_api_keys_deleted_at ON api_keys(deleted_at) WHERE deleted_at IS NULL;
4444

45+
-- Create composite types for function return values (so they can be tracked by Hasura)
46+
DO $$
47+
BEGIN
48+
IF NOT EXISTS (
49+
SELECT 1 FROM pg_type WHERE typname = 'encrypted_api_key_result'
50+
) THEN
51+
CREATE TYPE encrypted_api_key_result AS (
52+
encrypted_value BYTEA
53+
);
54+
END IF;
55+
END $$;
56+
57+
DO $$
58+
BEGIN
59+
IF NOT EXISTS (
60+
SELECT 1 FROM pg_type WHERE typname = 'decrypted_api_key_result'
61+
) THEN
62+
CREATE TYPE decrypted_api_key_result AS (
63+
decrypted_value TEXT
64+
);
65+
END IF;
66+
END $$;
67+
4568
-- Helper functions for encryption/decryption (following secrets pattern)
69+
-- Modified to return composite types so they can be tracked by Hasura
4670
CREATE OR REPLACE FUNCTION encrypt_api_key(
4771
p_value TEXT,
4872
p_key TEXT
49-
) RETURNS BYTEA AS $$
73+
) RETURNS encrypted_api_key_result AS $$
5074
BEGIN
51-
RETURN pgp_sym_encrypt(
52-
p_value,
53-
p_key,
54-
'cipher-algo=aes256'
55-
);
75+
RETURN ROW(
76+
pgp_sym_encrypt(
77+
p_value,
78+
p_key,
79+
'cipher-algo=aes256'
80+
)
81+
)::encrypted_api_key_result;
5682
END;
5783
$$ LANGUAGE plpgsql SECURITY DEFINER;
5884

5985
CREATE OR REPLACE FUNCTION decrypt_api_key(
6086
p_encrypted_value BYTEA,
6187
p_key TEXT
62-
) RETURNS TEXT AS $$
88+
) RETURNS decrypted_api_key_result AS $$
6389
BEGIN
64-
RETURN pgp_sym_decrypt(
65-
p_encrypted_value,
66-
p_key
67-
);
90+
RETURN ROW(
91+
pgp_sym_decrypt(
92+
p_encrypted_value,
93+
p_key
94+
)
95+
)::decrypted_api_key_result;
6896
END;
6997
$$ LANGUAGE plpgsql SECURITY DEFINER;
7098

0 commit comments

Comments
 (0)