Workload, Application, Container and Serverless SecurityIntroduction and ContextCloud security has moved from protecting isolated servers to securing continuously changing workloads. A workload may be a virtual machine (VM), database, managed platform service, API, container, Kubernetes workload, or serverless function. Each model changes the location of control, the visibility available to defenders, and the responsibilities shared between the cloud provider and customer. The central security problem is not simply preventing intrusion. It is maintaining confidentiality, integrity, availability, traceability and recoverability while applications are provisioned, deployed, scaled and retired at high speed. A secure workload therefore requires controls across its entire lifecycle: design, build, release, deployment, operation, monitoring, response and disposal. Cloud security follows a shared-responsibility model. The provider normally secures physical facilities, hardware and foundational services, while the customer remains responsible for configuration, identities, data, code and, depending on the service model, operating systems and runtime components. Responsibility must be verified for each service rather than assumed from a generic cloud model. Learning ObjectivesBy the end of this chapter, learners should be able to: - distinguish security responsibilities for VMs, managed services, containers, Kubernetes and serverless functions;
- apply hardening principles to operating systems, networks, identities, APIs and application runtimes;
- evaluate container images and software dependencies for vulnerabilities and malicious content;
- explain Kubernetes security boundaries, admission controls and runtime protection;
- design security controls for serverless applications and event-driven architectures;
- construct a vulnerability-management process based on risk, exploitability and business impact;
- analyse a workload-security scenario and recommend proportionate controls.
1. Workload Security as a Lifecycle DisciplineA workload is secure when its design and operation reduce the likelihood and impact of unacceptable events. Security should be treated as a set of verifiable properties rather than a one-time configuration task. Important properties include: - Confidentiality: only authorised identities and processes can access information.
- Integrity: code, configurations, data and execution results cannot be changed improperly.
- Availability: services remain usable within required performance and recovery limits.
- Authenticity: users, services, images and messages can be trusted as claimed.
- Accountability: actions can be attributed through reliable logging and identity records.
- Resilience: the workload can withstand faults and recover from compromise.
A practical lifecycle is: - Threat model: identify assets, trust boundaries, actors, abuse cases and dependencies.
- Design securely: minimise privileges, isolate components and define security requirements.
- Build reproducibly: use controlled source repositories, dependency management and automated tests.
- Assure artefacts: scan, sign and approve images, packages and infrastructure definitions.
- Deploy safely: enforce policy, use least privilege and separate environments.
- Operate observably: collect useful logs, metrics, traces and security signals.
- Respond and improve: contain incidents, recover, investigate root causes and update controls.
- Retire securely: revoke credentials, delete temporary data and remove obsolete access paths.
The lifecycle is continuous because cloud workloads are frequently rebuilt rather than manually repaired. Immutable replacement is often safer than repeatedly modifying a running resource, provided that data, identity and configuration are handled correctly. 2. Virtual-Machine SecurityA VM combines a guest operating system, applications, virtual hardware, storage, network interfaces and cloud control-plane permissions. Although the hypervisor is operated by the provider, the customer usually manages the guest operating system and everything installed above it. 2.1 VM HardeningA hardened VM normally has the following characteristics: - a minimal operating-system image from a trusted source;
- unnecessary packages, services, ports and user accounts removed;
- secure baseline configuration applied and continuously checked;
- current security patches and supported software versions;
- host-based firewall rules restricting inbound and outbound traffic;
- administrative access through identity-aware management channels rather than exposed remote administration ports;
- disk and backup encryption using appropriately protected keys;
- endpoint detection or host monitoring where justified;
- synchronised time for reliable event correlation;
- centralised logs protected against alteration.
Hardening should be automated through image pipelines or configuration management. Manual changes create configuration drift: the gradual divergence between approved configuration and the actual running state. 2.2 Network and Identity ControlsA VM should not be considered safe merely because it is placed in a private subnet. Network segmentation limits reachability, but it does not replace authentication or authorisation. Security groups, network firewalls and routing rules should implement deny-by-default principles, while application-layer controls validate requests. Administrative identities should be individual, strongly authenticated and time-limited where possible. Long-lived access keys stored in scripts are particularly dangerous. Workloads should use managed identities or short-lived credentials, and permissions should be restricted to the precise resources and actions required. 2.3 Patch and Vulnerability ManagementPatching must consider exposure, exploitability, asset importance and operational constraints. A critical vulnerability on an internet-facing authentication service may require emergency action, whereas the same vulnerability on an isolated, deprecated system may be handled through compensating controls and a planned replacement. A useful prioritisation model is qualitative rather than mathematically absolute: Priority = exposure × exploitability × business impact × asset criticality This expression is a decision aid, not a universal risk equation. Each factor must be defined by the organisation, and the result should be interpreted alongside active exploitation intelligence, available mitigations and patch reliability. It should not be treated as a precise probability. 3. Managed Services and Application SecurityManaged services reduce operational burden but do not eliminate security responsibility. The customer still controls data classification, access policies, application configuration, network integration, logging choices and often encryption keys. Examples include managed databases, object storage, message queues, API gateways and managed identity services. Common failures include public exposure, excessive permissions, weak authentication, unencrypted data, missing audit logs and insecure default settings. A managed service review should ask: - What data is stored or processed?
- Which identities can access it, from where and by which actions?
- Is access private, public, or conditionally restricted?
- Are encryption, key rotation, backup and deletion requirements satisfied?
- Are administrative and data-plane events logged?
- Can configuration changes be detected and reversed?
- What provider dependencies and service-level limitations exist?
3.1 Application Security PrinciplesApplication security begins with secure requirements. Developers should identify trust boundaries, validate all external input, encode output appropriately, use parameterised queries, protect sessions, handle errors without revealing secrets, and enforce authorisation on every sensitive operation. Authentication answers “Who are you?” Authorisation answers “What may you do?” These must not be conflated. A valid token does not automatically grant access to every object. Object-level authorisation is essential in APIs to prevent an authenticated user from accessing another user’s records by changing an identifier. Secrets such as database passwords, signing keys and API tokens must not be embedded in source code, container images or logs. They should be held in a dedicated secret-management service, accessed through workload identity, rotated and audited. 4. API and Microservice SecurityMicroservices increase agility but create a larger communication surface. Each service may have its own identity, data store, deployment process and failure modes. Security must therefore address both individual services and interactions between them. 4.1 API ControlsEffective API security commonly includes: - strong authentication using standards appropriate to the architecture;
- fine-grained authorisation at endpoint and object level;
- schema validation and strict content-type handling;
- input-size limits and protection against injection;
- rate limits, quotas and concurrency controls;
- replay protection for sensitive operations;
- TLS for data in transit and certificate lifecycle management;
- safe error messages and consistent response handling;
- versioning and retirement of obsolete interfaces;
- centralised audit records containing actor, action, resource, result and correlation identifier.
Rate limiting is not a complete defence against denial of service, but it reduces accidental overload and some forms of abuse. Limits should be based on identity, client, endpoint and business operation where appropriate. 4.2 Service-to-Service TrustA microservice should authenticate other services rather than trusting network location. Mutual TLS, signed tokens or platform workload identities can provide service identity. Authorisation policies should specify which service may perform which action, on which resource, and under what conditions. Distributed tracing and correlation identifiers assist incident investigation, but logs must avoid passwords, tokens, sensitive personal information and unnecessary payload data. Observability systems themselves require access control and retention policies. 5. Container SecurityContainers package application code and dependencies into portable artefacts. Unlike VMs, containers generally share the host kernel, so a container boundary is not equivalent to a separate physical machine. Containers improve consistency and deployment speed, but insecure images or excessive runtime privileges can create significant risk. 5.1 Image AssuranceA secure image pipeline should: - obtain base images from approved registries;
- pin versions or immutable digests where practical;
- remove compilers, shells, package managers and debugging tools not needed at runtime;
- scan operating-system packages and application dependencies;
- check licences and software provenance;
- generate a software bill of materials (SBOM);
- sign approved images and verify signatures before deployment;
- retain build and provenance records;
- rebuild regularly to incorporate patched base layers.
Scanning is imperfect. A scanner may report a vulnerability that is not reachable in the application, miss a newly disclosed issue, or fail to understand runtime configuration. Therefore, scan results require expert triage and should be combined with exploitability, exposure and business impact. 5.2 Runtime ControlsContainers should run as non-root users, use read-only filesystems where possible, drop unnecessary Linux capabilities, restrict system calls, avoid privileged mode and limit CPU, memory and process counts. Network policies should control which containers may communicate. Sensitive values should be injected through secure mechanisms rather than environment variables when those variables may be exposed through diagnostics. A container should have a clear lifecycle. It must be replaced when its image changes, rather than silently modified in production. Runtime detection should identify unexpected processes, file changes, privilege escalation, unusual network connections and anomalous resource use. 6. Kubernetes SecurityKubernetes introduces a control plane, worker nodes, namespaces, service accounts, admission mechanisms, controllers, workloads and an API server. Its flexibility means that a single misconfiguration can affect many applications. 6.1 Control-Plane and Cluster BoundariesThe Kubernetes API server is a high-value target. Access should require strong authentication and least-privilege authorisation through role-based access control (RBAC). Administrative credentials should be protected, audited and preferably short-lived. The cluster should use encryption for sensitive data stored in its configuration datastore, with keys managed according to organisational policy. Namespaces support organisation and policy application, but they are not automatically complete security boundaries. Network policies, pod security controls, identity separation and node isolation may also be required. Workloads that require different trust levels should not casually share nodes or service accounts. 6.2 Workload and Admission SecurityA secure pod specification generally: - runs as a non-root user;
- prevents privilege escalation;
- uses a read-only root filesystem when feasible;
- drops unused capabilities;
- defines resource requests and limits;
- avoids host networking, host PID namespaces and host path mounts unless justified;
- uses approved images by digest or trusted signature;
- receives only the service-account permissions it needs.
Admission control can reject insecure manifests before they reach a cluster. Policies may require signed images, approved registries, resource limits, restricted security contexts and authorised namespaces. Policy enforcement should be tested carefully so that availability is not damaged by an overly rigid rule. 6.3 Kubernetes Secrets and Supply ChainA Kubernetes Secret object is not automatically equivalent to a fully protected enterprise secret store. Encryption at rest, access control, rotation, external secret integration and avoidance of accidental logging are necessary. Cluster administrators should assume that excessive API permissions can expose secrets. The software supply chain includes source code, build runners, dependencies, registries, manifests and deployment controllers. Provenance, reproducible builds, signed artefacts and separation of build and release privileges reduce the chance that a compromised pipeline inserts malicious code. 7. Serverless SecurityServerless functions execute in provider-managed environments and are commonly triggered by HTTP requests, queues, schedules, object events or database changes. The provider manages much of the operating system and runtime, but the customer remains responsible for function code, dependencies, permissions, event validation, data protection and configuration. 7.1 Distinctive RisksServerless applications face several characteristic risks: - over-privileged execution roles;
- injection through untrusted event data;
- insecure function-to-function trust;
- exposed function URLs or API endpoints;
- vulnerable third-party packages;
- secrets in environment configuration or source code;
- event replay and duplicate processing;
- excessive concurrency and cost-based denial of service;
- sensitive data appearing in logs;
- vulnerable dependencies hidden inside deployment packages or layers.
Functions should validate event structure, authenticate event producers, authorise each operation, and implement idempotency where duplicate delivery is possible. An idempotent operation produces the same intended business result when the same event is processed more than once. This is an application property, not a guarantee that the platform will deliver an event only once. 7.2 Serverless Least PrivilegeEach function should have a separate execution role with only the permissions required for its purpose. A function that reads one storage prefix should not receive unrestricted access to the entire storage account. Resource-based policies, network egress restrictions and environment-specific configuration further reduce blast radius. Cold starts, ephemeral execution and autoscaling complicate traditional host monitoring. Security telemetry should therefore focus on invocation identity, event source, function version, permission changes, dependency state, outbound destinations and anomalous invocation patterns. 8. Vulnerability Management and Runtime DefenceVulnerability management is a repeating process rather than a scanner purchase. It includes asset discovery, identification, validation, prioritisation, remediation, verification and reporting. 8.1 Asset and Dependency VisibilityAn organisation cannot protect what it cannot identify. Inventories should include VMs, images, packages, functions, APIs, clusters, managed services, dependencies, owners and data classifications. The inventory should record version, environment, exposure, support status and deployment location. Software composition analysis identifies known vulnerable dependencies. Static analysis examines source or compiled code for weaknesses. Dynamic testing examines running applications. Configuration assessment checks deployed settings. Penetration testing provides adversarial validation within an approved scope. These methods complement rather than replace one another. 8.2 Risk-Based RemediationA vulnerability’s severity score is not the same as organisational risk. Risk assessment should consider: - whether the vulnerable component is present and reachable;
- whether exploitation is known or technically practical;
- privileges required and likely impact;
- internet exposure and compensating controls;
- sensitivity and criticality of affected assets;
- availability of patches, mitigations or replacement components;
- confidence in detection and recovery capabilities.
Remediation outcomes include patching, upgrading, rebuilding an image, removing a dependency, changing configuration, isolating the workload, adding detection, accepting the risk formally, or retiring the asset. Risk acceptance should have an accountable owner, expiry or review date and documented justification. 8.3 Detection and ResponseRuntime protection should detect both known indicators and behavioural anomalies. Useful signals include unexpected child processes, privilege changes, unusual API calls, access to sensitive paths, anomalous outbound traffic, image drift, new administrative accounts and sudden changes in invocation volume. An incident response plan should define containment actions before an incident occurs. Examples include disabling a compromised identity, revoking tokens, quarantining a workload, blocking an image digest, rotating secrets, preserving evidence and deploying a known-good version. Response actions must account for volatile cloud resources and shared responsibility with the provider. 9. Governance, Ethics and ComplianceWorkload security involves more than technical controls. Security teams must respect privacy, employment law, contractual obligations and sector regulation. Monitoring should be proportionate, transparent and limited to legitimate purposes. Logs may contain personal or confidential data, so collection, access, retention and deletion require governance. Organisations should define ownership for applications, images, clusters, APIs and serverless functions. Useful governance artefacts include secure coding standards, baseline configurations, exception registers, incident playbooks, data classifications and service-level patching targets. Automation must remain accountable. An automated policy that blocks deployments can improve safety, but a poorly designed policy can create unsafe workarounds or prevent urgent fixes. Policies should be version-controlled, tested, monitored and subject to human review when consequences are significant. 10. Integrated Applied CaseBackgroundThe following is an illustrative case. A retail organisation operates an online ordering platform. Its architecture includes a public API gateway, containerised microservices on Kubernetes, a managed relational database, object storage and serverless functions that process order events. ProblemA security review identifies four weaknesses: a container image contains an outdated library; several services share a broad Kubernetes service account; an object-storage bucket is reachable from the public internet; and an event-processing function logs complete customer records. The organisation also has no reliable inventory of image versions or function dependencies. AnalysisThe weaknesses are interconnected. The vulnerable image increases the probability of compromise. Shared service-account permissions increase blast radius if one service is compromised. Public storage exposure creates a direct confidentiality risk. Excessive logs create privacy and retention risk, while poor inventory prevents reliable remediation and verification. Approach and SolutionThe organisation first establishes ownership and inventories images, functions, data stores and identities. It rebuilds the affected image using a supported base, scans it, produces an SBOM, signs the approved digest and configures admission policy to reject unsigned or unapproved images. Each microservice receives a distinct service account and narrowly scoped permissions. Kubernetes policies require non-root execution, prohibit privileged containers and impose resource limits. Network policies restrict service-to-service communication to documented paths. The storage bucket is made private, access is granted through workload identity, and monitoring is added for policy changes and unusual downloads. The event function is changed to log a correlation identifier and event outcome rather than customer records. Its execution role is limited to the required queue and database actions, and dependency scanning is integrated into the build pipeline. Finally, the organisation introduces a vulnerability-management service level based on exposure and business criticality, tests restoration and rotates credentials that may have been exposed during earlier deployments. OutcomeThe changes reduce attack surface, limit lateral movement, improve evidence quality and make future remediation repeatable. The organisation does not claim that scanning proves the system is secure. Instead, it combines preventive controls, runtime detection, ownership, testing and incident readiness. Learning Points- Security weaknesses often combine across layers; fixing only the vulnerable package would not address excessive permissions or data leakage.
- Image signatures and SBOMs improve assurance but require trustworthy build and release processes.
- Kubernetes namespaces and service accounts must be designed as explicit security boundaries.
- Serverless logs and event data require the same privacy discipline as conventional application logs.
- Inventory, ownership and verification are foundations of sustainable vulnerability management.
11. Challenges and Contemporary DevelopmentsCloud-native security faces persistent challenges. Rapid deployment can outpace review; ephemeral resources can disappear before evidence is collected; managed services can obscure implementation details; and multi-cloud environments produce inconsistent identity and policy models. Software supply-chain attacks have increased the importance of provenance, signed artefacts, dependency control and isolated build systems. Confidential-computing technologies seek to protect data while it is being processed, although their value depends on threat model, workload support and key-management design. Runtime security increasingly uses behavioural analytics and eBPF-based telemetry, but such tools require careful performance, privacy and false-positive evaluation. Artificial intelligence can assist with code review, alert triage, dependency analysis and policy generation. It can also introduce insecure generated code, expose confidential prompts or create overconfident recommendations. AI-assisted security decisions should therefore include human review, data-protection controls, testing against adversarial inputs and clear accountability. Best-Practice Checklist- Maintain an authoritative inventory of workloads, owners, data and dependencies.
- Use least privilege for users, services, functions and deployment pipelines.
- Build from trusted, minimal and supported images.
- Scan dependencies and images, but validate findings in context.
- Generate SBOMs and verify artefact provenance and signatures.
- Enforce secure runtime settings through policy as code.
- Segment workloads and authenticate service-to-service communication.
- Keep secrets out of code, images and ordinary logs.
- Patch or rebuild according to exposure, exploitability and business impact.
- Monitor control-plane changes, runtime behaviour and unusual data access.
- Test incident response, rollback, backup restoration and credential rotation.
- Review exceptions, managed-service responsibilities and compliance obligations.
Chapter SummaryWorkload security applies layered controls to VMs, managed services, APIs, microservices, containers, Kubernetes and serverless functions. Secure operation begins with threat modelling and continues through hardened images, least-privilege identities, network segmentation, secure coding, dependency assurance, signed artefacts, admission policies, runtime monitoring, patching and incident response. VMs require operating-system hardening and controlled administration. Managed services require careful configuration and verification of the customer’s remaining responsibilities. APIs and microservices require authentication, authorisation, validation, rate control and service identity. Containers require secure images and restricted runtime privileges. Kubernetes requires protection of the API server, RBAC, admission controls, pod security and supply-chain assurance. Serverless systems require secure event handling, narrowly scoped execution roles, dependency management, idempotency and privacy-aware logging. No single scanner, platform setting or certification proves security. Effective cloud security combines visibility, preventive controls, detection, recovery, governance and continual risk-based improvement. Key TermsWorkload: A cloud-executed application, service, function, VM or related processing unit. Shared responsibility: Allocation of security duties between cloud provider and customer. Configuration drift: Divergence between approved configuration and deployed state. Least privilege: Granting only the permissions required for an approved task. Managed service: A provider-operated service in which the customer configures and uses capabilities without managing all underlying infrastructure. API: An interface through which software components request data or actions. Microservice: A relatively small, independently deployable service performing a focused function. Container image: A packaged filesystem and metadata used to create a container. SBOM: A software bill of materials listing components and dependencies in an artefact. Image signing: Cryptographic attestation that links an artefact to an issuer or build process. Runtime security: Protection and monitoring applied while software is executing. Kubernetes: A platform for orchestrating containerised workloads. RBAC: Role-based access control assigning permissions through roles. Admission control: Policy enforcement that evaluates resources before deployment. Service account: A non-human identity used by a workload or automated process. Serverless function: Provider-managed code execution commonly triggered by events. Idempotency: The property that repeated processing produces the same intended business result. Vulnerability management: Identification, prioritisation, remediation and verification of weaknesses. Configuration drift: Difference between intended and actual security configuration. Workload identity: A platform-managed identity assigned to an application or service. Review QuestionsShort Answer Questions- What responsibilities commonly remain with a customer when using a managed database service?
- Why is a container boundary not identical to a VM boundary?
- What is the purpose of an SBOM?
- Why should serverless functions use separate execution roles?
- What is configuration drift, and how can automation reduce it?
Long Answer Questions- Explain a secure lifecycle for a cloud workload from threat modelling through retirement.
- Compare the principal security controls for VMs, containers and serverless functions.
- Explain how Kubernetes RBAC, admission control and network policy work together.
- Discuss why vulnerability severity alone is insufficient for remediation prioritisation.
- Describe a secure software supply chain for containerised microservices.
Analytical / Application Questions- A public API service runs in a container with root privileges and uses a service account that can read all production storage. Analyse the risks and propose a staged remediation plan.
- A serverless order processor may receive duplicate queue events and currently writes full customer records to logs. Explain the security and reliability issues and design suitable controls.
- A critical library vulnerability is found in an image used by an internal, isolated service and an internet-facing payment service. Explain how remediation priority should differ and identify evidence needed for the decision.
Multiple Choice Questions with AnswersQuestion 1Which control most directly limits the damage caused if a microservice is compromised? A. Giving every service administrator permissions B. Using a separate, least-privileged identity for each service C. Disabling all application logs D. Placing every service in the same network segment Correct Answer: B. Using a separate, least-privileged identity for each service Question 2What is the primary purpose of an SBOM? A. To encrypt container network traffic B. To list software components and dependencies in an artefact C. To replace runtime monitoring D. To assign Kubernetes IP addresses Correct Answer: B. To list software components and dependencies in an artefact Question 3Which Kubernetes practice is most appropriate for a restricted workload? A. Running the container as root with privilege escalation enabled B. Mounting the host filesystem by default C. Using a non-root user and dropping unnecessary capabilities D. Giving the pod cluster-admin permissions Correct Answer: C. Using a non-root user and dropping unnecessary capabilities Question 4Why should a serverless function validate incoming events? A. Events are always trusted because they originate in the cloud B. Validation prevents all infrastructure failures C. Event data may be manipulated, malformed or unexpectedly structured D. Validation eliminates the need for authorisation Correct Answer: C. Event data may be manipulated, malformed or unexpectedly structured Question 5Which statement best describes image signing? A. It proves that the image contains no vulnerabilities B. It provides an attestation linking an image to an issuer or build process C. It automatically removes outdated packages D. It prevents all runtime compromise Correct Answer: B. It provides an attestation linking an image to an issuer or build process Question 6Which control is most suitable for preventing unauthorised container images from entering a Kubernetes cluster? A. Admission policy that verifies approved registries or signatures B. Increasing pod CPU limits C. Disabling application health checks D. Allowing unrestricted image pulls Correct Answer: A. Admission policy that verifies approved registries or signatures Question 7An idempotent event handler is designed so that: A. Every duplicate event creates a new business transaction B. Repeated processing produces the same intended business result C. Events can never be delayed D. Authentication is unnecessary for event producers Correct Answer: B. Repeated processing produces the same intended business result Question 8Which factor should be included when prioritising a vulnerability? A. Only the length of the vulnerability description B. Asset exposure, exploitability and business impact C. The number of developers on the team D. The visual appearance of the dashboard Correct Answer: B. Asset exposure, exploitability and business impact Question 9What is a major limitation of relying only on a private subnet for VM security? A. Private subnets make encryption impossible B. Network location does not replace authentication and authorisation C. Private subnets prevent patching D. Private subnets disable all logging Correct Answer: B. Network location does not replace authentication and authorisation Question 10Which logging practice is most appropriate for a function processing customer data? A. Log complete customer records for every invocation B. Log passwords to support troubleshooting C. Log correlation identifiers and outcomes while minimising sensitive data D. Disable all logs permanently Correct Answer: C. Log correlation identifiers and outcomes while minimising sensitive data
|