This commit is contained in:
Waylon Walker 2025-11-21 12:50:29 -06:00
commit 1e11c8ca5e
12 changed files with 579 additions and 0 deletions

21
justfile Normal file
View file

@ -0,0 +1,21 @@
start-auth:
./main_auth.py &
stop-auth:
pkill -f main_auth.py || true
start-nginx:
docker run \
--rm \
-d \
--name nginx \
--network host \
-v "$PWD/site":/usr/share/nginx/html:ro \
-v "$PWD/nginx.conf":/etc/nginx/nginx.conf:ro \
docker.io/library/nginx
logs-nginx:
docker logs -f nginx
stop-nginx:
docker stop nginx

72
main_auth.py Executable file
View file

@ -0,0 +1,72 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "fastapi",
# "uvicorn[standard]",
# ]
# ///
from fastapi import FastAPI, Request, Response, HTTPException, Depends
from fastapi.responses import RedirectResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import secrets
app = FastAPI()
security = HTTPBasic()
USERS = {
"admin": {"password": "admin", "role": "admin"},
"reader": {"password": "reader", "role": "reader"},
}
# Cookie format: session=username
def get_current_user(request: Request):
session = request.cookies.get("session")
if session and session in USERS:
return session
return None
def get_current_role(user: str):
return USERS[user]["role"]
@app.post("/login")
async def login(credentials: HTTPBasicCredentials = Depends(security)):
user = credentials.username
pwd = credentials.password
if user in USERS and secrets.compare_digest(USERS[user]['password'], pwd):
resp = Response("OK", status_code=200)
resp.set_cookie("session", user, httponly=True, samesite='lax', path="/")
# Ensure login response isn't cached
resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0"
resp.headers["Pragma"] = "no-cache"
return resp
raise HTTPException(status_code=401, detail="Invalid credentials")
@app.get("/logout")
def logout():
resp = RedirectResponse("/")
resp.delete_cookie("session")
# Ensure logout response isn't cached
resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0"
resp.headers["Pragma"] = "no-cache"
resp.headers["Expires"] = "Thu, 01 Jan 1970 00:00:00 GMT"
return resp
@app.get("/authz")
def authz(request: Request):
session = request.cookies.get("session")
path = request.headers.get("X-Original-URI")
if not session or session not in USERS:
return Response("Not authenticated", status_code=401)
user_role = USERS[session]['role']
# Only admin may access /admin
if path and path.startswith("/admin") and user_role != 'admin':
return Response("Forbidden", status_code=403)
# Everything else: allowed
return Response("OK", status_code=200)
if __name__ == "__main__":
import uvicorn
app.mount("/static", StaticFiles(directory="static"), name="static")
uvicorn.run(app, host="localhost", port=5115)

90
nginx.conf Normal file
View file

@ -0,0 +1,90 @@
worker_processes 1;
events { worker_connections 1024; }
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server {
listen 8000;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Custom error pages
error_page 403 /403/;
error_page 404 /404/;
location / {
auth_request /authz;
error_page 401 = @login; # If not authed, redirect to login page
error_page 403 = @forbidden; # If forbidden, show custom 403 page
# Disable all caching for demo purposes
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
add_header Pragma "no-cache";
add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT";
try_files $uri $uri/ @not_found;
}
location = /authz {
internal;
proxy_pass http://127.0.0.1:5115/authz;
proxy_set_header X-Original-URI $request_uri;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
}
location @login {
add_header Content-Type text/html;
return 302 http://localhost:8000/login/;
}
location @forbidden {
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
add_header Pragma "no-cache";
add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT";
rewrite ^.*$ /403/ last;
}
location @not_found {
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
add_header Pragma "no-cache";
add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT";
return 404;
}
# Login page is public
location /login/ {
# Disable caching for login page too
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
add_header Pragma "no-cache";
add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT";
try_files $uri $uri/index.html =404;
}
# Custom error pages are public and shouldn't be cached
location ~ ^/(403|404)/$ {
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
add_header Pragma "no-cache";
add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT";
try_files $uri $uri/index.html =404;
}
# AJAX login: POST to FastAPI
location /login {
proxy_pass http://127.0.0.1:5115/login;
proxy_set_header Content-Type $content_type;
proxy_pass_request_body on;
}
location /logout {
proxy_pass http://127.0.0.1:5115/logout;
# Ensure logout response isn't cached
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
add_header Pragma "no-cache";
}
}
}

72
site/403.html Normal file
View file

@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>403 - Access Forbidden</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f8f9fa;
margin: 0;
padding: 50px;
}
.error-container {
max-width: 600px;
margin: 0 auto;
background: white;
padding: 40px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.error-code {
font-size: 72px;
font-weight: bold;
color: #dc3545;
margin: 0;
}
.error-message {
font-size: 24px;
color: #6c757d;
margin: 20px 0;
}
.error-description {
font-size: 16px;
color: #495057;
margin: 20px 0;
}
.nav-links {
margin-top: 30px;
}
.nav-links a {
display: inline-block;
margin: 0 10px;
padding: 10px 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 5px;
transition: background-color 0.3s;
}
.nav-links a:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="error-container">
<h1 class="error-code">403</h1>
<h2 class="error-message">Access Forbidden</h2>
<p class="error-description">
You don't have permission to access this resource.
You may need to log in with appropriate credentials or your current user role doesn't have access to this page.
</p>
<div class="nav-links">
<a href="/">Go Home</a>
<a href="/login.html">Login</a>
<a href="/logout">Logout</a>
</div>
</div>
</body>
</html>

33
site/403/index.html Normal file
View file

@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>403 Forbidden - nginx auth demo</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-white min-h-screen flex items-center justify-center">
<div class="text-center space-y-6 max-w-md mx-auto">
<h1 class="text-6xl font-bold text-red-400">403</h1>
<h2 class="text-2xl font-semibold text-gray-200">Access Forbidden</h2>
<p class="text-gray-300">Your current user role doesn't have access to this resource</p>
<div class="bg-red-900/20 border border-red-500 rounded p-4 text-red-300">
<p class="text-sm">🔒 nginx auth_request blocked this request</p>
<p class="text-sm">Try logging in with different credentials</p>
</div>
<div class="space-y-3">
<div>
<a href="/login" class="inline-block px-6 py-3 bg-blue-600 hover:bg-blue-700 rounded text-white">
Login with Different User
</a>
</div>
<div class="space-x-4">
<a href="/" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded">Home</a>
<a href="/logout" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded">Logout</a>
</div>
</div>
</div>
</body>
</html>

83
site/404.html Normal file
View file

@ -0,0 +1,83 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 - Page Not Found</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f8f9fa;
margin: 0;
padding: 50px;
}
.error-container {
max-width: 600px;
margin: 0 auto;
background: white;
padding: 40px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.error-code {
font-size: 72px;
font-weight: bold;
color: #ffc107;
margin: 0;
}
.error-message {
font-size: 24px;
color: #6c757d;
margin: 20px 0;
}
.error-description {
font-size: 16px;
color: #495057;
margin: 20px 0;
}
.nav-links {
margin-top: 30px;
}
.nav-links a {
display: inline-block;
margin: 0 10px;
padding: 10px 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 5px;
transition: background-color 0.3s;
}
.nav-links a:hover {
background-color: #0056b3;
}
.search-suggestion {
margin: 20px 0;
padding: 15px;
background-color: #e9ecef;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="error-container">
<h1 class="error-code">404</h1>
<h2 class="error-message">Page Not Found</h2>
<p class="error-description">
The page you are looking for might have been removed, had its name changed,
or is temporarily unavailable.
</p>
<div class="search-suggestion">
<strong>Available pages:</strong><br>
<a href="/">Home</a> |
<a href="/admin.html">Admin Page</a> |
<a href="/login.html">Login</a>
</div>
<div class="nav-links">
<a href="/">Go Home</a>
<a href="/login.html">Login</a>
</div>
</div>
</body>
</html>

30
site/404/index.html Normal file
View file

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 Not Found - nginx auth demo</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-white min-h-screen flex items-center justify-center">
<div class="text-center space-y-6 max-w-md mx-auto">
<h1 class="text-6xl font-bold text-yellow-400">404</h1>
<h2 class="text-2xl font-semibold text-gray-200">Page Not Found</h2>
<p class="text-gray-300">The page you're looking for doesn't exist</p>
<div class="bg-gray-800 rounded p-4 text-sm">
<p class="text-gray-300 mb-2">Available pages:</p>
<div class="space-y-1">
<p><a href="/" class="text-blue-400 hover:underline">/ (home)</a></p>
<p><a href="/admin" class="text-red-400 hover:underline">/admin (requires admin role)</a></p>
<p><a href="/login" class="text-green-400 hover:underline">/login</a></p>
</div>
</div>
<div class="space-x-4">
<a href="/" class="px-6 py-3 bg-blue-600 hover:bg-blue-700 rounded text-white">Go Home</a>
<a href="/login" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded">Login</a>
</div>
</div>
</body>
</html>

2
site/admin.html Normal file
View file

@ -0,0 +1,2 @@
<h1>Admin page</h1>
<p>Only admins can see this page!</p>

24
site/admin/index.html Normal file
View file

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin - nginx auth demo</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-white min-h-screen flex items-center justify-center">
<div class="text-center space-y-6">
<h1 class="text-4xl font-bold text-red-400">Admin Page</h1>
<p class="text-gray-300">Only admins can see this page!</p>
<div class="bg-red-900/20 border border-red-500 rounded p-4 text-red-300">
<p class="text-sm">🔒 This page is protected by nginx auth_request</p>
<p class="text-sm">Only users with "admin" role can access</p>
</div>
<div class="space-x-4">
<a href="/" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded">Home</a>
<a href="/logout" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded">Logout</a>
</div>
</div>
</body>
</html>

27
site/index.html Normal file
View file

@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>nginx auth demo</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-white min-h-screen flex items-center justify-center">
<div class="text-center space-y-6">
<h1 class="text-4xl font-bold text-blue-400">nginx auth demo</h1>
<p class="text-gray-300">Everyone can see this page</p>
<div class="space-y-4">
<div>
<a href="/admin" class="inline-block px-6 py-3 bg-red-600 hover:bg-red-700 rounded text-white">
Admin Page (requires admin role)
</a>
</div>
<div class="space-x-4">
<a href="/login" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded">Login</a>
<a href="/logout" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded">Logout</a>
</div>
</div>
</div>
</body>
</html>

63
site/login.html Normal file
View file

@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<style>
body { font-family: sans-serif; margin: 2em; }
form { max-width: 300px; margin: 2em auto; padding: 1.5em; border: 1px solid #ccc; background: #fafafa; border-radius: 8px;}
label { display: block; margin-top: 1em; }
input[type="text"], input[type="password"] {
width: 100%; padding: 0.5em; box-sizing: border-box;
}
.error { color: red; margin-top: 1em;}
button { margin-top: 1.2em; width: 100%; padding: 0.7em; background: #007bff; color: #fff; border: none; border-radius: 4px;}
</style>
</head>
<body>
<h2>Login</h2>
<form id="login-form">
<label>
Username:
<input type="text" name="username" id="username" autocomplete="username" required autofocus />
</label>
<label>
Password:
<input type="password" name="password" id="password" autocomplete="current-password" required />
</label>
<button type="submit">Log In</button>
<div class="error" id="error" style="display:none;"></div>
</form>
<script>
document.getElementById('login-form').onsubmit = async function(e) {
e.preventDefault();
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
const errorDiv = document.getElementById('error');
errorDiv.style.display = "none";
const headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
try {
const resp = await fetch('/login', {
method: 'POST',
headers,
});
if (resp.ok) {
window.location.href = '/';
} else if (resp.status === 401) {
errorDiv.textContent = "Invalid username or password.";
errorDiv.style.display = "block";
} else {
errorDiv.textContent = "Unknown error (" + resp.status + ").";
errorDiv.style.display = "block";
}
} catch (err) {
errorDiv.textContent = "Network error.";
errorDiv.style.display = "block";
}
};
</script>
</body>
</html>

62
site/login/index.html Normal file
View file

@ -0,0 +1,62 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - nginx auth demo</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-white min-h-screen flex items-center justify-center">
<div class="text-center space-y-6 max-w-md mx-auto">
<h1 class="text-4xl font-bold text-blue-400">Login</h1>
<p class="text-gray-300">Enter your credentials</p>
<form id="loginForm" class="space-y-4">
<div>
<input type="text" id="username" placeholder="Username"
class="w-full px-4 py-3 bg-gray-800 border border-gray-600 rounded text-white placeholder-gray-400 focus:outline-none focus:border-blue-500">
</div>
<div>
<input type="password" id="password" placeholder="Password"
class="w-full px-4 py-3 bg-gray-800 border border-gray-600 rounded text-white placeholder-gray-400 focus:outline-none focus:border-blue-500">
</div>
<button type="submit" class="w-full px-6 py-3 bg-blue-600 hover:bg-blue-700 rounded text-white font-semibold">
Login
</button>
</form>
<div class="bg-gray-800 rounded p-4 text-sm">
<p class="text-gray-300 mb-2">Demo credentials:</p>
<p class="text-blue-300">admin / admin (can access /admin)</p>
<p class="text-green-300">reader / reader (cannot access /admin)</p>
</div>
<a href="/" class="inline-block px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded">Back to Home</a>
</div>
<script>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
try {
const response = await fetch('/login', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(username + ':' + password)
}
});
if (response.ok) {
window.location.href = '/';
} else {
alert('Invalid credentials');
}
} catch (error) {
alert('Login failed');
}
});
</script>
</body>
</html>