Skip to main content

Kubernetes

Starting at version 1.5.0, Otoroshi provides a native Kubernetes support. Multiple otoroshi jobs (that are actually kubernetes controllers) are provided in order to

  • sync kubernetes secrets of type kubernetes.io/tls to otoroshi certificates
  • act as a standard ingress controller (supporting Ingress objects)
  • provide Custom Resource Definitions (CRDs) to manage Otoroshi entities from Kubernetes and act as an ingress controller with its own resources

Installing otoroshi on your kubernetes cluster​

warning

You need to have cluster admin privileges to install otoroshi and its service account, role mapping and CRDs on a kubernetes cluster. We also advise you to create a dedicated namespace (you can name it otoroshi for example) to install otoroshi

If you want to deploy otoroshi into your kubernetes cluster, you can download the deployment descriptors from https://github.com/MAIF/otoroshi/tree/master/kubernetes and use kustomize to create your own overlay.

You can also create a kustomization.yaml file with a remote base

resources:
- github.com/MAIF/otoroshi/kubernetes/kustomize/overlays/simple/?ref=v18.1.0

Then deploy it with kubectl apply -k ./overlays/myoverlay.

Helm​

The chart lives at kubernetes/helm/otoroshi/. It ships:

  • a single-pod standalone mode (default) or a Leader / Worker cluster mode (cluster.enabled=true);
  • a bundled Redis subchart that you can disable to bring your own (redis.deploy=false, set env.redisURL);
  • the Otoroshi CRDs and Kubernetes Gateway API integration (opt-in via gatewayApi.enabled=true);
  • optional PodDisruptionBudget, NetworkPolicy, HPA, validating / sidecar-injector admission webhooks, and a Helm smoke test.

Quick install:

helm repo add otoroshi https://maif.github.io/otoroshi/helm
helm install my-otoroshi otoroshi/otoroshi

Admin credentials (password, clientId, clientSecret, OTOROSHI_SECRET) are auto-generated on first install and stored in a Kubernetes Secret. They are preserved across helm upgrade via the Helm lookup function — read them back with:

kubectl -n <ns> get secret otoroshi-admin-secret -o jsonpath='{.data.password}' | base64 -d

Bring your own Secret instead (recommended for GitOps):

kubectl create secret generic my-otoroshi-creds \
--from-literal=password=$(openssl rand -hex 24) \
--from-literal=clientId=admin-api-apikey-id \
--from-literal=clientSecret=$(openssl rand -hex 32) \
--from-literal=otoroshiSecret=$(openssl rand -hex 32)

helm install my-otoroshi otoroshi/otoroshi --set env.existingSecret=my-otoroshi-creds

Common overrides:

# External / managed Redis (skip bundled subchart)
helm install my-otoroshi otoroshi/otoroshi \
--set redis.deploy=false \
--set env.redisURL=redis://redis.example.com:6379/0 \
--set env.redisPasswordExistingSecret.name=my-redis-creds \
--set env.redisPasswordExistingSecret.key=password

# Otoroshi cluster (Leader + Worker)
helm install my-otoroshi otoroshi/otoroshi \
--set cluster.enabled=true \
--set cluster.leader.replicaCount=2 \
--set cluster.worker.replicaCount=3

# Enable Kubernetes Gateway API support (install Gateway API CRDs separately)
helm install my-otoroshi otoroshi/otoroshi --set gatewayApi.enabled=true

# Cloud-provider LoadBalancer hints
helm install my-otoroshi otoroshi/otoroshi \
--set 'loadbalancer.annotations.service\.beta\.kubernetes\.io/aws-load-balancer-type=nlb' \
--set 'loadbalancer.sourceRanges[0]=10.0.0.0/8'

# Keep the public domains out of the certificate the chart generates
# (another certificate already covers them)
helm install my-otoroshi otoroshi/otoroshi \
--set certificate.publicHosts.adminUi=false \
--set certificate.publicHosts.adminApi=false \
--set certificate.publicHosts.privateApps=false

# JVM options: they win over the ones the image picks from the limits of the pods
helm install my-otoroshi otoroshi/otoroshi --set javaOpts="-XX:MaxRAMPercentage=70.0"

The chart sets no JAVA_OPTS by default: the image sizes the JVM from resources.limits, with 60% of the memory limit for the heap and thread pools that follow the CPU limit, see memory and JVM options. If you remove the CPU limit, add -XX:ActiveProcessorCount=<n> to javaOpts, otherwise the JVM sizes itself for every CPU of the node. Autoscaling (autoscaling.enabled) only targets the CPU by default: the heap of a JVM fills up whatever the traffic, so a memory target would keep the deployment at its maximum.

The chart also creates a proxy.otoroshi.io/v1 Certificate for the Otoroshi services, signed by the Otoroshi intermediate CA (certificate.issuer). It always covers the in-cluster service names, as cluster mode mTLS between the workers and the leader API relies on them, plus otoroshi.<env.domain>, otoroshi-api.<env.domain> and privateapps.<env.domain>. Turn those public ones off with certificate.publicHosts.* when you already have a certificate for these domains: when two certificates match the same host, the one Otoroshi presents at handshake time is not deterministic.

Helm does not upgrade the CRDs of a release: see upgrading with Helm before an upgrade.

For the full list of values (pod scheduling, security contexts, extraEnv, extra volumes, JAVA_OPTS, autoscaling, NetworkPolicy, …), see values.yaml.

Below, you will find example of deployment. Do not hesitate to adapt them to your needs. Those descriptors have value placeholders that you will need to replace with actual values like

env:
- name: APP_STORAGE_ROOT
value: otoroshi
- name: APP_DOMAIN
value: ${domain}

you will have to edit it to make it look like

env:
- name: APP_STORAGE_ROOT
value: otoroshi
- name: APP_DOMAIN
value: 'apis.my.domain'

if you don't want to use placeholders and environment variables, you can create a secret containing the configuration file of otoroshi

apiVersion: v1
kind: Secret
metadata:
name: otoroshi-config
type: Opaque
stringData:
oto.conf: >
include "application.conf"
otoroshi {
storage = "redis"
domain = "apis.my.domain"
}

and mount it in the otoroshi container

apiVersion: apps/v1
kind: Deployment
metadata:
name: otoroshi-deployment
spec:
selector:
matchLabels:
run: otoroshi-deployment
template:
metadata:
labels:
run: otoroshi-deployment
spec:
serviceAccountName: otoroshi-admin-user
terminationGracePeriodSeconds: 60
hostNetwork: false
containers:
- image: maif/otoroshi:18.1.0
imagePullPolicy: IfNotPresent
name: otoroshi
args: ['-Dconfig.file=/usr/app/otoroshi/conf/oto.conf']
ports:
- containerPort: 8080
name: "http"
protocol: TCP
- containerPort: 8443
name: "https"
protocol: TCP
volumeMounts:
- name: otoroshi-config
mountPath: "/usr/app/otoroshi/conf"
readOnly: true
volumes:
- name: otoroshi-config
secret:
secretName: otoroshi-config
...

You can also create several secrets for each placeholder, mount them to the otoroshi container then use their file path as value

env:
- name: APP_STORAGE_ROOT
value: otoroshi
- name: APP_DOMAIN
value: 'file:///the/path/of/the/secret/file'

you can use the same trick in the config. file itself

Upgrading with Helm​

helm repo update
helm upgrade my-otoroshi otoroshi/otoroshi -f my-values.yaml
warning

Helm only installs CRDs (under the chart's crds/ directory) on the first helm install. When upgrading Otoroshi to a newer version, re-apply the CRDs manually:

kubectl apply -f https://raw.githubusercontent.com/MAIF/otoroshi/master/kubernetes/helm/otoroshi/crds/crds.yaml
# or, via otoroshictl (includes any custom extension CRDs):
otoroshictl resources crds | kubectl apply -f -

See the updating rbac and crds section below.

Otoroshi rewrites two fields of its admission webhooks at runtime: clientConfig.caBundle, where it injects its CA, and failurePolicy, which it switches from Ignore to Fail once it can answer. So the chart renders the live values of these two fields, read with lookup, and its defaults ("" and Ignore) only on the first install.

Helm 4 applies the manifests with server-side apply: helm install defaults to --server-side=true, and helm upgrade keeps the method of the previous release. With the charts up to 18.0.1, which always render "" and Ignore, the upgrade of a release installed with Helm 4 fails with:

Error: UPGRADE FAILED: conflict occurred while applying object /otoroshi-admission-webhook-validation admissionregistration.k8s.io/v1, Kind=ValidatingWebhookConfiguration: Apply failed with 2 conflicts: conflicts with "pekko-http" using admissionregistration.k8s.io/v1:
- .webhooks[name="otoroshi-admission-webhook.otoroshi.io"].failurePolicy
- .webhooks[name="otoroshi-admission-webhook.otoroshi.io"].clientConfig.caBundle

pekko-http is Otoroshi. Helm applies the other resources anyway, the Deployments included, and the webhook keeps the values Otoroshi set, but the release is marked failed. Upgrade with a newer chart, or pass --force-conflicts: Helm resets the two fields, and Otoroshi sets them again on the next run of its CRDs job (syncIntervalSeconds, 60 seconds by default).

Tools that render the chart with helm template, like Argo CD, get no answer from lookup and always render the defaults: tell them to ignore these two fields (with Argo CD, ignoreDifferences on .webhooks[].clientConfig.caBundle and .webhooks[].failurePolicy, and the RespectIgnoreDifferences=true sync option).

Note on bare metal kubernetes cluster installation​

note

Bare metal kubernetes clusters don't come with support for external loadbalancers (service of type LoadBalancer). So you will have to provide this feature in order to route external TCP traffic to Otoroshi containers running inside the kubernetes cluster. You can use projects like MetalLB that provide software LoadBalancer services to bare metal clusters or you can use and customize examples below.

warning

We don't recommand running Otoroshi behind an existing ingress controller (or something like that) as you will not be able to use features like TCP proxying, TLS, mTLS, etc. Also, this additional layer of reverse proxy will increase call latencies.

Common manifests​

Each overlay of kubernetes/kustomize/overlays builds on base/, the manifests that are always needed (otoroshi CRDs, service account, role, etc.), and composes the components of kubernetes/kustomize/components it needs. The readme of each overlay lists its prerequisites and what to override. Deploy one with kubectl apply -k. The redis component is not mandatory, it's just an example: you can use your own existing setup.

warning

When updating an existing otoroshi cluster, new kubernetes entities can be expected to be available by the kubernetes plugins. So it could be helpful to check if that's the case before deploying the new version. If you want to automate this process, you can check the following section

---
kind: ServiceAccount
apiVersion: v1
metadata:
name: otoroshi-admin-user
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: otoroshi-admin-user
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: otoroshi-admin-user
subjects:
- kind: ServiceAccount
name: otoroshi-admin-user
namespace: $namespace
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: otoroshi-admin-user
rules:
- apiGroups:
- ""
resources:
- services
- endpoints
- secrets
- configmaps
- deployments
- namespaces
- pods
verbs:
- get
- list
- watch
- apiGroups:
- "apps"
resources:
- deployments
verbs:
- get
- list
- watch
- apiGroups:
- discovery.k8s.io
resources:
- endpointslices
verbs:
- get
- list
- watch
- apiGroups:
- ""
resources:
- secrets
- configmaps
verbs:
- update
- create
- delete
- apiGroups:
- networking.k8s.io
- extensions
resources:
- ingresses
- ingressclasses
verbs:
- get
- list
- watch
- apiGroups:
- networking.k8s.io
- extensions
resources:
- ingresses/status
verbs:
- update
- apiGroups:
- admissionregistration.k8s.io
resources:
- validatingwebhookconfigurations
- mutatingwebhookconfigurations
verbs:
- get
- update
- patch
- apiGroups:
- proxy.otoroshi.io
resources:
- routes
- backends
- route-compositions
- service-descriptors
- tcp-services
- error-templates
- apikeys
- certificates
- jwt-verifiers
- auth-modules
- admin-sessions
- admins
- auth-module-users
- service-groups
- organizations
- tenants
- teams
- user-rights-policies
- data-exporters
- scripts
- wasm-plugins
- global-configs
- green-scores
- coraza-configs
- http-listeners
- plugins
verbs:
- get
- list
- watch

Updating rbac and crds when upgrading Otoroshi using otoroshictl​

Updating rbac and crds definition for an Otoroshi upgrade can be tedious and is quite a manual process. But it can be largely simplified by using otoroshictl from our friends at Cloud APIM.

otoroshictl has some commands to automate the creation for rbac.yaml and crds.yaml for your otoroshi deployments. Using it is quite handy as it will also generate the descriptor for any custom extension your using on your Otoroshi instance.

First add your otoroshi instance to otoroshictl (it may be already done, in that case, just use it with otoroshictl config use new-cluster).

$ otoroshictl config add new-cluster \
--current \
--hostname otoroshi.foo.bar \
--port 8443 \
--tls \
--client-id xxx \
--client-secret xxxxx

then you can generate the crds.yaml file using the command

$ otoroshictl resources crds > crds.yaml

and you can generate the rbac.yaml file using the command

$ otoroshictl resources rbac --namespace mynamespace > rbac.yaml

you can also directly apply it on your kubernetes cluster

$ otoroshictl resources rbac --namespace mynamespace | kubectl apply -f -
$ otoroshictl resources crds | kubectl apply -f -

Deploy a simple otoroshi instanciation on a cloud provider managed kubernetes cluster​

Here we have 2 replicas connected to the same redis instance. Nothing fancy. We use a service of type LoadBalancer to expose otoroshi to the rest of the world. You have to setup your DNS to bind otoroshi domain names to the LoadBalancer external CNAME (see the example below)

See overlays/simple and its readme.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: otoroshi

resources:
# External-facing Service (LoadBalancer) lives in deployment.yaml.
- ../../base
- deployment.yaml

components:
# Otoroshi Deployment + internal Service + Certificate (single-mode).
- ../../components/single-deployment
# Provides the otoroshi-initial-customization ConfigMap (mounted at
# /etc/otoroshi/initial-customization.json). Shared across the simple*
# overlays; cluster* overlays use initial-customization-cluster instead.
- ../../components/initial-customization-single
# Opt-in add-ons — uncomment to enable.
# - ../../components/webhooks
# - ../../components/redis
# - ../../components/hpa
# - ../../components/coredns
# - ../../components/gateway-api
# - ../../components/pdb-single
# - ../../components/network-policy

# Recommended Kubernetes labelset applied to every resource (resource labels
# and pod template labels, but NOT to .spec.selector — selectors are immutable
# on existing Deployments). Override `instance` per environment.
labels:
- includeSelectors: false
pairs:
app.kubernetes.io/name: otoroshi
app.kubernetes.io/instance: simple
app.kubernetes.io/version: "18.1.0"
app.kubernetes.io/part-of: otoroshi
app.kubernetes.io/managed-by: kustomize

# Image — bump with `kustomize edit set image maif/otoroshi=maif/otoroshi:NEW`
images:
- name: maif/otoroshi
newTag: 18.1.0

# Replicas — bump with `kustomize edit set replicas otoroshi-deployment=N`
replicas:
- name: otoroshi-deployment
count: 2

# Admin credentials. Override before deploying to anything other than a
# throwaway cluster. For production, replace this generator with a
# `behavior: replace` one in a personal overlay, or feed values from a real
# secret manager (External Secrets, SOPS, Vault, …).
secretGenerator:
- name: otoroshi-admin-secret
literals:
- password=password
- clientId=admin-api-apikey-id
- clientSecret=admin-api-apikey-secret
- otoroshiSecret=verysecretvaluethatyoumustoverwrite
# Redis connection. The full URL is in a Secret (not a ConfigMap) because it
# may contain a password (redis://:password@host:port/db). The default points
# at the bundled `components/redis` Service; override here when bringing your
# own Redis. The `components/redis` component overrides this Secret to inject
# the auto-generated password into the URL.
- name: otoroshi-redis-secret
literals:
- redisUrl=redis://redis-leader-service:6379/0

# Non-secret configuration.
configMapGenerator:
- name: otoroshi-config
literals:
- domain=oto.tools
# Initial admin login (OTOROSHI_INITIAL_ADMIN_LOGIN). Override here, or
# remove to fall back to Otoroshi's built-in default (admin@otoroshi.io).
- adminLogin=admin@otoroshi.io

Deploy a simple otoroshi instanciation on a bare metal kubernetes cluster​

Here we have 2 replicas connected to the same redis instance. Nothing fancy. The otoroshi instance are exposed as nodePort so you'll have to add a loadbalancer in front of your kubernetes nodes to route external traffic (TCP) to your otoroshi instances. You have to setup your DNS to bind otoroshi domain names to your loadbalancer (see the example below).

See overlays/simple-baremetal and its readme.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: otoroshi

resources:
# External-facing Service (NodePort) lives in deployment.yaml.
- ../../base
- deployment.yaml

components:
- ../../components/single-deployment
- ../../components/initial-customization-single
# Opt-in add-ons — uncomment to enable.
# - ../../components/webhooks
# - ../../components/redis
# - ../../components/hpa
# - ../../components/coredns
# - ../../components/gateway-api
# - ../../components/pdb-single
# - ../../components/network-policy

labels:
- includeSelectors: false
pairs:
app.kubernetes.io/name: otoroshi
app.kubernetes.io/instance: simple-baremetal
app.kubernetes.io/version: "18.1.0"
app.kubernetes.io/part-of: otoroshi
app.kubernetes.io/managed-by: kustomize

images:
- name: maif/otoroshi
newTag: 18.1.0

replicas:
- name: otoroshi-deployment
count: 2

secretGenerator:
- name: otoroshi-admin-secret
literals:
- password=password
- clientId=admin-api-apikey-id
- clientSecret=admin-api-apikey-secret
- otoroshiSecret=verysecretvaluethatyoumustoverwrite
- name: otoroshi-redis-secret
literals:
- redisUrl=redis://redis-leader-service:6379/0

configMapGenerator:
- name: otoroshi-config
literals:
- domain=oto.tools
# Initial admin login (OTOROSHI_INITIAL_ADMIN_LOGIN). Override here, or
# remove to fall back to Otoroshi's built-in default (admin@otoroshi.io).
- adminLogin=admin@otoroshi.io

Deploy a simple otoroshi instanciation on a bare metal kubernetes cluster using a DaemonSet​

Here we have one otoroshi instance on each kubernetes node (with the otoroshi-kind: instance label) with redis persistance. The otoroshi instances are exposed as hostPort so you'll have to add a loadbalancer in front of your kubernetes nodes to route external traffic (TCP) to your otoroshi instances. You have to setup your DNS to bind otoroshi domain names to your loadbalancer (see the example below).

See overlays/simple-baremetal-daemonset and its readme.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: otoroshi

resources:
- ../../base
- deployment.yaml

components:
- ../../components/initial-customization-single
# Opt-in add-ons — uncomment to enable.
# - ../../components/webhooks
# - ../../components/redis
# - ../../components/hpa
# - ../../components/coredns
# - ../../components/gateway-api
# - ../../components/pdb-single
# - ../../components/network-policy

labels:
- includeSelectors: false
pairs:
app.kubernetes.io/name: otoroshi
app.kubernetes.io/instance: simple-baremetal-daemonset
app.kubernetes.io/version: "18.1.0"
app.kubernetes.io/part-of: otoroshi
app.kubernetes.io/managed-by: kustomize

images:
- name: maif/otoroshi
newTag: 18.1.0

# (no `replicas:` block — this overlay uses a DaemonSet, which has one pod per
# matching node and ignores `replicas`.)

secretGenerator:
- name: otoroshi-admin-secret
literals:
- password=password
- clientId=admin-api-apikey-id
- clientSecret=admin-api-apikey-secret
- otoroshiSecret=verysecretvaluethatyoumustoverwrite
- name: otoroshi-redis-secret
literals:
- redisUrl=redis://redis-leader-service:6379/0

configMapGenerator:
- name: otoroshi-config
literals:
- domain=oto.tools
# Initial admin login (OTOROSHI_INITIAL_ADMIN_LOGIN). Override here, or
# remove to fall back to Otoroshi's built-in default (admin@otoroshi.io).
- adminLogin=admin@otoroshi.io

Deploy an otoroshi cluster on a cloud provider managed kubernetes cluster​

Here we have 2 replicas of an otoroshi leader connected to a redis instance and 2 replicas of an otoroshi worker connected to the leader. We use a service of type LoadBalancer to expose otoroshi leader/worker to the rest of the world. You have to setup your DNS to bind otoroshi domain names to the LoadBalancer external CNAME (see the example below)

See overlays/cluster and its readme.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: otoroshi

resources:
# External-facing LoadBalancer Services (leader + worker) live in
# deployment.yaml.
- ../../base
- deployment.yaml

components:
- ../../components/cluster-deployments
- ../../components/initial-customization-cluster
# Opt-in add-ons — uncomment to enable.
# - ../../components/webhooks
# - ../../components/redis
# - ../../components/hpa
# - ../../components/coredns
# - ../../components/gateway-api
# - ../../components/pdb-cluster
# - ../../components/network-policy

labels:
- includeSelectors: false
pairs:
app.kubernetes.io/name: otoroshi
app.kubernetes.io/instance: cluster
app.kubernetes.io/version: "18.1.0"
app.kubernetes.io/part-of: otoroshi
app.kubernetes.io/managed-by: kustomize

images:
- name: maif/otoroshi
newTag: 18.1.0

replicas:
- name: otoroshi-leader-deployment
count: 2
- name: otoroshi-worker-deployment
count: 2

secretGenerator:
- name: otoroshi-admin-secret
literals:
- password=password
- clientId=admin-api-apikey-id
- clientSecret=admin-api-apikey-secret
- otoroshiSecret=verysecretvaluethatyoumustoverwrite
- name: otoroshi-redis-secret
literals:
- redisUrl=redis://redis-leader-service:6379/0

configMapGenerator:
- name: otoroshi-config
literals:
- domain=oto.tools
# Initial admin login (OTOROSHI_INITIAL_ADMIN_LOGIN). Override here, or
# remove to fall back to Otoroshi's built-in default (admin@otoroshi.io).
- adminLogin=admin@otoroshi.io

Deploy an otoroshi cluster on a bare metal kubernetes cluster​

Here we have 2 replicas of otoroshi leader connected to the same redis instance and 2 replicas for otoroshi worker. The otoroshi instances are exposed as nodePort so you'll have to add a loadbalancer in front of your kubernetes nodes to route external traffic (TCP) to your otoroshi instances. You have to setup your DNS to bind otoroshi domain names to your loadbalancer (see the example below).

See overlays/cluster-baremetal and its readme.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: otoroshi

resources:
- ../../base

components:
- ../../components/cluster-deployments
- ../../components/initial-customization-cluster
# Opt-in add-ons — uncomment to enable.
# - ../../components/webhooks
# - ../../components/redis
# - ../../components/hpa
# - ../../components/coredns
# - ../../components/gateway-api
# - ../../components/pdb-cluster
# - ../../components/network-policy

# deployment.yaml here is NOT a resource — it's a strategic-merge patch that
# changes the cluster-deployments component's leader/worker Services from
# ClusterIP to NodePort, and pins the four nodePort values documented in the
# top-level readme.
patches:
- path: deployment.yaml

labels:
- includeSelectors: false
pairs:
app.kubernetes.io/name: otoroshi
app.kubernetes.io/instance: cluster-baremetal
app.kubernetes.io/version: "18.1.0"
app.kubernetes.io/part-of: otoroshi
app.kubernetes.io/managed-by: kustomize

images:
- name: maif/otoroshi
newTag: 18.1.0

replicas:
- name: otoroshi-leader-deployment
count: 2
- name: otoroshi-worker-deployment
count: 2

secretGenerator:
- name: otoroshi-admin-secret
literals:
- password=password
- clientId=admin-api-apikey-id
- clientSecret=admin-api-apikey-secret
- otoroshiSecret=verysecretvaluethatyoumustoverwrite
- name: otoroshi-redis-secret
literals:
- redisUrl=redis://redis-leader-service:6379/0

configMapGenerator:
- name: otoroshi-config
literals:
- domain=oto.tools
# Initial admin login (OTOROSHI_INITIAL_ADMIN_LOGIN). Override here, or
# remove to fall back to Otoroshi's built-in default (admin@otoroshi.io).
- adminLogin=admin@otoroshi.io

Deploy an otoroshi cluster on a bare metal kubernetes cluster using DaemonSet​

Here we have 1 otoroshi leader instance on each kubernetes node (with the otoroshi-kind: leader label) connected to the same redis instance and 1 otoroshi worker instance on each kubernetes node (with the otoroshi-kind: worker label). The otoroshi instances are exposed as nodePort so you'll have to add a loadbalancer in front of your kubernetes nodes to route external traffic (TCP) to your otoroshi instances. You have to setup your DNS to bind otoroshi domain names to your loadbalancer (see the example below).

See overlays/cluster-baremetal-daemonset and its readme.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: otoroshi

resources:
- ../../base
- deployment.yaml

components:
- ../../components/initial-customization-cluster
# Opt-in add-ons — uncomment to enable.
# - ../../components/webhooks
# - ../../components/redis
# - ../../components/hpa
# - ../../components/coredns
# - ../../components/gateway-api
# - ../../components/pdb-cluster
# - ../../components/network-policy

labels:
- includeSelectors: false
pairs:
app.kubernetes.io/name: otoroshi
app.kubernetes.io/instance: cluster-baremetal-daemonset
app.kubernetes.io/version: "18.1.0"
app.kubernetes.io/part-of: otoroshi
app.kubernetes.io/managed-by: kustomize

images:
- name: maif/otoroshi
newTag: 18.1.0

# (no `replicas:` block — this overlay uses DaemonSets, which have one pod per
# matching node and ignore `replicas`.)

secretGenerator:
- name: otoroshi-admin-secret
literals:
- password=password
- clientId=admin-api-apikey-id
- clientSecret=admin-api-apikey-secret
- otoroshiSecret=verysecretvaluethatyoumustoverwrite
- name: otoroshi-redis-secret
literals:
- redisUrl=redis://redis-leader-service:6379/0

configMapGenerator:
- name: otoroshi-config
literals:
- domain=oto.tools
# Initial admin login (OTOROSHI_INITIAL_ADMIN_LOGIN). Override here, or
# remove to fall back to Otoroshi's built-in default (admin@otoroshi.io).
- adminLogin=admin@otoroshi.io

Using Otoroshi as an Ingress Controller​

If you want to use Otoroshi as an Ingress Controller, just go to the danger zone, and in Global plugins add the job named Kubernetes Ingress Controller.

Then add the following configuration for the job (with your own tweaks of course)

{
"KubernetesConfig": {
"enabled": true,
"endpoint": "https://127.0.0.1:6443",
"token": "eyJhbGciOiJSUzI....F463SrpOehQRaQ",
"namespaces": [
"*"
]
}
}

the configuration can have the following values

{
"KubernetesConfig": {
"endpoint": "https://127.0.0.1:6443", // the endpoint to talk to the kubernetes api, optional
"token": "xxxx", // the bearer token to talk to the kubernetes api, optional
"userPassword": "user:password", // the user password tuple to talk to the kubernetes api, optional
"caCert": "/etc/ca.cert", // the ca cert file path to talk to the kubernetes api, optional
"trust": false, // trust any cert to talk to the kubernetes api, optional
"namespaces": ["*"], // the watched namespaces
"labels": ["label"], // the watched namespaces
"ingressClasses": ["otoroshi"], // the watched kubernetes.io/ingress.class annotations, can be *
"defaultGroup": "default", // the group to put services in otoroshi
"ingresses": true, // sync ingresses
"crds": false, // sync crds
"kubeLeader": false, // delegate leader election to kubernetes, to know where the sync job should run
"restartDependantDeployments": true, // when a secret/cert changes from otoroshi sync, restart dependant deployments
"templates": { // template for entities that will be merged with kubernetes entities. can be "default" to use otoroshi default templates
"service-group": {},
"service-descriptor": {},
"apikeys": {},
"global-config": {},
"jwt-verifier": {},
"tcp-service": {},
"certificate": {},
"auth-module": {},
"data-exporter": {},
"script": {},
"organization": {},
"team": {},
"data-exporter": {},
"routes": {},
"route-compositions": {},
"backends": {}
}
}
}

If endpoint is not defined, Otoroshi will try to get it from $KUBERNETES_SERVICE_HOST and $KUBERNETES_SERVICE_PORT. If token is not defined, Otoroshi will try to get it from the file at /var/run/secrets/kubernetes.io/serviceaccount/token. If caCert is not defined, Otoroshi will try to get it from the file at /var/run/secrets/kubernetes.io/serviceaccount/ca.crt. If $KUBECONFIG is defined, endpoint, token and caCert will be read from the current context of the file referenced by it.

Now you can deploy your first service ;)

Deploy an ingress route​

now let's say you want to deploy an http service and route to the outside world through otoroshi

---
apiVersion: apps/v1
kind: Deployment
metadata:
name: http-app-deployment
spec:
selector:
matchLabels:
run: http-app-deployment
replicas: 1
template:
metadata:
labels:
run: http-app-deployment
spec:
containers:
- image: kennethreitz/httpbin
imagePullPolicy: IfNotPresent
name: otoroshi
ports:
- containerPort: 80
name: "http"
---
apiVersion: v1
kind: Service
metadata:
name: http-app-service
spec:
ports:
- port: 8080
targetPort: http
name: http
selector:
run: http-app-deployment
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: http-app-ingress
annotations:
kubernetes.io/ingress.class: otoroshi
spec:
tls:
- hosts:
- httpapp.foo.bar
secretName: http-app-cert
rules:
- host: httpapp.foo.bar
http:
paths:
- path: /
backend:
serviceName: http-app-service
servicePort: 8080

once deployed, otoroshi will sync with kubernetes and create the corresponding service to route your app. You will be able to access your app with

curl -X GET https://httpapp.foo.bar/get

Support for Ingress Classes​

Since Kubernetes 1.18, you can use IngressClass type of manifest to specify which ingress controller you want to use for a deployment (https://kubernetes.io/blog/2020/04/02/improvements-to-the-ingress-api-in-kubernetes-1.18/#extended-configuration-with-ingress-classes). Otoroshi is fully compatible with this new manifest kind. To use it, configure the Ingress job to match your controller

{
"KubernetesConfig": {
...
"ingressClasses": ["otoroshi.io/ingress-controller"],
...
}
}

then you have to deploy an IngressClass to declare Otoroshi as an ingress controller

apiVersion: "networking.k8s.io/v1beta1"
kind: "IngressClass"
metadata:
name: "otoroshi-ingress-controller"
spec:
controller: "otoroshi.io/ingress-controller"
parameters:
apiGroup: "proxy.otoroshi.io/v1alpha"
kind: "IngressParameters"
name: "otoroshi-ingress-controller"

and use it in your Ingress

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: http-app-ingress
spec:
ingressClassName: otoroshi-ingress-controller
tls:
- hosts:
- httpapp.foo.bar
secretName: http-app-cert
rules:
- host: httpapp.foo.bar
http:
paths:
- path: /
backend:
serviceName: http-app-service
servicePort: 8080

Use multiple ingress controllers​

It is of course possible to use multiple ingress controller at the same time (https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/#using-multiple-ingress-controllers) using the annotation kubernetes.io/ingress.class. By default, otoroshi reacts to the class otoroshi, but you can make it the default ingress controller with the following config

{
"KubernetesConfig": {
...
"ingressClass": "*",
...
}
}

Supported annotations​

if you need to customize the service descriptor behind an ingress rule, you can use some annotations. If you need better customisation, just go to the CRDs part. The following annotations are supported :

  • ingress.otoroshi.io/groups
  • ingress.otoroshi.io/group
  • ingress.otoroshi.io/groupId
  • ingress.otoroshi.io/name
  • ingress.otoroshi.io/targetsLoadBalancing
  • ingress.otoroshi.io/stripPath
  • ingress.otoroshi.io/enabled
  • ingress.otoroshi.io/userFacing
  • ingress.otoroshi.io/privateApp
  • ingress.otoroshi.io/forceHttps
  • ingress.otoroshi.io/maintenanceMode
  • ingress.otoroshi.io/buildMode
  • ingress.otoroshi.io/strictlyPrivate
  • ingress.otoroshi.io/sendOtoroshiHeadersBack
  • ingress.otoroshi.io/readOnly
  • ingress.otoroshi.io/xForwardedHeaders
  • ingress.otoroshi.io/overrideHost
  • ingress.otoroshi.io/allowHttp10
  • ingress.otoroshi.io/logAnalyticsOnServer
  • ingress.otoroshi.io/useAkkaHttpClient
  • ingress.otoroshi.io/useNewWSClient
  • ingress.otoroshi.io/tcpUdpTunneling
  • ingress.otoroshi.io/detectApiKeySooner
  • ingress.otoroshi.io/letsEncrypt
  • ingress.otoroshi.io/publicPatterns
  • ingress.otoroshi.io/privatePatterns
  • ingress.otoroshi.io/additionalHeaders
  • ingress.otoroshi.io/additionalHeadersOut
  • ingress.otoroshi.io/missingOnlyHeadersIn
  • ingress.otoroshi.io/missingOnlyHeadersOut
  • ingress.otoroshi.io/removeHeadersIn
  • ingress.otoroshi.io/removeHeadersOut
  • ingress.otoroshi.io/headersVerification
  • ingress.otoroshi.io/matchingHeaders
  • ingress.otoroshi.io/ipFiltering.whitelist
  • ingress.otoroshi.io/ipFiltering.blacklist
  • ingress.otoroshi.io/api.exposeApi
  • ingress.otoroshi.io/api.openApiDescriptorUrl
  • ingress.otoroshi.io/healthCheck.enabled
  • ingress.otoroshi.io/healthCheck.url
  • ingress.otoroshi.io/jwtVerifier.ids
  • ingress.otoroshi.io/jwtVerifier.enabled
  • ingress.otoroshi.io/jwtVerifier.excludedPatterns
  • ingress.otoroshi.io/authConfigRef
  • ingress.otoroshi.io/redirection.enabled
  • ingress.otoroshi.io/redirection.code
  • ingress.otoroshi.io/redirection.to
  • ingress.otoroshi.io/clientValidatorRef
  • ingress.otoroshi.io/transformerRefs
  • ingress.otoroshi.io/transformerConfig
  • ingress.otoroshi.io/accessValidator.enabled
  • ingress.otoroshi.io/accessValidator.excludedPatterns
  • ingress.otoroshi.io/accessValidator.refs
  • ingress.otoroshi.io/accessValidator.config
  • ingress.otoroshi.io/preRouting.enabled
  • ingress.otoroshi.io/preRouting.excludedPatterns
  • ingress.otoroshi.io/preRouting.refs
  • ingress.otoroshi.io/preRouting.config
  • ingress.otoroshi.io/issueCert
  • ingress.otoroshi.io/issueCertCA
  • ingress.otoroshi.io/gzip.enabled
  • ingress.otoroshi.io/gzip.excludedPatterns
  • ingress.otoroshi.io/gzip.whiteList
  • ingress.otoroshi.io/gzip.blackList
  • ingress.otoroshi.io/gzip.bufferSize
  • ingress.otoroshi.io/gzip.chunkedThreshold
  • ingress.otoroshi.io/gzip.compressionLevel
  • ingress.otoroshi.io/cors.enabled
  • ingress.otoroshi.io/cors.allowOrigin
  • ingress.otoroshi.io/cors.exposeHeaders
  • ingress.otoroshi.io/cors.allowHeaders
  • ingress.otoroshi.io/cors.allowMethods
  • ingress.otoroshi.io/cors.excludedPatterns
  • ingress.otoroshi.io/cors.maxAge
  • ingress.otoroshi.io/cors.allowCredentials
  • ingress.otoroshi.io/clientConfig.useCircuitBreaker
  • ingress.otoroshi.io/clientConfig.retries
  • ingress.otoroshi.io/clientConfig.maxErrors
  • ingress.otoroshi.io/clientConfig.retryInitialDelay
  • ingress.otoroshi.io/clientConfig.backoffFactor
  • ingress.otoroshi.io/clientConfig.connectionTimeout
  • ingress.otoroshi.io/clientConfig.idleTimeout
  • ingress.otoroshi.io/clientConfig.callAndStreamTimeout
  • ingress.otoroshi.io/clientConfig.callTimeout
  • ingress.otoroshi.io/clientConfig.globalTimeout
  • ingress.otoroshi.io/clientConfig.sampleInterval
  • ingress.otoroshi.io/enforceSecureCommunication
  • ingress.otoroshi.io/sendInfoToken
  • ingress.otoroshi.io/sendStateChallenge
  • ingress.otoroshi.io/secComHeaders.claimRequestName
  • ingress.otoroshi.io/secComHeaders.stateRequestName
  • ingress.otoroshi.io/secComHeaders.stateResponseName
  • ingress.otoroshi.io/secComTtl
  • ingress.otoroshi.io/secComVersion
  • ingress.otoroshi.io/secComInfoTokenVersion
  • ingress.otoroshi.io/secComExcludedPatterns
  • ingress.otoroshi.io/secComSettings.size
  • ingress.otoroshi.io/secComSettings.secret
  • ingress.otoroshi.io/secComSettings.base64
  • ingress.otoroshi.io/secComUseSameAlgo
  • ingress.otoroshi.io/secComAlgoChallengeOtoToBack.size
  • ingress.otoroshi.io/secComAlgoChallengeOtoToBack.secret
  • ingress.otoroshi.io/secComAlgoChallengeOtoToBack.base64
  • ingress.otoroshi.io/secComAlgoChallengeBackToOto.size
  • ingress.otoroshi.io/secComAlgoChallengeBackToOto.secret
  • ingress.otoroshi.io/secComAlgoChallengeBackToOto.base64
  • ingress.otoroshi.io/secComAlgoInfoToken.size
  • ingress.otoroshi.io/secComAlgoInfoToken.secret
  • ingress.otoroshi.io/secComAlgoInfoToken.base64
  • ingress.otoroshi.io/securityExcludedPatterns

for more informations about it, just go to https://maif.github.io/otoroshi/swagger-ui/index.html

with the previous example, the ingress does not define any apikey, so the route is public. If you want to enable apikeys on it, you can deploy the following descriptor

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: http-app-ingress
annotations:
kubernetes.io/ingress.class: otoroshi
ingress.otoroshi.io/group: http-app-group
ingress.otoroshi.io/forceHttps: 'true'
ingress.otoroshi.io/sendOtoroshiHeadersBack: 'true'
ingress.otoroshi.io/overrideHost: 'true'
ingress.otoroshi.io/allowHttp10: 'false'
ingress.otoroshi.io/publicPatterns: ''
spec:
tls:
- hosts:
- httpapp.foo.bar
secretName: http-app-cert
rules:
- host: httpapp.foo.bar
http:
paths:
- path: /
backend:
serviceName: http-app-service
servicePort: 8080

now you can use an existing apikey in the http-app-group to access your app

curl -X GET https://httpapp.foo.bar/get -u existing-apikey-1:secret-1

Use Otoroshi CRDs for a better/full integration​

Otoroshi provides some Custom Resource Definitions for kubernetes in order to manage Otoroshi related entities in kubernetes

  • routes
  • backends
  • route-compositions
  • tcp-services
  • error-templates
  • apikeys
  • certificates
  • jwt-verifiers
  • auth-modules
  • admin-sessions
  • admins
  • auth-module-users
  • service-groups
  • organizations
  • tenants
  • teams
  • user-rights-policies
  • data-exporters
  • wasm-plugins
  • global-configs
  • green-scores
  • coraza-configs

using CRDs, you will be able to deploy and manager those entities from kubectl or the kubernetes api like

sudo kubectl get apikeys --all-namespaces
sudo kubectl get routes --all-namespaces
curl -X GET \
-H 'Authorization: Bearer eyJhbGciOiJSUzI....F463SrpOehQRaQ' \
-H 'Accept: application/json' -k \
https://127.0.0.1:6443/apis/proxy.otoroshi.io/v1/apikeys | jq

You can see this as better Ingress resources. Like any Ingress resource can define which controller it uses (using the kubernetes.io/ingress.class annotation), you can chose another kind of resource instead of Ingress. With Otoroshi CRDs you can even define resources like Certificate, Apikey, AuthModules, JwtVerifier, etc. It will help you to use all the power of Otoroshi while using the deployment model of kubernetes.

warning

when using Otoroshi CRDs, Kubernetes becomes the single source of truth for the synced entities. It means that any value in the descriptors deployed will overrides the one in Otoroshi datastore each time it's synced. So be careful if you use the Otoroshi UI or the API, some changes in configuration may be overriden by CRDs sync job.

warning

when using Otoroshi CRDs, all the kubernetes accounts/users that need to access/write Otoroshi CRDs resources will need to be able to access those with the according rights.

Resources examples​

apiVersion: proxy.otoroshi.io/v1
kind: ServiceGroup
metadata:
name: http-app-group
annotations:
io.otoroshi/id: http-app-group
spec:
description: a group to hold services about the http-app

Configuration​

To configure it, just go to the danger zone, and in Global plugins add the job named Kubernetes Otoroshi CRDs Controller. Then add the following configuration for the job (with your own tweak of course)

{
"KubernetesConfig": {
"enabled": true,
"crds": true,
"endpoint": "https://127.0.0.1:6443",
"token": "eyJhbGciOiJSUzI....F463SrpOehQRaQ",
"namespaces": [
"*"
]
}
}

the configuration can have the following values

{
"KubernetesConfig": {
"endpoint": "https://127.0.0.1:6443", // the endpoint to talk to the kubernetes api, optional
"token": "xxxx", // the bearer token to talk to the kubernetes api, optional
"userPassword": "user:password", // the user password tuple to talk to the kubernetes api, optional
"caCert": "/etc/ca.cert", // the ca cert file path to talk to the kubernetes api, optional
"trust": false, // trust any cert to talk to the kubernetes api, optional
"namespaces": ["*"], // the watched namespaces
"labels": ["label"], // the watched namespaces
"ingressClasses": ["otoroshi"], // the watched kubernetes.io/ingress.class annotations, can be *
"defaultGroup": "default", // the group to put services in otoroshi
"ingresses": false, // sync ingresses
"crds": true, // sync crds
"crdsKinds": { "include": ["*"], "exclude": [], "namespaces": {} }, // the kinds of entities the job reads, see below
"kubeLeader": false, // delegate leader election to kubernetes, to know where the sync job should run
"restartDependantDeployments": true, // when a secret/cert changes from otoroshi sync, restart dependant deployments
"templates": { // template for entities that will be merged with kubernetes entities. can be "default" to use otoroshi default templates
"service-group": {},
"service-descriptor": {},
"apikeys": {},
"global-config": {},
"jwt-verifier": {},
"tcp-service": {},
"certificate": {},
"auth-module": {},
"data-exporter": {},
"script": {},
"organization": {},
"team": {},
"data-exporter": {}
}
}
}

If endpoint is not defined, Otoroshi will try to get it from $KUBERNETES_SERVICE_HOST and $KUBERNETES_SERVICE_PORT. If token is not defined, Otoroshi will try to get it from the file at /var/run/secrets/kubernetes.io/serviceaccount/token. If caCert is not defined, Otoroshi will try to get it from the file at /var/run/secrets/kubernetes.io/serviceaccount/ca.crt. If $KUBECONFIG is defined, endpoint, token and caCert will be read from the current context of the file referenced by it.

you can find a more complete example of the configuration object here

Choose the kinds of entities the job reads​

By default, the job reads every kind of Otoroshi entity, in every namespace it watches. crdsKinds limits the kinds it reads, globally and by namespace, both at once if needed:

{
"KubernetesConfig": {
"crds": true,
"namespaces": ["*"],
"crdsKinds": {
"include": ["*"],
"exclude": ["admins", "global-configs"],
"namespaces": {
"team-*": { "include": ["routes", "backends", "apikeys", "certificates"] },
"team-sandbox": { "exclude": ["certificates"] }
}
}
}
}
  • a kind is the plural name of its crd (routes, apikeys, admins, global-configs, ..., the ones of the admin extensions too) or a pattern of plural names (*, *-plugins)
  • include and exclude are the global rule: a kind is read when it matches one of the included patterns and none of the excluded ones. include is ["*"] when missing
  • namespaces holds the rules of some namespaces, by name or pattern of name. They only narrow the global rule: a kind is read in a namespace when the global rule allows it, and the rule of every pattern matching the namespace allows it too. In the example, team-sandbox can only hold routes, backends and apikeys
  • the job neither fetches nor watches a kind the global rule excludes, and it neither creates, updates nor deletes the entities of a kind it does not read in their namespace: an entity synced before its kind was excluded stays in Otoroshi, delete it by hand if needed
  • the admins are read from the simple-admin-users crd: admins and simple-admin-users are the same kind, a rule on one of them applies to both
  • a crdsKinds that cannot be read makes the job read nothing, rather than every kind: a value that is not an object, an unknown field (excludes), a list that does not only hold strings, a namespace rule that is not an object. The error is logged

With the helm chart, set the crdsKinds value the same way.

Note about apikeys and certificates resources​

Apikeys and Certificates are a little bit different than the other resources. They have ability to be defined without their secret part, but with an export setting so otoroshi will generate the secret parts and export the apikey or the certificate to kubernetes secret. Then any app will be able to mount them as volumes (see the full example below)

In those resources you can define

exportSecret: true
secretName: the-secret-name

and omit clientSecret for apikey or publicKey, privateKey for certificates. For certificate you will have to provide a csr for the certificate in order to generate it

csr:
issuer: CN=Otoroshi Root
hosts:
- httpapp.foo.bar
- httpapps.foo.bar
key:
algo: rsa
size: 2048
subject: UID=httpapp-front, O=OtoroshiApps
client: false
ca: false
duration: 31536000000
signatureAlg: SHA256WithRSAEncryption
digestAlg: SHA-256

when apikeys are exported as kubernetes secrets, they will have the type otoroshi.io/apikey-secret with values clientId and clientSecret

apiVersion: v1
kind: Secret
metadata:
name: apikey-1
type: otoroshi.io/apikey-secret
data:
clientId: TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdA==
clientSecret: TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdA==

when certificates are exported as kubernetes secrets, they will have the type kubernetes.io/tls with the standard values tls.crt (the full cert chain) and tls.key (the private key). For more convenience, they will also have a cert.crt value containing the actual certificate without the ca chain and ca-chain.crt containing the ca chain without the certificate.

apiVersion: v1
kind: Secret
metadata:
name: certificate-1
type: kubernetes.io/tls
data:
tls.crt: TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdA==
tls.key: TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdA==
cert.crt: TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdA==
ca-chain.crt: TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdA==

Full CRD example​

then you can deploy the previous example with better configuration level, and using mtls, apikeys, etc

Let say the app looks like :

const fs = require('fs');
const https = require('https');

// here we read the apikey to access http-app-2 from files mounted from secrets
const clientId = fs.readFileSync('/var/run/secrets/kubernetes.io/apikeys/clientId').toString('utf8')
const clientSecret = fs.readFileSync('/var/run/secrets/kubernetes.io/apikeys/clientSecret').toString('utf8')

const backendKey = fs.readFileSync('/var/run/secrets/kubernetes.io/certs/backend/tls.key').toString('utf8')
const backendCert = fs.readFileSync('/var/run/secrets/kubernetes.io/certs/backend/cert.crt').toString('utf8')
const backendCa = fs.readFileSync('/var/run/secrets/kubernetes.io/certs/backend/ca-chain.crt').toString('utf8')

const clientKey = fs.readFileSync('/var/run/secrets/kubernetes.io/certs/client/tls.key').toString('utf8')
const clientCert = fs.readFileSync('/var/run/secrets/kubernetes.io/certs/client/cert.crt').toString('utf8')
const clientCa = fs.readFileSync('/var/run/secrets/kubernetes.io/certs/client/ca-chain.crt').toString('utf8')

function callApi2() {
return new Promise((success, failure) => {
const options = {
// using the implicit internal name (*.global.otoroshi.mesh) of the other service descriptor passing through otoroshi
hostname: 'http-app-service-descriptor-2.global.otoroshi.mesh',
port: 433,
path: '/',
method: 'GET',
headers: {
'Accept': 'application/json',
'Otoroshi-Client-Id': clientId,
'Otoroshi-Client-Secret': clientSecret,
},
cert: clientCert,
key: clientKey,
ca: clientCa
};
let data = '';
const req = https.request(options, (res) => {
res.on('data', (d) => {
data = data + d.toString('utf8');
});
res.on('end', () => {
success({ body: JSON.parse(data), res });
});
res.on('error', (e) => {
failure(e);
});
});
req.end();
})
}

const options = {
key: backendKey,
cert: backendCert,
ca: backendCa,
// we want mtls behavior
requestCert: true,
rejectUnauthorized: true
};
https.createServer(options, (req, res) => {
res.writeHead(200, {'Content-Type': 'application/json'});
callApi2().then(resp => {
res.write(JSON.stringify{ ("message": `Hello to ${req.socket.getPeerCertificate().subject.CN}`, api2: resp.body }));
});
}).listen(433);

then, the descriptors will be :

---
apiVersion: apps/v1
kind: Deployment
metadata:
name: http-app-deployment
spec:
selector:
matchLabels:
run: http-app-deployment
replicas: 1
template:
metadata:
labels:
run: http-app-deployment
spec:
containers:
- image: foo/http-app
imagePullPolicy: IfNotPresent
name: otoroshi
ports:
- containerPort: 443
name: "https"
volumeMounts:
- name: apikey-volume
# here you will be able to read apikey from files
# - /var/run/secrets/kubernetes.io/apikeys/clientId
# - /var/run/secrets/kubernetes.io/apikeys/clientSecret
mountPath: "/var/run/secrets/kubernetes.io/apikeys"
readOnly: true
volumeMounts:
- name: backend-cert-volume
# here you will be able to read app cert from files
# - /var/run/secrets/kubernetes.io/certs/backend/tls.crt
# - /var/run/secrets/kubernetes.io/certs/backend/tls.key
mountPath: "/var/run/secrets/kubernetes.io/certs/backend"
readOnly: true
- name: client-cert-volume
# here you will be able to read app cert from files
# - /var/run/secrets/kubernetes.io/certs/client/tls.crt
# - /var/run/secrets/kubernetes.io/certs/client/tls.key
mountPath: "/var/run/secrets/kubernetes.io/certs/client"
readOnly: true
volumes:
- name: apikey-volume
secret:
# here we reference the secret name from apikey http-app-2-apikey-1
secretName: secret-2
- name: backend-cert-volume
secret:
# here we reference the secret name from cert http-app-certificate-backend
secretName: http-app-certificate-backend-secret
- name: client-cert-volume
secret:
# here we reference the secret name from cert http-app-certificate-client
secretName: http-app-certificate-client-secret
---
apiVersion: v1
kind: Service
metadata:
name: http-app-service
spec:
ports:
- port: 8443
targetPort: https
name: https
selector:
run: http-app-deployment
---
apiVersion: proxy.otoroshi.io/v1
kind: ServiceGroup
metadata:
name: http-app-group
annotations:
otoroshi.io/id: http-app-group
spec:
description: a group to hold services about the http-app
---
apiVersion: proxy.otoroshi.io/v1
kind: ApiKey
metadata:
name: http-app-apikey-1
# this apikey can be used to access the app
spec:
# a secret name secret-1 will be created by otoroshi and can be used by containers
exportSecret: true
secretName: secret-1
authorizedEntities:
- group_http-app-group
---
apiVersion: proxy.otoroshi.io/v1
kind: ApiKey
metadata:
name: http-app-2-apikey-1
# this apikey can be used to access another app in a different group
spec:
# a secret name secret-1 will be created by otoroshi and can be used by containers
exportSecret: true
secretName: secret-2
authorizedEntities:
- group_http-app-2-group
---
apiVersion: proxy.otoroshi.io/v1
kind: Certificate
metadata:
name: http-app-certificate-frontend
spec:
description: certificate for the http-app on otorshi frontend
autoRenew: true
csr:
issuer: CN=Otoroshi Root
hosts:
- httpapp.foo.bar
key:
algo: rsa
size: 2048
subject: UID=httpapp-front, O=OtoroshiApps
client: false
ca: false
duration: 31536000000
signatureAlg: SHA256WithRSAEncryption
digestAlg: SHA-256
---
apiVersion: proxy.otoroshi.io/v1
kind: Certificate
metadata:
name: http-app-certificate-backend
spec:
description: certificate for the http-app deployed on pods
autoRenew: true
# a secret name http-app-certificate-backend-secret will be created by otoroshi and can be used by containers
exportSecret: true
secretName: http-app-certificate-backend-secret
csr:
issuer: CN=Otoroshi Root
hosts:
- http-app-service
key:
algo: rsa
size: 2048
subject: UID=httpapp-back, O=OtoroshiApps
client: false
ca: false
duration: 31536000000
signatureAlg: SHA256WithRSAEncryption
digestAlg: SHA-256
---
apiVersion: proxy.otoroshi.io/v1
kind: Certificate
metadata:
name: http-app-certificate-client
spec:
description: certificate for the http-app
autoRenew: true
secretName: http-app-certificate-client-secret
csr:
issuer: CN=Otoroshi Root
key:
algo: rsa
size: 2048
subject: UID=httpapp-client, O=OtoroshiApps
client: false
ca: false
duration: 31536000000
signatureAlg: SHA256WithRSAEncryption
digestAlg: SHA-256
---
apiVersion: proxy.otoroshi.io/v1
kind: ServiceDescriptor
metadata:
name: http-app-service-descriptor
spec:
description: the service descriptor for the http app
groups:
- http-app-group
forceHttps: true
hosts:
- httpapp.foo.bar # hostname exposed oustide of the kubernetes cluster
# - http-app-service-descriptor.global.otoroshi.mesh # implicit internal name inside the kubernetes cluster
matchingRoot: /
targets:
- url: https://http-app-service:8443
# alternatively, you can use serviceName and servicePort to use pods ip addresses
# serviceName: http-app-service
# servicePort: https
mtlsConfig:
# use mtls to contact the backend
mtls: true
certs:
# reference the DN for the client cert
- UID=httpapp-client, O=OtoroshiApps
trustedCerts:
# reference the DN for the CA cert
- CN=Otoroshi Root
sendOtoroshiHeadersBack: true
xForwardedHeaders: true
overrideHost: true
allowHttp10: false
publicPatterns:
- /health
additionalHeaders:
x-foo: bar
# here you can specify everything supported by otoroshi like jwt-verifiers, auth config, etc ... for more informations about it, just go to https://maif.github.io/otoroshi/swagger-ui/index.html

now with this descriptor deployed, you can access your app with a command like

CLIENT_ID=`kubectl get secret secret-1 -o jsonpath="{.data.clientId}" | base64 --decode`
CLIENT_SECRET=`kubectl get secret secret-1 -o jsonpath="{.data.clientSecret}" | base64 --decode`
curl -X GET https://httpapp.foo.bar/get -u "$CLIENT_ID:$CLIENT_SECRET"

Expose Otoroshi to outside world​

If you deploy Otoroshi on a kubernetes cluster, the Otoroshi service is deployed as a loadbalancer (service type: LoadBalancer). You'll need to declare in your DNS settings any name that can be routed by otoroshi going to the loadbalancer endpoint (CNAME or ip addresses) of your kubernetes distribution. If you use a managed kubernetes cluster from a cloud provider, it will work seamlessly as they will provide external loadbalancers out of the box. However, if you use a bare metal kubernetes cluster, id doesn't come with support for external loadbalancers (service of type LoadBalancer). So you will have to provide this feature in order to route external TCP traffic to Otoroshi containers running inside the kubernetes cluster. You can use projects like MetalLB that provide software LoadBalancer services to bare metal clusters or you can use and customize examples in the installation section.

warning

We don't recommand running Otoroshi behind an existing ingress controller (or something like that) as you will not be able to use features like TCP proxying, TLS, mTLS, etc. Also, this additional layer of reverse proxy will increase call latencies.

Access a service from inside the k8s cluster​

Using host header overriding​

You can access any service referenced in otoroshi, through otoroshi from inside the kubernetes cluster by using the otoroshi service name (if you use a template based on https://github.com/MAIF/otoroshi/tree/master/kubernetes/base deployed in the otoroshi namespace) and the host header with the service domain like :

CLIENT_ID="xxx"
CLIENT_SECRET="xxx"
curl -X GET -H 'Host: httpapp.foo.bar' https://otoroshi-service.otoroshi.svc.cluster.local:8443/get -u "$CLIENT_ID:$CLIENT_SECRET"

Using dedicated services​

it's also possible to define services that targets otoroshi deployment (or otoroshi workers deployment) and use then as valid hosts in otoroshi services

apiVersion: v1
kind: Service
metadata:
name: my-awesome-service
spec:
selector:
# run: otoroshi-deployment
# or in cluster mode
run: otoroshi-worker-deployment
ports:
- port: 8080
name: "http"
targetPort: "http"
- port: 8443
name: "https"
targetPort: "https"

and access it like

CLIENT_ID="xxx"
CLIENT_SECRET="xxx"
curl -X GET https://my-awesome-service.my-namspace.svc.cluster.local:8443/get -u "$CLIENT_ID:$CLIENT_SECRET"

Using coredns integration​

You can also enable the coredns integration to simplify the flow. You can use the the following keys in the plugin config :

{
"KubernetesConfig": {
...
"coreDnsIntegration": true, // enable coredns integration for intra cluster calls
"kubeSystemNamespace": "kube-system", // the namespace where coredns is deployed
"corednsConfigMap": "coredns", // the name of the coredns configmap
"otoroshiServiceName": "otoroshi-service", // the name of the otoroshi service, could be otoroshi-workers-service
"otoroshiNamespace": "otoroshi", // the namespace where otoroshi is deployed
"clusterDomain": "cluster.local", // the domain for cluster services
...
}
}

otoroshi will patch coredns config at startup then you can call your services like

CLIENT_ID="xxx"
CLIENT_SECRET="xxx"
curl -X GET https://my-awesome-service.my-awesome-service-namespace.otoroshi.mesh:8443/get -u "$CLIENT_ID:$CLIENT_SECRET"

By default, all services created from CRDs service descriptors are exposed as ${service-name}.${service-namespace}.otoroshi.mesh or ${service-name}.${service-namespace}.svc.otoroshi.local

Using coredns with manual patching​

you can also patch the coredns config manually

kubectl edit configmaps coredns -n kube-system # or your own custom config map

and change the Corefile data to add the following snippet in at the end of the file

otoroshi.mesh:53 {
errors
health
ready
kubernetes cluster.local in-addr.arpa ip6.arpa {
pods insecure
upstream
fallthrough in-addr.arpa ip6.arpa
}
rewrite name regex (.*)\.otoroshi\.mesh otoroshi-worker-service.otoroshi.svc.cluster.local
forward . /etc/resolv.conf
cache 30
loop
reload
loadbalance
}

you can also define simpler rewrite if it suits you use case better

rewrite name my-service.otoroshi.mesh otoroshi-worker-service.otoroshi.svc.cluster.local

do not hesitate to change otoroshi-worker-service.otoroshi according to your own setup. If otoroshi is not in cluster mode, change it to otoroshi-service.otoroshi. If otoroshi is not deployed in the otoroshi namespace, change it to otoroshi-service.the-namespace, etc.

By default, all services created from CRDs service descriptors are exposed as ${service-name}.${service-namespace}.otoroshi.mesh

then you can call your service like

CLIENT_ID="xxx"
CLIENT_SECRET="xxx"

curl -X GET https://my-awesome-service.my-awesome-service-namespace.otoroshi.mesh:8443/get -u "$CLIENT_ID:$CLIENT_SECRET"

Using old kube-dns system​

if your stuck with an old version of kubernetes, it uses kube-dns that is not supported by otoroshi, so you will have to provide your own coredns deployment and declare it as a stubDomain in the old kube-dns system.

Here is an example of coredns deployment with otoroshi domain config

---
apiVersion: v1
kind: ConfigMap
metadata:
name: otoroshi-dns
labels:
app: otoroshi
component: coredns
data:
Corefile: |
otoroshi.mesh:5353 {
errors
health
ready
kubernetes cluster.local in-addr.arpa ip6.arpa {
pods insecure
fallthrough in-addr.arpa ip6.arpa
}
rewrite name regex (.*)\.otoroshi\.mesh otoroshi-service.otoroshi.svc.cluster.local
forward . /etc/resolv.conf
cache 30
loop
reload
loadbalance
}
.:5353 {
errors
health
kubernetes cluster.local in-addr.arpa ip6.arpa {
pods insecure
fallthrough in-addr.arpa ip6.arpa
}
forward . /etc/resolv.conf
cache 30
loop
reload
loadbalance
}
---
apiVersion: v1
kind: Service
metadata:
name: otoroshi-dns
labels:
app: otoroshi
component: coredns
spec:
selector:
app: otoroshi
component: coredns
type: ClusterIP
ports:
- name: dns
port: 5353
protocol: UDP
- name: dns-tcp
port: 5353
protocol: TCP
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: otoroshi-dns
labels:
app: otoroshi
component: coredns
spec:
replicas: 2
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
selector:
matchLabels:
app: otoroshi
component: coredns
template:
metadata:
labels:
app: otoroshi
component: coredns
spec:
serviceAccountName: otoroshi-admin-user
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
topologyKey: kubernetes.io/hostname
labelSelector:
matchExpressions:
- key: app
operator: In
values: [otoroshi]
- key: component
operator: In
values: [coredns]
tolerations:
- key: CriticalAddonsOnly
operator: Exists
containers:
- name: coredns
image: coredns/coredns:1.11.3
imagePullPolicy: IfNotPresent
args: ["-conf", "/etc/coredns/Corefile"]
ports:
- containerPort: 5353
name: dns
protocol: UDP
- containerPort: 5353
name: dns-tcp
protocol: TCP
resources:
limits:
memory: 170Mi
requests:
cpu: 100m
memory: 70Mi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
add: [NET_BIND_SERVICE]
drop: [ALL]
livenessProbe:
httpGet:
path: /health
port: 8080
scheme: HTTP
initialDelaySeconds: 30
timeoutSeconds: 5
successThreshold: 1
failureThreshold: 5
volumeMounts:
- name: config-volume
mountPath: /etc/coredns
readOnly: true
dnsPolicy: Default
volumes:
- name: config-volume
configMap:
name: otoroshi-dns
items:
- key: Corefile
path: Corefile

then you can enable the kube-dns integration in the otoroshi kubernetes job

{
"KubernetesConfig": {
...
"kubeDnsOperatorIntegration": true, // enable kube-dns integration for intra cluster calls
"kubeDnsOperatorCoreDnsNamespace": "otoroshi", // namespace where coredns is installed
"kubeDnsOperatorCoreDnsName": "otoroshi-dns", // name of the coredns service
"kubeDnsOperatorCoreDnsPort": 5353, // port of the coredns service
...
}
}

Using Openshift DNS operator​

Openshift DNS operator does not allow to customize DNS configuration a lot, so you will have to provide your own coredns deployment and declare it as a stub in the Openshift DNS operator.

Here is an example of coredns deployment with otoroshi domain config

---
apiVersion: v1
kind: ConfigMap
metadata:
name: otoroshi-dns
labels:
app: otoroshi
component: coredns
data:
Corefile: |
otoroshi.mesh:5353 {
errors
health
ready
kubernetes cluster.local in-addr.arpa ip6.arpa {
pods insecure
fallthrough in-addr.arpa ip6.arpa
}
rewrite name regex (.*)\.otoroshi\.mesh otoroshi-service.otoroshi.svc.cluster.local
forward . /etc/resolv.conf
cache 30
loop
reload
loadbalance
}
.:5353 {
errors
health
kubernetes cluster.local in-addr.arpa ip6.arpa {
pods insecure
fallthrough in-addr.arpa ip6.arpa
}
forward . /etc/resolv.conf
cache 30
loop
reload
loadbalance
}
---
apiVersion: v1
kind: Service
metadata:
name: otoroshi-dns
labels:
app: otoroshi
component: coredns
spec:
selector:
app: otoroshi
component: coredns
type: ClusterIP
ports:
- name: dns
port: 5353
protocol: UDP
- name: dns-tcp
port: 5353
protocol: TCP
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: otoroshi-dns
labels:
app: otoroshi
component: coredns
spec:
replicas: 2
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
selector:
matchLabels:
app: otoroshi
component: coredns
template:
metadata:
labels:
app: otoroshi
component: coredns
spec:
serviceAccountName: otoroshi-admin-user
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
topologyKey: kubernetes.io/hostname
labelSelector:
matchExpressions:
- key: app
operator: In
values: [otoroshi]
- key: component
operator: In
values: [coredns]
tolerations:
- key: CriticalAddonsOnly
operator: Exists
containers:
- name: coredns
image: coredns/coredns:1.11.3
imagePullPolicy: IfNotPresent
args: ["-conf", "/etc/coredns/Corefile"]
ports:
- containerPort: 5353
name: dns
protocol: UDP
- containerPort: 5353
name: dns-tcp
protocol: TCP
resources:
limits:
memory: 170Mi
requests:
cpu: 100m
memory: 70Mi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
add: [NET_BIND_SERVICE]
drop: [ALL]
livenessProbe:
httpGet:
path: /health
port: 8080
scheme: HTTP
initialDelaySeconds: 30
timeoutSeconds: 5
successThreshold: 1
failureThreshold: 5
volumeMounts:
- name: config-volume
mountPath: /etc/coredns
readOnly: true
dnsPolicy: Default
volumes:
- name: config-volume
configMap:
name: otoroshi-dns
items:
- key: Corefile
path: Corefile

then you can enable the Openshift DNS operator integration in the otoroshi kubernetes job

{
"KubernetesConfig": {
...
"openshiftDnsOperatorIntegration": true, // enable openshift dns operator integration for intra cluster calls
"openshiftDnsOperatorCoreDnsNamespace": "otoroshi", // namespace where coredns is installed
"openshiftDnsOperatorCoreDnsName": "otoroshi-dns", // name of the coredns service
"openshiftDnsOperatorCoreDnsPort": 5353, // port of the coredns service
...
}
}

don't forget to update the otoroshi ClusterRole

- apiGroups:
- operator.openshift.io
resources:
- dnses
verbs:
- get
- list
- watch
- update

CRD validation in kubectl​

In order to get CRD validation before manifest deployments right inside kubectl, you can deploy a validation webhook that will do the trick. Also check that you have otoroshi.plugins.jobs.kubernetes.KubernetesAdmissionWebhookCRDValidator request sink enabled (see the enabling the admission webhook sinks section below). The webhooks kustomize component ships it, as otoroshi-admission-webhook-validation, next to the sidecar injector one:

---
# ValidatingWebhookConfiguration — calls Otoroshi to validate any new/updated
# proxy.otoroshi.io CR before kube-apiserver persists it. caBundle is left empty
# and gets injected at runtime by the KubernetesAdmissionWebhookCRDValidator
# sink, which also patches failurePolicy. Make sure that sink is enabled in
# `initial-customization.json` (it is by default).
#
# `clientConfig.service.name` MUST be the service declared as
# `KubernetesConfig.otoroshiServiceName` in `initial-customization.json` — the sink
# only matches a Host of `<otoroshiServiceName>.<namespace>.svc[.cluster.local]` and
# the generated certificate carries only those SANs. In cluster mode that is
# `otoroshi-worker-service`, not `otoroshi-service` — see readme.md.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: otoroshi-admission-webhook-validation
labels:
app: otoroshi
component: otoroshi-validation-webhook
webhooks:
- name: otoroshi-admission-webhook.otoroshi.io
rules:
- operations:
- CREATE
- UPDATE
apiGroups:
- proxy.otoroshi.io
apiVersions:
- "*"
resources:
- "*"
scope: Namespaced
clientConfig:
service:
name: otoroshi-service
namespace: otoroshi
path: /apis/webhooks/validation
port: 8443
caBundle: ""
failurePolicy: Ignore
sideEffects: None
admissionReviewVersions:
- v1
---
# MutatingWebhookConfiguration — injects an otoroshi-sidecar container into
# pods labeled `otoroshi.io/sidecar: inject`. Same caBundle / failurePolicy
# runtime-injection contract as the validating one above (handled by the
# KubernetesAdmissionWebhookSidecarInjector sink).
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
name: otoroshi-admission-webhook-injector
labels:
app: otoroshi
component: otoroshi-validation-webhook
webhooks:
- name: otoroshi-admission-webhook-injector.otoroshi.io
rules:
- operations:
- CREATE
apiGroups:
- ""
apiVersions:
- v1
resources:
- pods
scope: Namespaced
objectSelector:
matchLabels:
otoroshi.io/sidecar: inject
clientConfig:
service:
name: otoroshi-service
namespace: otoroshi
path: /apis/webhooks/inject
port: 8443
caBundle: ""
failurePolicy: Ignore
sideEffects: None
admissionReviewVersions:
- v1

Enabling the admission webhook sinks​

Both admission webhooks are served by Otoroshi request sinks — plugins that answer requests no route matched. The next-gen proxy engine, which is the default, only picks up request sinks declared in the global config under plugins.config.ng; the older scripts.sinkRefs list is read by the legacy engine only. Declaring them in both places covers either engine:

{
"plugins": {
"enabled": true,
"config": {
"ng": [
{
"enabled": true,
"debug": false,
"include": [],
"exclude": [],
"plugin": "cp:otoroshi.next.plugins.NgClientCredentials",
"config": {
"expiration": 3600000,
"default_key_pair": "otoroshi-jwt-signing",
"domain": "*",
"secure": true
}
},
{
"enabled": true,
"debug": false,
"include": [],
"exclude": [],
"plugin": "cp:otoroshi.next.plugins.wrappers.RequestSinkWrapper",
"config": {
"plugin": "cp:otoroshi.plugins.jobs.kubernetes.KubernetesAdmissionWebhookCRDValidator"
}
},
{
"enabled": true,
"debug": false,
"include": [],
"exclude": [],
"plugin": "cp:otoroshi.next.plugins.wrappers.RequestSinkWrapper",
"config": {
"plugin": "cp:otoroshi.plugins.jobs.kubernetes.KubernetesAdmissionWebhookSidecarInjector"
}
}
]
}
},
"scripts": {
"enabled": true,
"sinkRefs": [
"cp:otoroshi.plugins.jobs.kubernetes.KubernetesAdmissionWebhookCRDValidator",
"cp:otoroshi.plugins.jobs.kubernetes.KubernetesAdmissionWebhookSidecarInjector"
],
"sinkConfig": {}
}
}

RequestSinkWrapper is what lets the next-gen engine run these plugins, which are written against the legacy request-sink API. They need no configuration of their own: the KubernetesConfig block used by the sinks falls back to scripts.jobConfig.KubernetesConfig, the very one the CRDs controller job uses.

warning

plugins.config.ng replaces Otoroshi's built-in plugin list rather than merging into it — a JSON deep merge does not merge arrays. Keep the entries that were already there, such as the default NgClientCredentials above.

warning

When this configuration is passed through OTOROSHI_INITIAL_CUSTOMIZATION, it is only applied on the very first boot, while the datastore is still empty. On an upgrade — or against a pre-existing Redis — Otoroshi keeps the global config it already has, and the change must be applied by hand from the admin UI (Danger zone → Global plugins) or through the admin API.

Troubleshooting​

kubectl apply failing with:

Internal error occurred: failed calling webhook "otoroshi-admission-webhook.otoroshi.io":
failed to call webhook: the server could not find the requested resource

means Otoroshi answered 404 on /apis/webhooks/validation, i.e. no request sink handled the call. The two usual causes are:

  • the sinks are not registered for the running engine — see the section above;
  • the Host the apiserver used does not match what the sinks accept. They only match <otoroshiServiceName>.<namespace>.svc and <otoroshiServiceName>.<namespace>.svc.<clusterDomain>, taken from KubernetesConfig. So webhooks[].clientConfig.service.name in the webhook manifest must be the very service named by otoroshiServiceName — in a Leader/Worker setup, that is the worker service. This is also the name the certificate Otoroshi generates for the endpoint is issued for, so a mismatch breaks the TLS handshake as well.

Note that the failure can stay invisible for a while: the manifests ship with failurePolicy: Ignore, and the CRDs controller job flips it to Fail on its first sync loop. Before the flip, the apiserver silently swallows the 404 and manifests are accepted unvalidated; after it, every apply fails.

Easier integration with otoroshi-sidecar​

Otoroshi can help you to easily use existing services without modifications while gettings all the perks of otoroshi like apikeys, mTLS, exchange protocol, etc. To do so, otoroshi will inject a sidecar container in the pod of your deployment that will handle call coming from otoroshi and going to otoroshi. To enable otoroshi-sidecar, you need to deploy the otoroshi-admission-webhook-injector admission webhook, shipped by the webhooks kustomize component next to the validation one. Also check that you have otoroshi.plugins.jobs.kubernetes.KubernetesAdmissionWebhookSidecarInjector request sink enabled (see the enabling the admission webhook sinks section above).

---
# ValidatingWebhookConfiguration — calls Otoroshi to validate any new/updated
# proxy.otoroshi.io CR before kube-apiserver persists it. caBundle is left empty
# and gets injected at runtime by the KubernetesAdmissionWebhookCRDValidator
# sink, which also patches failurePolicy. Make sure that sink is enabled in
# `initial-customization.json` (it is by default).
#
# `clientConfig.service.name` MUST be the service declared as
# `KubernetesConfig.otoroshiServiceName` in `initial-customization.json` — the sink
# only matches a Host of `<otoroshiServiceName>.<namespace>.svc[.cluster.local]` and
# the generated certificate carries only those SANs. In cluster mode that is
# `otoroshi-worker-service`, not `otoroshi-service` — see readme.md.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: otoroshi-admission-webhook-validation
labels:
app: otoroshi
component: otoroshi-validation-webhook
webhooks:
- name: otoroshi-admission-webhook.otoroshi.io
rules:
- operations:
- CREATE
- UPDATE
apiGroups:
- proxy.otoroshi.io
apiVersions:
- "*"
resources:
- "*"
scope: Namespaced
clientConfig:
service:
name: otoroshi-service
namespace: otoroshi
path: /apis/webhooks/validation
port: 8443
caBundle: ""
failurePolicy: Ignore
sideEffects: None
admissionReviewVersions:
- v1
---
# MutatingWebhookConfiguration — injects an otoroshi-sidecar container into
# pods labeled `otoroshi.io/sidecar: inject`. Same caBundle / failurePolicy
# runtime-injection contract as the validating one above (handled by the
# KubernetesAdmissionWebhookSidecarInjector sink).
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
name: otoroshi-admission-webhook-injector
labels:
app: otoroshi
component: otoroshi-validation-webhook
webhooks:
- name: otoroshi-admission-webhook-injector.otoroshi.io
rules:
- operations:
- CREATE
apiGroups:
- ""
apiVersions:
- v1
resources:
- pods
scope: Namespaced
objectSelector:
matchLabels:
otoroshi.io/sidecar: inject
clientConfig:
service:
name: otoroshi-service
namespace: otoroshi
path: /apis/webhooks/inject
port: 8443
caBundle: ""
failurePolicy: Ignore
sideEffects: None
admissionReviewVersions:
- v1

then it's quite easy to add the sidecar, just add the following label to your pod otoroshi.io/sidecar: inject and some annotations to tell otoroshi what certificates and apikeys to use.

annotations:
otoroshi.io/sidecar-apikey: backend-apikey
otoroshi.io/sidecar-backend-cert: backend-cert
otoroshi.io/sidecar-client-cert: oto-client-cert
otoroshi.io/token-secret: secret
otoroshi.io/expected-dn: UID=oto-client-cert, O=OtoroshiApps

now you can just call you otoroshi handled apis from inside your pod like curl http://my-service.namespace.otoroshi.mesh/api without passing any apikey or client certificate and the sidecar will handle everything for you. Same thing for call from otoroshi to your pod, everything will be done in mTLS fashion with apikeys and otoroshi exchange protocol

here is a full example

---
# A whoami backend wrapped with the otoroshi-sidecar pattern. Drop this
# alongside an Otoroshi install (with the `webhooks` component enabled, so the
# mutating webhook can inject the sidecar) and Otoroshi will:
# 1. Inject an otoroshi-sidecar container into the pod (label-driven).
# 2. Use the listed ApiKey + Certificates for mTLS to / from the sidecar.
# 3. Expose the backend through the `backend` ServiceDescriptor below
# at `https://backend.oto.tools`.
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-deployment
spec:
selector:
matchLabels:
run: app-deployment
app: node
replicas: 1
template:
metadata:
labels:
run: app-deployment
app: node
# Tells the otoroshi mutating webhook to inject the sidecar.
otoroshi.io/sidecar: inject
annotations:
otoroshi.io/sidecar-apikey: backend-apikey
otoroshi.io/sidecar-backend-cert: backend-cert
otoroshi.io/sidecar-client-cert: oto-client-cert
otoroshi.io/token-secret: secret
otoroshi.io/expected-dn: UID=oto-client-cert, O=OtoroshiApps
spec:
containers:
- image: containous/whoami:latest
name: whoami
args: ["--port", "8081"]
ports:
- name: main-port
containerPort: 8081
---
apiVersion: v1
kind: Service
metadata:
name: app-service
spec:
selector:
run: app-deployment
ports:
- port: 8443
name: https
targetPort: https
---
apiVersion: proxy.otoroshi.io/v1
kind: Certificate
metadata:
name: backend-cert
spec:
description: backend-cert
autoRenew: true
exportSecret: true
secretName: backend-cert
csr:
hosts:
- app-service.default.svc.cluster.local
issuer: otoroshi-intermediate-ca
key:
algo: rsa
size: 2048
subject: UID=backend-cert, O=OtoroshiApps
duration: 31536000000
signatureAlg: SHA256WithRSAEncryption
digestAlg: SHA-256
---
apiVersion: proxy.otoroshi.io/v1
kind: Certificate
metadata:
name: client-cert
annotations:
otoroshi.io/id: client-cert
spec:
description: client-cert
autoRenew: true
exportSecret: true
client: true
secretName: client-cert
csr:
client: true
issuer: otoroshi-intermediate-ca
key:
algo: rsa
size: 2048
subject: UID=client-cert, O=OtoroshiApps
duration: 31536000000
signatureAlg: SHA256WithRSAEncryption
digestAlg: SHA-256
---
apiVersion: proxy.otoroshi.io/v1
kind: Certificate
metadata:
name: oto-client-cert
annotations:
otoroshi.io/id: oto-client-cert
spec:
description: oto-client-cert
autoRenew: true
exportSecret: true
client: true
secretName: oto-client-cert
csr:
client: true
issuer: otoroshi-intermediate-ca
key:
algo: rsa
size: 2048
subject: UID=oto-client-cert, O=OtoroshiApps
duration: 31536000000
signatureAlg: SHA256WithRSAEncryption
digestAlg: SHA-256
---
apiVersion: proxy.otoroshi.io/v1
kind: Certificate
metadata:
name: frontend-cert
spec:
description: frontend-cert
autoRenew: true
csr:
issuer: otoroshi-intermediate-ca
hosts:
- backend.oto.tools
key:
algo: rsa
size: 2048
subject: UID=frontend-cert, O=OtoroshiApps
duration: 31536000000
signatureAlg: SHA256WithRSAEncryption
digestAlg: SHA-256
---
apiVersion: proxy.otoroshi.io/v1
kind: Certificate
metadata:
name: mesh-cert
spec:
description: mesh-cert
autoRenew: true
csr:
issuer: otoroshi-intermediate-ca
hosts:
- "*.default.otoroshi.mesh"
key:
algo: rsa
size: 2048
subject: O=Otoroshi, OU=Otoroshi Certificates, CN=kubernetes-mesh
duration: 31536000000
signatureAlg: SHA256WithRSAEncryption
digestAlg: SHA-256
---
apiVersion: proxy.otoroshi.io/v1
kind: ApiKey
metadata:
name: backend-apikey
spec:
exportSecret: true
secretName: backend-apikey
authorizedEntities:
- group_default
---
apiVersion: proxy.otoroshi.io/v1
kind: ServiceDescriptor
metadata:
name: backend
spec:
description: backend
groups:
- default
forceHttps: false
hosts:
- backend.oto.tools
matchingRoot: /
publicPatterns:
- /.*
secComUseSameAlgo: true
secComVersion: 2
secComInfoTokenVersion: Latest
secComSettings:
type: HSAlgoSettings
size: 512
secret: secret
base64: false
secComAlgoChallengeOtoToBack:
type: HSAlgoSettings
size: 512
secret: secret
base64: false
secComAlgoChallengeBackToOto:
type: HSAlgoSettings
size: 512
secret: secret
base64: false
secComAlgoInfoToken:
type: HSAlgoSettings
size: 512
secret: secret
base64: false
targets:
- url: https://app-service.default.svc.cluster.local:8443
mtlsConfig:
mtls: true
certs:
- UID=oto-client-cert, O=OtoroshiApps
trustedCerts:
- otoroshi-intermediate-ca
warning

Please avoid to use port 80 for your pod as it's the default port to access otoroshi from your pod and the call will be redirect to the sidecar via an iptables rule

Daikoku integration​

It is possible to easily integrate daikoku generated apikeys without any human interaction with the actual apikey secret. To do that, create a plan in Daikoku and setup the integration mode to Automatic

then when a user subscribe for an apikey, he will only see an integration token

then just create an ApiKey manifest with this token and your good to go

apiVersion: proxy.otoroshi.io/v1
kind: ApiKey
metadata:
name: http-app-2-apikey-3
spec:
exportSecret: true
secretName: secret-3
daikokuToken: RShQrvINByiuieiaCBwIZfGFgdPu7tIJEN5gdV8N8YeH4RI9ErPYJzkuFyAkZ2xy

Kubernetes Gateway API​

Starting from version 17.13.0, Otoroshi supports the Kubernetes Gateway API specification (v1.4). This is the standard Kubernetes API for managing ingress traffic, designed as the successor to the Ingress resource.

With Gateway API support enabled, you can define GatewayClass, Gateway, HTTPRoute, and GRPCRoute resources in your cluster and Otoroshi will automatically convert them into native NgRoute entities. This allows you to use standard, portable Kubernetes manifests while benefiting from Otoroshi's full feature set. GRPCRoute backends are automatically called using HTTP/2.

Quick setup​

First, install the Gateway API CRDs on your cluster:

kubectl apply -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.4.0/standard-install.yaml

Make sure the Otoroshi ServiceAccount has RBAC permissions for Gateway API resources (gatewayclasses, gateways, httproutes, grpcroutes, referencegrants, backendtlspolicies and their status subresources).

Then enable the Gateway API controller job in your Otoroshi deployment configuration:

{
"config": {
"scripts": {
"enabled": true,
"jobRefs": [
"cp:otoroshi.plugins.jobs.kubernetes.KubernetesGatewayApiControllerJob"
],
"jobConfig": {
"KubernetesConfig": {
"namespaces": ["*"],
"gatewayApi": true,
"gatewayApiControllerName": "otoroshi.io/gateway-controller",
"gatewayApiHttpListenerPort": 8080,
"gatewayApiHttpsListenerPort": 8443,
"gatewayApiSyncIntervalSeconds": 30
}
}
}
}
}

Once configured, you can create Gateway API resources:

apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: otoroshi
spec:
controllerName: otoroshi.io/gateway-controller
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: my-gateway
namespace: default
spec:
gatewayClassName: otoroshi
listeners:
- name: http
protocol: HTTP
port: 8080
hostname: "*.my.domain"
allowedRoutes:
namespaces:
from: Same
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: my-route
namespace: default
spec:
parentRefs:
- name: my-gateway
sectionName: http
hostnames:
- "api.my.domain"
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: my-service
port: 80

Otoroshi will automatically create an NgRoute that forwards traffic for api.my.domain to my-service:80.

note

The Gateway API controller can run alongside the existing CRDs controller. Both share the same KubernetesConfig configuration block.

For the full documentation — including supported filters, configuration reference, current limitations, and troubleshooting — see Kubernetes Gateway API support.