Web Application, API and Client-Side TestingIntroductionWeb applications and APIs are among the most frequently attacked components of modern information systems. They process personal data, authenticate users, enforce business rules, connect mobile and browser clients, and integrate with third-party services. A vulnerability in an application may therefore expose data even when the underlying operating system and network perimeter are well protected. Ethical testing of these systems is not simply a search for technical defects. It is a structured assessment of whether the application preserves confidentiality, integrity, availability, authentication, authorization, accountability and business trust. Testing must be performed only with written authorization, clearly defined scope, agreed test accounts, approved time windows and appropriate data-handling procedures. This chapter applies principles from the OWASP Web Security Testing Guide, OWASP Top 10, OWASP API Security Top 10 and OWASP Application Security Verification Standard. These resources are complementary: the Top 10 highlights major risk classes, while testing guides and verification standards provide more detailed assessment structure. Learning ObjectivesBy the end of this chapter, a learner should be able to: - Describe the architecture and attack surface of web applications, APIs and client-side components.
- Test authentication, authorization, sessions and input handling safely.
- Explain injection, insecure design, security misconfiguration and server-side weaknesses.
- Assess browser security controls such as cookies, CORS, CSP and framing protection.
- Test APIs for object-level authorization, excessive data exposure and abuse of business functions.
- Document evidence, assess impact and recommend practical remediation.
- Apply ethical, legal and governance requirements to penetration testing.
1. Application Attack Surface and Testing MethodA web application commonly contains a browser interface, web server, application services, databases, file stores, identity providers, queues and external integrations. An API may expose similar functionality through JSON, XML, GraphQL or other protocols. Client-side code can contain sensitive logic, but it must never be treated as a trusted security boundary because users control their browsers and devices. A useful assessment begins with an attack-surface inventory: | Component | Examples | Typical questions |
|---|
| Entry points | URLs, parameters, headers, cookies, uploads | What data can an attacker influence? | | Identity | Login, password reset, MFA, tokens | Can identity controls be bypassed or abused? | | Authorization | Roles, ownership, tenant boundaries | Can one user access another user's object? | | State | Sessions, carts, workflows | Can state be forged, reused or skipped? | | Server functions | Database, filesystem, commands, templates | Is untrusted data interpreted as instructions? | | Client controls | DOM, JavaScript, storage, browser policies | Can browser-side assumptions be manipulated? | | Integrations | Payment, email, identity and cloud APIs | Are trust relationships and failures controlled? |
A professional methodology normally follows these stages: - Pre-engagement: define authorization, scope, exclusions, test intensity, contacts and evidence rules.
- Reconnaissance: identify technologies, routes, parameters, roles, workflows and API versions.
- Mapping: create an application map and a role-to-function matrix.
- Manual and automated testing: use an intercepting proxy, browser developer tools, API clients and carefully configured scanners.
- Validation: reproduce findings, eliminate false positives and determine realistic impact.
- Reporting: explain the condition, evidence, risk, affected assets and remediation.
- Retesting: verify that corrective changes address the root cause without creating regressions.
Automation is useful for discovery and repeated checks, but it cannot reliably understand business rules, authorization context or intended workflows. Human analysis remains essential. 2. Authentication and Identity TestingAuthentication establishes who a user or service is. Authorization determines what that identity may do. These concepts must be tested separately. A system can authenticate users correctly while allowing them to access resources belonging to another account. 2.1 Registration and loginAssess whether registration permits duplicate identities, weak passwords, predictable identifiers or unauthorized role selection. Login testing should examine: - password policy and protection against common or breached passwords;
- consistent error messages that do not unnecessarily reveal whether an account exists;
- rate limiting, progressive delays or account-protection controls;
- MFA enrollment, reset and bypass paths;
- session creation after login;
- protection against credential stuffing and password spraying;
- secure transport and absence of credentials in URLs or logs.
Rate limiting should be evaluated carefully in an authorized environment because aggressive testing can deny service to legitimate users. Test accounts and prearranged thresholds are preferable. 2.2 Password recovery and account lifecyclePassword-reset tokens should be unpredictable, single-use, time-limited and bound to the intended account. A reset process should not disclose secrets through URLs that may be stored in browser history, referrer data or monitoring systems. Changes to passwords, email addresses, MFA devices and recovery factors should require appropriate reauthentication and generate notifications. Account deactivation, role changes and employee departure are also security functions. A disabled account should not retain valid sessions or API tokens indefinitely. 2.3 Multi-factor authenticationMFA strength depends on both factor independence and lifecycle protection. Testing should examine enrollment, replacement, recovery, remembered-device functions, fallback channels and session behavior. A system that protects login with MFA but permits an insecure password-reset route may still be bypassable. 3. Authorization and Access-Control TestingAuthorization failures are among the most consequential application defects. Testing should use at least two ordinary users, and where appropriate, a manager, administrator and tenant from a separate organization. A role-function matrix records permitted actions: | Function | Anonymous | User A | User B | Manager | Administrator |
|---|
| View own profile | No | Yes | Yes | Yes | Yes | | View another user's profile | No | No | No | Policy-dependent | Policy-dependent | | Edit own record | No | Yes | Yes | Yes | Yes | | Delete organization | No | No | No | No | Yes |
Testing should compare requests that differ only in identity, object identifier, HTTP method, API version or workflow stage. Important categories include: - Horizontal privilege escalation: User A accesses User B's data or actions.
- Vertical privilege escalation: A lower-privileged user performs an administrator function.
- Insecure direct object reference or broken object-level authorization: an identifier is accepted without checking ownership or permission.
- Function-level authorization failure: a hidden interface or endpoint can be called directly.
- Tenant isolation failure: one organization can access another organization's records.
Authorization must be enforced server-side on every relevant request. Hiding buttons, disabling HTML controls or relying on client-side role flags is not security. 4. Session ManagementAfter authentication, the application uses a session identifier or token to associate requests with an identity. Assess session creation, rotation, expiration, revocation and transport. Important checks include: - session identifiers are generated using a cryptographically secure mechanism;
- identifiers do not contain predictable user information;
- the identifier changes after authentication or privilege elevation;
- logout invalidates the session where required;
- idle and absolute timeouts match risk and business needs;
- password changes and account disablement invalidate active sessions;
- cookies use
Secure, HttpOnly and an appropriate SameSite attribute; - tokens are not exposed in URLs, client logs or unsafe browser storage.
HttpOnly reduces access from JavaScript but does not prevent all cross-site request attacks. SameSite helps control cross-site cookie sending but must be selected with regard to legitimate cross-site workflows. Session protections are defense in depth, not substitutes for authorization.
JSON Web Tokens require particular care. Signature validation must include an approved algorithm policy, issuer and audience checks where applicable, expiry validation and secure key management. A token's decoded payload must not be trusted merely because it is readable by the client. 5. Input Validation and InjectionInput validation should be based on expected type, length, range, encoding and business meaning. A robust design uses allowlists where practical, canonicalizes data before validation and applies context-appropriate output encoding. Validation is not a single filter placed at the front of an application. 5.1 SQL and other interpreter injectionSQL injection occurs when untrusted data changes the structure of a database query. The preferred defense is parameterized queries or prepared statements. Escaping alone is fragile because correctness depends on database engine, encoding and context. Related injection classes include command, LDAP, XML, template, expression-language and NoSQL injection. The testing principle is the same: determine whether attacker-controlled data reaches an interpreter as instructions rather than data. In an authorized lab, testers should use harmless proof-of-concept inputs and avoid destructive commands, data extraction or persistence. 5.2 Cross-site scriptingReflected XSS appears in an immediate response, stored XSS persists in application data, and DOM-based XSS arises from client-side processing. Defenses include context-specific output encoding, safe templating, input constraints, secure DOM APIs and an effective Content Security Policy. Sanitization may be necessary for intentionally supported rich text, but it must use a well-maintained, context-aware sanitizer. A finding should identify the execution context, affected users, required privileges, data exposure and whether CSP limits exploitation. Do not use payloads that steal real credentials or harm other users. 5.3 File handlingUpload testing should assess extension and content validation, size limits, storage location, filename handling, authorization, decompression behavior and retrieval headers. Uploaded content should not become executable server-side code. Download functions should prevent unauthorized access and unsafe path construction. 6. Business Logic and Insecure DesignSome vulnerabilities cannot be found by looking for malformed input. They arise because the workflow permits an illegitimate outcome. Examples include applying a discount repeatedly, approving one's own transaction, changing a price after payment, skipping identity verification, reusing a one-time invitation or completing steps out of order. A business-logic test models the intended process and then asks: - What assumptions does each step make?
- Can a request be repeated, reordered or omitted?
- Are limits enforced on the server?
- Are actions atomic and protected against race conditions?
- Is the actor authorized at the moment of action, not only at login?
- Are financial and administrative actions auditable?
Controls should be designed around explicit server-side state transitions, transaction integrity, authorization and idempotency. Security requirements belong in design and threat modeling, not only in final testing. 7. API Security TestingAPIs expose structured operations and often have more endpoints than a visible web interface. Build an inventory from documentation, source repositories, mobile applications, traffic observation and version discovery. Undocumented endpoints must be handled within scope and with care. The OWASP API Security Top 10 emphasizes risks such as broken object-level authorization, broken authentication, unrestricted resource consumption, broken function-level authorization, unrestricted access to sensitive business flows, server-side request forgery, security misconfiguration, improper inventory management and unsafe consumption of APIs. Assess: - object identifiers and ownership checks;
- mass assignment or automatic binding of client fields to privileged properties;
- excessive response data and unnecessary internal fields;
- pagination, filtering and export limits;
- rate limits and resource-cost controls;
- content-type and schema validation;
- errors that reveal stack traces, secrets or internal topology;
- deprecated versions and shadow endpoints;
- webhook authentication, replay protection and signature validation;
- GraphQL introspection policy, query depth and field authorization where relevant.
An API gateway can provide useful controls, but it does not replace authorization in the application service. Each service must validate identity, permission, object ownership and input according to its own trust boundary. 8. Client-Side and Browser SecurityThe browser is an execution environment controlled partly by the user. Client-side controls improve usability and defense in depth, but sensitive decisions must be repeated on the server. 8.1 Cross-site request forgeryCSRF occurs when a browser sends an authenticated request that the user did not intentionally initiate. Test state-changing operations, cookie behavior, anti-CSRF tokens, origin checks and SameSite settings. Tokens should be unpredictable, bound to the session or request context and validated server-side. APIs using authorization headers rather than automatically attached cookies have a different threat profile, but they still require careful token protection. 8.2 CORSCross-Origin Resource Sharing controls which browser origins may read responses. Test whether arbitrary origins are reflected, whether credentials are allowed with overly broad origins and whether sensitive methods and headers are exposed. CORS is not an authorization mechanism; a server must still authenticate and authorize the request. 8.3 Content Security Policy and related headersCSP can restrict script sources, object loading, framing and other browser behaviors. A policy should be tested for unsafe allowances such as broad script sources, inline execution or unrestricted dynamic code. Other useful headers include frame-ancestors or equivalent framing protection, HSTS, appropriate content type handling and controlled referrer policy. Headers should support, not replace, secure application design. 8.4 DOM and browser storageReview client code for unsafe sinks, exposed secrets, insecure postMessage handling, unvalidated redirects and sensitive data in local storage. Messages should validate both origin and message structure. Redirect targets should be allowlisted or represented by server-side identifiers. Public client code cannot protect embedded secrets; credentials intended to remain secret must not be shipped to the browser. 9. Server-Side Weaknesses and MisconfigurationServer-side request forgery occurs when an application fetches a resource based on attacker-influenced input. Testing should be authorized and designed to avoid access to cloud metadata, internal services or sensitive networks. Defenses include strict destination allowlists, safe URL parsing, DNS and redirect controls, egress filtering and network segmentation. Security misconfiguration includes default credentials, unnecessary services, verbose errors, debug interfaces, permissive methods, exposed administration panels, weak TLS settings, missing security headers and publicly accessible backups. Configuration should be consistent across development, testing and production, with secrets stored in managed secret systems and rotated appropriately. Deserialization, unsafe file processing and server-side template injection require particular caution because successful exploitation may lead to code execution. A tester should first establish the presence of an unsafe design using non-destructive evidence rather than attempting uncontrolled compromise. 10. Reporting and Risk EvaluationA useful report is reproducible and actionable. Each finding should include: - title and affected asset;
- vulnerability class and affected endpoint or workflow;
- prerequisites and attacker position;
- concise reproduction steps;
- sanitized request and response evidence;
- impact on confidentiality, integrity and availability;
- likelihood and business context;
- root cause;
- prioritized remediation;
- limitations and retest requirements.
CVSS may assist technical prioritization, but it does not replace business risk analysis. A moderate technical weakness in a payment or identity system may deserve urgent treatment. Reports should avoid unnecessary personal data and should encrypt sensitive evidence. Applied Case: Illustrative Multi-Tenant Invoice PortalBackgroundA fictional company operates an online invoice portal. Customers use a browser application and JSON API to view invoices, download receipts and request refunds. The assessment is authorized for a staging environment containing synthetic data. ProblemThe client wants assurance that tenant boundaries, refund controls and session protections work correctly before launch. AnalysisThe tester creates two ordinary accounts in different tenants and maps browser requests. An invoice endpoint uses a numeric identifier. Replacing the identifier in a request returns another tenant's invoice. The response also contains internal payment references that the interface does not display. A refund endpoint accepts a client-supplied amount and does not verify that the invoice has not already been refunded. Finally, logout removes a browser cookie but an API token remains valid. These observations represent separate issues: broken object-level authorization, excessive data exposure, business-logic failure and incomplete token revocation. None requires a sophisticated exploit; the risk results from missing server-side controls. Approach and solutionThe development team changes invoice retrieval to authorize the object against the authenticated tenant and user permission. Response models are redesigned to return only required fields. Refunds are implemented as an authorized, atomic state transition with server-side amount calculation and an idempotency mechanism. Token revocation is added for logout, password change and account disablement, with short-lived access tokens and controlled refresh-token rotation. The tester retests using both accounts, repeated refund requests, altered amounts, old tokens and direct API calls. Logs are reviewed to confirm that denied actions are recorded without storing secrets. Outcome and learning pointsThe corrected portal prevents cross-tenant access, eliminates unnecessary fields, rejects repeated or altered refunds and invalidates relevant tokens. The case demonstrates that authorization, data minimization, workflow integrity and lifecycle management must be tested together. A secure user interface alone would not have revealed or prevented these failures. Ethical, Legal and Governance ConsiderationsTesting without permission may violate computer misuse, privacy, telecommunications or data-protection laws. Written authorization should identify the organization, systems, dates, methods and emergency contacts. Testers must minimize collection, avoid real-user harm, protect credentials and promptly report critical findings. Third-party services and cloud resources require explicit permission because the system owner may not own the full infrastructure. Organizations should integrate application security into a secure development lifecycle. Threat modeling, security requirements, code review, dependency management, secrets management, automated testing, penetration testing and incident response are complementary activities. AI-assisted scanners and code tools can improve coverage, but their outputs require human validation. Sensitive source code, tokens and customer data should not be submitted to unapproved AI services. Challenges and LimitationsTesting is constrained by scope, credentials, incomplete documentation, changing deployments and limited test data. A clean penetration test is not proof of absence of vulnerabilities. Automated tools miss business logic and may generate false positives; manual testing is slower and dependent on tester skill. A staging environment may differ from production, while production testing may introduce operational risk. Findings should therefore state coverage, assumptions and limitations clearly. Best-Practice Checklist- Obtain written authorization and define rules of engagement.
- Inventory routes, APIs, roles, data flows and trust boundaries.
- Test authentication and authorization independently.
- Use multiple roles and tenants to test object and function boundaries.
- Prefer parameterized queries, safe output encoding and validated schemas.
- Verify session rotation, expiration, revocation and cookie protections.
- Test business workflows, replay, ordering, limits and race-sensitive actions.
- Minimize API responses and maintain an accurate endpoint inventory.
- Review CORS, CSP, CSRF, redirect, upload and browser-storage behavior.
- Avoid destructive payloads and protect evidence.
- Report root causes and retest remediation.
Chapter SummaryWeb, API and client-side testing requires more than scanning for common strings. A professional assessment maps the application, identifies trust boundaries and evaluates authentication, authorization, sessions, inputs, workflows, APIs, browser controls and server configuration. OWASP guidance provides useful categories and verification practices, but testers must apply judgment to business context and architecture. The most serious failures often occur when server-side authorization is missing, workflows trust client input, APIs expose excessive data or security controls are implemented only in the browser. Ethical authorization, safe evidence handling, clear reporting and retesting are essential parts of the technical process. Key TermsAuthentication: Process of establishing a user's or system's identity. Authorization: Decision about which actions or resources an authenticated identity may access. Broken object-level authorization: Failure to verify access to a specific requested object. CSRF: Attack that causes a user's browser to submit an unintended authenticated request. CORS: Browser mechanism controlling permitted cross-origin reads. CSP: Browser policy restricting content and script behavior. DOM XSS: Cross-site scripting caused by unsafe client-side document manipulation. Horizontal privilege escalation: Access to another user's resources at the same privilege level. Idempotency: Property allowing repeated equivalent requests without an unintended additional effect. Injection: Interpretation of untrusted data as commands or query structure. Mass assignment: Unsafe automatic binding of client fields to server-side object properties. MFA: Authentication using two or more independent factors. OWASP: Open Worldwide Application Security Project. Privilege escalation: Obtaining permissions beyond those legitimately assigned. Session fixation: Attack involving use of a session identifier known or controlled before authentication. SSRF: Server-side request forgery through attacker-influenced server network requests. Tenant isolation: Separation preventing one organization's users or data from being accessed by another. Threat modeling: Structured identification of threats, trust boundaries and mitigations. Vertical privilege escalation: Performance of higher-privilege functions by a lower-privileged user. Review QuestionsShort Answer Questions- Why must authentication and authorization be tested separately?
- State two important security attributes for session cookies.
- What is broken object-level authorization?
- Why are parameterized queries preferred for SQL injection prevention?
- Give two examples of client-side controls that do not replace server-side authorization.
Long Answer Questions- Describe a professional methodology for testing a web application from pre-engagement through retesting.
- Explain how authentication, password recovery and MFA lifecycle weaknesses can combine into an account takeover.
- Discuss the major areas that should be assessed when testing a JSON API.
- Explain how business-logic testing differs from conventional input-validation testing.
- Discuss the ethical, legal and governance responsibilities of an application penetration tester.
Analytical / Application Questions- Two users from different tenants can request the same invoice endpoint by changing an identifier. Analyze the likely vulnerability, evidence required and remediation.
- An application uses secure cookies but permits a refund request to be repeated indefinitely. Identify the relevant security properties and propose a test and design correction.
- A browser application reflects any supplied origin in CORS responses while allowing credentials. Analyze the risk and recommend a safer policy.
Multiple Choice Questions with AnswersQuestion 1Which statement best distinguishes authentication from authorization? A. Authentication determines identity; authorization determines permitted actions. B. Authentication encrypts data; authorization compresses data. C. Authentication validates input; authorization logs events. D. Authentication creates backups; authorization restores them. Correct Answer: A. Authentication determines identity; authorization determines permitted actions. Question 2Which control is the preferred primary defense against SQL injection? A. Hiding database error messages only B. Parameterized queries or prepared statements C. Disabling browser JavaScript D. Changing the database table names Correct Answer: B. Parameterized queries or prepared statements Question 3A normal user changes an invoice identifier and receives another tenant's invoice. What is the most direct classification? A. Broken object-level authorization B. Clickjacking C. Weak TLS encryption D. Cross-site scripting Correct Answer: A. Broken object-level authorization Question 4Which cookie attribute prevents ordinary JavaScript from reading the cookie? A. Secure B. SameSite C. HttpOnly D. Path Correct Answer: C. HttpOnly Question 5What is the main purpose of testing two users from different tenants? A. To measure page-rendering speed B. To assess tenant isolation and horizontal access control C. To discover the browser version D. To test screen-reader compatibility Correct Answer: B. To assess tenant isolation and horizontal access control Question 6Which API weakness involves returning internal fields that the client does not need? A. Excessive data exposure B. Session fixation C. Clickjacking D. DNS poisoning Correct Answer: A. Excessive data exposure Question 7Which statement about CORS is correct? A. CORS replaces server-side authorization. B. CORS controls browser cross-origin reading and is not an authorization mechanism. C. CORS encrypts API responses. D. CORS prevents all server-side request forgery. Correct Answer: B. CORS controls browser cross-origin reading and is not an authorization mechanism. Question 8Which practice best supports safe testing of a destructive business function? A. Use real customer records to increase realism. B. Run unlimited automated requests without notification. C. Use authorized synthetic data and agreed test limits. D. Publish the endpoint before testing it. Correct Answer: C. Use authorized synthetic data and agreed test limits. Question 9A refund endpoint accepts a client-supplied amount without recalculating it. What is the primary concern? A. Insecure business logic and trust in client-controlled data B. Missing image compression C. Weak browser color contrast D. Excessive DNS caching Correct Answer: A. Insecure business logic and trust in client-controlled data Question 10Why is human analysis still necessary when automated scanners are used? A. Scanners cannot send HTTP requests. B. Scanners always modify production data. C. Scanners reliably understand every business rule. D. Scanners may miss workflow and authorization-context failures. Correct Answer: D. Scanners may miss workflow and authorization-context failures.
|