# Policies

> Control who can read and write data, and who can call services and operations, using Taxi policies

Source: https://taxilang.org/docs/language/policies

## Overview

A policy is a set of rules about who can see data, and who can change it.

A policy can apply to:

* **A type** - to shape the data that is read, and to decide whether an instance may be written
* **A service** - to decide whether its operations may be called
* **A single member of a service** - an operation, query operation, table or stream

Here's a policy that lets a user read trades from any desk, but hides the counterparty unless the trade belongs to
the user's own desk. Only traders on the same desk can write a trade:

```taxi
type DeskId inherits String
type CounterpartyName inherits String
type UserGroup inherits String

model Trade {
   desk : DeskId
   counterparty : CounterpartyName
}

model UserInfo {
   desk : DeskId
   groups : UserGroup[]
}

policy TradePolicy against Trade (user: UserInfo) -> {
   read {
      when {
         user.desk == this.desk -> Trade
         else -> Trade as {
            counterparty : CounterpartyName = null
            ...
         }
      }
   }
   write { user.groups.contains('TRADER') && user.desk == this.desk }
}
```

> **Note: Taxi defines policies, the runtime enforces them**
>
> Taxi defines policies and checks they are valid when your project compiles. It does not run them. Enforcing a policy
> is the job of the runtime that executes your queries, such as [Orbital](https://orbitalhq.com).

## Anatomy of a policy

```taxi
policy TradePolicy against Trade (user: UserInfo) -> {
   read { Trade }
   write { user.desk == this.desk }
}
```

| Part | Example | Meaning |
|---|---|---|
| Name | `TradePolicy` | The name of the policy |
| Target | `against Trade` | What the policy applies to: a type, a service, or `Service::member` |
| Inputs | `(user: UserInfo) ->` | Values the rules can use. Optional |
| Rules | `read { ... }` | Expressions that decide the outcome. A rule can start with `read` or `write` |

Inputs are optional. Without them, the rules follow the target directly:

```taxi
policy CustomerServiceAccess against CustomerService {
   write { false }
}
```

## Policies against a type

A policy against a type has `read` rules and `write` rules.

### Read rules

A `read` rule shapes the data that is returned when an instance of the type is read.
Inside the rule, `this` is the instance being read.

A read rule returns one of:

* The value itself (eg: `Trade`), to return it unchanged
* A projection that hides some fields (eg: `Trade as { counterparty : CounterpartyName = null ... }`)
* `null`, to remove the value
* `throw(...)`, to fail the query with an error

```taxi
policy TradePolicy against Trade (user: UserInfo) -> {
   read {
      when {
         // Traders on the desk see everything
         user.desk == this.desk -> Trade
         // Compliance see the trade, without the counterparty
         user.groups.contains('COMPLIANCE') -> Trade as {
            counterparty : CounterpartyName = null
            ...
         }
         // Nobody else sees the trade at all
         else -> null
      }
   }
}
```

A rule with no `read` or `write` keyword is a read rule. These two policies are the same:

```taxi
policy FilmPolicy against Film {
   read { Film }
}

policy SameFilmPolicy against Film {
   { Film }
}
```

To fail the query instead of removing the value, use `throw`:

```taxi
policy TradePolicy against Trade (user: UserInfo) -> {
   read {
      when {
         user.desk == this.desk -> Trade
         else -> throw('You can only read trades from your own desk')
      }
   }
}
```

### Write rules

A `write` rule decides whether an instance of the type may be written - for example, when it is passed to a
[write operation](https://taxilang.org/docs/language/services#write-operations-mutations).
Inside the rule, `this` is the instance being written.

A write rule must return a `Boolean`:

```taxi
policy TradePolicy against Trade (user: UserInfo) -> {
   write { user.groups.contains('TRADER') && user.desk == this.desk }
}
```

A write rule that returns something else is a compile error:

```
Write rules decide whether a write is permitted, so they must return Boolean (true to permit, false to deny).
```

#### Writing null values

Write rules also run when the value being written is null. This includes a field that is left out of a
request, which is treated the same as a field set to null. So `write { false }` also stops a value from
being cleared.

To let nulls through, compare the value to `null` using the type's name, before checking anything else:

```taxi
type Age inherits Int

parameter model UpdatePersonRequest {
   age : Age?
}

// An age can be cleared, but when it's set it must be 18 or over
policy AgePolicy against Age {
   write { Age == null || Age >= 18 }
}

// A trade can be cleared, but only traders on its desk can set it
policy TradePolicy against Trade (user: UserInfo) -> {
   write { Trade == null || user.desk == this.desk }
}
```

When the value is null, a rule that reads one of its fields (eg: `this.desk`) denies the write.

### Policies against primitive types are not allowed

A policy can't be declared against a primitive type such as `String` or `Int`, or an array of one (eg: `String[]`).
This is a compile error. Instead, declare a semantic type, use it in your models, and declare the policy against it:

```taxi
type CustomerName inherits String

model Customer {
   name : CustomerName
}

policy CustomerNamePolicy against CustomerName {
   write { false }
}
```

## Policies against a service

A policy against a service decides whether the service's operations may be called.

```taxi
model Customer {
   id : CustomerId inherits String
}

service CustomerService {
   operation findCustomer(CustomerId):Customer
   write operation saveCustomer(Customer):Customer
}

// Everyone can read, only admins can write
policy CustomerServiceAccess against CustomerService (user: UserInfo) -> {
   read { true }
   write { user.groups.contains('ADMIN') }
}
```

* A `read` rule applies to the service's read members. An operation is a read unless it is declared as a
  `write operation`.
* A `write` rule applies to the service's write members.
* A rule with no keyword applies to every member, read or write.

Every rule must return a `Boolean`. There is no `this` in a service policy, as the policy is about calling the
service, not about a particular piece of data.

```taxi
policy CustomerServiceAccess against CustomerService (user: UserInfo) -> {
   // Applies to every operation on CustomerService
   { user.groups.contains('STAFF') }
}
```

## Policies against a single member

To target one member of a service, write `Service::member`. The member can be an operation, a query operation,
a table or a stream.

```taxi
type TransferAmount inherits Decimal
type AccountId inherits String

model Payment {
   amount : TransferAmount
}

service PaymentService {
   operation getBalance(AccountId):TransferAmount
   write operation transfer(AccountId, TransferAmount):Payment
   table payments : Payment[]
}

policy TransferLimit against PaymentService::transfer (user: UserInfo, amount: TransferAmount) -> {
   amount <= 10000 || user.groups.contains('SENIOR_TELLER')
}
```

A member is already either a read or a write, so the body can be a single expression, with no `read { }` or
`write { }` block around it. The expression must return a `Boolean`. As with service policies, there is no `this`.

You can still use a `read` or `write` block, but the keyword must agree with the member:

| Member | Allowed keywords |
|---|---|
| `operation` | `read` |
| `write operation` | `write` |
| Query operation | `read` (a query operation is always a read) |
| `table` | `read` or `write` |
| `stream` | `read` or `write` |

Tables and streams can be read from and written to, so a policy can have a rule for each:

```taxi
policy PaymentsTable against PaymentService::payments (user: UserInfo) -> {
   read { true }
   write { user.groups.contains('ADMIN') }
}
```

A keyword that disagrees with the member is a compile error. For example, `transfer` is a `write operation`,
so it can't have a `read` rule:

```
PaymentService::transfer is a service member that writes, so it can't have a read rule
```

## Inputs

Inputs are the values a policy's rules can use, such as details about the user making the request.
Each input has a name and a type: `(user: UserInfo)`.

Inputs are found by their type, not their name. When the policy runs, the runtime looks for a value of type
`UserInfo` and passes it in as `user`.

On service and member policies, the arguments of the call are available the same way. In the `TransferLimit`
policy above, `amount: TransferAmount` is the `TransferAmount` passed to `transfer`:

```taxi
policy TransferLimit against PaymentService::transfer (user: UserInfo, amount: TransferAmount) -> {
   amount <= 10000 || user.groups.contains('SENIOR_TELLER')
}
```

## Rules that return a Boolean

`write` rules on a type, and every rule on a service or member policy, return a `Boolean`.
These rules have three possible outcomes:

| Result | Meaning |
|---|---|
| `true` | Permitted |
| `false` | Denied |
| `throw(...)` | The query fails with the given error |

```taxi
policy CustomerServiceAccess against CustomerService (user: UserInfo) -> {
   write {
      when {
         user.groups.contains('ADMIN') -> true
         else -> throw('Only admins can change customers')
      }
   }
}
```

## How policies combine

When more than one rule applies to a call, every one of them must permit it. For example, a call to
`PaymentService::transfer` must be permitted by any policy against `PaymentService`, and by any policy against
`PaymentService::transfer`.

When no rule applies, the call is permitted. A service policy with only `read` rules does not restrict writes.
To block writes, say so:

```taxi
policy CustomerServiceAccess against CustomerService {
   read { true }
   write { false }
}
```
