{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.13.0"
    },
    "blog_metadata": {
      "topic": "If your AI platform can’t prove its keys, logs, and TLS path, it isn’t enterprise-ready",
      "slug": "if-your-ai-platform-can-t-prove-its-keys-logs-and-tls-path-i",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-10-21T12:41:54.647Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# If your AI platform can’t prove its keys, logs, and TLS path, it isn’t enterprise-ready\n",
        "\n",
        "This notebook turns the article into a hands-on validation workflow. It focuses on the three proof points that matter most for enterprise AI readiness: key custody, TLS termination and peer identity, and structured audit evidence.\n",
        "\n",
        "The goal is not to trust a platform demo or vendor PDF, but to generate observable evidence you can review, store, and repeat across environments."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install -q cryptography"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import os\n",
        "import ssl\n",
        "import json\n",
        "import uuid\n",
        "import socket\n",
        "import hashlib\n",
        "import logging\n",
        "from pprint import pprint\n",
        "from datetime import datetime, timezone\n",
        "from textwrap import dedent"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Start with the path, not the promise\n",
        "\n",
        "Before validating controls, document the request path. Enterprise readiness depends on the supporting control plane around the model: secrets or KMS, certificate validation, and immutable audit storage.\n",
        "\n",
        "The next cell captures the architecture sketch from the article in a machine-readable form so you can inspect or adapt it."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "architecture = {\n",
        "    \"nodes\": [\n",
        "        \"Client App\",\n",
        "        \"API Gateway\",\n",
        "        \"TLS Termination\",\n",
        "        \"AI Platform\",\n",
        "        \"Secrets Store / KMS\",\n",
        "        \"Central Log Pipeline\",\n",
        "        \"Certificate Chain + OCSP/CRL\",\n",
        "        \"Immutable Audit Store\",\n",
        "        \"Enterprise Readiness\"\n",
        "    ],\n",
        "    \"edges\": [\n",
        "        [\"Client App\", \"API Gateway\"],\n",
        "        [\"API Gateway\", \"TLS Termination\"],\n",
        "        [\"TLS Termination\", \"AI Platform\"],\n",
        "        [\"AI Platform\", \"Secrets Store / KMS\"],\n",
        "        [\"AI Platform\", \"Central Log Pipeline\"],\n",
        "        [\"TLS Termination\", \"Certificate Chain + OCSP/CRL\"],\n",
        "        [\"Central Log Pipeline\", \"Immutable Audit Store\"],\n",
        "        [\"Enterprise Readiness\", \"Secrets Store / KMS\"],\n",
        "        [\"Enterprise Readiness\", \"Central Log Pipeline\"],\n",
        "        [\"Enterprise Readiness\", \"Certificate Chain + OCSP/CRL\"]\n",
        "    ]\n",
        "}\n",
        "\n",
        "print(json.dumps(architecture, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Prove the TLS path with your own hands\n",
        "\n",
        "This example performs a real TLS handshake to a remote endpoint and captures the negotiated TLS version, cipher suite, peer subject, issuer, and SANs. This is the minimum evidence needed to answer what certificate and peer identity were actually observed at validation time.\n",
        "\n",
        "You can rerun this after network, proxy, gateway, or connector changes."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "host = \"api.openai.com\"\n",
        "port = 443\n",
        "\n",
        "ctx = ssl.create_default_context()\n",
        "with socket.create_connection((host, port), timeout=5) as sock:\n",
        "    with ctx.wrap_socket(sock, server_hostname=host) as tls:\n",
        "        cert = tls.getpeercert()\n",
        "        print(\"TLS version:\", tls.version())\n",
        "        print(\"Cipher:\", tls.cipher())\n",
        "        print(\"Peer subject:\")\n",
        "        pprint(cert.get(\"subject\"))\n",
        "        print(\"Issuer:\")\n",
        "        pprint(cert.get(\"issuer\"))\n",
        "        print(\"SANs:\")\n",
        "        pprint(cert.get(\"subjectAltName\"))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Sequence the evidence chain\n",
        "\n",
        "The article also describes the operational sequence: retrieve a secret, log only a fingerprint, perform a TLS handshake, log certificate details, send the request, and log the outcome. The next cell models that sequence as structured data so teams can align runbooks and evidence collection."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "sequence = [\n",
        "    {\"step\": 1, \"actor\": \"App\", \"target\": \"KMS/Secrets\", \"action\": \"Fetch API key / signing secret\"},\n",
        "    {\"step\": 2, \"actor\": \"KMS/Secrets\", \"target\": \"App\", \"action\": \"Return secret material\"},\n",
        "    {\"step\": 3, \"actor\": \"App\", \"target\": \"Audit Log\", \"action\": \"Log key fingerprint only\"},\n",
        "    {\"step\": 4, \"actor\": \"App\", \"target\": \"TLS Endpoint\", \"action\": \"Start TLS handshake\"},\n",
        "    {\"step\": 5, \"actor\": \"TLS Endpoint\", \"target\": \"App\", \"action\": \"Return cert chain + negotiated cipher\"},\n",
        "    {\"step\": 6, \"actor\": \"App\", \"target\": \"Audit Log\", \"action\": \"Log cert thumbprint + TLS version\"},\n",
        "    {\"step\": 7, \"actor\": \"App\", \"target\": \"AI Platform\", \"action\": \"Send request with correlation ID\"},\n",
        "    {\"step\": 8, \"actor\": \"AI Platform\", \"target\": \"App\", \"action\": \"Return response\"},\n",
        "    {\"step\": 9, \"actor\": \"App\", \"target\": \"Audit Log\", \"action\": \"Log outcome, latency, principal\"}\n",
        "]\n",
        "\n",
        "for item in sequence:\n",
        "    print(f\"{item['step']}. {item['actor']} -> {item['target']}: {item['action']}\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Required environment variables\n",
        "\n",
        "The next example reads a secret from the environment.\n",
        "\n",
        "Required variables:\n",
        "- `OPENAI_API_KEY`: API key or placeholder secret used only to demonstrate safe fingerprinting\n",
        "\n",
        "Important: this notebook logs only a short fingerprint and key length, never the raw secret."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Prove key custody without leaking the key\n",
        "\n",
        "This example demonstrates a safe pattern for proving a secret was present and which version was likely in use, without exposing the secret itself. It emits a short SHA-256-derived fingerprint and the key length for correlation during a request window."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "logging.basicConfig(level=logging.INFO, format=\"%(message)s\", force=True)\n",
        "\n",
        "api_key = os.environ.get(\"OPENAI_API_KEY\", \"\")\n",
        "if not api_key:\n",
        "    raise SystemExit(\"OPENAI_API_KEY is not set\")\n",
        "\n",
        "fingerprint = hashlib.sha256(api_key.encode()).hexdigest()[:12]\n",
        "logging.info(\"api_key_present=true api_key_fingerprint=%s\", fingerprint)\n",
        "logging.info(\"api_key_length=%d source=environment\", len(api_key))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Emit structured audit logs\n",
        "\n",
        "Prompt logs and latency metrics are not enough for governance. The next example emits a structured audit event with a timestamp, correlation ID, principal, key fingerprint, TLS peer, and a redaction-safe prompt reference."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "logging.basicConfig(level=logging.INFO, format=\"%(message)s\", force=True)\n",
        "\n",
        "event = {\n",
        "    \"ts\": datetime.now(timezone.utc).isoformat(),\n",
        "    \"event\": \"ai_request_authorized\",\n",
        "    \"correlation_id\": str(uuid.uuid4()),\n",
        "    \"principal\": \"svc-ai-gateway\",\n",
        "    \"key_fingerprint\": \"a1b2c3d4e5f6\",\n",
        "    \"tls_peer\": \"CN=api.openai.com\",\n",
        "    \"prompt_sha256\": \"redacted-or-hashed-only\",\n",
        "}\n",
        "logging.info(json.dumps(event, separators=(\",\", \":\")))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Enforce minimum TLS version and capture a certificate fingerprint\n",
        "\n",
        "This example strengthens the TLS validation by enforcing a minimum TLS version and computing the SHA-256 fingerprint of the leaf certificate presented by the remote peer. If you provide an expected fingerprint, the code can also fail closed on mismatch."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "host = \"api.openai.com\"\n",
        "expected_thumbprint = \"REPLACE_WITH_REAL_SHA256_CERT_FINGERPRINT\"\n",
        "\n",
        "ctx = ssl.create_default_context()\n",
        "ctx.minimum_version = ssl.TLSVersion.TLSv1_2\n",
        "\n",
        "with socket.create_connection((host, 443), timeout=5) as sock:\n",
        "    with ctx.wrap_socket(sock, server_hostname=host) as tls:\n",
        "        der = tls.getpeercert(binary_form=True)\n",
        "        actual = hashlib.sha256(der).hexdigest().upper()\n",
        "        print(\"tls_version=\", tls.version())\n",
        "        print(\"cert_sha256=\", actual)\n",
        "        if expected_thumbprint != \"REPLACE_WITH_REAL_SHA256_CERT_FINGERPRINT\" and actual != expected_thumbprint:\n",
        "            raise SystemExit(\"Certificate pin mismatch\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Create a tamper-evident audit record\n",
        "\n",
        "A proper immutable logging pipeline is still required, but you can make event integrity visible by hashing the serialized event payload and storing the record hash alongside the event. This makes basic tamper evidence testable during validation."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "event = {\n",
        "    \"ts\": datetime.now(timezone.utc).isoformat(),\n",
        "    \"event\": \"tls_verified\",\n",
        "    \"correlation_id\": str(uuid.uuid4()),\n",
        "    \"principal\": \"svc-ai-gateway\",\n",
        "    \"tls_version\": \"TLS1.2+\",\n",
        "    \"cert_thumbprint\": \"ABCD1234EF567890\"\n",
        "}\n",
        "\n",
        "payload = json.dumps(event, separators=(\",\", \":\"), sort_keys=True)\n",
        "record_hash = hashlib.sha256(payload.encode(\"utf-8\")).hexdigest().upper()\n",
        "event[\"record_hash\"] = record_hash\n",
        "\n",
        "print(json.dumps(event, separators=(\",\", \":\"), indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Evidence standard checklist\n",
        "\n",
        "Use this checklist as the scale gate for any production AI pattern:\n",
        "\n",
        "1. Key ownership: who owns, uses, rotates, recovers, and break-glass approves the credential.\n",
        "2. Authorized access paths: which identities call which services through which gateways or connectors.\n",
        "3. Transport map: where TLS terminates, where traffic is inspected, and where it is re-encrypted.\n",
        "4. Logging sources: which systems emit authoritative events for identity, policy, gateway, tool use, backend access, and operator action.\n",
        "5. Retention and integrity: how long logs are retained, where immutable copies live, and how tampering is detected.\n",
        "6. Named operators: which team owns runtime operations, incident response, and exception approval."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "control_evidence_packet = {\n",
        "    \"key_ownership\": {\n",
        "        \"owner\": None,\n",
        "        \"authorized_users\": [],\n",
        "        \"rotators\": [],\n",
        "        \"recoverers\": [],\n",
        "        \"break_glass_path\": None\n",
        "    },\n",
        "    \"authorized_access_paths\": [],\n",
        "    \"transport_map\": {\n",
        "        \"tls_termination_points\": [],\n",
        "        \"inspection_points\": [],\n",
        "        \"re_encryption_hops\": [],\n",
        "        \"expected_certificates\": []\n",
        "    },\n",
        "    \"logging_sources\": {\n",
        "        \"identity\": [],\n",
        "        \"policy\": [],\n",
        "        \"gateway\": [],\n",
        "        \"tool_use\": [],\n",
        "        \"backend_access\": [],\n",
        "        \"operator_intervention\": []\n",
        "    },\n",
        "    \"retention_and_integrity\": {\n",
        "        \"retention_days\": None,\n",
        "        \"immutable_store\": None,\n",
        "        \"tamper_detection\": []\n",
        "    },\n",
        "    \"named_operators\": {\n",
        "        \"runtime_ops\": None,\n",
        "        \"incident_response\": None,\n",
        "        \"exception_approval\": None\n",
        "    }\n",
        "}\n",
        "\n",
        "print(json.dumps(control_evidence_packet, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "This notebook validated the core claim of the article: enterprise AI readiness is a proof problem, not a demo problem. You inspected a live TLS peer, generated a safe secret fingerprint, emitted structured audit events, and created a tamper-evident record shape.\n",
        "\n",
        "## Next Steps\n",
        "\n",
        "- Run the TLS checks against every gateway, proxy, private endpoint, and model endpoint in your real path.\n",
        "- Replace placeholder identities and fingerprints with environment-specific values from your platform.\n",
        "- Store outputs in your formal control-evidence packet for architecture review and audit readiness.\n",
        "- Correlate gateway, identity, tool, and backend logs using a shared correlation ID.\n",
        "- Make this notebook or its equivalent part of deployment validation and post-change verification."
      ]
    }
  ]
}