LoginSignup
1
0

More than 3 years have passed since last update.

Rails new するだけで、なぜかローカルのPostgreSQL環境につながってしまう話

Last updated at Posted at 2019-06-08

という問題に遭遇。

database.ymlで、
ユーザ名もパスワードも設定していないのに、
普通にdb:createとか出来てしまう。

個人開発の環境で、
RailsからDBにアクセスはできるので直ちに実害は無いけど、
気持ち悪いので調査。

結論としては、以下2つの組み合わせっぽい。

  • Rails database.ymlデフォルト動作
  • HomebrewからPostgreSQLをインストールした際のデフォルト設定

Rails database.ymlデフォルト動作

特にdatabase.ymlでusernameもpasswordも設定していない場合、
Railsは以下のような動作をするらしい。

database.yml
  # The specified database role being used to connect to postgres.
  # To create additional roles in postgres see `$ createuser --help`.
  # When left blank, postgres will use the default role. This is
  # the same name as the operating system user that initialized the database.
  username:

端的に言うと、
usernameが設定されていない場合は、
DBの初期設定を実施したOSのユーザ名を使うよ、

という感じだと思う。

多分通常は、PCのユーザ名辺りが使われるんだろう。
なるほどなるほど。

HomebrewからPostgreSQLをインストールした際のデフォルト設定

usernameを設定しなくても、有効なPostgreSQLのユーザ名を指定してくれるのは分かった。

でもPostgreSQL側で設定しているはずのpasswordが無視されているのは納得いかない!

で調べた所あっさり理由は見つかった。

HomebrewでPostgreSQLをインストールすると
pg_hba.conf に記載される初期設定では、 接続を無条件で許可する というせっていになっている。
https://qiita.com/Mitsunori_Tsukada/items/383a7b7124e3c4d9c82f

何だそりゃまじかー。

確かにこんな感じになっていた。

pg_hba.conf
# CAUTION: Configuring the system for local "trust" authentication
# allows any local user to connect as any PostgreSQL user, including
# the database superuser.  If you do not trust all your local users,
# use another authentication method.

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust

コメント含めて、めっちゃ書いてあるね。

まとめ

  • コメント有能。ちゃんと読むべき。
  • PostgreSQLの基本設定項目くらいは知っとかないとな。。。

特にPostgreSQLはこの設定知っていれば瞬殺だった気がする;;

1
0
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
0