# Give access to one bucket

Give a script or a service an access key that reaches one bucket only, through a service account with a policy for that bucket, or hand out a temporary key for a few hours.

What a key may do is decided by the policies of the IAM user or service account it acts as. A
long-lived access key carries no limit of its own. To give a script access to one bucket, give it
a service account whose only policy allows that bucket, and a key for that account. For a
credential narrower than yourself, for a few hours, create a temporary key for the bucket. Replace
_example-uploads_ with your bucket's name and _org-EXAMPLE1234_ with your organization's id.

## Prerequisites

- Permission for `iam:CreateAccessKey`, `iam:CreatePolicy` and `iam:AttachUserPolicy`, and
  `iam:CreateUser` for a new service account. Without `iam:CreateAccessKey` the bucket has no
  **Create access key** button.
- You may yourself do every action the policy hands out on the bucket. Otherwise the request is
  refused with `403` and nothing is created.
- In the console, `s3:GetBucket` to open the bucket.

## Create an access key for the bucket

The bucket's **Create access key** does three things in one step: it creates a service account
(or uses one you choose), attaches a policy that allows this bucket only to that account, and
creates a key for the account. The key itself carries no limit.

**Console**
1. Open **Object Storage**, open the bucket, then choose the **Access** tab.
2. Choose **Create access key**. The **Create access key for example-uploads** sheet opens.
   **Create access key** in the bucket's header opens the same sheet.
3. For **Service account**, keep **A new service account** and, for **Name**, keep
   `example-uploads-access` or enter another name. Or choose an existing service account.
4. Under **Access to this bucket**, choose **Read only** or **Read and write**. **Read and write**
   is chosen.
5. (Optional) For **Folder (prefix)**, enter a prefix, for example `incoming/` (no `*`). Listing
   still shows every object name in the bucket.
6. (Optional) For **Description**, enter what uses the key.
7. (Optional) Open **Show the policy (JSON)** to read the policy before it is created. It is named
   `s3-read-write-example-uploads` (`s3-read-example-uploads` for **Read only**).
8. Choose **Create access key**.

The panel shows the key ID and the secret, names the service account and the policy, and shows
**Connect a tool** with the setup for each S3 tool. The secret is shown only now.

**CLI**
```sh
dcloud s3 buckets create-access-key example-uploads --access readwrite \
  --description "uploads app"
```

`--service-account-name` names the new service account; `--service-account-id` gives the key to
an existing one instead. `--access read` gives read only, and `--prefix incoming/` limits the
policy to one prefix.

**API**
```http
POST /s3/api/buckets/example-uploads/access-keys
{ "access": "readwrite", "description": "uploads app" }
```

The body also takes `serviceAccountName` (a new account; default `<bucket>-access`) or
`serviceAccountId` (an existing one), `prefix` and `expiresInDays`. The answer is `201` with the
key (`accessKeyId`, `secretKey`, `expiresAt`), the `account` and the `policy` (`null` when the
account already had this access).

**Terraform**
```hcl
resource "dcloud_iam_user" "uploads" {
  username = "example-uploads-access"
  type     = "service_account"
}

resource "dcloud_iam_policy" "uploads" {
  name = "s3-read-write-example-uploads"
  document = jsonencode({
    Version = "2024-01-01"
    Statement = [
      {
        Effect   = "Allow"
        Action   = ["s3:GetBucket", "s3:ListObjects", "s3:ListBucketVersions", "s3:GetBucketVersioning"]
        Resource = ["rn:ews::org-EXAMPLE1234:s3:bucket/example-uploads"]
      },
      {
        Effect   = "Allow"
        Action   = ["s3:GetObject", "s3:GetObjectVersion", "s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload", "s3:DeleteObjectVersion"]
        Resource = ["rn:ews::org-EXAMPLE1234:s3:bucket/example-uploads/object/*"]
      },
    ]
  })
}

resource "dcloud_iam_user_policy_attachment" "uploads" {
  user_id   = dcloud_iam_user.uploads.id
  policy_id = dcloud_iam_policy.uploads.id
}

resource "dcloud_iam_access_key" "uploads" {
  iam_user_id = dcloud_iam_user.uploads.id
  description = "uploads app"
}
```

The secret is kept in the Terraform state; protect the state.

### The policy

| Access         | On the bucket                                                                       | On its objects (or the prefix)                                                              |
| -------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Read only      | `s3:GetBucket`, `s3:ListObjects`, `s3:ListBucketVersions`, `s3:GetBucketVersioning` | `s3:GetObject`, `s3:GetObjectVersion`                                                       |
| Read and write | the same                                                                            | also `s3:PutObject`, `s3:DeleteObject`, `s3:AbortMultipartUpload`, `s3:DeleteObjectVersion` |

For one prefix, the object resource ends with it:
`rn:ews::org-EXAMPLE1234:s3:bucket/example-uploads/object/incoming/*`. The policy is attached to
the account like any other policy and the attachment is recorded in the audit log. When the
account already has this access, no policy is attached again.

### Result

The key acts as the service account and can do what the account's policies allow: this bucket
only. S3 may take up to 30 seconds to see a newly attached policy, so the first requests can be
refused with `AccessDenied`. A key that reaches one bucket cannot list your buckets: `aws s3 ls`
answers `AccessDenied`. Name the bucket in every command (`aws s3 ls s3://example-uploads/`), and
in tools that start from a bucket list (Cyberduck, S3 Browser), type the bucket in as the path.

## A temporary key for one bucket

A temporary key acts as you, narrowed to this bucket by a session policy, and expires on its own.
It is the way to get a credential narrower than an account: it can do only what you may do
yourself, within this bucket. It needs `s3:CreateTemporaryCredentials`.

**Console**
1. Open **Object Storage**, open the bucket, then choose the **Access** tab.
2. Choose **Temporary key**.
3. Under **Valid for**, choose **1 hour**, **4 hours** or **12 hours**.
4. Under **Access to this bucket**, choose **Read only** or **Read and write**. **Read only** is
   chosen.
5. (Optional) For **Folder (prefix)**, enter a prefix, for example `incoming/`.
6. Choose **Create temporary key**.

The sheet shows the **Access key ID**, the **Secret** and the **Session token**, with an
**AWS CLI profile** for them. They are shown only now.

**CLI**
```sh
dcloud s3 buckets temporary-key example-uploads --hours 4
```

**API**
```http
POST /s3/api/buckets/example-uploads/temporary-credentials
{ "hours": 4, "access": "read" }
```

`hours` is 0.25 to 12 and defaults to 1; `access` is `read` (the default) or `readwrite`; `prefix`
and `description` are optional. The answer is `201` with `accessKeyId`, `secretAccessKey`,
`sessionToken` and `expiresAt`. When your own policies allow nothing of what you ask for, the
request is refused with `409`.

**Terraform:** not available. A key that expires within hours is not configuration.

Set all three values in the client; every request carries the session token. See
[Create temporary credentials](create-temporary-credentials.md).

## See who can reach a bucket

The bucket's **Access** tab lists everything that can reach the bucket, evaluated as the storage
gateway evaluates a request:

- **Users, service accounts and roles** whose policies, or the bucket policy, let them list, read
  or write the bucket: what each may do, the policy that allows it, how that policy reaches them
  (attached directly, through a group or through a role), and whether it allows every bucket or
  this bucket. When only principals whose policies allow every bucket reach it, the tab says that
  only the organization's administrators reach the bucket.
- **Legacy limited keys** limited to this bucket, and whether each can still reach it.
- **Other ways in**, one line each: temporary credentials alive now, public access, the website
  and the bucket policy.

The same view from the CLI and the API:

```sh
dcloud s3 buckets access example-uploads
```

```http
GET /s3/api/buckets/example-uploads/access
```

The list of keys needs `iam:ListAccessKeys`, the principals and temporary credentials need
`iam:ListUsers`, and the bucket policy needs `s3:GetBucketPolicy`. A part you may not read is
left out and named.

## Keys with a limit (legacy)

Keys created before long-lived keys stopped carrying a limit keep it. The limit is still enforced
and never widened: such a key can do what its account's policies allow, and only within its
limit. A limit never grants access. A key limited to a bucket whose account has no policy for
that bucket is refused on every request.

The console marks these keys as legacy limited keys. **Identity** › **Access keys** lists them
under **Legacy limited keys**, each with what it can do today, and a bucket's **Access** tab lists
those limited to that bucket.

**Migrate** replaces one such key. It creates a dedicated service account whose one policy is what
the key could actually do (the account's policies narrowed by the key's limit, with every `Deny`
kept), and a new key for it, shown once. Put the new key where the old one is used. The old key
keeps working and is switched off, not deleted, once it has gone unused for 7 days after the
migration. Migrating needs `iam:CreateUser`, `iam:CreatePolicy`, `iam:AttachUserPolicy` and
`iam:CreateAccessKey`.

**Console**
1. Open **Identity**, then choose **Access keys**.
2. Under **Legacy limited keys**, find the key. It shows what Migrate creates: the service account
   and the policy, with the policy's JSON.
3. Choose **Migrate**.
4. Copy the new key ID and secret. This is the only time the secret is shown.

**CLI**
```sh
dcloud iam access-keys legacy-limits
dcloud iam access-keys migrate key-id
```

**API**
```http
GET /iam/api/access-keys/legacy-limits
```

```http
POST /iam/api/access-keys/key-id/migrate
```

`legacy-limits` changes nothing: it lists each key with what it can do and what migrating it would
create. A key that can do nothing has nothing to migrate; delete it.

**Terraform:** not available. Migrating replaces a key once; it is not configuration.

Keys the platform makes for its own purposes, such as Error Tracking tokens and cloud shell keys,
keep their limits and are not listed.

## Related

- [Create an access key](create-an-access-key.md)
- [Create temporary credentials](create-temporary-credentials.md)
- [Access control](access-control.md)
- `dcloud s3 buckets create-access-key` · `dcloud s3 buckets temporary-key` · `dcloud s3 buckets access`
- `dcloud_iam_user` · `dcloud_iam_policy` · `dcloud_iam_user_policy_attachment` · `dcloud_iam_access_key`
