# ProtectedResource

> Reference for the nauthera.io/v1alpha1 ProtectedResource resource: an API access tokens name as their audience, its scopes, token lifetime and introspection.

A `ProtectedResource` registers an API with an organization from git: the identifier a
client sends as `resource` (RFC 8707) and its access tokens name in `aud`, the scopes the
API defines, the longest a token for it lives, the client the API introspects tokens
as, and the organization's [declared user attributes](https://www.nauthera.io/docs/v1/user-attributes) its tokens
carry. Once an organization registers one, its clients get tokens only for the APIs it
registers and each client's [`OIDCClient`](https://www.nauthera.io/docs/v1/oidc-client) lists in `spec.resources`.
The [admin dashboard](https://www.nauthera.io/docs/v1/admin-dashboard) and the admin API list an organization's
protected resources; only a `ProtectedResource` registers, changes or removes one.
[Protect an API with a ProtectedResource](https://www.nauthera.io/docs/v1/guides/protected-resources) walks through
one from the platform team's allocation to an API that authorizes on its tokens'
attributes.

| Property | Value |
|---|---|
| API group / version | `nauthera.io/v1alpha1` |
| Kind | `ProtectedResource` |
| Plural / short name | `protectedresources` / `protres` |
| Scope | Namespaced |
| Definition | `deploy/crds/protectedresource-crd.yaml` in nauthera-server |

## Example

An HR API of the main organization. The platform team lets the `hr` namespace register
APIs under `https://hr.acme.example/`, in the chart's values:

```yaml
config:
  orgs:
    main:
      protected_resources:
        - namespaces: [hr]
          identifier_prefixes: ["https://hr.acme.example/"]
```

The HR team registers the API. Its tokens live at most ten minutes, whatever the calling
client's own lifetime, and the API introspects them as the confidential client
`hr-api-introspector`, an `OIDCClient` in the same namespace:

```yaml
apiVersion: nauthera.io/v1alpha1
kind: ProtectedResource
metadata:
  name: hr-api
  namespace: hr
spec:
  identifier: https://hr.acme.example/api
  displayName:
    en: HR API
    de: Personal-API
  scopes:
    - name: hr.employees:read
      descriptions:
        en: Read employee records
        de: Mitarbeiterdaten lesen
    - name: hr.employees:write
      descriptions:
        en: Change employee records
  accessTokenTtlSeconds: 600                # optional
  introspectionClient: hr-api-introspector  # optional
```

A service that calls the API lists it among its resources, and asks for a token with
`resource=https://hr.acme.example/api`:

```yaml
apiVersion: nauthera.io/v1alpha1
kind: OIDCClient
metadata:
  name: payroll-worker
  namespace: hr
spec:
  clientId: payroll-worker
  displayName: Payroll worker
  grantTypes:
    - client_credentials
  scopes:
    - hr.employees:read
  resources:
    - https://hr.acme.example/api
  tokenEndpointAuthMethod: client_secret_basic
  secret:
    generate: true
```

```bash
kubectl apply -f hr-api.yaml
kubectl -n hr get protectedresource hr-api   # PHASE Ready, reason Registered
```

## Allocating identifiers

An organization accepts a `ProtectedResource` only under an identifier that starts with a
prefix it allocates to the resource's namespace, so one team cannot take another team's
audience and set its tokens' lifetime. An `Organization` allocates them in
[`spec.protectedResources`](https://www.nauthera.io/docs/v1/organization-resource); the main organization in
[`orgs.main.protected_resources`](https://www.nauthera.io/docs/v1/configuration#the-main-organization). Each entry
names namespaces, or `*` for every one, and prefixes: `https://` with a host, ending in
`/`, or `urn:` ending in `:`. `https://hr.acme.example/` covers
`https://hr.acme.example/api` and not `https://hr.acme.example.evil/`.

```yaml
apiVersion: nauthera.io/v1alpha1
kind: Organization
metadata:
  name: acme
spec:
  slug: acme
  displayName: Acme
  namespaces: [hr]
  protectedResources:
    - namespaces: [hr]
      identifierPrefixes: ["https://hr.acme.example/", "urn:acme:hr:"]
```

An organization that allocates nothing accepts no `ProtectedResource`: each is `Refused`
on `spec.identifier`, naming the namespace. Removing an entry leaves the resources it
covered registered and refuses their next write.

## Which clients get tokens for it

In an organization that registers no protected resource, a client may name any
well-formed `resource`. The first one it registers changes that for every client:

- **Only registered APIs.** A `resource` the organization does not register is refused
  with `invalid_target` at `/authorize`, `/par`, `/device_authorization` and `/token`.
  Register together every API the organization's clients name.
- **Only the client's APIs.** A client gets a token for a registered API only when its
  `OIDCClient` lists the identifier in `spec.resources`, written exactly as the
  resource's `spec.identifier` is; a client listing none may name none. A listed API need
  not be registered yet, so a manifest may apply the client and the API in any order; the
  server refuses a token for it until it is.
- **Checked again at every mint.** The token endpoint checks both rules when it issues a
  token, so a code or refresh token for an API since removed, or since dropped from the
  client's list, is refused. The refresh token stays usable for the APIs the client still
  lists.
- **Without `resource`.** A token requested for no resource names the client's
  `client_id` in `aud`. Where a registered resource's identifier is that `client_id`,
  the token is held to that resource as if the client had named it.

A request may name up to eight distinct resources, the parameter repeated. The token
names each in `aud` and lives no longer than the shortest-lived of them allows. Only a
token naming this server alone, by its client id or the organization's issuer, is
accepted at UserInfo and the admin API.

## Attributes in its tokens

`spec.attributes` (at most 16, each named once) selects the organization's declared user
attributes the API's access tokens carry, `in: token`, the default and the one
destination. A user's access token carries one when its declaration sets
`accessToken: true`, the grant holds one of the scopes the declaration releases it under
(the scopes the user consented to, never the client's registered ones alone), every
resource the token names selects it, and the user has a value. A token naming no
`resource`, or an identifier the organization does not register, carries none, and a
claim the token sets itself is never replaced.

```yaml
apiVersion: nauthera.io/v1alpha1
kind: ProtectedResource
metadata:
  name: hr-api
  namespace: hr
spec:
  identifier: https://hr.acme.example/api
  scopes:
    - name: hr.employees:read
  attributes:
    - name: department
    - name: cost_center
```

- **Checked when written.** The server refuses, on `spec.attributes[i].name`, an
  attribute the organization does not declare with `accessToken: true`, and, on
  `spec.attributes`, a selection whose largest values from the declared bounds take more
  than 4096 bytes of a token: a string counts up to six bytes a character up to its
  `maxLength` (1024 without one), and a list its `maxItems` members (32 without). Select
  a string only with a `maxLength`.
- **Not re-checked when the declaration changes.** An attribute the organization stops
  declaring, or declares without `accessToken`, is no longer carried, from the next token.
- **Never a partial token.** A user's value that breaks its declaration, or values over
  4096 bytes, refuse that user's token with `invalid_target` (causes
  `attribute_value_invalid` and `token_attributes_too_large`) rather than leave an
  attribute out; see the [runbook](https://www.nauthera.io/docs/v1/runbooks/oauth/invalid_target).
- **As they are at each mint.** Every token, a refreshed one's included, carries the
  values and the declaration as they are when it is minted, so `accessTokenTtlSeconds`
  bounds how long a changed value lives on in a token already issued.

It needs control-plane contract 21; an older server leaves the resource `Unsupported`.

## Introspection

`spec.introspectionClient` names an `OIDCClient` in the same namespace and organization,
by its resource name, and the operator sends that client's `status.clientId`.
`/introspect` (RFC 7662) then describes the client every token whose `aud` names the
API, besides the tokens issued to it; any other caller is answered `active: false`. The
server refuses a client that is not confidential or that the operator did not register
in the resource's namespace.

While the client is missing, not registered yet or of another organization, the resource
is `IntrospectionClientNotFound` and the API is registered with no introspection client,
so one the server held is cleared. The server holds the client it accepted by its
registration: a client deleted and another registered under its `client_id` is not the
API's until the operator sends it again.

{/* Attributes in an introspection answer: nauthera/nauthera-server#2023 */}
An introspection answer carries no declared attribute; the API reads them from the token.

## Behavior

- **The identifier** is the `resource` a client sends and the `aud` its token names: an
  `https` URL with a host or a `urn:`, in ASCII and without userinfo or a fragment, at
  most 2048 bytes, unique in the organization, and other than its issuer and its service
  attribute API, `<issuer>/v1/user-attributes`, which the server answers as its own. Its
  path holds no `.` or `..` segment (`%2E` counts as `.`, and `;` ends a segment) and no
  `%2F` or `%5C`, so a server in front of the API cannot read it as another path. The server
  compares identifiers in the form RFC 3986 §6.2.2 gives them: the scheme and host in
  lower case, no empty or default port, percent-encodings of unreserved characters decoded
  and the rest in upper case, and an empty path written `/`. Nothing else is folded, so
  `https://hr.acme.example/api/` is another API. The manifest writes that form; the server
  refuses any other as `Refused`, naming the form to write: `https://hr.acme.example` is
  written `https://hr.acme.example/`.
- **Changing the identifier** registers the API under the new one. A token already issued
  keeps the one it names.
- **Scopes.** At most 64, each named once: 1 to 128 printable ASCII characters other than
  space, `"` and `\`, with up to 16 descriptions by BCP 47 tag of at most 500 characters,
  which the dashboard shows in the viewer's language. The server refuses a name in the
  reserved `nauthera.` namespace and one OpenID Connect or the server defines: `openid`,
  `profile`, `email`, `offline_access`, `groups`, `address` and `phone`.
- **The display name** is the name the dashboard shows for the API: up to 16 names
  by BCP 47 tag, at most 100 characters each, with no control, bidirectional or invisible
  character. {/* Resource names and scope descriptions on the consent screen: nauthera/nauthera-server#2022 */}
- **Token lifetime.** `accessTokenTtlSeconds`, 30 to 86400, bounds every access token
  issued for the identifier: it lives the shorter of its client's lifetime and this one.
  Left out, the client's lifetime alone applies.
- **One organization.** The organization follows from the resource's namespace (see
  [Which organization a resource configures](https://www.nauthera.io/docs/v1/operator#which-organization-a-resource-configures));
  `spec.organization` names it where several admit the namespace, may be set once on a
  resource that named none, and is fixed after. A resource whose namespace comes to
  configure another organization is `OrganizationChanged`: delete and recreate it to move
  it.
- **Who may write one.** The operator's grant needs the `protected_resources` operation,
  which the chart's default entry includes (see
  [the grant](https://www.nauthera.io/docs/v1/operator#what-the-operator-may-do-on-the-server)), and the chart's
  `nauthera-app-developer` role may write `ProtectedResource` in the namespaces it is
  bound in. A server older than control-plane contract 15 leaves the resource
  `Unsupported`; one older than contract 17 issues a token for a registered API to any
  client, so list each client's `spec.resources` before or with the upgrade.

### Deleting a resource

Deleting the resource removes the API from the server. There is no `deletionPolicy`: an
API left registered with no manifest would be one nothing manages, still bounding its
tokens. A finalizer (`nauthera.io/protectedresource`) goes on before the first call and
holds the resource until the server has removed the API. While the server does not
answer, serves a contract below 15, or holds the API in an organization the operator's
grant no longer covers, the resource stays in phase `Deleting` with reason
`ProtectedResourceNotRemoved`. A resource never sent goes at once, and one the server
never accepted (without `status.etag`) is let go when the grant lacks the
`protected_resources` operation.

## Spec

{/* AUTO-GENERATED-SPEC-START */}

### `spec.accessTokenTtlSeconds`

**Type:** `integer` | **Optional**

The most an access token for the API lives, in seconds, whatever
its client's own lifetime. Omitted, a token lives as long as its
client's do.

### `spec.attributes`

**Type:** `[]object` | **Optional**

The organization's declared user attributes the API selects, each
named once. An access token issued for the API carries one when the
attribute's spec.userAttributes entry sets accessToken, the token's
grant holds one of its scopes, every audience of the token selects
it, and the user has a value that conforms to its declaration; a
value that does not conform refuses the token. The server refuses an
attribute the organization does not declare with accessToken, and a
selection whose largest values from the declared bounds (maxLength,
maxItems, minimum and maximum, an enum's longest member) take more
than 4096 bytes of a token. An attribute the declaration later stops
allowing is no longer carried. Needs control-plane contract 21.

| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `in` | `string` | No | `"token"` | Where the API receives it: token, in the access tokens issued for it, the one destination today. One of: `token`. |
| `name` | `string` | Yes | `—` | The attribute's name in its organization's spec.userAttributes. |

### `spec.displayName`

**Type:** `map[string]string` | **Optional**

The name the consent screen shows for the API, by BCP 47 language
tag, with no control, bidirectional or invisible character.

### `spec.identifier`

**Type:** `string` | **Required**

The resource indicator a client asks for (RFC 8707 §2) and the
audience its access tokens name, exactly as they carry it: an https
URL with a host or a URN, in ASCII and without userinfo or a fragment,
unique in the organization, other than its issuer and the issuer's
/v1/user-attributes, with no "." or ".." path segment (%2E counts as
".", and ";" ends a segment) and no %2F or %5C, in the form the
server compares it in (RFC 3986 §6.2.2). That is the scheme and host in
lower case, no empty or default port, percent-encodings of unreserved
characters decoded and the rest in upper case, and an empty path written
"/". The server refuses one written otherwise, naming the form to write,
and one no entry of the organization's spec.protectedResources
(orgs.main.protected_resources for the main organization) allocates
to this namespace.

### `spec.introspectionClient`

**Type:** `string` | **Optional**

The OIDCClient, in this resource's namespace and organization, whose
client the API introspects tokens as (RFC 7662), by its resource
name: a confidential client. Introspection describes it every token
whose aud names this resource. While it is missing or not yet
registered on the server, the API is registered with no
introspection client and the resource reports it.

### `spec.organization`

**Type:** `string` | **Optional**

The slug of the organization this API belongs to. Needed only where
more than one organization admits the namespace in its
spec.namespaces; otherwise the one that does is taken. The main
organization is "default". Immutable.

### `spec.scopes`

**Type:** `[]object` | **Optional**

The scopes the API defines (RFC 6749 §3.3), each named once. A name
in the reserved nauthera. namespace, or one OpenID Connect or the
server defines (openid, profile, email, offline_access, groups,
address, phone), is refused.

| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `descriptions` | `map[string]string` | No | `—` | What granting the scope allows, as the consent screen says it, by BCP 47 language tag, with no control character. |
| `name` | `string` | Yes | `—` | The scope's name as a client requests it: printable ASCII other than space, '"' and '\'. |

{/* AUTO-GENERATED-SPEC-END */}

## Status

`status.introspectionClientId` is the `client_id` the server holds as the API's
introspection client, and `status.organization` the organization it holds the API in.
`phase` is one of `Pending`, `Ready`, `Error` or `Deleting`. Beside the connection
reasons every resource shares (`Refused`, `Unreachable`, `Unsupported`,
`CredentialUnavailable`, `TrustAnchorUnavailable`; see the
[OIDCClient reference](https://www.nauthera.io/docs/v1/oidc-client#status)) and the namespace reasons
(`NamespaceNotCovered`, `NamespaceNotAdmitted`, `OrganizationAmbiguous`,
`OrganizationNotReady`, `OrganizationChanged`), the `Ready` condition's reason is one of:

| Reason | Phase | Meaning |
|---|---|---|
| `Registered` | `Ready` | The server holds the API as the spec says. |
| `IntrospectionClientNotFound` | `Error` | The `OIDCClient` `spec.introspectionClient` names is missing, not registered yet or of another organization. The API is registered with no introspection client. |
| `ProtectedResourceNotRemoved` | `Deleting` | The resource is being deleted and the server has not removed the API. |

Each failure reason has a [runbook](https://www.nauthera.io/docs/v1/runbooks).

{/* AUTO-GENERATED-STATUS-START */}

| Field | Type | Description |
|---|---|---|
| `conditions` | `[]object` | Standard Kubernetes conditions (Ready, ...). |
| `etag` | `string` | The server's revision of the resource as the operator last wrote it. |
| `introspectionClientId` | `string` | The client_id the server holds as the API's introspection client, the status.clientId of the OIDCClient spec.introspectionClient names. |
| `lastReconciledTime` | `string` | When the operator last reconciled the resource, whatever the outcome. A stale value means the operator is not running, not the leader, or cannot see the resource. |
| `observedGeneration` | `integer` | .metadata.generation last reconciled by the server. |
| `organization` | `string` | The slug of the organization the server holds the resource in. Once set, a namespace that comes to configure another organization is refused rather than moving the resource. |
| `phase` | `string` | High-level lifecycle phase. |

{/* AUTO-GENERATED-STATUS-END */}

## Related

- [Protect an API with a ProtectedResource](https://www.nauthera.io/docs/v1/guides/protected-resources): the guide,
  from allocation to attributes an application updates
- [User Attributes](https://www.nauthera.io/docs/v1/user-attributes): declaring the attributes `spec.attributes`
  selects
- [OIDCClient](https://www.nauthera.io/docs/v1/oidc-client): a client's `spec.resources`
- [Organization](https://www.nauthera.io/docs/v1/organization-resource): allocating identifiers with `spec.protectedResources`
- [Tokens & Sender Constraint](https://www.nauthera.io/docs/v1/tokens#revocation-and-introspection): introspection
- [Audit events](https://www.nauthera.io/docs/v1/audit-events): the `protected_resource.*` actions
- [Operator](https://www.nauthera.io/docs/v1/operator#who-may-change-what): the grant and the team roles
