Commit e7762cd5 authored by Vitali Tatarintev's avatar Vitali Tatarintev

Merge branch 'encrypted-smtp-creds' into 'master'

Add support for encrypted SMTP credentials

See merge request gitlab-org/gitlab!67802
parents c4e80089 07973a98
...@@ -118,6 +118,8 @@ production: &base ...@@ -118,6 +118,8 @@ production: &base
# ca_certs_file: /home/git/gitlab/.gitlab_smime_ca_certs # ca_certs_file: /home/git/gitlab/.gitlab_smime_ca_certs
# Email server smtp settings are in config/initializers/smtp_settings.rb.sample # Email server smtp settings are in config/initializers/smtp_settings.rb.sample
# File location to read encrypted SMTP secrets from
# email_smtp_secret_file: /mnt/gitlab/smtp.yaml.enc # Default: shared/encrypted_settings/smtp.yaml.enc
# default_can_create_group: false # default: true # default_can_create_group: false # default: true
# username_changing_enabled: false # default: true - User can change their username/namespace # username_changing_enabled: false # default: true - User can change their username/namespace
......
...@@ -178,6 +178,7 @@ Settings.gitlab['email_display_name'] ||= ENV['GITLAB_EMAIL_DISPLAY_NAME'] || 'G ...@@ -178,6 +178,7 @@ Settings.gitlab['email_display_name'] ||= ENV['GITLAB_EMAIL_DISPLAY_NAME'] || 'G
Settings.gitlab['email_reply_to'] ||= ENV['GITLAB_EMAIL_REPLY_TO'] || "noreply@#{Settings.gitlab.host}" Settings.gitlab['email_reply_to'] ||= ENV['GITLAB_EMAIL_REPLY_TO'] || "noreply@#{Settings.gitlab.host}"
Settings.gitlab['email_subject_suffix'] ||= ENV['GITLAB_EMAIL_SUBJECT_SUFFIX'] || "" Settings.gitlab['email_subject_suffix'] ||= ENV['GITLAB_EMAIL_SUBJECT_SUFFIX'] || ""
Settings.gitlab['email_smime'] = SmimeSignatureSettings.parse(Settings.gitlab['email_smime']) Settings.gitlab['email_smime'] = SmimeSignatureSettings.parse(Settings.gitlab['email_smime'])
Settings.gitlab['email_smtp_secret_file'] = Settings.absolute(Settings.gitlab['email_smtp_secret_file'] || File.join(Settings.encrypted_settings['path'], "smtp.yaml.enc"))
Settings.gitlab['base_url'] ||= Settings.__send__(:build_base_gitlab_url) Settings.gitlab['base_url'] ||= Settings.__send__(:build_base_gitlab_url)
Settings.gitlab['url'] ||= Settings.__send__(:build_gitlab_url) Settings.gitlab['url'] ||= Settings.__send__(:build_gitlab_url)
Settings.gitlab['user'] ||= 'git' Settings.gitlab['user'] ||= 'git'
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
if Rails.env.production? if Rails.env.production?
Rails.application.config.action_mailer.delivery_method = :smtp Rails.application.config.action_mailer.delivery_method = :smtp
secrets = Gitlab::Email::SmtpConfig.secrets
ActionMailer::Base.delivery_method = :smtp ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = { ActionMailer::Base.smtp_settings = {
...@@ -16,6 +17,10 @@ if Rails.env.production? ...@@ -16,6 +17,10 @@ if Rails.env.production?
port: 465, port: 465,
user_name: "smtp", user_name: "smtp",
password: "123456", password: "123456",
## If you are using encrypted smtp credentials then you should instead use the secrets user_name/password
## See: https://docs.gitlab.com/ee/administration/raketasks/smtp.html#secrets
# user_name: secrets.username,
# password: secrets.password,
domain: "gitlab.company.com", domain: "gitlab.company.com",
authentication: :login, authentication: :login,
enable_starttls_auto: true, enable_starttls_auto: true,
...@@ -31,6 +36,7 @@ end ...@@ -31,6 +36,7 @@ end
# #
# if Rails.env.production? # if Rails.env.production?
# Rails.application.config.action_mailer.delivery_method = :smtp_pool # Rails.application.config.action_mailer.delivery_method = :smtp_pool
# secrets = Gitlab::Email::SmtpConfig.secrets
# #
# ActionMailer::Base.delivery_method = :smtp_pool # ActionMailer::Base.delivery_method = :smtp_pool
# ActionMailer::Base.smtp_pool_settings = { # ActionMailer::Base.smtp_pool_settings = {
...@@ -40,6 +46,10 @@ end ...@@ -40,6 +46,10 @@ end
# port: 465, # port: 465,
# user_name: "smtp", # user_name: "smtp",
# password: "123456", # password: "123456",
# ## If you are using encrypted smtp credentials then you should instead use the secrets user_name/password
# ## See: https://docs.gitlab.com/ee/administration/raketasks/smtp.html#secrets
# # user_name: secrets.username,
# # password: secrets.password,
# domain: "gitlab.company.com", # domain: "gitlab.company.com",
# authentication: :login, # authentication: :login,
# enable_starttls_auto: true, # enable_starttls_auto: true,
......
---
key_path: settings.smtp_encrypted_secrets_enabled
description: Is encrypted SMTP secrets configured?
product_section: enablement
product_stage: enablement
product_group: distribution
value_type: boolean
status: implemented
milestone: "14.2"
introduced_by_url: https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67802
time_frame: none
data_source: system
data_category: Optional
distribution:
- ce
- ee
tier:
- free
- premium
- ultimate
...@@ -12,6 +12,7 @@ type: reference ...@@ -12,6 +12,7 @@ type: reference
GitLab can read settings for certain features from encrypted settings files. The supported features are: GitLab can read settings for certain features from encrypted settings files. The supported features are:
- [LDAP `user_bn` and `password`](auth/ldap/index.md#using-encrypted-credentials) - [LDAP `user_bn` and `password`](auth/ldap/index.md#using-encrypted-credentials)
- [SMTP `user_name` and `password`](raketasks/smtp.md#secrets)
In order to enable the encrypted configuration settings, a new base key needs to be generated for In order to enable the encrypted configuration settings, a new base key needs to be generated for
`encrypted_settings_key_base`. The secret can be generated in the following ways: `encrypted_settings_key_base`. The secret can be generated in the following ways:
......
---
stage: Enablement
group: Distribution
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#assignments
---
# SMTP Rake tasks **(FREE SELF)**
[Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67802) in GitLab 14.2.
The following are SMTP-related Rake tasks.
## Secrets
GitLab can use SMTP configuration secrets to read from an encrypted file. The following Rake tasks are provided for updating the contents of the encrypted file.
### Show secret
Show the contents of the current SMTP secrets.
**Omnibus Installation**
```shell
sudo gitlab-rake gitlab:smtp:secret:show
```
**Source Installation**
```shell
bundle exec rake gitlab:smtp:secret:show RAILS_ENV=production
```
**Example output:**
```plaintext
password: '123'
user_name: 'gitlab-inst'
```
### Edit secret
Opens the secret contents in your editor, and writes the resulting content to the encrypted secret file when you exit.
**Omnibus Installation**
```shell
sudo gitlab-rake gitlab:smtp:secret:edit EDITOR=vim
```
**Source Installation**
```shell
bundle exec rake gitlab:smtp:secret:edit RAILS_ENV=production EDITOR=vim
```
### Write raw secret
Write new secret content by providing it on STDIN.
**Omnibus Installation**
```shell
echo -e "password: '123'" | sudo gitlab-rake gitlab:smtp:secret:write
```
**Source Installation**
```shell
echo -e "password: '123'" | bundle exec rake gitlab:smtp:secret:write RAILS_ENV=production
```
### Secrets examples
**Editor example**
The write task can be used in cases where the edit command does not work with your editor:
```shell
# Write the existing secret to a plaintext file
sudo gitlab-rake gitlab:smtp:secret:show > smtp.yaml
# Edit the smtp file in your editor
...
# Re-encrypt the file
cat smtp.yaml | sudo gitlab-rake gitlab:smtp:secret:write
# Remove the plaintext file
rm smtp.yaml
```
**KMS integration example**
It can also be used as a receiving application for content encrypted with a KMS:
```shell
gcloud kms decrypt --key my-key --keyring my-test-kms --plaintext-file=- --ciphertext-file=my-file --location=us-west1 | sudo gitlab-rake gitlab:smtp:secret:write
```
**Google Cloud secret integration example**
It can also be used as a receiving application for secrets out of Google Cloud:
```shell
gcloud secrets versions access latest --secret="my-test-secret" > $1 | sudo gitlab-rake gitlab:smtp:secret:write
```
...@@ -42,6 +42,7 @@ The following Rake tasks are available for use with GitLab: ...@@ -42,6 +42,7 @@ The following Rake tasks are available for use with GitLab:
| [Project import/export](../administration/raketasks/project_import_export.md) | Prepare for [project exports and imports](../user/project/settings/import_export.md). | | [Project import/export](../administration/raketasks/project_import_export.md) | Prepare for [project exports and imports](../user/project/settings/import_export.md). |
| [Sample Prometheus data](generate_sample_prometheus_data.md) | Generate sample Prometheus data. | | [Sample Prometheus data](generate_sample_prometheus_data.md) | Generate sample Prometheus data. |
| [Sidekiq job migration](sidekiq_job_migration.md) | Migrate Sidekiq jobs scheduled for future dates to a new queue. | | [Sidekiq job migration](sidekiq_job_migration.md) | Migrate Sidekiq jobs scheduled for future dates to a new queue. |
| [SMTP maintenance](../administration/raketasks/smtp.md) | SMTP-related tasks. |
| [SPDX license list import](spdx.md) | Import a local copy of the [SPDX license list](https://spdx.org/licenses/) for matching [License Compliance policies](../user/compliance/license_compliance/index.md). | | [SPDX license list import](spdx.md) | Import a local copy of the [SPDX license list](https://spdx.org/licenses/) for matching [License Compliance policies](../user/compliance/license_compliance/index.md). |
| [Repository storage](../administration/raketasks/storage.md) | List and migrate existing projects and attachments from legacy storage to hashed storage. | | [Repository storage](../administration/raketasks/storage.md) | List and migrate existing projects and attachments from legacy storage to hashed storage. |
| [Uploads migrate](../administration/raketasks/uploads/migrate.md) | Migrate uploads between local storage and object storage. | | [Uploads migrate](../administration/raketasks/uploads/migrate.md) | Migrate uploads between local storage and object storage. |
......
# frozen_string_literal: true
module Gitlab
module Email
class SmtpConfig
def self.encrypted_secrets
Settings.encrypted(Gitlab.config.gitlab.email_smtp_secret_file)
end
def self.secrets
self.new
end
def initialize
@secrets ||= self.class.encrypted_secrets.config
rescue StandardError => e
Gitlab::AppLogger.error "SMTP encrypted secrets are invalid: #{e.inspect}"
end
def username
@secrets&.fetch(:user_name, nil)&.chomp
end
def password
@secrets&.fetch(:password, nil)&.chomp
end
end
end
end
# frozen_string_literal: true
# rubocop:disable Rails/Output
module Gitlab
class EncryptedCommandBase
DISPLAY_NAME = "Base"
EDIT_COMMAND_NAME = "base"
class << self
def encrypted_secrets
raise NotImplementedError
end
def write(contents)
encrypted = encrypted_secrets
return unless validate_config(encrypted)
validate_contents(contents)
encrypted.write(contents)
puts "File encrypted and saved."
rescue Interrupt
warn "Aborted changing file: nothing saved."
rescue ActiveSupport::MessageEncryptor::InvalidMessage
warn "Couldn't decrypt #{encrypted.content_path}. Perhaps you passed the wrong key?"
end
def edit
encrypted = encrypted_secrets
return unless validate_config(encrypted)
if ENV["EDITOR"].blank?
warn 'No $EDITOR specified to open file. Please provide one when running the command:'
warn "gitlab-rake #{self::EDIT_COMMAND_NAME} EDITOR=vim"
return
end
temp_file = Tempfile.new(File.basename(encrypted.content_path), File.dirname(encrypted.content_path))
contents_changed = false
encrypted.change do |contents|
contents = encrypted_file_template unless File.exist?(encrypted.content_path)
File.write(temp_file.path, contents)
system(ENV['EDITOR'], temp_file.path)
changes = File.read(temp_file.path)
contents_changed = contents != changes
validate_contents(changes)
changes
end
puts "Contents were unchanged." unless contents_changed
puts "File encrypted and saved."
rescue Interrupt
warn "Aborted changing file: nothing saved."
rescue ActiveSupport::MessageEncryptor::InvalidMessage
warn "Couldn't decrypt #{encrypted.content_path}. Perhaps you passed the wrong key?"
ensure
temp_file&.unlink
end
def show
encrypted = encrypted_secrets
return unless validate_config(encrypted)
puts encrypted.read.presence || "File '#{encrypted.content_path}' does not exist. Use `gitlab-rake #{self::EDIT_COMMAND_NAME}` to change that."
rescue ActiveSupport::MessageEncryptor::InvalidMessage
warn "Couldn't decrypt #{encrypted.content_path}. Perhaps you passed the wrong key?"
end
def validate_config(encrypted)
dir_path = File.dirname(encrypted.content_path)
unless File.exist?(dir_path)
warn "Directory #{dir_path} does not exist. Create the directory and try again."
return false
end
if encrypted.key.nil?
warn "Missing encryption key encrypted_settings_key_base."
return false
end
true
end
def validate_contents(contents)
begin
config = YAML.safe_load(contents, permitted_classes: [Symbol])
error_contents = "Did not include any key-value pairs" unless config.is_a?(Hash)
rescue Psych::Exception => e
error_contents = e.message
end
puts "WARNING: Content was not a valid #{self::DISPLAY_NAME} secret yml file. #{error_contents}" if error_contents
contents
end
def encrypted_file_template
raise NotImplementedError
end
end
end
end
# rubocop:enable Rails/Output
...@@ -2,93 +2,13 @@ ...@@ -2,93 +2,13 @@
# rubocop:disable Rails/Output # rubocop:disable Rails/Output
module Gitlab module Gitlab
class EncryptedLdapCommand class EncryptedLdapCommand < EncryptedCommandBase
class << self DISPLAY_NAME = "LDAP"
def write(contents) EDIT_COMMAND_NAME = "gitlab:ldap:secret:edit"
encrypted = Gitlab::Auth::Ldap::Config.encrypted_secrets
return unless validate_config(encrypted)
validate_contents(contents)
encrypted.write(contents)
puts "File encrypted and saved."
rescue Interrupt
puts "Aborted changing file: nothing saved."
rescue ActiveSupport::MessageEncryptor::InvalidMessage
puts "Couldn't decrypt #{encrypted.content_path}. Perhaps you passed the wrong key?"
end
def edit
encrypted = Gitlab::Auth::Ldap::Config.encrypted_secrets
return unless validate_config(encrypted)
if ENV["EDITOR"].blank?
puts 'No $EDITOR specified to open file. Please provide one when running the command:'
puts 'gitlab-rake gitlab:ldap:secret:edit EDITOR=vim'
return
end
temp_file = Tempfile.new(File.basename(encrypted.content_path), File.dirname(encrypted.content_path)) class << self
contents_changed = false def encrypted_secrets
Gitlab::Auth::Ldap::Config.encrypted_secrets
encrypted.change do |contents|
contents = encrypted_file_template unless File.exist?(encrypted.content_path)
File.write(temp_file.path, contents)
system(ENV['EDITOR'], temp_file.path)
changes = File.read(temp_file.path)
contents_changed = contents != changes
validate_contents(changes)
changes
end
puts "Contents were unchanged." unless contents_changed
puts "File encrypted and saved."
rescue Interrupt
puts "Aborted changing file: nothing saved."
rescue ActiveSupport::MessageEncryptor::InvalidMessage
puts "Couldn't decrypt #{encrypted.content_path}. Perhaps you passed the wrong key?"
ensure
temp_file&.unlink
end
def show
encrypted = Gitlab::Auth::Ldap::Config.encrypted_secrets
return unless validate_config(encrypted)
puts encrypted.read.presence || "File '#{encrypted.content_path}' does not exist. Use `gitlab-rake gitlab:ldap:secret:edit` to change that."
rescue ActiveSupport::MessageEncryptor::InvalidMessage
puts "Couldn't decrypt #{encrypted.content_path}. Perhaps you passed the wrong key?"
end
private
def validate_config(encrypted)
dir_path = File.dirname(encrypted.content_path)
unless File.exist?(dir_path)
puts "Directory #{dir_path} does not exist. Create the directory and try again."
return false
end
if encrypted.key.nil?
puts "Missing encryption key encrypted_settings_key_base."
return false
end
true
end
def validate_contents(contents)
begin
config = YAML.safe_load(contents, permitted_classes: [Symbol])
error_contents = "Did not include any key-value pairs" unless config.is_a?(Hash)
rescue Psych::Exception => e
error_contents = e.message
end
puts "WARNING: Content was not a valid LDAP secret yml file. #{error_contents}" if error_contents
contents
end end
def encrypted_file_template def encrypted_file_template
......
# frozen_string_literal: true
# rubocop:disable Rails/Output
module Gitlab
class EncryptedSmtpCommand < EncryptedCommandBase
DISPLAY_NAME = "SMTP"
EDIT_COMMAND_NAME = "gitlab:smtp:secret:edit"
class << self
def encrypted_secrets
Gitlab::Email::SmtpConfig.encrypted_secrets
end
def encrypted_file_template
<<~YAML
# password: '123'
# user_name: 'gitlab-inst'
YAML
end
end
end
end
# rubocop:enable Rails/Output
...@@ -256,6 +256,7 @@ module Gitlab ...@@ -256,6 +256,7 @@ module Gitlab
{ {
settings: { settings: {
ldap_encrypted_secrets_enabled: alt_usage_data(fallback: nil) { Gitlab::Auth::Ldap::Config.encrypted_secrets.active? }, ldap_encrypted_secrets_enabled: alt_usage_data(fallback: nil) { Gitlab::Auth::Ldap::Config.encrypted_secrets.active? },
smtp_encrypted_secrets_enabled: alt_usage_data(fallback: nil) { Gitlab::Email::SmtpConfig.encrypted_secrets.active? },
operating_system: alt_usage_data(fallback: nil) { operating_system }, operating_system: alt_usage_data(fallback: nil) { operating_system },
gitaly_apdex: alt_usage_data { gitaly_apdex }, gitaly_apdex: alt_usage_data { gitaly_apdex },
collected_data_categories: add_metric('CollectedDataCategoriesMetric', time_frame: 'none') collected_data_categories: add_metric('CollectedDataCategoriesMetric', time_frame: 'none')
......
# frozen_string_literal: true
namespace :gitlab do
namespace :smtp do
namespace :secret do
desc 'GitLab | SMTP | Secret | Write SMTP secrets'
task write: [:environment] do
content = $stdin.tty? ? $stdin.gets : $stdin.read
Gitlab::EncryptedSmtpCommand.write(content)
end
desc 'GitLab | SMTP | Secret | Edit SMTP secrets'
task edit: [:environment] do
Gitlab::EncryptedSmtpCommand.edit
end
desc 'GitLab | SMTP | Secret | Show SMTP secrets'
task show: [:environment] do
Gitlab::EncryptedSmtpCommand.show
end
end
end
end
...@@ -1067,8 +1067,9 @@ RSpec.describe Gitlab::UsageData, :aggregate_failures do ...@@ -1067,8 +1067,9 @@ RSpec.describe Gitlab::UsageData, :aggregate_failures do
subject { described_class.system_usage_data_settings } subject { described_class.system_usage_data_settings }
it 'gathers settings usage data', :aggregate_failures do it 'gathers encrypted secrets usage data', :aggregate_failures do
expect(subject[:settings][:ldap_encrypted_secrets_enabled]).to eq(Gitlab::Auth::Ldap::Config.encrypted_secrets.active?) expect(subject[:settings][:ldap_encrypted_secrets_enabled]).to eq(Gitlab::Auth::Ldap::Config.encrypted_secrets.active?)
expect(subject[:settings][:smtp_encrypted_secrets_enabled]).to eq(Gitlab::Email::SmtpConfig.encrypted_secrets.active?)
end end
it 'populates operating system information' do it 'populates operating system information' do
......
...@@ -38,13 +38,13 @@ RSpec.describe 'gitlab:ldap:secret rake tasks' do ...@@ -38,13 +38,13 @@ RSpec.describe 'gitlab:ldap:secret rake tasks' do
it 'displays error when key does not exist' do it 'displays error when key does not exist' do
Settings.encrypted(ldap_secret_file).write('somevalue') Settings.encrypted(ldap_secret_file).write('somevalue')
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil) allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil)
expect { run_rake_task('gitlab:ldap:secret:show') }.to output(/Missing encryption key encrypted_settings_key_base./).to_stdout expect { run_rake_task('gitlab:ldap:secret:show') }.to output(/Missing encryption key encrypted_settings_key_base./).to_stderr
end end
it 'displays error when key is changed' do it 'displays error when key is changed' do
Settings.encrypted(ldap_secret_file).write('somevalue') Settings.encrypted(ldap_secret_file).write('somevalue')
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(SecureRandom.hex(64)) allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(SecureRandom.hex(64))
expect { run_rake_task('gitlab:ldap:secret:show') }.to output(/Couldn't decrypt .* Perhaps you passed the wrong key?/).to_stdout expect { run_rake_task('gitlab:ldap:secret:show') }.to output(/Couldn't decrypt .* Perhaps you passed the wrong key?/).to_stderr
end end
it 'outputs the unencrypted content when present' do it 'outputs the unencrypted content when present' do
...@@ -64,18 +64,18 @@ RSpec.describe 'gitlab:ldap:secret rake tasks' do ...@@ -64,18 +64,18 @@ RSpec.describe 'gitlab:ldap:secret rake tasks' do
it 'displays error when key does not exist' do it 'displays error when key does not exist' do
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil) allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil)
expect { run_rake_task('gitlab:ldap:secret:edit') }.to output(/Missing encryption key encrypted_settings_key_base./).to_stdout expect { run_rake_task('gitlab:ldap:secret:edit') }.to output(/Missing encryption key encrypted_settings_key_base./).to_stderr
end end
it 'displays error when key is changed' do it 'displays error when key is changed' do
Settings.encrypted(ldap_secret_file).write('somevalue') Settings.encrypted(ldap_secret_file).write('somevalue')
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(SecureRandom.hex(64)) allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(SecureRandom.hex(64))
expect { run_rake_task('gitlab:ldap:secret:edit') }.to output(/Couldn't decrypt .* Perhaps you passed the wrong key?/).to_stdout expect { run_rake_task('gitlab:ldap:secret:edit') }.to output(/Couldn't decrypt .* Perhaps you passed the wrong key?/).to_stderr
end end
it 'displays error when write directory does not exist' do it 'displays error when write directory does not exist' do
FileUtils.rm_rf(Rails.root.join('tmp/tests/ldapenc')) FileUtils.rm_rf(Rails.root.join('tmp/tests/ldapenc'))
expect { run_rake_task('gitlab:ldap:secret:edit') }.to output(/Directory .* does not exist./).to_stdout expect { run_rake_task('gitlab:ldap:secret:edit') }.to output(/Directory .* does not exist./).to_stderr
end end
it 'shows a warning when content is invalid' do it 'shows a warning when content is invalid' do
...@@ -87,7 +87,7 @@ RSpec.describe 'gitlab:ldap:secret rake tasks' do ...@@ -87,7 +87,7 @@ RSpec.describe 'gitlab:ldap:secret rake tasks' do
it 'displays error when $EDITOR is not set' do it 'displays error when $EDITOR is not set' do
stub_env('EDITOR', nil) stub_env('EDITOR', nil)
expect { run_rake_task('gitlab:ldap:secret:edit') }.to output(/No \$EDITOR specified to open file. Please provide one when running the command/).to_stdout expect { run_rake_task('gitlab:ldap:secret:edit') }.to output(/No \$EDITOR specified to open file. Please provide one when running the command/).to_stderr
end end
end end
...@@ -106,12 +106,12 @@ RSpec.describe 'gitlab:ldap:secret rake tasks' do ...@@ -106,12 +106,12 @@ RSpec.describe 'gitlab:ldap:secret rake tasks' do
it 'displays error when key does not exist' do it 'displays error when key does not exist' do
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil) allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil)
expect { run_rake_task('gitlab:ldap:secret:write') }.to output(/Missing encryption key encrypted_settings_key_base./).to_stdout expect { run_rake_task('gitlab:ldap:secret:write') }.to output(/Missing encryption key encrypted_settings_key_base./).to_stderr
end end
it 'displays error when write directory does not exist' do it 'displays error when write directory does not exist' do
FileUtils.rm_rf('tmp/tests/ldapenc/') FileUtils.rm_rf('tmp/tests/ldapenc/')
expect { run_rake_task('gitlab:ldap:secret:write') }.to output(/Directory .* does not exist./).to_stdout expect { run_rake_task('gitlab:ldap:secret:write') }.to output(/Directory .* does not exist./).to_stderr
end end
it 'shows a warning when content is invalid' do it 'shows a warning when content is invalid' do
......
# frozen_string_literal: true
require 'rake_helper'
RSpec.describe 'gitlab:smtp:secret rake tasks' do
let(:smtp_secret_file) { 'tmp/tests/smtpenc/smtp_secret.yaml.enc' }
before do
Rake.application.rake_require 'tasks/gitlab/smtp'
stub_env('EDITOR', 'cat')
stub_warn_user_is_not_gitlab
FileUtils.mkdir_p('tmp/tests/smtpenc/')
allow(Gitlab.config.gitlab).to receive(:email_smtp_secret_file).and_return(smtp_secret_file)
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(SecureRandom.hex(64))
end
after do
FileUtils.rm_rf(Rails.root.join('tmp/tests/smtpenc'))
end
describe ':show' do
it 'displays error when file does not exist' do
expect { run_rake_task('gitlab:smtp:secret:show') }.to output(/File .* does not exist. Use `gitlab-rake gitlab:smtp:secret:edit` to change that./).to_stdout
end
it 'displays error when key does not exist' do
Settings.encrypted(smtp_secret_file).write('somevalue')
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil)
expect { run_rake_task('gitlab:smtp:secret:show') }.to output(/Missing encryption key encrypted_settings_key_base./).to_stderr
end
it 'displays error when key is changed' do
Settings.encrypted(smtp_secret_file).write('somevalue')
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(SecureRandom.hex(64))
expect { run_rake_task('gitlab:smtp:secret:show') }.to output(/Couldn't decrypt .* Perhaps you passed the wrong key?/).to_stderr
end
it 'outputs the unencrypted content when present' do
encrypted = Settings.encrypted(smtp_secret_file)
encrypted.write('somevalue')
expect { run_rake_task('gitlab:smtp:secret:show') }.to output(/somevalue/).to_stdout
end
end
describe 'edit' do
it 'creates encrypted file' do
expect { run_rake_task('gitlab:smtp:secret:edit') }.to output(/File encrypted and saved./).to_stdout
expect(File.exist?(smtp_secret_file)).to be true
value = Settings.encrypted(smtp_secret_file)
expect(value.read).to match(/password: '123'/)
end
it 'displays error when key does not exist' do
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil)
expect { run_rake_task('gitlab:smtp:secret:edit') }.to output(/Missing encryption key encrypted_settings_key_base./).to_stderr
end
it 'displays error when key is changed' do
Settings.encrypted(smtp_secret_file).write('somevalue')
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(SecureRandom.hex(64))
expect { run_rake_task('gitlab:smtp:secret:edit') }.to output(/Couldn't decrypt .* Perhaps you passed the wrong key?/).to_stderr
end
it 'displays error when write directory does not exist' do
FileUtils.rm_rf(Rails.root.join('tmp/tests/smtpenc'))
expect { run_rake_task('gitlab:smtp:secret:edit') }.to output(/Directory .* does not exist./).to_stderr
end
it 'shows a warning when content is invalid' do
Settings.encrypted(smtp_secret_file).write('somevalue')
expect { run_rake_task('gitlab:smtp:secret:edit') }.to output(/WARNING: Content was not a valid SMTP secret yml file/).to_stdout
value = Settings.encrypted(smtp_secret_file)
expect(value.read).to match(/somevalue/)
end
it 'displays error when $EDITOR is not set' do
stub_env('EDITOR', nil)
expect { run_rake_task('gitlab:smtp:secret:edit') }.to output(/No \$EDITOR specified to open file. Please provide one when running the command/).to_stderr
end
end
describe 'write' do
before do
allow($stdin).to receive(:tty?).and_return(false)
allow($stdin).to receive(:read).and_return('username: foo')
end
it 'creates encrypted file from stdin' do
expect { run_rake_task('gitlab:smtp:secret:write') }.to output(/File encrypted and saved./).to_stdout
expect(File.exist?(smtp_secret_file)).to be true
value = Settings.encrypted(smtp_secret_file)
expect(value.read).to match(/username: foo/)
end
it 'displays error when key does not exist' do
allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil)
expect { run_rake_task('gitlab:smtp:secret:write') }.to output(/Missing encryption key encrypted_settings_key_base./).to_stderr
end
it 'displays error when write directory does not exist' do
FileUtils.rm_rf('tmp/tests/smtpenc/')
expect { run_rake_task('gitlab:smtp:secret:write') }.to output(/Directory .* does not exist./).to_stderr
end
it 'shows a warning when content is invalid' do
Settings.encrypted(smtp_secret_file).write('somevalue')
expect { run_rake_task('gitlab:smtp:secret:edit') }.to output(/WARNING: Content was not a valid SMTP secret yml file/).to_stdout
value = Settings.encrypted(smtp_secret_file)
expect(value.read).to match(/somevalue/)
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment