LoginSignup
31
12

More than 3 years have passed since last update.

不正な config/master.key が原因でRailsの起動に失敗するケースとその対処方法

Last updated at Posted at 2021-01-17

発生する問題

git cloneでローカルに持ってきたRailsアプリを、rails srails cで起動しようとすると以下のようなエラーが発生する。

$ rails s
=> Booting Puma
=> Rails 6.1.0 application starting in development 
=> Run `bin/rails server --help` for more startup options
Exiting
/Users/jnito/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/activesupport-6.1.0/lib/active_support/message_encryptor.rb:203:in `rescue in _decrypt': ActiveSupport::MessageEncryptor::InvalidMessage (ActiveSupport::MessageEncryptor::InvalidMessage)

エラーの原因

config/master.key の鍵が config/credentials.yml.enc 用の鍵と一致していないため、例外が発生してRailsが起動しなくなった。

もう少し詳しく

config/master.keyは通常、.gitignoreに追加してソースコード管理の対象外とするファイルである。そのため、git cloneしてもconfig/master.keyはローカルにはコピーされない。

その状態で「credentials.yml.encを編集したい」と思ってEDITOR="vi" bin/rails credentials:editのようなコマンドを実行すると、以下のようなメッセージとともに、config/master.keyが新規に作成されてしまう。(加えて、credentials.yml.encの編集もできない)

$ EDITOR="vi" bin/rails credentials:edit
Adding config/master.key to store the encryption key: 6eb4ad(以下略)

Save this in a password manager your team can access.

If you lose the key, no one, including you, can access anything encrypted with it.

      create  config/master.key

Couldn't decrypt config/credentials.yml.enc. Perhaps you passed the wrong key?

ただし、新規に作られたconfig/master.keyはgit cloneしてきたconfig/credentials.yml.encの鍵ではないため、Rails起動時に復号化に失敗して例外(ActiveSupport::MessageEncryptor::InvalidMessage)が発生してしまう。

対処方法

状況によって対処方法は異なる。

git cloneする前にcredentials.yml.encが使われていた場合

開発チーム内で鍵の共有方法が決められているはずなので、その運用ルールに従って適切なconfig/master.keyを自分のローカルに配置する。

credentials.yml.encが今まで使われていなかった場合

自動的に作られたconfig/master.keyを削除すればRailsが起動するようになる。

今後もcredentials.yml.encを使わないのであれば、config/credentials.yml.encごと削除するのも一手。

逆に、これからcredentials.yml.encを使っていく(=自分がチーム内で最初の利用者になる)場合は、新規にconfig/credentials.yml.encを作り直した上でcredentials/master.keyをチーム内で適切に管理・共有する必要がある。
(ただし、どこかから適切なconfig/master.keyを入手できれば新規に作り直す必要はない)

# 既存のcredentials.yml.encを削除
$ rm config/credentials.yml.enc

# credentials.yml.encとmaster.keyを新規に作成して編集する
$ EDITOR="vi" bin/rails credentials:edit
Adding config/master.key to store the encryption key: 917c31e316061bcdd909754a56897f61

Save this in a password manager your team can access.

If you lose the key, no one, including you, can access anything encrypted with it.

      create  config/master.key

File encrypted and saved.

動作確認環境

  • Rails 6.1.0
31
12
2

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
31
12