Some environmental variables accessible, others not? - ruby-on-rails

I have a rails app and am trying to use an environmental variable (API key) inside of a controller and it is failing. Debugging shows it's value to be nil. Weird thing is that other keys from that file are accessible, so I am not really understanding why. They are all in my secrets.yml file.
I have tried accessing it using both ENV["STRIPE_TEST_SECRET_KEY"] and Rails.application.secrets.stripe_test_secret_key and both come back nil. I get the error:
No API key provided. Set your API key using "Stripe.api_key = <API-KEY>". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support#stripe.com if you have any questions.
using the better errors gem. How do I make these available throughout my app?

You need to set STRIPE_TEST_SECRET_KEY in the environment running the Rails app.
Check out the Choices gem, it makes overriding env vars pretty easy.
You can set the env vars on the CLI in development like this:
$ STRIPE_TEST_SECRET_KEY=abc123 rails s
If you are using Rbenv, you can create a .rbenv-vars file in the root of your project that contains one env var per line like this:
DATABASE_URL=mysql://db_user:db_pass#localhost:3306/dev_db
STRIPE_TEST_SECRET_KEY=abc123
SOME_OTHER_VAR=foo

Related

What is the correct way to use config/credentials in Rails 6? And how do I stop my app from using /tmp/development_secret?

I'm working on a Rails application and I am attempting to organize my secret_key_base and related important secrets (Think API keys, database credentials, etc.)
I am trying to find a way to setup something like the following, under /config
/config
credentials.yml.enc
master.key
/config/credentials
development.yml.enc
development.key
production.yml.enc
production.key
test.yml.enc
test.key
First Question:
Is it that secret_key_base exists in /config/credentials.yml.enc, which is loaded (first?) and then the credentials are loaded for the environment rails is running in? Or should I create a different secret_key_base for each environment?
Second Question:
No matter what I do, when I run in development or test, tmp/development_secret loads first. In addition, whenever I try to access my secrets in development, (Rails.application.secret_key_base) as referenced here: What's the correct way of defining secret_key_base on Rails 6, I run into an issue where I only ever receive nil when looking for secrets I've defined in my development.yml.enc, which I assume is because it's not loading anything in that file, it's going to tmp/development_secret and not finding anything else (Maybe I'm wrong.)
Goals:
Stop tmp/development_secret from being created, and instead access
secrets using the specific .yml.enc file depending on the
environment.
Understand why /config/credentials.yml.enc exists if it doesn't
load in all the environments. If it doesn't, then it isn't clear when it loads.
Why?
Using config/database.yml as an example, I want to store different creds for each environment, but none of them in version control. (I want nobody but a few to have production.) However, I want to access them the exact same way in all of my environments. Not having creds load in production because of an issue with a .yml file will crash my app, so I don't want to load them differently in test/development.
Put together a blog post about this because searching for documentation on this feature is painful. It's a really easy thing because then only the master.key, and production.key would need loaded as ENV variables which is great. (Or possibility just one of them.)
This really should be a simple, out-of-the-box thing, but it's hard to find real documentation on best practices.
I've found the answer, at least the one I'm looking for. You can have your initializer load whatever file you want by overriding the defaults.
config.credentials.content_path = 'config/credentials/development.yml.enc'
config.credentials.key_path = 'config/credentials/development.key'
https://edgeapi.rubyonrails.org/classes/Rails/Application.html

Initializing object within devolopment.rb envirorment using gem within rails mountable engine

Completely lost.
I'm following this sample app tutorial https://www.wepay.com/developer/resources/wefarm-tutorial
which seems like a simple tutorial to follow except I'm building it inside a rails engine. I'm currently attempting to follow the tutorial and initialize the new object.
initialize a new WePay object. add these variables to config/development.rb:
wefarm / config / environments / development.rb
App specific information
CLIENT_ID = 32636
CLIENT_SECRET = "180c800c62"
USE_STAGE = true
WEPAY = WePay.new(CLIENT_ID, CLIENT_SECRET, USE_STAGE)
The issue I think I'm having is the gem is within my core engine allong with user's and the rest of the application and I'm adding these lines of code into the empty shell app. How would I make sure my engine uses this in development I'm also assuming I will come across this issue again when I'm set for production.
In another question a user specified I'm putting this code into the wrong area if I'm using an engine it should be in the initializer folder, but within the documents they just specify putting the code within the config/environments file so where/how exactly do I translate this over to an engine. If it goes into the initializer folder how would I make that file to just include the code specified?
Any help would be amazingly helpful.
Ps. The client Id and secret our just test information
In Rails 4 engine, define the app specific information in secrets.yml
Specifying secrete keys and ids according to environment will solve environment related configuration for keys.
Example :
development:
CLIENT_ID: 123
Make engine configurable
Example in config/initializer/wefarm.rb
Weform.CLIENT_ID = Rails.application.secrets.CLIENT_ID
In lib/engine.rb (engine)
mattr_accessor :CLIENT_ID
Now you can access client_id in engine as WeForm.CLIENT_ID
For more information Rails Engine

Stripe API key missing Rails

We're facing a problem with Stripe API keys. What I've done so far is:
set environment/*.rb to utilise appropriate Stripe keys using constants
created a config/initializers/stripe.rb with the line Stripe.api_key = STRIPE_SECRET
using the rails console, both STRIPE_PUBLIC and STRIPE_SECRET constants are set and visible. STRIPE_PUBLIC => "pk_test_xxxxxxxxx"
However, once these things are in place, making a call to Stripe's API using the browser results in:
Stripe::AuthenticationError in some_controller#some_action
No API key provided. Set your API key using "Stripe.api_key = <API-KEY>". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support#stripe.com if you have any questions.
Using the web-console gem, we can tell that STRIPE_SECRET and STRIPE_PUBLIC are nil in the website. But every time we run rails console we get our keys from our constants.
I fixed my issue. The terminal running rails server had been opened since before the environment variables had been set.
Therefore, running source ~/.bashrc (for me) or using a new terminal worked for me.
Thank you, sincerely, to everyone who tried to help!
I think the issue you are encountering is happening because if the way you are setting the key.
You cannot expect something you set using the rails console to be available to the web application. The Rails console started up as its own unique process that does not share anything with the web process started and accessed by the browser.
If you want the key to be available to the web application try setting it as an environment variable and reading it accordingly in your stripe.rb file
Try restarting the rails server to make these values available to the rails app since the changes were made in the initializers directory.

Setting Test environment variables in rails without putting in source code

I'm using Twilio for an app and on production I set the auth token using heroku's CLI. I'm using sms-spec (https://github.com/monfresh/sms-spec) to test my app's Twilio integration locally. I want to set ENV['TWILIO_AUTH_TOKEN'] to my token in the test environment.
I use guard to auto-run my tests whenever I make changes so I don't want to have to manually set the ENV variable each time I run tests. I also don't want to put the token in my source code for security reasons.
Is there a way I can set the ENV variable for my local test environment such that it is permanent and not in my source? I've spent a few hours researching this and can't seem to find a good explanation of how to do this. Any help is much appreciated :)
Two approaches:
Use a gem like Dotenv (link). This is the approach I use in most of my applications for development. Simply include the gem in your gemfile, bundle install and then store any environment variable settings in a top level file called .env. Restart your rails server and ENV will be automatically loaded. Very easy to use and convenient.
If you are flexible on the ENV part, and you are running Rails 4.1+, you can use config/secrets/yml. This is documented very well in the Rails 4.1 release notes, Section 2.2. So, in your case, you would set it up like so:
development:
twilio_auth_token: verysecretstring
Then, in your initializer, instead of referencing ENV['TWILIO_AUTH_TOKEN'], you would use Rails.application.secrets.twilio_auth_token. I haven't tried this myself, but it is on my list as I would rather use native Rails functionality than a separate gem.
Of course, any files which contain your secrets needs to be safeguarded carefully. At a minimum, make sure you include in .gitignore so that your secrets do not find their way into your code respository.

Adding urls api keys in environment variable in ruby

I have a url that I am using in one of the controllers. Is there a better place to put this url? The url uses an API key and I was wondering if there is a better place to add this url and/or api key such that its not added in the controller class code and ergo more editable? If i add it as an environment variable or anything else how do i access it from my controller class? thank you. ITS A RUBY AND RAILS PROJECT
Using environment variables might be a good idea if you want to keep things like API keys and passwords out of your source code. Accessing them from within your code is done with the ENV object:
my_api_key = ENV['MY_API_KEY']
To use this technique, you need to set up the variables in your environment before launching your app, and how you do this depends on your local setup, and will likely also vary between development and production.
In development, you can simply set the environment vars in your shell, e.g. with bash:
$ export MY_API_KEY=foobar123abc
$ rails s
Now rails will start and have access to this environment variable. You can also set variables for just a single command:
$ MY_API_KEY=foobar123abc rails s
Depending on what the sevice/api is, you could set some of them to default development/test values in config/environments/development.rb (or test.rb):
ENV['MY_API_KEY'] = 'non_secret_api_key_that_can_be_shared_around'
Setting up environment variables in production will depend on how you're deploying your app. Phusion have an article on using environment variables in Passenger if your using that. There's also a useful article on using environment variables with Heroku which is worth a read even if you're not using them for deployment.
You can add it to application.rb file as
config.service {
:api_key => 'api_key'
}
Or better yet, add it to development.rb and production.rb files so that you can test it better.
You can access this api_key from controller like
Rails.application.config.service[:api_key]

Resources