name: Security Baseline Controls
description: Minimum security controls every service must implement: authentication/authorization, input validation, secrets management, security headers, dependency security, audit logging, and operational guardrails
Security Baseline Controls
Overview
มาตรฐาน security ขั้นต่ำที่ทุก service ต้องมี: authentication, authorization, input validation, secrets handling, และ security headers ที่ทำให้ระบบปลอดภัยตั้งแต่ day one
Why This Matters
- Compliance: Meet SOC2, ISO27001, GDPR requirements
- Defense in depth: Multiple security layers
- Consistency: Same security posture across services
- Audit: Clear evidence of controls
Core Concepts
1. Authentication Requirements
- ทุก endpoint (ยกเว้น health) ต้องมี authentication
- validate tokens อย่างถูกต้อง: signature, issuer, audience, expiry, clock skew
- สำหรับ sessions ต้องมี: secure cookie, CSRF protection, session rotation
2. Authorization Patterns
- resource-level authorization (owner/tenant) เป็น default
- RBAC สำหรับ roles ทั่วไป, ABAC/policies สำหรับเงื่อนไขซับซ้อน (tenant tier, attributes)
- deny-by-default: ถ้าไม่มี policy/permission ให้ reject
3. Input Validation
- validate ที่ boundary: request body/query/path headers (schema-based)
- enforce limits: max size, max length, enums, number ranges
- normalize/sanitize ตามชนิดข้อมูล (เช่น trim, canonicalize emails)
4. Output Encoding
- ตั้ง
Content-Type ถูกต้องเสมอ และใช้ JSON serialization มาตรฐาน
- UI ที่ render HTML ต้อง escape/encode ตาม context (server ไม่ควรส่ง HTML ที่มี user input โดยตรง)
- หลีกเลี่ยงการสะท้อน input กลับไปใน error message โดยไม่ sanitize
5. Secrets Management
- secrets ต้องไม่อยู่ใน repo, container image, หรือ logs
- ใช้ secret manager + least privilege access (scoped identities)
- รองรับ rotation: short TTL tokens, reload without redeploy ถ้าเป็นไปได้
6. Security Headers
- เปิดใช้ HSTS บน production domains ที่รองรับ HTTPS
- ใส่ CSP ที่เหมาะสม (สำหรับ web apps) และปิด clickjacking (
X-Frame-Options/frame-ancestors)
- ตั้ง
Referrer-Policy, X-Content-Type-Options เป็น baseline
7. Dependency Security
- เปิดใช้ dependency scanning ใน CI (SCA) และกำหนด SLA ในการ patch
- pin versions และหลีกเลี่ยง
latest ใน production
- สำหรับ containers: scan base image + SBOM ถ้า platform รองรับ
8. Audit Logging
- log security-relevant events: login, token refresh, permission changes, admin actions, data export
- audit logs ต้อง immutable/append-only และเข้าถึงจำกัด
- ใส่
requestId/actorId/tenantId (ถ้ามี) และ redact PII ตาม policy
Quick Start
import helmet from "helmet";
import type { Request, Response, NextFunction } from "express";
export function securityHeaders() {
return helmet({
contentSecurityPolicy: false, // enable + tune per app (web) when ready
});
}
export function requireAuth(req: Request, res: Response, next: NextFunction) {
const auth = req.header("authorization");
if (!auth?.startsWith("Bearer ")) return res.status(401).json({ error: "Unauthorized" });
// verify token (issuer/audience/signature/expiry) here
next();
}
Production Checklist
Security Headers
// Required headers
{
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
"Content-Security-Policy": "default-src 'self'",
"Referrer-Policy": "strict-origin-when-cross-origin"
}
Input Validation Checklist
// Every user input must be:
// 1. Type-checked (string, number, etc.)
// 2. Length-limited (max characters)
// 3. Format-validated (regex, enum)
// 4. Sanitized (HTML escape, SQL escape)
const schema = z.object({
email: z.string().email().max(255),
name: z.string().min(1).max(100),
age: z.number().int().min(0).max(150)
});
Authentication Requirements
| Endpoint Type |
Auth Required |
Notes |
| Health check |
No |
/health, /ready |
| Metrics |
Optional |
Depends on exposure |
| Public API |
Yes |
Bearer token |
| Internal API |
Yes |
Service-to-service auth |
| Admin API |
Yes |
Additional MFA |
Anti-patterns
- Security as afterthought: Add security later
- Trust internal traffic: No service-to-service auth
- Log everything: Including secrets
- Ignore dependencies: Old vulnerable packages
- Over-logging: log PII/credentials แล้วค่อย “ลบทีหลัง” (ทำไม่ได้จริง)
Integration Points
- Identity providers
- Secret managers
- Security scanning tools
- SIEM systems
Further Reading
1---2name: security-baseline-controls3description: มาตรฐาน security ขั้นต่ำที่ทุก service ต้องมี: authentication, authorization, input validation, secrets handling, และ security headers ที่ทำให้ระบบปลอดภัยตั้งแต่ day one4---5
6---
7name: Security Baseline Controls
8description: Minimum security controls every service must implement: authentication/authorization, input validation, secrets management, security headers, dependency security, audit logging, and operational guardrails
9---
10
11# Security Baseline Controls
12
13## Overview
14
15มาตรฐาน security ขั้นต่ำที่ทุก service ต้องมี: authentication, authorization, input validation, secrets handling, และ security headers ที่ทำให้ระบบปลอดภัยตั้งแต่ day one
16
17## Why This Matters
18
19- **Compliance**: Meet SOC2, ISO27001, GDPR requirements
20- **Defense in depth**: Multiple security layers
21- **Consistency**: Same security posture across services
22- **Audit**: Clear evidence of controls
23
24---
25
26## Core Concepts
27
28### 1. Authentication Requirements
29
30- ทุก endpoint (ยกเว้น health) ต้องมี authentication
31- validate tokens อย่างถูกต้อง: signature, issuer, audience, expiry, clock skew
32- สำหรับ sessions ต้องมี: secure cookie, CSRF protection, session rotation
33
34### 2. Authorization Patterns
35
36- resource-level authorization (owner/tenant) เป็น default
37- RBAC สำหรับ roles ทั่วไป, ABAC/policies สำหรับเงื่อนไขซับซ้อน (tenant tier, attributes)
38- deny-by-default: ถ้าไม่มี policy/permission ให้ reject
39
40### 3. Input Validation
41
42- validate ที่ boundary: request body/query/path headers (schema-based)
43- enforce limits: max size, max length, enums, number ranges
44- normalize/sanitize ตามชนิดข้อมูล (เช่น trim, canonicalize emails)
45
46### 4. Output Encoding
47
48- ตั้ง `Content-Type` ถูกต้องเสมอ และใช้ JSON serialization มาตรฐาน
49- UI ที่ render HTML ต้อง escape/encode ตาม context (server ไม่ควรส่ง HTML ที่มี user input โดยตรง)
50- หลีกเลี่ยงการสะท้อน input กลับไปใน error message โดยไม่ sanitize
51
52### 5. Secrets Management
53
54- secrets ต้องไม่อยู่ใน repo, container image, หรือ logs
55- ใช้ secret manager + least privilege access (scoped identities)
56- รองรับ rotation: short TTL tokens, reload without redeploy ถ้าเป็นไปได้
57
58### 6. Security Headers
59
60- เปิดใช้ HSTS บน production domains ที่รองรับ HTTPS
61- ใส่ CSP ที่เหมาะสม (สำหรับ web apps) และปิด clickjacking (`X-Frame-Options`/`frame-ancestors`)
62- ตั้ง `Referrer-Policy`, `X-Content-Type-Options` เป็น baseline
63
64### 7. Dependency Security
65
66- เปิดใช้ dependency scanning ใน CI (SCA) และกำหนด SLA ในการ patch
67- pin versions และหลีกเลี่ยง `latest` ใน production
68- สำหรับ containers: scan base image + SBOM ถ้า platform รองรับ
69
70### 8. Audit Logging
71
72- log security-relevant events: login, token refresh, permission changes, admin actions, data export
73- audit logs ต้อง immutable/append-only และเข้าถึงจำกัด
74- ใส่ `requestId`/`actorId`/`tenantId` (ถ้ามี) และ redact PII ตาม policy
75
76## Quick Start
77
78```typescript
79import helmet from "helmet";
80import type { Request, Response, NextFunction } from "express";
81
82export function securityHeaders() {
83 return helmet({
84 contentSecurityPolicy: false, // enable + tune per app (web) when ready
85 });
86}
87
88export function requireAuth(req: Request, res: Response, next: NextFunction) {
89 const auth = req.header("authorization");
90 if (!auth?.startsWith("Bearer ")) return res.status(401).json({ error: "Unauthorized" });
91 // verify token (issuer/audience/signature/expiry) here
92 next();
93}
94```
95
96## Production Checklist
97
98- [ ] Authentication on all endpoints (except health)
99- [ ] Authorization checks for protected resources
100- [ ] Input validation on all user inputs
101- [ ] Security headers configured
102- [ ] Secrets from secret manager (not env/code)
103- [ ] Dependencies scanned for vulnerabilities
104- [ ] Security audit logging enabled
105
106## Security Headers
107
108```typescript
109// Required headers
110{
111 "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
112 "X-Content-Type-Options": "nosniff",
113 "X-Frame-Options": "DENY",
114 "X-XSS-Protection": "1; mode=block",
115 "Content-Security-Policy": "default-src 'self'",
116 "Referrer-Policy": "strict-origin-when-cross-origin"
117}
118```
119
120## Input Validation Checklist
121
122```typescript
123// Every user input must be:
124// 1. Type-checked (string, number, etc.)
125// 2. Length-limited (max characters)
126// 3. Format-validated (regex, enum)
127// 4. Sanitized (HTML escape, SQL escape)
128
129const schema = z.object({
130 email: z.string().email().max(255),
131 name: z.string().min(1).max(100),
132 age: z.number().int().min(0).max(150)
133});
134```
135
136## Authentication Requirements
137
138| Endpoint Type | Auth Required | Notes |
139|---------------|---------------|-------|
140| Health check | No | `/health`, `/ready` |
141| Metrics | Optional | Depends on exposure |
142| Public API | Yes | Bearer token |
143| Internal API | Yes | Service-to-service auth |
144| Admin API | Yes | Additional MFA |
145
146## Anti-patterns
147
1481. **Security as afterthought**: Add security later
1492. **Trust internal traffic**: No service-to-service auth
1503. **Log everything**: Including secrets
1514. **Ignore dependencies**: Old vulnerable packages
1525. **Over-logging**: log PII/credentials แล้วค่อย “ลบทีหลัง” (ทำไม่ได้จริง)
153
154## Integration Points
155
156- Identity providers
157- Secret managers
158- Security scanning tools
159- SIEM systems
160
161## Further Reading
162
163- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
164- [OWASP ASVS](https://owasp.org/www-project-application-security-verification-standard/)
165- [Security Headers](https://securityheaders.com/)