mod_rails AKA mod_rack AKA mod_passenger AKA mod…

January 27th, 2012 No comments

mod_rails AKA mod_rack AKA mod_passenger AKA mod_works_some_times

Mixing:  Apache 2.x, Ruby on Rails 3.x, Passenger 3.0.9, Fedora Linux (FC 13.)

As always the problems that you encounter may be self-inflicted – in this case I had to ‘turn off’ anything that I thought that I knew about configuring Apache…   The mod_passenger documentation provides many examples  but as I followed those steps I only found errors…  I successfully DUPLICATED following ‘the docs’ to multiple non-working implementations of mod_passenger (Phusion Passenger) using multiple Linux virtual machines – I now dub Passenger mod_passenger_confusion…

I am successfully serving an Empty/New Rails project using a config similar to what is described here.  Of course I would prefer a dynamic environment where I did not need to make any system level/server changes to add a new application – even a test application.

Mod_Rails/Mod_Passenger/Mod_Rack seems to be the answer…

Since I am using RVM (Ruby Version Manager) the module paths are a bit long…

The only way that I could get a simple ‘hello world’ Rack to work was by using the setup below – this would work fine for ONE app but the point is to be able to deploy multiple apps without this manual stuff.

File:  /etc/httpd/conf.d/passenger.conf (Apache 2.x)

I found many, many examples using ‘virtual hosts’ and ALL of them used FQDNs – there is NO REASON to use a ‘real’ FQDN for TESTING – provided that your test system is configured to use the /etc/hosts files for simple DNS resolution, i.e.

127.0.0.1    railsapp3  railsapp3.test
# OR some IP using internal IP address space
192.168.10.143    railsapp3  railsapp3.test

Note that if you are using a proxy like Squid then the above also works on any PC on your local network that uses the proxy since it will use the DNS resolution on the server (at least that is how I configured it…)

Sample Apache (2) config file below:  /etc/httpd/conf.d/passenger.conf

#############
LoadModule passenger_module /usr/local/rvm/gems/some_long_path/mod_passenger.so
PassengerRoot /usr/local/rvm/gems/some_long_path/passenger-3.0.9
PassengerRuby /usr/local/rvm/wrappers/some_long_path/ruby

#############
<VirtualHost *:80>
  ServerName railsapp3.test
 DocumentRoot /var/www/html/rails_apps/hello_world/
 PassengerAppRoot /var/www/html/rails_apps/hello_world/

### Passenger error #2
  RailsBaseURI /hello_world
  RailsBaseURI /app_three
  RailsBaseURI /rack_example2
  RailsBaseURI /rack_example3

  PassengerResolveSymlinksInDocumentRoot  on
  PassengerUser apache
  PassengerGroup apache
  PassengerDefaultUser apache
  PassengerDefaultGroup apache

  <Directory /var/www/html/rails_apps/>
     AllowOverride all
       Options -MultiViews FollowSymLinks
       Allow from all
  </Directory>
</VirtualHost>

The Error Page that I see when I remove ‘hello_world’ from the DocumentRoot and PassengerAppRoot paths:

Ruby on Rails application could not be started

A source file that the application requires, is missing.

  • It is possible that you didn’t upload your application files correctly. Please check whether all your application files are uploaded.
  • A required library may not installed. Please install all libraries that this application requires.

Further information about the error may have been written to the application’s log file. Please check it in order to analyse the problem.

Error message:
no such file to load — /var/www/html/rails_apps/config/environment
Exception class:
LoadError
Application root:
/var/www/html/rails_apps/
Backtrace: (~20 lines or Ruby/Rails code…)

After too much time experimenting and getting non-working results, here is A solution/FIX – simplify:

  1. Create one master Apache configuration file for all Generic Passenger settings and
  2. One configuration file for EACH application using Unique Virtual Host Names (for testing)
  3. Create a unique DNS entry OR an entry in /etc/hosts for as many Test-Virtual-Hosts as needed
  4. This approach does REQUIRE a re-start of Apache (and re-start Squid as well) if you add/remove virtual hosts; however, you should be able to simple replace the contents of any existing application folder to cause semi-dynamic ‘updates’…
######  /etc/httpd/conf.d/passenger.conf | Fedora Apache 2 #####
LoadModule passenger_module /usr/local/rvm/PATH_TO//mod_passenger.so
PassengerRoot /usr/local/rvm/PATH_TO/passenger-3.0.9
PassengerRuby /usr/local/rvm/PATH_TO/ruby
##
### debug ###
PassengerDebugLogFile /var/log/httpd/passdebug.log
PassengerLogLevel 3
###
### other passenger defaults
PassengerUser apache
PassengerGroup apache
PassengerDefaultUser apache
PassengerDefaultGroup apache

For each Virtual-Host/App combo a new file is used, i.e.:   /etc/httpd/conf.d/railsapp3.conf

##### railsapp3.conf | Apache 2 ####
<VirtualHost *:80>
        ServerName railsapp3.test
        ServerAlias railsapp3
RailsEnv development
#RackEnv development
        DocumentRoot /var/www/html/rails_apps/APP_FOLDER/public
</VirtualHost>
#############

The above works fine for an internal Test server, but, of course would require DNS updates for testing via external browsers…  A sample list of /path_to_web_files/www/rails_apps with APP_FOLDER folders and unique Test-Domains:

  1. demo_app |   http://railsapp1
  2. first_app |   http://railsapp2
  3. hello_world  |   http://railsapp3
  4. r3tutorial  |    http://railsapp4
  5. sample_app  |    http://railsapp5
  6. sample_app_3_1  |    http://railsapp6

Note that if you do not set the RailsEnv or RackEnv to ‘development’ then the default of ‘production’ is automatically set; this may cause your application to fail (most likely due to lack of needed database files/data…)  Note that several weeks have passed prior to posting this so there may be new changes/fixes/solutions for the issues discussed here.   As always, your mileage should vary a bit. :)

Share and Enjoy:
  • LinkedIn
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Technorati
  • Live
  • Slashdot
  • Sphinn
  • Mixx
  • Yahoo! Buzz
  • StumbleUpon
  • Facebook
  • MSN Reporter
  • Reddit
  • RSS
  • Add to favorites
  • FriendFeed

WordPress security note – setup-config.php

January 25th, 2012 No comments

Limiting access to WordPress /wp-admin/* tools should be a standard approach; since there are so many installation scenarios this might not always be possible so some WordPress specific mod_security rules (see links below) may be more appropriate.  You may also want to consider some of the free WordPress security plugins.  Additional WordPress specific security-related suggestions/discussion are available on the WordPress web site.

Spider Labs provides several setup-config.php  WordPress specific mod_security rules that may assist in preventing problematic/un-authorized access to a WordPress installation.  The rules should work for generic WordPress installations, however, a simpler approach might include IP address specific and/or GeoIP address specific restrictions – see below for examples.

A more detailed discussion and sample scenarios are provided by TrustWave.

Potential Problem WordPress URIs

  • POST /wp-admin/setup-config.php?step=2 HTTP/1.1
  • GET /wp-admin/install.php HTTP/1.1
  • phpinfo(); included within a theme or plugin, i.e.:  GET /wp-content/themes/default/404.php HTTP/1.1

Note that if you don’t have mod_security then it is also possible to manage these types of issues for WordPress sites by making configuration changes; you can limit access to /wp-admin/ using Apache configuration files (*.conf) and with some limitations, with Apache .htaccess files (the Apache server must be configured to allow certain directives.)  In general, for better performance and security it is best to avoid using .htaccess files and use httpd configuration files instead…  If all of this is a bit too techy then some of the WordPress security plugins may be a good (or additional) alternative (see link above.)

Disabling phpinfo()

I found several web pages on a  number of domains that suggest adding the line below  to your .htaccess file – it DOES NOT currently WORK in .htaccess – perhaps it did in previous versions of PHP… See the PHP 5 manual – disable_functions is only available in the ‘php.ini’ file. (1/2012 – a reminder that you need to test any solution(s) that you find on the Internet – you could be getting stale or inaccurate info – of course include the pages from this domain since change happens…)

  • php_value disable_functions phpinfo ## disable_functions does not work in .htaccess files

Add to your ‘php.ini’ file (global disable) and phpinfo()is disabled after you restart Apache.

  • disable_functions = phpinfo

While there may be cases where using phpinfo() is valid, in general it should NOT be allowed within WordPress themes or plugins since some-evil-bad-guy could use the information to hack into your system…  Note that dis-abling phpinfo() may ‘break’ some themes and/or plugins.

Locating php.ini

If you are not sure where your php.ini file is located you can use a short PHP program on your web site or the shell command shown below. Assuming that your server supports PHP then you can add the php code below to any working HTML file on your server.  I suggest removing the changes once you have the information that you need…

Create a file with the code snippet below OR append to an existing PHP script.

<?php
$inipath = php_ini_loaded_file();

if ($inipath) {
    echo 'Loaded php.ini: ' . $inipath;
} else {
    echo 'A php.ini file is not loaded';
}
?>

Locating your php.ini via a shell commands – output will vary based on OS and configuration:

#php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File:         /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed:      /etc/php.d/bcmath.ini,
/etc/php.d/cups.ini,
/etc/php.d/curl.ini,
/etc/php.d/dom.ini,
/etc/php.d/fileinfo.ini,
/etc/php.d/zip.ini
#php -v
PHP 5.3.6 (cli) (built: Mar 17 2011 21:19:28)
Copyright (c) 1997-2011 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies

 

Apache WordPress Security Configuration Tweaks

Sample  tweak for  *.conf restrictions for /wp-admin/

 1. allow wp-admin with SSL and good IP address
<Location /wp-admin/>
    SSLRequireSSL
    Order deny,allow
    Deny from all
    Allow from A.B.C.D # (Good.Guy.IP.Address )
</Location>
2. allow wp-admin access via good IP address
<Location /wp-admin/>
    Order deny,allow
    Deny from all
    Allow from A.B.C.D # (Good.Guy.IP.Address )
</Location>
3. dis-allow all wp-admin access ## denies and requires SSL
<Location /wp-admin/>
    SSLRequireSSL
    Order deny,allow
    Deny from all
</Location>

Option 1 above is suggested but requires that:

  • your server supports SSL
  • you can provide the appropriate IP address OR
  • you can provide the appropriate GeoIP data (i.e. limit by Country, State, City, Zip Code, etc.)

Using GeoIP information to restrict access & Caveats

  • GeoIP data changes so this requires regular updates
  • GeoIP data is NOT inclusive and may not be accurate so it is best to combine this with other measures
  • mod_geoip & appropriate data are required for server-level use
  • add to Configuration/.htaccess:  SetEnvIf GEOIP_COUNTRY_CODE US AllowCountry
  • add to Configuration/.htaccess:  Allow from env=AllowCountry


Require ‘Good’ GeoIP (i.e. limited in the ‘US’), with SSL and/or good IP address

 <Location /wp-admin/>
    SSLRequireSSL
    SetEnvIf GEOIP_COUNTRY_CODE US AllowCountry
    Order deny,allow
    Deny from all
    Allow from env=AllowCountry A.B.C.D # (Good.Guy.IP.Address )
</Location>

Restricting WordPress Access by File names

If you take this approach then you may need a ‘rule’ for each file and/or a ‘wildcard’ rule (see the WordPress security link above for more examples/suggestions.)

<Files setup-config.php>
        order deny,allow
        deny from all
</Files>

If you take any of these approaches then testing is a really good idea… See related posts for more information on using mod_security, mod_geoip and securing Apache services.

 

Share and Enjoy:
  • LinkedIn
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Technorati
  • Live
  • Slashdot
  • Sphinn
  • Mixx
  • Yahoo! Buzz
  • StumbleUpon
  • Facebook
  • MSN Reporter
  • Reddit
  • RSS
  • Add to favorites
  • FriendFeed

Suggestions for Rails 3 Newbee

December 11th, 2011 No comments

The Joy of Rails

I wrote this list/post as I worked through Rails 3 as a newbee (not new to systems, development – just new to Rails 3.)  I am working through The Ruby on Rails 3 Tutorial and touching on issues/resolutions as I encounter them.  Note that as a Newbee my comments/solutions may not reflect ‘the Rails Way’ of doing things; also note that any solutions that I present  may or may not work for you (best I can tell this is simply part of the Joy of Rails…)  :)

Consider some sort of Development User Sandbox

Sand-boxing development environments (isolating non-production code) is hopefully familiar/common to you.  Sand-boxing your user accounts may be less familiar but it may provide you similar isolation from ‘bad things’…

If you plan on using Online services for serving/storing data/apps etc. then here are a few items that most online tutorials don’t tell you about but they are simple things that you should consider:

  • create unique user_accounts on your local Linux Server specifically when using any online account/service where ‘keys’ are shared between two or more systems, especially for ‘test’/'trial’ services – i.e. at this time I have one GitHub account with two ‘users’ from my Linux system.
  • use unique emails (aliases are fine) for each such account – I have been using email aliases for years – when you are done with the alias you can safely delete it since you only use it for one thing; if you start getting SPAM to any email address you can easily change it without affecting your ‘normal’ email address that you use for sending messages.
  • use unique ssh keys if any are required – i.e. as noted above I use two local Linux accounts with unique SSH keys to work with GitHub projects;  when I am working on a particular project I either login to the needed account on the local system OR I use ‘su – Account_name’ (the ‘-’ is required for this type of use) to ‘become’ the user. While it is possible to use multiple keys with one user account I find that it is simpler to create unique users with unique keys.)

While using the above approach adds some potential complexity it may help insulate you from future issues.  If you are using  a Linux/*nix type operating system then you could simply create a dedicated user for use with Open Source type projects (where you expose your information on a global scale.)  After creating the user on your local machine simply login to the account using your GUI login process.  Opening a terminal using your ‘normal’ login and then using sudo/su is possible but can lead to gotchas like:

  1. login as normal user using the GUI
  2. start a terminal session
  3. use su/sudo to change to a new user_account in the terminal session (i.e.  su – dev_user)
  4. if you now try to start a GUI process it *should* fail unless you have configured your GUI to allow direct access via a second user account (probably a very, very bad idea…)

A Sandbox Virtual Machine – A simpler approach (provided you have adequate hardware)

  1. login as normal user using the GUI
  2. create a dedicated Virtual Machine with a dedicated development user account and all development software/tools installed (with or without GUI support)
  3. start the VM and login as the dedicated development user
  4. limit ‘public projects’ to this dedicated VM

In the book Ruby on Rails Tutorial: Learn Rails by Example Michael Hartl he writes: “Also beware that lots of little things can go wrong….”, and a few sentences later on the same page, “When things like this happen to you, it’s always frustrating, but at least you know that it happens to everyone…“  [ Note that I purchased both the book and video combo product and liked them enough to become an 'affiliate' so clicking the link above AND purchasing help support this site - of course you could also hit the donate button...:) ]  BTW – if you are using the book/videos then you need to review the updates on the site – Chapter 13 covers Rails 3.1 and notes many of the items in this post (and possibly more.)


Rails Touts ‘Test Driven Development

Where is the Test Driven Install?

Start with a ‘clean install’

  • to avoid system-level trouble shooting don’t use a ‘system install’; instead install Rails and related tools as a specific user (while I prefer a ‘system’ install, and that is what I am using, I will guess that you may have fewer ‘version’ related issues if you install as a specific user, especially if you are the only user on the machine…)
  • use rvm – Rails Version Manager – it can help limit the version-type problems that you will encounter (this tool should or something similar should be part of the Rails base install.)
  • consider using a virtual machine just for Rails development (requires a PC/system with adequate computing resources; provides another layer of isolation.)
  • realize that if you use the default ‘settings’ for Rails 3 then EVERY new project will download the latest code from the Internet – this may not be the best approach for real projects… (do you really want to add more potential issues with ‘new code’ in your project?)
  • start with simple projects.

I don’t want to re-install!

  • then expect to spend excessive amounts of fruitless effort searching for a solution (the most likely outcome.)  [I note that the 're-install fix' is currently the standard approach for highly complex systems, i.e. any recent version of the Windows operating system - it is simply faster to start over than it is to figure out what is 'wrong' and resolve...] Search engines will most likely provide many ‘hits’ for your error message and few, if any of those ‘hits’ will contain a real solution/explanation – they may contain work-arounds that worked-for-the-poster who is using OS Version YadaYada with Rails Version XYZ; my experience is that such work-arounds lead to additional issues or the time spent trying them is simply wasted time.
  • re-install…  If that does not ‘fix’ the issue then you will have to dive into the cycle:
  1. search engines – hoping for an ‘exact match’ WITH a solution…
  2. Rails specific forums
  3. Rails specific mailing lists
  4. your Rails ‘network’
  5. Rails books – normally at least a little out-dated within months of being published…

Common Resources for Rails Development

  • git – source code version control; ‘git’ creates a hidden project sub-folder where all of your changes are stored – best if you combine this with some sort of replication to either a local or remote server (i.e. GitHub.Com)
  • github.com – online repository for ‘git managed’ code with ‘free’ storage for Open Source projects
  • Heroku - almost instant ‘publishing’ for your application; great for testing using a ‘free’ account
  • Blueprint is a CSS framework, which aims to cut down on your development time. It gives you a solid foundation to build your project on top of, with an easy-to-use grid, sensible typography, useful plugins, and even a stylesheet for printing.

Ok, you create an account with Heroku, upload and successfully run a few applications and then with your next test application you hit a Heroku 500 Response code:

We’re sorry, but something went wrong.

We’ve been notified about this issue and we’ll take a look at it shortly.

This could be your code or it could be the Heroku Server.  (I noted that no one contacted me about this issue so the error message is generic and Heroku could save YOU some time by improving it…  Sounds like the price of free…)   You can query your Heroku Application logs:

>>heroku logs

2011-11-25T00:02:32+00:00 heroku[router]: GET YOUR_Application_URI.heroku.com/ dyno=web.1 queue=0 wait=0ms service=599ms status=500 bytes=728

When I experienced this I deleted the Heroku App with:

  • heroku destroy # you will be prompted to confirm; then re-create with
  • heroku create   # you should get a new application
  • git push heroku master # now upload
  • heroku rake db:migrate  ## Still getting the 500 error – oops maybe a ‘data issue’?

heroku rake db:migrate
rake aborted!
Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.)
Tasks: TOP => db:migrate => db:load_config

Actually, this is a Heroku ‘confinment’Postgres is required – The Fix:

  • install Postgres on your system as a native application (non Ruby/Rails system level binary)
  • install the ‘pg’ gem
  • make these changes to your Gemfile (for the app being deployed via Heroku; note that Heroku strongly encourages the use of Postgres in both development and ‘production’ to avoid these types of issues…)  In your project ‘Gemfile’, make sure to ‘comment out’ any existing lines for ‘sqlite3′…
###############################
## from Heroku docs - use 'postgres' for production/sqlite for dev
group :production do
  gem 'pg'
end

group :development, :test do
  gem 'sqlite3'
end
###############################
  • bundle install  # make sure that all is up to date
  • rake db:migrate # make sure that your DB is updated
  • heroku rake db:migrate  # send the changes to Heroku
  • try your app now (worked for me)

Using ‘git’

Mr. Hartl’s book/screenscasts frequently use ‘git’ to manage the code.  If you are new to ‘git’ and if you are using his book I suggest naming ‘git commits’ with extended comments that include book chapter numbers, i.e.:

  1. rails new new_project # create a new Rails 3 project
  2. cd new_project # move into the new folder
  3. git init # initialize the folder for use with ‘git’
  4. vi Readme.markdown # create a project description file using your editor of choice (using ‘vi’ in this example)
  5. git status # git should report that there is a new file
  6. git add . # add your changes to the git repo
  7. git commit -am “Starting Chapter 1 – created project Readme” # ‘commit’ your changes with an enhanced comment
  8. git add .  # update the git repo as desired as you work through the chapter
  9. git commit -am “Chapter 1 – section on some_new_topic” # make sense?
  10. git add .  # update the git repo as desired as you work through the chapter
  11. git commit -am “Completed Chapter 1″ # Completed this chapter
  12. git commit -am “Starting Chapter N “
  13. git commit -am “Completed Chapter N” # make sense?

Extended ‘commit comments’ may make it easier when reviewing the project or if you want to ‘rollback’ and re-do a section of the tutorial.   Based on my experience a reasonable approach for working through the tutorial code might be to simply ‘checkout chapters’ as you move along OR checkout the entire project and then ‘rollback’ to the point that you want to work.   During my exploration I frequently created my own issues (via fat-fingers, whoops! moments, missed ‘step #nnn”, etc.) and found that my version of the app did not work due to my new-bee-ness (well, that’s my excuse..)  Soooo, the short story for this is that I will create another post detailing using git with a ‘test project’ in this fashion.

Additional Resources

  • Markdown – text based documentation with minimal ‘tags’ for presentation management – used by GitHub
  • Pandoc – an exceptional tool for converting between mark-up formats (HTML 2 Markdown)
  • Ruby Regular Expression editor/test site – test, experiment, explore, create regular expressions for use in your Ruby Code; also a great way to simply learn about using Regex.

As Ruby on Rails & it’s components Transition you will most likely encounter errors like:

Warnings about deprecations – I am guessing that it is most likely you will see this from ‘generated’ code and it will continue until the ‘code generator’ is updated with the new whatever_was_deprecated OR, until the code simply no longer works and your application will (most likely) ‘break’…  It may also occur from ‘gems’ that need to be updated.

sample_app_3_1 (master)]$ rspec spec/
DEPRECATION WARNING: ActiveRecord::Associations::AssociationCollection is deprecated! Use ActiveRecord::Associations::CollectionProxy instead. (called from <top (required)> at /usr/local/Tutorial/sample_app_3_1/config/environment.rb:5)
….

Finished in 0.49615 seconds
4 examples, 0 failures

In this case I quickly found a simple solution – which I try and it appears to ‘solve’ the warning problem.  After changing the Gemfile I ran bundle install but no changes seem to occur (which probably means that the needed gem is already installed.)


StyleSheets & Images not working with Rails 3.x?

In the 3.1 release of Rails (So, for a small version change a ‘standard’ item has just bee relocated?) it appears that stylesheets should be placed in:

  • app/assets/stylesheets (instead of)
  • public/stylesheets
  • likewise ‘images’ has been moved to app/assets/images

Check the source for the application web page – it will show you where the stylesheet is being pulled from…


Getting many errors when you try to use Annotate?  Try:

  • gem ‘annotate’, ’2.4.1.beta1′ ## update Gemfile, run ‘bundle install’
  • bundle exec annotate ## may be required for command line use

While working on the tutorial I also worked on some related posts:

 

Setting Up Local Resources – possible future posts…

  • using Apache to run/test applications
  • setting  up a local Git repository
  • setting up a local Phusion (Heroku type ‘service’, AKA mod_rails/mod_rack/mod_passenger)

As always, I expect that your experiences will vary a bit (along with your opinions) – which is as it should be.  :)

Share and Enjoy:
  • LinkedIn
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Technorati
  • Live
  • Slashdot
  • Sphinn
  • Mixx
  • Yahoo! Buzz
  • StumbleUpon
  • Facebook
  • MSN Reporter
  • Reddit
  • RSS
  • Add to favorites
  • FriendFeed
________________________________________________
YOUR GeoIP Data | Ip: 38.107.179.223
Continent: NA | Country Code: US | Country Name: United States
Region: CA | State/Region Name: California | City: Glendora
(US only) Area Code: 626 | Postal code/Zip:
Latitude: 34.132099 | Longitude: -117.851097
Note - if using a mobile device your physical location may NOT be accurate...
________________________________________________

Georgia-USA.Com - Web Hosting for Business
____________________________________