GuideRBAC and ServiceAccounts

Guide

RBAC and ServiceAccounts

ServiceAccounts, Roles and bindings as classes, so that the names a binding, a subject and a pod spec share are references that resolve or fail the render.

RBAC is where string-typed YAML hurts most: a binding names a Role, a subject names a ServiceAccount in a namespace, a pod spec names the ServiceAccount again. Four strings that must agree, in four files, and nothing checks them until something is Forbidden at run time. In Klass8s each is a class reference.

ServiceAccounts

src/K8S/Shop/Manifest/WorkerServiceAccount.phnsrc/K8S/Shop/Manifest/WorkerServiceAccount.php
namespace App\K8S\Shop\Manifest;

use App\K8S\Shop\ShopApp;
use Klass8s\Core\ServiceAccount\AbstractServiceAccount;
use Klass8s\Core\ServiceAccount\Configurator\ImagePullSecretsConfigurator;
use Klass8s\Manifest\Reference\ManifestClassReference;

class WorkerServiceAccount extends AbstractServiceAccount
{
    static shortName(): string => 'worker';

    // pods under this ServiceAccount pull with the registry credential, without naming it
    imagePullSecrets(ImagePullSecretsConfigurator $imagePullSecrets): void
        => $imagePullSecrets->add(new ManifestClassReference(ShopApp::NAME, RegistryPullSecret::class));
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use App\K8S\Shop\ShopApp;
use Klass8s\Core\ServiceAccount\AbstractServiceAccount;
use Klass8s\Core\ServiceAccount\Configurator\ImagePullSecretsConfigurator;
use Klass8s\Manifest\Reference\ManifestClassReference;

class WorkerServiceAccount extends AbstractServiceAccount
{
    public static function shortName(): string
    {
        return 'worker';
    }

    // pods under this ServiceAccount pull with the registry credential, without naming it
    public function imagePullSecrets(ImagePullSecretsConfigurator $imagePullSecrets): void
    {
        $imagePullSecrets->add(new ManifestClassReference(ShopApp::NAME, RegistryPullSecret::class));
    }
}

A ServiceAccount that carries a registry credential lets every pod under it pull private images without naming the credential. The credential here is a Docker config Secret:

src/K8S/Shop/Manifest/RegistryPullSecret.phnsrc/K8S/Shop/Manifest/RegistryPullSecret.php
namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Secret\AbstractDockerConfigSecret;
use Klass8s\Core\Secret\DockerAuth;

// A development registry's credential. A real one is written by a secret operator (ConfigMaps and Secrets).
class RegistryPullSecret extends AbstractDockerConfigSecret
{
    static shortName(): string => 'registry-pull';

    protected auths(): iterable {
        yield new DockerAuth('registry.dev.example.com', 'dev', 'dev-only');
    }
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Secret\AbstractDockerConfigSecret;
use Klass8s\Core\Secret\DockerAuth;

// A development registry's credential. A real one is written by a secret operator (ConfigMaps and Secrets).
class RegistryPullSecret extends AbstractDockerConfigSecret
{
    public static function shortName(): string
    {
        return 'registry-pull';
    }

    protected function auths(): iterable
    {
        yield new DockerAuth('registry.dev.example.com', 'dev', 'dev-only');
    }
}

imagePullSecrets() takes references to Secret manifests; secrets() the ServiceAccount's other Secrets. automountServiceAccountToken() returns false by default and renders it, so mounting the API token is a choice a workload makes; return true to mount it, or null to leave the field out and let the cluster decide. configureServiceAccount() receives the generated object.

Attaching a ServiceAccount to a workload

Every workload has two methods:

src/K8S/Shop/Manifest/WorkerDeployment.phnsrc/K8S/Shop/Manifest/WorkerDeployment.php
// by class reference: checked, renamed with the class, works across Apps
serviceAccount(): ?ManifestClassReference => new ManifestClassReference(ShopApp::NAME, WorkerServiceAccount::class);
// by class reference: checked, renamed with the class, works across Apps
public function serviceAccount(): ?ManifestClassReference
{
    return new ManifestClassReference(ShopApp::NAME, WorkerServiceAccount::class);
}

serviceAccountName() returns a plain name, for a ServiceAccount outside the build. When both return a value, the name wins.

Because serviceAccount() is a method like any other, a subscriber can answer it for every workload that did not choose: the platform's ServiceAccount for every pod, in one class.

Roles and ClusterRoles

rules() is the one method a Role needs besides shortName():

src/K8S/Shop/Manifest/WorkerLeaderElectionRole.phnsrc/K8S/Shop/Manifest/WorkerLeaderElectionRole.php
namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Rbac\AbstractRole;
use Klass8s\Core\Rbac\Configurator\PolicyRulesConfigurator;
use Klass8s\Core\Rbac\Verb;

class WorkerLeaderElectionRole extends AbstractRole
{
    static shortName(): string => 'worker-leader-election';

    rules(PolicyRulesConfigurator $rules): void {
        $rules->add()
            ->addApiGroups('coordination.k8s.io')
            ->addResources('leases')
            ->addVerbs(Verb::Get, Verb::Create, Verb::Update);

        $rules->add()
            ->addApiGroups('')                      // '' is the core API group
            ->addResources('pods')
            ->addVerbs(Verb::Get, Verb::List, Verb::Watch);
    }
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Rbac\AbstractRole;
use Klass8s\Core\Rbac\Configurator\PolicyRulesConfigurator;
use Klass8s\Core\Rbac\Verb;

class WorkerLeaderElectionRole extends AbstractRole
{
    public static function shortName(): string
    {
        return 'worker-leader-election';
    }

    public function rules(PolicyRulesConfigurator $rules): void
    {
        $rules->add()
            ->addApiGroups('coordination.k8s.io')
            ->addResources('leases')
            ->addVerbs(Verb::Get, Verb::Create, Verb::Update);

        $rules->add()
            ->addApiGroups('')                      // '' is the core API group
            ->addResources('pods')
            ->addVerbs(Verb::Get, Verb::List, Verb::Watch);
    }
}

Each add() starts a rule; a rule takes API groups, resources, resource names, non-resource URLs and verbs. Verb has the standard verbs (Get, List, Watch, Create, Update, Patch, Delete, DeleteCollection) and All (*); for a resource's own verbs (impersonate, bind, escalate, use), rule() returns the raw rule. AbstractClusterRole adds aggregationRule() for aggregated ClusterRoles; configureRole() and configureClusterRole() receive the generated objects.

Bindings

A binding is roleRef() and subjects(), both by class:

src/K8S/Shop/Manifest/WorkerLeaderElectionRoleBinding.phnsrc/K8S/Shop/Manifest/WorkerLeaderElectionRoleBinding.php
namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Rbac\AbstractRoleBinding;
use Klass8s\Core\Rbac\Configurator\Binding\RoleRefConfigurator;
use Klass8s\Core\Rbac\Configurator\Binding\SubjectsConfigurator;

class WorkerLeaderElectionRoleBinding extends AbstractRoleBinding
{
    // a subject names its namespace; this is a binding of config/services.yaml
    __construct(private string $namespace) {}

    static shortName(): string => 'worker-leader-election';

    roleRef(RoleRefConfigurator $ref): void => $ref->fromRoleClass(WorkerLeaderElectionRole::class);

    subjects(SubjectsConfigurator $subjects): void
        => $subjects->addServiceAccountClass(WorkerServiceAccount::class, $this->namespace);
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Rbac\AbstractRoleBinding;
use Klass8s\Core\Rbac\Configurator\Binding\RoleRefConfigurator;
use Klass8s\Core\Rbac\Configurator\Binding\SubjectsConfigurator;

class WorkerLeaderElectionRoleBinding extends AbstractRoleBinding
{
    // a subject names its namespace; this is a binding of config/services.yaml
    public function __construct(private string $namespace) {}

    public static function shortName(): string
    {
        return 'worker-leader-election';
    }

    public function roleRef(RoleRefConfigurator $ref): void
    {
        $ref->fromRoleClass(WorkerLeaderElectionRole::class);
    }

    public function subjects(SubjectsConfigurator $subjects): void
    {
        $subjects->addServiceAccountClass(WorkerServiceAccount::class, $this->namespace);
    }
}
  • fromRoleClass() and fromClusterRoleClass() resolve the name and check that the class belongs to the binding's App; withExternalApp() refers to another App's. fromRoleName() and fromClusterRoleName() take plain names.
  • addServiceAccountClass() and addServiceAccount() add ServiceAccounts, with the namespace Kubernetes requires on the subject; addUser() and addGroup() add people and groups, and the WellKnownUserOrGroup enum names the built-in ones (system:authenticated and others).

A binding without a role or without a subject fails the render rather than reaching the cluster as a binding that does nothing. AbstractClusterRoleBinding works the same way.

The whole picture

Renderedbin/console k8s:render:apps shop
# File: /shop/registry-pull.secret.yaml
apiVersion: v1
kind: Secret
data:
  .dockerconfigjson: eyJhdXRocyI6eyJyZWdpc3RyeS5kZXYuZXhhbXBsZS5jb20iOnsidXNlcm5hbWUiOiJkZXYiLCJwYXNzd29yZCI6ImRldi1vbmx5IiwiYXV0aCI6IlpHVjJPbVJsZGkxdmJteDUifX19
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: registry-pull
  name: shop-registry-pull
type: kubernetes.io/dockerconfigjson
---
# File: /shop/worker.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: worker
  name: shop-worker
spec:
  replicas: 1
  revisionHistoryLimit: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: shop
      app.kubernetes.io/component: worker
  template:
    metadata:
      annotations:
        klass8s.dev/env-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
        klass8s.dev/volume-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
      labels:
        app.kubernetes.io/name: shop
        app.kubernetes.io/component: worker
    spec:
      containers:
        -
          image: 'registry.dev.example.com/acme/shop-worker:1.4.0'
          imagePullPolicy: IfNotPresent
          name: app
      serviceAccountName: shop-worker
---
# File: /shop/worker-leader-election.role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: worker-leader-election
  name: shop-worker-leader-election
rules:
  -
    apiGroups:
      - coordination.k8s.io
    resources:
      - leases
    verbs:
      - get
      - create
      - update
  -
    apiGroups:
      - ''
    resources:
      - pods
    verbs:
      - get
      - list
      - watch
---
# File: /shop/worker-leader-election.role-binding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: worker-leader-election
  name: shop-worker-leader-election
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: shop-worker-leader-election
subjects:
  -
    apiGroup: ''
    kind: ServiceAccount
    name: shop-worker
    namespace: shop
---
# File: /shop/worker.service-account.yaml
apiVersion: v1
kind: ServiceAccount
automountServiceAccountToken: false
imagePullSecrets:
  -
    name: shop-registry-pull
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: worker
  name: shop-worker

Four small classes, no name typed twice. Rename WorkerServiceAccount and the subject, the pod spec and the ServiceAccount follow.

Next