Cloud Security

Chapter 7
Cloud-Native Application, API, Container, and Kubernetes Security

Bachelors Program in IT
Cloud Security   •   Bachelor

Cloud-Native Application, API, Container, and Kubernetes Security

Introduction and Context

Cloud-native computing is an approach to building and operating software around elastic infrastructure, automated delivery, distributed services, and declarative management. Typical cloud-native systems combine microservices, APIs, containers, Kubernetes, managed databases, serverless functions, service meshes, third-party dependencies, and continuous integration and delivery (CI/CD). These technologies improve scalability and release speed, but they also distribute responsibility across many components and teams.

Traditional perimeter security is insufficient for such systems. A request may cross a public gateway, several services, a service mesh proxy, a message queue, and a database. Workloads may be created and destroyed within seconds, while software images and dependencies may originate from many sources. Security must therefore be designed into the application lifecycle and continuously enforced at identity, code, network, workload, data, and operational layers.

This chapter explains how to secure cloud-native applications, APIs, containers, registries, Kubernetes clusters, serverless workloads, service meshes, runtime environments, and software dependencies. It emphasizes security as a system property rather than a collection of isolated tools.

Learning Objectives

By the end of this chapter, students should be able to:

  1. Explain the security characteristics and risks of cloud-native architectures.
  2. Apply secure design principles to microservices and APIs.
  3. Describe container-image construction, signing, scanning, and runtime controls.
  4. Analyze Kubernetes identity, admission, network, and workload security.
  5. Compare security controls for containers, serverless functions, and service meshes.
  6. Evaluate software supply-chain risks and select suitable mitigations.
  7. Design a practical defense-in-depth approach for a cloud-native system.
  8. Assess ethical, governance, compliance, and operational implications.

1. Cloud-Native Security as a Layered System

A cloud-native application can be viewed as a set of interacting layers:

  • Application layer: business logic, authentication, authorization, input validation, and error handling.
  • API layer: endpoints, gateways, tokens, quotas, schemas, and API discovery.
  • Workload layer: containers, functions, processes, and runtime permissions.
  • Orchestration layer: Kubernetes control plane, nodes, namespaces, controllers, and admission policies.
  • Network layer: virtual networks, ingress, egress, DNS, service discovery, and service-to-service traffic.
  • Data layer: databases, object stores, caches, queues, secrets, and encryption keys.
  • Supply-chain layer: source code, dependencies, build systems, registries, deployment manifests, and signing.
  • Operational layer: logging, monitoring, detection, incident response, backup, and recovery.

A weakness at one layer can undermine another. For example, a secure API is still exposed if a compromised container can read another service’s credentials. Conversely, a hardened cluster cannot compensate for broken authorization in application code. Defense in depth requires controls that reduce both the likelihood and impact of compromise.

A useful security model is to ask four questions for every component:

  1. Who may access it? This concerns identity and authorization.
  2. What may it do? This concerns privileges and permitted actions.
  3. What may communicate with it? This concerns network policy and trust boundaries.
  4. How will misuse be detected and contained? This concerns telemetry and response.

These questions support zero-trust thinking: no workload, network location, or service is automatically trusted merely because it is inside a cloud account or cluster.

2. Microservices and API Security

2.1 Microservice-specific risks

Microservices decompose an application into independently deployable services. Decomposition can limit failure and allow teams to scale components independently, but it increases the number of interfaces, identities, configurations, and trust relationships. Important risks include:

  • inconsistent authentication or authorization between services;
  • excessive service privileges;
  • insecure service discovery and exposed administrative endpoints;
  • sensitive information in logs or error messages;
  • confused-deputy attacks, in which one service performs an action on behalf of an unauthorized caller;
  • inadequate protection of asynchronous messages;
  • cascading failures caused by retries, resource exhaustion, or dependency outages.

Security ownership must be explicit. The team that owns a service should define its data classification, callers, privileges, security tests, operational alerts, and decommissioning process.

2.2 Secure API design

A secure API begins with an explicit contract. OpenAPI or an equivalent specification should define operations, parameters, data types, error behavior, authentication requirements, and authorization expectations. The contract should be versioned and reviewed like source code.

Core controls include:

  • Strong authentication: Use an identity provider and standards such as OAuth 2.0 and OpenID Connect where appropriate. Do not treat an API key alone as proof of a human identity.
  • Authorization at the resource and action level: A valid token does not imply permission to access every resource. Enforce least privilege and check object ownership or tenant boundaries on the server.
  • Input validation: Validate type, length, format, range, encoding, and business constraints. Reject unexpected fields where practical.
  • Output control: Return only necessary attributes. Avoid stack traces, internal identifiers, secrets, and sensitive debugging data.
  • Replay and abuse protection: Use expiry, nonce or request identifiers for suitable operations, rate limits, quotas, and idempotency controls.
  • Transport protection: Use TLS for external and internal traffic. Certificate validation must not be disabled to resolve deployment problems.
  • Safe errors: Use stable error codes and correlation identifiers while recording diagnostic detail in controlled logs.
  • Lifecycle control: Inventory, version, test, document, and retire APIs. Undocumented or forgotten endpoints are a common source of exposure.

Rate limiting may be implemented as a token-bucket mechanism. If a bucket has capacity B tokens, refills at r tokens per second, and a request consumes c tokens, the long-run sustainable request rate is at most r ÷ c requests per second, subject to the bucket’s burst capacity. This relationship is not a universal security guarantee: it assumes accurate accounting and does not prevent low-rate attacks, credential abuse, or attacks distributed across many identities.

2.3 Service-to-service identity

Service identities should be distinct from user identities. A user token may carry delegated context, but a service should not automatically receive all permissions of the user or of the calling service. Short-lived credentials, workload identity, audience restrictions, and explicit scopes reduce replay and privilege-escalation risk.

For sensitive actions, the receiving service should independently authorize the requested operation. Trusting a header such as X-User-Role from an untrusted caller is not authorization; headers must be generated or authenticated by a trusted component.

2.4 API gateways and asynchronous interfaces

An API gateway can centralize TLS termination, authentication integration, rate limiting, schema validation, routing, and threat detection. It is not a substitute for authorization inside services. A gateway misconfiguration can also create a single point of exposure.

Messages in queues and event streams require equivalent controls: authenticated producers and consumers, topic-level authorization, schema validation, encryption, retention limits, duplicate handling, and protection against malicious payloads. Consumers should assume that messages may be delayed, duplicated, reordered, or malformed.

3. Container Security

A container packages an application and its user-space dependencies while sharing the host kernel. It is therefore not equivalent to a virtual machine. A kernel vulnerability, excessive capability, privileged configuration, or container escape can affect the host and other workloads.

3.1 Secure image construction

A secure image process includes:

  1. Use a trusted, minimal base image and record its provenance.
  2. Pin dependencies to reviewed versions or immutable digests where feasible.
  3. Remove compilers, package managers, shells, credentials, caches, and test data from production images.
  4. Run as a non-root user with an explicit user identifier.
  5. Use a read-only root filesystem when the application permits it.
  6. Drop Linux capabilities and add only narrowly justified capabilities.
  7. Define a health check that does not disclose sensitive information.
  8. Build reproducibly and generate a software bill of materials (SBOM).
  9. Scan the image and its operating-system and application dependencies.
  10. Sign the image and verify its signature before deployment.

A Dockerfile instruction that copies a secret into an image leaves the secret in an image layer even if a later instruction deletes the visible file. Secrets must be supplied through an appropriate secret-management mechanism at build or runtime, and build logs and caches must also be reviewed.

3.2 Vulnerability scanning and risk interpretation

A vulnerability scanner identifies known patterns; it does not prove that an image is safe. Teams should consider exploitability, reachability, privileges, exposure, compensating controls, and whether the vulnerable component is loaded or used. False positives and false negatives are possible.

A practical policy can block deployment when a critical vulnerability is exploitable in the deployed context, while allowing a documented exception for a lower-risk finding with a remediation deadline. Exceptions require an owner, justification, expiry date, and compensating controls.

3.3 Runtime controls

Runtime controls include seccomp profiles, mandatory access control such as SELinux or AppArmor, resource limits, process and filesystem restrictions, network policies, and runtime detection. Resource requests and limits reduce noisy-neighbor effects and some denial-of-service risks, although poorly chosen limits can also cause failures.

Containers should be isolated by default. Privileged mode, host networking, host PID or IPC namespaces, host filesystem mounts, and unrestricted device access require exceptional justification because they weaken isolation. A container that needs broad host access may be an architectural warning rather than a normal workload.

4. Image Registries and the Software Supply Chain

The software supply chain includes source repositories, developers’ environments, dependency repositories, CI runners, build tools, artifact registries, deployment systems, and configuration. Attackers may insert malicious code, steal signing keys, substitute packages, compromise a build runner, or exploit a vulnerable transitive dependency.

4.1 Provenance and integrity

Important controls are:

  • protected branches and peer review;
  • multifactor authentication and least-privileged repository access;
  • dependency pinning, lockfiles, and approved sources;
  • isolated, ephemeral build workers;
  • separation of build, approval, and deployment authority;
  • SBOM generation in a standard format;
  • artifact signing and signature verification;
  • registry access control, immutability, retention, and malware scanning;
  • provenance statements identifying source, builder, inputs, and build process;
  • rapid revocation and redeployment when compromise is detected.

A digest identifies content, while a tag such as latest is a mutable name. Production deployment should prefer a verified digest, with a controlled process for updating it. Signing establishes integrity and provenance claims; it does not establish that the code is free of vulnerabilities or that the publisher is ethically trustworthy.

4.2 Dependency governance

Direct dependencies are those explicitly selected by a project; transitive dependencies are introduced by those dependencies. Both require inventory and maintenance. Teams should monitor vulnerability advisories, maintain supported versions, test updates, remove unused packages, and limit dependency permissions.

Dependency confusion occurs when a build system retrieves a malicious public package instead of an intended private package with the same name. Private registries, namespace controls, repository pinning, and explicit source configuration reduce this risk. Developers should not blindly copy code or install packages based only on popularity.

5. Kubernetes Security

Kubernetes is a control system that schedules workloads and reconciles declared state. Its security depends on the API server, identity provider, admission chain, etcd, nodes, kubelets, controllers, network plugins, container runtime, and workload configuration.

5.1 Control-plane protection

The Kubernetes API server is a high-value target. Controls include strong administrator authentication, role-based access control (RBAC), audit logging, restricted network exposure, secure encryption of sensitive data in etcd, and regular upgrades. The etcd data store may contain secrets and configuration; it requires encryption, access control, backups, and restricted network access.

Kubernetes Secrets are encoded rather than automatically protected merely because they use a Secret object. Encryption at rest, tightly scoped RBAC, external secret managers, rotation, and prevention of secret exposure in logs are necessary.

5.2 RBAC and service accounts

RBAC grants permissions to subjects through roles and bindings. Effective access is determined by the union of permissions granted through applicable bindings; a permission not granted is not automatically available. Prefer namespace-scoped roles, narrowly defined verbs and resources, and separate service accounts for separate workloads.

Avoid assigning cluster-administrator permissions to applications. Disable automatic service-account token mounting when a workload does not need Kubernetes API access. Workload identity should provide cloud permissions without distributing long-lived cloud keys inside containers.

5.3 Admission and workload policy

Admission controls can reject insecure objects before they run. Useful policies require approved registries, signed images, non-root execution, dropped capabilities, resource limits, restricted host access, and valid labels. Policy-as-code tools can make these requirements reviewable and consistent, but policies must be tested to avoid blocking legitimate recovery or encouraging unsafe bypasses.

Namespaces provide organization and some isolation, not a complete security boundary. Pair them with RBAC, network policies, resource quotas, admission rules, and separate nodes or clusters where threat levels justify stronger separation.

5.4 Kubernetes networking

A default-allow network model means that a compromised workload can often attempt connections to many services. Default-deny ingress and egress policies, followed by explicit allowances, reduce lateral movement. Policies must account for DNS, health checks, control-plane communication, observability, and required external services.

Network policy enforcement depends on the selected CNI implementation. A policy object that the network plugin does not enforce creates false confidence. Teams should verify behavior with tests rather than assuming that a manifest is effective.

5.5 Node and kubelet security

Nodes require operating-system hardening, rapid patching, restricted administrative access, disk encryption where appropriate, runtime protection, and monitoring. Kubelet credentials and APIs must not be unnecessarily exposed. Workloads should not mount host paths or access the container runtime socket unless the operational design explicitly requires it and the risk is controlled.

6. Serverless and Service-Mesh Security

6.1 Serverless functions

Serverless platforms reduce infrastructure management but do not remove application security responsibilities. A function should have a separate execution role, minimal permissions, controlled event sources, input validation, dependency management, concurrency limits, and protected environment configuration. Cold starts and retries can produce duplicate processing, so sensitive operations should be idempotent.

Function logs may contain event payloads, tokens, or personal data. Logging must be purposeful, access-controlled, retained according to policy, and redacted. Dependencies should be packaged and scanned through the same supply-chain process used for containers.

6.2 Service meshes

A service mesh commonly uses sidecar or node-level proxies to provide service discovery, mutual TLS (mTLS), traffic policy, retries, telemetry, and identity. mTLS protects confidentiality and authenticates workloads at the transport layer, but it does not decide whether a user is authorized to delete a particular record. Application-level authorization remains necessary.

Meshes can introduce operational complexity, certificate-rotation failures, proxy vulnerabilities, policy conflicts, and performance overhead. Teams should define which controls belong in the mesh and which belong in the service, test failure modes, and prevent observability data from becoming a privacy risk.

7. Observability, Detection, and Response

Security telemetry should support questions such as: Which identity accessed the resource? From which workload and location? What changed? Was the request authorized? What data was returned? Audit logs should be time-synchronized, protected against tampering, access-controlled, and retained according to legal and operational requirements.

Useful signals include API authorization failures, unusual service-account use, image pulls from unapproved registries, new privileged workloads, anomalous egress, secret-access spikes, failed admission requests, and changes to RBAC. Detection must be connected to response playbooks.

A cloud-native incident response process should include workload isolation, credential revocation, image and artifact quarantine, preservation of relevant evidence, scope analysis, recovery from trusted artifacts, and post-incident improvement. Automatic deletion of compromised workloads may destroy evidence; response automation must balance containment and investigation.

8. Worked Application: Security Design for a Retail Platform

The following is an illustrative case. A retailer operates a web and mobile platform consisting of an API gateway, identity service, catalog service, order service, payment integration, event queue, Kubernetes workloads, and a serverless notification function.

Background and problem

The retailer discovers that a test service account can list secrets across a namespace, images are deployed using mutable tags, and the order API accepts an object identifier without verifying tenant ownership. Logs also contain payment-provider response details. The business requires rapid releases but must protect customer information and maintain reliable order processing.

Analysis

The risks are not independent. Secret-list permission could expose payment credentials. Mutable tags make it difficult to determine which code is running. The object-authorization flaw could allow one customer to view another customer’s order. Excessive logs increase privacy and breach impact. The event-driven design also requires protection against duplicate order events.

Approach and solution

The team first inventories data flows and trust boundaries. It then:

  1. Separates service accounts and replaces broad secret permissions with access to specific external secret references.
  2. Disables unnecessary service-account token mounting and uses workload identity for cloud access.
  3. Requires signed images from an approved registry and deploys by immutable digest.
  4. Adds admission policies requiring non-root execution, dropped capabilities, resource limits, and approved registries.
  5. Applies default-deny network policies and permits only documented service paths.
  6. Corrects the order API to authorize the authenticated customer or service against the requested order tenant and operation.
  7. Redacts payment data, defines retention periods, and protects audit logs.
  8. Adds idempotency keys and a durable event identifier so repeated payment or order events do not create duplicate effects.
  9. Adds tests for RBAC, image provenance, API authorization, network policy, and secret exposure to the CI pipeline.
  10. Creates an incident playbook for compromised images, leaked credentials, and suspicious order access.

Outcome

The architecture now has separate identities, verifiable artifacts, constrained network paths, and authorization at the business-resource boundary. Releases remain automated, but deployment is blocked when artifacts are unsigned or violate policy. Security monitoring focuses on high-value events rather than indiscriminate collection.

Learning points

The case demonstrates that cloud-native security is not achieved by installing a scanner or service mesh alone. Effective protection combines secure application logic, identity discipline, supply-chain integrity, policy enforcement, privacy-aware observability, and tested response procedures.

9. Governance, Ethics, and Professional Practice

Security controls process information about users, employees, and systems. Collection should be necessary, proportionate, documented, and protected. Excessive monitoring can create privacy harms and undermine trust. Access to production logs should be role-based, audited, and limited to legitimate purposes.

Organizations should map controls to applicable laws, contractual requirements, and frameworks such as the NIST Cybersecurity Framework, NIST guidance for zero trust and software supply-chain security, the OWASP Application Security Verification Standard, the OWASP API Security Top 10, and the Center for Internet Security Kubernetes Benchmark. Frameworks support consistency but do not replace threat modeling or professional judgment.

Responsible disclosure, accurate vulnerability reporting, segregation of duties, change approval, accessibility, and non-discrimination are professional responsibilities. Automated policy and AI-assisted code generation require human review: generated code may contain insecure authentication, dependency, or data-handling decisions, and confidential code or prompts may be exposed to third parties.

10. Contemporary Developments and Limitations

Emerging practices include software supply-chain levels and attestations, confidential computing, workload identity federation, eBPF-based observability, automated policy analysis, and platform engineering with secure internal developer platforms. These developments can improve assurance but introduce new dependencies and operational risks.

No control is perfect. Image scanning misses unknown vulnerabilities and runtime behavior. mTLS authenticates workloads but may not establish business authorization. RBAC can be technically correct yet operationally excessive. Network policies may be incomplete. Automated remediation can interrupt production or destroy evidence. Security therefore requires measurable assumptions, testing, review, and continuous adaptation.

A practical maturity path is:

  • establish asset and API inventories;
  • remove default credentials and excessive privileges;
  • implement protected CI/CD and signed artifacts;
  • enforce baseline workload and network policies;
  • add centralized, privacy-aware telemetry;
  • test recovery and incident response;
  • measure exceptions, patch age, unauthorized access attempts, and time to remediate;
  • improve controls using threat modeling and lessons from incidents.

Chapter Summary

Cloud-native security protects a distributed system across application, API, workload, orchestration, network, data, supply-chain, and operational layers. Microservices require explicit service identities, least privilege, resource-level authorization, secure contracts, and protection for synchronous and asynchronous interfaces. Containers should be built from trusted minimal images, run with restricted privileges, scanned, documented with SBOMs, and verified through signatures and provenance.

Kubernetes security depends on protected control-plane components, carefully scoped RBAC, secure secrets, admission policies, network restrictions, hardened nodes, and tested runtime controls. Serverless functions need least-privileged execution roles, safe event handling, dependency governance, and privacy-aware logging. Service meshes provide useful workload identity and mTLS but do not replace application authorization.

The software supply chain must be treated as a security boundary. Secure engineering combines preventive controls, detection, incident response, governance, ethics, and continuous improvement. The central principle is to make trust explicit, privileges narrow, artifacts verifiable, communication controlled, and failures observable and recoverable.

Key Terms

Cloud-native security: Security practices designed for distributed, elastic, automated cloud systems.

Microservice: A small, independently deployable service that performs a bounded business function.

API gateway: A managed entry point that routes, protects, and observes API traffic.

OAuth 2.0: A framework for delegated authorization.

OpenID Connect: An identity layer built on OAuth 2.0 for authentication.

Least privilege: Granting only the permissions required for an approved task.

Container image: A packaged filesystem and metadata used to create a container.

Container registry: A repository that stores and distributes images and related artifacts.

SBOM: A software bill of materials listing software components and dependencies.

Provenance: Evidence describing where and how an artifact was produced.

Image digest: A content-derived identifier for a specific artifact.

Kubernetes: A platform for orchestrating containerized workloads.

RBAC: Role-based access control that assigns permissions through roles and bindings.

Admission control: A mechanism that validates or mutates Kubernetes requests before persistence.

Network policy: A rule controlling permitted network communication between workloads.

Workload identity: An identity assigned to an application workload rather than a human or host.

Service mesh: An infrastructure layer that manages service-to-service communication.

mTLS: Mutual TLS in which both communicating parties authenticate certificates.

Idempotency: The property that repeating an operation produces the same intended effect.

Zero trust: A security approach that continuously verifies identity, authorization, and context rather than trusting network location.

Review Questions

Short Answer Questions

  1. Why is a container not equivalent to a virtual machine?
  2. What is the difference between authentication and authorization in an API?
  3. Why should production deployments prefer image digests over mutable tags?
  4. What security functions can Kubernetes admission controls perform?
  5. Why does mTLS not replace application-level authorization?

Long Answer Questions

  1. Explain a defense-in-depth security architecture for a Kubernetes-based microservice application.
  2. Describe the major security controls across a container image supply chain, from source code to deployment.
  3. Compare the security responsibilities of an API gateway, a microservice, and a service mesh.
  4. Explain how RBAC, service accounts, secrets, and network policies work together to limit Kubernetes risk.
  5. Discuss the ethical and governance issues associated with cloud-native logging and security monitoring.

Analytical / Application Questions

  1. A Kubernetes workload can read all secrets in its namespace and communicate with every other workload. Analyze the risks and propose a prioritized remediation plan.
  2. An organization discovers that a signed image contains a critical vulnerable library, but the image is used only by an internal service. Should deployment be blocked? Develop a risk-based decision using exploitability, exposure, compensating controls, and remediation time.
  3. Design security controls for an order-processing system that uses APIs, containers, a message queue, a service mesh, and a serverless notification function. Identify identities, trust boundaries, authorization checks, supply-chain controls, telemetry, and incident-response actions.

Multiple Choice Questions with Answers

Question 1

Which control most directly prevents a service from accessing another customer’s order by changing an object identifier?

A. Checking resource ownership and authorization in the service

B. Increasing the container CPU limit

C. Using a mutable image tag

D. Enabling service discovery

Correct Answer: A. Checking resource ownership and authorization in the service

Question 2

What does an image digest primarily provide?

A. A mutable human-readable deployment alias

B. A content-derived identifier for a specific artifact

C. Automatic proof that the artifact has no vulnerabilities

D. A replacement for authorization

Correct Answer: B. A content-derived identifier for a specific artifact

Question 3

Which Kubernetes practice best follows least privilege?

A. Granting every workload cluster-administrator access

B. Using one shared service account for all applications

C. Giving each workload only the narrowly required permissions

D. Allowing all pods to list every secret

Correct Answer: C. Giving each workload only the narrowly required permissions

Question 4

What is the principal purpose of a software bill of materials?

A. To list software components and dependencies in an artifact

B. To encrypt network traffic between services

C. To assign IP addresses to pods

D. To replace application testing

Correct Answer: A. To list software components and dependencies in an artifact

Question 5

Which statement about mutual TLS in a service mesh is correct?

A. It guarantees that a user may perform every requested business action

B. It authenticates communication endpoints but does not replace business authorization

C. It eliminates the need for identity management

D. It prevents all vulnerabilities in service code

Correct Answer: B. It authenticates communication endpoints but does not replace business authorization

Question 6

Why are mutable image tags risky in production?

A. They always make images larger

B. They prevent containers from using networks

C. They can point to different content over time, reducing deployment certainty

D. They automatically grant root access

Correct Answer: C. They can point to different content over time, reducing deployment certainty

Question 7

Which measure most directly reduces lateral movement between Kubernetes workloads?

A. Default-deny network policies with explicit permitted flows

B. Adding more labels to images

C. Increasing API response size

D. Disabling all application logs

Correct Answer: A. Default-deny network policies with explicit permitted flows

Question 8

A token-bucket API limiter refills at 20 tokens per second and each request consumes 2 tokens. Ignoring bursts, what sustainable request rate does this support?

A. 2 requests per second

B. 10 requests per second

C. 20 requests per second

D. 40 requests per second

Correct Answer: B. 10 requests per second

Question 9

Which practice is unsafe for storing a production secret?

A. Using an external secret manager with rotation

B. Scoping access to a specific workload identity

C. Copying the secret into a container image and deleting it in a later layer

D. Auditing secret access

Correct Answer: C. Copying the secret into a container image and deleting it in a later layer

Question 10

What is a key security requirement for event-driven order processing?

A. Assuming every message is delivered exactly once

B. Making sensitive operations idempotent and handling duplicate events

C. Allowing unauthenticated producers

D. Disabling schema validation

Correct Answer: B. Making sensitive operations idempotent and handling duplicate events

Cloud Security
Chapter 7 of 15