Content Security Policy (CSP) in Cybersecurity - Time & Space Complexity
Analyzing how Content Security Policy (CSP) processes rules helps us understand how it affects website security checks.
We want to know how the time to check CSP rules grows as the number of rules or resources increases.
Analyze the time complexity of the following CSP rule checking process.
// Simplified CSP check for resource loading
function checkCSP(resource, cspRules) {
for (let rule of cspRules) {
if (resource.type === rule.type && resource.url.startsWith(rule.source)) {
return true; // Allowed by this rule
}
}
return false; // No matching rule found
}
This code checks if a resource is allowed by comparing it against each CSP rule until a match is found.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all CSP rules to find a match.
- How many times: Up to once per rule, until a match is found or all rules checked.
As the number of CSP rules grows, the time to check a resource grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 rule checks |
| 100 | Up to 100 rule checks |
| 1000 | Up to 1000 rule checks |
Pattern observation: Doubling the number of rules roughly doubles the checks needed.
Time Complexity: O(n)
This means the time to check a resource grows linearly with the number of CSP rules.
[X] Wrong: "Checking CSP rules happens instantly no matter how many rules there are."
[OK] Correct: Each rule must be checked one by one until a match is found, so more rules mean more checks and more time.
Understanding how CSP rule checks scale helps you explain security feature performance clearly and confidently.
"What if CSP rules were stored in a hash map by resource type? How would the time complexity change?"