Hướng dẫn thử thách
1 / 1
Security and Privacy Review
## Security vs Privacy
**Security** protects data from unauthorized access, theft, and malicious damage. It builds technical defenses such as firewalls, encryption, and antivirus software to keep bad actors out of your systems.
**Privacy** controls how organizations collect, store, use, and share personal data. It gives users the power to decide who sees their information.
The two concepts are closely related but distinct:
- You can have security without privacy. A company can store your data in a highly secure database and still sell it to advertisers without your consent. In that case, security is intact, but privacy is violated.
- You cannot have true privacy without security. If a server holding private data is breached, any privacy promise is immediately broken.
Security provides the technical defense mechanism, while privacy governs the legal rights and policies around data use.
## HTTPS
**HTTP** transfers data in plain text, making it readable to anyone who intercepts it. **HTTPS** (Hypertext Transfer Protocol Secure) uses **TLS (Transport Layer Security)** to encrypt the communication channel between a browser and a server. TLS replaced the older **SSL (Secure Sockets Layer)** protocol, though many web hosting platforms still reference SSL in their settings today.
Key benefits of HTTPS:
- **Encryption:** Scrambles data into unreadable code. Only the browser and server hold the keys to decrypt it.
- **Authentication:** Requires the site owner to obtain a digital certificate from a trusted organization, proving the website is legitimate.
- **Data integrity:** Prevents anyone from altering data in transit, you receive exactly what the server sent.
- **Public Wi-Fi protection:** Creates a private tunnel through open networks, hiding your traffic from nearby attackers.
Modern browsers warn users when a site uses plain HTTP and require HTTPS for advanced features such as geolocation and push notifications.
## Same-Origin Policy and CORS
The **Same-Origin Policy (SOP)** is a browser security rule that prevents a webpage from reading data from a different origin. An **origin** consists of three parts that must all match exactly:
- **Protocol** (e.g., `https`)
- **Domain name** (e.g., `example.com`)
- **Port number** (e.g., `443`, the HTTPS default and `80`, the HTTP default)
This policy stops malicious sites opened in one browser tab from stealing data from a banking site open in another tab.
**CORS (Cross-Origin Resource Sharing)** allows servers to opt into controlled cross-origin data sharing using HTTP headers:
- The browser sends an `Origin` header with every cross-origin request.
- If the server trusts that origin, it replies with an `Access-Control-Allow-Origin` header.
- The browser then allows the response data to be read; otherwise it blocks it.
In Express, the `cors` package handles this:
```javascript
// development: allow all origins
app.use(cors());
// production: restrict to trusted domains
app.use(cors({ origin: ['https://yourapp.com', 'https://admin.yourapp.com'], credentials: true }));
```
## Cookies: Storage, Security, and Privacy
**Cookies** are small text files websites save on your device to remember information between visits. The server sends a `Set-Cookie` header; the browser stores the file and sends it back automatically on every subsequent request.
Security flags for protecting cookies:
- **`HttpOnly`:** Blocks JavaScript from reading the cookie, preventing session token theft via XSS.
- **`Secure`:** Ensures the cookie is only transmitted over HTTPS, protecting it from interception on public Wi-Fi.
- **`SameSite=Strict`:** Prevents the browser from sending the cookie on any cross-site request, blocking CSRF attacks.
- **`SameSite=Lax`:** Allows cookies on safe top-level navigation but blocks them on cross-site form submissions and API requests.
**Privacy implications:**
- **First-party cookies** track your actions only on the website you are visiting.
- **Third-party cookies** are placed by advertising networks and track you across entirely different websites, building detailed profiles of your interests.
Privacy laws like GDPR require websites to display cookie consent banners and give users the right to reject tracking cookies. Modern browsers now block third-party tracking cookies by default.
## Situations Where Security Issues Occur
Security vulnerabilities rarely happen by chance. Common triggering situations include:
- **Rushing to ship:** Development teams skip thorough code reviews and security testing to meet strict deadlines, leaving unpatched bugs and missing access controls.
- **Complex system integration:** Every external library, third-party API, or microservice adds supply chain risk. A vulnerability in one dependency spreads into the main application.
- **Poor configuration management:** Deploying servers or cloud databases using default factory settings often leaves blank admin passwords, open ports, and public data access enabled. Automated scanners hunt for these misconfigured systems.
- **Human error:** Employees targeted by phishing emails, fraudulent SMS messages, or deceptive phone calls can inadvertently expose credentials or transfer data to attackers.
- **Organizational mergers:** Connecting two different corporate networks quickly creates blind spots such as lost visibility over old servers, misconfigured firewalls, and excessive access permissions.
## Common Security Threats and Mitigations
| Threat | How it works | Mitigation |
|---|---|---|
| **Phishing** | Fraudulent emails mimic trusted brands to steal credentials | Security awareness training; email authentication protocols (SPF, DKIM, DMARC) |
| **Malware (ransomware, spyware)** | Encrypts or steals victim files; demands payment | Automated patching; antimalware software |
| **Credential stuffing** | Automated tools test millions of stolen username/password pairs across sites | Enforce multi-factor authentication (MFA) |
| **DDoS** | Floods a server with fake traffic to crash it | Cloud-based traffic filtering services (e.g., Cloudflare) |
| **Insider threats** | Disgruntled or careless employees leak or steal data | Principle of least privilege; monitor system logs for unusual access |
## Content Security Policy (CSP) and Permissions-Policy
**Content Security Policy (CSP)** is an HTTP response header that restricts which external resources a browser can load on a page. It defends primarily against **Cross-Site Scripting (XSS)** attacks by whitelisting trusted source domains for scripts, styles, and images.
If a malicious script from an unapproved domain tries to run, the browser drops it and logs a security error.
**Permissions-Policy** (formerly Feature-Policy) controls access to browser features and device hardware such as the webcam, microphone, and geolocation. You can restrict a feature to your own domain or disable it entirely:
```http
Permissions-Policy: camera=(self), geolocation=()
```
`camera=(self)`: only your own domain may access the camera.
`geolocation=()`: geolocation is disabled for everyone on the page.
Together, CSP locks down data delivery and prevents code injection; Permissions-Policy guards device hardware and enforces privacy compliance.
## Fundamental Concepts in User Privacy
| Concept | Definition |
|---|---|
| **PII (Personally Identifiable Information)** | Any data that can directly or indirectly identify a person. Direct identifiers: name, address, ID number. Indirect identifiers: IP address, device serial number, location history. |
| **Confidentiality** | Ensuring private data remains inaccessible to unauthorized parties through encryption and access controls. |
| **Data minimization** | Collect only the minimum amount of PII required to complete a specific task. |
| **Purpose limitation** | Data collected for one reason cannot legally be used for another (e.g., selling contact info to advertisers). |
| **Tracking** | Continuous monitoring of online activity using scripts, device fingerprinting, and browser history logs to build user profiles. |
| **Informed consent** | Users must actively opt in to data collection. Pre-ticked boxes do not constitute valid consent. |
| **Right to be Forgotten** | Users can legally request that an organization permanently delete all their personal data and tracking history. |
## Regional Privacy Laws
| Law | Jurisdiction | Key requirements |
|---|---|---|
| **GDPR** | European Union | Strict opt-in consent required; users have the right to access and delete their data; heavy fines for violations. |
| **CCPA / CPRA** | California, USA | Opt-out model; businesses must display a "Do Not Sell My Personal Information" link. |
| **COPPA** | USA (federal) | Verifiable parental consent required before collecting data from children under 13. |
| **DPA / UK GDPR** | United Kingdom | Lawful, fair, and transparent data processing; individuals have rights to access and deletion. |
| **NDPA** | Nigeria | Governs the collection, storage, and use of personal data of Nigerian residents. |
| **DPDP** | India | Governs how personal data of Indian residents are used. |
**Practical compliance steps:**
1. **Location-aware consent banners:** Detect the user's geographic location and display cookie banners matching local regulations.
2. **Automated DSAR system:** Handle Data Subject Access Requests to securely export or delete a user's entire data history.
3. **Data minimization and age-gating:** Collect only what is necessary and use age-verification to protect minors.
4. **Data Protection Officer (DPO):** Designate an expert to oversee privacy architecture and manage regulatory compliance.
## The `.env` File and `dotenv` Library
A **`.env` file** is a plain text file placed at the root of a project that stores sensitive configuration data as key-value pairs. These include API keys, database passwords, and port numbers. It keeps them out of source code and away from public repositories.
```bash
PORT=3000
DB_HOST=localhost
API_KEY=xyz123secretkey
```
Always add `.env` to `.gitignore` so it is never committed to version control.
The **`dotenv` package** reads the `.env` file at startup and injects the keys into `process.env`:
```javascript
require('dotenv').config();
const port = process.env.PORT || 5000;
const apiKey = process.env.API_KEY;
```
Two key benefits:
- **Security:** Sensitive credentials never appear in source code or version history.
- **Flexibility:** The same codebase runs across development, testing, and production by simply swapping the `.env` file on each server.
Nhiệm vụ của bạn
Review the security and privacy concepts covered in the lectures before taking the quiz.
Vượt qua bài kiểm tra hiện tại để mở khóa bài tiếp theo.
main.sql
UTF-8 • Tab Size: 2Kiểm tra bài:⌘↵