How to disable "Cannot Render Console from..." on Rails - ruby-on-rails

I'm using Ubuntu/vagrant as my development environment.
I'm getting these messages on rails console:
Started GET "/assets/home-fcec5b5a277ac7c20cc9f45a209a3bcd.js?body=1" for 10.0.2.2 at 2015-04-02 15:48:31 +0000
Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Is it possible to disable those "cannot render..." messages or allow them in any way?

You need to specifically allow the 10.0.2.2 network space in the Web Console config.
So you'll want something like this:
class Application < Rails::Application
config.web_console.permissions = '10.0.2.2'
end
Read here for more information.
As pointed out by pguardiario, this wants to go into config/environments/development.rb rather than config/application.rb so it is only applied in your development environment.

You can whitelist single IP's or whole networks.
Say you want to share your console with 192.168.0.100. You can do this:
class Application < Rails::Application
config.web_console.whitelisted_ips = '192.168.0.100'
end
If you want to whitelist the whole private network, you can do:
class Application < Rails::Application
config.web_console.whitelisted_ips = '192.168.0.0/16'
end
If you don't wanna see this message anymore, set this option to false:
class Application < Rails::Application
config.web_console.whiny_requests = false
end
Be careful what you wish for, 'cause you might just get it all
This is probably only for development purposes so you might prefer to place it under config/environments/development.rb instead of config/application.rb.

Hardcoding an IP into a configuration file isn't good. What about other devs? What if the ip changes?
Docker-related config should not leak into the rails app whenever possible. That's why you should use env vars in the config/environments/development.rb file:
class Application < Rails::Application
# Check if we use Docker to allow docker ip through web-console
if ENV['DOCKERIZED'] == 'true'
config.web_console.whitelisted_ips = ENV['DOCKER_HOST_IP']
end
end
You should set correct env vars in a .env file, not tracked into version control.
In docker-compose.yml you can inject env vars from this file with env_file:
app:
build: .
ports:
- "3000:3000"
volumes:
- .:/app
links:
- db
environment:
- DOCKERIZED=true
env_file:
- ".env"
Based on the feebdack received in comments, we can also build a solution without environment variables:
class Application < Rails::Application
# Check if we use Docker to allow docker ip through web-console
if File.file?('/.dockerenv') == true
host_ip = `/sbin/ip route|awk '/default/ { print $3 }'`.strip
config.web_console.whitelisted_ips << host_ip
end
end
I'll leave the solutions with env var for learning purposes.

Auto discovery within your config/development.rb
config.web_console.whitelisted_ips = Socket.ip_address_list.reduce([]) do |res, addrinfo|
addrinfo.ipv4? ? res << IPAddr.new(addrinfo.ip_address).mask(24) : res
end
Of course might need to add
require 'socket'
require 'ipaddr'
Within your file.

Anyone on any of my private networks is welcome.
I run in a docker container and I don't care which network it wants to use this week.
config/environments/development.rb add line
config.web_console.whitelisted_ips = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16']

For development environment: Detect if it's docker, then determine the IP address and whitelist it
# config/environments/development.rb
require 'socket'
require 'ipaddr'
Rails.application.configure do
...
# When inside a docker container
if File.file?('/.dockerenv')
# Whitelist docker ip for web console
# Cannot render console from 172.27.0.1! Allowed networks: 127.0.0.1
Socket.ip_address_list.each do |addrinfo|
next unless addrinfo.ipv4?
next if addrinfo.ip_address == "127.0.0.1" # Already whitelisted
ip = IPAddr.new(addrinfo.ip_address).mask(24)
Logger.new(STDOUT).info "Adding #{ip.inspect} to config.web_console.whitelisted_ips"
config.web_console.whitelisted_ips << ip
end
end
end
For me this prints the following and the warning goes away 🎉
Adding 172.27.0.0 to config.web_console.whitelisted_ips
Adding 172.18.0.0 to config.web_console.whitelisted_ips
My solution was to combine
the answer from user2481743 ⭐️ https://stackoverflow.com/a/42142563/2037928
the comment from jottr ⭐️ How to disable "Cannot Render Console from..." on Rails

If you run your site locally (on the host) it generally works out, since 127.0.0.1 is always permitted. But if you're going to put your site into a container (not in production, locally), you might want to add this into config/environments/development.rb:
require 'socket'
require 'ipaddr'
Rails.application.configure do
...
config.web_console.permissions = Socket.getifaddrs
.select { |ifa| ifa.addr.ipv4_private? }
.map { |ifa| IPAddr.new(ifa.addr.ip_address + '/' + ifa.netmask.ip_address) }
...
end
P.S. Most of the time you want it to whine (don't want to do config.web_console.whiny_requests = false). Because it might mean you're running web-console in production (which you shouldn't do).

For me, whitelisted_ips didn't seem to work in a new project. The Readme states the corresponding configuration entry is supposed to be permissions now:
Rails.application.configure do
config.web_console.permissions = '192.168.0.0/16'
end
https://github.com/rails/web-console/blob/master/README.markdown

If you want to stop seeing this error message you can add this line in development.rb
config.web_console.whiny_requests = false

Note that only the last 'config.web_console.whitelisted_ips' will be used. So
config.web_console.whitelisted_ips = '10.0.2.2'
config.web_console.whitelisted_ips = '192.168.0.0/16'
will only whitelist 192.168.0.0/16, not 10.0.2.2.
Instead, use:
config.web_console.whitelisted_ips = ['10.0.2.2', '192.168.0.0/16']

class Application < Rails::Application
config.web_console.whitelisted_ips = %w( 0.0.0.0/0 ::/0 )
end

If you are using Docker most likely you don't want neither to introduce new ENV variables nor to hardcode your specific IP address.
Instead you may want to check that you are in Docker using /proc/1/cgroup, and to allow your host IP (both for web_console and better_errors). Add to your config/environments/development.rb
# https://stackoverflow.com/a/20012536/4862360
if File.read('/proc/1/cgroup').include?('docker')
# https://stackoverflow.com/a/24716645/4862360
host_ip = `/sbin/ip route|awk '/default/ { print $3 }'`.strip
BetterErrors::Middleware.allow_ip!(host_ip) if defined?(BetterErrors::Middleware)
config.web_console.whitelisted_ips << host_ip
end

I just want to add this because my own mistake caused me to get the same error.
I was missing this from the controller
load_and_authorize_resource except: [:payment_webhook]
Basically I was using cancancan to place authorization on that route, which was causing a 404 to be returned. I saw the message and assumed the two were related, when in fact they were not
Cannot render console from xxxxxx Allowed networks: xxxxx
So if you are getting an error message, it's possible that it has nothing to do with the Cannot render console from xxxxxx Allowed networks: xxxxx you see - look for other problems!

Related

DB Ownership process error running phoenix test in containerized elixir 1.6.1

I have an umbrella project compose by:
gateway - Phoenix application
core - business model layer notifications a dedicated app for delivering sms, email, etc… users
user management, role system, and authentication.
The three components are connected via AMQP, so they can send and receive messages between them.
We are using Docker, and drone.io hosted on google cloud’s kubernetes engine. So, what is happening is that randomly the application raises the following exception while running my tests:
{\"status\":\"error\",\"message\":\"%DBConnection.OwnershipError{message: \\\"cannot find ownership process for #PID<0.716.0>.\\\\n\\\\nWhen using ownership, you must manage connections in one\\\\nof the four ways:\\\\n\\\\n* By explicitly checking out a connection\\\\n* By explicitly allowing a spawned process\\\\n* By running the pool in shared mode\\\\n* By using :caller option with allowed process\\\\n\\\\nThe first two options require every new process to explicitly\\\\ncheck a connection out or be allowed by calling checkout or\\\\nallow respectively.\\\\n\\\\nThe third option requires a {:shared, pid} mode to be set.\\\\nIf using shared mode in tests, make sure your tests are not\\\\nasync.\\\\n\\\\nThe fourth option requires [caller: pid] to be used when\\\\nchecking out a connection from the pool. The caller process\\\\nshould already be allowed on a connection.\\\\n\\\\nIf you are reading this error, it means you have not done one\\\\nof the steps above or that the owner process has crashed.\\\\n\\\\nSee Ecto.Adapters.SQL.Sandbox docs for more information.\\\"}\",\"code\":0}"
It’s a Json since we exchange amqp messages in our tests, for instance:
# Given the module FindUserByEmail
def Users.Services.FindUserByEmail do
use GenAMQP.Server, event: "find_user_by_email", conn_name:
Application.get_env(:gen_amqp, :conn_name)
alias User.Repo
alias User.Models.User, as: UserModel
def execute(payload) do
%{ "email" => email } = Poison.decode!(payload)
resp =
case Repo.get_by(UserModel, email: email) do
%UserModel{} = user -> %{status: :ok, response: user}
nil -> ErrorHelper.err(2011)
true -> ErrorHelper.err(2012)
{:error, %Ecto.Changeset{} = changeset} -> ViewHelper.translate_errors(changeset)
end
{:reply, Poison.encode!(resp)}
end
end
# and the test
defmodule Users.Services.FindUserByEmailTest do
use User.ModelCase
alias GenAMQP.Client
def execute(payload) do
resp = Client.call_with_conn(#conn_name, "find_user_by_email", payload)
data = Poison.decode!(resp, keys: :atoms)
assert data.status == "ok"
end
end
Following details my .drone.yaml file:
pipeline:
unit-tests:
image: bitwalker/alpine-elixir-phoenix:1.6.1
environment:
RABBITCONN: amqp://user:pass#localhost:0000/unit_testing
DATABASE_URL: ecto://username:password#postgres/testing
commands:
- mix local.hex --force && mix local.rebar --force
- mix deps.get
- mix compile --force
- mix test
mix.exs file in every app contains the following aliases
defp aliases do
[
"test": ["ecto.create", "ecto.migrate", "test"]
]
end
All ours model_case files contain this configuration:
setup tags do
:ok = Sandbox.checkout(User.Repo)
unless tags[:async] do
Sandbox.mode(User.Repo, {:shared, self()})
end
:ok
end
How can I debug this? it only occurs while testing code inside the container. Would the issue be related to container’s resources?
Any tip or hint would be appreciated.
Try setting onwership_timeout and timeout to a large numbers in your config/tests.exs
config :app_name, User.Repo,
adapter: Ecto.Adapters.Postgres,
username: ...,
password: ...,
database: ...,
hostname: ...,
pool: Ecto.Adapters.SQL.Sandbox,
timeout: 120_000, # i think the default is 5000
pool_timeout: 120_000,
ownership_timeout: 120_000 #i think the default is 5000

Rails correctly configure host/port with Cucumber/Capybara on CircleCI

I have problems figuring out the good way to set up the host/port for test on CircleCI
EDIT 2 - Requirements :
Rails app running locally on TEST_PORT (if available in ENV variable) or on default port 3000
I have session based tests, so magically switching from localhost to 127.0.0.1 will cause test failures
On my CircleCI environment I mapped host www.example.com to 127.0.0.1 and I'd like Capybara to connect to that website instead of directly localhost/127.0.0.1
On my CircleCI environment the port 80 is reserved so the rails app HAS to run on a different port (like 3042)
Some integration tests need to connect to remote website (Sorry no VCR yet) www.example-remote.com on port 80
Previously my test suite was running fine with localhost:3042 but then I realized I had problems with tests that used session : the rails app itself started on localhost but then emails were sent to the 127.0.0.1 address which caused session-based tests to fail
I changed the following config
# feature/env.rb
Capybara.server_port = ENV['TEST_PORT'] || 3042
Rails.application.routes.default_url_options[:port] = Capybara.server_port
if ENV['CIRCLECI']
Capybara.default_host = 'http://www.example.com/'
end
# configuration/test.rb
config.action_mailer.default_url_options = {
host: (ENV['CIRCLECI'].present? ? 'www.example.com' : '127.0.0.1'),
port: ENV['TEST_PORT'] || 3042
}
# circle.yml
machine:
hosts:
www.example.com: 127.0.0.1
But now I'm getting weird email urls being generated like http://www.example.com/:3042/xxx
Did someone manage a working configuration on circleCI using custom host name ?
EDIT
Capybara 2.13
Rails 5.0
Cucumber 2.4
CircleCI 1.x
Capybara.default_host only affects tests using the rack_test driver (and only if Capybara.app_host isn't set). It shouldn't have the trailing '/' on it, and it already defaults to 'http://www.example.com' so your setting of it should be unnecessary.
If what you're trying to do is make all your tests (JS and non-JS) go to 'http://www.example.com' by default then you should be able to do either
Capybara.server_host = 'www.example.com'
or
Capybara.app_host = 'http://www.example.com'
Capybara.always_include_port = true
My new config which seems to work for session-based tests but fails for remote websites (it tries to reach the remote server with the same TEST_PORT I have defined (eg click on email with http://www.example-remote.com/some_path --> Capybara connects to http://www.example-remote.com:TEST_PORT/some_path)
# features/env.rb
# If test port specified, use it
if ENV['TEST_PORT'].present?
Capybara.server_port = ENV['TEST_PORT']
elsif ActionMailer::Base.default_url_options[:port].try do |port|
Capybara.server_port = port
end
else
Rails.logger.warn 'Capybara server port could not be inferred'
end
# Note that Capybara needs either an IP or a URL with http://
# Most TEST_HOST env variable will only include domain name
def set_capybara_host
host = [
ENV['TEST_HOST'],
ActionMailer::Base.default_url_options[:host]
].detect(&:present?)
if host.present?
# If the host is an IP, Capybara.app_host = IP will crash so do nothing
return if host =~ /^[\d\.]+/
# If hostname starts with http(s)
if host =~ %r(^(?:https?\:\/\/)|(?:\d+))
# OK
elsif Capybara.server_port == 443
host = 'https://' + host
else
host = 'http://' + host
end
puts "Attempting to set Capybara host to #{host}"
Capybara.app_host = host
else
Rails.logger.warn 'Capybara server host could not be inferred'
end
end
set_capybara_host
# config/environments/test.rb
Capybara.always_include_port = true
config.action_mailer.default_url_options = {
host: (ENV['TEST_HOST'].present? ? ENV['TEST_HOST'] : '127.0.0.1'),
port: (ENV['TEST_PORT'].present? ? ENV['TEST_PORT'] : 3042)
}

How do I have different envirenment variable values in Rails?

This is how I run rails console command:
COMPANY=b2b RAILS_ENV=development DEPLOY_ENV=localhost rails console
Instead I want to run only rails console command by setting these variables internally. How do I do that?
I saw some answers and made the config/company.yml file:
development:
COMPANY: b2b
DEPLOY_ENV: localhost
production:
COMPANY: b2c
DEPLOY_ENV: xyz.com
And I wrote the following config/initializers/company.rb file:
COMPANY_CONFIG = YAML.load_file("#{::Rails.root}/config/company.yml")[::Rails.env]
How do I access these variables in some helper/controller? I didn't understand how to do that? How do I set these ENV variables after running only rails console or rails server without passing the extra environment variable shown above?
You can't set environment variables in yaml file this difference things. Use dotenv gem for manage environment variables.
Read first Environment Variables
But have dirty hack. You can create ENV variable when rails loaded
add this code to before_configuration in config/application.rb:
config.before_configuration do
env_file = File.join(Rails.root, 'config', 'company.yml') # Find yml file
YAML.load(File.open(env_file)).each do |key, value| # Open file
ENV[key.to_s] = value # Set value to ENV
end if File.exists?(env_file) # If file exists
end
And now you can access to env variables from yml file anywhere in app.
I do not test this but i think this work.
This work.
Some info
You can create these settings variables in the config/initializers/application.rb file:
company_settings_path = Rails.root.join('config', 'company.yml')
COMPANY_CONFIG = { development: { company: :default, deploy_env: :none_yet } }
COMPANY_CONFIG = YAML::load(File.open(company_settings_path)) if File.exists?(company_settings_path)
COMPANY_CONFIG = COMPANY_CONFIG.with_indifferent_access
And then access them like this:
# controller
def show
if COMPANY_CONFIG[:company] == 'b2c'
# your logic
else
# other logic
end
end
You can acces the constant COMPANY_CONFIG everywhere in your app (models, controllers, views, helpers) the same way I used below.

Location of Config files in Adhearsion and FreeSWITCH

I'm getting on well, hooking up the ruby engine Adhearsion with the telephony engine FreeSwitch. However, the instructions tell me to give some config files a once over.
Specifically
config.punchblock.platform
and the permissions set on the directory
/var/punchblock/record
Could anyone please tell me where these are located?
Full instructions here:
http://adhearsion.com/docs/getting-started/freeswitch
config.punchblock.platform
is in config/adhearsion.rb in your Adhearsion app.
and
/var/punchblock/record
is where asterisk is running.
Changing file, folder permissions
Yes, that's what I did for database connection.
Adhearsion.config do |config|
config.adhearsion_activerecord do |db|
db.username = "user"
db.password = "password"
db.database = "database"
db.adapter = "mysql"
db.host = "localhost"
db.port = 3306
end
end
#Centralized way to specify any Adhearsion platform or plugin configuration
#To update a plugin configuration you can write either:
# Option 1
Adhearsion.config.<plugin-name> do |config|
config.<key> = <value>
end
# Option 2
Adhearsion.config do |config|
config.<plugin-name>.<key> = <value>
end

Rails/Passenger sub URI error

I am attempting to deploy a Rails 3.0.0 application to a sub URI using passenger 2.2.15.
I believe I've made the correct RailsBaseURI changes to my http.conf , have symlinked the sub URI to the public directory of my app and added the following line of code to environments/production.rb:
config.action_controller.relative_url_root = "/sub_uri"
I've done this several times pre-rails3.0.0. That said, the app won't launch. It fails with the following Passenger error:
Error Message: wrong number of arguments(1 for 0)
Exception class: ArgumentError
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.0/lib/action_controller/railtie.rb 54 in `relative_url_root='
Is there an incompatibility between passenger 2.2.15 and rails 3.0.0 that affects sub URI's?
Any help sorting out this error is greatly appreciated.
The setter is depreciated, it's nowhere to be found in actionpack/lib/action_controller/railtie.rb.
As seen here (actionpack/lib/action_controller/depreciated/base.rb):
module ActionController
class Base
# Deprecated methods. Wrap them in a module so they can be overwritten by plugins
# (like the verify method.)
module DeprecatedBehavior #:nodoc:
def relative_url_root
ActiveSupport::Deprecation.warn "ActionController::Base.relative_url_root is ineffective. " <<
"Please stop using it.", caller
end
def relative_url_root=
ActiveSupport::Deprecation.warn "ActionController::Base.relative_url_root= is ineffective. " <<
"Please stop using it.", caller
end
end
end
end
In actionpack/lib/action_controller/metal/compatibility.rb you can see it's setter is an ENV variable:
self.config.relative_url_root = ENV['RAILS_RELATIVE_URL_ROOT']
So you need to set the ENV variable: RAILS_RELATIVE_URL_ROOT="/sub_uri"
To set the environment variable add:
SetEnv RAILS_RELATIVE_URL_ROOT /sub_uri
To the VirtualHost section (or similar) of your apache config then make sure it's being read by restarting apache and passenger.
cd <your_rails_project>
sudo apache2ctl graceful
touch tmp/restart

Resources