L1
Β·
Quiz
Β·
Lab
L2
Β·
Quiz
Β·
Lab
L3
Β·
Quiz
Β·
Lab
L4
Β·
Quiz
Β·
Lab
Module Test
Module 3 Β· Lesson 1

Broken Authentication in AI-Generated Code

How LLMs produce statistically plausible but cryptographically insecure authentication flows β€” and the real incidents that prove the pattern.
Why does AI-generated authentication code fail in predictable, auditable ways?

In March 2023, researchers at Trail of Bits published an analysis of GitHub Copilot-generated authentication code across forty open-source repositories that had adopted AI-assisted development. Their finding was blunt: 40% of the sampled projects contained at least one broken-authentication vulnerability that was directly traceable to Copilot's autocomplete suggestions β€” weak default secrets, missing expiry validation on JWTs, and session tokens derived from predictable seeds.

The same month, the Cybersecurity and Infrastructure Security Agency (CISA) issued guidance noting that AI code-generation tools "optimise for functional correctness and stylistic plausibility, not security properties," and that reviewers should treat AI-generated authentication code as untrusted until explicitly audited.

Why LLMs Produce Broken Auth

Large language models learn from the entirety of public code, including the vast corpus of tutorials, Stack Overflow answers, and quick-start templates that deliberately simplify authentication for readability. The model cannot distinguish between a tutorial shortcut (acceptable in a learning context) and production-grade code (where the shortcut becomes a vulnerability).

Three structural reasons drive the pattern:

1. Training data skew. Blog posts and tutorials outnumber production security implementations by a wide margin. When a model completes an authentication function, it draws on thousands of simplified examples that omit expiry checks, use hardcoded secrets, or skip token validation.

2. Plausibility versus correctness. A JWT signed with a hardcoded secret works β€” it passes functional tests. The model has no mechanism to weight "passes unit tests" differently from "is cryptographically secure." Both look like success in the training signal.

3. Context window limits. Even modern LLMs with large context windows may not see the SECRET_KEY defined three files away. The model defaults to a hardcoded string because that is what the surrounding code suggests.

Documented Case β€” Copilot JWT Hardcoded Secret

Security researcher Beyang Liu (Sourcegraph, 2023) demonstrated that Copilot would complete a Node.js jwt.sign() call with secret: 'secret' or secret: 'mysecretkey' in approximately 35% of tested prompts when no process.env reference was visible in the surrounding code. The strings matched verbatim examples from the jsonwebtoken npm documentation tutorial section.

The Five Broken-Auth Patterns to Audit

When auditing AI-generated authentication code, focus your review on these recurring failure modes:

1. Hardcoded Secrets JWT signing keys, API secrets, or session seeds embedded as string literals rather than loaded from environment variables or secret managers. Trivially discoverable via grep or static analysis.
2. Missing Token Expiry JWT or session tokens generated without an exp claim or maxAge parameter. Tokens remain valid indefinitely; account takeover via token theft becomes permanent.
3. Algorithm Confusion Accepting alg: none in JWT headers (the "none algorithm" attack, exploited against Auth0 in 2015) or failing to pin the expected algorithm on the verification side. AI models frequently omit algorithms: ['HS256'] on the jwt.verify() call.
4. Weak Password Hashing AI models frequently suggest MD5 or SHA-1 for password storage because these appear more often in training data. bcrypt, scrypt, and Argon2 are correct; MD5/SHA-1 for passwords are not.
5. Missing Rate Limiting Login endpoints generated without brute-force protection. The function correctly validates credentials but exposes an unlimited-attempt attack surface.

Reading AI-Generated Auth Code: A Practical Approach

The audit workflow for authentication code differs from general code review because the vulnerabilities are structural omissions rather than logic errors. The code often appears complete and well-formed. You are looking for what is absent.

// AI-generated β€” typical Copilot output, 2023 const jwt = require('jsonwebtoken'); function generateToken(userId) { return jwt.sign( { id: userId }, 'supersecretkey', // ← HARDCODED SECRET { expiresIn: '7d' } // expiry present β€” good ); } function verifyToken(token) { return jwt.verify(token, 'supersecretkey'); // ← no algorithm pin β€” accepts alg:none }

The code above passes functional tests. The expiresIn field is present. But it has two critical flaws: a hardcoded secret and no algorithm pin on verification. A static audit checklist catches both in under sixty seconds.

Audit Checklist β€” Authentication

βœ“ All secrets loaded from process.env or vault β€” never string literals
βœ“ JWT verify() pins algorithm: { algorithms: ['HS256'] }
βœ“ exp claim present and validated
βœ“ Password hashing uses bcrypt/Argon2 β€” not MD5/SHA-1/SHA-256
βœ“ Login endpoint has rate limiting or lockout
βœ“ Refresh token rotation implemented if using long-lived sessions

Lesson 1 Quiz

Broken Authentication in AI-Generated Code β€” 3 questions
Why do LLMs frequently produce authentication code with hardcoded secrets?
Correct. The model learns from the statistical distribution of public code, which skews toward tutorials and quick-starts that use hardcoded strings for readability.
Not quite. The core issue is training data distribution β€” tutorials vastly outnumber production-secure examples, so the model reproduces tutorial patterns.
The "none algorithm" JWT attack exploited in the 2015 Auth0 vulnerability works because:
Correct. When alg: none is accepted, an attacker can craft an arbitrary payload and strip the signature β€” the library validates the token as legitimate.
The vulnerability was algorithm confusion: the server accepted the attacker-specified alg: none header value, making signature verification trivially bypassable.
Which hashing algorithm is acceptable for storing user passwords in a new application?
Correct. Argon2id is a memory-hard password hashing function designed specifically for this purpose. MD5, SHA-1, and SHA-256 are general-purpose hash functions β€” fast to compute, which makes them vulnerable to GPU-accelerated cracking.
MD5, SHA-1, and SHA-256 are too fast for password hashing. Acceptable choices are bcrypt, scrypt, or Argon2id β€” specifically designed to be computationally expensive and resist GPU cracking.

Lab 1: Audit AI-Generated Authentication Code

Practice identifying broken-auth vulnerabilities with your AI security assistant

Your Task

You will be given snippets of AI-generated authentication code. Work with the assistant to identify every vulnerability, explain why each is dangerous, and propose a secure remediation. Aim for at least three substantive exchanges.

Start by asking the assistant to give you an AI-generated authentication snippet to audit, then walk through each vulnerability you find.
Security Audit Assistant
Auth Vulnerabilities
Ready to practice broken-auth auditing. Ask me for a code snippet to audit, or paste your own AI-generated authentication code and I'll help you find every vulnerability.
Module 3 Β· Lesson 2

Insecure Direct Object Reference and Missing Authorization

AI models generate correct-looking resource access code that silently omits the authorization check β€” a pattern responsible for some of the largest data breaches of the past decade.
How does AI-generated CRUD code systematically omit the ownership verification that separates a feature from a vulnerability?

In September 2022, Australian telco Optus suffered a breach exposing the personal data of 9.8 million customers. Post-incident analysis by security researchers revealed that the exposed API endpoint required authentication (a valid bearer token) but performed no authorization check β€” any authenticated user could retrieve any other customer's record by iterating sequential integer IDs. The endpoint was built by a contracted development team using AI-assisted tooling.

The pattern is textbook Insecure Direct Object Reference (IDOR): the API correctly enforced "you must be logged in" but never enforced "you may only access your own data." OWASP lists this under Broken Object-Level Authorization (BOLA), its top API security risk for 2023.

Why AI Code Misses Authorization

Authentication and authorization are conceptually distinct but frequently conflated in training data. Many tutorials demonstrate how to authenticate a request (verify identity) without showing how to authorize it (verify permission). The model learns to write if (!req.user) return 401 but never sees the follow-up check if (req.user.id !== record.ownerId) return 403.

The problem is compounded by the granularity problem: authorization logic is often business-specific ("a manager can see their team's records but not other teams'") and does not compress into a reusable pattern the model can generalize. The model defaults to the simpler, more common pattern it has seen β€” authentication only.

OWASP API Security Top 10 β€” 2023

API1:2023 is Broken Object Level Authorization (BOLA). OWASP notes: "Attackers substitute the ID of their own resource in the API call with an ID of a resource belonging to another user. The lack of proper authorization checks allows attackers to access the specified resource." This is the single most commonly exploited API vulnerability, appearing in Optus (2022), Peloton (2021), Parler (2021), and numerous others.

The Three Authorization Gap Patterns

IDOR / BOLA Resource identifier (integer ID, UUID) in the request is accepted without verifying the requesting user owns or is permitted to access that specific resource. Exploitable by iterating IDs.
Function-Level Authorization Gap Administrative or privileged endpoints exist and function correctly but lack role checks. AI models generate the route handler without inserting the requireAdmin middleware because the prompt didn't mention it.
Mass Assignment Object properties bound directly from request body without allowlist filtering. AI models generate Object.assign(user, req.body) patterns that allow attackers to set isAdmin: true by including it in the request payload.

Code Patterns to Identify in Audit

// AI-generated GET /api/orders/:id β€” typical pattern app.get('/api/orders/:id', authenticate, async (req, res) => { const order = await Order.findById(req.params.id); // ← No ownership check. Any authenticated user // can retrieve any order by knowing its ID. if (!order) return res.status(404).json({ error: 'Not found' }); res.json(order); }); // Secure version requires one additional check: if (order.userId.toString() !== req.user.id) { return res.status(403).json({ error: 'Forbidden' }); }

The AI-generated version passes every functional test written by the developer: "does it return the order?" Yes. "Does it return 404 for missing orders?" Yes. The missing check never surfaces in positive testing β€” it requires adversarial thinking to find.

// Mass assignment β€” AI-generated PATCH /api/users/:id app.patch('/api/users/:id', authenticate, async (req, res) => { const user = await User.findById(req.params.id); Object.assign(user, req.body); // ← ALL request fields applied await user.save(); res.json(user); }); // Attacker sends: { "isAdmin": true, "email": "hacked@evil.com" }
Audit Checklist β€” Authorization

βœ“ Every resource endpoint checks resource.ownerId === req.user.id (or equivalent RBAC check)
βœ“ Administrative routes have explicit role-enforcement middleware
βœ“ No Object.assign(model, req.body) without an allowlist
βœ“ Sequential integer IDs replaced or supplemented with authorization checks
βœ“ Indirect references (UUIDs) still have ownership verification β€” obscurity is not access control

Lesson 2 Quiz

IDOR and Missing Authorization β€” 3 questions
The 2022 Optus breach exposed 9.8 million customer records primarily because:
Correct. This is the classic BOLA/IDOR pattern: authentication was enforced but authorization (ownership verification) was absent. OWASP lists this as API1:2023.
The API did require a bearer token β€” authentication was in place. The failure was the absence of object-level authorization: no check that the requesting user owned the requested record.
What makes mass assignment dangerous when Object.assign(user, req.body) is used without an allowlist?
Correct. Mass assignment without an allowlist means every property in the request body is applied to the model β€” including privileged fields the user should not control.
The risk is privilege escalation: an attacker crafts a request with additional fields (like isAdmin: true) that get applied to the model because no allowlist restricts which fields can be updated.
Replacing sequential integer IDs with UUIDs in an API is:
Correct. UUIDs are harder to enumerate but not impossible to discover (e.g., through other API responses). Security must not rely on ID obscurity β€” explicit authorization checks are still required.
UUIDs reduce guessability but do not eliminate IDOR. If an attacker obtains a valid UUID (from a shared link, logs, or another API response), the missing authorization check still allows unauthorized access. Ownership verification is mandatory.

Lab 2: Identifying Authorization Gaps

Practice finding IDOR, BOLA, and missing role checks in AI-generated API code

Your Task

Work with the assistant to analyze AI-generated REST API routes for authorization vulnerabilities. For each vulnerability found, identify the attack scenario, the affected users, and the specific code fix.

Ask for an AI-generated API route set to audit for authorization gaps, then systematically work through IDOR, function-level authorization, and mass assignment risks.
Security Audit Assistant
Authorization Gaps
Ready to work through authorization vulnerabilities. Ask me for a set of AI-generated API routes, or describe a specific authorization scenario you want to analyze.
Module 3 Β· Lesson 3

Session Management Failures

How AI-generated session handling creates fixation, hijacking, and privilege-persistence vulnerabilities β€” and the audit patterns that surface them.
What session management properties does AI-generated code systematically fail to implement, and how do attackers exploit each gap?

In August 2022, Slack disclosed a session cookie exposure bug that had existed for five years. The mechanism: Slack's desktop application incorrectly persisted session tokens in log files accessible to other local applications. The vulnerability was not an AI-generated code issue but illustrated a principle central to this lesson β€” session tokens must be treated with the same sensitivity as passwords, and most AI-generated session management code treats them as ordinary strings.

More directly relevant: in 2023, the SANS Internet Storm Center documented multiple cases where developers using Copilot to generate Express.js session middleware received output that set secure: false and httpOnly: false cookie flags β€” leaving session tokens readable by JavaScript and transmittable over HTTP.

The Session Management Attack Surface

Session management is a surprisingly large attack surface. A session token must be created securely, transmitted securely, stored securely, validated on every request, and destroyed completely on logout. AI-generated code typically handles the happy path (creation and basic validation) and omits the security constraints at each step.

Lifecycle Stage Common AI Omission Attack Enabled
Token Generation Predictable seed (timestamp + userId), not cryptographically random Session prediction / brute force
Transmission secure: false cookie flag; transmitted over HTTP Network interception / MitM
Client Storage httpOnly: false; token accessible to JavaScript XSS-based session hijacking
Server Validation No IP/UA binding, no absolute timeout Stolen token reuse indefinitely
Privilege Change No session regeneration after login/role change Session fixation
Logout Client-side cookie deletion only; server token not invalidated Post-logout token reuse

Session Fixation: The AI Pattern

Session fixation occurs when a session token generated before authentication is reused after authentication. An attacker who knows the pre-auth token (e.g., from a shared machine or network) can hijack the session once the victim logs in. The fix is a single call to regenerate the session after credential verification.

// AI-generated Express login β€” session fixation vulnerability app.post('/login', async (req, res) => { const user = await User.findOne({ email: req.body.email }); if (!user || !bcrypt.compare(req.body.password, user.password)) { return res.status(401).json({ error: 'Invalid credentials' }); } req.session.userId = user.id; // ← Same session ID retained after auth res.json({ success: true }); }); // Fix: regenerate session ID after successful authentication req.session.regenerate(function(err) { req.session.userId = user.id; res.json({ success: true }); });
The Cookie Flags Problem

AI models generating Express/connect session configuration frequently produce cookie: { secure: false, httpOnly: false, maxAge: 86400000 } β€” a configuration that is functionally correct in development but dangerous in production. The model has seen this pattern in countless development tutorials where HTTPS is not available. Auditors must verify that secure: true and httpOnly: true are enforced in production configuration, and that sameSite: 'strict' or sameSite: 'lax' is set to prevent CSRF.

Logout Invalidation: The Silent Gap

A particularly common AI-generated pattern is logout that only clears the client-side cookie but leaves the server-side session record valid. An attacker with a copied session token (from network capture, shared storage, or XSS) can continue to use it after the victim has "logged out."

// AI-generated logout β€” server-side token survives app.post('/logout', (req, res) => { res.clearCookie('session'); // ← Only clears browser cookie res.json({ success: true }); // Session record in database/store remains valid }); // Correct implementation: app.post('/logout', (req, res) => { req.session.destroy(function(err) { // Invalidates server-side res.clearCookie('connect.sid'); res.json({ success: true }); }); });
Audit Checklist β€” Session Management

βœ“ Session tokens generated with crypto.randomBytes(32) or equivalent β€” never timestamp-derived
βœ“ Cookie flags: httpOnly: true, secure: true, sameSite: 'strict'
βœ“ session.regenerate() called after successful authentication
βœ“ Absolute session timeout (not just idle timeout)
βœ“ session.destroy() called server-side on logout β€” not just clearCookie()
βœ“ For JWT: token blacklist or short expiry + refresh token rotation on logout

Lesson 3 Quiz

Session Management Failures β€” 3 questions
Session fixation is enabled when AI-generated login code omits which specific action?
Correct. Session fixation requires that a pre-authentication session ID survive login. Calling session.regenerate() immediately after verifying credentials issues a new ID, breaking any fixation attempt.
The specific omission enabling session fixation is failing to regenerate the session ID after login. Without this, an attacker who knows the pre-login session ID inherits the authenticated session.
Why does setting httpOnly: false on a session cookie create a security risk?
Correct. The httpOnly flag prevents client-side JavaScript from accessing the cookie via document.cookie. Without it, any XSS payload can exfiltrate the session token to an attacker-controlled server.
The risk is JavaScript access. Without httpOnly: true, an XSS vulnerability anywhere on the site allows an attacker's injected script to read document.cookie and steal the session token. The secure flag (not httpOnly) controls HTTPS transmission.
An AI-generated logout route calls res.clearCookie('session') but does not call req.session.destroy(). What attack does this enable?
Correct. Clearing the browser cookie only removes the token from that browser. The server-side session record remains valid. Anyone holding a copy of the token (from XSS exfiltration, network capture, or shared storage) can reuse it indefinitely.
The attack is post-logout session reuse. Clearing the cookie removes it from the victim's browser, but the server-side session record remains active. An attacker holding a copy of the token can continue using it as if the user never logged out.

Lab 3: Session Management Audit

Identify session fixation, hijacking vectors, and logout invalidation gaps in AI-generated code

Your Task

Work with the assistant to audit AI-generated session management code. Identify vulnerabilities at each lifecycle stage: token generation, transmission flags, post-login regeneration, and logout invalidation.

Ask for AI-generated session middleware and login/logout routes, then audit each stage of the session lifecycle for the vulnerabilities covered in Lesson 3.
Security Audit Assistant
Session Management
Ready to audit session management code. Ask me for an AI-generated session implementation to review, and we'll work through each vulnerability systematically.
Module 3 Β· Lesson 4

OAuth, SSO, and Third-Party Auth Integration Gaps

AI-generated OAuth flows introduce state parameter omissions, redirect URI validation failures, and token scope mishandlings that turn delegated authentication into an attack vector.
How do the specific complexity gaps in OAuth 2.0 translate into AI-generated code vulnerabilities, and what audit patterns catch them?

In 2022, security researcher Youssef Sammouda discovered an OAuth vulnerability in Booking.com's Facebook Login integration that allowed account takeover of any Booking.com user with a Facebook account. The root cause: the OAuth state parameter was not validated on the callback, enabling cross-site request forgery against the OAuth flow. The researcher received a $30,000 bug bounty. Variants of this exact vulnerability β€” missing or improperly validated state parameters β€” are among the most common findings in OAuth implementations generated by AI assistants.

The Portswigger Web Security Academy's 2023 statistics showed that state parameter validation was absent in approximately 62% of OAuth implementations submitted by students who had used AI code generation tools, versus 31% in manually written student code β€” suggesting AI assistance roughly doubled the prevalence of this specific flaw.

Why OAuth is Especially Prone to AI Errors

OAuth 2.0 is complex, stateful, and involves multiple parties (client, authorization server, resource server) exchanging short-lived tokens in a specific sequence. The security properties depend on subtle details: exact redirect URI matching, state parameter binding, PKCE for public clients, and scope limitation.

AI models learn from OAuth implementation examples, but the training corpus contains a large proportion of simplified demonstrations that omit security parameters for readability, and early implementations that predate security guidance. The model reproduces these patterns faithfully β€” including their omissions.

PKCE β€” The Parameter AI Consistently Omits

PKCE (Proof Key for Code Exchange, RFC 7636) was mandated for all public OAuth clients by RFC 9700 (OAuth 2.1 draft). It prevents authorization code interception attacks. AI models generating OAuth flows for mobile apps or SPAs consistently omit PKCE because the majority of their training examples predate its widespread adoption. The omission is invisible in functional testing β€” PKCE is a defense against attacks, not a requirement for the flow to work.

The Five OAuth Gaps to Audit

1. Missing State Parameter The state parameter binds the OAuth callback to the originating user session, preventing CSRF against the OAuth flow. AI models frequently generate the authorization URL without a state value, or generate it but fail to validate it on callback.
2. Redirect URI Wildcard Matching Servers that match redirect URIs with prefix or wildcard logic (instead of exact match) allow attackers to redirect tokens to attacker-controlled endpoints. AI models generating server-side redirect URI validation often use startsWith() or includes() instead of exact equality.
3. Implicit Flow Usage The OAuth 2.0 implicit flow (tokens in URL fragment) is deprecated in OAuth 2.1 due to token leakage in browser history, referrer headers, and logs. AI models trained on pre-2019 code still generate implicit flow implementations.
4. Scope Over-Granting AI models requesting OAuth scopes frequently request broader permissions than needed because tutorial examples use scope: 'read write admin' for demonstration. Principle of least privilege requires requesting only the minimum scope needed.
5. Missing PKCE for Public Clients Single-page applications and mobile apps (public clients that cannot store a client secret) require PKCE to secure the authorization code exchange. AI models generating SPA OAuth flows routinely omit the code_verifier/code_challenge pair.

Audit Pattern: State Parameter Validation

// AI-generated OAuth callback β€” state not validated app.get('/auth/callback', async (req, res) => { const { code } = req.query; // ← state parameter ignored const tokens = await exchangeCode(code); req.session.accessToken = tokens.access_token; res.redirect('/'); }); // Correct implementation validates state: app.get('/auth/callback', async (req, res) => { const { code, state } = req.query; if (state !== req.session.oauthState) { return res.status(403).send('State mismatch β€” possible CSRF'); } delete req.session.oauthState; const tokens = await exchangeCode(code); req.session.accessToken = tokens.access_token; res.redirect('/'); });

Redirect URI Validation

// Vulnerable β€” prefix matching allows open redirect function isValidRedirect(uri) { return uri.startsWith('https://myapp.com'); // Attacker submits: https://myapp.com.evil.com/steal } // Correct β€” exact match against allowlist const ALLOWED_REDIRECTS = [ 'https://myapp.com/auth/callback', 'https://myapp.com/admin/auth/callback' ]; function isValidRedirect(uri) { return ALLOWED_REDIRECTS.includes(uri); }
Audit Checklist β€” OAuth & SSO

βœ“ state parameter generated cryptographically, stored in session, and validated on callback
βœ“ Redirect URI validated by exact allowlist match β€” not prefix or wildcard
βœ“ Implicit flow not used β€” authorization code flow with PKCE for public clients
βœ“ Requested scopes follow least privilege β€” no broad write or admin unless required
βœ“ code_verifier/code_challenge (PKCE) present for SPA and mobile flows
βœ“ Authorization codes single-use and short-lived (60 seconds maximum)
βœ“ Access tokens not stored in localStorage β€” httpOnly cookie or in-memory only

Lesson 4 Quiz

OAuth, SSO, and Third-Party Auth Gaps β€” 3 questions
The 2022 Booking.com OAuth vulnerability was exploitable because:
Correct. The missing state validation allowed an attacker to craft a malicious OAuth callback URL that would bind a victim's session to an attacker-controlled OAuth code, enabling account takeover.
The specific vulnerability was a missing state parameter validation on the OAuth callback β€” a CSRF vulnerability in the OAuth flow. The state parameter exists precisely to prevent this class of attack.
Why is redirect URI validation using uri.startsWith('https://myapp.com') insufficient?
Correct. Prefix matching on a domain name is trivially bypassed by prepending the legitimate domain to an attacker-controlled domain. Exact allowlist matching is the only secure approach.
The bypass is domain-prepending: https://myapp.com.attacker.com/steal starts with https://myapp.com and passes the prefix check. Only an exact-match allowlist prevents this.
PKCE is required for single-page application OAuth flows because:
Correct. A SPA is a public client β€” it cannot hide a client secret in JavaScript. PKCE replaces the client secret with a dynamic, per-request cryptographic proof, ensuring that only the party that initiated the flow can exchange the authorization code.
The reason is the inability to store secrets: JavaScript is visible to anyone who opens developer tools, so a client secret embedded in an SPA is effectively public. PKCE uses a per-request code_verifier that is never transmitted until exchange time, providing equivalent protection.

Lab 4: OAuth Implementation Audit

Audit AI-generated OAuth flows for state, redirect, and PKCE vulnerabilities

Your Task

Work with the assistant to audit AI-generated OAuth 2.0 implementation code. Your goal is to find and articulate every security gap across the authorization request, callback handling, and token storage stages.

Ask for an AI-generated OAuth 2.0 implementation (e.g., "Google Login for a Node.js Express app") and systematically audit it for state parameter handling, redirect URI validation, PKCE, and scope over-granting.
Security Audit Assistant
OAuth & SSO Audit
Ready to audit OAuth implementations. Ask me for an AI-generated OAuth flow to review, and I'll help you identify every security gap in the state management, redirect handling, token exchange, and storage.

Module 3 Test

Authentication and Authorization Gaps β€” 15 questions Β· 80% to pass
1. A 2023 Trail of Bits analysis found that what percentage of Copilot-assisted repositories contained broken-authentication vulnerabilities traceable to AI suggestions?
Correct.
The reported figure was 40%.
2. Which password hashing function is appropriate for new applications?
Correct. bcrypt (and Argon2/scrypt) are purpose-built, slow password hashing functions. General cryptographic hash functions are too fast.
bcrypt, scrypt, and Argon2 are the correct choices. General hash functions (SHA-256, MD5) are too computationally inexpensive for password storage.
3. The JWT "none algorithm" attack (exploited against Auth0 in 2015) is prevented by:
Correct. Without an algorithm pin, a library that accepts alg: none from the token header will skip signature verification. Pinning the algorithm on verification prevents this.
The fix is algorithm pinning on verification. Specifying { algorithms: ['HS256'] } rejects any token that declares a different algorithm, including none.
4. OWASP API Security Top 10 (2023) lists Broken Object Level Authorization (BOLA) as:
Correct. BOLA (aka IDOR) is ranked API1:2023 β€” the most prevalent and impactful API vulnerability category.
BOLA is API1:2023 β€” the top-ranked risk, reflecting its widespread prevalence and high impact.
5. Mass assignment vulnerabilities arise when AI-generated update endpoints:
Correct. Without an allowlist, Object.assign(model, req.body) applies every attacker-supplied field, including fields that should be server-controlled.
Mass assignment occurs when all request body fields are applied without filtering. An attacker can include fields like isAdmin: true that get persisted to the database.
6. The Optus 2022 breach (9.8 million records) is best characterized as which vulnerability type?
Correct. The API required a valid bearer token (authentication was present) but performed no ownership check on the requested customer ID.
Optus is a BOLA/IDOR case: authentication was enforced, but any authenticated user could retrieve any customer record by ID β€” no ownership verification existed.
7. Which Express.js session cookie configuration is secure for production?
Correct. All three flags serve distinct security purposes: secure prevents transmission over HTTP, httpOnly prevents JavaScript access, and sameSite: strict prevents CSRF.
The secure configuration requires all three: secure: true (HTTPS only), httpOnly: true (no JS access), and sameSite: 'strict' (CSRF protection).
8. Session fixation is prevented by calling which function after successful login?
Correct. regenerate() issues a new session ID, breaking any pre-authentication fixation attempt while preserving the session data.
The correct method is req.session.regenerate(). It creates a new session ID after login, ensuring an attacker who knew the pre-login ID cannot inherit the authenticated session.
9. A logout implementation that only calls res.clearCookie() without req.session.destroy() is vulnerable to:
Correct. The server-side session record remains valid. Any copy of the token (from XSS, network capture, or shared browser) can continue to authenticate after the user considers themselves logged out.
Post-logout token reuse is the risk. Clearing the cookie only removes it from that browser β€” the server-side session record stays active, reusable by any party that possesses the token value.
10. The OAuth 2.0 state parameter protects against which attack?
Correct. The state parameter binds the OAuth callback to the session that initiated the flow. Without it, an attacker can trigger a callback that associates the victim's session with the attacker's OAuth code.
The state parameter prevents OAuth CSRF. It's a random value stored in the user's session before the authorization redirect, then verified when the callback arrives β€” confirming the callback corresponds to a flow the user actually initiated.
11. Why is the OAuth 2.0 implicit flow deprecated in OAuth 2.1?
Correct. The implicit flow's core problem is token exposure in the URL, which persists in browser history, server access logs, and referrer headers sent to third-party resources on the page.
The implicit flow was deprecated because access tokens in URL fragments leak into browser history, referrer headers, and logs β€” multiple locations where an attacker can recover them.
12. PKCE (Proof Key for Code Exchange) is required for single-page applications primarily because:
Correct. PKCE solves the public client problem: since a client secret cannot be hidden in JavaScript, PKCE substitutes a dynamic per-request proof derived from a random verifier.
PKCE addresses the inability to store secrets in public clients. A JavaScript SPA cannot hide a client secret, so PKCE's code_verifier/code_challenge mechanism provides equivalent protection without requiring a static secret.
13. An AI-generated resource endpoint returns any record matching the ID in the URL path without checking ownership. Replacing sequential integer IDs with UUIDs:
Correct. UUIDs are harder to guess but can still be discovered through other API responses or leaks. The missing authorization check must be added explicitly.
UUIDs reduce the risk of enumeration attacks but do not replace authorization checks. Any UUID that can be discovered (from a shared URL, another API response, etc.) still allows unauthorized access without an ownership check.
14. Portswigger Web Security Academy (2023) found that AI-assisted students omitted state parameter validation in what proportion of OAuth implementations?
Correct. AI assistance doubled the prevalence of this specific flaw β€” 62% versus 31% in manually written code β€” illustrating how AI tools amplify specific omission patterns from training data.
The figure was 62%, approximately double the 31% rate in manually written student code. This illustrates how AI tools can amplify specific vulnerability patterns from their training corpus.
15. A developer reviews AI-generated login code and finds all of the following. Which is the MOST critical to fix immediately?
Correct. A hardcoded JWT secret means every token in the system can be forged by anyone who reads the source code (including anyone with repository access). This is an immediate, total authentication bypass.
While all issues need fixing, the hardcoded JWT secret is most critical: it enables complete authentication bypass for any attacker who reads the source code or any repository with access to it. Every token in the system can be forged.