惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cisco Talos Blog
Cisco Talos Blog
L
Lohrmann on Cybersecurity
AWS News Blog
AWS News Blog
J
Java Code Geeks
博客园_首页
Scott Helme
Scott Helme
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
T
The Exploit Database - CXSecurity.com
Security Latest
Security Latest
V
Visual Studio Blog
Cloudbric
Cloudbric
Jina AI
Jina AI
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
A
Arctic Wolf
C
Cybersecurity and Infrastructure Security Agency CISA
S
SegmentFault 最新的问题
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
W
WeLiveSecurity
K
Kaspersky official blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hacker News: Ask HN
Hacker News: Ask HN
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
量子位
Google Online Security Blog
Google Online Security Blog
博客园 - Franky
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 三生石上(FineUI控件)
Recent Commits to openclaw:main
Recent Commits to openclaw:main

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Part 5 — Multi-tenant auth and routing in Kubernetes
Akarshan Gan · 2026-05-05 · via DEV Community

In the first four chapters of this series I've talked about what the Auth Gateway decides. This chapter is about who it decides for.

We run a multi-tenant platform. Every request, on every endpoint, belongs to one tenant. Get tenant resolution wrong and you don't have a security incident — you have a cross-tenant data leak incident, which is a category of bad you don't recover from.

This chapter is the boring, careful, paranoid story of how NGINX and the Auth Service cooperate to never let a request through without a clear tenant identity.

The two questions

Every multi-tenant request raises two questions:

  1. Which tenant is this for? (resolution)
  2. Where does the request go for that tenant? (routing)

We answer #1 at the NGINX layer, before auth. We answer #2 partly at NGINX (path-based routing) and partly inside the upstream service (tenant-scoped queries). The Auth Service sits between them: it makes sure the token's tenant matches the request's tenant before either service sees the request.

Resolution: two valid inputs, one explicit failure mode

We accept two ways to identify a tenant:

  • X-Tenant-ID header. Explicit. Used by service-to-service calls and SDKs that know who they're for.
  • Host header (mapped via X-Tenant-Host). Implicit. Used by per-tenant DNS like tenant1.example.com.

We do not accept a third way: a default tenant. There is no fallback. If both inputs are missing or unknown, NGINX returns 400 before the Auth Service is even called.

Why so strict? Because a default tenant is the most expensive bug you can ship. Every "wait why is data showing up in tenant X?" post-mortem starts the same way: somebody added a fallback "for convenience" and somebody else's request hit it without a tenant header.

We removed our default tenant on day 90 and have never looked back.

Per-tenant SNI server blocks

For tenants with their own DNS, NGINX uses server blocks to short-circuit resolution. The Helm chart templates one server per tenant from global.tenants:

{{- range .Values.global.tenants }}
server {
  listen {{ $.Values.containers.containerPort }};
  server_name {{ .tenant_dns }};

  set $tenant_id        {{ .tenant_id }};
  set $tenant_namespace {{ .tenant_namespace }};

  include /etc/nginx/auth.conf;
  include /etc/nginx/locations.conf;
  include /etc/nginx/custom_error_locations.conf;
}
{{- end }}

Enter fullscreen mode Exit fullscreen mode

A request to tenant1.example.com matches server_name tenant1.example.com, lands in this block, and $tenant_id is already set before any other directive runs. There is no header parsing, no map lookup, no opportunity for ambiguity. Tenant identity is pinned at SNI time.

This is also nice for TLS: the per-tenant ingress can attach per-tenant certificates if you want them, and the SNI selection happens before any HTTP processing.

The default server block: header-based fallback

Not every tenant has its own DNS. Many service-to-service calls hit a shared in-cluster ingress with X-Tenant-ID set explicitly. For those, the default server block handles resolution:

server {
  listen {{ .Values.containers.containerPort }};
  server_name _;                            # match anything not matched above

  set $tenant_id "";

  if ($http_x_tenant_id) {
    set $tenant_id $http_x_tenant_id;       # priority 1
  }

  if ($tenant_id = "") {
    set $tenant_id $tenant_id_from_host;    # priority 2: map of X-Tenant-Host
  }

  if ($tenant_id = "") {
    return 400 "Tenant not specified";      # priority 3: hard fail
  }

  include /etc/nginx/auth.conf;
  include /etc/nginx/locations.conf;
  include /etc/nginx/custom_error_locations.conf;
}

Enter fullscreen mode Exit fullscreen mode

$tenant_id_from_host is a map populated from the same global.tenants list:

map $http_x_tenant_host $tenant_id_from_host {
  {{- range .Values.global.tenants }}
  "{{ .tenant_dns }}" "{{ .tenant_id }}";
  {{- end }}
}

Enter fullscreen mode Exit fullscreen mode

A few subtleties worth highlighting:

  • The order matters. Header beats host. We picked header priority because programmatic clients should be explicit.
  • $tenant_id_from_host defaults to empty string if the host isn't in the map. We then 400 — same as if the header was missing entirely.
  • if directives in NGINX are deeply weird. We confined them to this block and resisted the temptation to put ifs anywhere else in the config.

Tenant binding inside the JWT

Once NGINX has set $tenant_id, it forwards it as X-Tenant-ID to the Auth Service. But the token also carries a tenant claim. The Auth Service must check they match:

if userToken.TenantID != log.TenantID {
    c.fail(ctx, log, 401, ReasonTenantMismatch, "tenant mismatch")
    return
}

Enter fullscreen mode Exit fullscreen mode

This is the line that saves you when a malicious actor copies a token from tenant A and replays it against tenant B's hostname. The token signature is valid. The token isn't expired. The token isn't revoked. But the tenant in the token is tenantA and the request is for tenantB. We 401.

Three things make this work:

  1. The token is bound to a tenant at issuance. Our token issuer puts tid: "tenantA" in the JWT claims when it mints the token. We sign with the per-tenant RSA key (Chapter 3), so a token from tenant A can't be re-signed for tenant B without the private key.
  2. The gateway picks the verification key by X-Tenant-ID. If the request says it's for tenant B, we verify the token's signature with tenant B's public key. A tenant A token signed with tenant A's key fails signature validation, not tenant binding — but either way it's denied.
  3. The tenant claim is also checked. Even if the keys were the same, the explicit userToken.TenantID != log.TenantID check would catch reuse.

Belt and suspenders. We've never regretted having both.

Sequence: tenant flow end-to-end

Routing: MT vs ST upstreams

Once we know the tenant, we have to route the request. We have two upstream models:

  • MT (multi-tenant) services. One deployment, serves all tenants. Tenant comes in as X-Tenant-ID, the service queries data with WHERE tenant_id = ?.
  • ST (single-tenant) services. One deployment per tenant, in the tenant's own Kubernetes namespace. The service doesn't even need to know about other tenants — it can't see them.

This is purely a per-service architectural choice. Some products are happy with MT; some have stricter isolation requirements (or run heavy per-tenant data) and want ST.

The location loop in locations.conf handles both with one branch:

proxy_pass http://{{ if eq $type "ST" }}{{ $serviceDict.SERVICE_HOST }}.$tenant_namespace.svc.cluster.local{{ else }}{{ $serviceDict.SERVICE_HOST }}{{ end }};

Enter fullscreen mode Exit fullscreen mode

Unrolled:

  • MT: proxy_pass http://user-service — the bare service name. CoreDNS resolves it to the service's ClusterIP in whatever namespace the gateway lives in.
  • ST: proxy_pass http://api-service.tenant1-ns.svc.cluster.local — the FQDN includes the tenant namespace. Each tenant has its own copy of the service in their own namespace.

A few subtleties:

  • For ST, the tenant namespace is part of the DNS name. NGINX's resolver kicks in at request time, not at config-load time. Adding a new tenant means deploying its services in tenantN-ns, then adding it to global.tenants. NGINX picks it up on the next config reload.
  • For MT, all tenants hit the same upstream IP. The upstream service is responsible for tenant scoping. We trust it because we forward X-Tenant-ID and the upstream service's auth library re-checks the header against the token's tenant. (Yes, double-checking. After the first cross-tenant near-miss, we added it.)
  • ST is more expensive operationally — N deployments of every service — but radically simpler to reason about. Two services, two answers; pick what your compliance team can defend.

Headers we propagate to upstream

After auth passes, NGINX sends a defined set of headers to the upstream. From locations.conf:

proxy_set_header X-Identity-ID       $identity_id;
proxy_set_header X-Identity-Type     $identity_type;
proxy_set_header X-Identity-Name     $identity_name;
proxy_set_header X-Session-ID        $session_id;
proxy_set_header X-Tenant-ID         $tenant_id;
proxy_set_header X-Tenant-Namespace  $tenant_namespace;
proxy_set_header X-Request-ID        $request_id;

Enter fullscreen mode Exit fullscreen mode

The upstream contract:

  • X-Identity-ID is the principal. Treat it as the user's primary key.
  • X-Identity-Type is USER or SERVICE_ACCOUNT. Some endpoints reject service accounts, some require them.
  • X-Tenant-ID is the tenant. Always scope queries by it.
  • X-Tenant-Namespace is the Kubernetes namespace, useful for diagnostics and per-tenant Kafka topic naming.
  • X-Session-ID is an opaque session correlation ID. Useful for logging, never for auth.
  • X-Request-ID is the trace correlation ID. Forward it to your downstream calls so the whole graph stitches together.

We do not forward Authorization. The upstream service has no business looking at the JWT. If it needs to know who's calling, it uses X-Identity-ID. If it needs to make a downstream call, it gets a fresh service-account token — it does not replay the user's token.

Stripping Authorization was one of those changes that everyone agrees is a great idea in principle and fights tooth-and-nail when their service breaks during the rollout. Worth the fight.

Skipping tenant for a few endpoints

A handful of endpoints genuinely don't have a tenant: NGINX /healthz, public OAuth callbacks, JWKS endpoints, version probes. For these, tenant resolution must not run.

In NGINX:

location /healthz {
  access_log off;
  return 204;
}

Enter fullscreen mode Exit fullscreen mode

This location is matched before the tenant-resolving if block in the default server, because NGINX processes more-specific locations first. /healthz returns 204 without ever evaluating $tenant_id.

Inside the Auth Service, the equivalent pattern shows up: the trie has rows with endpoint_type=OPEN and no tenant requirement. Even if NGINX did pass through, the Auth Service would allow without checking the tenant. Belt and suspenders again.

The Ingress regex: another layer of opt-in

Our cluster's Ingress controller routes some paths through the Auth Gateway and some paths around it. The chart's multi-tenant Ingress uses a negative-lookahead regex to express "send everything to NGINX except these specific exempt paths":

- path: "/(?!{{ $exemptedPattern }}).*"
  pathType: ImplementationSpecific
  backend:
    service:
      name: {{ $shortName }}
      port:
        number: 80

Enter fullscreen mode Exit fullscreen mode

$exemptedPattern is a long alternation built from values.yaml:

ingress:
  exemptedPaths:
    - api/
    - login/
  exemptedPrefixes:
    - ui
  exemptedExtensions:
    - js
    - css
    - ico
    # ... static assets

Enter fullscreen mode Exit fullscreen mode

Anything matching the regex bypasses the gateway and goes to a legacy ingress. This is how we rolled the gateway out one service at a time — and how we keep it manageable today as services migrate at different speeds.

What we'd warn future-us about

A few real lessons:

  • Default tenants are forever. If you ship one, every subsequent design decision will assume it exists, and removing it later is a multi-quarter project.
  • Tenant-aware logging is non-negotiable. Every log line must carry tenant_id. We don't grep by user — we grep by tenant first, then narrow. Chapter 9 has the log format.
  • Keep the tenant model boring. "What is a tenant?" should have a 1-sentence answer. The moment "tenant" starts meaning different things in different services, your isolation guarantees evaporate.
  • MT and ST are different operating models, not different security models. The same auth contract should hold. If your ST services can be looser because "they're isolated anyway," you have a problem.
  • Never derive tenant from the user. "User belongs to tenant X, so I'll use tenant X" sounds reasonable until you have users in multiple tenants. The tenant comes from the request, not from the user.

What's next

Chapter 6 stays on tenant boundaries but zooms in on the authorization side: roles, access levels, the role → access-level → endpoint mapping, and the bitmap fast path that replaced our original string-set matching. We'll see why a JWT should not be the source of truth for a user's full permission set, and how to encode permissions densely enough that the gateway can decide in O(1) bitwise.