Full Stack Application Architecture and Design Patterns

Chapter 11
Security, Privacy, Ethics and Compliance by Design

Post Graduate Diploma in Full Stack Development
Full Stack Application Architecture and Design Patterns   •   Post Graduate

11. Security, Privacy, Ethics and Compliance by Design

Introduction and Context

Security in a full stack application is not a feature added after implementation. It is an architectural property that emerges from decisions about identity, data, interfaces, infrastructure, dependencies, user experience, and organizational governance. A system may have strong encryption and still be insecure if authorization is poorly designed. Similarly, an application may comply with a technical security standard while collecting excessive personal data or using manipulative consent practices.

Security, privacy, ethics, and compliance therefore need to be considered together. Security protects systems and information from unauthorized actions. Privacy governs the legitimate collection, use, sharing, retention, and deletion of information about identifiable individuals. Ethics asks whether a system is fair, responsible, explainable, and respectful of human autonomy. Compliance translates legal, regulatory, contractual, and professional obligations into demonstrable controls.

The phrase by design indicates that these concerns are incorporated during requirements analysis, domain modeling, interface design, coding, testing, deployment, and operations. The objective is not merely to prevent attacks, but to create systems that remain trustworthy under ordinary use, misuse, operational failure, and deliberate attack.

Learning Objectives

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

1. Explain the relationship between security, privacy, ethics, governance, and compliance.

2. Conduct a practical threat-modeling exercise using assets, actors, threats, vulnerabilities, and controls.

3. Apply zero-trust principles and defense in depth across a full stack architecture.

4. Design secure authentication, authorization, OAuth/OIDC flows, and session management.

5. Select appropriate approaches to secrets management, encryption, auditability, and software supply-chain security.

6. Apply privacy-by-design, accessibility, ethical design, and data-governance principles.

7. Evaluate risks, trade-offs, limitations, and compliance responsibilities in professional projects.

Security as an Architectural Responsibility

A useful starting point is the CIA triad: confidentiality, integrity, and availability. Confidentiality limits information access to authorized parties. Integrity protects information and system behavior from unauthorized alteration. Availability ensures that legitimate users can obtain services when required. Modern architectures extend this view with authenticity, accountability, privacy, resilience, and safety.

A security requirement should be expressed as a verifiable property. “The application must be secure” is too vague. “Only an account owner or an approved support role may view an invoice, and every access must be recorded” is testable and can be mapped to design controls. Security requirements should be linked to business impact, regulatory obligations, and threat scenarios.

Defense in depth places multiple, partially independent controls around important assets. A customer database might be protected by network segmentation, private subnets, strong service identity, parameterized queries, database permissions, encryption, monitoring, backups, and tested recovery procedures. No single control is assumed to be perfect. The design goal is to prevent compromise where possible, detect it quickly, limit its impact, and recover reliably.

Security principles commonly used in architecture include least privilege, secure defaults, fail-safe behavior, separation of duties, complete mediation, economy of mechanism, and minimizing the attack surface. Least privilege means that a user, service, or process receives only the permissions required for its task. Complete mediation means that authorization is checked whenever access occurs rather than only at login. Secure defaults prevent accidental exposure when configuration is incomplete.

Threat Modeling: From Assets to Design Decisions

Threat modeling is a structured method for identifying what can go wrong and deciding how risk should be reduced. It is most valuable early in the development lifecycle, when architectural changes are less expensive. It should also be revisited when features, dependencies, interfaces, or deployment environments change.

A practical threat-modeling process begins by identifying assets. Assets include personal data, credentials, payment information, source code, business rules, availability, audit records, and the reputation of the organization. The team then identifies actors and trust boundaries. Actors may include customers, administrators, third-party providers, internal services, automated agents, and attackers. Trust boundaries mark transitions where data or commands move between different authority domains, such as a browser-to-API boundary or an application-to-payment-provider boundary.

The next step is to draw a data-flow diagram showing processes, data stores, external entities, and flows. Each flow is examined for spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege. These categories are often summarized by the STRIDE model. The model does not replace professional judgment; it provides a systematic vocabulary for discussion.

Risks can be prioritized through likelihood and impact. A simple qualitative matrix may classify a risk as low, moderate, high, or critical. More advanced programs use quantitative estimates, attack-path analysis, or business-impact modeling. Risk treatment may involve avoiding a feature, reducing likelihood, limiting impact, transferring risk through contracts or insurance, or accepting the risk with documented approval.

Threat modeling should produce concrete outputs: security requirements, assumptions, trust-boundary decisions, prioritized threats, mitigation owners, residual risks, and verification activities. A threat that has no owner or test is not adequately managed.

Identity, Authentication, and Authorization

Identity answers “who or what is requesting access?” Authentication verifies that claim, while authorization determines what the authenticated subject may do. These are distinct responsibilities. A valid login does not imply permission to read every record or perform administrative actions.

Authentication may use knowledge factors, possession factors, inherence factors, or combinations of them. Passwords should be stored using slow, memory-hard password-hashing algorithms with unique salts; they should never be stored reversibly. Password policies should avoid unnecessary complexity rules that encourage unsafe behavior, while supporting breached-password screening, rate limiting, secure recovery, and multifactor authentication for sensitive actions.

Session management requires unpredictable session identifiers, secure transport, appropriate expiration, rotation after authentication or privilege changes, and protection against cross-site request forgery where cookie-based sessions are used. Cookies commonly require Secure, HttpOnly, and suitable SameSite attributes. Tokens should have a narrowly defined audience, issuer, lifetime, and scope. A token should not contain sensitive information merely because it is encoded rather than encrypted.

Authorization models should reflect the domain. Role-based access control assigns permissions through roles; attribute-based access control evaluates properties such as department, ownership, location, or transaction value. Relationship-based authorization represents relationships such as “user is a member of project” or “doctor treats patient.” In complex systems, policy engines can centralize decisions, but centralized policy does not eliminate the need for resource-level checks.

Every server-side operation must enforce authorization. Hiding a button in a user interface is not an authorization control. Common failures include insecure direct object references, privilege escalation, confused-deputy behavior, and inconsistent checks between endpoints. Denial should be the default when identity, policy, or resource ownership cannot be established.

OAuth, OpenID Connect, and Federated Identity

OAuth 2.0 is an authorization framework that allows a client to obtain limited access to a resource on behalf of a resource owner. It is not, by itself, an authentication protocol. OpenID Connect adds an identity layer using an identity token and standardized claims.

In an authorization-code flow, a client redirects a user to an authorization server, which authenticates the user and obtains consent where appropriate. The client receives a short-lived authorization code and exchanges it for tokens. Proof Key for Code Exchange (PKCE) binds the exchange to the initiating client and is important for public clients such as mobile and browser applications. Redirect URIs must be strictly registered, state must protect against request forgery, and nonce values help detect replay or token-substitution attacks in OpenID Connect.

Architects must distinguish the authorization server, resource server, client, and identity provider. Tokens should be validated for signature, issuer, audience, expiry, and relevant claims. Applications should request the smallest practical scopes and avoid treating external identity claims as unquestionable business authorization. Federation creates operational dependencies: provider outages, account-linking errors, claim changes, and termination delays must be addressed.

Secrets, Encryption, and Data Protection

Secrets include API keys, database passwords, signing keys, certificates, recovery codes, and private credentials. They should not appear in source code, container images, public configuration, logs, tickets, or chat messages. A secrets manager should control storage, access, rotation, versioning, and audit events. Applications should receive only the secrets required for their current function, preferably through short-lived credentials or workload identity.

Encryption in transit protects communication, normally through current versions of TLS and correctly validated certificates. Encryption at rest protects stored data, but its value depends on key management, access controls, backup handling, and separation of duties. Application-level encryption may be appropriate for especially sensitive fields, while tokenization can reduce exposure in payment or analytics workflows. Hashing is one-way transformation for integrity or password storage; encryption is reversible when the key is available. These purposes must not be confused.

Key management includes generation, secure storage, rotation, revocation, backup, recovery, and documented ownership. Excessive rotation without operational readiness can cause outages, while permanent keys increase compromise impact. Cryptographic algorithms should normally be selected from maintained, well-reviewed libraries rather than implemented by application developers.

Secure Coding and Supply-Chain Security

Secure coding converts architectural controls into reliable implementation. Input validation should use allowlists and domain-specific constraints. Output encoding must be appropriate to the context, such as HTML, JavaScript, SQL, or a command shell. Parameterized queries reduce injection risk. File uploads require type, size, content, storage, and execution controls. Error messages should support diagnosis without exposing credentials, internal paths, or sensitive records.

Dependency security is a major architectural concern because applications rely on frameworks, libraries, container images, build tools, and hosted services. A supply-chain program maintains an inventory or software bill of materials, pins or otherwise controls versions, scans for known vulnerabilities, verifies package provenance where possible, and separates build permissions from deployment permissions. Automated scanning is valuable but cannot determine whether a vulnerable component is reachable or whether a malicious package has escaped detection.

A secure build pipeline should protect source branches, review sensitive changes, use isolated and reproducible builds where practical, scan infrastructure and images, sign artifacts, and verify them before deployment. Dependency updates should be risk-based rather than postponed indefinitely. Emergency response procedures are necessary when a critical library or signing key is compromised.

Privacy by Design and Ethical Engineering

Privacy begins with purpose. A system should identify why each category of personal data is collected, whether collection is necessary, who can access it, how long it is retained, and how it will be deleted or corrected. Data minimization reduces both privacy exposure and breach impact. Purpose limitation prevents data collected for one service from being silently repurposed for unrelated surveillance or profiling.

Privacy notices should be clear, specific, and understandable. Consent, where used, should be informed, voluntary, specific, and withdrawable; it should not be hidden behind confusing interface choices. Depending on jurisdiction and context, obligations may include rights of access, correction, deletion, portability, objection, restriction, and explanation. Organizations must identify applicable laws and contracts rather than assuming that one framework applies universally.

Ethical design extends beyond legal compliance. A recommendation system may be lawful but unfair if it systematically excludes a group. A notification system may be technically effective but manipulative if it exploits anxiety. Ethical review should ask who benefits, who bears risk, whether users can meaningfully refuse, whether automated decisions are contestable, and whether vulnerable users are disproportionately affected.

Accessibility is part of responsible design. Keyboard operation, readable contrast, captions, semantic structure, alternative text, clear error messages, and compatibility with assistive technologies help prevent exclusion. Accessibility testing should involve both automated tools and users with relevant disabilities.

Zero Trust, Observability, and Auditability

Zero trust is an architectural stance that rejects implicit trust based solely on network location. Every request should be evaluated using identity, device or workload context, resource, action, and policy. Network segmentation remains useful, but being inside a corporate network does not automatically authorize access.

A zero-trust implementation normally combines strong identity, short-lived credentials, service-to-service authentication, least privilege, policy enforcement near protected resources, endpoint or workload posture checks, and continuous monitoring. It should be introduced incrementally; imposing complex controls without service ownership, reliable identity data, or recovery procedures can create operational failure.

Auditability means that important actions can be reconstructed. Audit records should identify the actor, action, target, time, result, and relevant request or correlation identifier. Logs must avoid unnecessary personal data and protect against alteration. Time synchronization, restricted access, retention rules, alerting, and tested investigation procedures are essential. Logging everything is not the same as being auditable: excessive low-value events can obscure a serious incident.

Security monitoring should support detection and response rather than surveillance without purpose. Organizations need defined incident roles, escalation thresholds, evidence-preservation procedures, communication plans, and recovery exercises. Metrics may include time to detect, time to contain, remediation age, coverage of critical assets, failed authorization rates, and recovery-test results.

Compliance and Governance

Compliance is an organizational capability, not a checklist delegated entirely to developers. A governance program maps obligations to policies, controls, evidence, owners, and review dates. Common sources include privacy law, sector regulation, payment requirements, contractual commitments, accessibility obligations, records-management rules, and professional codes.

Frameworks such as information-security management standards, control catalogs, privacy frameworks, and secure-development guidance can provide structure. However, adopting a framework does not automatically establish compliance. The organization must define scope, assess risks, implement controls, test their effectiveness, record exceptions, and remediate findings.

Governance also includes data classification, retention schedules, vendor due diligence, change management, separation of duties, business continuity, and security training. Third-party risk deserves particular attention because providers may process personal data, hold credentials, or become a critical availability dependency. Contracts should address security responsibilities, breach notification, sub-processors, deletion, audit rights, service levels, and exit arrangements.

An Illustrative Case: Secure Architecture for a Telehealth Platform

Background

Consider an illustrative company, CareLink, developing a telehealth platform connecting patients, clinicians, laboratories, and insurers. The platform includes a web application, mobile client, API gateway, appointment service, clinical-record service, messaging service, payment provider, and analytics pipeline.

Situation and Problem

An early design used one shared service account, stored API credentials in deployment scripts, relied on user-interface role checks, and copied complete clinical records into analytics storage. The product team also proposed recording all video sessions indefinitely for quality review. These decisions created security, privacy, ethical, and compliance concerns.

Analysis

Threat modeling identified account takeover, unauthorized record access, insecure partner integrations, insider misuse, ransomware, excessive retention, and disclosure through logs and analytics. The most serious assets were clinical records, identity credentials, appointment information, and service availability. Trust boundaries existed between patients and the API, the API and internal services, and CareLink and external providers.

Approach and Strategy

CareLink introduced federated identity with multifactor authentication for clinicians and an authorization model based on patient-care relationships rather than broad job roles. Each service received a distinct workload identity and narrowly scoped permissions. The clinical-record service enforced authorization at the resource level, independent of the user interface.

The platform adopted authorization-code flow with PKCE for mobile and browser clients, secure session handling, centralized secrets management, encrypted transport, and field-level protection for especially sensitive data. Analytics received de-identified or minimized data through a governed pipeline, with documented purpose and retention limits. Video recording became opt-in, with visible indicators, restricted access, deletion controls, and a separate clinical justification.

The delivery pipeline added dependency inventory, image scanning, protected branches, signed artifacts, security tests, and approval for production changes. Audit events recorded access to clinical records without placing clinical content in ordinary application logs. Incident exercises tested account compromise, provider outage, and restoration from backup.

Outcome

The redesigned architecture reduced the impact of a compromised service account, improved traceability of record access, and aligned data processing with defined purposes. It also exposed trade-offs: stronger controls increased implementation complexity, and minimizing analytics data reduced some short-term research convenience. These costs were accepted because they reduced material privacy and safety risks.

Learning Points

The case demonstrates that security controls, privacy decisions, ethical choices, and compliance evidence are interconnected. The most important improvement was not a single product or tool; it was the replacement of implicit trust and excessive collection with explicit policy, minimized data, independent controls, and accountable operations.

Challenges, Limitations, and Common Mistakes

Security programs face competing pressures involving delivery speed, usability, cost, legacy systems, and incomplete information. Excessively restrictive controls can encourage workarounds. Poorly designed multifactor authentication can lock out legitimate users. Centralized identity or policy services can become availability bottlenecks. Encryption can complicate searching, recovery, and lawful access. Automated vulnerability scanners produce false positives and may miss business-logic flaws.

Common mistakes include treating compliance as proof of security; placing secrets in environment files without access governance; trusting client-side role information; using one account for multiple services; logging personal data unnecessarily; failing to test backups; assuming internal networks are safe; retaining data indefinitely; and designing consent screens to maximize acceptance rather than understanding.

Risk acceptance should be explicit, time-limited, owned by an accountable authority, and accompanied by compensating controls where possible. Security debt should appear in the product and operational backlog rather than remaining invisible.

Current Developments and Strategic Implications

Modern development increasingly combines software supply-chain attestations, passwordless authentication, workload identity, confidential-computing techniques, automated policy checks, privacy-enhancing computation, and machine-assisted detection. Artificial intelligence introduces additional concerns: prompt injection, sensitive-data leakage, model supply chains, biased decisions, insecure tool access, and difficulty explaining outputs. AI systems should receive threat models, access boundaries, monitoring, human review, and documented data provenance.

The strategic direction is toward continuous assurance rather than periodic certification alone. Infrastructure as code, policy as code, automated evidence collection, continuous control monitoring, and secure software-development metrics can connect architecture with governance. Automation should enforce repeatable controls, not replace judgment about context, proportionality, fairness, and human impact.

Best-Practice Decision Framework

When reviewing a feature, an architecture team can ask:

  • What assets and people could be affected?
  • Which actors, trust boundaries, and abuse cases exist?
  • What identity and authorization decision is required at each resource?
  • What data is genuinely necessary, and when should it be deleted?
  • How are secrets, keys, dependencies, logs, and backups protected?
  • What happens if a provider, credential, component, or control fails?
  • Can the action be detected, investigated, reversed, and explained?
  • Which legal, contractual, accessibility, ethical, and professional obligations apply?
  • What evidence demonstrates that the control works?

These questions transform security from a narrow implementation activity into a disciplined architectural practice.

Chapter Summary

Security, privacy, ethics, and compliance by design require coordinated decisions across the full stack and the organization that operates it. Threat modeling identifies assets, actors, trust boundaries, abuse cases, and prioritized mitigations. Defense in depth, least privilege, zero trust, secure coding, strong identity, resource-level authorization, secrets management, encryption, auditability, and supply-chain controls reduce both likelihood and impact of failure.

Privacy requires purposeful collection, minimization, transparency, retention control, and respect for individual rights. Ethical engineering additionally considers fairness, autonomy, accessibility, vulnerable groups, and the consequences of automated decisions. Compliance becomes effective when obligations are mapped to owners, controls, evidence, testing, and governance. No tool guarantees safety; trustworthy architecture depends on appropriate controls, professional judgment, continuous monitoring, and accountable decision-making.

Key Terms

CIA triad: The security objectives of confidentiality, integrity, and availability.

Defense in depth: Multiple independent or complementary controls that reduce the chance and impact of failure.

Threat modeling: A structured process for identifying assets, threats, risks, and mitigations.

Trust boundary: A point where data or authority crosses between different security domains.

STRIDE: A threat-modeling classification covering spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege.

Authentication: Verification of the identity of a user, service, or device.

Authorization: Determination of which actions or resources an authenticated subject may access.

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

OAuth 2.0: A framework for delegated authorization to protected resources.

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

PKCE: A mechanism that binds an authorization-code exchange to the client that initiated it.

Secrets management: Controlled storage, distribution, rotation, and auditing of sensitive credentials and keys.

Encryption: Reversible transformation of data using a key to protect confidentiality.

Hashing: A one-way transformation used for integrity, indexing, or secure password storage.

Zero trust: A security model that avoids implicit trust and continuously evaluates access requests.

Auditability: The ability to reconstruct and substantiate important actions from reliable records.

Privacy by design: Incorporating privacy protections into systems from conception through operation.

Data minimization: Collecting and retaining only the data necessary for a defined purpose.

Software bill of materials: An inventory of components contained in a software product.

Residual risk: Risk remaining after controls have been implemented.

Review Questions

Short Answer Questions

1. Distinguish authentication from authorization.

2. What is the purpose of a trust boundary in threat modeling?

3. Why should secrets not be stored in source code or container images?

4. State two characteristics of privacy by design.

5. What does zero trust reject?

Long Answer Questions

1. Explain how threat modeling can guide full stack architecture decisions from requirements through operations.

2. Compare role-based, attribute-based, and relationship-based authorization, including suitable application contexts.

3. Explain the security responsibilities involved in OAuth 2.0 and OpenID Connect implementations.

4. Discuss how supply-chain security, secure coding, and build-pipeline controls reinforce one another.

5. Analyze the relationship between privacy, ethical design, accessibility, and regulatory compliance.

Analytical / Application Questions

1. A banking API validates a user at login but permits access to any account number supplied in a URL. Identify the threat, explain the design failure, and propose layered controls.

2. A company wants to retain all customer conversations indefinitely for AI training. Evaluate this proposal using threat modeling, privacy, ethics, governance, and data-minimization principles.

3. Design a security and compliance strategy for a microservice that processes sensitive personal data and depends on two external providers. Identify identities, trust boundaries, secrets, logs, failure scenarios, and evidence requirements.

22. Multiple Choice Questions with Answers

Question 1

A customer is authenticated successfully but attempts to view another customer’s invoice by changing an identifier in the URL. Which control is primarily missing?

A. Resource-level authorization

B. Transport encryption

C. Password hashing

D. Dependency pinning

Correct Answer: A. Resource-level authorization

Question 2

Which statement most accurately describes OAuth 2.0?

A. It is primarily a delegated authorization framework

B. It is a password-storage algorithm

C. It guarantees that every identity claim is trustworthy

D. It replaces authorization checks in resource servers

Correct Answer: A. It is primarily a delegated authorization framework

Question 3

What is the principal purpose of PKCE in an authorization-code flow?

A. To bind the code exchange to the initiating client

B. To encrypt database backups

C. To classify personal data

D. To replace multifactor authentication

Correct Answer: A. To bind the code exchange to the initiating client

Question 4

Which architectural decision best represents zero trust?

A. Allowing all internal services to communicate because they share a private network

B. Evaluating each service request using identity, resource, action, and policy

C. Removing authentication after a user enters the corporate network

D. Granting administrators permanent unrestricted access

Correct Answer: B. Evaluating each service request using identity, resource, action, and policy

Question 5

Why is data minimization a security and privacy benefit?

A. It eliminates the need for access control

B. It reduces exposure and potential breach impact

C. It ensures data can never be corrected

D. It makes all processing automatically lawful

Correct Answer: B. It reduces exposure and potential breach impact

Question 6

Which practice is most appropriate for application secrets?

A. Embedding them in a public JavaScript bundle

B. Storing them in a governed secrets manager with controlled rotation

C. Writing them into ordinary application logs

D. Sharing one permanent credential across all services

Correct Answer: B. Storing them in a governed secrets manager with controlled rotation

Question 7

A threat-modeling exercise identifies a payment service, an API, a browser, and a database. What should the team examine next?

A. Only the visual design of the browser

B. Data flows, actors, trust boundaries, and possible threats

C. Only the number of lines of application code

D. Whether the database has the largest storage capacity

Correct Answer: B. Data flows, actors, trust boundaries, and possible threats

Question 8

Which audit record is most useful for investigating unauthorized data access?

A. A generic message saying ‘request completed’

B. Actor, action, target, time, result, and correlation identifier

C. The user’s password and full personal record

D. Only the server’s operating-system version

Correct Answer: B. Actor, action, target, time, result, and correlation identifier

Question 9

A software bill of materials primarily helps an organization to:

A. Inventory components and assess dependency exposure

B. Replace all functional testing

C. Grant every developer production access

D. Guarantee that no component can ever be compromised

Correct Answer: A. Inventory components and assess dependency exposure

Question 10

Which proposal best reflects ethical and privacy-conscious AI design?

A. Retain all personal data indefinitely because it may become useful

B. Provide defined purposes, minimized data, human review, and contestability

C. Hide automated decisions to prevent users from questioning them

D. Use consent interfaces designed to pressure acceptance

Correct Answer: B. Provide defined purposes, minimized data, human review, and contestability

Full Stack Application Architecture and Design Patterns
Chapter 11 of 15