LoginSignup
1
2

More than 1 year has passed since last update.

PostgreSQL: security definerは「関数定義者で実行する」という設定である

Last updated at Posted at 2021-08-13

PostgreSQLはcreate functionで関数を定義できます。通常、関数の実行はPostgreSQLに接続したユーザーの権限で行われます。関数定義時にsecurity definerを指定すると、この通常の振る舞いではなく、関数の定義者ユーザーの権限で実行されます。

security definerのユースケース

security definerの使い道としては、あるスキーマやテーブルにはアクセスさせたくないユーザーに対して、特定の操作のときだけそのテーブルなどの使用を認めたい場合です。

例えば、accountテーブルにはパスワードやメールアドレスが入っていて、一般ユーザーにはselectupdateをさせたくないとします。しかし、アカウント新規登録は一般ユーザー権限でもできるようにしたい場合があります。こういったケースでは、アカウント新規登録用の関数を、accountテーブルへのCRUD権限があるユーザーで定義しておくと便利です。

アカウント登録関数の例:

create function register_author(name text, email text, password text) returns authors as
$$
declare
  author authors;
begin
  insert into authors
    (name)
    values
      (name)
    returning * into author;
  insert into private.account
    (id, email, password_hash)
    values
      (author.id, email, crypt(password, gen_salt('bf')));
  return author;
end;
$$ language plpgsql strict
                    security definer
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2