---
url: /en/repo/secret.md
---
A KeyStore is a **high-security code repository** provided by `Cloud Native Build`, specifically designed for storing and managing sensitive information like passwords, API keys, certificates, tokens, etc.
It employs multiple security mechanisms—strict access controls, operational restrictions, audit logs, and watermarks—to ensure the secure storage and compliant usage of sensitive data throughout its entire lifecycle.

## Create a KeyStore

1. **Go to the Creation Page**
   Log in to your account and [click here to go to the repository creation page](https://cnb.cool/new/repos).

2. **Select Repository Type and Fill in Info**
   Under repository type, be sure to select **`KeyStore`**, and fill in the corresponding repository name and description.

   ![Create KeyStore](/images/keystore/create-keystore.en.png)

3. **Complete Creation**
   Click the create button to complete the setup of your KeyStore.

## Core Features

### 1. Operational Restrictions

For enhanced security, KeyStores have strict operational restrictions compared to standard repositories:

| Capability               | Standard Repo | KeyStore | Description |
| :----------------------- | :------------ | :------- | :---------- |
| Git Clone to Local       | ✅             | ❌        | **Prevents** downloading sensitive data to an uncontrolled local environment. |
| Push Code from Local     | ✅             | ❌        | **Prevents** pushing changes from local, mitigating introduction risks. |
| Edit Files via Web UI    | ✅             | ✅        | All changes must be made through the audited Web interface. |
| Create Branches/Tags/PRs | ✅             | ✅        | Supports code management within a controlled scope. |
| Reference in Pipelines   | ✅             | ✅        | Core functionality: enables secure use of secrets within pipelines. |

### 2. Security Enhancements

* **Dynamic Watermark**: Automatically adds a semi-transparent watermark with the current username on all pages, effectively preventing screenshot leaks and enabling accountability tracing.
* **Comprehensive Audit Logs**: Records all access and reference events for files in this repository (e.g., when and by which pipeline), supporting full traceability.
* **Web-Only Operations**: File editing is exclusively supported on the platform's Web interface, fundamentally eliminating leakage risks from local environments.
* **Strict Permission Controls**: Adheres to the system's unified [Role Permissions Model](../guide/role-permissions.md) for fine-grained access management.
* **Declarative Access Scope**: Allows precise control over the conditions under which secret files can be referenced via configuration. See the [Permission Checks](../build/file-reference.md#permission-checks) rules in pipeline file reference for details.

## Reference in Pipelines

### 1. Store Secret Files

Within a KeyStore, it's common to use `YAML` or `JSON` files to store secrets in a structured way.

```yaml title="env.prod.yml"
# Production environment secrets
DOCKER_USER: "prod_username"
DOCKER_TOKEN: "prod_token_123456"
DOCKER_REGISTRY: "registry.prod.com"
```

```yaml title="env.dev.yml"
# Development/Test environment secrets
DOCKER_USER: "dev_username"
DOCKER_TOKEN: "dev_token_123456"
DOCKER_REGISTRY: "registry.dev.com"
```

### 2. Inject as Environment Variables

In your pipeline configuration (`.cnb.yml`), use the `imports` keyword to reference files from a KeyStore. Their contents are automatically injected as environment variables for pipeline tasks.

```yaml title=".cnb.yml"
main:
  push:
    - services:
        - docker
      imports:
        # Reference the specific file from the KeyStore
        - https://cnb.share.ralphlauren.cn/<your-repo-slug>/-/blob/main/env.prod.yml
      stages:
        - name: Build and Push Image
          script: |
            # Injected environment variables can be used directly in the script
            echo "Logging into the container registry..."
            docker login -u $DOCKER_USER -p "$DOCKER_TOKEN" $DOCKER_REGISTRY
            echo "Building image..."
            docker build -t $DOCKER_REGISTRY/$CNB_REPO_SLUG_LOWERCASE:latest .
            echo "Pushing image..."
            docker push $DOCKER_REGISTRY/$CNB_REPO_SLUG_LOWERCASE:latest
```

### 3. Reference Authorization & Scope Control

* **Default Permissions**: By default, only pipelines triggered by members with **Admin** or **Owner** roles for the KeyStore are authorized to reference its files.
* **Broadening Permissions & Fine-Grained Control**: To allow pipelines triggered by a broader range of members (e.g., regular developers) to reference the files, you must declare `allow_*` fields in the secret file for **fine-grained authorization**, for example:
  * `allow_slugs`: Restrict which repositories' pipelines can reference this file.
  * `allow_events`: Restrict which events (e.g., `tag_push`) can trigger a pipeline that references this file.
  * `allow_branches`: Restrict which branches (e.g., `main`, `prod`) can reference this file in their pipelines.
  * `allow_images`: Restrict which specific plugin tasks (by image) can reference this file.

    **Important Note**: Once `allow_*` rules are configured, the system **ignores the triggerer's role permissions** and instead validates solely based on these rules. All rules must pass for the reference to be allowed. For details, see [Permission Checks](../build/file-reference.md#permission-checks).

### 4. Preventing Leakage Within Pipelines

While the KeyStore itself is secure, remain vigilant about leakage risks within pipeline scripts once secrets are injected (e.g., accidentally printing environment variables to logs).

**Protection Recommendations:**

1. **Secure the Pipeline Configuration Itself**: Store pipeline configurations containing `imports` references in a **separate, access-controlled repository**. Other project repositories can then use `include` to reference them. This limits who can modify the pipeline logic.
2. **Use Protected Branches**: Combine with `allow_branches` rules in the secret file to restrict usage to **protected branches**. Changes to protected branches require a Pull Request and **code review**, adding a layer of manual audit.
3. **Audit and Log Monitoring**: Regularly check pipeline logs for unusual activity.

## Best Practices

1. **Isolation and Categorization**
   * **Environment Isolation**: Create different KeyStores or files for different environments like production (`prod`), staging, and development/testing (`dev`).
   * **Project Isolation**: Use separate KeyStores for different projects or applications to isolate permissions and impact.
   * **Centralized Management**: Consider managing all KeyStores within a dedicated top-level organization, strictly limiting membership.

2. **Principle of Least Privilege**
   * **Role Control**: Assign KeyStore **Admin** and **Owner** roles judiciously, following the "need-to-know" principle.
   * **Scope Control**: Actively use the `allow_*` configurations to declare the **minimal allowed scope** for each secret file, avoiding over-permissioning.
     * `allow_slugs`: Limit which projects can reference it.
     * `allow_events`: Limit triggering to deployment events (`tag_push`, `tag_deploy.*`), not every code push.
     * `allow_branches`: Limit usage to stable, protected branches.

3. **Reduce Configuration Leak Risk**
   * Encapsulate pipeline logic containing sensitive references in **controlled, shared configuration repositories** and provide them to other projects via `include`. This concentrates the core risk control points to a few repositories.

4. **Regular Rotation and Auditing**
   * **Secret Rotation**: Establish a routine for rotating secrets. Simply update the file content in the KeyStore's Web interface, and all pipelines referencing it will automatically get the new values.
   * **Permission Audits**: Regularly review audit logs, clean up invalid references and authorization rules, and promptly revoke access for members who have left or changed roles.
