Skip to content

feat(operator): identify the operator by name in the user agent - #1348

Merged
kimpenhaus merged 3 commits into
mainfrom
feat/user-agent
Nov 28, 2026
Merged

kimpenhaus merged 3 commits into
mainfrom
feat/user-agent

Conversation

@kimpenhaus

@kimpenhaus kimpenhaus commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

What

The operator identifies itself to the Kubernetes API server with its own name instead of the generic user agent of the C# client:

# before
kubernetes-csharp/21.0.8+75f253d651

# after
my-operator/1.2.0 kubeops/15.0.0 kubernetes-csharp/21.0.8+75f253d651

Build metadata (+<commit>) is dropped from the operator and KubeOps versions; the C# client token stays as the client sends it.

The API server records the user agent in its audit logs, so requests of an operator can now be told apart from those of other clients built on the C# client. This complements the explicit field manager from #1346: the API server derives the field manager of a write without fieldManager from the part of the user agent before the first /. The operator always sends an explicit field manager, so managedFields do not change.

How

  • KubernetesUserAgent (public static class in KubeOps.KubernetesClient) with two members:
    • Create(product, version) returns <product>[/<version>] kubeops/<version> <client default>. Characters that are not allowed in an HTTP product token (RFC 9110 tchar), e.g. spaces, / or CR/LF, are replaced by -. An empty version is left out, build metadata is dropped.
    • Apply(config, product, version) sets that user agent on a KubernetesClientConfiguration unless it already carries an own one. An empty user agent and the client default count as not configured.
  • OperatorBuilder: the default IKubernetes applies the user agent from the operator name and the informational version of the entry assembly to the configuration before it creates the client. This also covers a KubernetesClientConfiguration registered by the user, as long as it has no own user agent; the registered configuration is changed in place (documented). The user agent always starts with the operator name, independent of WithFieldManager. With an empty operator name the client default is kept.
  • KubeOps CLI identifies itself as kubeops-cli/<version>.

No new setting: an own user agent is set through KubernetesClientConfiguration.UserAgent, which already exists.

Behavioural changes for users

No public API is removed or changed. Visible differences:

  • The User-Agent header of the operator and the CLI changes, e.g. in API server audit logs. Anything that matches on kubernetes-csharp in the user agent still matches, because the client token stays at the end.
  • An IKubernetes registered by the user keeps the user agent of its configuration; KubernetesUserAgent can be used to set it (documented).
  • KubernetesClient constructed directly (outside the operator) is unchanged.

Docs

  • New page docs/docs/operator/configuration/user-agent.mdx, linked from the Advanced Configuration index and from the Field Manager page
  • KubeOps.KubernetesClient README
  • CLI page
  • Migration guide ("New in v15 (non-breaking)")

Tests

  • Unit tests (Area KubernetesClient / Configuration / Cli):
    • format, omitted version, dropped build metadata, token sanitisation (incl. CR/LF), empty product
    • Apply: replaces a missing, empty and default user agent, keeps an own one
    • OperatorBuilder wiring: operator name independent of the field manager, own configured user agent, empty operator name
    • CLI factory
  • dotnet build -c Release, dotnet format --verify-no-changes and the unit tests of KubeOps.KubernetesClient.Test, KubeOps.Operator.Test and KubeOps.Cli.Test pass locally, and the docs build (npm run build, onBrokenLinks: throw) succeeds. I did not run the integration tests locally.

Reviews

Run before merge: /code-review, /simplify, /security-review, docs sync.

  • /code-review: fixed
    • an empty operator name with an explicit field manager made resolving IKubernetes throw, because the product is required; the user agent is now skipped in that case
    • build metadata (+<sha>) ended up in the user agent, unlike the documented format; it is now dropped
    • an empty UserAgent counted as configured; it now counts as not configured
    • the in-place change of a user-registered configuration is now documented
  • /simplify: public surface reduced from four members (ClientDefault, Create, CreateFromAssembly, SetIfNotConfigured) to Create and Apply; string building simplified; redundant tests (incl. a wire-level test of upstream behaviour) and duplicated docs removed. Efficiency: no findings.
    • Skipped: changing the existing public KubernetesClient(config, fieldManager) constructor to also set the user agent. It was released in 14.1.0, and mutating the caller's configuration from a constructor would be a surprising behaviour change; tools call KubernetesUserAgent.Apply instead.
    • Skipped: sharing BuildProvider / the stub API server between test classes (small, test-only duplication).
  • /security-review: no findings. Product and version pass through the token sanitiser, so no header/CRLF injection; only UserAgent of the configuration is changed, never TLS or credentials.
  • Docs: synced with the final API (user-agent page, README, migration guide).

Kubernetes client 21.0.41

main moved to KubernetesClient 21.0.41 (#1349) while this PR was open. Docs only:

  • The user agent example shows kubernetes-csharp/21.0.41+d05b908e20.
  • migration.mdx (v15): the client now rejects an API server certificate that does not match the server address when a CA from the kubeconfig is used (kubernetes-client/csharp#1964), with how to fix a kubeconfig (server or tls-server-name). Our code has no own certificate validation and needs no change.

kimpenhaus added a commit that referenced this pull request Nov 25, 2026
## Summary

#1047 (v10.3.0) added `fieldManager`, `force` and `dryRun` to every
`PatchAsync` overload. Three of them always send a JSON patch:

- `PatchAsync(entity, operationsFilter, fieldManager, force, dryRun)`
- `PatchAsync(from, to, operationsFilter, fieldManager, force, dryRun)`
- `PatchAsync(entity, JsonPatch, fieldManager, force, dryRun)`

The API server rejects `force` for every patch type except apply, even
`force: false`
([`ValidatePatchOptions`](https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go)):

```go
default:
    if options.Force != nil {
        allErrs = append(allErrs, field.Forbidden(field.NewPath("force"), "may not be specified for non-apply patch"))
    }
```

So `force` on these overloads could only ever produce `422 Unprocessable
Entity`. It is removed there; the `V1Patch` overloads keep it for
server-side apply.

Also fixed:
- Docs of `fieldManager` (applies to every patch, not only server-side
apply) and `force` (only valid for `ApplyPatch`).
- The server-side apply example in the `KubeOps.KubernetesClient` README
did not compile (missing comma) and passed namespace and name in the
wrong order.

## Breaking change

The three JSON patch overloads no longer take `force`. A call that
passes it fails to compile instead of failing with 422 at runtime; no
working call changes behaviour. Documented in `migration.mdx` (v15),
with server-side apply as the replacement.

## Checks

- Release build without warnings, `dotnet format` clean, unit tests
`KubeOps.KubernetesClient.Test` (84) and `KubeOps.Operator.Web.Test`
(172) green; docs build green.
- `/code-review`, `/simplify`, `/security-review` done by hand for the
small diff: positional forwarding between the overloads checked, no new
overload ambiguity, no findings.

Note: touches the same `PatchAsync` lines and `operationsFilter` docs as
#1350, and `migration.mdx` like #1348/#1351; whichever merges later
needs a small rebase.
kimpenhaus added a commit that referenced this pull request Nov 27, 2026
## Summary

`UpdateStatusAsync` replaced the status with a `PUT`. The request
carried the `resourceVersion` and failed with `409 Conflict` whenever
the resource had changed in the meantime, e.g. its spec, and the field
manager owned the whole status.

`UpdateStatusAsync` now writes the status with **server-side apply**,
without a new method:

- The apply configuration contains `apiVersion`, `kind`,
`metadata.name`, `metadata.namespace` (if any) and `status`, and goes to
the `/status` subresource.
- It carries no `resourceVersion`, so an outdated entity no longer fails
with 409. The spec and the status fields that are not sent stay as they
are.
- `force: true`, as the Kubernetes docs recommend for controllers ("It
is strongly recommended for controllers to always force conflicts on
objects that they own and manage"). Without it, the first write after
the upgrade would conflict with the operator's own `Update` entry from
the `PUT`.
- The field manager comes from the client, as for every other write: the
`FieldManagerHandler` of the operator, or the one passed to `new
KubernetesClient(config, fieldManager)`. There is no fallback; without a
field manager the API server rejects the apply.

Supersedes #1351, which added `PatchStatusAsync` overloads instead.

## Breaking change

- `UpdateStatusAsync` no longer fails with 409 on an outdated entity.
- It needs a field manager. Within an operator with the default
`IKubernetes` nothing changes; an own `IKubernetes` needs the
`FieldManagerHandler` (already documented since 14.1); a
`KubernetesClient` outside an operator needs to be created with a field
manager.
- Status fields written before the upgrade stay with the `Update` entry
of the `PUT` until they are sent again.

All documented in `migration.mdx` (v15).

## Tests

- `KubernetesClient.UpdateStatus.Test.cs`: path with `?force=true`,
`application/apply-patch+yaml`, and the apply configuration for
namespaced and cluster-scoped entities.
- `KubernetesClient.FieldManager.Test.cs`: the status write is now a
`PATCH` with the field manager.
- `KubernetesClient.UpdateStatus.Integration.Test.cs` (cluster): an
outdated entity is written without 409, the spec change of the other
writer is kept, and `managedFields` shows `Apply` on `status`. Two
existing integration tests now use a client with a field manager. Not
run locally (no cluster), runs in CI.

## Docs

`migration.mdx`, `troubleshooting.mdx` (409 only for `UpdateAsync`),
`field-manager.mdx`, `KubeOps.KubernetesClient` README.

## Reviews

- `/code-review`: the reconcile pipeline already loads the entity fresh
before each reconcile and skips a recreated object
(`EntityQueueBackgroundService`), so a stale status is limited to a
running reconcile. Documented the upgrade case (fields owned by the old
`Update` entry) and the own-`IKubernetes` case. Not changed: core group
types (`/apis//v1/...`, pre-existing, tracked in the roadmap); a type
with a `null` status applies an empty status.
- `/simplify` and `/security-review` by hand: no new type or method;
name and namespace are escaped path parameters of the official client,
the body is a `JsonObject`; `force` only affects fields of our own
status, and the generated RBAC rule for `<plural>/status` already
contains `patch`.

Note: `migration.mdx`, `field-manager.mdx` and the client README are
also changed by #1348; whichever merges second needs a small rebase,
which I will do.
kimpenhaus added a commit that referenced this pull request Nov 28, 2026
…references (#1355)

## Summary

`MakeOwnerReference` set neither `controller: true` nor
`blockOwnerDeletion: true`. Without a controller reference
there is no unique managing controller (the basis for owned watches, cf.
controller-runtime `Owns()`), and without
`blockOwnerDeletion` a foreground deletion of the owner does not wait
for its resources. The helpers follow
controller-runtime's `controllerutil`:

- **`MakeControllerReference()`** (new): an owner reference with
`controller: true` and `blockOwnerDeletion: true`.
- **`WithControllerReference(owner)`** (new): adds the owner as
controller. A resource has at most one controller;
if another owner is already the controller, it throws an
`InvalidOperationException` (cf. `AlreadyOwnedError`).
- **`WithOwnerReference(owner)`** and
**`WithControllerReference(owner)`**:
- replace a reference to the same owner (same API group, kind and name;
the version is ignored) instead of adding
it again, e.g. with the new `uid` of a recreated owner. `controller` and
`blockOwnerDeletion` of the existing
reference stay, so ensuring an owner never drops the controller (fabric8
and kopf keep the existing reference
as well; controller-runtime's `SetOwnerReference` would downgrade it),
- throw an `ArgumentException` for an owner without name or `uid`, and
for a namespaced owner of a resource that
has no or another namespace. The garbage collector treats such an owner
as missing and deletes the resource.
- **`MakeOwnerReference()`** and **`MakeObjectReference()`** take a
missing `apiVersion` or `kind` from the
`KubernetesEntityAttribute` of the type. Items of a list response carry
neither, so two listed owners of different
kinds with the same name were indistinguishable, and the API server
rejects an owner reference without `kind`.
- The controller reference is read with `GetController()` of the
Kubernetes client; no own getter.

Docs: new section [Owner
References](docs/docs/operator/building-blocks/controllers.mdx)
(including the RBAC note for
`OwnerReferencesPermissionEnforcement`, e.g. on OpenShift:
`blockOwnerDeletion` needs `update` on
`<plural>/finalizers` of the owner) and a v15 entry in `migration.mdx`.

## Breaking change

`WithOwnerReference`:

- no longer adds a second reference to an owner that is already
referenced; it replaces it and keeps its
  `controller` and `blockOwnerDeletion`.
- throws an `ArgumentException` for a namespaced owner if the resource
has no or another namespace, and for an owner
  without name or `uid`.

**Migration:** set the namespace of a resource before adding the owner.
Use `WithControllerReference` for the
resources a controller manages.

## Open points

- Follow-up: `KubernetesClient.ListAsync` could fill `apiVersion`/`kind`
of the items itself, which would fix all
  consumers (events, logging) at the source.
- `migration.mdx`: #1348 also appends to the v15 section; whichever is
merged second needs a rebase.

## Checks

- `/code-review`: one bug fixed (owners from list responses without
`apiVersion`/`kind` were merged by name);
clearer error for a resource without namespace. Not changed: a
namespaced owner object without its namespace set
  is treated as cluster-scoped.
- `/simplify`: own `GetControllerReference` replaced by
`GetController()` of the Kubernetes client; `apiVersion`/
`kind` fallback shared with `MakeObjectReference` via
`EntityMetadata.GroupWithVersion`; `ApiGroup` simplified.
- `/security-review`: no findings.
- `dotnet build -c Release` without warnings, `dotnet format
--verify-no-changes`, `KubeOps.Abstractions.Test`
(330) and the unit tests of `KubeOps.Operator.Test` (610) pass. Not
tested against a cluster.
The client sends <operator-name>/<version> kubeops/<version> kubernetes-csharp/<version> instead of the generic kubernetes-csharp/<version>, so requests of the operator can be told apart in audit logs. A configuration with an own UserAgent keeps it. The KubeOps CLI identifies itself as kubeops-cli/<version>.
Shrink KubernetesUserAgent to Create and Apply, drop build metadata from versions, treat an empty user agent as not configured, skip the user agent for an empty operator name, and trim redundant tests and docs.
Update the user agent example to the client version 21.0.41 and describe in the migration guide that the client now rejects an API server certificate that does not match the server address when a CA from the kubeconfig is used (kubernetes-client/csharp#1964).
@kimpenhaus
kimpenhaus enabled auto-merge (squash) November 28, 2026 08:54
@kimpenhaus
kimpenhaus merged commit b30a2ba into main Nov 28, 2026
7 checks passed
@kimpenhaus
kimpenhaus deleted the feat/user-agent branch November 28, 2026 09:01
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

🎉 This PR is included in version 15.0.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant