# Web Security: CORS and CSP

Web security involves protecting web applications from threats. Two fundamental browser-based security mechanisms are **CORS** (Cross-Origin Resource Sharing) and **CSP** (Content Security Policy).

## 1. CORS (Cross-Origin Resource Sharing)

CORS is a mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

### The Same-Origin Policy (SOP)
By default, browsers enforce the **Same-Origin Policy**. This prevents a malicious script on one page (e.g., `evil.com`) from obtaining access to sensitive data on another web page (e.g., `bank.com`).
*   **Origin:** Defined by Protocol + Host + Port (e.g., `https://example.com:443`).

### How CORS Works
If your frontend (`client.com`) tries to fetch data from your backend (`api.com`), the browser blocks it by default because the origins differ. To allow this, the backend must send specific HTTP headers.

*   **`Access-Control-Allow-Origin`:** Specifies which origins are allowed.
    *   `Access-Control-Allow-Origin: https://client.com` (Secure)
    *   `Access-Control-Allow-Origin: *` (Insecure, allows everyone)
*   **`Access-Control-Allow-Methods`:** Allowed HTTP methods (GET, POST, PUT).
*   **`Access-Control-Allow-Headers`:** Allowed custom headers.

### Preflight Requests
For "complex" requests (e.g., requests with custom headers or methods like PUT/DELETE), the browser first sends an `OPTIONS` request to check permissions. This is called a **Preflight Request**.

## 2. CSP (Content Security Policy)

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks.

### The Goal: Prevent XSS
XSS attacks occur when an attacker injects malicious scripts into content that is viewed by other users. CSP allows you to tell the browser: "Only execute scripts that come from these trusted domains."

### How it Works
You configure CSP by sending the `Content-Security-Policy` HTTP header from your server.

```http
Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.google.com
```

### Common Directives
*   **`default-src`:** The fallback for other directives.
*   **`script-src`:** Defines valid sources for JavaScript.
*   **`style-src`:** Defines valid sources for stylesheets.
*   **`img-src`:** Defines valid sources for images.
*   **`connect-src`:** Restricts the URLs which can be loaded using script interfaces (fetch, XHR, WebSockets).

### Example Policy
```http
Content-Security-Policy: default-src 'self'; img-src *; script-src userscripts.example.com
```
*   Images can load from anywhere (`*`).
*   Scripts can only load from `userscripts.example.com`.
*   Everything else can only load from the same origin (`'self'`).

## 3. CSRF (Cross-Site Request Forgery)

CSRF is an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated.

### The Mechanism
It relies on the fact that browsers automatically send cookies (including session IDs) with every request to a domain, even if that request originated from a different site.

*   **Example:** You are logged into your bank. You visit a malicious site that has a hidden form or image tag: `<img src="http://bank.com/transfer?to=attacker&amount=1000">`. Your browser sends the request to `bank.com` *with your session cookies*, and the bank processes the transfer.

### Prevention

1.  **Anti-CSRF Tokens:** The server generates a unique, unpredictable token that the client must include in the request (usually in a hidden form field or header). Since the attacker can't read data from the bank's site (due to SOP), they can't guess this token.
2.  **SameSite Cookies:** Setting the `SameSite` attribute on cookies helps.
    *   `SameSite=Strict`: Cookies are never sent on cross-site requests.
    *   `SameSite=Lax`: Cookies are not sent on cross-site subrequests (like images or frames), but are sent when a user navigates to the origin site (i.e., follows a link).

## 4. XSS (Cross-Site Scripting)

Cross-Site Scripting (XSS) is a vulnerability that allows an attacker to inject malicious scripts into web pages viewed by other users.

### Types of XSS

1.  **Reflected XSS (Non-Persistent):**
    The malicious script is reflected off the web server, such as in an error message or search result. The attack is delivered via a link.
    *   *Example:* A user clicks `http://example.com/search?q=<script>alert(1)</script>`. The server echoes the query back in the HTML: `You searched for: <script>alert(1)</script>`.

2.  **Stored XSS (Persistent):**
    The malicious script is permanently stored on the target server (e.g., in a database, forum post, comment field). The victim retrieves the malicious script when they view the stored content.
    *   *Example:* An attacker posts a comment: `Great post! <script>stealCookies()</script>`. Every user who views the comments executes the script.

3.  **DOM-based XSS:**
    The vulnerability exists in the client-side code rather than the server-side code. The attack payload is executed as a result of modifying the DOM "environment" in the victim's browser used by the original client-side script.
    *   *Example:* A script reads `window.location.hash` and writes it to the page using `innerHTML` without sanitization.

[[programming/cybersecurity-basics]]
[[programming/rest-apis]]
[[programming/client-vs-backend]]