Loading the endpoint configuration from the system environment - environment-variables

I have the following endpoint initialization in lib/flashcards_web/endpoint.ex:
#doc """
Callback invoked for dynamically configuring the endpoint.
It receives the endpoint configuration and checks if
configuration should be loaded from the system environment.
"""
def init(_key, config) do
if config[:load_from_system_env] do
port = System.get_env("PORT") || raise "expected the PORT environment variable to be set"
jwt_token_ttl_minutes =
"USER_SESSION_MINUTES"
|> System.get_env
|> String.to_integer
|| raise "expected the USER_SESSION_MINUTES environment variable to be set"
config =
config
|> Keyword.put(:http, [:inet6, port: port])
|> Keyword.put(:jwt_token_ttl_minutes, jwt_token_ttl_minutes)
{:ok, config}
else
{:ok, config}
end
end
and the required load_from_system_env: true line in config/dev.exs:
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :flashcards, FlashcardsWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin",
cd: Path.expand("../assets", __DIR__)]],
load_from_system_env: true
However when running
PORT=4000 USER_SESSION_MINUTES=1 iex -S mix phx.server
I get:
iex(1)> Application.get_env(:flashcards, FlashcardsWeb.Endpoint)[:jwt_token_ttl_minutes]
nil
Am I missing something here?

Found the solution to access the dynamic endpoint configuration.
The docs mention that a config/2 function is automatically generated at the endpoint.
The dynamic endpoint configuration can therefore be accessed as follows:
iex(2)> FlashcardsWeb.Endpoint.config(:jwt_token_ttl_minutes)
1

Related

Winlogbeat setup error: x509 certificate is valid for <ip>, not <same ip>

I'm trying to send logs from Winlogbeat to my ELK stack.
I installed my ELK stack with docker and configured TLS on it.
I did everything according to the official guide and it worked for my host.
However, when copying the same winlogbeat directory to my Event Collector server, it did not work (all files are the same including the yml file).
When trying to run the "winlogbeat.exe setup -e" I got the following error: 'error connecting to elasticsearch at "https://elastic-host:9200" Get "https://elastic-host:9200" Winlogbeat setup error: x509 certificate is valid for elastic-host ip, not elastic-host ip' (same ips). The CA is already added to the trusted root certificates. Everything is configured the same as on the host, on the host it works, on the server it doesn't. (the ELK server and the EVC are in the same segment so there shouldn't be any firewall drops)
My .yml (same file on host and EVC server):
on the host it works without the ssl as well and the traffic is still encrypted due to the TLS that I configured on the docker cluster. So I'm not sure the ssl configuration is needed (but I wanted to include them in case they are needed).
# This file is an example configuration file highlighting only the most common
# options. The winlogbeat.reference.yml file from the same directory contains
# all the supported options with more comments. You can use it as a reference.
#
# You can find the full configuration reference here:
# https://www.elastic.co/guide/en/beats/winlogbeat/index.html
# ======================== Winlogbeat specific options =========================
# event_logs specifies a list of event logs to monitor as well as any
# accompanying options. The YAML data type of event_logs is a list of
# dictionaries.
#
# The supported keys are name (required), tags, fields, fields_under_root,
# forwarded, ignore_older, level, event_id, provider, and include_xml. Please
# visit the documentation for the complete details of each option.
# https://go.es.io/WinlogbeatConfig
winlogbeat.event_logs:
- name: Application
ignore_older: 72h
- name: System
- name: Security
processors:
- script:
lang: javascript
id: security
file: ${path.home}/module/security/config/winlogbeat-security.js
- name: Microsoft-Windows-Sysmon/Operational
processors:
- script:
lang: javascript
id: sysmon
file: ${path.home}/module/sysmon/config/winlogbeat-sysmon.js
- name: Windows PowerShell
event_id: 400, 403, 600, 800
processors:
- script:
lang: javascript
id: powershell
file: ${path.home}/module/powershell/config/winlogbeat-powershell.js
- name: Microsoft-Windows-PowerShell/Operational
event_id: 4103, 4104, 4105, 4106
processors:
- script:
lang: javascript
id: powershell
file: ${path.home}/module/powershell/config/winlogbeat-powershell.js
- name: ForwardedEvents
tags: [forwarded]
processors:
- script:
when.equals.winlog.channel: Security
lang: javascript
id: security
file: ${path.home}/module/security/config/winlogbeat-security.js
- script:
when.equals.winlog.channel: Microsoft-Windows-Sysmon/Operational
lang: javascript
id: sysmon
file: ${path.home}/module/sysmon/config/winlogbeat-sysmon.js
- script:
when.equals.winlog.channel: Windows PowerShell
lang: javascript
id: powershell
file: ${path.home}/module/powershell/config/winlogbeat-powershell.js
- script:
when.equals.winlog.channel: Microsoft-Windows-PowerShell/Operational
lang: javascript
id: powershell
file: ${path.home}/module/powershell/config/winlogbeat-powershell.js
# ====================== Elasticsearch template settings =======================
setup.template.settings:
index.number_of_shards: 1
#index.codec: best_compression
#_source.enabled: false
# ================================== General ===================================
# The name of the shipper that publishes the network data. It can be used to group
# all the transactions sent by a single shipper in the web interface.
#name:
# The tags of the shipper are included in their own field with each
# transaction published.
#tags: ["service-X", "web-tier"]
# Optional fields that you can specify to add additional information to the
# output.
#fields:
# env: staging
# ================================= Dashboards =================================
# These settings control loading the sample dashboards to the Kibana index. Loading
# the dashboards is disabled by default and can be enabled either by setting the
# options here or by using the `setup` command.
#setup.dashboards.enabled: false
# The URL from where to download the dashboards archive. By default this URL
# has a value which is computed based on the Beat name and version. For released
# versions, this URL points to the dashboard archive on the artifacts.elastic.co
# website.
#setup.dashboards.url:
# =================================== Kibana ===================================
# Starting with Beats version 6.0.0, the dashboards are loaded via the Kibana API.
# This requires a Kibana endpoint configuration.
setup.kibana:
# Kibana Host
# Scheme and port can be left out and will be set to the default (http and 5601)
# In case you specify and additional path, the scheme is required: http://localhost:5601/path
# IPv6 addresses should always be defined as: https://[2001:db8::1]:5601
host: "192.168.101.129:5601"
protocol: https
username: "elastic"
password: "passwd"
setup.kibana.ssl.enabled: true
setup.kibana.ssl.certificate_authorities: ["C:\\Program Files\\Winlogbeat\\ca.crt"]
setup.kibana.ssl.certificate: "C:\\Program Files\\Winlogbeat\\winlogbeat.crt"
setup.kibana.ssl.key: "C:\\Program Files\\Winlogbeat\\winlogbeat.key"
# Kibana Space ID
# ID of the Kibana Space into which the dashboards should be loaded. By default,
# the Default Space will be used.
#space.id:
# =============================== Elastic Cloud ================================
# These settings simplify using Winlogbeat with the Elastic Cloud (https://cloud.elastic.co/).
# The cloud.id setting overwrites the `output.elasticsearch.hosts` and
# `setup.kibana.host` options.
# You can find the `cloud.id` in the Elastic Cloud web UI.
#cloud.id:
# The cloud.auth setting overwrites the `output.elasticsearch.username` and
# `output.elasticsearch.password` settings. The format is `<user>:<pass>`.
#cloud.auth:
# ================================== Outputs ===================================
# Configure what output to use when sending the data collected by the beat.
# ---------------------------- Elasticsearch Output ----------------------------
output.elasticsearch:
# Array of hosts to connect to.
hosts: ["192.168.101.129:9200"]
username: "elastic"
password: "passwd"
# Protocol - either `http` (default) or `https`.
protocol: "https"
output.elasticsearch.ssl.certificate_authorities: ["C:\\Program Files\\Winlogbeat\\ca.crt"]
output.elasticsearch.ssl.certificate: "C:\\Program Files\\Winlogbeat\\winlogbeat.crt"
output.elasticsearch.ssl.key: "C:\\Program Files\\Winlogbeat\\winlogbeat.key"
# Authentication credentials - either API key or username/password.
#api_key: "id:api_key"
# ------------------------------ Logstash Output -------------------------------
#output.logstash:
# The Logstash hosts
#hosts: ["localhost:5044"]
# Optional SSL. By default is off.
# List of root certificates for HTTPS server verifications
#ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]
# Certificate for SSL client authentication
#ssl.certificate: "/etc/pki/client/cert.pem"
# Client Certificate Key
#ssl.key: "/etc/pki/client/cert.key"
# ================================= Processors =================================
processors:
- add_host_metadata:
when.not.contains.tags: forwarded
- add_cloud_metadata: ~
# ================================== Logging ===================================
# Sets log level. The default log level is info.
# Available log levels are: error, warning, info, debug
#logging.level: debug
# At debug level, you can selectively enable logging only for some components.
# To enable all selectors use ["*"]. Examples of other selectors are "beat",
# "publish", "service".
#logging.selectors: ["*"]
# ============================= X-Pack Monitoring ==============================
# Winlogbeat can export internal metrics to a central Elasticsearch monitoring
# cluster. This requires xpack monitoring to be enabled in Elasticsearch. The
# reporting is disabled by default.
# Set to true to enable the monitoring reporter.
#monitoring.enabled: false
# Sets the UUID of the Elasticsearch cluster under which monitoring data for this
# Winlogbeat instance will appear in the Stack Monitoring UI. If output.elasticsearch
# is enabled, the UUID is derived from the Elasticsearch cluster referenced by output.elasticsearch.
#monitoring.cluster_uuid:
# Uncomment to send the metrics to Elasticsearch. Most settings from the
# Elasticsearch output are accepted here as well.
# Note that the settings should point to your Elasticsearch *monitoring* cluster.
# Any setting that is not set is automatically inherited from the Elasticsearch
# output configuration, so if you have the Elasticsearch output configured such
# that it is pointing to your Elasticsearch monitoring cluster, you can simply
# uncomment the following line.
#monitoring.elasticsearch:
# ============================== Instrumentation ===============================
# Instrumentation support for the winlogbeat.
#instrumentation:
# Set to true to enable instrumentation of winlogbeat.
#enabled: false
# Environment in which winlogbeat is running on (eg: staging, production, etc.)
#environment: ""
# APM Server hosts to report instrumentation results to.
#hosts:
# - http://localhost:8200
# API Key for the APM Server(s).
# If api_key is set then secret_token will be ignored.
#api_key:
# Secret token for the APM Server(s).
#secret_token:
# ================================= Migration ==================================
# This allows to enable 6.7 migration aliases
#migration.6_to_7.enabled: true
In your output, you need to specify ssl.verification_mode: certificate.
For your example, it looks like it is the Kibana output that has a certificate specified on it:
setup.kibana.ssl.enabled: true
setup.kibana.ssl.certificate_authorities: ["C:\\Program Files\\Winlogbeat\\ca.crt"]
setup.kibana.ssl.certificate: "C:\\Program Files\\Winlogbeat\\winlogbeat.crt"
setup.kibana.ssl.key: "C:\\Program Files\\Winlogbeat\\winlogbeat.key"
setup.kibana.ssl.verification_mode: certificate
Older versions of winlogbeat will need ssl.verification_mode: none instead.
See SSL/TLS configuration documentation at https://www.elastic.co/guide/en/beats/winlogbeat/current/configuration-ssl.html

Rails: system process won't start in rails server, but will in rails console

I want to start a ngrok process when server starts. To achieve this, I coded a ngrok.rb lib and I call it within an initializer
app/lib/ngrok.rb
require "singleton"
class Ngrok
include Singleton
attr_accessor :api_url, :front_url
def start
if is_running?
return fetch_urls
end
authenticate
started = system("ngrok start --all -log=stdout > #{ENV['APP_ROOT']}/log/ngrok.log &")
system("sleep 1")
if !started
return { api: nil, front: nil }
end
urls = fetch_urls
sync_urls(urls["api_url"], urls["front_url"])
return urls
end
def sync_urls(api_url, front_url)
NgrokSyncJob.perform_later(api_url, front_url)
end
def is_running?
return system("ps aux | grep ngrok")
end
def restart
stop
return start
end
def stop
return system("pkill ngrok")
end
def authenticate
has_file = system("ls ~/.ngrok2/ngrok.yml")
if has_file
return true
else
file_created = system("ngrok authtoken #{ENV['NGROK_TOKEN']}")
if file_created
return system("cat " + ENV['APP_ROOT'] + '/essentials/ngrok/example.yml >> ~/.ngrok2/ngrok.yml')
else
return false
end
end
end
def fetch_urls
logfile = ENV['APP_ROOT'] + '/log/ngrok.log'
file = File.open logfile
text = file.read
api_url = nil
front_url = nil
text.split("\n").each do |line|
next if !line.include?("url=") || !line.include?("https")
if line.split("name=")[1].split(" addr=")[0] == "ncommerce-api"
api_url = line.split("url=")[1]
elsif line.split("name=")[1].split(" addr=")[0] == "ncommerce"
front_url = line.split("url=")[1]
end
end
file.close
self.api_url = api_url
self.front_url = front_url
res = {}
res["api_url"] = api_url
res["front_url"] = front_url
return res
end
end
config/initializers/app-init.rb
module AppModule
class Application < Rails::Application
config.after_initialize do
puts "XXXXXXXXXXXXXXXXXXXXXXX"
Ngrok.instance.start
puts "XXXXXXXXXXXXXXXXXXXXXXX"
end
end
end
When I type rails serve, here is a sample of the output
So we know for sure my initializer is being called, but when I look at rails console if it's running, it's not!
But when I type Ngrok.instance.start in rails console, here's the output:
And it starts!
So, my question is: WHY ON EARTH is system("ngrok start --all -log=stdout > #{ENV['APP_ROOT']}/log/ngrok.log &") NOT working on rails serve, but it is on rails console?
UPDATE
If I use 'byebug' within ngrok.rb and use rails serve, when I exit byebug with "continue", the ngrok process is created and works
You're creating an orphaned process in the way that you use system() to start the ngrok process in the background:
system("ngrok start --all -log=stdout > #{ENV['APP_ROOT']}/log/ngrok.log &")
Note the & at the end of the commandline.
I'd need more details about your runtime environment to tell precisely which system policy kills the orphaned ngrok process right after starting it (which OS? if Linux, is it based on systemd? how do you start rails server, from a terminal or as a system service?).
But what's happening is this:
system() starts an instance of /bin/sh to interpret the commandline
/bin/sh starts the ngrok process in the background and terminates
ngrok is now "orphaned", meaning that its parent process /bin/sh is terminated, so that the ngrok process can't be wait(2)ed for
depending on the environment, the terminating /bin/sh may kill ngrok with a SIGHUP signal
or the OS re-parents ngrok, normally to the init-process (but this depends)
When you use the rails console or byebug, in both cases you're entering an interactive environment, which prepares "process groups", "session ids" and "controlling terminals" in a way suitable for interactive execution. These properties are inherited by child processes, like ngrok. This influences system policies regarding the handling of the orphaned background process.
When ngrok is started from rails server, these properties will be different (depending on the way rails server is started).
Here's a nice article about some of the OS mechanisms that might be involved: https://www.jstorimer.com/blogs/workingwithcode/7766093-daemon-processes-in-ruby
You would probably have better success by using Ruby's Process.spawn to start the background process, in combination with Process.detach in your case. This would avoid orphaning the ngrok process.

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

How do I populate my Elixir config from runtime variables? [duplicate]

Following the setup instructions, I have the following Ecto configuration in my config/config.exs file :
config :my_app, MyApp.Repo,
adapter: Ecto.Adapters.Postgres,
url: "postgresql://postgres#localhost/myrepo",
size: 20
If my understanding is correct, the config.exs is evaluated at compile-time.
Is there a way to do this configuration step at runtime ?
This is for an app which will be distributed as a compiled binary (via exrm). The end-user should be able to customize the database url and pool size via flags or environment variables, not by editing sys.config
Loading from the system is possible by using {:system, "KEY" } e.g.:
config :my_app Repo
url: {:system, "DATABASE_URL" },
size: {:system, "DATABASE_POOL_SIZE" }
instead
config :my_app, Repo,
url: "ecto://postgres:postgres#localhost/ecto_simple",
size: 20
In this case you set up Ecto to use the system properties. Of course, a user has to configure it.
Using {:system, "KEY"} has been deprecated in Ecto v3.
Instead, you are advised to define an init/2 callback function within your Repo module to set runtime config:
def init(_type, config) do
config = Keyword.put(config, :url, System.get_env("DATABASE_URL"))
{:ok, config}
end
Using a runtime init/2 function allows configuration to be read from more than just environment variables.

How to disable "Cannot Render Console from..." 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!

Resources