Back
+20 XP
Concept

Zero-Trust Architecture: Token Introspection

Zero-Trust replaces perimeter security with continuous cryptographic verification ("never trust, always verify"). Microservices reject requests based on caller IP addresses, demanding cryptographically signed capability tokens containing explicit subject identities, scopes, and expiration bounds 🛡️🔐.

python
import hmac
import hashlib
import json
import base64

KEY = b"mesh_token_signing_secret"

def inspect_claims(token):
    b64_payload, signature = token.split(".")
    raw_json = base64.urlsafe_b64decode(b64_payload.encode() + b"==")

    # Constant-time signature verification:
    expected = hmac.new(KEY, raw_json, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(signature, expected):
        raise PermissionError("Forged capability token! 🛑")

    return json.loads(raw_json.decode())

# Example capability token:
claims = {"sub": "svc-payments", "scope": "write:charges"}
data = json.dumps(claims).encode()
tok = f"{base64.urlsafe_b64encode(data).decode().rstrip('=')}.{hmac.new(KEY, data, hashlib.sha256).hexdigest()}"

print(f"Verified scope: {inspect_claims(tok)['scope']} 🚀")

# 74. Zero-Trust Architecture: Token Introspection In legacy "castle-and-moat" architectures, developers placed a firewall at the edge and allowed all internal microservices to communicate without authentication. If an attacker penetrated a single web container via an SSRF vulnerability, the entire cluster fell like dominoes 🛑. ```python # The Castle-and-Moat Failure: # Hacker breaches public container -> sends raw HTTP to payment-service:8080 # Payment service checks IP -> "It's from 10.0.0.12! Trusted!" -> Drains funds! ``` ### The Zero-Trust Pillars 1. **Never Trust, Always Verify**: Network locality never confers authority. A request from the local container on `localhost` is treated with the exact same skepticism as a request from an untrusted public internet IP. 2. **Cryptographic Capability Tokens**: Every RPC call transmits a cryptographically signed token containing identity claims (`sub`), authorized operations (`scope`), and short-lived expiry (`exp`). 3. **Least Privilege Enforcement**: Receiving services inspect the token claims at runtime. If a reporting service attempts to execute `DELETE /customers`, the service rejects the request immediately regardless of network origin 🛡️🔐. --- ### Interactive Pop-Quiz 🧠 #### What is the foundational philosophy behind Zero-Trust network architecture? - [ ] Assume the internal network is hostile; continuously authenticate and authorize every request explicitly 🛡️ - [ ] Allow any device on the office WiFi to access production databases without passwords - [ ] Disable TLS encryption to maximize network throughput across data centers - [ ] Trust all internal microservices whose IP addresses begin with 10.0.0.x --- ### Practical Challenge 🎯 Implement `introspect(token, secret)` that splits `b64_data.signature`, validates the HMAC-SHA256 signature, decodes the JSON payload, and returns the claims dict. Raise `PermissionError('Invalid token')` if the signature is invalid. Test with a signed token for `{'app': 'gateway', 'access': 'granted'}`. Assert `claims['app'] == 'gateway'`, and print `'ZERO_TRUST_OK'`. <details> <summary>Solution</summary> ```python import hmac import hashlib import json import base64 def introspect(token, secret): b64_part, sig = token.split(".") raw = base64.urlsafe_b64decode(b64_part.encode() + b"==") expected = hmac.new(secret, raw, hashlib.sha256).hexdigest() if not hmac.compare_digest(sig, expected): raise PermissionError("Invalid token") return json.loads(raw.decode()) secret = b"SECRET_KEY_99" payload = {"app": "gateway", "access": "granted"} raw_bytes = json.dumps(payload).encode() b64_data = base64.urlsafe_b64encode(raw_bytes).decode().rstrip("=") signature = hmac.new(secret, raw_bytes, hashlib.sha256).hexdigest() token = f"{b64_data}.{signature}" claims = introspect(token, secret) assert claims["app"] == "gateway" print("ZERO_TRUST_OK") ``` </details>

Checkpoint

What is the foundational philosophy behind Zero-Trust network architecture? 🧠

Practice

Implement `introspect(token, secret)` that splits `b64_data.signature`, validates the HMAC-SHA256 signature, decodes the JSON payload, and returns the claims dict. Raise `PermissionError('Invalid token')` if the signature is invalid. Test with a signed token for `{'app': 'gateway', 'access': 'granted'}`. Assert `claims['app'] == 'gateway'`, and print `'ZERO_TRUST_OK'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks