From c320343bb23dee027e7591b7829cb203e67ea850 Mon Sep 17 00:00:00 2001 From: Aidan Haran Date: Sat, 19 Oct 2024 18:18:34 +0100 Subject: [PATCH] Updated secrets error message if secrets files do not exist --- lib/kamal/secrets.rb | 17 +++++++++++------ test/secrets_test.rb | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/lib/kamal/secrets.rb b/lib/kamal/secrets.rb index c7d4cc03f..7a382f988 100644 --- a/lib/kamal/secrets.rb +++ b/lib/kamal/secrets.rb @@ -1,13 +1,10 @@ require "dotenv" class Kamal::Secrets - attr_reader :secrets_files - Kamal::Secrets::Dotenv::InlineCommandSubstitution.install! def initialize(destination: nil) - @secrets_files = \ - [ ".kamal/secrets-common", ".kamal/secrets#{(".#{destination}" if destination)}" ].select { |f| File.exist?(f) } + @destination = destination @mutex = Mutex.new end @@ -17,10 +14,10 @@ def [](key) secrets.fetch(key) end rescue KeyError - if secrets_files + if secrets_files.present? raise Kamal::ConfigurationError, "Secret '#{key}' not found in #{secrets_files.join(", ")}" else - raise Kamal::ConfigurationError, "Secret '#{key}' not found, no secret files provided" + raise Kamal::ConfigurationError, "Secret '#{key}' not found, no secret files (#{secrets_filenames.join(", ")}) provided" end end @@ -28,10 +25,18 @@ def to_h secrets end + def secrets_files + @secrets_files ||= secrets_filenames.select { |f| File.exist?(f) } + end + private def secrets @secrets ||= secrets_files.inject({}) do |secrets, secrets_file| secrets.merge!(::Dotenv.parse(secrets_file)) end end + + def secrets_filenames + [ ".kamal/secrets-common", ".kamal/secrets#{(".#{@destination}" if @destination)}" ] + end end diff --git a/test/secrets_test.rb b/test/secrets_test.rb index bb77a1965..aca9cebe8 100644 --- a/test/secrets_test.rb +++ b/test/secrets_test.rb @@ -31,4 +31,18 @@ class SecretsTest < ActiveSupport::TestCase assert_equal "JKL", Kamal::Secrets.new(destination: "nodest")["SECRET2"] end end + + test "no secrets files" do + with_test_secrets do + error = assert_raises(Kamal::ConfigurationError) do + Kamal::Secrets.new["SECRET"] + end + assert_equal "Secret 'SECRET' not found, no secret files (.kamal/secrets-common, .kamal/secrets) provided", error.message + + error = assert_raises(Kamal::ConfigurationError) do + Kamal::Secrets.new(destination: "dest")["SECRET"] + end + assert_equal "Secret 'SECRET' not found, no secret files (.kamal/secrets-common, .kamal/secrets.dest) provided", error.message + end + end end