Skip to content

feat: Add RBAC package for managing user permissions #929

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 79 commits into from
Apr 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
79 commits
Select commit Hold shift + click to select a range
ab61328
WIP: This is a massive WIP
Emyrk Mar 26, 2022
03e4d0f
More info in the print
Emyrk Mar 26, 2022
9981291
Fix all()
Emyrk Mar 27, 2022
3ab32da
reduce the amount of memoery allocated
Emyrk Mar 27, 2022
e1d5893
Reuse a buffer
Emyrk Mar 28, 2022
84a90f3
fix: use return size over size
Emyrk Mar 29, 2022
1fac0d9
WIP: don't look at this
Emyrk Mar 29, 2022
1e3aac0
WIP: 🍐 auth-> testdata, refactoring and restructuring
johnstcn Mar 30, 2022
e977e84
testdata -> authztest
johnstcn Mar 30, 2022
00a7c3f
WIP: start work on SVO
johnstcn Mar 30, 2022
1f04c01
reduce allocations for union sets
Emyrk Mar 31, 2022
fbf4db1
fix: Fix nil permissions as Strings()
Emyrk Mar 31, 2022
4946897
chore: Make all permission variant levels
Emyrk Mar 31, 2022
7e6cc66
First full draft of the authz authorize test
Emyrk Mar 31, 2022
a0017e5
Tally up failed tests
Emyrk Mar 31, 2022
4b110b3
Change test pkg
Emyrk Mar 31, 2022
65ef4e3
Use an interface for the object
Emyrk Mar 31, 2022
d294786
fix: make authztest.Objects return correct type
johnstcn Apr 1, 2022
c1f8945
refactor: rename consts {Read,Write,Modify,Delete}Action to Action$1
johnstcn Apr 1, 2022
01f3d40
chore: Define object interface
Emyrk Apr 1, 2022
de7de6e
test: Unit test extra properties
Emyrk Apr 1, 2022
4c86e44
Merge remote-tracking branch 'origin/stevenmasley/rbac' into stevenma…
Emyrk Apr 1, 2022
30c6568
put back interface assertion
Emyrk Apr 1, 2022
a419a65
Fix some compile errors from merge
Emyrk Apr 1, 2022
bbd1c4c
test: Roles, sets, permissions, iterators
Emyrk Apr 1, 2022
def010f
Test string functions
Emyrk Apr 1, 2022
c4ee590
test: Unit test permission string
Emyrk Apr 4, 2022
84e3ab9
Add A+ and A-
Emyrk Apr 4, 2022
c2eec18
Parallelize tests
Emyrk Apr 4, 2022
5a2834a
fix code line in readme
Emyrk Apr 4, 2022
913d141
Merge remote-tracking branch 'origin/main' into stevenmasley/rbac
Emyrk Apr 4, 2022
2804b92
test: ParsePermissions from strings
Emyrk Apr 4, 2022
5698938
use fmt over str builder for easier to read
Emyrk Apr 4, 2022
75ed8ef
Linting
Emyrk Apr 4, 2022
b2db661
authz: README.md: update table formatting
johnstcn Apr 5, 2022
26ef1e6
Make action CRUD
Emyrk Apr 5, 2022
19aba30
LevelID -> OrganizationID
Emyrk Apr 5, 2022
ceee9cd
feat: authztest: categorize test failures by test name
johnstcn Apr 5, 2022
ee8bf04
fixup! feat: authztest: categorize test failures by test name
johnstcn Apr 5, 2022
44c02a1
chore: add documentation for authz and authztest
johnstcn Apr 6, 2022
dfb9ad1
fixup! chore: add documentation for authz and authztest
johnstcn Apr 6, 2022
e482d2c
chore: more authz/authztest docs
johnstcn Apr 6, 2022
a4e038f
Remove underscore from test names
Emyrk Apr 6, 2022
9918c16
zObject does not need exported fields
Emyrk Apr 6, 2022
4cf4808
checkpoint: crowd programming: define and simplify top-level API
johnstcn Apr 7, 2022
359a04d
Add tabled tests for authz
Emyrk Apr 7, 2022
22cf0cc
fix: made roles named and now they span all levels
johnstcn Apr 8, 2022
c51ddd1
fixup! fix: made roles named and now they span all levels
johnstcn Apr 8, 2022
891e442
fixup! fixup! fix: made roles named and now they span all levels
johnstcn Apr 8, 2022
ad048dd
vscode is illiterate
johnstcn Apr 8, 2022
bb28930
fixup! vscode is illiterate
johnstcn Apr 8, 2022
2e23a34
Remove Org & Owner obj interfaces
Emyrk Apr 8, 2022
13466e1
Show a nice builder syntax
Emyrk Apr 8, 2022
3ac2eaa
Add more tabled tests
Emyrk Apr 8, 2022
c7dc715
fixup! Add more tabled tests
Emyrk Apr 8, 2022
f5d95ef
correct comments
Emyrk Apr 8, 2022
0868301
fixup! correct comments
Emyrk Apr 8, 2022
512c09e
Address PR comments
Emyrk Apr 10, 2022
d9f761d
Drop unused resources & roles
Emyrk Apr 11, 2022
81ca08a
Rename chaining functions
Emyrk Apr 11, 2022
fced411
Rename OrgOwner -> OrgID
Emyrk Apr 11, 2022
f620ebf
feat: Add rego policy implementation
Emyrk Apr 12, 2022
07951a7
Merge remote-tracking branch 'origin/main' into cj/rbac_table_driven
Emyrk Apr 12, 2022
690d41d
Update go mod with opa
Emyrk Apr 12, 2022
fae3314
Go mod tidy
Emyrk Apr 12, 2022
856a933
Add rego comments
Emyrk Apr 12, 2022
e048104
Use cached rego query
Emyrk Apr 12, 2022
adae379
Correct user-deny perm in test
Emyrk Apr 12, 2022
0e7f9fa
tabs to spaces
Emyrk Apr 12, 2022
b1c7df4
Rename package to rbac
Emyrk Apr 12, 2022
35574ad
run golangci-lint and goimports
johnstcn Apr 12, 2022
8a16947
authz_test.go: log internal error
johnstcn Apr 12, 2022
2969fc1
fixup! run golangci-lint and goimports
johnstcn Apr 12, 2022
b22b723
to-done
johnstcn Apr 12, 2022
c1423d4
Merge remote-tracking branch 'origin/main' into cj/rbac_table_driven
johnstcn Apr 12, 2022
c2b1dde
Remove unused fields
Emyrk Apr 12, 2022
cfdd2cb
Add some comments to rego
Emyrk Apr 12, 2022
5c113a0
Move Authorize param order
Emyrk Apr 12, 2022
44a7679
Drop resources.go file
Emyrk Apr 12, 2022
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
73 changes: 73 additions & 0 deletions coderd/rbac/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Authz

Package `authz` implements AuthoriZation for Coder.

## Overview

Authorization defines what **permission** a **subject** has to perform **actions** to **objects**:
- **Permission** is binary: *yes* (allowed) or *no* (denied).
- **Subject** in this case is anything that implements interface `authz.Subject`.
- **Action** here is an enumerated list of actions, but we stick to `Create`, `Read`, `Update`, and `Delete` here.
- **Object** here is anything that implements `authz.Object`.

## Permission Structure

A **permission** is a rule that grants or denies access for a **subject** to perform an **action** on a **object**.
A **permission** is always applied at a given **level**:

- **site** level applies to all objects in a given Coder deployment.
- **org** level applies to all objects that have an organization owner (`org_owner`)
- **user** level applies to all objects that have an owner with the same ID as the subject.

**Permissions** at a higher **level** always override permissions at a **lower** level.

The effect of a **permission** can be:
- **positive** (allows)
- **negative** (denies)
- **abstain** (neither allows or denies, not applicable)

**Negative** permissions **always** override **positive** permissions at the same level.
Both **negative** and **positive** permissions override **abstain** at the same level.

This can be represented by the following truth table, where Y represents *positive*, N represents *negative*, and _ represents *abstain*:

| Action | Positive | Negative | Result |
|--------|----------|----------|--------|
| read | Y | _ | Y |
| read | Y | N | N |
| read | _ | _ | _ |
| read | _ | N | Y |


## Permission Representation

**Permissions** are represented in string format as `<sign>?<level>.<object>.<id>.<action>`, where:

- `negated` can be either `+` or `-`. If it is omitted, sign is assumed to be `+`.
- `level` is either `site`, `org`, or `user`.
- `object` is any valid resource type.
- `id` is any valid UUID v4.
- `action` is `create`, `read`, `modify`, or `delete`.

## Example Permissions

- `+site.*.*.read`: allowed to perform the `read` action against all objects of type `devurl` in a given Coder deployment.
- `-user.workspace.*.create`: user is not allowed to create workspaces.

## Roles

A *role* is a set of permissions. When evaluating a role's permission to form an action, all the relevant permissions for the role are combined at each level. Permissions at a higher level override permissions at a lower level.

The following table shows the per-level role evaluation.
Y indicates that the role provides positive permissions, N indicates the role provides negative permissions, and _ indicates the role does not provide positive or negative permissions. YN_ indicates that the value in the cell does not matter for the access result.

| Role (example) | Site | Org | User | Result |
|-----------------|------|-----|------|--------|
| site-admin | Y | YN_ | YN_ | Y |
| no-permission | N | YN_ | YN_ | N |
| org-admin | _ | Y | YN_ | Y |
| non-org-member | _ | N | YN_ | N |
| user | _ | _ | Y | Y |
| | _ | _ | N | N |
| unauthenticated | _ | _ | _ | N |

11 changes: 11 additions & 0 deletions coderd/rbac/action.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package rbac

// Action represents the allowed actions to be done on an object.
type Action string

const (
ActionCreate = "create"
ActionRead = "read"
ActionUpdate = "update"
ActionDelete = "delete"
)
70 changes: 70 additions & 0 deletions coderd/rbac/authz.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package rbac

import (
"context"
_ "embed"

"golang.org/x/xerrors"

"github.com/open-policy-agent/opa/rego"
)

// RegoAuthorizer will use a prepared rego query for performing authorize()
type RegoAuthorizer struct {
query rego.PreparedEvalQuery
}

// Load the policy from policy.rego in this directory.
//go:embed policy.rego
var policy string

func NewAuthorizer() (*RegoAuthorizer, error) {
ctx := context.Background()
query, err := rego.New(
// allowed is the `allow` field from the prepared query. This is the field to check if authorization is
// granted.
rego.Query("allowed = data.authz.allow"),
rego.Module("policy.rego", policy),
).PrepareForEval(ctx)

if err != nil {
return nil, xerrors.Errorf("prepare query: %w", err)
}
Comment on lines +23 to +32
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we do this in init and panic if an error occurs? Then users don't have to hold a struct, and can just call Authorize.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking about that, and I just hate init() functions. I figure we can put the init() anywhere if it's a pain to pass around, meaning we can put the init in coderd somewhere too. So we can decide to init() once we use this.

We will need more PRs for integration, and that is when I think we can make that call.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough fair enough

return &RegoAuthorizer{query: query}, nil
}

type authSubject struct {
ID string `json:"id"`
Roles []Role `json:"roles"`
}

func (a RegoAuthorizer) Authorize(ctx context.Context, subjectID string, roles []Role, action Action, object Object) error {
input := map[string]interface{}{
"subject": authSubject{
ID: subjectID,
Roles: roles,
},
"object": object,
"action": action,
}

results, err := a.query.Eval(ctx, rego.EvalInput(input))
if err != nil {
return ForbiddenWithInternal(xerrors.Errorf("eval rego: %w, err"), input, results)
}

if len(results) != 1 {
return ForbiddenWithInternal(xerrors.Errorf("expect only 1 result, got %d", len(results)), input, results)
}

allowedResult, ok := (results[0].Bindings["allowed"]).(bool)
if !ok {
return ForbiddenWithInternal(xerrors.Errorf("expected allowed to be a bool but got %T", allowedResult), input, results)
}

if !allowedResult {
return ForbiddenWithInternal(xerrors.Errorf("policy disallows request"), input, results)
}

return nil
}
Loading