Building and Deploying Applications on Istio
local graph
Chapter 17 — Building and Deploying Applications on Istio
Section titled “Chapter 17 — Building and Deploying Applications on Istio”In the previous chapter, we deployed Istio and Kiali into our cluster. We also deployed an example application to see how the pieces fit together. In this chapter, we’re going to look at what it takes to build applications that will run on Istio. We’ll start by examining the differences between microservices and monolithic applications. Then, we’ll deploy a monolithic application on Istio and move on to building microservices that will run on Istio. This chapter will cover the following main topics:
- Comparing microservices and monoliths
- Deploying a monolith
- Building a microservice
- Do I need an API gateway?
Once you have completed this chapter, you’ll have a practical understanding of the difference between a monolith and a microservice, along with the information you’ll need to determine which one is best for you, and you will also have deployed a secured microservice in Istio.
Technical requirements
Section titled “Technical requirements”To run the examples in this chapter, you’ll need:
- A running cluster with Istio deployed, as outlined in Chapter 16, An Introduction to Istio.
- Scripts from this book’s GitHub repository.
You can access the code for this chapter by going to this book’s GitHub repository: https://github.com/PacktPublishing/Kubernetes-An-Enterprise-Guide-Third-Edition/tree/main/chapter17.
Comparing microservices and monoliths
Section titled “Comparing microservices and monoliths”Before we dive too deeply into code, we should spend some time discussing the differences between microservices and monolithic architecture. The microservices versus monolithic architecture debate is as old as computing itself (and the theory is probably even older). Understanding how these two approaches relate to each other and your problem set will help you decide which one to use.
My history with microservices versus monolithic architecture
Section titled “My history with microservices versus monolithic architecture”Before we get into the microservices versus monoliths discussion, I wanted to share my own history. I doubt it’s unique, but it does frame my outlook on the discussion and adds some context to the recommendations in this chapter.
My introduction to this discussion was when I was a computer science student in college and had started using Linux and open source. One of my favorite books, Open Sources: Voices from the Open Source Revolution, had an appendix on the debate between Andrew Tanenbaum and Linus Torvalds on microkernels versus monolithic kernels. Tanenbaum was the inventor of Minix, and a proponent of a minimalist kernel, with most of the functionality in user space. Linux, instead, uses a monolithic kernel design, where much more is done in the kernel. If you’ve ever run modprobe to load a driver, you’re interacting with the kernel! The entire thread is available at https://www.oreilly.com/openbook/opensources/book/appa.html.
Linus’ core argument was that a well-managed monolith was much easier to maintain than a microkernel.
Tanenbaum instead pointed to the idea that microkernels were easier to port and that most “modern” kernels were microkernels. Windows (at the time, Windows NT) is probably the most prevalent microkernel today. As a software developer, I’m constantly trying to find the smallest unit I can build. The microkernel architecture really appealed to that aspect of my talents.
At the same time, I was starting my career in IT, primarily as a Windows developer in the data management and analysis space. I spent most of my time working with ASP (Active Server Pages, Microsoft’s version of PHP), Visual Basic, and SQL Server. I tried to convince my bosses that we should move off of a monolithic application design to use MTS (Microsoft Transaction Server). MTS was my first exposure to what we would call today a distributed application. My bosses and mentors all pointed out that our costs, and so our customers’ costs, would go through the roof if we injected the additional infrastructure for no benefit other than a cleaner code base. There was nothing we were working on that couldn’t be accomplished with our tightly bound trio of ASP, Visual Basic, and SQL Server at a much lower cost.
I later moved from data management to identity management. I also switched from Microsoft to Java. One of my first projects was to deploy an identity management vendor’s product that was built using a distributed architecture. At the time, I thought it was great, until I started trying to debug issues and trace down problems across dozens of log files. I quickly started using another vendor’s product that was built as a monolith. Deployments were slow, as they required a full recompile, but otherwise, management was much easier, and it scaled every bit as well. We found that a distributed architecture didn’t help because identity management was done by such a centralized team that having a monolith didn’t impact productivity or management. The benefits of distributing implementation just didn’t outweigh the additional complexity.
Fast forward to the founding of Tremolo Security. This was in 2010, so it was before Kubernetes and Istio came along. At the time, virtual appliances were all the rage! We decided OpenUnison would take the monolithic approach because we wanted to make it easier to deploy and upgrade. In Chapter 6, Integrating Authentication into Your Cluster, we deployed OpenUnison with some Helm charts to layer on different configurations. How much harder would it have been had there been an authentication service to install, a directory service, a just-in-time provisioning service, etc.? It made for a much simpler deployment having one system.
With all that said, it’s not that I’m anti-microservice—I’m not! When used correctly, it’s an incredibly powerful architecture used by many of the world’s largest companies. I’ve learned through the years that if it’s not the right architecture for your system, it will considerably impact your ability to deliver. Now that I’ve filled you in on my own journey through architectures, let’s take a deeper look at the differences between microservices and monoliths.
Comparing architectures in an application
Section titled “Comparing architectures in an application”First, let’s talk about what these two architecture approaches each do in a common example application, a storefront.
Monolithic application design
Section titled “Monolithic application design”Let’s say you have an online store. Your store will likely need a product lookup service, a shopping cart, a payment system, and a shipping system. This is a vast oversimplification of a storefront application, but the point of the discussion is how to break up development and not how to build a storefront. There are two ways you could approach building this application. The first is you could build a monolithic application where all the code for each service is stored and managed in the same tree. Your application infrastructure would probably look something like this:

A diagram of a storefront application Description automatically generated
Figure 17.1: Monolithic application architecture
In our application, we have a single system with multiple modules. Depending on your programming language of choice, these could be classes, structs, or other forms of code module. A central application manages the user’s interaction with this code. This would likely be a web frontend with the modules being server-side code, written up as web services or a post/response-style app.
Yes, web services can be used in a monolith! These modules likely need to store data, usually in some kind of a database. Whether it’s a relational database, a document database, or a series of databases isn’t really important.
The biggest advantage to this monolithic architecture is it’s relatively simple to manage and have the systems interact with each other. If the user wants to do a product search, the storefront will likely just execute some code like the following:
list_of_products = products.search(search_criteria);display(list_of_products);The application code only needs to know the interface of the services it’s going to call. There’s no need to “authenticate” that call from the application controller to the product directory module. There’s no concern with creating rate-limiting systems or trying to work out which version of the service to use. Everything is tightly bound. If you make an update to any system, you know pretty quickly if you broke an interface, since you’re likely using a development tool that will tell you when module interfaces break. Finally, deployment is usually pretty simple. You upload your code to a deployment service (or create a container… this is a Kubernetes book!).
What happens if you need to have one developer update your ordering system while another developer updates your payment system? They each have their own copies of the code that need to be merged. After merging, the changes from both branches need to be reconciled before deployment. This may be fine for a small system, but as your storefront grows, this can become cumbersome to the point of being unmanageable.
Another potential issue is, what if there’s a better language or system to build one of these services in than the overall application? I’ve been on multiple projects over the years where Java was a great choice for certain components, but C# had better APIs for others. Maybe one service team was built around Python and another on Ruby. Standardization is all well and good, but you wouldn’t use the butt end of a screwdriver to drive in a nail for the sake of standardization, would you?
This argument doesn’t pertain to frontend versus backend. An application with a JavaScript frontend and a Golang backend can still be a monolithic application. Both the Kubernetes Dashboard and Kiali are examples of monolithic applications built on service APIs across different languages. Both have HTML and JavaScript frontends, while their backend APIs are written in Golang.
Microservices design
Section titled “Microservices design”What if we broke these modules up into services? Instead of having one single source tree, we would break our application up into individual services like the following:

A diagram of a storefront application Description automatically generated
Figure 17.2: Simple microservices architecture
This doesn’t look that much more complex. Instead of a big box, there’s a bunch of lines. Let’s zoom in on the call from our frontend to our product lookup service:

A picture containing text, screenshot, diagram, design Description automatically generated
Figure 17.3: Service call architecture
It’s no longer a simple function or method call. Now, our storefront controller needs to determine where to send the service call, and this will likely change in each environment. It also needs to inject some kind of authentication token, since you wouldn’t want just anyone calling your services. Since the remote service no longer has a local code representation, you’ll either need to build the call manually or use a schema language to describe your product listing service, combining it with a client binding. Once the call is made, the service needs to validate the call’s schema and apply security rules for authentication and authorization. Once the response is packaged and sent back to our storefront controller, the controller needs to validate the schema of the response. If there’s a failure, it needs to decide if it’s going to retry or not.
Combine all this additional complexity with version management. Which version of the product lookup service should our storefront use? Are other services tightly coupled together? There are several benefits to the microservices approach, as we discussed earlier, in terms of version and deployment management. These advantages come with the cost of additional complexity.
Choosing between monoliths and microservices
Section titled “Choosing between monoliths and microservices”Which of these two approaches is right for you? That really depends. What does your team look like? What are your management needs? Do you need the flexibility that comes from microservices or will a monolith’s simpler design make for an easier-to-manage system?
One of the major benefits of a microservice architecture is that you can have multiple teams working on their own code without having to share the same source repository. Before assuming that breaking the services into their own source repositories will benefit your team, how closely tied are the services? If there are numerous interdependencies, then your microservices are really just a distributed monolith, and you may not get the benefits of different repositories. It may be easier to manage branches and merge them.
Also, will your services need to be called by other systems? Look at the cluster we built in the last chapter. Kiali has its own services, but they’re not likely to be used by other applications. Jaeger and Prometheus, however, do have services that are used by Kiali, even if those systems have their own frontends too. In addition to these services, Kiali uses the Kubernetes API. All these components are deployed separately and are managed separately. They need to be upgraded on their own, monitored, and so on. This can be a management headache because each system is independently managed and maintained. That said, it wouldn’t make any sense for the Kiali team to re-implement Prometheus and Jaeger in their own project. It also wouldn’t make sense to just import the entire source tree for these projects and be forced to keep them up to date.
Using Istio to help manage microservices
Section titled “Using Istio to help manage microservices”We’ve spent quite a bit of time talking about microservices and monoliths without talking about Istio. Earlier in this chapter, Figure 17.3 pointed out decisions that were needed by our microservice before we could get to calling our code.
These should look familiar because we covered objects from Istio that service most of these needs in the last chapter! Istio can remove our need to write code to authenticate and authorize clients, discover where services are running, and manage traffic routing. Throughout the rest of this chapter, we’re going to walk through building a small application off of a microservice, using Istio to leverage these common services without having to build them into our code.
So far, we’ve looked at the differences between monoliths and microservices, and how those differences interact with Istio at a conceptual level. Next, we’ll see how a monolith is deployed into Istio.
Deploying a monolith
Section titled “Deploying a monolith”This chapter is about microservices, so why are we starting with deploying monoliths in Istio? The first answer is, because we can! There’s no reason to not get the benefits of Istio’s built-in capabilities when working with monoliths in your cluster. Even though it’s not a “microservice,” it’s still good to be able to trace through application requests, manage deployments, and so on. The second answer is, because we need to. Our microservice will need to know which user in our enterprise is calling it. To do that, Istio will need a JWT to validate. We’ll use OpenUnison to generate JWTs first so that we can call our service manually, and then so we can authenticate users from a frontend and allow it to call our service securely.
Starting with your cluster from Chapter 16, we’re now going to deploy OpenUnison. Go to the chapter17/openunison-istio directory and run deploy_openunison_istio.sh:
cd chapter17/openunison-istio./deploy_openunison_istio.shThis is going to take a while to run. This script does a few things:
- Deploys
cert-managerwith our enterprise CA. - Deploys all of the OpenUnison components (including our testing Active Directory) for impersonation, so we don’t need to worry about updating the API server for SSO to work.
- Labels the
openunisonnamespace withistio-injection: enabled. This tells Istio to enable sidecar injection for all pods. You can do this manually by runningkubectl label ns openunison istio-injection=enabled. - Creates all of our Istio objects for us (we’ll go into the details of these next).
- Creates an
ou-tls-certificateCertificate in the theistio-systemnamespace. Again, we’ll dive into the details as to why in the next section.
Once the script is run, we’re able to now log in to our monolith! Just like in Chapter 6, Integrating Authentication into Your Cluster, go to https://k8sou.apps.XX-XX-XX-XX.nip.io/ to log in, where XX-XX-XX-XX is your host’s IP address.
For instance, my host runs on 192.168.2.114, so my URL is https://k8sou.apps.192-168-2-114.nip.io/. Again, as in Chapter 6, the username is mmosley and the password is start123.
Now that our monolith is deployed, let’s walk through the Istio-specific configuration as it relates to our deployment.
Exposing our monolith outside our cluster
Section titled “Exposing our monolith outside our cluster”Our OpenUnison is running, so let’s look at the objects that expose it to our network. There are two main objects that do this work: Gateway and VirtualService. These objects were created when we installed OpenUnison. How these objects are configured was described in Chapter 16, An Introduction to Istio. Then, we’ll look at running instances to show how they grant access. First, let’s look at the important parts of our gateways. There are two. The first one, openunison-gateway-orchestra, handles access to the OpenUnison portal and the Kubernetes Dashboard:
apiVersion: networking.istio.io/v1beta1kind: Gatewaymetadata:spec: selector: istio: ingressgateway servers: - hosts: - k8sou.apps.192-168-2-114.nip.io - k8sdb.apps.192-168-2-114.nip.io port: name: http number: 80 protocol: HTTP tls: httpsRedirect: true - hosts: - k8sou.apps.192-168-2-114.nip.io - k8sdb.apps.192-168-2-114.nip.io port: name: https-443 number: 443 protocol: HTTPS tls: credentialName: ou-tls-certificate mode: SIMPLEThe selector tells Istio which ingress-ingressgateway pod to work with. The default gateway deployed to istio-system has the label istio: ingressgateway, which will match this one. You could run multiple gateways, using this section to determine which one you want to expose your service to. This is useful if you have multiple networks with different traffic or if you want to separate traffic between applications on a cluster.
The first entry in the servers list tells Istio that if a request comes on HTTP to port 80 for either of our hosts, then we want Istio to send a redirect to the HTTPS port. This is a good security practice, so folks, don’t try to bypass HTTPS. The second entry in servers tells Istio to accept HTTPS connections on port 443, using the certificate in the Secret named ou-tls-certificate. This Secret must be a TLS Secret and be in the same namespace as the pod running the ingress gateway. For our cluster, this means that ou-tls-certificate MUST be in the istio-system namespace. That’s why our deployment script created the wild card certificate in the istio-system namespace. This is different from using an Ingress object with NGINX, where you keep the TLS Secret in the same namespace as your Ingress object.
If you don’t include your Secret in the correct namespace, it can be difficult to debug. The first thing you’ll notice is that when you try to connect to your host, your browser will report that the connection has been reset. This is because Istio doesn’t have a certificate to serve. Kiali won’t tell you there’s a configuration issue, but looking at the istiod pod in istio-system ‘s logs, you’ll find failed to fetch key and certificate for kubernetes://secret-name, where secret-name is the name of your Secret. Once you copy your Secret into the correct namespace, your app will start working on HTTPS.
The second Gateway, openunison-api-gateway-orchestra, is used to expose OpenUnison directly via HTTPS for the API server host. This bypasses most of Istio’s built-in functionality, so it’s not something we’ll want to do unless needed. The important difference in this Gateway versus our other Gateway is how we configure TLS:
- hosts: - k8sapi.192-168-2-114.nip.io port: name: https-443 number: 443 protocol: HTTPS tls: mode: PASSTHROUGHWe use PASSTHROUGH as the mode instead of SIMPLE. This tells Istio to not bother trying to decrypt the HTTPS request and, instead, send it downstream. We have to do this for the Kubernetes API calls because Envoy doesn’t support the SPDY protocol used by kubectl for exec, cp, and port-forward, so we need to bypass it. This, of course, means that we lose much of Istio’s capabilities, so it’s not something we want to do if we can avoid it.
While the Gateway objects tell Istio how to listen for connections, the VirtualService objects tell Istio where to send the traffic to. Just like with the Gateway objects, there are two VirtualService objects. The first object handles traffic for both the OpenUnison portal and the Kubernetes Dashboard. Here are the important parts:
spec: gateways: - openunison-gateway-orchestra hosts: - k8sou.apps.192-168-2-114.nip.io - k8sdb.apps.192-168-2-114.nip.io http: - match: - uri: prefix: / route: - destination: host: openunison-orchestra port: number: 80The gateways section tells Istio which Gateway objects to link this to. You could, in theory, have multiple Gateways as sources for traffic. The hosts section tells Istio which hostnames to apply this configuration to, with the match section telling Istio what conditions to match requests on. This section can provide quite a bit of power for routing microservices, but for monoliths, just / is usually good enough.
Finally, the route section tells Istio where to send the traffic. destination.host is the name of the Service you want to send the traffic to. We’re sending all traffic to port 80 (sort of).
The NGINX Ingress version of this configuration sent all traffic to OpenUnison’s HTTPS port (8443). This meant that all data was encrypted over the wire from the user’s browser, all the way to the OpenUnison pod. We’re not doing that here because we’re going to rely on mTLS from Istio’s sidecar.
Even though we’re sending traffic to port 80 using HTTP, the traffic will be encrypted from when it leaves the ingressgateway pod until it arrives at the sidecar on our OpenUnison pod that intercepts all of OpenUnison’s inbound network connections. There’s no need to configure TLS explicitly!
Now that we’re routing traffic from our network to OpenUnison, let’s tackle a common requirement of monolithic applications: sticky sessions.
Configuring sticky sessions
Section titled “Configuring sticky sessions”Most monolithic applications require sticky sessions. Enabling sticky sessions means that every request in a session is sent to the same pod. This is generally not needed in microservices because each API call is distinct. Web applications that users interact with generally need to manage state, usually via cookies. However, those cookies don’t generally store all of the session’s state because they would get too big and would likely have sensitive information. Instead, most web applications use a cookie that points to a session that’s saved on the server, usually in memory. While there are ways to make sure that this session is available to any instance of the application in a highly available way, it’s not very common to do so. These systems are expensive to maintain and are generally not worth the work.
OpenUnison is no different than most other web applications and needs to make sure that sessions are sticky to the pod they originated from. To tell Istio how we want sessions to be managed, we use DestinationRule. The DestinationRule objects tell Istio what to do about traffic routed to a host by a VirtualService. Here are the important parts of ours:
spec: host: openunison-orchestra trafficPolicy: loadBalancer: consistentHash: httpCookie: name: openunison-orchestra path: / ttl: 0s tls: mode: ISTIO_MUTUALThe host in the rule refers to the target (Service) of the traffic, not the hostname in the original URL. spec.trafficPolicy.loadBalancer.consistentHash tells Istio how we want to manage stickiness. Most monolithic applications will want to use cookies. ttl is set to 0s, so the cookie is considered a “session cookie.” This means that when the browser is closed, the cookie disappears from its cookie jar.
You should avoid cookies with specific times to live. These cookies are persisted by the browser and can be treated as a security risk by your enterprise.
With OpenUnison up and running and understanding how Istio is integrated, let’s take a look at what Kiali will tell us about our monolith.
Integrating Kiali and OpenUnison
Section titled “Integrating Kiali and OpenUnison”First, let’s integrate OpenUnison and Kiali. Kiali, like any other cluster management system, should be configured to require access. Kiali, just like the Kubernetes Dashboard, can integrate with Impersonation so that Kiali will interact with the API server, using the user’s own permissions. Doing this is pretty straight forward. We created a script in the chapter17/kiali folder called integrate-kiali-openunison.sh that:
- Deletes the old Gateways and VirtualServices for Kiali, Prometheus, Jaeger, and Grafana.
- Updates Grafana to accept a header for SSO from OpenUnison.
- Updates the Kiali Helm chart to use
headerforauth.strategyand restarts Kiali to pick up the changes. - Redeploys OpenUnison with Kiali, Prometheus, Jaeger, and Grafana integrated for SSO.
The integration works the same way as the dashboard, but if you’re interested in the details, you can read about them at https://openunison.github.io/applications/kiali/.
With the integration completed, let’s see what Kiali can tell us about our monolith. First, log in to OpenUnison. You’ll see new badges on the portal screen:

Graphical user interface, application, logo, company name Description automatically generated
Figure 17.4: OpenUnison portal with the Kiali, Prometheus, Grafana, and Jaeger badges
Next, click on the Kiali badge to open Kiali, then click on Graphs, and choose the openunison namespace. You’ll see a graph similar to the following:

A screenshot of a computer Description automatically generated with medium confidence
Figure 17.5: OpenUnison graph in Kiali
You can now view the connections between OpenUnison, apacheds, and other containers the same way you would with a microservice! Speaking of which, now that we’ve learned how to integrate a monolith into Istio, let’s build a microservice and learn how it integrates with Istio.
Building a microservice
Section titled “Building a microservice”We spent quite a bit of time talking about monoliths. First, we discussed which is the best approach for you, then we spent some time showing how to deploy a monolith into Istio to get from it many of the benefits that microservices do. Now, let’s dive into building and deploying a microservice. Our microservice will be pretty simple. The goal is to show how a microservice is built and integrated into an application, rather than how to build a full-fledged application based on microservices. Our book is focused on enterprise, so we’re going to focus on a service that:
- Requires authentication from a specific user
- Requires authorization for a specific user based on a group membership or attribute
- Does something very important
- Generates some log data about what happened
This is common in enterprise applications and the services they’re built on. Most enterprises need to be able to associate actions, or decisions, with a particular person in an organization. If an order is placed, who placed it? If a case is closed, who closed it? If a check is cut, who cut it? There are of course many instances where a user isn’t responsible for an action. Sometimes, it’s another service that is automated. A batch service that pulls in data to create a warehouse isn’t associated with a particular person. That is an interactive service, meaning that an end user is expected to interact with it, so we’re going to assume that the user is a person in the enterprise.
Once you know who is going to use the service, you’ll then need to know if the user is authorized to do so. In the previous paragraph, we identified that you need to know “who cut the check.” Another important question is, “Are they allowed to cut the check?” You really don’t want just anybody in your organization sending out checks, do you? Identifying who is authorized to perform an action could be the subject of multiple books, so to keep things simple, we’ll make our authorization decisions based on group membership, at least at a high level.
Having identified the user and authorized them, the next step is to do something important. It’s an enterprise, filled with important things that need doing! Since writing a check is something that we can all relate to and represents many of the challenges enterprise services face, we’re going to stick with this as our example. We’re going to write a check service that will let us send out checks.
Finally, having done something important, we need to make a record of it. We need to track who called our service, and once the service does the important parts, we need to make sure we record it somewhere. This can be recorded in a database or another service, or even sent to standard-out so that it can be collected by a log aggregator, like the OpenSearch we deployed in Chapter 15.
Having identified all the things that our service will do, the next step is to identify which part of our infrastructure will be responsible for each decision and action. For our service:
| Action | Component | Description |
|---|---|---|
| User Authentication | OpenUnison | Our OpenUnison instance will authenticate users to our “Active Directory” |
| Service Routing | Istio | How we will expose our service to the world |
| Service Authentication | Istio | The RequestAuthentication object will describe how to validate the user for our service |
| Service Coarse Grained Authorization | Istio | AuthorizationPolicy will make sure users are members of a specific group to call our service |
| Fine-Grained Authorization, or Entitlements | Service | Our service will determine which payees you’re able to write checks for |
| Writing a Check | Service | The point of writing this service! |
| Log who Wrote the Check and to whom it was Sent | Service | Write this data to standard-out |
| Log Aggregation | Kubernetes | In production – a tool like OpenSearch |
Table 17.1: Service responsibilities
We’ll build each of these components, layer by layer, in the following sections. Before we get into the service itself, we need to say hello to the world.
Deploying Hello World
Section titled “Deploying Hello World”Our first service will be a simple Hello World service that will serve as the starting point for our check-writing service. Our service is built on Python using Flask. We’re using this because it’s pretty simple to use and deploy. Go to chapter17/hello-world and run the deploy_helloworld.sh script. This will create our Namespace, Deployment, Service, and Istio objects. Look at the code in the service-source ConfigMap. This is the main body of our code and the framework on which we will build our check service. The code itself doesn’t do much:
@app.route('/')def hello(): retVal = { "msg":"hello world!", "host":"%s" % socket.gethostname() } return json.dumps(retVal)This code accepts all requests to / and runs our function called hello(), which sends a simple response. We’re embedding our code as a ConfigMap for the sake of simplicity.
If you’ve read all the previous chapters, you’ll notice that we’re violating some cardinal rules with this container from a security standpoint. It’s a Docker Hub container running as root. That’s OK for now. We didn’t want to get bogged down in the build processes for this chapter. In Chapter 19*, Building a Developer Portal*, we’ll walk through using GitLab workflows to build out a more secure version of the container for this service.
Once our service is deployed, we can test it out by using curl:
$ curl http://service.192-168-2-114.nip.io/{"msg": "hello world!", "host": "run-service-785775bf98-fln49"}%This code isn’t terribly exciting, but next, we’ll add some security to our service.
Integrating authentication into our service
Section titled “Integrating authentication into our service”In Chapter 16, An Introduction to Istio, we introduced the RequestAuthentication object. Now, we will use this object to enforce authentication. We want to make sure that in order to access our service, you must have a valid JWT. In the previous example, we just called our service directly. Now, we want to only get a response if a valid JWT is embedded in the request. We need to make sure to pair our RequestAuthentication with an AuthorizationPolicy that forces Istio to require a JWT; otherwise, Istio will only reject JWTs that don’t conform to our RequestAuthentication but allow requests that have no JWT at all.
Even before we configure our objects, we need to get a JWT from somewhere. We’re going to use OpenUnison. To work with our API, let’s deploy the pipeline token generation chart we deployed in Chapter 6*, Integrating Authentication into Your Cluster*. Go to the chapter6/pipelines directory and run the Helm chart:
$ helm install orchestra-token-api token-login -n openunison -f /tmp/openunison-values.yamlNAME: orchestra-token-apiLAST DEPLOYED: Tue Aug 31 19:41:30 2021NAMESPACE: openunisonSTATUS: deployedREVISION: 1TEST SUITE: NoneThis will give us a way to easily generate a JWT from our internal Active Directory. Next, we’ll deploy the actual policy objects. Go into the chapter17/authentication directory and run deploy-auth.sh. It will look like this:
$ ./deploy-auth.shsecret/cacerts configuredpod "istiod-75d8d56b68-tm6b7" deletedrequestauthentication.security.istio.io/hello-world-auth createdauthorizationpolicy.security.istio.io/simple-hellow-world createdFirst, we created a Secret called cacerts to store our enterprise CA certificate and restart istiod. This will allow istiod to communicate with OpenUnison to pull jwks signature verification keys. Next, two objects are created. The first is the RequestAuthentication object and then a simple AuthorizationPolicy. First, we will walk through RequestAuthentication:
apiVersion: security.istio.io/v1kind: RequestAuthenticationmetadata: name: hello-world-auth namespace: istio-hello-worldspec: jwtRules: - audiences: - kubernetes issuer: https://k8sou.192-168-2-119.nip.io/auth/idp/k8sIdp jwksUri: https://k8sou.192-168-2-119.nip.io/auth/idp/k8sIdp/certs outputPayloadToHeader: User-Info selector: matchLabels: app: run-serviceThis object first specifies how the JWT needs to be formatted in order to be accepted. We’re cheating here a bit by just leveraging our Kubernetes JWT. Let’s compare this object to our JWT:
{ "iss": "https://k8sou.192-168-2-119.nip.io/auth/idp/k8sIdp", "aud": "kubernetes", "exp": 1630421193, "jti": "JGnXlj0I5obI3Vcmb1MCXA", "iat": 1630421133, "nbf": 1630421013, "sub": "mmosley", "name": " Mosley", "groups": [ "cn=group2,ou=Groups,DC=domain,DC=com", "cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com" ], "preferred_username": "mmosley", "email": "[email protected]"}The aud claim in our JWT lines up with the audiences in our RequestAuthentication. The iss claim lines up with issuer in our RequestAuthentication. If either of these claims doesn’t match, then Istio will return a 401 HTTP error code to tell you that the request is unauthorized.
We also specify outputPayloadToHeader: User-Info to tell Istio to pass the user info to the downstream service as a base64-encoded JSON header, with the name User-Info. This header can be used by our service to identify who called it. We’ll get into the details of this when we get into entitlement authorization.
Additionally, the jwksUri section specifies the URL that contains the RSA public keys used to verify the JWT. This can be obtained by first going to the issuer’s OIDC discovery URL and getting the URL from the jwks claim.
It’s important to note that the RequestAuthentication object will tell Istio what form the JWT needs to take, but not what data about the user needs to be present. We’ll cover that next, in the authorization section.
Speaking of authorization, we want to make sure to enforce the requirement for a JWT, so we will create this very simple AuthorizationPolicy:
apiVersion: security.istio.io/v1kind: AuthorizationPolicymetadata: name: simple-hellow-world namespace: istio-hello-worldspec: action: ALLOW rules: - from: - source: requestPrincipals: - '*' selector: matchLabels: app: run-serviceThe from section says that there must be a requestPrincipal. This tells Istio there must be a user (and in this case, anonymous is not a user). requestPrincipal comes from JWTs and represents users. There is also a principal configuration, but this represents the service calling our URL, which in this case would be ingressgateway. This tells Istio that a user must be authenticated via a JWT.
With our policy in place, we can now test it. First, with no user:
curl -v http://service.192-168-2-119.nip.io/* Trying 192.168.2.119:80...* TCP_NODELAY set* Connected to service.192-168-2-119.nip.io (192.168.2.119) port 80 (#0)> GET / HTTP/1.1> Host: service.192-168-2-119.nip.io> User-Agent: curl/7.68.0> Accept: */*>* Mark bundle as not supporting multiuse< HTTP/1.1 403 Forbidden< content-length: 19< content-type: text/plain< date: Tue, 31 Aug 2021 20:23:14 GMT< server: istio-envoy< x-envoy-upstream-service-time: 2<* Connection #0 to host service.192-168-2-119.nip.io left intactWe can see that the request was denied with a 403 HTTP code. We received 403 because Istio was expecting a JWT but there wasn’t one. Next, let’s generate a valid token the same way we did in Chapter 6*, Integrating Authentication into Your Cluster*:
curl -H "Authorization: Bearer $(curl --insecure -u 'mmosley:start123' https://k8sou.apps.192-168-2-119.nip.io/k8s-api-token/token/user 2>/dev/null| jq -r '.token.id_token')" http://service.192-168-2-119.nip.io/{"msg": "hello world!", "host": "run-service-785775bf98-6bbwt"}Now, we have success! Our hello world service now requires proper authentication. Next, we’ll update our authorization to require a specific group from Active Directory.
Authorizing access to our service
Section titled “Authorizing access to our service”So far, we’ve built a service and made sure users have a valid JWT from our identity provider before they can access it.
Now, we want to apply what’s often referred to as “coarse-grained” authorization. This is application- or service-level access. It says, “You are generally able to use this service,” but it doesn’t say you’re able to perform the action you wish to take. For our check-writing service, you may be authorized to write a check, but there are likely more controls that limit who you can write a check for. If you’re responsible for the Enterprise Resource Planning (ERP) system in your enterprise, you probably shouldn’t be able to write checks for the facility vendors. We’ll get into how your service can manage these business-level decisions in the next section, but for now, we’ll focus on the service-level authorization.
It turns out we have everything we need. Earlier, we looked at our mmosley user’s JWT, which had multiple claims. One such claim was the groups claim. We used this claim in Chapter 6, Integrating Authentication into Your Cluster, and Chapter 7, RBAC Policies and Auditing, to manage access to our cluster. In a similar fashion, we’ll manage who can access our service based on our membership of a particular group. First, we’ll delete our existing policy:
kubectl delete authorizationpolicy simple-hellow-world -n istio-hello-worldauthorizationpolicy.security.istio.io "simple-hellow-world" deletedWith the policy disabled, you can now access your service without a JWT. Next, we’ll create a policy that requires you to be a member of the group cn=group2,ou=Groups,DC=domain,DC=com in our Active Directory.
Deploy the below policy (in chapter17/coursed-grained-authorization/coursed-grained-az.yaml):
---apiVersion: security.istio.io/v1kind: AuthorizationPolicymetadata: name: service-level-az namespace: istio-hello-worldspec: action: ALLOW selector: matchLabels: app: run-service rules: - when: - key: request.auth.claims[groups] values: ["cn=group2,ou=Groups,DC=domain,DC=com"]This policy tells Istio that only users with a claim called groups that have the value cn=group2,ou=Groups,DC=domain,DC=com are able to access this service. With this policy deployed, you’ll see that you can still access the service as mmosley, and trying to access the service anonymously still fails. Next, try accessing the service as jjackson, with the same password:
curl -H "Authorization: Bearer $(curl --insecure -u 'jjackson:start123' https://k8sou.192-168-2-119.nip.io/k8s-api-token/token/user 2>/dev/null| jq -r '.token.id_token')" http://service.192-168-2-119.nip.io/RBAC: access deniedWe’re not able to access this service as jjackson. If we look at jjackson ‘s id_token, we can see why:
{ "iss": "https://k8sou.192-168-2-119.nip.io/auth/idp/k8sIdp", "aud": "kubernetes", "exp": 1630455027, "jti": "Ae4Nv22HHYCnUNJx780l0A", "iat": 1630454967, "nbf": 1630454847, "sub": "jjackson", "name": " Jackson", "groups": "cn=k8s-create-ns,ou=Groups,DC=domain,DC=com", "preferred_username": "jjackson", "email": "[email protected]"}Looking at the claims, jjackson isn’t a member of the group cn=group2,ou=Groups,DC=domain,DC=com.
Now that we’re able to tell Istio how to limit access to our service to valid users, the next step is to tell our service who the user is. We’ll then use this information to look up authorization data, log actions, and act on the user’s behalf.
Telling your service who’s using it
Section titled “Telling your service who’s using it”When writing a service that does anything involving a user, the first thing you need to determine is, “Who is trying to use my service?” So far, we have told Istio how to determine who the user is, but how do we propagate that information down to our service? Our RequestAuthentication included the configuration option outputPayloadToHeader: User-Info, which injects the claims from our user’s authentication token as base64-encoded JSON into the HTTP request’s headers. This information can be pulled from that header and used by your service to look up additional authorization data.
We can view this header with a service we built, called /headers. This service will just give us back all the headers that are passed to our service. Let’s take a look:
curl -H "Authorization: Bearer $(curl --insecure -u 'mmosley:start123' https://k8sou.192-168-2-119.nip.io/k8s-api-token/token/user 2>/dev/null| jq -r '.token.id_token')" http://service.192-168-2-119.nip.io/headers 2>/dev/null | jq -r '.headers'Host: service.192-168-2-119.nip.ioUser-Agent: curl/7.75.0Accept: */*X-Forwarded-For: 192.168.2.112X-Forwarded-Proto: httpX-Request-Id: 6397d068-537e-94b7-bf6b-a7c649db5b3dX-Envoy-Attempt-Count: 1X-Envoy-Internal: trueX-Forwarded-Client-Cert: By=spiffe://cluster.local/ns/istio-hello-world/sa/default;Hash=1a58a7d0abf62d32811c084a84f0a0f42b28616ffde7b6b840c595149d99b2eb;Subject="";URI=spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-accountUser-Info: eyJpc3MiOiJodHRwczovL2s4c291LjE5Mi0xNjgtMi0xMTkubmlwLmlvL2F1dGgvaWRwL2s4c0lkcCIsImF1ZCI6Imt1YmVybmV0ZXMiLCJleHAiOjE2MzA1MTY4MjQsImp0aSI6InY0ekpCNzdfRktpOXJoQU5jWDVwS1EiLCJpYXQiOjE2MzA1MTY3NjQsIm5iZiI6MTYzMDUxNjY0NCwic3ViIjoibW1vc2xleSIsIm5hbWUiOiIgTW9zbGV5IiwiZ3JvdXBzIjpbImNuPWdyb3VwMixvdT1Hcm91cHMsREM9ZG9tYWluLERDPWNvbSIsImNuPWs4cy1jbHVzdGVyLWFkbWlucyxvdT1Hcm91cHMsREM9ZG9tYWluLERDPWNvbSJdLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJtbW9zbGV5IiwiZW1haWwiOiJtbW9zbGV5QHRyZW1vbG8uZGV2In0=X-B3-Traceid: 28fb185aa113ad089cfac2d6884ce9acX-B3-Spanid: d40f1784a6685886X-B3-Parentspanid: 9cfac2d6884ce9acX-B3-Sampled: 1There are several headers here. The one we care about is User-Info. This is the name of the header we specified in our RequestAuthentication object. If we decode from base64, we’ll get some JSON:
{ "iss": "https://k8sou.192-168-2-119.nip.io/auth/idp/k8sIdp", "aud": "kubernetes", "exp": 1630508679, "jti": "5VoEAAgv1rkpf1vOJ9uo-g", "iat": 1630508619, "nbf": 1630508499, "sub": "mmosley", "name": " Mosley", "groups": [ "cn=group2,ou=Groups,DC=domain,DC=com", "cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com" ], "preferred_username": "mmosley", "email": "[email protected]"}We have all the same claims as if we had decoded the token ourselves. What we don’t have is the JWT. This is important from a security standpoint. Our service can’t leak a token it doesn’t possess.
Now that we know how to determine who the user is, let’s integrate that into a simple who-am-i service that just tells us who the user is. First, let’s look at our code:
@app.route('/who-am-i') def who_am_i(): user_info = request.headers["User-Info"] user_info_json = base64.b64decode(user_info).decode("utf8") user_info_obj = json.loads(user_info_json) ret_val = { "name": user_info_obj["sub"], "groups": user_info_obj["groups"] } return json.dumps(ret_val)This is pretty basic. We’re getting the header from our request. Next, we decode it from base64, and finally, we get the JSON and add it to a return. If this were a more complex service, this is where we might query a database to determine what entitlements our user has.
In addition to not requiring that our code knows how to verify the JWT, this also makes it easier for us to develop our code in isolation from Istio. Open a shell in your run-service pod and try accessing this service directly with any user:
kubectl exec -ti run-service-785775bf98-g86gl -n istio-hello-world – bash# export USERINFO=$(echo -n '{"sub":"marc","groups":["group1","group2"]}' | base64 -w 0)# curl -H "User-Info: $USERINFO" http://localhost:8080/who-am-i{"name": "marc", "groups": ["group1", "group2"]}We were able to call our service without having to know anything about Istio, JWTs, or cryptography! Everything was offloaded to Istio so that we could focus on our service. While this does make for easier development, what are the impacts on security if there’s a way to inject any information we want into our service?
Let’s try this directly from a namespace that doesn’t have the Istio sidecar:
$ kubectl run -i --tty curl --image=alpine --rm=true – sh/ # apk update add curl/ # curl -H "User-Info $(echo -n '{"sub":"marc","groups":["group1","group2"]}' | base64 -w 0)" http://run-service.istio-hello-world.svc/who-am-iRBAC: access deniedOur RequestAuthentication and AuthorizationPolicy stop the request. While we’re not running the sidecar, our service is, and it redirects all traffic to Istio where our policies will be enforced. What about if we try to inject our own User-Info header from a valid request?
export USERINFO=$(echo -n '{"sub":"marc","groups":["group1","group2"]}' | base64 -w 0)curl -H "Authorization: Bearer $(curl --insecure -u 'mmosley:start123' https://k8sou.192-168-2-119.nip.io/k8s-api-token/token/user 2>/dev/null| jq -r '.token.id_token')" -H "User-Info: $USERINFO" http://service.192-168-2-119.nip.io/who-am-i{"name": "mmosley", "groups": ["cn=group2,ou=Groups,DC=domain,DC=com", "cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com"]}Once again, our attempt to override who the user is outside of a valid JWT has been foiled by Istio. We’ve shown how Istio injects a user’s identity into our service; now, we need to know how to authorize a user’s entitlements.
Authorizing user entitlements
Section titled “Authorizing user entitlements”So far, we’ve managed to add quite a bit of functionality to our service without having to write any code. We added token-based authentication and coarse-grained authorization. We know who the user is and have determined that, at the service level, they are authorized to call our service. Next, we need to decide if the user is allowed to do the specific action they’re trying to do. This is often called fine-grained authorization or entitlements. In this section, we’ll walk through multiple approaches you can take, discussing how you should choose an approach.
Authorizing in service
Section titled “Authorizing in service”Unlike coarse-grained authorizations and authentication, entitlements are generally not managed at the service mesh layer. That’s not to say it’s impossible. We’ll talk about ways you can do this in the service mesh, but in general, it’s not the best approach. Authorizations are generally tied to business data that’s usually locked up in a database. Sometimes, that database is a generic relational database, like MySQL or SQL Server, but it could really be anything. Since the data used to make the authorization decision is often owned by the service owner, not the cluster owner, it’s generally easier and more secure to make entitlement decisions directly in our code.
Earlier, we discussed in our check-writing service that we don’t want someone responsible for the ERP to cut checks to the facilities vendor. Where is the data that determines that? Well, it’s probably in your enterprise’s ERP system. Depending on how big you are, this could be a homegrown application or a SAP or Oracle. Let’s say you wanted Istio to make the authorization decision for our check-writing service. How would it get that data? Do you think the people responsible for the ERP want you, as a cluster owner, to talk to their database directly? Do you, as a cluster owner, want that responsibility? What happens when something goes wrong with the ERP and someone points the finger at you for the problem? Do you have the resources to prove that you, and your team, were not responsible?
It turns out that the silos in enterprises that benefit from the management aspects of microservice design also work against centralized authorization. In our example of determining who can write the check for a specific vendor, it’s probably just easiest to make this decision inside our service. This way, if there’s a problem, it’s not the Kubernetes team’s responsibility to determine the issue, and the people who are responsible are in control of their own destiny.
That’s not to say there isn’t an advantage to a more centralized approach to authorization. Having teams implement their own authorization code will lead to different standards being used and different approaches. Without careful controls, it can lead to a compliance nightmare. Let’s look at how Istio could provide a more robust framework for authorization.
Using OPA with Istio
Section titled “Using OPA with Istio”Using the Envoy filters feature discussed in Chapter 16, An Introduction to Istio, you can integrate the Open Policy Agent (OPA) into your service mesh to make authorization decisions. We discussed OPA in Chapter 11, Extending Security Using Open Policy Agent. There are a few key points about OPA we need to review:
- OPA does not (typically) reach out to external data stores to make authorization decisions. Much of the benefit of OPA requires that it uses its own internal database.
- OPA’s database is not persistent. When an OPA instance dies, it must be repopulated with data.
- OPA’s databases are not clustered. If you have multiple OPA instances, each database must be updated independently.
To use OPA to validate whether our user can write a check for a specific vendor, OPA would either need to be able to pull that data directly from the JWT or have the ERP data replicated in its own database. The former is unlikely to happen for multiple reasons. First, the issues with your cluster talking to your ERP will still exist when your identity provider tries to talk to your ERP. Second, the team that runs your identity provider would need to know to include the correct data, which is a difficult task and is unlikely something they’re interested in doing. Finally, there could be numerous folks, from security to the ERP team, who are not comfortable with this data being stored in a token that gets passed around. The latter option, syncing data into OPA, is more likely to be successful.
There are two ways you could sync your authorization data from your ERP into your OPA databases. The first is by pushing the data. A “bot” could push updates to each OPA instance. This way, the ERP owner is responsible for pushing the data, with your cluster just being a consumer. However, there’s no simple way to do this, and security would be a concern to make sure someone doesn’t push false data. The alternative is to write a pull “bot” that runs as a sidecar to your OPA pods. This is how GateKeeper works. The advantage here is that you have the responsibility of keeping your data synced without having to build a security framework to push data.
In either scenario, you’ll need to understand whether there are any compliance issues with the data you are storing. Now that you have the data, what’s the impact of losing it in a breach? Is that a responsibility you want?
Centralized authorization services have been discussed for entitlements long before Kubernetes or even RESTful APIs existed. They even predate SOAP and XML! For enterprise applications, it’s never really worked because of the additional costs in data management, ownership, and bridging silos. If you own all of the data, this is a great approach. When one of the main goals of microservices is to allow silos to better manage their own development, forcing a centralized entitlements engine is not likely to succeed.
With all that said, there has been a move towards centralizing authorization services. This movement has spawned several commercial companies and projects outside of OPA:
- Cedar: An open source project from Amazon Web Services that creates a new policy language. Amazon has also created a service built on this language: https://github.com/cedar-policy.
- Topaz: Built on OPA and Zanzibar, Topaz provides the OPA authorization engine with relationship-based authorizations from Zanzibar. There’s also a commercial offering: https://github.com/aserto-dev/topaz.
- OpenFGA: Another engine built on Zanzibar’s relationship-based authorization system, built by Auth0/Okta: https://github.com/openfga.
We’re not going to dive into any of these solutions in detail; the point is that there has been a clear movement toward building authorization solutions, similar to how externalized authentication has been a product and project category for multiple decades.
Now that we know some of the issues involved in creating a centralized authorization, let’s build out an authorization rule with OPA for Istio.
Creating an OPA Authorization Rule
Section titled “Creating an OPA Authorization Rule”Earlier in this section, we discussed writing checks. A common rule for writing checks is that the person who writes the check is now also allowed to sign the check. This rule is called a “separation of duties.” It’s designed to build checkpoints for potentially harmful and costly processes. For instance, if an employee were allowed to both write the check and sign it, there’s no chance for someone to ask if the check is being written for a valid reason.
We’ve already implemented an AuthorizationPolicy that validates group membership, but for separation of duties, what we want is to implement a rule that validates that a user is a member of one group while NOT a member of another group. This sort of complex decision isn’t possible with a generic AuthorizationPolicy, so we’re going to need to build our own. We can use OPA as our authorization engine while instructing Istio to use our policy.
Before we deploy our policy, let’s review it. The full policy is in chapter17/opa/rego and includes test cases:
package istio.authzimport input.attributes.request.http as http_requestimport input.parsed_pathdefault allow = falsecontains_element(arr, elem) = true { arr[_] = elem} else = false { true }verify_headers() = payload { startswith(http_request.headers["authorization"], "Bearer ") [header, payload, signature] := io.jwt.decode(trim_prefix(http_request.headers["authorization"], "Bearer "))} else = false {true}allow { payload := verify_headers() payload.groups contains_element(payload.groups,"cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com") not contains_element(payload.groups,"cn=group2,ou=Groups,DC=domain,DC=com")}allow { payload := verify_headers() payload.groups payload.groups == "cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com"}We removed the comments to make the code more compact. The basics of this policy are that we:
- Verify that there’s an
authorizationheader. - Verify that the
authorizationheader is aBearertoken. - Verify that the bearer token is a JWT.
- Parse the JWT and verify that there is a
groupsclaim. - If the
groupsclaim is a list, make sure that it contains thek8s-cluster-adminsgroup, but NOT thegroup2group. - If the
groupsclaim is not a list, only validate that it’s thek8s-cluster-adminsgroup.
We are validating that the authorization header is present and properly formatted because Istio does not require a token to be present to pass authentication. This was done by our previous AuthorizationPolicy, either explicitly by requiring that a principal be present or implicitly by requiring that a specific claim has a specific value.
Once we have validated that the authorization header is properly formatted, we parse it for a payload. We’re not validating the JWT based on its public key, validity, or issuer because our RequestAuthentication object is doing that for us. We just need to make sure that the token is there.
Finally, we have two potential allow policies. The first is if the groups claim is a list, so we need to apply array logic to see if the correct group is present and that the forbidden group is not present. The second allow policy will trigger if the groups claim is not a list but only a single value. In this case, we only care that the group’s value is our admin group.
To deploy this policy, go to the chapter17/opa directory and run deploy_opa_istio.sh. The script will enable authorization and deploy our policy:
- Configure istiod: Updates the
istioConfigMapthat stores the mesh configuration to enable theenvoyExtAuthzGrpcextension provider. - Deploy an OPA mutating admission controller: A mutating admission controller is deployed to automate the creation of an OPA instance on pods that runs alongside your services.
- Deploys our policy: The policy we created earlier is created as a
ConfigMap. - Redeploy our service: Deletes the pod so that it is recreated with our authorization policy.
- Once everything is deployed, we can now verify that our policy is being enforced using a
curlcommand. If we try to call our headers service now with ourmmosleyuser, it will fail becausemmosleyis a member of both thek8s-cluster-admingroup and thegroup2group:
$ curl -v -H "Authorization: Bearer $(curl --insecure -u 'mmosley:start123' https://k8sou.apps.192-168-2-96.nip.io/k8s-api-token/token/user 2>/dev/null| jq -r '.token.id_token')" http://service.192-168-2-96.nip.io/headers* Trying 192.168.2.96:80...* Connected to service.192-168-2-96.nip.io (192.168.2.96) port 80> GET /headers HTTP/1.1> Host: service.192-168-2-96.nip.io> User-Agent: curl/8.4.0> Accept: */*> Authorization: Bearer …>< HTTP/1.1 403 Forbidden< date: Tue, 27 Feb 2024 19:49:49 GMT< server: istio-envoy< content-length: 0< x-envoy-upstream-service-time: 8<* Connection #0 to host service.192-168-2-96.nip.io left intactHowever, if we use our pipeline_svc_account user, it succeeds because this user is only a member of the k8s-cluster-admin group:
$ curl -H "Authorization: Bearer $(curl --insecure -u 'pipeline_svc_account:start123' https://k8sou.apps.192-168-2-96.nip.io/k8s-api-token/token/user 2>/dev/null| jq -r '.token.id_token')" http://service.192-168-2-96.nip.io/headers{"headers": "Host: service.192-168-2-96.nip.io\r\nUser-Agent: curl/8.4.0\r\nAccept: */*\r\nX-Forwarded-For: 192.168.3.6\r\nX-Forwar…Now, we can build more complex policies than what’s possible with Istio’s AuthorizationPolicy ‘s built-in authorization capabilities.
Having determined how to integrate entitlements into our services, the next question we need to answer is, how do we securely call other services?
Calling other services
Section titled “Calling other services”We’ve written services that do simple things, but what about when your service needs to talk to another service? Just like with almost every other set of choices in your cluster rollout, you have multiple options to authenticate to other services. Which choice you make will depend on your needs. We’ll first cover the OAuth2 standard way of getting new tokens for service calls and how Istio works with it. We’ll then cover some alternatives that should be considered anti-patterns but that you may choose to use anyway.
Using OAuth2 Token Exchange
Section titled “Using OAuth2 Token Exchange”Your service knows who your user is but needs to call another service. How do you identify yourself to the second service? The OAuth2 specification, which OpenID Connect is built on, has RFC 8693 – OAuth2 Token Exchange for this purpose. The basic idea is that your service will get a fresh token from your identity provider for the service call, based on the existing user. By getting a fresh token for your own call to a remote service, you’re making it easier to lock down where tokens can be used and who can use them, allowing yourself to more easily track a call’s authentication and authorization flow. The following diagram gives a high-level overview.

A picture containing text, screenshot, line, diagram Description automatically generated
Figure 17.6: OAuth2 Token Exchange sequence
There are some details we’ll walk through that depend on your use case:
- The user requests an
id_tokenfrom the identity provider. How the user gets their token doesn’t really matter for this part of the sequence. We’ll use a utility in OpenUnison for our lab. - Assuming you’re authenticated and authorized, your identity provider will give you an
id_tokenwith anaudclaim that will be accepted by Service-X. - The user uses the
id_tokenas a bearer token to call Service-X. It goes without saying that Istio will validate this token. - Service-X requests a token for Service-Y from the identity provider on behalf of the user. There are two potential methods to do this. One is impersonation; the other is delegation. We’ll cover both in detail later in this section. You’ll send your identity provider your original
id_tokenand something to identify the service to the identity provider. - Assuming Service-X is authorized, the identity provider sends a new
id_tokento Service-X with the original user’s attributes and anaudscoped to Service-Y. - Service-X uses the new
id_tokenas theAuthorizationheader when calling Service-Y. Again, Istio validates theid_token.
Steps 7 and 8 in the previous diagram aren’t really important here.
If you think this seems like quite a bit of work to make a service call, you’re right. There are several authorization steps going on here:
- The identity provider authorizes the user to generate a token scoped to Service-X.
- Istio validates the token and that it’s properly scoped to Service-X.
- The identity provider authorizes Service-X to get a token for Service-Y and to do so for our user.
- Istio validates that the token used by Service-X for Service-Y is properly scoped.
These authorization points provide a chance for an improper token to be stopped, allowing you to create very short-lived tokens that are harder to abuse and are more narrowly scoped. For instance, if the token used to call Service-X was leaked, it couldn’t be used to call Service-Y on its own. You’d still need Service-X’s own token before you could get a token for Service-Y. That’s an additional step an attacker would need to take in order to get control of Service-Y. It also means breaching more than one service, providing multiple layers of security. This lines up with our discussion of defense in depth from Chapter 11, Extending Security Using Open Policy Agent. With a high-level understanding of how OAuth2 Token Exchange works, the next question we need to answer is, how will your services authenticate themselves to your identity provider?
Authenticating your service
Section titled “Authenticating your service”In order for the token exchange to work, your identity provider needs to know who the original user is and which service wants to exchange the token on behalf of the user. In the check-writing service example we’ve discussed, you wouldn’t want the service that provides today’s lunch menu to be able to generate a token for issuing a check! You accomplish this by making sure your identity provider knows the difference between your check-writing services and your lunch menu service by authenticating each service individually.
There are three ways a service running in Kubernetes can authenticate itself to the identity provider:
- Use the Pod’s
ServiceAccounttoken - Use Istio’s mTLS capabilities
- Use a pre-shared “client secret”
Throughout the rest of this section, we’re going to focus on option #1, using the Pod’s built-in ServiceAccount token. This token is provided by default for each running pod. This token can be validated by either submitting it to the API server’s TokenReview service or by treating it as a JWT, validating it against the public key published by the API server.
In our examples, we’re going to use the TokenReview API to test the passed-in ServiceAccount token against the API server. This is the most backward-compatible approach and supports any kind of token integrated into your cluster. For instance, if you’re deployed in a managed cloud with its own IAM system that mounts tokens, you could use that as well. This could generate a considerable amount of load on your API server, since every time a token needs to be validated, it gets sent to the API server.
The TokenRequest API discussed in Chapter 6, Integrating Authentication into Your Cluster, can be used to cut down on this additional load. Instead of using the TokenReview API, we can call the API server’s issuer endpoint to get the appropriate token verification public key and use that key to validate the token’s JWT. While this is convenient and scales better, it does have some drawbacks:
- Starting in 1.21,
ServiceAccounttokens are mounted using theTokenRequestAPI but with lifespans of a year or more. You can manually change this to be as short as 10 minutes. - Validating the JWT directly against a public key won’t tell you if the pod is still running. The
TokenReviewAPI will fail if aServiceAcounttoken is associated with a deleted pod, adding an additional layer of security. - Enabling this feature requires enabling anonymous authentication in your cluster, which can be leveraged to elevate privileges with misconfigured RBAC or potential bugs.
We’re not going to use Istio’s mTLS capabilities because it’s not as flexible as tokens. It’s primarily meant for intra-cluster communications, so if our identity provider were outside of the cluster, it would be much harder to use. Also, since mTLS requires a point-to-point connection, any TLS termination points would break its use. Since it’s rare for an enterprise system to host its own certificate, even outside of Kubernetes, it would be very difficult to implement mTLS between your cluster’s services and your identity provider.
Finally, we’re not going to use a shared secret between our services and our identity provider because we don’t need to. Shared secrets are only needed when you have no other way to give a workload an identity. Since Kubernetes gives every pod its own identity, there’s no need to use a client secret to identify our service.
Now that we know how our services will identify themselves to our identity provider, let’s walk through an example of using OAuth2 Token Exchange to securely call one service from another.
Deploying and running the check-writing service
Section titled “Deploying and running the check-writing service”Having walked through much of the theory of using a token exchange to securely call services, let’s deploy an example check-writing service. When we call this service, it will call two other services. The first service, check-funds, will use the impersonation profile of OAuth2 Token Exchange, while the second service, pull-funds, will use delegation. We’ll walk through each of these individually. First, use Helm to deploy an identity provider. Go into the chapter17 directory and run:
helm install openunison-service-auth openunison-service-auth -n openunisonNAME: openunison-service-authLAST DEPLOYED: Mon Sep 13 01:08:09 2021NAMESPACE: openunisonSTATUS: deployedREVISION: 1TEST SUITE: NoneWe’re not going to go into the details of OpenUnison’s configuration. Suffice it to say, this will set up an identity provider for our services and a way to get an initial token. Next, deploy the write-checks service:
cd write-checks/./deploy_write_checks.shgetting oidc configgetting jwksnamespace/write-checks createdconfigmap/service-source createddeployment.apps/write-checks createdservice/write-checks createdgateway.networking.istio.io/service-gateway createdvirtualservice.networking.istio.io/service-vs createdrequestauthentication.security.istio.io/write-checks-auth createdauthorizationpolicy.security.istio.io/service-level-az createdThis should look pretty familiar after the first set of examples in this chapter. We deployed our service as Python in a ConfigMap and the same Istio objects we created in the previous service. The only major difference is in our RequestAuthentication object:
apiVersion: security.istio.io/v1beta1kind: RequestAuthenticationmetadata: name: write-checks-auth namespace: write-checksspec: jwtRules: - audiences: - users - checkfunds - pullfunds forwardOriginalToken: true issuer: https://k8sou.apps.192-168-2-119.nip.io/auth/idp/service-idp jwksUri: https://k8sou.apps.192-168-2-119.nip.io/auth/idp/service-idp/certs outputPayloadToHeader: User-Info selector: matchLabels: app: write-checksThere’s an additional setting, forwardOriginalToken, that tells Istio to send the service the original JWT used to authenticate the call. We’ll need this token in order to prove to the identity provider that we should even attempt to perform a token exchange. You can’t ask for a new token if you can’t provide the original. This keeps someone with access to your service’s pod from requesting a token on your behalf with just the service’s ServiceAccount.
Earlier in the chapter, we said we couldn’t leak a token we didn’t have, so we shouldn’t have access to the original token. This would be true if we didn’t need it to get a token for another service. Following the concept of least privilege, we shouldn’t forward the token if we don’t need to. In this case, we need it for a token exchange, so it’s worth the increased risk to have more secure service-to-service calls.
With our example check-writing service deployed, let’s run it and work backward. Just like with our earlier examples, we’ll use curl to get the token and call our service. In chapter17/write-checks, run call_service.sh:
./call_service.sh{ "msg": "hello world!", "host": "write-checks-84cdbfff74-tgmzh", "user_jwt": "...", "pod_jwt": "...", "impersonated_jwt": "...", "call_funds_status_code": 200, "call_funds_text": "{\"funds_available\": true, \"user\": \"mmosley\"}", "actor_token": "...", "delegation_token": "...", "pull_funds_text": "{\"funds_pulled\": true, \"user\": \"mmosley\", \"actor\": \"system:serviceaccount:write-checks:default\"}"}The output you see is the result of the calls to /write-check, which then calls /check-funds and /pull-funds. Let’s walk through each call, the tokens that are generated, and the code that generates them.
Using Impersonation
Section titled “Using Impersonation”We’re not talking about the same Impersonation you used in Chapter 6, Integrating Authentication into Your Cluster. It’s a similar concept, but this is specific to token exchange. When /write-check needs to get a token to call /check-funds, it asks OpenUnison for a token on behalf of our user, mmosley. The important aspect of Impersonation is that there’s no reference to the requesting client in the generated token. The /check-funds service does not know that the token it’s received wasn’t retrieved by the user themselves. Working backward, the impersonated_jwt in the response to our service call is what /write-check uses to call /check-funds. Here’s the payload after dropping the result into jwt.io:
{ "iss": "https://k8sou.192-168-2-119.nip.io/auth/idp/service-idp", "aud": "checkfunds", "exp": 1631497059, "jti": "C8Qh8iY9FJdFzEO3pLRQzw", "iat": 1631496999, "nbf": 1631496879, "nonce": "bec42c16-5570-4bd8-9038-be30fd216016", "sub": "mmosley", "name": " Mosley", "groups": [ "cn=group2,ou=Groups,DC=domain,DC=com", "cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com" ], "preferred_username": "mmosley", "email": "[email protected]", "amr": [ "pwd" ]}The two important fields here are sub and aud. The sub field tells /check-funds who the user is and the aud field tells Istio which services can consume this token. Compare this to the payload from the original token in the user_jwt response:
{ "iss": "https://k8sou.192-168-2-119.nip.io/auth/idp/service-idp", "aud": "users", "exp": 1631497059, "jti": "C8Qh8iY9FJdFzEO3pLRQzw", "iat": 1631496999, "nbf": 1631496879, "sub": "mmosley", "name": " Mosley", "groups": [ "cn=group2,ou=Groups,DC=domain,DC=com", "cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com" ], "preferred_username": "mmosley", "email": "[email protected]", "amr": [ "pwd" ]}The original sub is the same, but the aud is different. The original aud is for users, while the impersonated aud is for checkfunds. This is what differentiates the impersonated token from the original one. While our Istio deployment is configured to accept both audiences for the same service, that’s not a guarantee in most production clusters. When we call /check-funds, you’ll see that, in the output, we echo the user of our token, mmosley.
Now that we’ve seen the end product, let’s see how we get it. First, we get the original JWT that was used to call /write-check:
# let's first get the original JWT. We'll# use this as an input for impersonationaz_header = request.headers["Authorization"]user_jwt = az_header[7:]Once we have the original JWT, we need the Pod’s ServiceAccount token:
# next, get the pod's ServiceAccount token# so we can identify the pod to the IdP for# an impersonation tokenpod_jwt = Path('/var/run/secrets/kubernetes.io/serviceaccount/token').read_text()We now have everything we need to get an impersonation token. We’ll create a POST body and an Authorization header to authenticate us to OpenUnison to get our token:
# with the subject (user) jwt and the pod# jwt we can now request an impersonated# token for our user from openunisonimpersonation_request = { "grant_type":"urn:ietf:params:oauth:grant-type:token-exchange", "audience":"checkfunds", "subject_token":user_jwt, "subject_token_type":"urn:ietf:params:oauth:token-type:id_token", "client_id":"sts-impersonation"}impersonation_headers = { "Authorization": "Bearer %s" % pod_jwt}The first data structure we created is the body of an HTTP POST that will tell OpenUnison to generate an impersonation token for the clientfunds aud, using our existing user (user_jwt). OpenUnison will authenticate our service by verifying the JWT sent in the Authorization header as a Bearer token, using the TokenReview API.
OpenUnison will then apply its internal policy to verify that our service is able to generate a token for mmosley for the clientfunds audience, and then generate an access_token, id_token, and refresh_token. We’ll use the id_token to call /check-funds:
resp = requests.post("https://k8sou.apps.IPADDR.nip.io/auth/idp/service-idp/token",verify=False,data=impersonation_request,headers=impersonation_headers)response_payload = json.loads(resp.text)impersonated_id_token = response_payload["id_token"]# with the impersonated user's id_token, call another# service as that usercall_funds_headers = { "Authorization": "Bearer %s" % impersonated_id_token}resp = requests.get("http://write-checks.IPADDR.nip.io/check-funds",verify=False,headers=call_funds_headers)Since the final JWT makes no mention of the impersonation, how do we track a request back to our service? Hopefully, you’re piping your logs into a centralized logging system. If we look at the jti claim of our impersonation token, we can find the impersonation call in the OpenUnison logs:
INFO AccessLog - [AzSuccess] - service-idp - https://k8sou.apps.192-168-2-119.nip.io/auth/idp/service-idp/token - username=system:serviceaccount:write-checks:default,ou=oauth2,o=Tremolo - client 'sts-impersonation' impersonating 'mmosley', jti : 'C8Qh8iY9FJdFzEO3pLRQzw'So, we at least have a way of tying them together. We can see that our Pod’s service account was authorized to create the impersonation token for mmosley.
Having worked through an example of impersonation, let’s cover token delegation next.
Using delegation
Section titled “Using delegation”In the last example, we used impersonation to generate a new token on behalf of our user, but our downstream service had no knowledge that the impersonation happened. Delegation is different in that the token carries information about both the original user and the service, or actor, that requested it.
This means that the service being called knows both the originator of the call and the service that makes the call. We can see this in the pull_funds_text value from the response of our call_service.sh run. It contains both our original user, mmosley, and the ServiceAccount for the service that made the call, system:serviceaccount:write-checks:default. Just as with impersonation, let’s look at the generated token:
{ "iss": "https://k8sou.apps.192-168-2-119.nip.io/auth/idp/service-idp", "aud": "pullfunds", "exp": 1631497059, "jti": "xkaQhMgKgRvGBqAsOWDlXA", "iat": 1631496999, "nbf": 1631496879, "nonce": "272f1900-f9d9-4161-a31c-6c6dde80fcb9", "sub": "mmosley", "amr": [ "pwd" ], "name": " Mosley", "groups": [ "cn=group2,ou=Groups,DC=domain,DC=com", "cn=k8s-cluster-admins,ou=Groups,DC=domain,DC=com" ], "preferred_username": "mmosley", "email": "[email protected]", "act": { "sub": "system:serviceaccount:write-checks:default", "amr": [ "k8s-sa" ], . . . }}In addition to the claims that identify the user as mmosley, there’s an act claim that identifies the ServiceAccount that’s used by /write-checks. Our service can make additional authorization decisions based on this claim or simply log it, noting that the token it received was delegated to a different service. In order to generate this token, we start by getting the original subject’s JWT and the Pod’s ServiceAccount token.
Instead of calling OpenUnison for a delegated token, our client first has to get an actor token by using the client_credentials grant. This will get us the token that will eventually go into the act claim:
client_credentials_grant_request = { "grant_type": "client_credentials", "client_id" : "sts-delegation"}delegation_headers = { "Authorization": "Bearer %s" % pod_jwt}resp = requests.post("https://k8sou.IPADDR.nip.io/auth/idp/service-idp/token",verify=False,data=client_credentials_grant_request,headers=delegation_headers)response_payload = json.loads(resp.text)actor_token = response_payload["id_token"]We authenticate to OpenUnison using our Pod’s native identity. OpenUnison returns an access_token and an id_token, but we only need the id_token. With our actor token in hand, we can now get our delegation token:
delegation_request = { "grant_type":"urn:ietf:params:oauth:grant-type:token-exchange", "audience":"pullfunds", "subject_token":user_jwt, "subject_token_type":"urn:ietf:params:oauth:token-type:id_token", "client_id":"sts-delegation", "actor_token": actor_token, "actor_token_type": "urn:ietf:params:oauth:token-type:id_token"}resp = requests.post("https://k8sou.IPADDR.nip.io/auth/idp/service-idp/token",verify=False,data=delegation_request)response_payload = json.loads(resp.text)delegation_token = response_payload["id_token"]Similarly to impersonation, in this call, we not only send the original user’s token (user_jwt) but also the actor_token we just received from OpenUnison. We also don’t send an Authorization header. The actor_token authenticates us already. Finally, we’re able to use our returned token to call /pull-funds.
Now that we’ve looked at the most correct way to call services, using both impersonation and delegation, let’s take a look at some anti-patterns and why you shouldn’t use them.
Passing tokens between services
Section titled “Passing tokens between services”Whereas, in the previous section, we used an identity provider to generate either impersonation or delegation tokens, this method skips that and just passes the original token from service to service. This is a simple approach that’s easy to implement. It also creates a larger blast radius. If the token gets leaked (and given that it’s now being passed to multiple services, the likelihood of it leaking goes up quite a bit), you’ve now not only exposed one service; you’ve also exposed all the services that trust that token.
While using OAuth2 Token Exchange does require more work, it will limit your blast radius should a token be leaked. Next, we’ll look at how you can simply tell a downstream service who’s calling it.
Using simple impersonation
Section titled “Using simple impersonation”Where the previous examples of service-to-service calls rely on a third party to generate a token for a user, direct impersonation is where your service’s code uses a service account (in the generic sense, not the Kubernetes version) to call the second service and just tells the service who the user is as an input to the call. For instance, instead of calling OpenUnison to get a new token, /write-check could have just used the Pod’s ServiceAccount token to call /check-funds, with a parameter containing the user’s ID. Something like the following would work:
call_headers = { "Authorization": "Bearer %s" % pod_jwt}resp = requests.post("https://write-checks.IPADDR.nip.io/check-funds?user=mmosley",verify=False,data=impersonation_request,headers=call_headers)This is, again, very simple. You can tell Istio to authenticate a Kubernetes ServiceAccount. This takes two lines of code to do something that took 15 to 20 lines using a token service. Just like with passing tokens between services, this approach leaves you exposed in multiple ways. First, if anyone gets the ServiceAccount used by our service, they can impersonate anyone they want without checks. Using the token service ensures that a compromised service account doesn’t lead to it being used to impersonate anyone.
You might find this method very similar to the impersonation we used in Chapter 6, Integrating Authentication into Your Cluster. You’re correct. While this uses the same mechanism, a ServiceAccount and some parameters to specify who the user is, the type of impersonation Kubernetes uses for the API server is often referred to as a protocol transition. This is used when you are moving from one protocol (OpenID Connect) to another (a Kubernetes service account). As we discussed in Chapter 5, there are several controls you can put in place with Kubernetes impersonation, including using NetworkPolicies, RBAC, and the TokenRequest API. It’s also a much more isolated use case than a generic service.
We’ve walked through multiple ways for services to call and authenticate each other. While it may not be the simplest way to secure access between services, it will limit the impact of a leaked token. Now that we know how our services will talk to each other, the last topic we need to cover is the relationship between Istio and API gateways.
Do I need an API gateway?
Section titled “Do I need an API gateway?”If you’re using Istio, do you still need an API gateway? In the past, Istio was primarily concerned with routing traffic for services. It got traffic into the cluster and figured out where to route it to. API gateways have typically focused more on application-level functionality such as authentication, authorization, input validation, and logging.
For example, earlier in this chapter, we identified schema input validation as a process that needs to be repeated for each call and shouldn’t need to be done manually. This is important to protect against attacks that can leverage unexpected input, and it also makes for a better developer experience, providing feedback to developers sooner in the integration process. This is a common function for API gateways but is not available in Istio.
Another example of a function that is not built into Istio but is common for API gateways is logging authentication and authorization decisions and information. Throughout this chapter, we leveraged Istio’s built-in authentication and authorization to validate service access, but Istio makes no record of that decision, other than that a decision was made. It doesn’t record who accessed a particular URL, only where it was accessed from. Logging who accessed a service, from an identity standpoint, is left to each individual service. This is a common function for API gateways.
Finally, API gateways are able to handle more complex transformations. Gateways will typically provide functionality for mapping inputs and outputs, or even integrating with legacy systems.
These functions could all be integrated into Istio, either directly or via Envoy filters. We saw an example of this when we looked at using OPA to make more complex authorization decisions than what the AuthorizationPolicy object provides. However, over the last few releases, Istio has moved further into the realm of traditional API gateways, and API gateways have begun taking on more service mesh capabilities. I suspect there will be considerable overlap between these systems in the future, but at the time of writing, Istio isn’t yet capable of fulfilling all the functions of an API gateway.
We’ve had quite the journey building out the services for our Istio service mesh. You should now have the tools you need to begin building services in your own cluster.
Summary
Section titled “Summary”In this chapter, we learned how both monoliths and microservices run in Istio. We explored why and when to use each approach. We deployed a monolith, taking care to ensure our monolith’s session management worked. We then moved into deploying microservices, authenticating requests, authorizing requests, and finally, how services can securely communicate. To wrap things up, we discussed whether an API gateway is still necessary when using Istio.
Istio can be complex, but when used properly, it can provide considerable power. What we didn’t cover in this chapter is how to build containers and manage the deployment of our services. We’re going to tackle that next, in Chapter 18, Provisioning a Multitenant Platform.
Questions
Section titled “Questions”- True or false: Istio is an API Gateway.
- True 2. False
Answer: b – False. Istio is a service mesh, and while it has many of the functions of a gateway, it doesn’t have all of them (such as schema checking).
- Should I always build applications as microservices?
- Obviously – this is the right way. 2. Only if a microservices architecture aligns with your organization’s structure and needs. 3. No. Microservices are more trouble than they’re worth. 4. What’s a microservice?
Answer: b – Microservices are great when you have a team that is able to make use of the granularity they provide.
- What is a monolith?
- A large object that appears to be made from a single piece by an unknown maker 2. An application that is self-contained 3. A system that won’t run on Kubernetes 4. A product from a new start-up
Answer: b – A monolith is a self-contained application that can run quite well on Kubernetes.
- How should you authorize access to your services in Istio?
- You can write a rule that limits access in Istio by a claim in the token. 2. You can integrate OPA with Istio for more complex authorization decisions. 3. You can embed complex authorization decisions in your code. 4. All of the above.
Answer: d – These are all valid strategies from a technical standpoint. Each situation is different, so look at each one to determine which one is best for you!
- True or false: Calling services on behalf of a user without token exchange is a secure approach.
- True 2. False
Answer: b. False – Without using token exchange to get a new token for when the user uses the next service, you leave yourself open to various attacks because you can’t limit calls or track them.
- True or false: Istio supports sticky sessions.
- True 2. False
Answer: a. True – They are not a default, but they are supported.
Join our book’s Discord space
Section titled “Join our book’s Discord space”Join the book’s Discord workspace for a monthly Ask Me Anything session with the authors:
