Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions docs/Access-Control-Lists.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
Access Control Lists (ACLs) are the main tool Rails::Auth provides for AuthZ. ACLs use a set of route-by-route [[matchers]] to control access to particular resources.

Rails::Auth encourages the use of YAML files for storing ACL definitions, although the use of YAML is not mandatory and the corresponding object structure output from `YAML.load` can be passed in instead. The following is an example of an ACL definition in YAML:

```yaml
---
- resources:
- method: ALL
path: /foo/bar/.*
allow_x509_subject:
ou: ponycopter
allow_claims:
groups: ["example"]
- resources:
- method: ALL
path: /_admin/?.*
allow_claims:
groups: ["admins"]
- resources:
- method: GET
path: /internal/frobnobs/.*
allow_x509_subject:
ou: frobnobber
- resources:
- method: GET
path: /
allow_all: true
```

An ACL consists of a list of guard expressions, each of which contains a list of resources and a set of [[matchers]] which can authorize access to those resources. Access will be authorized if *any* of the matchers for a given resource are a match (i.e. matchers have "or"-like behavior, not "and"-like behavior). Requiring more than one credential to access a resource is not supported directly, but can be accomplished by having credential-extracting middleware check for credentials from previous middleware before adding new credentials to the Rack environment.

Resources are defined by the following constraints:

* **method**: The requested HTTP method, or `"ALL"` to allow any method
* **path**: A regular expression to match the path. `\A` and `\z` are added by default to the beginning and end of the regex to ensure the entire path and not a substring is matched.
* **host** (optional): a regular expression to match the `Host:` header passed by the client. Useful if your app services traffic for more than one hostname and you'd like to restrict ACLs by host.

The following [[matchers]] are built-in and always available:

* **allow_all**: (options: `true` or `false`) always allow requests to the
given resources (so long as `true` is passed as the option)

Rails::Auth also ships with [[matchers]] for [[X.509]] certificates.
29 changes: 29 additions & 0 deletions docs/Comparison-With-Other-Libraries.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
Rails::Auth was primarily intended for use in environments with the following:

* [Microservices]: Rails::Auth is primarily intended to support environments with many services written as Rails apps which need to make authenticated requests to each other. Square uses Rails::Auth in an environment where we have many Rails microservices (and microservices written in other languages) authenticating to each other with [[X.509]] certificates.
* [Claims-Based Identity]: Rails::Auth is designed to work in conjunction with a central [Single Sign-On] (SSO) system which issues credentials that provide user identities. Rails::Auth does not ship with a specific implementation of an SSO system, but makes it easy to integrate with existing ones.

Below is a comparison of how Rails::Auth relates to the existing landscape of Rails AuthN and AuthZ libraries. These are grouped into two different categories: libraries Rails::Auth replaces, and libraries with which
Rails::Auth can be used in a complementary fashion.

## Replaces:

* [Warden]: Uses a single "opinionated" Rack middleware providing user-centric authentication and methods that allow controllers to imperatively interrogate the authentication context for authorization purposes. By comparison Rails::Auth is not prescriptive and much more flexible about credential types (supporting credentials for both user and service clients) and uses declarative authorization policies in the form of ACLs.

* [Devise]: A mature, flexible, expansive framework primarily intended for user authentication. Some of the same caveats as Warden apply, however Devise provides a framework for modeling users within a Rails app along with common authentication flows, making it somewhat orthogonal to what Rails::Auth provides. Rails::Auth is designed to easily support [claims-based identity] systems where user identity is outsourced to a separate microservice.

## Complements:

* [Pundit]: Domain object-centric fine-grained authorization using clean object-oriented APIs. Pundit makes authorization decisions around particular objects based on policy objects and contexts. Rails::Auth's credentials can be used as a powerful policy context for Pundit.

* [CanCanCan]: a continuation of the popular CanCan AuthZ library after a period of neglect. Uses a more DSL-like approach to AuthZ than Pundit, but provides many facilities similar to Pundit for domain object-centric
AuthZ.

[Warden]: https://github.com/hassox/warden/wiki
[Devise]: https://github.com/plataformatec/devise
[Pundit]: https://github.com/elabs/pundit
[CanCanCan]: https://github.com/CanCanCommunity/cancancan

[microservices]: http://martinfowler.com/articles/microservices.html
[claims-based identity]: https://en.wikipedia.org/wiki/Claims-based_identity
[single sign-on]: https://en.wikipedia.org/wiki/Single_sign-on
37 changes: 37 additions & 0 deletions docs/Design-Overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
Rails::Auth makes use of multiple, independent, single-purpose middleware
classes to handle specific types of AuthN/AuthZ.

## AuthN

Rails::Auth ships with the following AuthN middleware:

* `Rails::Auth::X509::Middleware`: authenticates [[X.509]] certificates obtained
from the Rack environment.

The goal of Rails::Auth's AuthN middleware is to authenticate *credentials*
taken from the Rack environment and place objects representing them under
the `"rails-auth.credentials"` key within the Rack environment for use by
subsequent AuthN or AuthZ middleware. The built-in support is for X.509
client certificates, but other middleware could handle authentication of
cookies or (OAuth) bearer credentials.

The intended usage is to have multiple AuthN middlewares that are capable
of extracting different types of credentials, but also allowing AuthZ
middleware to apply a single policy to all of them. It's also possible to
chain AuthN middleware together such that one credential obtained earlier
in the middleware stack is used to authenticate another (for e.g.
[channel-bound cookies]).

[channel-bound cookies]: http://www.browserauth.net/channel-bound-cookies

## AuthZ

Rails::Auth ships with one primary AuthZ middleware:

* `Rails::Auth::ACL::Middleware`: support for [[Access Control Lists]] (ACLs).

ACLs let you write a single, declarative policy for authorization in your application. ACLs are pluggable and let you write a single policy which can authorize access using different types of credentials.

ACLs are a declarative approach to authorization, consolidating policies into a single file that can be easily audited by a security team without deep understanding of the many eccentricities of Rails. These policies
provide coarse-grained authorization based on routes (as matched by regexes) and the credentials extracted by the AuthN middleware. However, the do not provide AuthZ which includes specific domain objects, or
policies around them. For that we suggest using a library like [Pundit](https://github.com/elabs/pundit).
15 changes: 15 additions & 0 deletions docs/Error-Handling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Rails::Auth includes two different middlewares for rendering error responses: one for debugging, and one intended for production environments which renders a static 403 page (or corresponding JSON response).

## Debug Page

The `Rails::Auth::ErrorPage::DebugMiddleware` provides a rich inspector for why access was denied:

![Debug Page](https://github.com/square/rails-auth/blob/master/images/debug_error_page.png?raw=true)

This page is enabled automatically in the development environment for Rails apps. It can also be enabled in production by passing the `error_page: :debug` option to `Rails::Auth::ConfigBuilder.production`. See [[Rails Usage]] for more information.

## Static Page

The `Rails::Auth::ErrorPage::Middleware` renders a static HTML page and/or JSON response in the event of an authorization failure.

This middleware is used by default in the production environment, and defaults to rendering `public/403.html`. The location of the page can be overridden using the `error_page:` option and passing a `Pathname` or `String` to the file's location. ERB is not presently supported. See [[Rails Usage]] for more information.
15 changes: 15 additions & 0 deletions docs/Home.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
## Intro

* [[Design Overview]]: an overview of Rails::Auth's middleware-based design
* [[Comparison With Other Libraries]]: How Rails::Auth compares to other Rails/Rack auth libraries/frameworks

## Usage

* [[Rails Usage]]: how to add Rails::Auth to a Rails app
* [[Rack Usage]]: how to use Rails::Auth's middleware outside of a Rails app
* [[Access Control Lists]]: how to define policy for what actions are allowed
* [[Matchers]]: how to make access control decisions based on credentials
* [[X.509]]: how to authorize requests using X.509 client certificates
* [[Error Handling]]: show a rich debugger or static 403 page on authorization errors
* [[Monitor]]: invokes a user-specified callback each time an AuthZ decision is made
* [[RSpec Support]]: use RSpec to write integration tests for Rails::Auth features and specs for ACLs
28 changes: 28 additions & 0 deletions docs/Matchers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Matchers are the component of Rails::Auth that make authorization decisions based on credentials. The following matchers are built-in and always available:

The following [[matchers]] are built-in and always available:

* **allow_all**: (options: `true` or `false`) always allow requests to the
given resources (so long as `true` is passed as the option)

The `Rails::Auth::X509::Matcher` class can be used to make authorization decisions based on X.509 certificates. For more information, see the [[X.509]] Wiki page.

Custom [[matchers]] can be any Ruby class that responds to the `#match` method. The full Rack environment is passed to `#match`. The corresponding object from the ACL definition is passed to the class's `#initialize` method.

Here is an example of a simple custom matcher:

```ruby
class MyClaimsMatcher
def initialize(options)
@options = options
end

def match(env)
claims = Rails::Auth.credentials(env)["claims"]
return false unless credential

@options["groups"].any? { |group| claims["groups"].include?(group) }
end
end

```
18 changes: 18 additions & 0 deletions docs/Monitor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
The `Rails::Auth::Monitor::Middleware` invokes a user-specified callback each time an AuthZ decision is made. The callback should look like this:

```ruby
my_monitor_callback = lambda do |env, success|
[...]
end
```

The parameters are:

* **env:** the full Rack environment associated with the request
* **success:** whether or not the request was authorized

On Rails, you can pass this callback as the `monitor:` option to `Rails::Auth::ConfigBuilder.production`. See [[Rails Usage]] for more information.

On Rack, you will have to instantiate the middleware yourself. See [[Rack Usage]] for more information.

These callbacks are useful for logging authorization decisions and/or reporting authorization failures to e.g. a central monitoring/alerting system.
117 changes: 117 additions & 0 deletions docs/RSpec-Support.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
Rails::Auth includes RSpec support useful for writing Rails integration tests and/or spec for your ACLs to ensure they have the behavior you expect.

To enable RSpec support, require the following:

```ruby
require "rails/auth/rspec"
```

## Helper Methods

### `with_credentials`: simulate credentials in tests

Configures a `Hash` of credentials (or doubles of them) to be used in the test. Helpful for simulating various scenarios in integration tests:

```ruby
RSpec.describe MyApiController, type: :request do
describe "#index" do
let(:example_app) { "foobar" }
let(:another_app) { "quux" }

it "permits access to the 'foobar' app" do
with_credentials(x509: x509_certificate(cn: example_app)) do
get my_api_path
end

expect(response.code).to eq "200"
end

it "disallows the 'quux' app" do
with_credentials(x509: x509_certificate(cn: another_app)) do
get my_api_path
end

expect(response.code).to eq "403"
end
end
end
```

### `x509_certificate`, `x509_certificate_hash`: create X.509 certificate doubles

The `x509_certificate` method creates a [verifying double] of a `Rails::Auth::X509::Certificate`. See the `#with_credentials` example for use in context.

It accepts the following options:

* **cn**: common name of the certificate (e.g. app name or app/host combo)
* **ou**: organizational unit of the certificate (e.g. app name, team name)

The `x509_certificate_hash` method produces a credential hash containing a `Rails::Auth::X509::Certificate`, and is shorthand so you don't have to do `{"x509" => x509_certificate(...)}`. Below is the same example as from `#with_credentials`, but rewritten with the `x509_certificate_hash` shorthand:

```ruby
RSpec.describe MyApiController, type: :request do
describe "#index" do
let(:example_app) { "foobar" }
let(:another_app) { "quux" }

it "permits access to the 'foobar' app" do
with_credentials(x509_certificate_hash(cn: example_app)) do
get my_api_path
end

expect(response.code).to eq "200"
end

it "disallows the 'quux' app" do
with_credentials(x509_certificate_hash(cn: another_app)) do
get my_api_path
end

expect(response.code).to eq "403"
end
end
end
```

See also: [[X.509]] Wiki page.

[verifying double]: https://relishapp.com/rspec/rspec-mocks/docs/verifying-doubles

## ACL Specs

Rails::Auth provides its own extensions to RSpec to allow you to write specs for the behavior of ACLs.

Below is an example of how to write an ACL spec:

```ruby
RSpec.describe "example_acl.yml", acl_spec: true do
let(:example_credentials) { x509_certificate_hash(ou: "ponycopter") }

subject do
Rails::Auth::ACL.from_yaml(
File.read("/path/to/example_acl.yml"),
matchers: { allow_x509_subject: Rails::Auth::X509::Matcher }
)
end

describe "/path/to/resource" do
it { is_expected.to permit get_request(credentials: example_credentials) }
it { is_expected.not_to permit get_request }
end
end
```

* Request builders: The following methods build requests from the described path:
* `get_request`
* `head_request`
* `put_request`
* `post_request`
* `delete_request`
* `options_request`
* `path_request`
* `link_request`
* `unlink_request`

The following matchers are available:

* `allow_request`: allows a request with the given Rack environment, and optional credentials
Loading
Loading