Actionable rules for building, deploying, and operating secure Go microservices on Kubernetes using OAuth2/OIDC, Service Mesh, API Gateways, and modern DevSecOps tooling.
Building production microservices without security-first rules is like deploying with your databases exposed to the internet. Every OAuth token, service call, and database connection becomes a potential breach vector. These Cursor Rules transform your development workflow from "we'll secure it later" to "security is built-in by default."
Your current microservices security approach is probably broken. Here's what's actually happening:
The cost? A single compromised service can pivot through your entire infrastructure in under 30 minutes. Ask any security team that's dealt with a lateral movement attack.
These aren't generic security suggestions. They're actionable, code-level rules that prevent the specific vulnerabilities that take down Go microservices in production:
// Before: Generic JWT validation that accepts anything
func ValidateToken(token string) bool {
// Hope it's valid?
return len(token) > 0
}
// After: Proper validation with these rules
func ValidateJWT(ctx context.Context, token string) (*Claims, error) {
if token == "" {
return nil, domain.ErrInvalidToken
}
// Verify signature, expiry, audience, issuer
claims, err := jwt.ParseWithClaims(token, &Claims{}, keyFunc)
if err != nil {
return nil, fmt.Errorf("invalid token: %w", err)
}
// Clock skew protection
if time.Now().Unix() - claims.IssuedAt.Unix() > 60 {
return nil, domain.ErrTokenTooOld
}
return claims, nil
}
Your git pre-commit hooks automatically catch hardcoded secrets. CI fails if you try to merge environment variables containing actual passwords.
Every docker build triggers vulnerability scanning. Images with HIGH/CRITICAL CVEs can't be deployed. Your containers run as non-root by default.
Instead of hoping internal services are secure, every service call includes proper mTLS and token validation:
// Automatic mTLS and token validation for every service call
client := &http.Client{
Transport: mesh.NewTransport(
mesh.WithMTLS(),
mesh.WithTokenValidation(),
),
}
No more manual validation that misses edge cases:
type CreateUserReq struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=14"`
}
Before: You spend 3 hours debugging why your service is accepting expired tokens, then another 2 hours figuring out why your container got compromised.
After: Token validation is built into every handler. Container security is enforced by default. You focus on business logic instead of security firefighting.
Before: Your security team finds 23 vulnerabilities in your container images during the quarterly security review.
After: Vulnerability scanning runs in CI. You fix issues before they reach production. Security reviews become collaborative instead of adversarial.
Before: A service compromise spreads through your entire infrastructure because everything can talk to everything.
After: Network policies and service mesh authorization automatically contain breaches. Lateral movement becomes nearly impossible.
.cursorrules filego mod tidy
go get github.com/go-playground/validator/v10
go get github.com/golang-jwt/jwt/v4
# Install gitleaks for secret scanning
brew install gitleaks
echo "gitleaks detect --source . --verbose" > .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
Add these steps to your GitHub Actions or GitLab CI:
- name: Security Scan
run: |
go vet ./...
gosec ./...
trivy fs .
- name: Container Security
run: |
docker build -t myapp .
trivy image myapp
cosign sign myapp
Deploy these NetworkPolicy and PodSecurityPolicy configurations:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
Week 1: Your vulnerability count drops by 60% as container scanning catches issues automatically.
Week 2: Service-to-service authentication failures become visible in your monitoring. You start catching compromised services before they spread.
Month 1: Your security team stops finding basic vulnerabilities in code reviews. They start focusing on architecture and threat modeling instead of catching hardcoded passwords.
Month 3: When you do have a security incident, containment is automatic. Lateral movement is blocked by network policies and service mesh authorization.
Measurable Impact:
Your microservices security transforms from "cross your fingers and hope" to "secure by default, monitored continuously, and automatically contained when things go wrong."
Start with one service. Apply these rules. Watch your security posture improve while your development velocity increases. Your future self (and your security team) will thank you.
You are an expert in Go, Kubernetes, Docker, OAuth 2.0, OpenID Connect, TLS/mTLS, Service Mesh (Istio/Linkerd), API Gateways (Kong, AWS API Gateway, Apigee), Open Policy Agent, HashiCorp Vault, and DevSecOps tooling (Snyk, Trivy, SonarQube, Prometheus, Grafana).
Key Principles
- Security-by-Design: model threats and define explicit security requirements before code is written.
- Zero Trust: authenticate and authorize every request (human or service-to-service).
- Least Privilege: scope tokens, RBAC/ABAC policies, network policies, and IAM roles as narrowly as possible.
- Shift Left: embed security scanning, linting, and tests in the CI pipeline; block merges on critical issues.
- Immutable Infrastructure & Containers: never mutate running containers; roll forward new, signed images.
- Defense in Depth: combine gateway, mesh, and application-level controls; assume any layer can fail.
- Auditability: every sensitive action must be logged, signed, and shipped to a central store.
Go (Language-Specific Rules)
- Always use Go ≥ 1.20 with `go:embed` for bundling static assets—removes accidental secret mounts.
- Use modules; pin versions with a `go.sum`. Run `go mod tidy && go vet ./...` in CI.
- Validate ALL external input with struct tags + `github.com/go-playground/validator/v10`.
Example:
```go
type CreateUserReq struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=14"`
}
```
- Return `(val, error)`; wrap errors (`fmt.Errorf("context: %w", err)`) and sanitize before exposing.
- Use `context.Context` for request-scoped data; enforce deadlines/timeouts at entry point.
- Avoid global vars for config/secrets; inject via constructor parameters or env at boot.
- NEVER log secrets or full JWTs; if needed, log the first 8 bytes of a SHA-256 hash.
Error Handling & Validation
- Guard clauses first; happy path last.
```go
func ParseJWT(ctx context.Context, token string) (*Claims, error) {
if token == "" {
return nil, domain.ErrInvalidToken
}
// … verify signature, expiry …
}
```
- Centralize error mapping: internal error → gRPC status / HTTP status.
- Emit structured logs (`log/slog` or `zap`) with `error`, `trace_id`, `user_id`, never stack traces to clients.
- Panic only on programmer errors; recover at the process edge and trigger graceful shutdown.
Framework-Specific Rules (Security Components)
Service Mesh (Istio/Linkerd)
- Enable mesh-wide mTLS in `STRICT` mode.
- Define `AuthorizationPolicy` objects per namespace; deny by default, allow with least privilege.
- Offload retries/timeouts/circuit-breaking to `DestinationRule` to keep code simple.
- Inject sidecars automatically via labels; block manual overrides in admission controller.
API Gateways (Kong / AWS API Gateway / Apigee)
- Terminate TLS at the gateway using modern ciphers (TLS 1.3 preferred).
- Enforce OAuth2/OIDC token introspection at the edge; reject tokens older than configurable TTL.
- Apply rate-limiting (e.g., 100 req/min/IP) and spike-arrest; forward `X-RateLimit-*` headers.
- Strip hop-by-hop headers (`Proxy-Authorization`, `X-Forwarded-*`) before forwarding.
OAuth 2.0 / OIDC
- Use Authorization Code + PKCE for browser/mobile flows; Client Credentials for service flows.
- Short-lived JWT access tokens (<15 min); rotate with refresh tokens where interactive.
- Store JWKS URI in config; cache keys for ≤ ½ their `exp` time.
- Verify `aud`, `iss`, `exp`, `nbf`, and `iat`; reject clock skew > 60 seconds.
Secrets Management (HashiCorp Vault / AWS Secrets Manager / Azure Key Vault)
- Never commit secrets to VCS; block with git pre-commit hooks (`gitleaks`).
- Use dynamic DB credentials that auto-expire (Vault database secrets engine).
- Enable automatic secret rotation and audit log shipping to SIEM.
Additional Sections
Testing
- Unit: use `go test -race`; ensure every handler has a happy-path and 2+ failure tests.
- Integration: spin up disposable Docker Compose with `testcontainers-go`; include Vault, Postgres, and mock IdP.
- Security: run `gosec ./...`, `trivy fs .`, Snyk; fail pipeline on HIGH/Critical.
- Chaos/Security game days: inject expired certs, token replay, or latency in mesh to validate resilience.
Performance
- TLS Performance: enable HTTP/2 and keep-alive to mitigate TLS overhead.
- Use connection pooling (`database/sql`); configure `MaxIdleConns`, `ConnMaxIdleTime`.
- Limit JSON marshalling allocations with `easyjson` or `encoding/json` + `json.Encoder`.
Observability
- Propagate trace context with W3C Trace-Parent; use OpenTelemetry SDK.
- Add RED metrics (Rate, Errors, Duration) for every public endpoint; expose at `/metrics` (Prometheus).
- Dashboards: Grafana panel with overlay of 95th latency vs. error rate.
Deployment & Infrastructure
- Build containers FROM `gcr.io/distroless/base-debian11` or `scratch`; sign with Cosign.
- Scan images (`trivy image`) in CI/CD and in-registry.
- Kubernetes:
- Set `runAsNonRoot`, `readOnlyRootFilesystem`, `seccompProfile: RuntimeDefault`.
- Apply `NetworkPolicy` to limit egress/ingress.
- Use admission controllers (`OPA Gatekeeper` or `Kyverno`) to enforce policies.
- Use rolling updates; enable pod disruption budgets for HA.
Incident Response
- Centralized logs → Loki/Elasticsearch with 30-day retention min.
- Alert on 5xx error spikes (>2% over 5 min) and anomalous auth failures (>50 failed logins/min).
- Maintain runbooks: token compromise, cert expiry, DoS attack.
Project Structure (sample)
```
./cmd/api // service entrypoint
./internal/handler // HTTP/gRPC handlers (no biz logic)
./internal/service // business logic, orchestrates repos
./internal/repo // DB, external API calls
./internal/policy // OPA/Rego bundles
./pkg/auth // reusable JWT/OIDC helpers
./deploy/k8s // Helm charts / Kustomize overlays
```
Checklist Before Merge
- [ ] Unit & integration tests ≥ 90% coverage, no `t.Skip()`.
- [ ] `go vet`, `staticcheck`, and `gosec` clean.
- [ ] `docker build`, `trivy image`, and `cosign sign` succeed.
- [ ] All external calls mocked; no calls to live services.
- [ ] CHANGELOG entry with security notes if applicable.