# operation-security-defined

Source: https://api-genie.dev/docs/linter/asyncapi/rules/operation-security-defined

A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error.

This rule checks whether every operation of an AsyncAPI document is protected
by a security requirement.

## Rule details

In AsyncAPI 3.x, security requirements can be declared on operations, on
operation traits, and on servers. The `operation-security-defined` rule
reports `Security requirement is not defined` for every operation that is
secured in none of the following ways:

- the operation has a non-empty `security` list,
- at least one of the operation's traits has a non-empty `security` list,
- every server the operation is available on has a non-empty `security`
  list. The servers of an operation are the servers listed in the `servers`
  field of its channel or, when the channel does not list any servers, all
  servers of the document.

An operation whose channel lists no servers in a document that has no servers
at all, or whose channel reference cannot be resolved, is not considered
secured by servers.

Turn the rule off for APIs that are intentionally public, or that are available only inside a
trusted network.

## Examples

**Good**. The operation declares its own security requirement.

```yaml
asyncapi: 3.0.0
info:
  title: Pet Events
  version: 1.0.0
channels:
  petAdopted:
    address: pets.adopted
operations:
  publishPetAdopted:
    action: send
    channel:
      $ref: "#/channels/petAdopted"
    security:
      - $ref: "#/components/securitySchemes/apiKey"
components:
  securitySchemes:
    apiKey:
      type: httpApiKey
      name: X-API-Key
      in: header
```

**Good**. The only server of the channel requires authentication.

```yaml
asyncapi: 3.0.0
info:
  title: Pet Events
  version: 1.0.0
servers:
  production:
    host: broker.your-company.com:9093
    protocol: kafka-secure
    security:
      - $ref: "#/components/securitySchemes/saslScram"
channels:
  petAdopted:
    address: pets.adopted
    servers:
      - $ref: "#/servers/production"
operations:
  onPetAdopted:
    action: receive
    channel:
      $ref: "#/channels/petAdopted"
components:
  securitySchemes:
    saslScram:
      type: scramSha512
```

**Bad**. The channel is available on all servers, and one of them does not
require authentication.

```yaml
asyncapi: 3.0.0
info:
  title: Pet Events
  version: 1.0.0
servers:
  production:
    host: broker.your-company.com:9093
    protocol: kafka-secure
    security:
      - $ref: "#/components/securitySchemes/saslScram"
  legacy:
    host: legacy.your-company.com:9092
    protocol: kafka
channels:
  petAdopted:
    address: pets.adopted
operations:
  onPetAdopted:
    action: receive
    channel:
      $ref: "#/channels/petAdopted"
components:
  securitySchemes:
    saslScram:
      type: scramSha512
```
