Serverless Computing & Microservices

Chapter 9
Security, Privacy and Zero-Trust Architecture

Advance Diploma in Cloud Computing
Serverless Computing & Microservices   •   Advance Diploma

Security, Privacy and Zero-Trust Architecture

Introduction

Serverless computing and microservices change the security boundary of an application. In a traditional monolith, a small number of servers, networks and application processes are administered by one organisation. In a serverless and microservices system, security responsibilities are distributed among cloud providers, platform services, application teams, third-party libraries, identity providers and data processors. Functions may be created dynamically, communicate through events, access managed databases and execute with short lifetimes. These characteristics improve scalability and delivery speed, but they also create more identities, interfaces, dependencies and opportunities for misuse.

Security therefore cannot be treated as a perimeter firewall or as a final testing activity. It must be designed into identity, code, deployment pipelines, data handling, observability and governance. This chapter develops a practical security model based on identity and access management (IAM), least privilege, OAuth 2.0, OpenID Connect (OIDC), secrets management, encryption, tenant isolation, software supply-chain security, threat modelling and secure coding. It also explains how these controls fit within zero-trust architecture.

Learning Objectives

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

  • explain the security implications of serverless and microservices architectures;
  • apply authentication, authorisation, IAM and least-privilege principles;
  • distinguish OAuth 2.0 from OIDC and select suitable flows;
  • design appropriate secrets, encryption and key-management controls;
  • evaluate tenant-isolation strategies;
  • identify software supply-chain risks and propose mitigations;
  • perform a threat model for an event-driven service;
  • apply secure coding, privacy and governance practices; and
  • assess a system using zero-trust principles.

1. The Security Context of Distributed Cloud Applications

A serverless application normally consists of functions, API gateways, queues, event buses, object stores, databases, identity services and monitoring systems. A microservices application adds independently deployed services, service-to-service APIs and often multiple data stores. Every component and communication path can become a security-relevant boundary.

Important characteristics include:

  1. Ephemeral execution. A function instance may disappear after a request. Local files, process memory and in-process security state cannot be relied upon as durable controls.
  2. Fine-grained identities. A function, deployment pipeline, human operator, workload and external client may each require a distinct identity.
  3. Asynchronous trust. Events can be delayed, duplicated, reordered or replayed. Consumers must validate event authenticity and idempotently process messages.
  4. Managed infrastructure. The provider secures the underlying platform, but the customer remains responsible for configuration, code, identities, data and many dependencies.
  5. Expanded attack surface. Public endpoints, internal APIs, event subscriptions, package registries, CI/CD systems and administrative consoles all require protection.

The shared-responsibility model should be made explicit. A cloud provider may secure physical facilities, hardware and the managed runtime. The customer normally controls data classification, IAM policies, application code, API configuration, secrets, dependency selection and tenant authorisation. Responsibility varies by service and contract, so assumptions must be checked against provider documentation and compliance obligations.

2. Zero-Trust Architecture

Zero trust is a security approach in which no user, device, network location or workload is automatically trusted. Access is granted after evaluating identity, resource, action, context and policy. The central ideas are often summarised as “verify explicitly, use least privilege and assume breach.” Zero trust is not a product and does not mean that every request must be manually approved. It means that trust is continuously and deliberately established.

A useful conceptual authorisation decision is:

Decision = Policy(Subject, Resource, Action, Context)

Here, Subject is a human or workload identity, Resource is the protected object, Action is the requested operation, and Context may include device posture, time, network, risk and authentication strength. The expression is a policy model, not a numerical equation; it assumes that relevant attributes are trustworthy, current and available to the policy engine.

A zero-trust design for serverless systems commonly includes:

  • strong authentication for people and workloads;
  • short-lived, narrowly scoped credentials;
  • explicit service-to-service authorisation;
  • encryption in transit and at rest;
  • segmentation through accounts, projects, virtual networks and policies;
  • central logging of authentication and authorisation decisions;
  • continuous monitoring and rapid credential revocation; and
  • tested recovery from compromised components.

Network location is not sufficient evidence of trust. A service inside a private subnet may still be compromised, misconfigured or impersonated. Conversely, a legitimate user may access a service through a changing network location. Identity and policy should therefore carry more security significance than IP allow-lists alone.

3. Identity, Authentication and Authorisation

Authentication establishes who or what is making a request. Authorisation determines what that identity may do. Accounting records relevant activity. Confusing these concepts creates serious design errors: a valid login does not imply permission to read every customer record.

3.1 IAM design

IAM should separate:

  • human identities, managed through an organisation’s identity provider;
  • workload identities, assigned to functions, containers, pipelines and services;
  • privileged administrator identities, protected with strong authentication and separate accounts; and
  • external consumer identities, governed through federation and contractual controls.

Use groups, roles and policy-as-code rather than assigning numerous individual permissions. A permission should identify an action and resource, such as orders:GetOrder on a defined order repository, rather than broad administrative access.

3.2 Least privilege

Least privilege means granting only the permissions necessary for an approved task, for the shortest practical period. It applies to users, functions, deployment systems, database accounts and third-party integrations.

Effective practice includes:

  • separate read, write, administer and delete permissions;
  • resource-level restrictions rather than unrestricted service-level permissions;
  • conditions based on tags, environments or tenant identifiers;
  • short-lived role assumption instead of permanent access keys;
  • separate production and development accounts or projects;
  • periodic access review and removal of unused privileges; and
  • monitoring for privilege escalation and unusual access.

Least privilege must be operationally realistic. Excessively broad roles are dangerous, but policies so restrictive that teams bypass them are also unsafe. Start with a narrow policy, observe denied legitimate actions, and refine it through controlled review.

3.3 Service-to-service identity

A microservice should authenticate another service using a workload identity, mTLS certificate or signed token—not a shared password embedded in source code. The receiving service must validate issuer, audience, expiry, signature and required claims. Authentication does not remove the need for authorisation: an authenticated payment service may be allowed to create payment intents but not to read unrelated customer profiles.

4. OAuth 2.0 and OpenID Connect

OAuth 2.0 is an authorisation framework for delegated access. It enables a client to obtain an access token for a resource server without receiving the user’s password. OIDC is an identity layer built on OAuth 2.0; it adds authentication and an ID token containing claims about the authenticated user.

The roles are:

  • Resource owner: usually the user who controls data or permissions.
  • Client: the application requesting access.
  • Authorisation server: authenticates the resource owner and issues tokens.
  • Resource server: hosts the protected API or data.

For a browser or mobile application, the authorisation-code flow with Proof Key for Code Exchange (PKCE) is generally preferred. PKCE binds the authorisation request to the later token exchange and reduces the value of an intercepted authorisation code. A confidential server-side client must protect its client credentials; a public client cannot safely keep a client secret.

An access token should be audience-restricted, short-lived and limited by scopes. A resource server should validate at least the token signature or introspection result, issuer, audience, expiry and relevant scopes. It should not accept an ID token as an API access token merely because both are issued by the same identity provider. An ID token describes an authentication event for the client; an access token authorises access to a resource server.

Redirect URIs must be exact and registered. State parameters help prevent request-forgery attacks, and nonce values help bind OIDC authentication responses to a particular request. Tokens should not be placed in URLs, logs or browser history. Refresh tokens require stronger protection, rotation and revocation controls.

5. Secrets Management and Cryptography

Secrets include passwords, API keys, private keys, database credentials, signing keys and encryption keys. They should not appear in source code, container images, tickets, command histories or ordinary logs.

A managed secrets service should provide controlled storage, access policies, encryption, auditing and rotation. Applications should retrieve secrets at runtime using workload identity. Environment variables may be preferable to source-code constants, but they are not automatically secure: debugging tools, crash reports or process inspection may expose them. Where possible, use short-lived credentials and automatic rotation rather than long-lived static secrets.

Encryption controls should be selected according to the threat and data classification:

  • In transit: use TLS for external and internal communication; validate certificates and disable obsolete protocols.
  • At rest: use provider encryption for databases, queues, disks and object stores, with customer-managed keys when governance requires stronger control.
  • In use: reduce exposure through tokenisation, minimisation, confidential-computing features or strict process isolation where justified.

Encryption does not solve authorisation. A stolen application identity may still decrypt data legitimately. Key management must include ownership, purpose, rotation, backup, revocation, separation of duties and recovery testing. Key rotation does not necessarily re-encrypt historical data; the chosen design must specify how old ciphertext remains accessible during transition and how compromised keys are retired.

6. Tenant Isolation and Privacy

Multi-tenancy allows one application to serve multiple organisations or customers. A tenant is an independently governed customer, business unit or user group. The principal risk is cross-tenant data disclosure caused by missing filters, insecure object references, shared caches or incorrect event routing.

Isolation strategies include:

StrategyStrengthMain trade-off
Separate account, project or subscriptionStrong administrative and resource boundaryHigher cost and operational complexity
Separate database or schemaClearer data boundaryMigration and connection-management overhead
Shared tables with tenant keyEfficient and scalableEvery query and index requires correct tenant enforcement
Per-tenant encryption keysStronger cryptographic separationKey lifecycle and cost complexity

Tenant identity should be derived from a trusted token claim or server-side mapping, not from an arbitrary client-supplied field. Authorisation checks should occur at the service and data layers. A request for /tenants/A/orders/17 must be rejected if the authenticated principal is not authorised for tenant A, even if order 17 exists.

Privacy engineering begins with purpose limitation, data minimisation, retention limits and transparency. Teams should identify what personal data is collected, why it is needed, where it flows, who can access it and when it is deleted. Logs and traces can unintentionally contain names, tokens, addresses or message payloads; redaction and structured allow-list logging are preferable to indiscriminate capture.

Applicable obligations may include data-protection and sector-specific laws. Requirements vary by jurisdiction, but common governance duties include lawful processing, access control, breach response, processor management, retention governance and evidence of compliance. Legal advice is required for an organisation’s specific obligations.

7. Software Supply-Chain Security

A cloud workload depends on source repositories, package managers, base images, build tools, infrastructure modules, third-party APIs and deployment identities. A compromise in any of these can introduce malicious code or alter releases.

A defensible supply-chain programme includes:

  1. inventorying direct and transitive dependencies;
  2. pinning versions and verifying package integrity;
  3. scanning source, dependencies, images and infrastructure configuration;
  4. using signed commits, artefacts and provenance attestations where supported;
  5. isolating and hardening CI/CD runners;
  6. preventing pull requests from obtaining unrestricted production credentials;
  7. reviewing high-risk dependencies and removing unused packages; and
  8. maintaining a vulnerability response and patch process.

A Software Bill of Materials (SBOM) records component identities and versions. It improves impact analysis when a vulnerability is announced, but an SBOM does not prove that components are safe. Build provenance and reproducibility provide stronger evidence about how an artefact was produced. Security gates should be risk-based: a critical exploitable vulnerability in a public-facing dependency deserves urgent treatment, while a non-exploitable development-only issue may follow a different workflow.

8. Threat Modelling for Serverless and Microservices

Threat modelling is a structured way to identify and prioritise threats before or during design. A useful process is:

  1. define system purpose, assets and security objectives;
  2. draw data flows, trust boundaries, identities and external dependencies;
  3. identify threats using STRIDE or another recognised method;
  4. estimate likelihood and impact;
  5. select preventive, detective and corrective controls; and
  6. validate assumptions through testing and review.

STRIDE considers spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege. For event-driven systems, add replay, duplicate delivery, poisoned messages, unauthorised subscriptions and dead-letter-queue exposure.

Assets may include customer records, payment instructions, signing keys, deployment credentials, event integrity and service availability. Threat statements should be specific: “An attacker submits an order identifier belonging to another tenant and obtains its details” is more actionable than “the API may be insecure.”

Risk can be prioritised qualitatively or quantitatively. A simple qualitative matrix considers likelihood and impact; it should not be treated as an objective measurement. If a quantitative model is used, an illustrative expected-loss expression is:

Expected annual loss = Annual rate of occurrence × Single loss expectancy

The annual rate of occurrence is the estimated number of events per year, and single loss expectancy is the monetary loss per event. The model assumes reasonably meaningful estimates and does not capture uncertainty, correlated events or non-financial harm. It is useful for comparing controls, not for pretending that security risk is precisely known.

9. Secure Coding and Operational Controls

Secure coding begins with input validation, safe output handling and explicit trust boundaries. Validate type, length, range, encoding and business rules using allow-lists where practical. Use parameterised database queries, context-appropriate output encoding and framework-supported authentication. Do not construct shell commands, SQL statements or HTML by concatenating untrusted input.

Serverless-specific practices include:

  • make handlers idempotent because events may be retried;
  • validate event schema, source, signature and timestamp;
  • set timeouts, memory limits, concurrency limits and payload limits;
  • avoid placing sensitive data in exception messages;
  • use dead-letter queues with restricted access and retention controls;
  • prevent SSRF by restricting outbound destinations and metadata access;
  • configure API gateways for authentication, throttling and request validation; and
  • separate deployment, runtime and emergency administrative permissions.

Observability should support detection without violating privacy. Record actor, action, resource, result, timestamp, correlation identifier and relevant policy decision. Protect logs from alteration, restrict access and synchronise clocks. Alerts should focus on meaningful signals such as impossible travel, unusual privilege use, repeated authorisation failures, anomalous data volume and unexpected deployment activity.

Incident response should cover credential revocation, isolation, evidence preservation, customer communication, recovery and lessons learned. Backups must be protected from ransomware and tested for restoration, not merely reported as successful.

Applied Case: Illustrative Multi-Tenant Appointment Platform

Background

A fictional healthcare appointment platform uses an API gateway, serverless functions, an event bus, a managed database and separate services for identity, scheduling, notifications and billing. Clinics are tenants. A mobile application allows patients to view appointments and receive reminders.

Problem

An assessment finds that the appointment service trusts a clinicId supplied in the request body. Functions use a shared database credential, CI/CD stores a long-lived cloud access key, and notification events contain full patient details. A compromised notification component could therefore access more information than necessary.

Analysis

The tenant identifier is an authorisation attribute, not an input that the client should control. The shared credential violates least privilege and makes attribution difficult. The deployment key creates a high-impact supply-chain risk. Full patient data in events violates minimisation and increases the consequences of event-bus or log exposure.

Threat modelling identifies spoofing of clinic users, information disclosure through cross-tenant queries, elevation of privilege through the pipeline, replay of appointment events and unauthorised access to notification queues.

Approach and Solution

The platform adopts OIDC for user authentication and authorisation-code plus PKCE for the mobile client. API tokens contain tenant and role claims, but the service also maps the subject to current server-side entitlements. Each function receives a separate workload role. The scheduling function can read and update appointments only; the notification function can consume a minimised event containing an appointment reference, delivery address token and reminder time.

The database applies tenant-aware access controls and parameterised queries. The pipeline uses federated short-lived credentials, protected deployment branches, dependency scanning and signed artefacts. Secrets move to a managed vault with rotation. TLS is required for service communication, and sensitive database fields use managed encryption keys. Events include identifiers, schema versions, timestamps and replay protections; consumers are idempotent.

Outcome

The revised design reduces the impact of a compromised function, improves auditability and prevents the client from selecting an arbitrary clinic. It does not eliminate risk: an authorised account can still be abused, a provider outage can affect availability, and privacy obligations still require retention and incident procedures.

Learning Points

Security controls must work together. OIDC alone does not provide tenant isolation; encryption alone does not prevent an authorised but compromised service from reading data; and a secure runtime cannot compensate for an untrusted deployment pipeline. Identity, policy, data minimisation and operational monitoring form a system of controls.

Challenges and Limitations

Zero trust can increase latency, operational effort and policy complexity. Excessive token validation, certificate management and central policy dependencies may affect availability. Fine-grained permissions require accurate inventories and regular review. Multi-tenant isolation may reduce economies of scale. Encryption can complicate search, analytics and lawful data recovery. Automated scanners produce false positives and may miss business-logic flaws. Threat models become stale as services, vendors and regulations change.

Security decisions should therefore be proportionate to risk. Use layered controls, document residual risk, test failure modes and design graceful degradation. Security architecture is not a one-time diagram; it is a continuing governance and engineering process.

Contemporary Developments

Important developments include workload identity federation, policy-as-code, confidential computing, passkeys, signed build provenance, software supply-chain frameworks, runtime application self-protection and privacy-enhancing computation. Artificial intelligence can assist code review, anomaly detection and threat prioritisation, but generated code may contain insecure assumptions, leak sensitive prompts or reproduce vulnerable patterns. AI-assisted security decisions require human review, protected data handling, reproducible evidence and testing against adversarial inputs.

Best-Practice Checklist

  • Establish a documented shared-responsibility model.
  • Use strong human and workload identities with short-lived credentials.
  • Enforce least privilege and review access continuously.
  • Use OAuth 2.0 for delegated authorisation and OIDC for authentication.
  • Store secrets in managed systems; never commit them to source control.
  • Encrypt data in transit and at rest, with governed key management.
  • Enforce tenant boundaries in identity, service logic and data access.
  • Maintain an SBOM, scan dependencies and protect CI/CD identities.
  • Threat-model trust boundaries, events, retries and administrative paths.
  • Validate inputs, use parameterised queries and design idempotent handlers.
  • Minimise personal data in events, logs and traces.
  • Monitor decisions, test incident response and verify restoration from backups.

Chapter Summary

Serverless and microservices architectures distribute security responsibility across identities, APIs, events, managed services, code and supply chains. Zero-trust architecture replaces implicit trust with explicit, contextual and least-privileged decisions. IAM must distinguish authentication from authorisation and must provide separate human and workload identities. OAuth 2.0 supports delegated access, while OIDC adds user authentication; tokens must be validated for issuer, audience, expiry and scope.

Secrets require managed storage, rotation and controlled retrieval. Encryption protects data but cannot replace authorisation or key governance. Tenant isolation must be enforced through trusted identity attributes and data-layer controls. Supply-chain security requires dependency inventory, protected pipelines, scanning, provenance and rapid response. Threat modelling provides a systematic method for analysing trust boundaries and threats. Secure coding, privacy-by-design, observability and tested incident response complete the control system. The central professional lesson is that security is an integrated property of architecture, implementation and operations.

Key Terms

Authentication: Verification of the identity of a user or workload.

Authorisation: Determination of which actions an authenticated identity may perform.

IAM: Governance and technical control of identities, permissions and access.

Least privilege: Granting only necessary permissions for the necessary duration.

Zero trust: Security model that requires explicit verification rather than implicit trust.

OAuth 2.0: Framework for delegated authorisation to protected resources.

OpenID Connect: Authentication and identity layer built on OAuth 2.0.

Access token: Credential presented to a resource server to request authorised access.

Workload identity: Identity assigned to an executing service, function or pipeline.

PKCE: Mechanism that binds an authorisation-code request to its token exchange.

Secret: Sensitive credential or cryptographic material requiring controlled protection.

Encryption at rest: Protection of stored data using cryptographic transformation.

Tenant isolation: Prevention of unauthorised access between customers or organisational tenants.

SBOM: Inventory of software components and versions in an artefact.

Threat modelling: Structured identification and treatment of security threats.

STRIDE: Threat-modelling categories covering spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege.

Idempotence: Property whereby repeating an operation produces the same intended result as performing it once.

Data minimisation: Collecting and exposing only data needed for a legitimate purpose.

Supply-chain security: Protection of code, dependencies, tools, artefacts and delivery processes.

Review Questions

Short Answer Questions

  1. Distinguish authentication from authorisation.
  2. Why is network location insufficient as a trust signal in a zero-trust system?
  3. State two differences between OAuth 2.0 and OIDC.
  4. Why should event-driven functions be idempotent?
  5. Name three controls that reduce software supply-chain risk.

Long Answer Questions

  1. Explain how least privilege should be applied to users, functions and CI/CD pipelines.
  2. Describe a secure OAuth 2.0 and OIDC design for a mobile application and API.
  3. Compare separate databases, separate schemas and shared tenant-key tables for multi-tenancy.
  4. Explain how encryption, secrets management and key management address different risks.
  5. Describe a complete threat-modelling process for an event-driven microservices system.

Analytical / Application Questions

  1. A notification function can read the entire customer database although it only sends appointment reminders. Analyse the risks and redesign its identity, data flow and permissions.
  2. A service accepts a tenant identifier from the request body and uses it in a database query. Identify the attack, explain why it is possible and propose layered controls.
  3. A CI/CD pipeline uses a permanent production access key and installs unpinned dependencies. Develop a migration plan based on zero trust and supply-chain security principles.

Multiple Choice Questions with Answers

Question 1

Which statement best distinguishes OAuth 2.0 from OpenID Connect?

A. OAuth 2.0 provides delegated authorisation, while OIDC adds an identity layer.

B. OAuth 2.0 encrypts databases, while OIDC manages encryption keys.

C. OAuth 2.0 is only for administrators, while OIDC is only for functions.

D. OAuth 2.0 replaces TLS, while OIDC replaces firewalls.

Correct Answer: A. OAuth 2.0 provides delegated authorisation, while OIDC adds an identity layer.

Question 2

Which is the strongest example of least privilege?

A. Giving every function administrator access to simplify deployment

B. Giving a notification function permission to read only its required queue and write delivery status

C. Using one database password for all services

D. Allowing all developers permanent production access

Correct Answer: B. Giving a notification function permission to read only its required queue and write delivery status

Question 3

What should a resource server normally validate on an access token?

A. Only the user’s display name

B. Only the network address of the client

C. Issuer, audience, expiry, signature and relevant permissions

D. The database password used by the client

Correct Answer: C. Issuer, audience, expiry, signature and relevant permissions

Question 4

Which practice best protects secrets in a serverless application?

A. Embedding them in source code

B. Placing them in public object storage

C. Writing them to ordinary application logs

D. Retrieving them at runtime from a managed secrets service using workload identity

Correct Answer: D. Retrieving them at runtime from a managed secrets service using workload identity

Question 5

Why is a client-supplied tenant identifier unsafe by itself?

A. It may allow a caller to select another tenant’s data

B. It always prevents database indexing

C. It automatically disables encryption

D. It makes TLS certificates expire

Correct Answer: A. It may allow a caller to select another tenant’s data

Question 6

Which control most directly addresses untrusted software dependencies?

A. Increasing function memory

B. Maintaining an SBOM and scanning and pinning dependencies

C. Disabling audit logs

D. Using a longer HTTP timeout

Correct Answer: B. Maintaining an SBOM and scanning and pinning dependencies

Question 7

In threat modelling, what does the information-disclosure category address?

A. Unauthorised exposure of protected information

B. A service having too much memory

C. A valid user changing a password

D. A scheduled software upgrade

Correct Answer: A. Unauthorised exposure of protected information

Question 8

Why are idempotent handlers important for event-driven systems?

A. Events are guaranteed to arrive exactly once

B. Retries or duplicate delivery should not create unintended repeated effects

C. They eliminate the need for authentication

D. They prevent all denial-of-service attacks

Correct Answer: B. Retries or duplicate delivery should not create unintended repeated effects

Question 9

Which statement about encryption is correct?

A. Encryption removes the need for authorisation

B. Encryption guarantees that compromised identities cannot access data

C. Encryption protects data confidentiality but requires sound key management and access control

D. Encryption is useful only for data stored on physical disks

Correct Answer: C. Encryption protects data confidentiality but requires sound key management and access control

Question 10

Which principle is central to zero-trust architecture?

A. Trust all internal network traffic

B. Verify explicitly and grant contextual, least-privileged access

C. Allow permanent credentials for convenience

D. Use a firewall as the only security control

Correct Answer: B. Verify explicitly and grant contextual, least-privileged access

Serverless Computing & Microservices
Chapter 9 of 15