# Policies

Policies in Vault control what a user can access. In the Authentication tutorial, you learned about *authentication* methods. This section is about *authorization*.

For authentication Vault has multiple options or methods that can be enabled and used. Vault always uses the same format for both authorization and policies. All auth methods map identities back to the core policies that are configured with Vault.

### Policy Format <a href="#policy-format" id="policy-format"></a>

Policies are authored in [HCL](https://github.com/hashicorp/hcl), but are JSON compatible. Here is an example policy:

```hcl
# Dev servers have version 2 of KV secrets engine mounted by default, so will
# need these paths to grant permissions:
path "secret/data/*" {
  capabilities = ["create", "update"]
}

path "secret/data/foo" {
  capabilities = ["read"]
}
```

The example policy grants capabilities for a KV version 2 secrets engine. If you are unfamiliar with the paths related to this secrets engine, consult the ACL Rules section of the secrets engine documentation.

With this policy, a user could write any secret to `secret/data/`, except to `secret/data/foo`, where only read access is allowed. Policies default to deny, so any access to an unspecified path is not allowed.

The policy format uses a prefix matching system on the API path to determine access control. The most specific defined policy is used, either an exact match or the longest-prefix glob match. Since everything in Vault must be accessed via the API, this gives strict control over every aspect of Vault, including enabling secrets engines, enabling auth methods, authenticating, as well as secret access.

There are some built-in policies that cannot be removed. For example, the `root` and `default` policies are required policies and cannot be deleted. The `default` policy provides a common set of permissions and is included on all tokens by default. The `root` policy gives a token super admin permissions, similar to a root user on a Linux machine.

View the `default` policy.

```shell-session
$ vault policy read default
```

### Write a Policy <a href="#write-a-policy" id="write-a-policy"></a>

To write a policy, use `vault policy write` command. Review the command help.

```shell-session
$ vault policy write -h

Usage: vault policy write [options] NAME PATH

  Uploads a policy with name NAME from the contents of a local file PATH or
  stdin. If PATH is "-", the policy is read from stdin. Otherwise, it is
  loaded from the file at the given path on the local disk.

  Upload a policy named "my-policy" from "/tmp/policy.hcl" on the local disk:

      $ vault policy write my-policy /tmp/policy.hcl

  Upload a policy from stdin:

      $ cat my-policy.hcl | vault policy write my-policy -

   ...snip...
```

Create the policy named `my-policy` with the contents from stdin.

```shell-session
$ vault policy write my-policy - << EOF
# Dev servers have version 2 of KV secrets engine mounted by default, so will
# need these paths to grant permissions:
path "secret/data/*" {
  capabilities = ["create", "update"]
}

path "secret/data/foo" {
  capabilities = ["read"]
}
EOF
```

**Successful output example:**

```plaintext
Success! Uploaded policy: my-policy
```

List all the policies.

```shell-session
$ vault policy list

default
my-policy
root
```

View the contents of the `my-policy` policy.

```shell-session
$ vault policy read my-policy

# Dev servers have version 2 of KV secrets engine mounted by default, so will
# need these paths to grant permissions:
path "secret/data/*" {
  capabilities = ["create", "update"]
}

path "secret/data/foo" {
  capabilities = ["read"]
}
```

### Test the Policy <a href="#test-the-policy" id="test-the-policy"></a>

The policy you created provides limited management of secrets defined for the KV-V2 secrets engine. Policies are attached to tokens that Vault generates directly or through its various auth methods.

Create a token, add the `my-policy` policy, and set the token ID as the value of the `VAULT_TOKEN` environment variable for later use.

```shell-session
$ export VAULT_TOKEN="$(vault token create -field token -policy=my-policy)"
```

{% hint style="info" %}
For this tutorial using a dev mode server, a token is created directly from the token auth method for simplicity. Keep in mind that in most production deployments, the token will be returned by an enabled auth method instead.
{% endhint %}

You can validate that the token ID was exported properly, and has the correct policies attached.

```shell-session
$ vault token lookup | grep policies
policies            [default my-policy]
```

The policy enables the create and update capabilities for every path within the `secret/` engine except one.

Write a secret to the path `secret/data/creds`.

```shell-session
$ vault kv put -mount=secret creds password="my-long-password"
== Secret Path ==
secret/data/creds

======= Metadata =======
Key              Value
---              -----
created_time     2023-11-12T18:05:42.537496856Z
deletion_time    n/a
destroyed        false
version          1
```

{% hint style="info" %}
When you access a KV v2 secrets engine using the `vault kv` CLI commands, we recommend using the `-mount` flag syntax (e.g. `vault kv get -mount=secret foo`) to reference the path to the KV v2 secrets engine. If you use the KV v1-like path prefix syntax (e.g. `vault kv get secret/foo`), `/data` will be automatically appended to the secret path, which may cause confusion.
{% endhint %}

The secret is created successfully.

The policy only enables the read capability for the `secret/data/foo` path. An attempt to write to this path results in a "permission denied" error.

Attempt to write to the `secret/data/foo` path.

```shell-session
$ vault kv put -mount=secret foo robot=beepboop

Error writing data to secret/data/foo: Error making API request.

URL: PUT http://localhost:8200/v1/secret/data/foo
Code: 403. Errors:

* 1 error occurred:
  * permission denied
```

The permission error is displayed.

This policy defines a limited set of paths and capabilities. Without access to `sys`, commands like `vault policy list` or `vault secrets list` will not work.

### Associate Policies to Auth Methods <a href="#associate-policies-to-auth-methods" id="associate-policies-to-auth-methods"></a>

Vault itself is the single policy authority, unlike authentication where you can enable multiple auth methods.

You can configure auth methods to automatically assign a set of policies to tokens created by authenticating with certain auth methods. The way this is done differs depending on the related auth method, but typically involves mapping a role to policies or mapping identities or groups to policies.

For example, you can achieve this with the `token_policies` parameter when configuring a role for the AppRole auth method.

Use a higher privileged token for the following steps. For a dev mode server you can specify the token ID that is output when you start the server or the one that you set with the `-dev-root-token-id=` flag. For example, if `-dev-root-token-id=root`, the following exports the correct root token ID.

```shell-session
$ export VAULT_TOKEN=root
```

First, check to verify that approle auth method has not been enabled at the path `approle/`.

```shell-session
$ vault auth list | grep 'approle/'
```

If this command produces no output (i.e. `approle/` is **not** listed), enable it before proceeding.

```shell-session
$ vault auth enable approle
```

**Successful output example**

```mdx-code-blocks_codeBlockMargin__TI7B4
Success! Enabled approle auth method at: approle/
```

Enable an AppRole role named "my-role", to configure some basic token options and to attach the previously defined "my-policy" policy to all tokens that it creates when applications authenticate with the role.

```shell-session
$ vault write auth/approle/role/my-role \
    secret_id_ttl=10m \
    token_num_uses=10 \
    token_ttl=20m \
    token_max_ttl=30m \
    secret_id_num_uses=40 \
    token_policies=my-policy
```

**Successful output example:**

```plaintext
Success! Data written to: auth/approle/role/my-role
```

You can validate that this AppRole role is attaching the policy by authenticating with the auth method.

To authenticate with AppRole, first fetch the role ID, and capture its value in a ROLE\_ID environment variable.

```shell-session
$ export ROLE_ID="$(vault read -field=role_id auth/approle/role/my-role/role-id)"
```

Next, get a secret ID (which is similar to a password for applications to use for AppRole authentication), and capture its value in the SECRET\_ID environment variable.

```shell-session
$ export SECRET_ID="$(vault write -f -field=secret_id auth/approle/role/my-role/secret-id)"
```

Finally, authenticate to AppRole with `vault write` by specifying the role path and passing the role ID and secret ID values with the respective options.

```shell-session
$ vault write auth/approle/login role_id="$ROLE_ID" secret_id="$SECRET_ID"
```

**Successful output example:**

```plaintext
Key                     Value
---                     -----
token                   s.Sh9h1wZ9ycATeSaASoOQvovr
token_accessor          xCgUIu6WWLM9opkEkAiNLsRc
token_duration          20m
token_renewable         true
token_policies          ["default" "my-policy"]
identity_policies       []
policies                ["default" "my-policy"]
token_meta_role_name    my-role
```

Note that "my-policy" policy is contained in the policies and token\_policies fields.

About policy fields

As shown in the example output, the token has three similarly named fields, **policies**, **identity\_policies**, and **token\_policies**. The difference in these fields is that token\_policies represent all policies attached to the token by auth methods, and identity\_policies represents all policies attached to the token by the Identity secrets engine. The policies field is a correlation of identity\_policies and token\_policies to show you all available policies for a given token. To learn more, refer to the Identity: Entities and Groups tutorial after completing the Getting Started tutorials.

### Next <a href="#next" id="next"></a>

Policies are an important part of Vault. While using the root token is easiest to get up and running, you will want to restrict access to Vault very quickly, and the policy system is the way to do this.

The syntax and function of policies is easy to understand and work with, and because auth methods all must map to the central policy system, you only have to learn this policy system.

You will learn how to create a Vault server configuration file to customize the server settings.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.enclaive.cloud/vault/tutorials/cli/access-control/policies.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
