# Secure an existing project

For a project people already use. The order avoids breaking anything for them: turn on checks that only report, fix what they find, then make them block. Risky steps say what can break and how to undo it.

Source: https://ha-barkley.github.io/security/walk-throughs/existing-project/

From HASC, the Home Assistant Security Controls for integrations, cards and apps. A community catalog, not an official Home Assistant or Open Home Foundation project.

Each control has an ID, cited as HASC-CI-4, and a level from 1 to 3. "Level marker" means anyone can check the control from outside the project, and levels are graded on those controls only.

## Your answers

Some steps depend on these answers. Those steps say which answer they're for.

- What is it? "An integration", "A dashboard card" or "An app (add-on)"
- Where does the repository live? "My own account" or "An organization with a security configuration"

## Turn on the checks that only report

None of these blocks anything yet. They show you what's already there, so you can fix it before anything starts failing.

### Apply your organization's configuration to this repository

*Level 1 · Only for: An organization with a security configuration*

A repository that was moved into the organization doesn't get it automatically. On the organization's Settings → Advanced Security → Configurations page, open the Repositories tab and select this repository's checkbox. Then choose Apply configuration, pick your configuration, and choose Apply.

**What can break:** Push protection starts rejecting pushes that contain a token it recognizes.

### POL-1: Turn on private vulnerability reporting

*Level 1 · Only for: My own account*

Settings → Advanced Security → Private vulnerability reporting → Enable. People then get a "Report a vulnerability" button on your Security and quality tab, and their report reaches you privately. You can ask questions, reject it, or accept it as a draft advisory to work in.

### CI-1: Turn on CodeQL default setup

*Level 1 (or a security workflow) · Level marker · Only for: My own account*

Settings → Advanced Security → Code scanning → CodeQL analysis → Set up → Default. It picks up Python, JavaScript and TypeScript, and runs on every pull request. Check that GitHub Actions is in its list of languages too, because that's the language that scans your workflow files, and default setup doesn't always include it. If it's missing, choose View CodeQL configuration, then Edit, select GitHub Actions under Languages, and choose Save changes.

### CI-3: Turn on secret scanning and push protection

*Level 1 · Only for: My own account*

Settings → Advanced Security. Push protection stops a push that contains a known token format before it reaches GitHub.

**What can break:** A push that contains a token GitHub recognizes is rejected. If it's a test value, you can bypass the block and give a reason. If it's real, revoke it, as the next phase describes.

**To undo:** Turn push protection off on the same page.

### CI-2: Turn on Dependabot alerts and security updates

*Level 1 · Level marker*

**Turn on Dependabot alerts and security updates** in the same Settings page, then add version updates for your package files and your workflow actions.

`.github/dependabot.yml`

```
version: 2
updates:
  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
  - package-ecosystem: "npm"        # cards: package.json and its lockfile
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
```

Dependabot doesn't read an integration's `manifest.json`. The workflow below checks those requirements with pip-audit instead.

`cooldown` makes Dependabot wait until a release is 7 days old before proposing it. It only delays version updates; security updates still arrive straight away.

**What can break:** Nothing breaks, but expect several pull requests in the first week. They're only proposals until you merge them.

**To undo:** Delete `.github/dependabot.yml` to stop version updates.

### DEP-4: Wait at least 7 days before taking a new release

*Level 1*

**Why:** Malicious versions are usually found and removed fast. npm removed the September 2025 phishing versions the same day, and TanStack's within about four and a half hours. With a 7-day cooldown, Dependabot only offers a release once it has been public for a week, so versions like these have been removed before it offers them ([how it happened](https://ha-barkley.github.io/security/attacks/#phishing)).

Set `cooldown: default-days: 7` in `dependabot.yml` (Dependabot waits 3 days if you set nothing), or `"minimumReleaseAge": "7 days"` in Renovate. Security updates aren't delayed.

## Add the files people look for

These change nothing for the people who use your app.

### POL-2: Add a SECURITY.md

*Level 1 · Level marker*

**Add a SECURITY.md** that points to it. In an organization, one `SECURITY.md` in its public `.github` repository covers every repository that doesn't have its own (see [Organizations](https://ha-barkley.github.io/security/controls/organizations/)).

`SECURITY.md`

```
# Security policy

## Reporting a problem

Please don't open a public issue. Report it privately through
GitHub: https://github.com/OWNER/REPO/security/advisories/new

I'll reply within 7 days and keep you posted until it's fixed.

## Supported versions

Only the latest release gets security fixes.
```

### REPO-2: Turn off blank issues and link the private report

*Level 1*

`.github/ISSUE_TEMPLATE/config.yml`

```
blank_issues_enabled: false
contact_links:
  - name: Report a security problem
    url: https://github.com/OWNER/REPO/security/advisories/new
    about: Please report security problems privately, not as an issue.
```

### REPO-1: Add a bug report form

*Level 1*

`.github/ISSUE_TEMPLATE/bug_report.yml`

```
name: Bug report
description: Something isn't working
labels: [bug]
body:
  - type: input
    id: version
    attributes:
      label: App version
      placeholder: "1.4.2"
    validations:
      required: true
  - type: input
    id: ha-version
    attributes:
      label: Home Assistant version
      placeholder: "2026.11.2"
    validations:
      required: true
  - type: dropdown
    id: install
    attributes:
      label: Installation type
      options: [Home Assistant OS, Container, Other]
  - type: textarea
    id: what
    attributes:
      label: What happened, and what did you expect?
    validations:
      required: true
  - type: textarea
    id: logs
    attributes:
      label: Logs
      description: Remove tokens, passwords and addresses before pasting.
      render: shell
```

### REPO-5: List the servers your app talks to

*Level 1*

**List the servers your app talks to** in the README, and what it sends to each. Users can't see that from the dashboard.

### REPO-3: Add a .gitignore

*Level 1*

**Add a .gitignore** before your first commit.

`.gitignore`

```
# Python
__pycache__/
*.py[cod]
.venv/
.pytest_cache/
.ruff_cache/
.coverage

# Node
node_modules/

# Secrets and local settings
.env
.env.*
secrets.yaml
*.pem
*.key

# Editors and OS
.idea/
.DS_Store
```

**What can break:** Nothing, but a `.gitignore` doesn't remove files that are already committed. Run `git ls-files` and look for anything secret, such as `.env` or a key file.

## Fix what the checks find

Give the checks a few days, then work through the repository's Security and quality tab. Fix or dismiss what's there before the later phases make checks block, or every pull request will fail on old findings.

### SEC-5: If a secret leaks, revoke it first

*Level 1*

Removing it from the history doesn't help, because clones, forks and caches already have a copy. Issue a new key, then clean up the history.

> Do this first, for anything secret scanning found and anything secret in `git ls-files`.

### Work through the other alerts

*Level 1*

Update the packages Dependabot flags, and fix each code scanning alert or dismiss it with a reason. Close the Dependabot pull requests you don't want, and it won't propose that version again.

### DEP-3: Pin exact versions

*Level 1*

**Why:** With a range such as `>=2.0`, every new install takes whatever was published last, including a version published from a stolen account an hour ago. With an exact pin, a new version only reaches your users after you merge a pull request for it ([phished logins](https://ha-barkley.github.io/security/attacks/#phishing), [Shai-Hulud](https://ha-barkley.github.io/security/attacks/#shai-hulud)).

Use `==` in `manifest.json`, and commit the lockfile for a card. Dependabot proposes updates for a card's lockfile. For `manifest.json`, Renovate can do it with a custom manager, or pip-audit in CI tells you when a pinned version has a known vulnerability.

**What can break:** An integration's exact pin can clash with a version Home Assistant or another integration needs, and then Home Assistant can't install your integration's requirements. Test with the current Home Assistant release.

**To undo:** Loosen the pin and release again.

### DEP-1: Use what Home Assistant already ships first

*Level 1 · Applies to integrations · Only for: An integration*

**Why:** Each package you add is code from more people you have to trust, and one more account that can be taken over. Home Assistant already ships and updates the common ones, so using them doesn't add anyone new for your users to trust.

aiohttp, voluptuous and many device libraries are already installed. Don't list those in `requirements`. Home Assistant's own version wins, and a different pin can stop your integration from installing.

**What can break:** Your integration then uses Home Assistant's version of the package, which may differ from the one you tested with.

**To undo:** Put the requirement back.

### DEP-2: Check a package before you add it

*Level 1*

**Why:** Some packages are published under a name one letter away from a popular one, so that a typo installs them. Others change hands without anyone noticing. In 2018, someone posing as a maintainer took over event-stream and added code aimed at one bitcoin wallet app ([how it happened](https://ha-barkley.github.io/security/attacks/#event-stream)).

Look for a release in the last year, more than one maintainer, a linked source repository, and the exact spelling of the name.

### DEP-6: Replace dead packages

*Level 2*

**Why:** A package nobody maintains gets no security fixes, and nobody is watching when it changes hands.

If a library hasn't had a release in years and has open security reports, switch to a maintained one or take over a fork in the open.

## Review the integration's code

*Only for: An integration*

Change one thing per release, so a user who hits a problem can tell what changed.

### INT-1: Never fetch code at run time

*Level 1 · Applies to integrations*

Don't run `pip install` from inside the integration, and don't download a script and run it. List packages in `manifest.json` with exact versions, and Home Assistant installs them.

`manifest.json (part)`

```
"requirements": ["examplelib==2.4.1"]
```

**What can break:** If the code installed a package while it ran, that package now has to be in `manifest.json`, or the integration fails to load.

### INT-2: Keep the login on every page you add

*Level 1 · Applies to integrations*

`HomeAssistantView` requires a login unless you turn it off. Only turn it off when the situation calls for it and none of these safer options fits:

- For calls from a device or a cloud service, use a webhook. It uses an id nobody can guess and can be limited to the local network.
- For a link to something that can't log in, like a speaker playing a sound or an image in a notification, use a signed path from `async_sign_path`. The page keeps its login check, and the link expires.
- For signing in to a cloud account, use Home Assistant's OAuth2 config flow helper (`config_entry_oauth2_flow`), which provides the redirect page for you.
- For your card's or panel's JavaScript, use `hass.http.async_register_static_paths`. These files load without a login by design, so put code in them and keep data out.

`Do webhook for inbound calls`

```
from homeassistant.components import webhook

webhook.async_register(
    hass, DOMAIN, "Example device",
    entry.data[CONF_WEBHOOK_ID], handle_webhook,
    local_only=True,
)
```

`Don't a page with the login turned off for no reason`

```
class StatusView(HomeAssistantView):
    url = "/api/example/status"
    name = "api:example:status"
    requires_auth = False   # anyone on the network
```

If you do turn the login off, return nothing sensitive from that page, and check any token or signature yourself in the handler. Create a webhook id in the config flow with `webhook.async_generate_id()`.

**What can break:** Anything that called the page without logging in, such as a device or a phone app, now gets 401 Unauthorized. Move those callers to a webhook first.

**To undo:** Turn `requires_auth` off again for that view.

### INT-3: Save settings and state with the storage helper, and never with pickle

*Level 1 · Applies to integrations*

The helper writes JSON safely, versions it, and keeps it where backups find it. Loading a pickle file runs any code inside it, so anything that can write that file can run code in Home Assistant.

For other kinds of data: large or binary files (images, firmware, models) go in plain files in your own folder, many records you query go in SQLite, and history belongs in entities, which the recorder already keeps.

`__init__.py`

```
from homeassistant.helpers.storage import Store

store = Store(hass, 1, f"{DOMAIN}.cache")
data = await store.async_load() or {}
await store.async_save(data)
```

**What can break:** Users lose what the old file held unless you move it across. Read the old file once, save it with the storage helper, then delete it.

### INT-4: Use Home Assistant's shared web session

*Level 1 · Applies to integrations*

**Use Home Assistant's shared web session** with certificate checks on. Only offer "don't verify SSL" for local devices with self-signed certificates, and default it to off.

`coordinator.py`

```
from homeassistant.helpers.aiohttp_client import async_get_clientsession

session = async_get_clientsession(hass)
```

**What can break:** Devices with self-signed certificates stop connecting until their users turn on the option this step describes.

### INT-5: Avoid the calls that turn data into code

*Level 1 · Applies to integrations*

`pickle.load`, `eval`, `exec`, `yaml.load` without a safe loader, and `subprocess` with `shell=True`.

**What can break:** `yaml.safe_load` refuses Python-specific tags that `yaml.load` accepted. Files your own code wrote are usually fine.

### INT-6: Send each credential only to its own service

*Level 1 · Applies to integrations*

A Supervisor token goes to the Supervisor, a user's cloud token goes to that cloud, and nothing goes to your own server unless the README says so.

### SEC-1: Ask users for credentials in the config flow

*Level 1 · Applies to integrations*

**Ask users for credentials in the config flow,** with a password field, and read them from the config entry. Don't hard-code your own account's keys into the app.

`config_flow.py`

```
from homeassistant.helpers.selector import (
    TextSelector, TextSelectorConfig, TextSelectorType,
)

STEP_USER = vol.Schema({
    vol.Required(CONF_USERNAME): str,
    vol.Required(CONF_PASSWORD): TextSelector(
        TextSelectorConfig(type=TextSelectorType.PASSWORD)
    ),
})
```

**What can break:** Existing setups keep their credentials wherever they are now, such as `configuration.yaml`. Add an import step so they move into a config entry, or users have to set the integration up again.

### SEC-2: Redact diagnostics and keep secrets out of logs

*Level 1 · Applies to integrations*

Users paste diagnostics into public issues.

`diagnostics.py`

```
from homeassistant.components.diagnostics import async_redact_data

TO_REDACT = {CONF_PASSWORD, CONF_API_KEY, CONF_TOKEN, "serial_number"}

async def async_get_config_entry_diagnostics(hass, entry):
    return {"entry": async_redact_data(entry.as_dict(), TO_REDACT)}
```

## Review the card's code

*Only for: A dashboard card*

Change one thing per release, so a user who hits a problem can tell what changed.

### CARD-1: Bundle your libraries into the card

*Level 1 · Applies to cards*

**Bundle your libraries into the card** at build time instead of loading them from a CDN when the card runs.

`Do bundled at build time`

```
import { formatDistance } from "date-fns";
```

`Don't loaded at run time`

```
const lib = await import(
  "https://cdn.example.com/lib@latest/index.js"
);
```

**What can break:** The card file gets bigger, because the library is now inside it.

### CARD-2: Keep the login token where it is

*Level 1 · Applies to cards*

Talk to Home Assistant through the card's own connection. For an outside service, put the call in an integration and have the card ask the integration.

`Do the card's own connection`

```
const states = await this.hass.callWS({
  type: "get_states",
});
```

`Don't send the token anywhere`

```
fetch(url, { headers: {
  Authorization: `Bearer ${this.hass.auth.data.access_token}`,
}});
```

**What can break:** Calls the card made to an outside service stop working until an integration makes them for it.

### CARD-3: Render with Lit templates, not innerHTML

*Level 1 · Applies to cards*

Entity names and attributes come from devices and other apps. Lit escapes them. `innerHTML` turns them into live HTML, and an attribute such as `onerror` can run script with the user's login.

**What can break:** Text that used to render as HTML, such as a formatted attribute, now shows as plain text.

### CARD-4: Keep build tools current

*Level 2 · Applies to cards*

**Keep build tools current,** commit the lockfile, and build with `npm ci`. Dependabot's npm updates cover development packages too.

## Review the app's config

*Only for: An app (add-on)*

Change one thing per release, so a user who hits a problem can tell what changed.

### APP-1: Ask only for the access the app uses

*Level 1 · Applies to apps*

Leave out `privileged`, `full_access`, `host_network`, `host_pid` and `docker_api` unless the app can't work without them, and say why in the README when it does.

`config.yaml`

```
name: Example
version: "1.0.0"
slug: example
arch: [aarch64, amd64]
ingress: true
ingress_port: 8099
homeassistant_api: true   # only if the app calls Home Assistant's API
# Leave these out unless the app can't work without them:
# privileged, full_access, host_network, host_pid, docker_api
```

**What can break:** A feature that used the access you removed stops working, for example one that read a host folder or talked to Docker. Test each feature on a real install first.

**To undo:** Put the option back in `config.yaml` and release again.

### APP-2: Use ingress instead of open ports

*Level 1 · Applies to apps*

Ingress puts the app's web page behind Home Assistant's login. An open port is reachable by anything on the network.

**What can break:** Anyone who opened the app at `http://<host>:<port>` has to open it from the Home Assistant sidebar instead, and anything that called that port directly stops reaching it.

**To undo:** Add the port back under `ports:` in `config.yaml`.

### APP-3: Keep AppArmor on

*Level 2 · Applies to apps*

**Keep AppArmor on** and ship a profile that allows only what the app does.

**What can break:** A profile that's too strict stops the app from reading or writing what it needs. The denials show in the host's logs.

**To undo:** Loosen the profile for that path, or set `apparmor: false` while you fix it.

### APP-4: Build on Home Assistant's base images

*Level 2 · Applies to apps*

**Build on Home Assistant's base images,** pin their versions, rebuild when they update, and don't run as root inside the container when you don't need to.

**What can break:** A newer base image can change package versions, and a non-root user can't write to folders root owned. Test the image before you release it.

## Make your workflows safe

Change one workflow at a time and watch its next run.

### CI-7: Give workflows read-only tokens

*Level 1*

Set `permissions: contents: read` at the top of every workflow and widen it only in the job that needs more. Then make read-only the default under Settings → Actions → General → Workflow permissions, and untick *Allow GitHub Actions to create and approve pull requests*. Repositories created since 2023 start read-only, but older ones may still give every workflow write access.

**What can break:** A job that writes, such as one that pushes, comments or publishes a release, fails with a 403 error.

**To undo:** Give that job the permission it needs in its own `permissions:` block, instead of widening the whole workflow.

### CI-8: Keep untrusted text out of `run:` lines

*Level 1*

An issue title, a pull request title or a branch name is chosen by whoever opens it. Written straight into a `run:` line with `${{ }}`, it runs as a shell command with your token. Pass it through `env:` instead, so the shell treats it as text.

`Do pass it as a variable`

```
- name: Log the new issue
  env:
    TITLE: ${{ github.event.issue.title }}
  run: echo "New issue: $TITLE"
```

`Don't write it into the command`

```
- name: Log the new issue
  run: echo "New issue: ${{ github.event.issue.title }}"
```

### CI-9: Never run a pull request's code in a `pull_request_target` workflow

*Level 1*

That trigger runs with your secrets and a token that can write, so checking out the pull request's code hands both to whoever opened it. Use `pull_request` for anything that builds or tests contributed code. `actions/checkout` v7 refuses this by default.

**What can break:** A workflow moved to `pull_request` no longer gets your secrets for pull requests from forks. That's the point. A job that only labels or comments can stay on `pull_request_target`, as long as it never checks out the pull request's code.

### CI-10: Pin actions to a full commit SHA

*Level 2*

A tag like `@v7` can be moved to different code by whoever controls the action, and your next run uses it with your token. The examples here use version tags and branch names so they're easier to read. Dependabot keeps pinned SHAs current when an action publishes new releases.

Some Home Assistant actions are updated on a branch instead. `hacs/action` hasn't tagged a release since 2022, and hassfest only started tagging in November 2026. Pin these to a commit SHA from their default branch, not to the old release, and check them for new commits every month or so.

**What can break:** A wrong SHA fails the run straight away, so you'll notice. Dependabot keeps the pins current after that.

### CI-11: Don't leave the token behind after checkout

*Level 2*

`actions/checkout` saves the token so later `git` commands work, which also hands it to every later step. Turn that off unless a later step pushes.

`.github/workflows/security.yaml (part)`

```
- uses: actions/checkout@v7
  with:
    persist-credentials: false
```

**What can break:** A later step that pushes, such as one that commits a version bump, fails.

**To undo:** Turn it back on in that job only.

### CI-4: Add a security workflow

*Level 1 (or CodeQL) · Level marker · Only for: An integration or A dashboard card*

**Add a security workflow** that runs on pull requests and on main. This one is for an integration; for a card, swap pip-audit for `npm audit --omit=dev`.

`.github/workflows/security.yaml`

```
name: Security
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  dependency-review:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/dependency-review-action@v5
        with:
          fail-on-severity: moderate
  pip-audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
      - run: pip install pip-audit==2.10.1
      - name: Check the integration's requirements
        run: |
          jq -r '.requirements // [] | .[]' custom_components/your_domain/manifest.json > requirements.txt
          if [ -s requirements.txt ]; then pip-audit -r requirements.txt; fi
  ruff-security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/ruff-action@v4.1.0
        with:
          args: check --select S
```

ruff-action has no `v4` tag, only exact versions such as `v4.1.0`, so it's pinned to one here.

pip-audit sometimes reports a vulnerability that has no fixed version yet, so there's nothing to upgrade to and the job keeps failing. Check whether it affects how your integration uses the library. If it doesn't, skip that one finding with `--ignore-vuln ID` and a comment saying why. An unpinned requirement resolves to its newest version on every run, so the result can change without a commit. [Dependencies](https://ha-barkley.github.io/security/controls/dependencies/) covers pinning.

**What can break:** Nothing blocks yet. Its first runs may fail on existing problems, so fix those before you require it.

### CI-4: Add a security workflow

*Level 1 (or CodeQL) · Level marker · Only for: An app (add-on)*

**Add a security workflow** that runs on pull requests and on main. This one is for an integration; for a card, swap pip-audit for `npm audit --omit=dev`.

`.github/workflows/security.yaml`

```
name: Security
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  dependency-review:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/dependency-review-action@v5
        with:
          fail-on-severity: moderate
  pip-audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.13"
      - run: pip install pip-audit==2.10.1
      - name: Check the integration's requirements
        run: |
          jq -r '.requirements // [] | .[]' custom_components/your_domain/manifest.json > requirements.txt
          if [ -s requirements.txt ]; then pip-audit -r requirements.txt; fi
  ruff-security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/ruff-action@v4.1.0
        with:
          args: check --select S
```

ruff-action has no `v4` tag, only exact versions such as `v4.1.0`, so it's pinned to one here.

pip-audit sometimes reports a vulnerability that has no fixed version yet, so there's nothing to upgrade to and the job keeps failing. Check whether it affects how your integration uses the library. If it doesn't, skip that one finding with `--ignore-vuln ID` and a comment saying why. An unpinned requirement resolves to its newest version on every run, so the result can change without a commit. [Dependencies](https://ha-barkley.github.io/security/controls/dependencies/) covers pinning.

> For an app, keep the dependency review job, and point the audit job at the app's own `requirements.txt` or `package.json`, if it has one. `manifest.json` is an integration's file.

**What can break:** Nothing blocks yet. Its first runs may fail on existing problems, so fix those before you require it.

### DEP-5: Check for known vulnerabilities in CI

*Level 1*

**Why:** Most vulnerable code in an app is an old version of a library that already has a fix. A check in CI tells you when a package you use gets an advisory, before a user reports it.

Use pip-audit or npm audit (see [Checks in CI](https://ha-barkley.github.io/security/controls/ci/)).

> The security workflow above does this.

### CI-5: Validate against Home Assistant's own rules

*Level 1 · Applies to integrations and cards · Only for: An integration or A dashboard card*

**Validate against Home Assistant's own rules** with hassfest and the Marketplace's validation action.

`.github/workflows/validate.yaml`

```
name: Validate
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  hassfest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: home-assistant/actions/hassfest@master
  marketplace:
    runs-on: ubuntu-latest
    steps:
      - uses: hacs/action@main
        with:
          category: integration
```

For a card, leave out the hassfest job, which only checks integrations, and set `category: plugin`, the Marketplace's name for dashboard cards.

**What can break:** hassfest and the Marketplace check may fail on things that worked before, such as a missing key in `manifest.json`. Nothing blocks until you require them.

### CI-5: Validate against Home Assistant's own rules

*Level 1 · Applies to integrations and cards · Only for: An app (add-on)*

**Validate against Home Assistant's own rules** with hassfest and the Marketplace's validation action.

`.github/workflows/validate.yaml`

```
name: Validate
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  hassfest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: home-assistant/actions/hassfest@master
  marketplace:
    runs-on: ubuntu-latest
    steps:
      - uses: hacs/action@main
        with:
          category: integration
```

For a card, leave out the hassfest job, which only checks integrations, and set `category: plugin`, the Marketplace's name for dashboard cards.

> For an app, leave out both jobs. hassfest only checks integrations, and the Marketplace action only checks integrations and cards. `frenck/action-addon-linter` checks an app's `config.yaml` instead.

**What can break:** The linter may fail on things that worked before. Nothing blocks until you require it.

### CI-13: Check your workflows with zizmor

*Level 2*

It finds the problems above, such as untrusted text in `run:` lines, broad tokens, unpinned actions and credentials left behind. Run `uvx zizmor .github/workflows/` before you push, or add it to your security workflow.

### CI-12: Use a GitHub App token instead of a personal access token

*Level 2*

When the built-in token can't do something, such as triggering another workflow, create a GitHub App with only the permissions it needs and install it on the repositories that need it. `actions/create-github-app-token` turns it into a token that expires after an hour. The app's private key is still a stored secret, but each token reaches only what you picked, and nothing is tied to your own account.

**What can break:** A step that used the old token, such as one that pushes or starts another workflow, fails until it uses the app's token.

**To undo:** Point the step back at the old secret, then revoke that token once the app's token works.

## Make the checks block

Do this once the checks pass on main. From here, a failing check stops a merge.

### GATE-3: Make sure each check can fail

*Level 2 · Level marker*

Remove `continue-on-error: true`, `|| true` and `--exit-zero` from security steps. Some tools report without failing unless you ask them to. Trivy, for example, needs `exit-code: 1`.

**What can break:** A check that was failing quietly now fails for real. Fix what it finds first.

### BR-1: Add a branch ruleset for main

*Level 2 · Level marker*

Settings → Rules → Rulesets → New branch ruleset.

- Enforcement: *Active*.
- Target: the default branch.
- Turn on *Restrict deletions*.
- Turn on *Block force pushes*.
- Turn on *Require a pull request before merging*. Zero required approvals is fine if you work alone, because the pull request still runs your checks before anything lands.

**What can break:** Pushing straight to main is rejected, for you and for any workflow or tool that commits to main.

**To undo:** Set the ruleset's Enforcement to *Disabled*. It keeps its settings, so you can turn it back on.

### GATE-2: Require your other checks by job name

*Level 2 (or code scanning) · Level marker*

*Require status checks to pass* → add `dependency-review`, `pip-audit`, `ruff-security`, `hassfest` and `marketplace` from the workflows in [Checks in CI](https://ha-barkley.github.io/security/controls/ci/). A check only shows up in the list after it has run once.

**What can break:** A required check that doesn't run on a pull request, for example because its job was renamed or skipped by a path filter, leaves the pull request waiting forever.

**To undo:** Remove that check from the ruleset's list.

### GATE-1: For CodeQL, require code scanning results

*Level 2 (or a required check) · Level marker*

In your main branch ruleset, turn on *Require code scanning results*, add CodeQL, and set it to block on security alerts of "High or higher". Requiring "Analyze (python)" only proves the scan ran.

**What can break:** Code scanning alerts of High or higher in the changed code block the merge. Fix or dismiss the existing ones first.

### BR-3: Keep the bypass list short

*Level 2*

If you add yourself so you can merge in an emergency, every bypass is logged. Don't add bots or apps you don't control.

### GATE-4: Work through pull requests, even alone

*Level 2 · Level marker*

Push to a branch, open a pull request and merge it when the checks are green. It takes a minute longer and it's the only way the required checks see your code first.

## Release from CI

Switch with your next release. Keep notes on the old way until a release from CI has worked.

### REL-1: Build and publish releases from a workflow

*Level 3 · Level marker*

**Build and publish releases from a workflow** instead of your laptop. This one zips an integration, refuses a tag that isn't on main, adds a provenance attestation, and publishes the release with the zip in one step.

`.github/workflows/release.yaml`

```
name: Release
on:
  push:
    tags: ["v*"]
permissions:
  contents: write
  id-token: write
  attestations: write
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - name: Only release code that's on main
        run: git merge-base --is-ancestor "$GITHUB_SHA" origin/main
      - name: Zip the integration
        run: |
          cd custom_components/your_domain
          zip -r "$GITHUB_WORKSPACE/your_domain.zip" .
      - uses: actions/attest-build-provenance@v4
        with:
          subject-path: your_domain.zip
      - name: Publish the release
        env:
          GH_TOKEN: ${{ github.token }}
        run: gh release create "$GITHUB_REF_NAME" your_domain.zip --verify-tag --generate-notes
```

Tell the Marketplace to install the zip with `"zip_release": true` and `"filename": "your_domain.zip"` in `hacs.json`. For a card, build the bundle in the workflow and attach the built file instead.

The "Only release code that's on main" step catches a tag pushed from the wrong branch by mistake. It can't stop someone with write access. The workflow that runs is the one in the tagged commit, so they could tag a commit whose workflow leaves that step out. A tag ruleset with *Restrict creations* stops that, because only the people on its bypass list can create release tags (see [Branch and tag protection](https://ha-barkley.github.io/security/controls/branches-and-tags/)).

> For an app, the release is its container image. Build and push the image in the workflow and name it as `image` in `config.yaml`. Without `image`, each user's Home Assistant builds the Dockerfile itself.

**What can break:** Users get whatever the new workflow publishes, so install the first one yourself before you announce it.

**To undo:** Publish the next release the old way. For an integration, also remove `zip_release` and `filename` from `hacs.json`, and the Marketplace installs from the repository again.

### REL-4: Don't commit build output you also release

*Level 3 · Only for: A dashboard card*

If a card's `dist/` is in the repository, make the release workflow fail when a fresh build doesn't match it.

### REL-2: Keep publishing secrets in a release environment

*Level 3*

If the release needs a secret, for example to push an image or publish a package, create an environment under Settings → Environments. Under Deployment branches and tags, allow only your release tags, add the secret to the environment instead of the repository, and add `environment: release` to the release job. A job started from any other branch or tag can't read it. With the tag ruleset above, only you can start one that can. Trusted publishing, where the registry supports it, needs no secret at all.

### SEC-4: In CI, prefer no secret at all

*Level 2*

Use the built-in `GITHUB_TOKEN` with the narrowest permissions, and trusted publishing (OpenID Connect) to publish to PyPI or npm instead of a long-lived token.

**What can break:** With trusted publishing set up, a publish from anywhere else, such as your laptop, is refused.

**To undo:** Remove the trusted publisher on PyPI or npm and go back to a token.

### BR-4: Add a tag ruleset for your release tags

*Level 3 (or immutable releases) · Level marker*

Settings → Rules → Rulesets → New tag ruleset.

- Enforcement: *Active*. A disabled ruleset protects nothing.
- Target: `v*`, or however you name versions.
- Turn on *Restrict updates* and *Restrict deletions*, so a published version can't be moved to different code later.
- Turn on *Restrict creations* if only you should cut releases. Then add the Repository admin role to the bypass list, or you won't be able to push new tags either.

**What can break:** With *Restrict creations* on, nobody outside the bypass list can push a release tag, and that includes you until the Repository admin role is on it.

**To undo:** Set the ruleset's Enforcement to *Disabled*.

### REL-3: Turn on immutable releases

*Level 3 (or a tag ruleset) · Level marker*

**Turn on immutable releases** (Settings → General → Releases), so a published release's files and tag can't be swapped later. It applies to releases you publish after turning it on. Because assets can't be added after publishing, the workflow above creates the release and its file together.

**What can break:** A published release can't be changed, so a forgotten file means a new version. Releases published while it's on stay that way even if you turn it off later.

**To undo:** Turn it off for future releases. The ones already published stay immutable.

## Plan for the long run

These come up once reports and issues arrive.

### POL-4: When a report comes in

*Level 1*

**When a report comes in,** fix it in the advisory's private fork, release the fix, then publish the advisory. You can request a CVE from the advisory. If your code is also published as a package on PyPI or npm, Dependabot then alerts the projects that depend on it.

### REPO-4: Close issues with the fix

*Level 2*

Write `Fixes #123` in the pull request, and GitHub closes the issue when it merges. Close stale questions with a short note rather than leaving them open.

### ACC-4: Sign your commits

*Level 2 · Level marker*

**Why:** Git lets anyone put any name and email on a commit. A signature can't be made without your key, so signed commits let people tell your work from a commit pushed with a stolen token or written to look like yours. In 2021, two malicious commits were pushed to PHP's source code in the names of two of its core developers ([PHP's announcement](https://news-web.php.net/php.internals/113838)).

An SSH key is the simplest way. You can use the one you already push with.

1. If you don't have an SSH key, run `ssh-keygen -t ed25519`. It saves the public half as `~/.ssh/id_ed25519.pub`.
2. Tell Git to sign every commit and tag with it.
   
   `Terminal`
   
   ```
   git config --global gpg.format ssh
   git config --global user.signingkey ~/.ssh/id_ed25519.pub
   git config --global commit.gpgsign true
   git config --global tag.gpgsign true
   ```
   
   Change the path if your key has a different name.
3. Give GitHub the public key, so it can check your signatures. Until you do, your signed commits show "Unverified". In Settings → SSH and GPG keys, choose New SSH key, set Key type to *Signing Key*, and paste the line that `cat ~/.ssh/id_ed25519.pub` prints. Only share the file ending in `.pub`. The one without `.pub` is your private key. From a terminal, the GitHub CLI can do it instead:
   
   `Terminal`
   
   ```
   gh auth refresh -h github.com -s admin:ssh_signing_key
   gh ssh-key add ~/.ssh/id_ed25519.pub --type signing --title "My laptop"
   ```
   
   A key you already added for pushing has to be added again as a signing key.

Where the private key is kept decides what someone gets if they copy your files or run code on your machine:

| Where the key is                                    | Someone copies your files         | Malware runs as you               | Day to day                                                        |
|-----------------------------------------------------|-----------------------------------|-----------------------------------|-------------------------------------------------------------------|
| A file with no passphrase                           | They have your key                | Can sign                          | Nothing to type                                                   |
| A file with a passphrase, loaded into the SSH agent | Useless without the passphrase    | Can sign while the key is loaded  | Unlock once per login. macOS can keep the passphrase in Keychain. |
| A password manager's SSH agent                      | There's no key file               | Asks before each app uses the key | Approve each app                                                  |
| A security key (`ssh-keygen -t ed25519-sk`)         | The key never leaves the hardware | Needs a touch for every signature | A touch for every commit, so a rebase of 20 commits is 20 touches |

With a password manager, its own instructions give the value for `user.signingkey`. GPG keys work too, with GitHub's GPG instructions.

In a codespace you don't need a key of your own. Turn on Settings → Codespaces → GPG verification for the repositories you trust, and GitHub signs the commits you make there. Commits you make on GitHub's website are signed by GitHub already.

> Commits you made before you started signing stay unsigned. Only new ones show "Verified".

### ACC-5: Then turn on vigilant mode

*Level 2*

**Why:** Signing only helps if an unsigned commit in your name stands out. Without vigilant mode, GitHub shows an unsigned commit with no label, like most commits. With it on, an unsigned commit in your name shows "Unverified".

On the same page, tick "Flag unsigned commits as unverified". Any commit with your name that you didn't sign then shows "Unverified", including one pushed with a stolen token. Wait until a commit you push shows "Verified", or your own commits show "Unverified" too.

### ACC-6: Give the project a second maintainer, or at least a plan

*Level 2*

**Why:** When one person can publish, nobody notices an odd release from that account, and nobody can step in if that person loses access or moves on. If its maintainer leaves without a plan, a project can pass to whoever asks for it. In 2018, someone posing as a maintainer took over the event-stream package on npm and added code that stole from bitcoin wallets ([how it happened](https://ha-barkley.github.io/security/attacks/#event-stream)).

A free GitHub organization lets several people share a project and can require two-factor login for all of them. [Organizations](https://ha-barkley.github.io/security/controls/organizations/) covers when it's worth it. If you're on your own, write down in the README who can take over.

## Next

Check where you stand on the [checklist](https://ha-barkley.github.io/security/checklist/?level=3). It lists every step, including the few this walk-through leaves out.
