Skip to content

Instantly share code, notes, and snippets.

@mansueli
Last active December 27, 2023 15:19
Show Gist options
  • Save mansueli/023b61137227547d8d509860a09672ca to your computer and use it in GitHub Desktop.
Save mansueli/023b61137227547d8d509860a09672ca to your computer and use it in GitHub Desktop.
Service role Vault interaction
GRANT pgsodium_keyiduser TO service_role;
CREATE OR REPLACE FUNCTION public.create_secret(secret text, name text, description text default '', key_id uuid default null)
RETURNS uuid
LANGUAGE plpgsql
SECURITY DEFINER
AS $function$
DECLARE
result uuid;
BEGIN
IF current_setting('request.jwt.claims', true)::jsonb->>'role' = 'service_role' THEN
SELECT * INTO result FROM vault.create_secret(
secret,
name,
description,
CASE WHEN key_id IS NULL THEN (pgsodium.create_key()).id ELSE key_id END
);
RETURN result;
ELSE
RAISE EXCEPTION 'Access denied: only service_role users can execute this function.';
END IF;
END;
$function$;
CREATE OR REPLACE FUNCTION public.get_secret(secret_name text)
RETURNS text
LANGUAGE plpgsql
SECURITY DEFINER
AS $function$
DECLARE
result text;
BEGIN
IF current_setting('request.jwt.claims', true)::jsonb->>'role' = 'service_role' THEN
SELECT decrypted_secret
INTO result
FROM vault.decrypted_secrets
WHERE name = secret_name;
RETURN result;
ELSE
RAISE EXCEPTION 'Access denied: only service_role users can execute this function.';
END IF;
END;
$function$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment