1. Web Security Foundations and Threat LandscapeIntroduction and ContextWeb applications are no longer isolated pages delivered from a single server. They are distributed systems involving browsers, mobile clients, application servers, APIs, identity providers, databases, cloud platforms, content-delivery networks, third-party services, and administrative interfaces. A weakness in any component can affect the security of the entire service. Consequently, web security is not merely the task of preventing malicious input; it is the disciplined protection of information, services, identities, and business processes throughout their lifecycle. Security failures may expose personal data, alter financial records, interrupt essential services, damage institutional reputation, or create legal and regulatory consequences. For a full-stack developer, security therefore begins before code is written. It involves identifying what must be protected, understanding who may interact with a system, defining trust relationships, reducing unnecessary exposure, and selecting controls that remain effective when individual components fail. This chapter establishes the conceptual foundation for secure coding. It introduces the principal security objectives, architectural principles, attack surfaces, trust boundaries, threat actors, and contemporary attack patterns. Later chapters can build upon these ideas to examine authentication, authorization, input handling, cryptography, secure APIs, testing, and operational security. Learning ObjectivesBy the end of this chapter, students should be able to: - explain confidentiality, integrity, availability, authenticity, and accountability;
- distinguish security principles from specific technical controls;
- apply least privilege, defence in depth, secure failure, and zero-trust thinking;
- identify attack surfaces and trust boundaries in a web architecture;
- classify threat actors according to capability, motivation, access, and resources;
- analyse common contemporary web attack patterns;
- evaluate security decisions using technical, organizational, ethical, and governance perspectives; and
- recommend proportionate security practices for a web application.
The Security Objectives of a Web ApplicationSecurity objectives provide a vocabulary for expressing what a system must protect. They are not interchangeable, and a control that improves one objective may create difficulties for another. For example, extensive logging may support accountability but also increase privacy risk if logs contain sensitive information. ConfidentialityConfidentiality means preventing information from being disclosed to unauthorized individuals, processes, or systems. A customer’s password reset token, an employee record, or an unpublished product design should be accessible only to authorized parties. Confidentiality depends on access control, encryption in transit and at rest, careful data classification, secure session management, and protection against information leakage through error messages, logs, caches, and URLs. Confidentiality is not equivalent to secrecy of the entire system. A public product catalogue may require no confidentiality, while the payment information used to purchase a product requires strong protection. Effective security begins by identifying which data is sensitive and why. IntegrityIntegrity is the assurance that data, code, configuration, and transactions are accurate, complete, and protected from unauthorized modification. An attacker who changes an account balance has violated integrity even if no information was disclosed. Integrity controls include authorization checks, transaction validation, cryptographic hashes or signatures, database constraints, version control, audit trails, and controlled deployment processes. Integrity also has a temporal dimension. A replayed but previously valid request may produce an invalid result if it is processed at the wrong time. Nonces, timestamps, transaction identifiers, and idempotency controls can help address this problem. AvailabilityAvailability means that authorized users can access a service or resource when required. Denial-of-service attacks, resource exhaustion, infrastructure failures, destructive malware, and poorly designed dependencies can all reduce availability. Availability is supported by capacity planning, rate limiting, redundancy, graceful degradation, backups, monitoring, incident response, and disaster recovery. Availability is a business requirement as well as a technical property. A public information site and an emergency healthcare service may have very different availability expectations. Security decisions should therefore reflect the consequences of interruption. AuthenticityAuthenticity concerns whether an entity, message, request, or piece of data is genuine. Authentication establishes confidence that a user is who they claim to be; message authentication establishes that a message originated from a trusted source and was not altered. Passwords, multifactor authentication, certificates, signed tokens, and cryptographic message authentication codes can support authenticity. Authentication alone does not determine what a user is allowed to do. A correctly authenticated user may still be prohibited from accessing another customer’s account. This distinction between authentication and authorization is central to web security. Accountability and Non-repudiationAccountability links actions to responsible identities and records. It requires reliable event recording, meaningful timestamps, protected logs, identity assurance, and procedures for reviewing evidence. Accountability supports investigation, compliance, fraud detection, and organizational learning. Non-repudiation is a stronger and context-dependent claim that an actor cannot credibly deny an action. Digital signatures may provide evidence of origin and integrity, but ordinary application logs do not automatically provide legal non-repudiation. Organizations must consider identity proofing, key custody, log protection, time synchronization, and applicable law before making such claims. The Security Triad and Its ExtensionConfidentiality, integrity, and availability are often called the CIA triad. Authenticity and accountability extend the model because modern applications must establish who is communicating, what they did, and whether records can be trusted. These objectives can conflict. Strict access checks may reduce convenience; extensive monitoring may affect privacy; aggressive availability measures may increase attack surface. Security engineering is therefore a process of risk-informed trade-offs rather than the pursuit of one absolute property. Principles for Building Resilient SystemsSecurity principles guide design decisions across technologies and frameworks. They are more durable than individual products or programming languages. Least PrivilegeLeast privilege gives a subject only the permissions necessary for its legitimate task, for only as long as necessary. A reporting service should not have permission to delete production records, and a web process should not run with operating-system administrator privileges. Least privilege applies to users, services, database accounts, API keys, containers, and developers. The principle is difficult to apply when permissions are granted broadly for convenience. Excessive privilege increases the impact of stolen credentials, compromised dependencies, and coding errors. Practical techniques include role-based access control, narrowly scoped service accounts, temporary credentials, permission reviews, and separation of administrative functions. Defence in DepthDefence in depth uses multiple, partly independent controls so that failure of one control does not immediately produce compromise. For example, an application may combine secure session cookies, authorization checks, database permissions, network segmentation, monitoring, and backup recovery. Defence in depth is not a justification for weak primary controls: encryption does not excuse poor authorization, and a firewall does not make vulnerable code safe. The quality of layered defence depends on independence. Five controls that all rely on the same misconfigured identity service may represent less depth than their number suggests. Secure Defaults and Fail-Safe FailureSecure defaults ensure that a newly deployed component begins in a restrictive state. Examples include disabled debugging in production, private storage by default, deny-by-default authorization, and secure cookie attributes. Fail-safe failure means that when a component cannot make a trustworthy decision, it should fail in a way that does not grant unintended access. An authorization service outage should not cause the application to treat every request as authorized. These principles must be balanced with availability. A system may deny access during an identity-service outage, or it may provide a limited read-only mode. The correct choice depends on risk and business context. Separation of Duties and Complete MediationSeparation of duties prevents one person or component from controlling an entire sensitive process. For example, one employee may create a payment request while another approves it. Complete mediation requires authorization to be checked whenever access occurs, rather than trusting a decision made long ago. Cached permissions and client-side role indicators must not replace server-side enforcement. Zero TrustZero trust is an architectural approach in which no user, device, network location, or service is automatically trusted. Each request is evaluated using available evidence such as identity, device posture, resource sensitivity, context, and policy. Access is granted explicitly, with least privilege and continuous monitoring. Zero trust does not mean that trust is absent; it means that trust is treated as a decision that must be justified and can change. A request from an internal network may still be malicious, and a valid service identity may be compromised. Zero-trust implementation commonly involves strong identity, segmentation, policy enforcement points, telemetry, and rapid revocation. Attack Surfaces and Trust BoundariesAn attack surface is the collection of points through which an attacker may interact with, influence, observe, or disrupt a system. It includes obvious interfaces such as login forms and APIs, but also less visible elements: file uploads, webhooks, administrative panels, cloud metadata services, error handlers, dependency update mechanisms, CI/CD pipelines, exposed storage buckets, and forgotten test environments. Attack-surface analysis asks questions such as: - What interfaces accept untrusted input?
- Which services are reachable from the public internet?
- What secrets, data, or privileges are available if a component is compromised?
- Which third-party systems can call or modify the application?
- Which administrative functions are insufficiently isolated?
A trust boundary is a point at which data, authority, or assumptions move between different levels of trust. Examples include the browser-to-server boundary, an API gateway-to-service boundary, an application-to-database boundary, and an organization-to-payment-provider boundary. Crossing a trust boundary requires validation, authentication where appropriate, authorization, and careful treatment of data formats. Trust boundaries are logical rather than merely physical. Two services in the same cloud network may still have different owners, privileges, and security assumptions. Conversely, a browser and a server may be physically distant but part of one authenticated transaction. Developers should document what each boundary guarantees and what it does not guarantee. A client-side validation rule, for instance, may improve usability but cannot be trusted as the final server-side control. Threat modelling makes these ideas actionable. A team can draw data-flow diagrams, identify assets, entry points, trust boundaries, and privileged operations, then consider threats using approaches such as STRIDE: spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege. The purpose is not to predict every attack but to discover important design assumptions early. Threat Actors and Their CapabilitiesA threat actor is an individual, group, organization, or automated process capable of causing harm. Classification should consider motivation and capability rather than relying only on labels. An opportunistic attacker scans for common weaknesses and uses readily available tools. A financially motivated criminal group may conduct credential theft, payment fraud, ransomware, or extortion. A malicious insider may possess legitimate access and understand organizational processes. Hacktivists may target availability or public reputation. Competitors or industrial-espionage groups may seek confidential information. Nation-state actors may possess substantial resources, patience, intelligence capabilities, and interest in strategic targets. Automated bots, compromised devices, and supply-chain attackers may operate at scale without direct interaction from a human at every stage. The same vulnerability can have different consequences depending on the actor. A weak password may lead to nuisance account takeover by an opportunist, while a targeted actor may combine it with social engineering and stolen session tokens. Threat analysis should therefore assess exposure, motivation, capability, opportunity, and likely impact. Contemporary Web Attack PatternsCredential Attacks and Account TakeoverCredential stuffing uses username-password pairs obtained from one service against another, exploiting password reuse. Brute-force attacks systematically try passwords, while password spraying tries a small number of common passwords against many accounts to avoid account lockouts. Phishing and adversary-in-the-middle techniques target users or authentication flows directly. Defences include multifactor authentication, breached-password screening, rate limiting designed to avoid denial of service, risk-based detection, secure recovery procedures, password managers, and strong session invalidation. Organizations should avoid relying solely on increasingly complex password composition rules. Injection and Interpreter AbuseInjection occurs when untrusted data is interpreted as commands or code. SQL injection can alter database queries; command injection can execute operating-system commands; template injection can manipulate server-side rendering; and cross-site scripting (XSS) can cause a browser to execute attacker-controlled script in a trusted origin. The central remedy is to keep data separate from instructions. Parameterized queries, context-aware output encoding, safe APIs, allow-list validation, and least-privileged database accounts are more reliable than attempting to remove a few dangerous characters. XSS prevention must consider HTML, attribute, URL, and JavaScript contexts separately. Broken Access Control and Insecure Direct Object ReferencesBroken access control occurs when a system fails to enforce what an authenticated subject may do. In an insecure direct object reference, a user changes an identifier in a URL or API request and obtains another user’s record. These failures are especially serious because they may be easy to exploit and difficult to detect through ordinary authentication monitoring. Authorization should be enforced on the server for every sensitive operation, using the authenticated identity, requested action, resource ownership, and organizational policy. Predictable identifiers may be acceptable in some systems, but obscuring an identifier is not a substitute for authorization. Cross-Site Request Forgery and Session AttacksCross-site request forgery (CSRF) abuses a browser’s automatic inclusion of credentials to induce a victim to submit an unwanted state-changing request. Anti-CSRF tokens, SameSite cookie settings, origin checks, and appropriate request design reduce risk. XSS can undermine many CSRF protections because injected script may act within the victim’s session. Session fixation, token theft, insecure cookie settings, excessive session duration, and failure to invalidate sessions after sensitive events can also enable account takeover. Secure, HttpOnly, and appropriately scoped cookies, token rotation, reauthentication for high-risk actions, and server-side session controls are important safeguards. Server-Side Request Forgery and Deserialization RisksServer-side request forgery (SSRF) occurs when an application fetches a user-influenced URL and can thereby reach internal services, cloud metadata endpoints, or administrative interfaces. Defences include strict destination allow-lists, network egress controls, URL parsing that resists alternative representations, and isolation of sensitive metadata services. Insecure deserialization occurs when attacker-controlled serialized data causes unexpected object creation or code execution. Safer data formats, type restrictions, integrity protection, and avoiding unnecessary deserialization reduce the risk. Resource Exhaustion and Distributed Denial of ServiceAttackers may consume CPU, memory, database connections, storage, bandwidth, or expensive third-party calls. A request does not need to be large to be costly; it may trigger complex searches, image processing, or repeated password hashing. Timeouts, quotas, pagination, bounded input, caching, asynchronous processing, circuit breakers, and infrastructure-level mitigation help preserve availability. Supply-Chain and Dependency AttacksWeb applications depend on packages, build tools, container images, cloud services, and deployment workflows. A compromised dependency or build pipeline can introduce malicious code with legitimate deployment privileges. Software bills of materials, dependency pinning, vulnerability monitoring, signed artifacts, protected build systems, minimal permissions, and review of transitive dependencies improve resilience. An Illustrative Case: The Exposed Customer PortalBackgroundConsider a fictional online education company, Northbridge Learning, operating a portal for students, instructors, and finance staff. The portal uses a single-page web client, REST APIs, a relational database, object storage for documents, and a third-party payment provider. SituationA student reports seeing another student’s invoice after changing the numeric identifier in an API URL. Investigation reveals that the API verifies whether the requester is logged in but does not verify ownership of the requested invoice. The object-storage bucket is also publicly readable because a deployment template used permissive defaults. Finally, application logs contain full password-reset URLs. AnalysisThe immediate defect is broken object-level authorization. It violates confidentiality and demonstrates that authentication is not authorization. The public bucket expands the attack surface and creates an independent confidentiality failure. Logging reset URLs creates another path to account compromise because tokens may be usable by anyone who obtains the logs. The defects are connected by weak trust-boundary assumptions: the client’s requested identifier was treated as trustworthy, storage permissions were assumed to be safe, and logs were treated as harmless operational data. Approach and SolutionNorthbridge first disabled public access to the bucket and rotated potentially exposed reset tokens. It added server-side ownership and role checks to every invoice endpoint, introduced automated authorization tests for horizontal and vertical access violations, and moved sensitive documents behind an authorization-controlled download service. Reset links were redacted from logs, and existing logs were handled as sensitive incident data. The team then performed a wider threat-model review. Service accounts were reduced to required permissions, deployment templates were changed to deny-by-default, monitoring was added for unusual object access, and an incident-response procedure was rehearsed. The organization also separated student, instructor, and finance permissions rather than relying on a single broad role. OutcomeThe immediate exposure was contained, and subsequent testing found no evidence that the affected invoices had been downloaded by unauthorized users. More importantly, the company changed its development process: authorization requirements were documented with each endpoint, security tests were included in the delivery pipeline, and cloud configuration was reviewed as application code. Learning PointsThe case illustrates that a secure login mechanism does not guarantee secure data access. It also shows why defence in depth matters: even if the API defect had remained, private storage and monitoring could have limited impact. Finally, security includes operational information such as logs and deployment configuration, not only source code. Organizational, Ethical, and Governance ConsiderationsSecurity decisions should be proportionate to risk and informed by the sensitivity of data, the likelihood of abuse, and the consequences of failure. Organizations have responsibilities to protect personal information, communicate honestly about incidents, retain only necessary data, and avoid surveillance that exceeds legitimate purposes. Privacy and security are related but not identical: collecting excessive data may create security risk rather than reduce it. Governance establishes ownership and accountability. Security policies should define access approval, vulnerability handling, logging, retention, incident reporting, third-party oversight, and exception management. Regulatory obligations vary by jurisdiction and sector, but compliance should be treated as a baseline rather than a complete security strategy. Professional conduct also matters. Developers must not test systems without authorization, expose real user data in demonstrations, or conceal known vulnerabilities to meet delivery targets. Automation and analytics can improve security through dependency scanning, infrastructure policy checks, anomaly detection, secret detection, and continuous authorization testing. Machine-learning systems may help identify unusual behaviour, but they can generate false positives, reproduce bias, or be manipulated by attackers. Automated decisions require human oversight, explainable response procedures, protected training data, and careful limits on autonomous actions. Common Mistakes and Practical Best PracticesFrequent mistakes include treating the frontend as a security boundary, trusting hidden form fields, using predictable identifiers as authorization, logging secrets, granting broad cloud permissions, disabling certificate validation during troubleshooting, assuming internal networks are safe, and postponing security testing until release. Another common error is to purchase a security tool without defining the risk it is intended to reduce. A practical baseline for full-stack teams is to: - catalogue assets, data flows, entry points, and trust boundaries;
- define authorization rules before implementing endpoints;
- validate untrusted input and encode output for its exact context;
- use parameterized database access and safe framework APIs;
- protect sessions and secrets throughout their lifecycle;
- apply least privilege to users, services, databases, and pipelines;
- configure secure defaults and review cloud exposure continuously;
- monitor meaningful security events without collecting unnecessary sensitive data;
- test both expected access and explicitly forbidden access;
- maintain backups, incident procedures, and recovery exercises; and
- review third-party components and dependencies as part of normal engineering.
Current DevelopmentsModern applications increasingly use microservices, serverless functions, APIs, mobile clients, containers, and software-as-a-service dependencies. These architectures can improve scalability but multiply identities, interfaces, and trust boundaries. API security, workload identity, software provenance, cloud configuration assurance, and centralized policy management are consequently becoming core security concerns. Passkeys and phishing-resistant authentication are gaining importance because passwords remain vulnerable to reuse and social engineering. Security teams are also adopting continuous exposure management, where internet-facing assets and configuration changes are assessed continuously rather than during occasional audits. At the same time, generative AI introduces new risks, including insecure generated code, prompt injection, sensitive-data disclosure, and overreliance on automated review. AI-assisted development should therefore remain subject to human design review, testing, threat modelling, and established secure-coding controls. Chapter SummaryWeb security protects information, identities, transactions, and services against unauthorized disclosure, alteration, misuse, and interruption. Confidentiality, integrity, availability, authenticity, and accountability provide the principal objectives for evaluating protection. Least privilege, defence in depth, secure defaults, separation of duties, complete mediation, and zero trust guide architecture and implementation. Attack surfaces include every interface or dependency through which a system can be influenced, while trust boundaries mark changes in authority or security assumptions. Threat actors differ in motivation, capability, access, and resources. Contemporary web risks include credential attacks, injection, broken access control, XSS, CSRF, SSRF, resource exhaustion, and supply-chain compromise. Effective security combines secure coding, identity and authorization controls, cloud and dependency governance, monitoring, recovery, ethical practice, and continuous risk assessment. Key TermsConfidentiality: Protection of information from unauthorized disclosure. Integrity: Assurance that data, code, and transactions are not improperly altered. Availability: Accessibility of authorized services and resources when required. Authenticity: Confidence that an entity, message, or data source is genuine. Accountability: Ability to associate actions with responsible identities and evidence. Least privilege: Granting only the permissions necessary for an authorized task. Defence in depth: Use of multiple, partly independent protective controls. Zero trust: An approach that requires explicit, contextual evaluation of every access request. Attack surface: The set of interfaces and components through which a system may be attacked. Trust boundary: A point where data, authority, or security assumptions cross between contexts. Threat actor: An individual, group, organization, or process capable of causing harm. Threat modelling: Structured identification and analysis of assets, threats, and controls. Authentication: Verification of an entity’s claimed identity. Authorization: Determination of what an authenticated entity may access or do. Injection: Exploitation of data being interpreted as commands or executable instructions. Cross-site scripting: Injection of attacker-controlled script into a trusted web context. Cross-site request forgery: Inducing a browser to submit an unwanted authenticated request. Server-side request forgery: Causing a server to make attacker-influenced network requests. Supply-chain attack: Compromise introduced through dependencies, tools, providers, or delivery processes. Rate limiting: Restricting the frequency or volume of operations to reduce abuse and exhaustion. Review QuestionsShort Answer Questions1. Distinguish confidentiality from integrity using a web-application example. 2. Why is authentication insufficient for protecting an invoice endpoint? 3. Define a trust boundary and identify one in a typical web architecture. 4. What is the purpose of least privilege? 5. State two controls that can reduce the risk of credential stuffing. Long Answer Questions1. Explain the CIA triad and discuss how authenticity and accountability extend it. 2. Describe defence in depth, secure defaults, separation of duties, and complete mediation. 3. Explain how attack-surface analysis and threat modelling support secure design. 4. Compare the principal characteristics and risks of opportunistic attackers, insiders, criminal groups, and nation-state actors. 5. Discuss contemporary web attack patterns and the secure-coding approaches used to mitigate them. Analytical / Application Questions1. A web API verifies that a user is logged in but permits the user to retrieve any record by changing an identifier. Analyse the trust-boundary failure and propose layered controls. 2. A service must fetch URLs supplied by users to generate previews. Identify the principal security risks and design a safer approach. 3. A company wants to log every request, including authorization headers and password-reset URLs, for accountability. Evaluate this decision and recommend a privacy-conscious logging strategy. 22. Multiple Choice Questions with AnswersQuestion 1A user is authenticated successfully but can access another customer’s invoice by changing an identifier in the URL. Which security property or control has primarily failed? A. Availability B. Object-level authorization C. Data compression D. Network redundancy Correct Answer: B. Object-level authorization Question 2Which design best demonstrates least privilege? A. Giving every service administrator access for operational convenience B. Allowing a reporting service to read only the approved reporting views C. Allowing the browser to decide which records a user may view D. Using one shared database account for all applications Correct Answer: B. Allowing a reporting service to read only the approved reporting views Question 3What is the main security concern when a server retrieves a user-supplied URL? A. Cross-site request forgery B. Server-side request forgery C. Password spraying D. Session fixation Correct Answer: B. Server-side request forgery Question 4Which practice most directly separates data from SQL instructions? A. Hiding database errors from users B. Using predictable record identifiers C. Using parameterized queries D. Increasing server memory Correct Answer: C. Using parameterized queries Question 5A system denies access when its authorization service is unavailable rather than treating requests as authorized. Which principle does this illustrate? A. Fail-safe failure B. Security through obscurity C. Open design D. Privilege accumulation Correct Answer: A. Fail-safe failure Question 6Why does zero-trust architecture reject automatic trust based only on network location? A. Internal networks can never transmit data B. A trusted network location proves that the user is harmless C. Requests require explicit and contextual evaluation D. Zero trust eliminates the need for authentication Correct Answer: C. Requests require explicit and contextual evaluation Question 7Which example is primarily an availability attack? A. Changing an account balance B. Reading a private medical record C. Exhausting database connections with expensive requests D. Forging a digital identity Correct Answer: C. Exhausting database connections with expensive requests Question 8Which statement about a client-side role indicator is correct? A. It is sufficient for authorization because users cannot normally see it B. It must be trusted if the connection uses HTTPS C. It may support presentation logic but cannot replace server-side authorization D. It prevents all insecure direct object references Correct Answer: C. It may support presentation logic but cannot replace server-side authorization Question 9Which combination most effectively reduces supply-chain risk? A. Unreviewed dependencies and broad build permissions B. Pinned dependencies, artifact verification, and protected build systems C. Disabling all monitoring after deployment D. Storing secrets in source code for auditability Correct Answer: B. Pinned dependencies, artifact verification, and protected build systems Question 10A company logs password-reset URLs to improve investigations. What is the principal problem? A. The logs may become a source of account compromise B. URLs cannot ever be recorded C. Logging always reduces availability D. Reset links improve authorization when logged Correct Answer: A. The logs may become a source of account compromise
|