12 Security Checks to Perform Before Launching Your Rails App

In today’s interconnected world, software security is paramount. With the rise in cyber threats and the potential for data breaches, it’s crucial to ensure that your Rails application is fortified against vulnerabilities before releasing it into the wild.

Neglecting security checks can lead to devastating consequences, tarnishing your reputation and putting sensitive user data at risk.

The possible threats could be hijacking user accounts, manipulation of access control, accessing sensitive data & doctoring with garbage contents. You should act proactively to protect your valuable information.

In this comprehensive guide, we’ll walk you through the essential security checks you must perform after Rails app development and before launching your Rails app.

Here you go with some useful security tips which you cannot ignore. Courtsey, Ruby on Rails Security Guide.

  • Don’t trust logged in users (Authentication != Authorization)

    • Always check whether the current logged in user is allowed to perform operation like create, update, delete and view.
    • Devise, a library which handles authentication, to verify that you can only get to the destroy action if you’re logged in. However, Devise does not handle authorization.
    • Apart from authentication authorization must be checked prior to allow any data sensitive operation.
  • Mass assignments vulnerability. (Use attr_accessible in your models!)

    • ‘Mass Assignment’ is the name Rails has given to the act of constructing your object with a parameters hash. Using “mass assignment” that you can assign multiple values to attributes via a single assignment operator.
    • A ‘params hash’ can contain anything, so protect all sensitive attributes from re-assignment. The best way to do this is by disabling mass assignment using ‘attr_accessible’ (or attr_protected) in your models.
  • Prevent your attribute being changed from outside with attr_readonly

    • Remember to disable updating protected attributes.
    • Using ‘attr_readonly’ declaration of ActiveRecord allows the attribute to be set on create, but never edited on update.
  • SQL Injection(SQLi)

    • SQL injection (SQLi) is a code injection technique in which a user can manipulate a database in an unintended manner. Consequences of SQL injection vulnerabilities range from data leaks, to authentication bypass, to root access on a database server.
    • To get rid, never include user submitted strings in database queries. Check all model scopes and find conditions that include ‘params’ or interpolated strings.

    Instead of using such unsafe code

Post.all(:conditions => "title = #{params[:title]}")

You can have safer, simpler code like

Post.all(:conditions => {:title => params[:title]})
  • Prevent executable files from being uploaded

    • We should always distrust the user/browser provided information, to make decisions on a file’s mime/content type.
    • Validate the content type of all attachments, and place uploaded files in protected directories or on another server/service e.g. S3/Cloudfront.
    • Content-types can easily faked, so check the file extensions and be sure to disable your web server from executing scripts in the upload directory.
    • Also, beware of plugins creating or writing in temp directories during file upload operation.They may create files or directories from user submitted ‘params’ without checking the file path.
  • Avoid Redirection

    • Avoid using redirects to user supplied URLs like redirect_to(params[:some_parameter]).
    • When the arguments for a redirect comes from ‘params’, you are open to redirect to unintended URLs.
  • Security updates and patches of Gems and Plugins

    • Always check your dependencies for security updates and patches.
    • If possible subscribe to the GitHub issues list (or any mailing list) of the gems or plugins you are using.
    • Always specify the version to avoid undesirable breaks to your code.
  • Passwords in the database

    • Never ever store passwords in the database as clear text.
    • Encourage strong alphanumeric passwords and if necessary follow other strong password practices (like multiple failed logins, password expiry/reset etc.)
    • Keep encrypted password in your database like the one devise generates.
  • Make non-ActionController methods private

    • Check whether the methods you have declared in a controller is accessible to the public.
    • Change accordingly in your ‘routes’ so that it is private and inaccessible to the public.
  • Include CSRF token in all form submissions

    • Include ‘csrf_meta_tag’ helper in the HTML head tag in Rails 3.
    • Enable ‘protect_from_forgery’ and use form helpers to include the Rails authenticity token in all form submissions.
  • Cross-Site Scripting (XSS)

    • Cross-site scripting attacks occur when malicious scripts are injected into web pages and executed in users’ browsers. 
    • Employ content security policies (CSP), sanitize user-generated content, and use proper escaping methods to prevent this attack vector.
  • Cross-Site Request Forgery (CSRF)

    • CSRF attacks exploit the trust a website has in a user’s browser by tricking it into executing unwanted actions on the site. 
    • Protect against this threat by implementing CSRF tokens in your forms and utilizing the built-in Rails mechanisms.

SEE ALSO: Security Patch to deal authentication bypass for RoR

Conclusion

The security of your Rails application is not a feature that can be fixed on at the last moment. It should be an integral part of your development process from day one.

By conducting comprehensive security checks before releasing your app, you demonstrate your commitment to safeguarding user data and maintaining the trust of your audience.

In a digital landscape where threats are ever-evolving, a proactive approach to security is not just a best practice—it’s a necessity.

Rails app developers always maintain a checklist of security measures to take before releasing the app. Top Rails app development companies have even more stringent security measures and follow them from the inception of the app development.

Related Questions

Q1: What is the first step in ensuring the security of a Rails app before its release?

A1: The first step is to perform a thorough code review and security assessment of your application. This involves analyzing the codebase for potential vulnerabilities, checking for proper implementation of authentication and authorization, and reviewing the usage of third-party libraries and dependencies.

Q2: How can I prevent SQL injection attacks in my Rails app?

A2: To prevent SQL injection attacks, you should use parameterized queries or an ORM (Object-Relational Mapping) framework like ActiveRecord. Avoid constructing SQL queries using string concatenation and ensure that user inputs are properly sanitized before being used in queries.

Q3: What measures can I take to protect against Cross-Site Scripting (XSS) attacks in my Rails app?

A3: To protect against XSS attacks, implement Content Security Policies (CSP) to restrict the sources of executable content, sanitize user-generated inputs to prevent the injection of malicious scripts, and use proper output escaping methods, such as using the h helper, when displaying dynamic content.

Q4: How do I handle secure session management in my Rails app?

A4: Secure session management involves setting appropriate session expiration times, using secure and HTTP-only cookies, and ensuring proper handling of session logout upon user inactivity. Rails provides mechanisms like protect_from_forgery and the session helper to help with these aspects.

Q5: Why is it important to update third-party dependencies in my Rails app?

A5: Third-party libraries and gems often contain vulnerabilities that can be exploited by attackers. Regularly updating and patching these dependencies is crucial to address known security issues. You can use tools like Bundler Audit to identify and mitigate potential risks associated with third-party code.

 

Unveiling FeedZirra: Simplifying Feed Parsing in Your Rails Application

What is a Feed?

A feed is a data format which is used to provide frequent updates and latest contents to the users. A feed has no particular type; it could be news, latest technology, game, gadgets, sports etc. These feeds can be easily parsed into your Rails application to make it more useful for the users. The feed is build up with XML and has particular format type.

What is Feedzirra?

“Feedzirra” on the other hand is a feed library built on Ruby that is designed to get and update a number of feeds as fast as possible. This includes using “libcurl-multi” through the “curb” gem for faster http gets, and “libxml” through “nokogiri” and “sax-machine” for faster parsing.

Suppose you need to add some updated information to your Rails application from other feed site like ‘feedburner’, in such cases you can easily work it out by using the gem “feedzirra”.

Here are the steps to use ‘feedzirra’ in your Rails application.

Step-1

Add the gem ‘feedzirra’ in to your gem file.

[sourcecode language=”plain”]gem ‘feedzirra'[/sourcecode]

Run ‘bundle install’ to install the gem along with its dependencies.

Step-2

Modify your controller where you are fetching the feeds.

[sourcecode language=”plain”]require ‘feedzirra'[/sourcecode]

Step-3

Now, write the following code in your method in order to parse feeds from an external site.

[sourcecode language=”plain”]feed =Feedzirra::Feed.fetch_and_parse("http://feeds.feedburner.com/TechCrunch/gaming")
@entry = feed.entries
[/sourcecode]

Note: Here we are parsing the feeds from ‘feedburne’r site with updated information on gaming news.

Step-4

Now, open your view section and write the following code snippet to display the information regarding the feeds.

[sourcecode language=”plain”]<ul>
<%@entry.each do |t|%>
<li>
<%= link_to "#{t.title}", "#{t.url}",:target => "_blank" %>
<%=t.author%>
<%=t.content%>
<%=t.published%>
<%=t.categories%>
</li>
<%end%>
</ul>
[/sourcecode]

Note: The above code will display the feed title, author name, content, published date and category type. Clicking the feed title, will launch a new tab in browser and display the detail information of that feed.

Step-5

You can also fetch multiple feeds by writing the following code.

[sourcecode language=”plain”]feed_urls = ["http://feeds.feedburner.com/PaulDixExplainsNothing", "http://feeds.feedburner.com/trottercashion"]
feeds = Feedzirra::Feed.fetch_and_parse(feed_urls)
[/sourcecode]

Conclusion:

The FeedZirra gem empowers Rails developers to seamlessly integrate feed parsing capabilities into their applications. 

Are you looking for a Ruby on Rails developer

Contact Us

Whether you’re building a news aggregator, a blog reader, or a content recommendation system, FeedZirra simplifies the process of retrieving and presenting timely content from various sources. 

By harnessing the power of FeedZirra, you can enhance user engagement, keep your app’s content fresh, and deliver a more dynamic user experience.

Related Questions

Q1: What is the FeedZirra gem, and how does it simplify feed parsing in Rails applications?

The FeedZirra gem is a powerful tool in the Ruby ecosystem that provides a user-friendly way to parse RSS and Atom feeds. It abstracts the complexities of handling different feed formats, making it easier for developers to extract and utilize the content they need within their Rails apps.

Q2: How can I integrate the FeedZirra gem into my Rails application for parsing feeds?

To integrate the FeedZirra gem into your Rails app, start by adding it to your Gemfile with the following line: gem ‘feedzirra’. After running bundle install, you can fetch and parse feeds using the Feedzirra::Feed.fetch_and_parse method. This allows you to access the feed’s entries (articles) and display them in your app.

Q3: What are some of the advanced features offered by the FeedZirra gem for feed parsing in Rails?

The FeedZirra gem provides several advanced features, including access to various properties of feed entries such as publication date, author, summary, and content. It also offers automatic HTML content sanitization to ensure safe rendering. Additionally, you can implement caching to reduce the load on feed sources and optimize performance.

Q4: How does the FeedZirra gem benefit developers when integrating feed parsing into their Rails applications?

The FeedZirra gem brings several benefits to developers, including streamlined efficiency by handling the intricacies of feed parsing. It supports multiple feed formats (RSS and Atom), making it compatible with a wide range of sources. The gem’s simple API is designed for ease of use, catering to developers of various skill levels. Moreover, it provides customization options to tailor parsed feed content to suit your app’s design and requirements.

Q5: Can the FeedZirra gem be used to enhance user engagement and content freshness in Rails apps?

Absolutely. By utilizing the FeedZirra gem to parse feeds, you can enhance user engagement by providing fresh and relevant content from various sources. Whether you’re building a news aggregator, a blog reader, or a content recommendation system, integrating feed parsing into your Rails app with FeedZirra helps create a dynamic user experience that keeps users informed and engaged.

4 Simple Steps To Implement “Delayed Job” In Rails

Here in this article, I going to tell you the best way to implement “delayed job” in rails

“delayed_job” is a ruby gem used to execute tasks as a background process in Rails environment, increasing page rendering speed.

Delayed::Job (or DJ) allows you to move jobs into the background for asynchronous processing.

Why you need a background process and is it really that important!

Let’s consider a scenario where a mailing application needs to send emails to a huge list of recipients. In such cases it is obvious that the processing time is too long, annoying the users.

Here are some of key points to consider:

  • Incredibly quick & easy to get rolling
  • No addition to your “stack”, runs just fine with Active Record
  • Good choice for beginners while migrating code from foreground to the background

Hence, it’s only wise to move the long running tasks as a background process by using “delayed_job” gem.

Detailed steps to integrate delayed job in a Rails application

Step# 1

  • Add gem to the Gemfile
  • “delayed_job” supports multiple back-ends for storing the job queue
  • To use “delayed_job” with Active Record, use gem ‘delayed_job_active_record’
  • To use “delayed_job” with Mongoid, use gem ‘delayed_job_mongoid’

Example

/Gemfile.rb

  • gem ‘delayed_job_active_record’, ‘4.0.3’
  • Run “bundle install” to install the “delayed_job” gem

Step# 2

  • Generate the related file for the Job run
  • Generate related files required to run the background job by running the following command
    • rails g delayed_job:active_record

It adds following files to the application

  • A Script named “delayed_job” inside “/bin” folder to run the jobs which are in queue.
  • Migration file to create a table to store the job with other information such as priority, attempts, handler, last_error, run_at, locked_at, failed_at, locked_by, queue.

Run the migration file by using the following command

  • rails db:migrate

Set the queue_adapter in config/application.rb

  • config.active_job.queue_adapter = :delayed_job

If you are using the protected_attributes gem, it must appear before delayed_job in your gemfile. If your jobs are failing with:

  • Setup Delayed::Job config in an initializer (config/initializers/delayed_job_config.rb)
    • Delayed::Worker.destroy_failed_jobs = false
    • Delayed::Worker.sleep_delay = 60
    • Delayed::Worker.max_attempts = 3
    • Delayed::Worker.max_run_time = 5.minutes
    • Delayed::Worker.read_ahead = 10
    • Delayed::Worker.default_queue_name = ‘default’
    • Delayed::Worker.delay_jobs = !Rails.env.test?
    • Delayed::Worker.raise_signal_exceptions = :term
    • Delayed::Worker.logger = Logger.new(File.join(Rails.root, ‘log’, ‘delayed_job.log’))

Step# 3

  • Replace script/delayed_job with bin/delayed_job
  • Start up the jobs process

There are two ways to do this.

  • If application is in development mode, we would use the below rake task instead.
    • rake jobs:work
  • If application is in production mode, then it is preferred to use the “delayed_job” script. This demonizes the job process and allows multiple background processes to be spawned.

To use this, pursue the following steps

  • Add gem “daemons” to your Gemfile
  • Run bundle install
  • Make sure you’ve run rails generate delayed_job
  • If you want to just run all available jobs and exit you can use rake jobs:workoff
  • Work off queues by setting the QUEUE or QUEUES environment variable.
    • QUEUE=tracking rake jobs:work
    • QUEUES=mailers,tasks rake jobs:work

Step# 4

  • Add task to run in background
  • In Controller just call .delay.method(params) on any object and it will be processed in the background.

Example:

UsersController before adding to background job

[code language=”html”]
class UsersController < ApplicationController
def send_email
User.find_each(is_subscribed: true) do |user|
NewsMailer.newsletter_mail(user).deliver
flash[:notice] = "Mail delivered"
redirect_to root_path
end
end
end
[/code]

 
UsersController after adding to background job

[code language=”html”]
class UsersController < ApplicationController
def send_email
User.find_each(is_subscribed: true) do |user|
# add .delay method to add it to background process. In case of mail sending remove the .deliver method to make it work.
NewsMailer.delay.newsletter_mail(user)
flash[:notice] = "Mail delivered"
redirect_to root_path
end
end
end
[/code]

Advantages of implementing above steps:

  • No more waiting for a response, after clicking a link to do a big stuff.
  • Just call .delay.method(params) on any object and it processes in the background.
  • Job objects are serialized to yaml and stored in the delayed_jobs table, so they can be restored by the job runner later.
  • It automatically retries on failure. If a method throws an exception it’s caught and the method reruns later. The method retries up to 25 times at increasingly longer intervals until it passes.
  • “delayed_job” gem maintains log by creating a log file “/log/delayed_job.log”

I am sure this article will give you a clear idea about the way to implement “delayed job” in rails. You can share your thoughts with comments if I have missed anything or if you want to know more.

Do you work on or use Ruby on Rails? Let’s Discuss!

Top Reasons To Bring RoR Development On Board

ror411-123

Rails is an innovation in development framework.  It encompasses all the necessary elements to boost a web application’s performance. This framework is designed to address agile development and deliver productivity as well as flexibility to RoR developers. Developed using Ruby programming language, it has transformed the world of web development through its practical approach.

Ruby on Rails is built upon two programming philosophies

  • “Convention over Configuration”: Developers only need to write codes for the irregular or unconventional aspects of the web application.
  • “Don’t Repeat Yourself”: The data is stored in definite place. It saves time and reduces code

Advantages of Ruby on Rails

  • Faster Development: Rails framework enables the developers to write concise and clear syntax and produces fewer codes than its competitors. Therefore it requires less time to code and generates fewer errors. On the other hand it facilitates the programmers to maintain much less code. It is also enabled to integrate numerous tools to automate repetitive tasks such as managing database errors, creating forms etc. it simplifies development process because the language is lightweight and easily readable, almost like the natural language.
  • Increases productivity: Rails framework is specifically featured to reduce the development aspects of applications, instead leveraging creativity and uniqueness of the web application. It empowers productivity by eliminating repetitive programming codes.
  • Assists development of creative interfaces: Rails includes numerous integrations to enable developers in creating rich, intriguing user interfaces. Integrated JavaScript framework is easier to activate and features elements like apparition progressive, drag & drop and many more to ease the designing aspects of the application.
  • Model View Controller design pattern: Rails is developed on MVC architecture that separates the development logics from the presentation layer. It provides a well-structured application to the developers and the code is maintained in a logical and coherent manner.  It encourages abstraction in the application and enables the team to work on separate modules without depending on each other. It focuses on the features rather than minute details. Rails framework delivers ease of project development, conciseness and faster deployment of application.

Rails Development makes web app development easier because it involves less coding while implementing new changes and updates into the development process. It enables the organizations to meet all the business requirements within the budget and schedule.

Collecting Contacts Using Cardmagic-Contacts Pplug-in in Rails 2.3.8

Rails3

Cardmagic-Contacts is a rails plug-in which provides an interface to fetch contact list information from various email providers including Hotmail, AOL, Gmail, Plaxo, Yahoo and many more.

This example narrates how to extract contact list using Rails 2.3.8 and cardmagic-contacts plug-in

Step#1

  • Download the plug-in by running the command below to store the plug-in in the folder “vendor/plug-ins”

Windows

ruby script/plugin install git://github.com/cardmagic/contacts

Linux

ruby script/plugin http://github.com/cardmagic/contacts

Step#2

  • Write down the following code on the top of the controller class
require 'contacts'

Step#3

  • Pass the required gmail/yahoo/hotmail/AOL login & password from view
<div>
 
<div style="margin-left:25px;" >Invite <img src="../images/yahoo.JPG">Yahoo
 
Friends </div>
 
<div style="margin-left:25px;">Yahoo Email: <input type="text" name="email"
 
id="yahoo_email_id"></div>
<div style="margin-left:25px;">Password:   <input type="password"
 
name="email"  id="yahoo_pwd_id"></div>
 
<div style="margin-left:122px;margin-top:20px;"><input type="button"
 
value="Login" name="btn_submit" id="btn_submit" ></div>
 
</div>

Step#4

  • Create an action to fetch the list of contacts for a specific email id

def grab_contacts #Grab gmail contacts @gmail_contacts=Contacts::Gmail.new(login, password).contacts #or @gmail_contacts=Contacts.new(:gmail, login, password).contacts #Grab yahoo contacts @yahoo_contacts = Contacts::Yahoo.new(login, password).contacts #or @yahoo_contacts = Contacts.new(:yahoo, login, password).contacts #Grab hotmail contacts @hotmail_contacts =Contacts::Hotmail.new(login, password).contacts #or @hotmail_contacts = Contacts.new(:hotmail, login, password).contacts end

Step#5

  • Here is also alternate method to get the contacts by providing  email_id and password
any_mail = Contacts.guess(login, password).contacts

The “Contacts.guess” method will automatically concatenate the entire
address book from each of the successful logins. If the login and password is
working with multiple email accounts then it will grab the contacts from all accounts.

Step#6

  • Display the friends list in your view page
<table>
<th>
<td >Friends Name</td>
<td >Friends Email</td>
</th>
<tr>
<% @gmail_contacts.each do |contact| %>
<td><%=contact[0]%></td>
<td><%=contact[1]%></td>
<% end %>
</tr>
</table>

How To Implement Event Calendar In Rails App

Event calendar is a way to show multiple, overlapping events across calendar days and rows. This is an interface to add events, edit events, & destroy event. In Rails there is a gem/plugin “event_calendar” to implement it just like Google calendar.

The following steps demonstrate the implementation of event_calendar in both Rails 2.3.x and Rails3.x environment.

Step#1 –

Installing the gem/plugin

  • In rails 2.3.x

Install the required plugin from below path

script/plugin install git://github.com/elevation/event_calendar.git

Generate the necessary static file and example

script/generate event_calendar
  • In rails 3.x

Install the required gems

gem 'event-calendar', :require => 'event_calendar'

Run “bundle install

You can also use as a Plugin, to install plugin

rails plugin install git://github.com/elevation/event_calendar.git

Generate the necessary static file for the event calendar

rails generate event_calendar

Step#2

Include the necessary style sheet & java-script into your layout/view

<%= stylesheet_link_tag "dialog","fullcalendar","jquery-ui","style" %>
<%= javascript_include_tag "jrails1/fullcalendar.js","jrails1/jquery-
ui.js","jrails1/gcal.js","jrails1/jrails.js","jrails1/jquery.validate.js"%>

Step#3

Create a migration file to add necessary columns as follows

class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.string :name
t.datetime :start_at
t.datetime :end_at
t.timestamps
end
end
def self.down
drop_table :events
end
end

Step#4

Add the necessary paths to the “config/routes” file

  • In Rails 2.3.x
map.calendar '/calendar/:year/:month', :controller => 'calendar', :action => 'index',
 
:requirements => {:year => /d{4}/, :month => /d{1,2}/}, :year => nil, :month => nil
  • In Rails3.x
match '/calendar(/:year(/:month))' => 'calendar#index', :as => :calendar, :constraints => {:year => /d{4}/, :month => /d{1,2}/}

Step#5

Change the Event model to add the calendar as follows

class Event < ActiveRecord::Base
has_event_calendar
end

Step#6

Modify the Calendar controller as follows

class CalendarController < ApplicationController
def index
@month = (params[:month] || Time.zone.now.month).to_i
@year = (params[:year] || Time.zone.now.year).to_i
@shown_month = Date.civil(@year, @month)
@event_strips = Event.event_strips_for_month(@shown_month)
end
end

Step#7

You can also override the events method in helpers/calendar_helper.rb

module CalendarHelper
def month_link(month_date)
link_to(I18n.localize(month_date, :format => "%B"), {:month => month_date.month, :year => month_date.year})
end
# custom options for this calendar
def event_calendar_options
{
:year => @year,
:month => @month,
:event_strips => @event_strips,
:month_name_text => I18n.localize(@shown_month, :format => "%B %Y"),
:previous_month_text => "<< " + month_link(@shown_month.prev_month),
:next_month_text => month_link(@shown_month.next_month) + " >>"
}
end
def event_calendar
calendar event_calendar_options do |args|
event = args[:event]
%(<a href="/events/#{event.id}" title="#{h(event.name)}">#{h(event.name)}</a>)
end
end
end

Step#8

Add the following code to display the calendar in the view file

<%= event_calendar %>

See Also: Security Checks you must do before Rails App release

I hope it helps you. Planning anything in Ruby on Rails? Get in touch with Andolasoft experts. Feel free to give your valuable feedback.