CyberSib
Field notesFN-003Nov 24, 202611 min read
Entry FN-003

Source Code Auditing vs. Dynamic Testing: What Each One Catches

The code explains why a weakness exists. The running system shows whether it can be reached. Four original examples and an assessment workflow show how to use both views.

Assessment illustration: a source code audit traces internal logic while dynamic testing observes runtime behavior; both contribute to evidence-backed findings.
Two views of the same application. Trace the implementation, test its behavior, and connect the evidence. Assessment illustration, not a captured test result.

A checkout can return a successful response while its payment and order records disagree. An authorization function can look reasonable until an early return skips the session check. A well-written application can still sit behind a misconfigured gateway.

Those are different questions, and they require different evidence. Source code auditing explains how a security decision is implemented. Dynamic testing checks what a running system actually allows. The useful question is not which method wins. It is which uncertainty you need to remove before a release.

The four examples below are deliberately simplified teaching examples created for this article. They are not client findings, incident accounts, or production-ready implementations.

§ 1Two methods, two kinds of evidence

A source code audit traces security-relevant paths through application code, dependencies, configuration, and data access. The reviewer follows untrusted input to sensitive operations, checks authorization boundaries, and looks for broken assumptions across branches and services. Manual review can use static application security testing (SAST) tools to find candidate patterns; it is not the same as accepting a scanner’s output as findings.

Dynamic testing exercises a running application: requests, sessions, role changes, workflow transitions, error cases, and concurrent operations. Dynamic application security testing (DAST) tools help automate parts of that work. Manual testing adds application-specific hypotheses that a generic scanner may not understand.

Neither method implies a particular access level. Dynamic testers can work with source code, documentation, and test accounts; they do not have to work blind. That combination is often called a code-assisted assessment.

Question Source code audit Dynamic testing
What do we inspect? Implementation, data flow, trust boundaries, configuration available for review Observable behavior of the deployed build and its integrations
What evidence can we produce? The faulty branch, missing control, or violated invariant, with code references Reproducible requests and resulting responses, state changes, or logs
What limits the conclusion? Scope, code completeness, deployment differences, and runtime assumptions Reachable paths, available identities, test data, environment, and timing

Read this comparison as coverage guidance, not a detection guarantee. A reviewer can miss a flaw in plain sight. A dynamic test can expose a subtle logic bug without ever seeing the source. A clean result from either is not proof that the application has no vulnerabilities.

§ 2Example 1: A hidden bypass in an authorization check

Consider middleware attached to an admin-only route. Assume there is no additional authorization check downstream:

javascript
1export function authorize(req, res, next) {2  const token = req.headers["x-session"];3  if (!token) return deny(res);4  const session = sessions.get(token);5  if (session?.role === "admin" || req.query.debug) {6    return next();7  }8  if (session.expires < Date.now()) {9    return deny(res, "expired");10  }11  req.user = session.user;12  return next();13}

The code contains four separate problems:

  1. A query parameter bypasses the gate. With a nonempty session header and a truthy debug value, execution reaches next() without a valid session. Downstream behavior determines the resulting impact.
  2. Admins skip expiry validation. The early return accepts a stored admin session before checking whether it has expired.
  3. Unknown tokens throw an exception. The optional chain protects session?.role, but not session.expires. An exception is an error-handling defect; it does not, by itself, establish an authorization bypass.
  4. Ordinary users are allowed through. A valid, unexpired non-admin session falls through to the final next(). Despite its name, the function does not enforce the route’s admin-only policy.

An auditor can enumerate those paths directly. A tester can check ordinary-user access and unknown tokens with suitable accounts, but an expired admin session or an undocumented branch may require extra setup. Source access turns those states into explicit test cases instead of guesses.

The intended decision path

Diagram
Admin-only authorization decision pathReject missing or expired sessions and non-admin roles. Only a valid admin session may attach its identity and continue.

No

Yes

No

Yes

No

Yes

Known session?

Deny request

Not expired?

Admin role?

Set user and allow

Figure 1. For this admin-only route, identity, session validity, and permission are separate checks. No debug branch gets to skip them.

What to verify: test absent, unknown, expired, ordinary-user, and admin sessions. Inspect the protected operation’s result, not just its status code. A 200 response containing an error message is not proof of access, and a redirect is not proof that no action occurred.

For object-level routes, add ownership and tenant checks. An admin-role check alone does not establish permission to read every customer’s records. OWASP’s Authorization Cheat Sheet recommends deny-by-default behavior and permission validation on every request.

§ 3Example 2: A checkout that disagrees with itself

Here the checkout applies a discount after requesting payment authorization:

javascript
1export async function checkout(cart, user) {2  const total = await pricing.total(cart);3  const order = await orders.create({ user, total });4  await payments.authorize(order.id, total);5  if (cart.coupon) order.total = applyCoupon(order, cart.coupon);6  await orders.save(order);7  return receipt(order);8}

Assume pricing.total returns 100 currency units before discounts and the coupon reduces the order to 80. The payment authorization is for 100; the stored order and receipt say 80. That mismatch is demonstrable from the code. An overcharge or financial loss is not established until you trace capture, settlement, cancellation, and refund behavior.

Follow the money, not just the response

Diagram
Payment authorization and order total divergeAuthorizing 100 before applying a 20 discount leaves an order total of 80. The amount used at capture determines the resulting charge.

Auth hold

Order

Price: 100

Authorize: 100

Coupon: minus 20

Stored total: 80

Capture amount?

May charge 100

May charge 80

Figure 2. A worked example of a mismatch, not a confirmed loss. The downstream capture path determines the consequence.

A source reviewer can follow the amount through every caller, payment adapter, and webhook handler. A dynamic tester can compare the receipt with sandbox payment records and exercise retries, failed authorizations, and delayed callbacks. Looking only at the checkout response misses part of the transaction.

The invariant to defend: for this single-capture example, the finalized payable amount and currency must agree across the order, payment request, and settlement record. Represent money in integer minor units, apply discounts before authorization, and use an explicit state machine for later adjustments. Partial captures, partial refunds, and currency conversion need their own documented rules.

Also inspect refund authorization and the remaining refundable balance. A payment provider may reject an excessive refund, but that does not replace the application’s ownership checks or protect against every concurrent request.

§ 4Example 3: An SSRF control that fails open

An application that fetches user-supplied URLs needs more than a check that the URL looks valid. Consider this simplified error path:

javascript
1export async function fetchPreview(url) {2  try {3    await assertAllowedDestination(url);4  } catch (error) {5    logger.warn("Destination check failed", { error });6    // Execution continues even though validation failed. [!flag]7  }8  return fetch(url);9}

The code has converted a security decision into a best-effort warning. If validation rejects a destination or cannot complete, the fetch still runs. A timeout, parsing failure, or resolver error can therefore remove a control that appeared to protect the normal path.

A code audit exposes the unconditional fallthrough. Dynamic testing checks whether it can be reached in the actual environment: what happens when validation fails, whether redirects change the destination, and which networks the fetcher can reach.

The defensive requirement is fail-closed behavior: a failed destination check must stop the request. For known integrations, prefer an explicit destination allowlist. Where arbitrary external URLs are required, account for schemes, ports, IPv4 and IPv6, private and link-local addresses, redirects, and DNS changes between validation and connection.

Do not resolve a hostname, approve one IP, then let the HTTP client independently resolve it again without enforcing the same policy. The connection must use a validated destination while preserving hostname and TLS certificate verification. Network egress restrictions provide another layer; they are not a substitute for application controls.

OWASP’s SSRF Prevention Cheat Sheet explains these trade-offs. Validate them using controlled destinations in an authorized test environment, not by probing unrelated internal services.

§ 5Example 4: One credit, two redemptions

Some failures are easiest to understand as an interleaving rather than as a single request. Imagine a one-use credit with this implementation:

javascript
1export async function redeem(creditId, user) {2  const credit = await credits.get(creditId);3  if (credit.used) throw new Error("Already redeemed");4  await balances.add(user.id, credit.amount);5  await credits.markUsed(creditId);6}

Assume ownership has already been checked, and these operations have no shared transaction or uniqueness constraint. Each call looks correct in isolation. Two calls can both read used = false before either marks the credit used.

A possible concurrent execution

Diagram
Two requests redeem one unused creditRequests A and B both read an unused credit before either marks it used, allowing two balance effects without atomic coordination.RequestBCreditRequestARequestBCreditRequestACredit applied twiceReadunusedReadunusedApply creditMark usedApply creditMark used

Figure 3. One possible interleaving when check and mutation are not atomic. A sequential test would not exercise this overlap.

A reviewer can identify the non-atomic read-check-write pattern. A controlled runtime test can establish whether the deployed path permits duplicate effects under the tested conditions. Record the ledger or balance change: two successful HTTP responses alone do not prove double redemption.

The fix must cover the whole invariant. Claiming the credit and applying its balance effect must succeed together or leave neither effect behind. Depending on the architecture, that may mean a transaction with an appropriate lock, a conditional update plus an atomic ledger write, or a uniquely constrained redemption record. Merely wrapping the original statements in a transaction is not necessarily sufficient; isolation and lock behavior matter.

If an external service performs the effect, design durable delivery and provider-side deduplication as well. An in-process lock cannot coordinate several application instances, and different client-supplied idempotency keys must not allow the same credit to be spent twice.

This pattern falls under CWE-362: Concurrent Execution using Shared Resource with Improper Synchronization. A failed attempt to reproduce it does not establish that the race is impossible; concurrency, latency, and deployment topology affect the result.

§ 6Where each method has the advantage

The distinction is visibility, not a permanent division of bug classes.

Security concern What code review contributes What runtime testing contributes
Hidden branches and feature flags Enumerates conditions and bypass paths Establishes whether those paths are reachable in the tested build
Authorization and tenant isolation Traces policy placement and object access Exercises a role, resource, and tenant matrix with real identities
Payment and workflow invariants Follows state and value across operations Compares observable effects with payment and application records
Error handling and outbound requests Reveals fallthrough, unsafe fallback, and validation gaps Exercises controlled failures and observes network policy
Signing and cryptographic usage Checks message encoding, key handling, and verification logic Tests tampering, replay, and interoperability of reachable paths
Concurrency Finds missing atomicity and coordination Tests overlapping execution and measures resulting state
Gateway, cookie, CORS, and TLS behavior Reviews supplied deployment and infrastructure configuration Checks the effective behavior after proxies and edge rules
External integrations Identifies assumptions in adapters and callbacks Observes actual authentication, retries, and failure behavior

Source review can include infrastructure-as-code and deployment configuration when those are in scope. It cannot establish that the reviewed configuration is what is running. Conversely, a runtime test observes a particular environment and time window, not every future deployment.

§ 7A code-assisted assessment workflow

The strongest connection between the two methods is a feedback loop: code suggests a test; the result sends the reviewer back to the implementation. Do not save runtime validation until after a long, untriaged list of suspicious code has accumulated.

Diagram
Code-assisted security assessment workflowScope the assessment, map boundaries, review code, test at runtime, correlate effects, fix the root cause, and retest. New evidence returns to code review.

New evidence

Scope assets and safety limits

Map boundaries and roles

Review high-risk code

Test the hypothesis

Correlate code and effects

Fix the shared root cause

Retest behavior and siblings

Figure 4. An assessment workflow, not a claim of exhaustive coverage. Repeat the review-and-test loop around the highest-risk paths.

  1. Agree the scope and safety boundaries. Record the source revision, deployed build, environments, allowed techniques, third-party restrictions, rate limits, and stop conditions. Prefer a representative staging environment for destructive and concurrency scenarios.
  2. Prepare identities and state. Supply accounts for the relevant roles and tenants, controlled test records, expired or revoked sessions, payment sandboxes, and permitted log access. Missing access is a coverage limitation to report, not conceal.
  3. Map critical paths. Prioritize identity, authorization, money movement, sensitive data, administrative actions, outbound requests, and asynchronous jobs. Write the invariant before testing it: “one credit produces at most one balance effect.”
  4. Turn code observations into falsifiable tests. State the prerequisite, action, expected control, and evidence that would show it failed. Distinguish a suspicious pattern from a reproduced finding.
  5. Correlate the evidence. Join code references with requests, timestamps, request IDs, and persisted state. If staging differs from production, state which conclusions transfer and which remain unverified.
  6. Fix and retest beyond the original endpoint. Review shared helpers and sibling callers, repeat the original scenario, check legitimate behavior, and add regression coverage for the repaired invariant.

What a useful finding contains

A finding should let an engineer reproduce the issue and understand its boundaries without reconstructing the assessment:

  • Context: affected build, endpoint or job, role, tenant, and prerequisites.
  • Root cause: file and function, relevant branch, and the security invariant it violates.
  • Evidence: minimal reproduction plus the observed response, state change, or controlled callback.
  • Impact and limits: what was demonstrated, what remains inferred, and what was not tested.
  • Remediation and retest: the shared control to repair, related paths checked, and evidence that the behavior changed.

§ 8How to choose for your next release

Start with source review when the immediate uncertainty is in a new authorization model, payment workflow, parser, signing implementation, or other security-sensitive logic. It can expose design and implementation problems before a representative environment is ready. Add runtime validation when the path can be exercised.

Start with dynamic testing when you need evidence about the attack surface of a deployed release, do not have source access, or suspect a proxy, identity-provider, or configuration issue. Document inaccessible roles and paths so the report does not imply coverage that was never possible.

Plan both around critical workflows when a release handles money, identity, tenant boundaries, or sensitive records. Source access makes tests more targeted; runtime evidence checks the assumptions in the source. If the budget is constrained, jointly select the highest-risk workflows rather than promise shallow coverage of everything.

Before you scope the work

  • Which release decision must the assessment inform?
  • Can the reviewed source revision be matched to the tested deployment?
  • Which roles, tenants, integrations, and background jobs are included?
  • Can testers observe persisted state and safely exercise failure and concurrency cases?
  • Will the deliverable separate confirmed behavior, code-only findings, assumptions, and coverage gaps?
  • Is retesting included after remediation?

The goal is not two reports. It is a defensible account of what can fail, why it fails, and whether the fix holds.

For help matching that scope to a release, explore source code auditing, read how we run a penetration test, or request a scoping call.

§ 9References

These sources support the testing and defensive principles in this article; they are not the origin of its teaching examples.

Further reading.

Related service

Source Code Auditing

We read application source line by line for vulnerabilities that dynamic testing and scanners miss.

Request a scoping call
Next up
§ 02 — Next step

Who should we prepare your report for?

Type your company name to see it on the report cover and the scoping worksheet underneath. Hover over the cover to lift it.Tap the cover to lift it.

CyberSib
Security Assessment Report
Prepared for
Your company
ScopeDefined at kickoff
Light box · auditor view · press X to exit