Introduction
In the wake of the Anthropic Mythos controversy involving SK Telecom, this tutorial will teach you how to build a secure AI model access control system using Python and cloud APIs. This system will help organizations manage and monitor access to their AI resources, similar to what Anthropic was doing when they revoked access to SK Telecom. You'll learn to implement authentication, authorization, and access logging for AI model endpoints.
Prerequisites
- Basic Python programming knowledge
- Understanding of REST APIs and HTTP requests
- Experience with cloud platforms (AWS, Azure, or GCP)
- Knowledge of JWT (JSON Web Tokens) for authentication
- Basic understanding of AI model deployment concepts
Step-by-Step Instructions
1. Setting Up Your Development Environment
1.1 Install Required Dependencies
First, create a virtual environment and install the necessary packages for our access control system.
python -m venv ai_access_control
source ai_access_control/bin/activate # On Windows: ai_access_control\Scripts\activate
pip install flask flask-jwt-extended requests python-dotenv
Why: We're using Flask for the web framework, JWT for secure authentication, and requests for making API calls to external services.
1.2 Create Project Structure
Set up the directory structure for our application.
mkdir ai_access_control
mkdir ai_access_control/{models,auth,controllers,utils}
touch ai_access_control/app.py ai_access_control/config.py ai_access_control/requirements.txt
Why: Organizing code into logical directories makes the system maintainable and scalable for enterprise use.
2. Configuring Authentication System
2.1 Create Configuration File
Create a configuration file to store your API keys and settings.
# ai_access_control/config.py
import os
from dotenv import load_dotenv
load_dotenv()
# JWT Configuration
JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY', 'your-secret-key-here')
JWT_ACCESS_TOKEN_EXPIRES = 3600 # 1 hour
# AI Model Endpoint
AI_MODEL_ENDPOINT = os.getenv('AI_MODEL_ENDPOINT', 'https://api.anthropic.com/v1/messages')
# Access Control Settings
ALLOWED_REGIONS = ['us-east-1', 'us-west-2', 'eu-west-1']
BLOCKED_REGIONS = ['cn-north-1', 'cn-northwest-1']
Why: This configuration centralizes all settings, making it easy to update without changing code.
2.2 Implement JWT Authentication
Create the authentication module that will handle user verification.
# ai_access_control/auth/__init__.py
from flask import jsonify
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required
from datetime import datetime
# Mock user database (in production, use a real database)
users = {
'anthropic_admin': {'password': 'secure_password_123', 'role': 'admin', 'region': 'us-east-1'},
'model_user': {'password': 'model_password_456', 'role': 'user', 'region': 'us-west-2'}
}
def authenticate_user(username, password):
user = users.get(username)
if user and user['password'] == password:
return user
return None
def create_token(user):
# Create access token with user identity and role
access_token = create_access_token(
identity={
'username': user['username'],
'role': user['role'],
'region': user['region'],
'timestamp': datetime.utcnow().isoformat()
}
)
return access_token
Why: JWT tokens provide secure, stateless authentication that's essential for API access control systems.
3. Building Access Control Logic
3.1 Create Access Control Middleware
Implement the core logic that checks if a user can access specific AI models based on their region and role.
# ai_access_control/controllers/access_control.py
from flask import jsonify
from flask_jwt_extended import get_jwt_identity
from config import ALLOWED_REGIONS, BLOCKED_REGIONS
def check_access_control(model_name):
"""Check if current user has access to the requested model"""
current_user = get_jwt_identity()
user_region = current_user.get('region', 'unknown')
# Check if region is blocked
if user_region in BLOCKED_REGIONS:
return False, 'Access denied: Your region is blocked'
# Check if region is allowed
if user_region not in ALLOWED_REGIONS:
return False, 'Access denied: Region not authorized'
# Check model-specific permissions
if model_name == 'claude-mythos' and current_user.get('role') != 'admin':
return False, 'Access denied: Claude Mythos requires admin privileges'
return True, 'Access granted'
def log_access_request(user_identity, model_name, status):
"""Log access request for auditing purposes"""
import datetime
log_entry = {
'timestamp': datetime.datetime.utcnow().isoformat(),
'user': user_identity.get('username'),
'model': model_name,
'region': user_identity.get('region'),
'status': status
}
print(f"Access log: {log_entry}") # In production, write to database/file
return log_entry
Why: This middleware implements the core security logic that prevents unauthorized access, similar to what happened with SK Telecom's access revocation.
3.2 Implement AI Model Endpoint
Create the main API endpoint that handles AI model requests with access control.
# ai_access_control/controllers/model_controller.py
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from access_control import check_access_control, log_access_request
import requests
from config import AI_MODEL_ENDPOINT
model_bp = Blueprint('model', __name__)
@model_bp.route('/model/', methods=['POST'])
@jwt_required()
def access_model(model_name):
current_user = get_jwt_identity()
# Check access control
access_granted, message = check_access_control(model_name)
if not access_granted:
log_access_request(current_user, model_name, 'DENIED')
return jsonify({'error': message}), 403
# Forward request to actual AI model
try:
# Get request data
data = request.get_json()
# Make request to AI model endpoint
response = requests.post(
AI_MODEL_ENDPOINT,
headers={'Content-Type': 'application/json'},
json=data
)
# Log successful access
log_access_request(current_user, model_name, 'GRANTED')
return jsonify(response.json()), response.status_code
except Exception as e:
log_access_request(current_user, model_name, 'ERROR')
return jsonify({'error': str(e)}), 500
Why: This endpoint serves as the gateway for AI model access, implementing the access control logic we defined earlier.
4. Setting Up the Main Application
4.1 Create Main Application File
Connect all components into a working application.
# ai_access_control/app.py
from flask import Flask
from flask_jwt_extended import JWTManager
from auth import authenticate_user, create_token
from controllers.model_controller import model_bp
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'your-secret-key-here' # Use environment variable in production
# Initialize JWT
jwt = JWTManager(app)
# Register blueprints
app.register_blueprint(model_bp)
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
user = authenticate_user(username, password)
if user:
# Add username to user data for token creation
user['username'] = username
token = create_token(user)
return jsonify({'access_token': token}), 200
return jsonify({'error': 'Invalid credentials'}), 401
if __name__ == '__main__':
app.run(debug=True)
Why: This file ties together all components and provides the entry point for the access control system.
4.2 Create Requirements File
Document all dependencies for easy deployment.
# ai_access_control/requirements.txt
Flask==2.3.3
Flask-JWT-Extended==4.5.3
requests==2.31.0
python-dotenv==1.0.0
Why: This ensures consistent deployment across different environments.
5. Testing Your Access Control System
5.1 Test Authentication
First, test that authentication works correctly.
curl -X POST http://localhost:5000/login \
-H "Content-Type: application/json" \
-d '{"username": "anthropic_admin", "password": "secure_password_123"}'
Why: This validates that your authentication system works before testing access control.
5.2 Test Model Access
Test accessing different AI models with your token.
curl -X POST http://localhost:5000/model/claude-mythos \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{"prompt": "Hello world"}'
Why: This simulates the actual access scenario that was disrupted in the Anthropic controversy.
Summary
This tutorial demonstrated how to build a secure AI model access control system similar to what organizations like Anthropic implement. You learned to create a JWT-based authentication system, implement region-based access controls, and build logging mechanisms for auditing. The system prevents unauthorized access to sensitive AI models, just as Anthropic did when they revoked SK Telecom's access to Claude Mythos. This hands-on approach gives you practical experience in implementing enterprise-level access control for AI resources.



