# Set Up Login Rules

Login Rules define logic that transforms the external traits of a user who signs into Teleport, providing consistent access control policies for users in your cluster. A Teleport administrator can use Login Rules to define transformations in user traits without requiring changes in their IdP configuration. This is particularly useful if the team that manages an organization's identity provider (IdP) is separate from the team that manages Teleport.

This guide walks you through the process of writing, testing, and adding the first Login Rule to your Teleport cluster.

## How it works

A Login Rule is a dynamic Teleport resource stored on the Auth Service backend. When a user authenticates to Teleport through an IdP, Teleport populates the user's **external traits** based on data from the IdP. Login Rules define logic for manipulating a user's external traits. When a user signs into Teleport, the Teleport Auth Service executes Login Rules in order of priority. After executing all Login Rules the Auth Service encodes the final set of external traits in the certificates that it issues to the user.

For more information about configuring Login Rules, see the [Login Rules Reference](https://goteleport.com/docs/reference/access-controls/login-rules.md).

## Prerequisites

- A running Teleport Enterprise cluster. If you want to get started with Teleport, [sign up](https://goteleport.com/signup) for a free trial or [set up a demo environment](https://goteleport.com/docs/get-started/deploy-community.md).

- The `tctl` and `tsh` clients.

  Installing `tctl` and `tsh` clients

  1. Determine the version of your Teleport cluster. The `tctl` and `tsh` clients must be at most one major version behind your Teleport cluster version. Send a GET request to the Proxy Service at `/v1/webapi/find` and use a JSON query tool to obtain your cluster version. Replace teleport.example.com:443 with the web address of your Teleport Proxy Service:

     ```
     $ TELEPORT_DOMAIN=teleport.example.com:443
     $ TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')"
     ```

  2. Follow the instructions for your platform to install `tctl` and `tsh` clients:

     **Mac**

     Download the signed macOS .pkg installer for Teleport, which includes the `tctl` and `tsh` clients:

     ```
     $ curl -O https://cdn.teleport.dev/teleport-${TELEPORT_VERSION?}.pkg
     ```

     In Finder double-click the `pkg` file to begin installation.

     ---

     DANGER

     Using Homebrew to install Teleport is not supported. The Teleport package in Homebrew is not maintained by Teleport and we can't guarantee its reliability or security.

     ---

     **Windows - Powershell**

     ```
     $ curl.exe -O https://cdn.teleport.dev/teleport-v${TELEPORT_VERSION?}-windows-amd64-bin.zip
     Unzip the archive and move the `tctl` and `tsh` clients to your %PATH%
     NOTE: Do not place the `tctl` and `tsh` clients in the System32 directory, as this can cause issues when using WinSCP.
     Use %SystemRoot% (C:\Windows) or %USERPROFILE% (C:\Users\<username>) instead.
     ```

     **Linux**

     All of the Teleport binaries in Linux installations include the `tctl` and `tsh` clients. For more options (including RPM/DEB packages and downloads for i386/ARM/ARM64) see our [installation page](https://goteleport.com/docs/installation.md).

     ```
     $ curl -O https://cdn.teleport.dev/teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gz
     $ tar -xzf teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gz
     $ cd teleport
     $ sudo ./install
     Teleport binaries have been copied to /usr/local/bin
     ```

* To check that you can connect to your Teleport cluster, sign in with `tsh login`, then verify that you can run `tctl` commands using your current credentials. For example, run the following command, assigning teleport.example.com to the domain name of the Teleport Proxy Service in your cluster and email\@example.com to your Teleport username:
  ```
  $ tsh login --proxy=teleport.example.com --user=email@example.com
  $ tctl status
  Cluster  teleport.example.com
  Version  18.7.3
  CA pin   sha256:abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678
  ```
  If you can connect to the cluster and run the `tctl status` command, you can use your current credentials to run subsequent `tctl` commands from your workstation. If you host your own Teleport cluster, you can also run `tctl` commands on the computer that hosts the Teleport Auth Service for full permissions.

Before you get started you’ll need a running Teleport Enterprise or Cloud cluster on version `11.3.1` or greater.

Login Rules only operate on SSO logins, so make sure you have configured an OIDC, SAML, or GitHub connector before you begin. Check the [Single Sign-On](https://goteleport.com/docs/zero-trust-access/sso.md) docs to learn how to set this up.

## Step 1/5. Configure RBAC

First, ensure you are logged into Teleport as a user that has permissions to read and modify `login_rule` resources. The preset `editor` role has access to this already, but in case you are using a more customized configuration, create a role called `loginrule-manager.yaml` with the following contents:

```
kind: role
metadata:
  name: loginrule-manager
spec:
  allow:
    rules:
      - resources: [login_rule]
        verbs: [list, create, read, update, delete]
version: v7

```

Create the role with `tctl`:

```
$ tctl create loginrule-manager.yaml
role 'loginrule-manager' has been created
```

---

TIP

You can also create and edit roles using the Web UI. Go to **Access -> Roles** and click **Create New Role** or pick an existing role to edit.

---

Assign the `loginrule-manager` role to your Teleport user by running the appropriate commands for your authentication provider:

**Local User**

1. Retrieve your local user's roles as a comma-separated list:

   ```
   $ ROLES=$(tsh status -f json | jq -r '.active.roles | join(",")')
   ```

2. Edit your local user to add the new role:

   ```
   $ tctl users update $(tsh status -f json | jq -r '.active.username') \
     --set-roles "${ROLES?},loginrule-manager"
   ```

3. Sign out of the Teleport cluster and sign in again to assume the new role.

**GitHub**

1. Open your `github` authentication connector in a text editor:

   ```
   $ tctl edit github/github
   ```

2. Edit the `github` connector, adding `loginrule-manager` to the `teams_to_roles` section.

   The team you should map to this role depends on how you have designed your organization's role-based access controls (RBAC). However, the team must include your user account and should be the smallest team possible within your organization.

   Here is an example:

   ```
     teams_to_roles:
       - organization: octocats
         team: admins
         roles:
           - access
   +       - loginrule-manager

   ```

3. Apply your changes by saving and closing the file in your editor.

4. Sign out of the Teleport cluster and sign in again to assume the new role.

**SAML**

1. Retrieve your `saml` configuration resource:

   ```
   $ tctl get --with-secrets saml/mysaml > saml.yaml
   ```

   Note that the `--with-secrets` flag adds the value of `spec.signing_key_pair.private_key` to the `saml.yaml` file. Because this key contains a sensitive value, you should remove the saml.yaml file immediately after updating the resource.

2. Edit `saml.yaml`, adding `loginrule-manager` to the `attributes_to_roles` section.

   The attribute you should map to this role depends on how you have designed your organization's role-based access controls (RBAC). However, the group must include your user account and should be the smallest group possible within your organization.

   Here is an example:

   ```
     attributes_to_roles:
       - name: "groups"
         value: "my-group"
         roles:
           - access
   +       - loginrule-manager

   ```

3. Apply your changes:

   ```
   $ tctl create -f saml.yaml
   ```

4. Sign out of the Teleport cluster and sign in again to assume the new role.

**OIDC**

1. Retrieve your `oidc` configuration resource:

   ```
   $ tctl get oidc/myoidc --with-secrets > oidc.yaml
   ```

   Note that the `--with-secrets` flag adds the value of `spec.signing_key_pair.private_key` to the `oidc.yaml` file. Because this key contains a sensitive value, you should remove the oidc.yaml file immediately after updating the resource.

2. Edit `oidc.yaml`, adding `loginrule-manager` to the `claims_to_roles` section.

   The claim you should map to this role depends on how you have designed your organization's role-based access controls (RBAC). However, the group must include your user account and should be the smallest group possible within your organization.

   Here is an example:

   ```
     claims_to_roles:
       - name: "groups"
         value: "my-group"
         roles:
           - access
   +       - loginrule-manager

   ```

3. Apply your changes:

   ```
   $ tctl create -f oidc.yaml
   ```

4. Sign out of the Teleport cluster and sign in again to assume the new role.

## Step 2/5. Draft your Login Rule resource

The following example will give all users a new `logins` trait set to the value of their current `username` trait converted to lowercase. Copy this example rule to a file called `my_rule.yaml` to continue with the guide.

```
# my_rule.yaml
kind: login_rule
version: v1
metadata:
  # Each Login Rule must have a unique name within the cluster.
  name: my_rule

  # expires is optional and usually should not be set for deployed login
  # rules, but it can be useful to set an expiry a short time in the future
  # while testing new Login Rules to prevent potentially locking yourself out of
  # your Teleport cluster.
  # expires: "2023-01-31T00:00:00-00:00"
spec:
  # priority orders the evaluation of Login Rules if multiple are present in the
  # cluster, lower priorities are evaluated first.
  priority: 0

  # traits_expression is a predicate expression which will be evaluated to
  # determine the final traits for each SSO user during login.
  #
  # This example expression sets the "logins" trait to the incoming "username"
  # trait converted to lowercase.
  traits_expression: 'external.put("logins", strings.lower(external["username"]))'

```

Each Login Rule resource must have either a `traits_map` or `traits_expression` field. In this guide we will use an example `traits_expression`.

The `traits_expression` is a form of script which will be evaluated by your Teleport cluster at runtime to determine the traits for each SSO user who logs in. The expression can access the incoming traits for the user via the `external` variable. The `external` variable is a dictionary which maps trait keys to sets of values for that trait.

## Step 3/5. Test the Login Rule

The `tctl login_rule test` command can be used to experiment with new Login Rules to check their syntax and see exactly how they will operate on example incoming traits.

Fetch your user's current traits and store them in `input.json`, then test your new Login Rule with that input.

```
$ tctl get --format json users/username | jq 'first.spec.traits' > input.json
$ tctl login_rule test --resource-file my_rule.yaml input.json
access:
- staging
groups:
- dbs
- devs
logins:
- alice
```

This script will catch any syntax errors in your expressions. Make sure that all expected traits are present in the output.

## Step 4/5. Create the Login Rule

Use the following command to create the Login Rule in your cluster:

```
$ tctl create my_rule.yaml
```

## Step 5/5. Try it out

As a final step, log out of your cluster, then log in again and make sure your user received the expected traits and roles. You can check the traits and roles with the following command:

```
$ tctl get --format json users/username | jq '{traits: first.spec.traits, roles: first.spec.roles}'
{
  "traits": {
    "access": [
      "staging"
    ],
    "groups": [
      "dbs",
      "devs"
    ],
    "logins": [
      "alice"
    ]
  },
  "roles": [
    "access",
    "editor",
    "auditor"
  ]
}
```

## Troubleshooting

The [`tctl sso test`](https://goteleport.com/docs/reference/cli/tctl.md) command can be used to debug SSO logins and see exactly which traits are being sent by your SSO provider and how they are being mapped by your Login Rules.

`tctl sso test` expects a connector spec. Run the following command to debug with a connector currently installed in your cluster, replacing SSO connector name with the name of the SSO connector you registered with Teleport:

```
$ tctl get connector/SSO connector name --with-secrets | tctl sso test
```

## Next steps

To learn more about the Login Rule expression syntax, check out the [Login Rule Reference](https://goteleport.com/docs/reference/access-controls/login-rules.md) page.

Learn about the `tctl login_rule test` command by running the help command or checking the [reference page](https://goteleport.com/docs/reference/cli/tctl.md).

```
$ tctl help login_rule test
```

The following `tctl` resource commands are helpful for viewing and modifying the login rules currently installed in your cluster.

| Command                           | Description                                     |
| --------------------------------- | ----------------------------------------------- |
| `tctl get login_rules`            | Show all Login Rules installed in your cluster. |
| `tctl get login_rule/<rule_name>` | Get a specific installed Login Rule.            |
| `tctl create login_rule.yaml`     | Install a new Login Rule.                       |
| `tctl create -f login_rule.yaml`  | Overwrite an existing Login Rule.               |
| `tctl rm login_rule/<rule_name>`  | Delete a Login Rule.                            |

## Example Login Rules

### Using an OIDC provider with arbitrary non-standard JSON claims

Standard OIDC claims consist of string values and lists. However, it is also possible to have provider that returns non-standard JSON claims. By default, Teleport will not attempt to read these claims for `claims_to_roles` mappings or for the user's Teleport traits.

For example, imagine a custom distributed IdP that aggregates claims for a user from multiple different provider sources. The claims set might look like a JSON object of the following format:

```
{
  "aggregated_claims": {
    "okta": {
      "groups": "okta_dev"
    },
    "auth0": {
      "groups": "auth0_devops"
    }
  }
}

```

The following JSONPath expression will take these claims and interpolate them into a standard groups claim:

```
kind: login_rule
version: v1
metadata:
  name: set_logins
spec:
  priority: 1
  traits_expression: |
    external.put("groups", jsonpath("$.aggregated_claims.*.groups"))

```

A user logging in with the claims and login rule above will be treated as if they have the following claims:

```
{
  "groups": [
    "okta_dev", 
    "auth0_devops"
  ]
}

```

These interpolated claims can be used in claims to roles mappings, and they are kept as Teleport traits like any standard claims would be.

### Set a trait to a static list of values defined per group

```
kind: login_rule
version: v1
metadata:
  name: example
spec:
  priority: 0
  traits_expression: |
    external.put("allow-env",
      choose(
        option(external.group.contains("dev"), set("dev", "staging")),
        option(external.group.contains("qa"), set("qa", "staging")),
        option(external.group.contains("admin"), set("dev", "qa", "staging", "prod")),
        option(true, set()),
      ))

```

### Use only specific traits provided by the OIDC/SAML provider

To only keep the `groups` and `email` traits, with their original values:

```
kind: login_rule
version: v1
metadata:
  name: example
spec:
  priority: 0
  traits_map:
    groups:
      - external.groups
    email:
      - external.email

```

### Remove a specific trait

To remove a specific trait and keep the rest:

```
kind: login_rule
version: v1
metadata:
  name: example
spec:
  priority: 0
  traits_expression: |
    external.remove("big-trait")

```

### Extend a specific trait with extra values

```
kind: login_rule
version: v1
metadata:
  name: example
spec:
  priority: 0
  traits_expression: |
    external.add_values("logins", "ubuntu", "ec2-user")

```

### Use the output of one Login Rule in another rule

```
kind: login_rule
version: v1
metadata:
  name: set_groups
spec:
  priority: 0
  traits_expression: |
    external.put("groups",
      ifelse(external.groups.contains("admins"),
        external["groups"].add("superusers"),
        external["groups"]))
---
kind: login_rule
version: v1
metadata:
  name: set_logins
spec:
  priority: 1
  traits_expression: |
    ifelse(external.groups.contains("superusers"),
      external.add_values("logins", "root"),
      external)

```
