Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ory/ladon
A SDK for access control policies: authorization for the microservice and IoT age. Inspired by AWS IAM policies. Written for Go.
https://github.com/ory/ladon
Last synced: 2 days ago
JSON representation
A SDK for access control policies: authorization for the microservice and IoT age. Inspired by AWS IAM policies. Written for Go.
- Host: GitHub
- URL: https://github.com/ory/ladon
- Owner: ory
- License: apache-2.0
- Created: 2015-10-16T15:21:28.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2024-09-19T14:43:26.000Z (3 months ago)
- Last Synced: 2024-12-02T22:02:25.992Z (9 days ago)
- Language: Go
- Homepage: https://www.ory.sh/?utm_source=github&utm_medium=banner&utm_campaign=ladon
- Size: 1.21 MB
- Stars: 2,404
- Watchers: 63
- Forks: 225
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- Changelog: HISTORY.md
- Contributing: CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE
- Audit: audit_logger.go
Awesome Lists containing this project
- awesome-auth - Ladon - SDK for access control policies: authorization for the microservice and IoT age. (Authorization / <a name="authZ-golang"></a>Golang)
- awesome-iam - Ladon - Access control library, inspired by AWS. (Authorization / Open-source policy frameworks)
- starred-awesome - ladon - A SDK for access control policies: authorization for the microservice and IoT age. Inspired by AWS IAM policies. Written for Go. (Go)
- awesome - ladon - A SDK for access control policies: authorization for the microservice and IoT age. Inspired by AWS IAM policies. Written for Go. (Go)
README
[![Join the chat at https://www.ory.sh/chat](https://img.shields.io/badge/join-chat-00cc99.svg)](https://www.ory.sh/chat)
[![Join newsletter](https://img.shields.io/badge/join-newsletter-00cc99.svg)](https://www.ory.sh/l/sign-up-newsletter)[![Build Status](https://travis-ci.org/ory/ladon.svg?branch=master)](https://travis-ci.org/ory/ladon)
[![Coverage Status](https://coveralls.io/repos/ory/ladon/badge.svg?branch=master&service=github)](https://coveralls.io/github/ory/ladon?branch=master)
[![Go Report Card](https://goreportcard.com/badge/github.com/ory/ladon)](https://goreportcard.com/report/github.com/ory/ladon)
[![GoDoc](https://godoc.org/github.com/ory/ladon?status.png)](https://godoc.org/github.com/ory/ladon)[Ladon](https://en.wikipedia.org/wiki/Ladon_%28mythology%29) is the serpent dragon protecting your resources.
Ladon is a library written in [Go](https://golang.org) for access control policies, similar to [Role Based Access Control](https://en.wikipedia.org/wiki/Role-based_access_control)
or [Access Control Lists](https://en.wikipedia.org/wiki/Access_control_list).
In contrast to [ACL](https://en.wikipedia.org/wiki/Access_control_list) and [RBAC](https://en.wikipedia.org/wiki/Role-based_access_control)
you get fine-grained access control with the ability to answer questions in complex environments such as multi-tenant or distributed applications
and large organizations. Ladon is inspired by [AWS IAM Policies](http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html).Ladon officially ships with an exemplary in-memory storage implementations.
Community-supported adapters are available for [CockroachDB](https://github.com/wehco/ladon-crdb).Ladon is now considered stable.
---
ORY builds solutions for better internet security and accessibility. We have a couple more projects you might enjoy:
* **[Hydra](https://github.com/ory/hydra)**, a security-first open source OAuth2 and OpenID Connect server for new and existing infrastructures that uses Ladon for access control.
* **[ORY Editor](https://github.com/ory/editor)**, an extensible, modern WYSI editor for the web written in React.
* **[Fosite](https://github.com/ory/fosite)**, an extensible security first OAuth 2.0 and OpenID Connect SDK for Go.
* **[Dockertest](https://github.com/ory/dockertest)**: Write better integration tests with dockertest!---
**Table of Contents**
- [Installation](#installation)
- [Concepts](#concepts)
- [Usage](#usage)
- [Policies](#policies)
- [Conditions](#conditions)
- [CIDR Condition](#cidr-condition)
- [String Equal Condition](#string-equal-condition)
- [Boolean Condition](#boolean-condition)
- [String Match Condition](#string-match-condition)
- [Subject Condition](#subject-condition)
- [String Pairs Equal Condition](#string-pairs-equal-condition)
- [Resource Contains Condition](#resource-contains-condition)
- [Adding Custom Conditions](#adding-custom-conditions)
- [Persistence](#persistence)
- [Access Control (Warden)](#access-control-warden)
- [Audit Log (Warden)](#audit-log-warden)
- [Metrics](#metrics)
- [Limitations](#limitations)
- [Regular expressions](#regular-expressions)
- [Examples](#examples)
- [Good to know](#good-to-know)
- [Useful commands](#useful-commands)Ladon utilizes ory-am/dockertest for tests.
Please refer to [ory-am/dockertest](https://github.com/ory-am/dockertest) for more information of how to setup testing environment.## Installation
This library works with Go 1.11+.
```
export GO111MODULE=on
go get github.com/ory/ladon
```Ladon uses [semantic versioning](http://semver.org/) and versions beginning with zero (`0.1.2`) might introduce backwards compatibility
breaks with [each minor version](http://semver.org/#how-should-i-deal-with-revisions-in-the-0yz-initial-development-phase).## Concepts
Ladon is an access control library that answers the question:
> **Who** is **able** to do **what** on **something** given some **context**
* **Who**: An arbitrary unique subject name, for example "ken" or "printer-service.mydomain.com".
* **Able**: The effect which can be either "allow" or "deny".
* **What**: An arbitrary action name, for example "delete", "create" or "scoped:action:something".
* **Something**: An arbitrary unique resource name, for example "something", "resources.articles.1234" or some uniform
resource name like "urn:isbn:3827370191".
* **Context**: The current context containing information about the environment such as the IP Address,
request date, the resource owner name, the department ken is working in or any other information you want to pass along.
(optional)To decide what the answer is, Ladon uses policy documents which can be represented as JSON
```json
{
"description": "One policy to rule them all.",
"subjects": ["users:", "users:maria", "groups:admins"],
"actions" : ["delete", ""],
"effect": "allow",
"resources": [
"resources:articles:<.*>",
"resources:printer"
],
"conditions": {
"remoteIP": {
"type": "CIDRCondition",
"options": {
"cidr": "192.168.0.1/16"
}
}
}
}
```and can answer access requests that look like:
```json
{
"subject": "users:peter",
"action" : "delete",
"resource": "resources:articles:ladon-introduction",
"context": {
"remoteIP": "192.168.0.5"
}
}
```However, Ladon does not come with a HTTP or server implementation. It does not restrict JSON either. We believe that it is your job to decide
if you want to use Protobuf, RESTful, HTTP, AMQP, or some other protocol. It's up to you to write the server!The following example should give you an idea what a RESTful flow *could* look like. Initially we create a policy by
POSTing it to an artificial HTTP endpoint:```
> curl \
-X POST \
-H "Content-Type: application/json" \
-d@- \
"https://my-ladon-implementation.localhost/policies" <", "users:maria", "groups:admins"],
"actions" : ["delete", ""],
"effect": "allow",
"resources": [
"resources:articles:<.*>",
"resources:printer"
],
"conditions": {
"remoteIP": {
"type": "CIDRCondition",
"options": {
"cidr": "192.168.0.1/16"
}
}
}
}
EOF
```Then we test if "peter" (ip: "192.168.0.5") is allowed to "delete" the "ladon-introduction" article:
```
> curl \
-X POST \
-H "Content-Type: application/json" \
-d@- \
"https://my-ladon-implementation.localhost/warden" <.
Subjects: []string{"max", "peter", ""},// Which resources this policy affects.
// Again, you can put regular expressions in inside < >.
Resources: []string{
"myrn:some.domain.com:resource:123", "myrn:some.domain.com:resource:345",
"myrn:something:foo:<.+>", "myrn:some.domain.com:resource:<(?!protected).*>",
"myrn:some.domain.com:resource:<[[:digit:]]+>",
},// Which actions this policy affects. Supports RegExp
// Again, you can put regular expressions in inside < >.
Actions: []string{"", "get"},// Should access be allowed or denied?
// Note: If multiple policies match an access request, ladon.DenyAccess will always override ladon.AllowAccess
// and thus deny access.
Effect: ladon.AllowAccess,// Under which conditions this policy is "active".
Conditions: ladon.Conditions{
// In this example, the policy is only "active" when the requested subject is the owner of the resource as well.
"resourceOwner": &ladon.EqualsSubjectCondition{},// Additionally, the policy will only match if the requests remote ip address matches address range 127.0.0.1/32
"remoteIPAddress": &ladon.CIDRCondition{
CIDR: "127.0.0.1/32",
},
},
}
```#### Conditions
Conditions are functions returning true or false given a context. Because conditions implement logic, they must
be programmed. Adding conditions to a policy consist of two parts, a key name and an implementation of `ladon.Condition`:```go
// StringEqualCondition is an exemplary condition.
type StringEqualCondition struct {
Equals string `json:"equals"`
}// Fulfills returns true if the given value is a string and is the
// same as in StringEqualCondition.Equals
func (c *StringEqualCondition) Fulfills(value interface{}, _ *ladon.Request) bool {
s, ok := value.(string)return ok && s == c.Equals
}// GetName returns the condition's name.
func (c *StringEqualCondition) GetName() string {
return "StringEqualCondition"
}var pol = &ladon.DefaultPolicy{
// ...
Conditions: ladon.Conditions{
"some-arbitrary-key": &StringEqualCondition{
Equals: "the-value-should-be-this"
}
},
}
```The default implementation of `Policy` supports JSON un-/marshalling. In JSON, this policy would look like:
```json
{
"conditions": {
"some-arbitrary-key": {
"type": "StringEqualCondition",
"options": {
"equals": "the-value-should-be-this"
}
}
}
}
```As you can see, `type` is the value that `StringEqualCondition.GetName()` is returning and `options` is used to
set the value of `StringEqualCondition.Equals`.This condition is fulfilled by (we will cover the warden in the next section)
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Context: ladon.Context{
"some-arbitrary-key": "the-value-should-be-this",
},
}
```but not by
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Context: ladon.Context{
"some-arbitrary-key": "some other value",
},
}
```and neither by:
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Context: ladon.Context{
"same value but other key": "the-value-should-be-this",
},
}
```Ladon ships with a couple of default conditions:
##### [CIDR Condition](condition_cidr.go)
The CIDR condition matches CIDR IP Ranges. Using this condition would look like this in JSON:
```json
{
"conditions": {
"remoteIPAddress": {
"type": "CIDRCondition",
"options": {
"cidr": "192.168.0.1/16"
}
}
}
}
```and in Go:
```go
var pol = &ladon.DefaultPolicy{
Conditions: ladon.Conditions{
"remoteIPAddress": &ladon.CIDRCondition{
CIDR: "192.168.0.1/16",
},
},
}
```In this case, we expect that the context of an access request contains a field `"remoteIpAddress"` matching
the CIDR `"192.168.0.1/16"`, for example `"192.168.0.5"`.##### [String Equal Condition](condition_string_equal.go)
Checks if the value passed in the access request's context is identical with the string that was given initially
```go
var pol = &ladon.DefaultPolicy{
Conditions: ladon.Conditions{
"some-arbitrary-key": &ladon.StringEqualCondition{
Equals: "the-value-should-be-this"
}
},
}
```and would match in the following case:
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Context: ladon.Context{
"some-arbitrary-key": "the-value-should-be-this",
},
}
```##### [Boolean Condition](condition_boolean.go)
Checks if the boolean value passed in the access request's context is identical with the expected boolean value in the policy
```go
var pol = &ladon.DefaultPolicy{
Conditions: ladon.Conditions{
"some-arbitrary-key": &ladon.BooleanCondition{
BooleanValue: true,
}
},
}
```and would match in the following case:
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Context: ladon.Context{
"some-arbitrary-key": true,
},
})
```This condition type is particularly useful if you need to assert a policy dynamically on resources for multiple subjects. For example, consider
if you wanted to enforce policy that only allows individuals that own a resource to view that resource. You'd have to be able to create a Ladon
policy that permits access to every resource for every subject that enters your system.With the Boolean Condition type, you can use conditional logic at runtime to create a match for a policy's condition.
##### [String Match Condition](condition_string_match.go)
Checks if the value passed in the access request's context matches the regular expression that was given initially
```go
var pol = &ladon.DefaultPolicy{
Conditions: ladon.Conditions{
"some-arbitrary-key": &ladon.StringMatchCondition{
Matches: "regex-pattern-here.+"
}
}
}
```and would match in the following case:
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Context: ladon.Context{
"some-arbitrary-key": "regex-pattern-here111"
}
}
})
```##### [Subject Condition](condition_subject_equal.go)
Checks if the access request's subject is identical with the string that was given initially
```go
var pol = &ladon.DefaultPolicy{
Conditions: ladon.Conditions{
"some-arbitrary-key": &ladon.EqualsSubjectCondition{}
},
}
```and would match
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Subject: "peter",
Context: ladon.Context{
"some-arbitrary-key": "peter",
},
}
```but not:
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Subject: "peter",
Context: ladon.Context{
"some-arbitrary-key": "max",
},
}
```##### [String Pairs Equal Condition](condition_string_pairs_equal.go)
Checks if the value passed in the access request's context contains two-element arrays
and that both elements in each pair are equal.```go
var pol = &ladon.DefaultPolicy{
Conditions: ladon.Conditions{
"some-arbitrary-key": &ladon.StringPairsEqualCondition{}
},
}
```and would match
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Context: ladon.Context{
"some-arbitrary-key": [
["some-arbitrary-pair-value", "some-arbitrary-pair-value"],
["some-other-arbitrary-pair-value", "some-other-arbitrary-pair-value"],
]
},
}
```but not:
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Context: ladon.Context{
"some-arbitrary-key": [
["some-arbitrary-pair-value", "some-other-arbitrary-pair-value"],
]
},
}
```##### [Resource Contains Condition](condition_resource_contains.go)
Checks if the string value passed in the access request's context is present in the resource string.
The Condition requires a value string and an optional delimiter (needs to match the resource string) to be passed.
A resource could for instance be: `myrn:some.domain.com:resource:123` and `myrn:some.otherdomain.com:resource:123` (the `:` is then considered a delimiter, and used by the condition to be able to separate the resource components from each other) to allow an action to the resources on `myrn:some.otherdomain.com` you could for instance create a resource condition with
{value: `myrn:some.otherdomain.com`, Delimiter: ":"}
alternatively:
{value: `myrn:some.otherdomain.com`}
> The delimiter is optional *but needed for* the condition to be able to separate resource string components:
> i.e. to make sure the value `foo:bar` matches `foo:bar` but not `foo:bara` nor `foo:bara:baz`.
>
> That is, a delimiter is necessary to separate:
>
> `{value: "myrn:fo", delimiter: ":"}` from `{value: "myrn:foo", delimiter: ":"}` or
> `{value: "myid:12"}` from `{value: "myid:123"}`.This condition is fulfilled by this (allow for all resources containing `part:north`):
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Resource: "rn:city:laholm:part:north"
Context: ladon.Context{
delimiter: ":",
value: "part:north"
},
}
```or ( allow all resources with `city:laholm`)
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Resource: "rn:city:laholm:part:north"
Context: ladon.Context{
delimiter: ":",
value: "city:laholm"
},
}
```but not (allow for all resources containing `part:west`, the resource does not contain `part:west`):
```go
var err = warden.IsAllowed(&ladon.Request{
// ...
Resource: "rn:city:laholm:part:north"
Context: ladon.Context{
delimiter: ":",
value: "part:west"
},
}
```##### Adding Custom Conditions
You can add custom conditions by appending it to `ladon.ConditionFactories`:
```go
import "github.com/ory/ladon"func main() {
// ...ladon.ConditionFactories[new(CustomCondition).GetName()] = func() Condition {
return new(CustomCondition)
}// ...
}
```#### Persistence
Obviously, creating such a policy is not enough. You want to persist it too. Ladon ships an interface `ladon.Manager` for
this purpose. You have to implement that interface for persistence. An exemplary in-memory adapter can be found in
[./manager/memory/manager_memory.go](./manager/memory/manager_memory.go):Let's take a look how to instantiate those:
**In-Memory** (officially supported)
```go
import (
"github.com/ory/ladon"
manager "github.com/ory/ladon/manager/memory"
)func main() {
warden := &ladon.Ladon{
Manager: manager.NewMemoryManager(),
}
err := warden.Manager.Create(pol)// ...
}
```### Access Control (Warden)
Now that we have defined our policies, we can use the warden to check if a request is valid.
`ladon.Ladon`, which is the default implementation for the `ladon.Warden` interface defines `ladon.Ladon.IsAllowed()` which
will return `nil` if the access request can be granted and an error otherwise.```go
import "github.com/ory/ladon"func main() {
// ...err := warden.IsAllowed(&ladon.Request{
Subject: "peter",
Action: "delete",
Resource: "myrn:some.domain.com:resource:123",
Context: ladon.Context{
"ip": "127.0.0.1",
},
})
if err != nil {
log.Fatal("Access denied")
}// ...
}
```### Audit Log (Warden)
In order to keep track of authorization grants and denials, it is possible to attach a `ladon.AuditLogger`.
The provided `ladon.AuditLoggerInfo` outputs information about the policies involved when responding to authorization requests.```go
import "github.com/ory/ladon"
import manager "github.com/ory/ladon/manager/memory"func main() {
warden := ladon.Ladon{
Manager: manager.NewMemoryManager(),
AuditLogger: &ladon.AuditLoggerInfo{}
}// ...
```
It will output to `stderr` by default.
### Metrics
Ability to track authorization grants,denials and errors, it is possible to implement own interface for processing metrics.
```go
type prometheusMetrics struct{}func (mtr *prometheusMetrics) RequestDeniedBy(r ladon.Request, p ladon.Policy) {}
func (mtr *prometheusMetrics) RequestAllowedBy(r ladon.Request, policies ladon.Policies) {}
func (mtr *prometheusMetrics) RequestNoMatch(r ladon.Request) {}
func (mtr *prometheusMetrics) RequestProcessingError(r ladon.Request, err error) {}func main() {
warden := ladon.Ladon{
Manager: manager.NewMemoryManager(),
Metric: &prometheusMetrics{},
}// ...
```## Limitations
Ladon's limitations are listed here.
### Regular expressions
Matching regular expressions has a complexity of `O(n)` ([except](https://groups.google.com/d/msg/golang-nuts/7qgSDWPIh_E/OHTAm4wRZL0J) lookahead/lookbehind assertions) and databases such as MySQL or Postgres can not
leverage indexes when parsing regular expressions. Thus, there is considerable overhead when using regular
expressions.We have implemented various strategies for reducing policy matching time:
1. An LRU cache is used for caching frequently compiled regular expressions. This reduces cpu complexity
significantly for memory manager implementations.
2. The SQL schema is 3NF normalized.
3. Policies, subjects and actions are stored uniquely, reducing the total number of rows.
4. Only one query per look up is executed.
5. If no regular expression is used, a simple equal match is done in SQL back-ends.You will get the best performance with the in-memory manager. The SQL adapters perform about 1000:1 compared to the in-memory solution. Please note that these tests where in laboratory environments with Docker, without an SSD, and single-threaded. You might get better results on your system. We are thinking about introducing simple cache strategies such as LRU with a maximum age to further reduce runtime complexity.
We are also considering to offer different matching strategies (e.g. wildcard match) in the future, which will perform better
with SQL databases. If you have ideas or suggestions, leave us an issue.## Examples
Check out [ladon_test.go](ladon_test.go) which includes a couple of policies and tests cases. You can run the code with `go test -run=TestLadon -v .`
## Good to know
* All checks are *case sensitive* because subject values could be case sensitive IDs.
* If `ladon.Ladon` is not able to match a policy with the request, it will default to denying the request and return an error.Ladon does not use reflection for matching conditions to their appropriate structs due to security considerations.
## Useful commands
**Create mocks**
```sh
mockgen -package ladon_test -destination manager_mock_test.go github.com/ory/ladon Manager
```## Third Party Libraries
By implementing the warden.Manager it is possible to create your own adapters to persist data in a datastore of your choice. Below are a list of third party implementations.- [Redis and RethinkDB](https://github.com/ory/ladon-community)
- [CockroachDB](https://github.com/dwin/ladon-crdb)
- [sql.DB](https://github.com/wirepair/ladonsqlmanager)