Files
skills/public/api-api-authorization.html
zeekay 747dafba10 Register WebMCP tools on every page, and name each page's twin from site.py
Every page now loads /webmcp.js, scripts/webmcp.ts with its types
stripped (npm run webmcp). Where the browser has document.modelContext
it registers two read-only tools: search_skills over the published
skills index, and get_skill, which returns a skill's markdown checked
against the index digest. The markdown alternate link moves from
build.py to site.py, so CI holds every page to it.

The API catalog gains the site itself (llms.txt and the skills index)
and hanzo.ai/agents; the live discovery check now fetches every
catalog link. tests/site.mjs drives the tools through a recording
modelContext, and checks a browser without one loads clean.
2026-10-26 20:57:05 -07:00

699 lines
35 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>api-api-authorization</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/api-api-authorization">
<link rel="alternate" type="text/markdown" href="/api-api-authorization.md">
<script type="module" src="/webmcp.js"></script>
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/api-api-authorization.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>api-api-authorization</h1><p class="lede">Implementing authorization logic in APIs</p><h1>API Authorization</h1>
<p><strong>Scope</strong>: Authorization models, permission systems, role-based access control <strong>Lines</strong>: ~240 <strong>Last Updated</strong>: 2025-10-18</p>
<h2>When to Use This Skill</h2>
<p>Activate this skill when:</p>
<ul><li>Implementing authorization logic in APIs</li><li>Designing permission systems for applications</li><li>Choosing between RBAC, ABAC, or ACL models</li><li>Building multi-tenant authorization systems</li><li>Implementing resource-level permissions</li><li>Configuring policy engines (OPA, Casbin)</li><li>Debugging authorization failures or security vulnerabilities</li></ul>
<h2>Core Concepts</h2>
<h3>Authentication vs Authorization</h3>
<p><strong>Authentication</strong>: &quot;Who are you?&quot; - Verifying identity (login, JWT, OAuth) <strong>Authorization</strong>: &quot;What can you do?&quot; - Verifying permissions</p>
<p><strong>This skill focuses on authorization only</strong>. For authentication patterns, see <code>api-authentication.md</code>.</p>
<hr>
<h2>Authorization Models</h2>
<h3>Access Control List (ACL)</h3>
<p><strong>What</strong>: Direct mapping of users/groups to resources and permissions.</p>
<p><strong>Structure</strong>:</p>
<pre><code>Resource → List of (User/Group, Permissions)</code></pre>
<p><strong>Example</strong>:</p>
<pre><code class="lang-json">{
&quot;document_123&quot;: {
&quot;alice&quot;: [&quot;read&quot;, &quot;write&quot;],
&quot;bob&quot;: [&quot;read&quot;],
&quot;editors_group&quot;: [&quot;read&quot;, &quot;write&quot;, &quot;delete&quot;]
}
}</code></pre>
<p><strong>Strengths</strong>:</p>
<ul><li>Simple to understand</li><li>Fine-grained control per resource</li><li>Easy to audit (&quot;who has access to X?&quot;)</li></ul>
<p><strong>Weaknesses</strong>:</p>
<ul><li>Doesn&#x27;t scale well (many resources × many users)</li><li>Difficult to manage patterns (all docs in folder X)</li><li>Redundant permissions across resources</li></ul>
<p><strong>Best for</strong>:</p>
<ul><li>File systems</li><li>Document sharing (Google Docs, Dropbox)</li><li>Small-scale applications with few resources</li></ul>
<h3>Role-Based Access Control (RBAC)</h3>
<p><strong>What</strong>: Permissions assigned to roles, users assigned to roles.</p>
<p><strong>Structure</strong>:</p>
<pre><code>User → Role → Permissions</code></pre>
<p><strong>Example</strong>:</p>
<pre><code class="lang-json">{
&quot;roles&quot;: {
&quot;admin&quot;: [&quot;users:read&quot;, &quot;users:write&quot;, &quot;users:delete&quot;, &quot;posts:*&quot;],
&quot;editor&quot;: [&quot;posts:read&quot;, &quot;posts:write&quot;, &quot;posts:delete&quot;],
&quot;viewer&quot;: [&quot;posts:read&quot;]
},
&quot;users&quot;: {
&quot;alice&quot;: [&quot;admin&quot;],
&quot;bob&quot;: [&quot;editor&quot;],
&quot;charlie&quot;: [&quot;viewer&quot;]
}
}</code></pre>
<p><strong>Strengths</strong>:</p>
<ul><li>Scales well (manage roles, not individual permissions)</li><li>Industry standard (widely understood)</li><li>Simple to implement and audit</li><li>Role hierarchy possible (manager inherits employee permissions)</li></ul>
<p><strong>Weaknesses</strong>:</p>
<ul><li>Coarse-grained (can&#x27;t easily do &quot;only own resources&quot;)</li><li>Role explosion for complex scenarios</li><li>Static (doesn&#x27;t consider context like time, location)</li></ul>
<p><strong>Best for</strong>:</p>
<ul><li>Internal tools (admin panels, CMS)</li><li>SaaS applications</li><li>Enterprise software</li><li>Multi-tenant systems</li></ul>
<h3>Attribute-Based Access Control (ABAC)</h3>
<p><strong>What</strong>: Permissions based on attributes (user, resource, environment).</p>
<p><strong>Structure</strong>:</p>
<pre><code>Policy: IF (user attributes + resource attributes + environment) THEN allow/deny</code></pre>
<p><strong>Example</strong>:</p>
<pre><code class="lang-python"># Policy: Users can edit their own posts during business hours
if (
user.id == post.author_id
and current_time &gt;= &quot;09:00&quot;
and current_time &lt;= &quot;17:00&quot;
and user.department == post.department
):
allow(&quot;edit&quot;)</code></pre>
<p><strong>Attributes</strong>:</p>
<ul><li><strong>User</strong>: role, department, clearance_level, location</li><li><strong>Resource</strong>: owner, sensitivity, department, created_date</li><li><strong>Environment</strong>: time, IP address, device_type</li></ul>
<p><strong>Strengths</strong>:</p>
<ul><li>Extremely flexible (context-aware)</li><li>Fine-grained control</li><li>Reduces role explosion</li><li>Dynamic (evaluates at runtime)</li></ul>
<p><strong>Weaknesses</strong>:</p>
<ul><li>Complex to implement and debug</li><li>Performance overhead (policy evaluation)</li><li>Difficult to audit (&quot;who can access X?&quot;)</li><li>Requires policy engine (OPA, Casbin)</li></ul>
<p><strong>Best for</strong>:</p>
<ul><li>Healthcare (HIPAA compliance)</li><li>Government/military (clearance levels)</li><li>Complex organizational hierarchies</li><li>Context-dependent access (time, location)</li></ul>
<hr>
<h2>Authorization Model Decision Tree</h2>
<pre><code>Start: What&#x27;s your primary requirement?
│
├─ Simple resource sharing?
│ └─ ACL (Google Docs-style)
│
├─ Predictable organizational roles?
│ ├─ Few roles (&lt;10) → RBAC
│ ├─ Many roles (&gt;20) → Continue
│ └─ Complex hierarchy → Hierarchical RBAC
│
├─ Context-dependent access? (time, location, attributes)
│ └─ ABAC (with policy engine)
│
├─ Resource-level permissions needed?
│ ├─ Per-user → ACL or ABAC
│ ├─ Per-role → RBAC with resource scopes
│ └─ Dynamic → ABAC
│
├─ Audit requirements?
│ ├─ &quot;Who has access?&quot; → ACL or RBAC
│ └─ &quot;Who accessed X?&quot; → Any (with logging)
│
└─ Default → RBAC (most common)</code></pre>
<hr>
<h2>RBAC vs ABAC Comparison</h2>
<p>| Criteria | RBAC | ABAC | |----------|------|------| | <strong>Complexity</strong> | Low (roles + permissions) | High (policies + attributes) | | <strong>Granularity</strong> | Coarse (role-level) | Fine (attribute-level) | | <strong>Scalability</strong> | Good (role explosion risk) | Excellent (policy-based) | | <strong>Performance</strong> | Fast (lookup) | Slower (policy evaluation) | | <strong>Auditability</strong> | Easy (&quot;list role permissions&quot;) | Hard (&quot;evaluate all policies&quot;) | | <strong>Context-awareness</strong> | None | Full (time, location, etc.) | | <strong>Implementation time</strong> | Days | Weeks/months | | <strong>Best for</strong> | 80% of applications | Complex compliance scenarios |</p>
<hr>
<h2>Implementing RBAC</h2>
<h3>Database Schema (PostgreSQL)</h3>
<pre><code class="lang-sql">-- Users table
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL
);
-- Roles table
CREATE TABLE roles (
id SERIAL PRIMARY KEY,
name VARCHAR(50) UNIQUE NOT NULL, -- e.g., &quot;admin&quot;, &quot;editor&quot;
description TEXT
);
-- Permissions table
CREATE TABLE permissions (
id SERIAL PRIMARY KEY,
resource VARCHAR(100) NOT NULL, -- e.g., &quot;posts&quot;, &quot;users&quot;
action VARCHAR(50) NOT NULL, -- e.g., &quot;read&quot;, &quot;write&quot;, &quot;delete&quot;
UNIQUE(resource, action)
);
-- Role-Permission mapping (many-to-many)
CREATE TABLE role_permissions (
role_id INT REFERENCES roles(id),
permission_id INT REFERENCES permissions(id),
PRIMARY KEY (role_id, permission_id)
);
-- User-Role mapping (many-to-many)
CREATE TABLE user_roles (
user_id INT REFERENCES users(id),
role_id INT REFERENCES roles(id),
PRIMARY KEY (user_id, role_id)
);</code></pre>
<h3>Permission Check Query</h3>
<pre><code class="lang-sql">-- Check if user has permission
SELECT EXISTS (
SELECT 1
FROM user_roles ur
JOIN role_permissions rp ON ur.role_id = rp.role_id
JOIN permissions p ON rp.permission_id = p.id
WHERE ur.user_id = $1 -- User ID
AND p.resource = $2 -- e.g., &quot;posts&quot;
AND p.action = $3 -- e.g., &quot;write&quot;
) AS has_permission;</code></pre>
<h3>Authorization Middleware (Python/FastAPI)</h3>
<pre><code class="lang-python">from functools import wraps
from fastapi import HTTPException, Depends
def require_permission(resource: str, action: str):
&quot;&quot;&quot;Decorator to check permissions&quot;&quot;&quot;
def decorator(func):
@wraps(func)
async def wrapper(*args, current_user=Depends(get_current_user), **kwargs):
# Query database for permission
has_perm = await db.fetch_one(
&quot;&quot;&quot;
SELECT EXISTS (
SELECT 1
FROM user_roles ur
JOIN role_permissions rp ON ur.role_id = rp.role_id
JOIN permissions p ON rp.permission_id = p.id
WHERE ur.user_id = $1 AND p.resource = $2 AND p.action = $3
) AS has_permission
&quot;&quot;&quot;,
[current_user.id, resource, action]
)
if not has_perm[&quot;has_permission&quot;]:
raise HTTPException(status_code=403, detail=&quot;Permission denied&quot;)
return await func(*args, current_user=current_user, **kwargs)
return wrapper
return decorator
# Usage
@app.delete(&quot;/posts/{post_id}&quot;)
@require_permission(&quot;posts&quot;, &quot;delete&quot;)
async def delete_post(post_id: int, current_user: User):
# Delete post logic
pass</code></pre>
<hr>
<h2>Resource-Level Permissions</h2>
<h3>Problem: RBAC + Ownership</h3>
<p><strong>Scenario</strong>: Editors can edit posts, but only their own posts.</p>
<p><strong>Solution 1: Hybrid RBAC + Resource Check</strong></p>
<pre><code class="lang-python">@app.put(&quot;/posts/{post_id}&quot;)
@require_permission(&quot;posts&quot;, &quot;write&quot;)
async def update_post(post_id: int, current_user: User):
post = await db.fetch_one(&quot;SELECT * FROM posts WHERE id = $1&quot;, [post_id])
if not post:
raise HTTPException(status_code=404)
# Resource-level check
if post[&quot;author_id&quot;] != current_user.id and &quot;admin&quot; not in current_user.roles:
raise HTTPException(status_code=403, detail=&quot;Not your post&quot;)
# Update post
pass</code></pre>
<p><strong>Solution 2: Scope-Based Permissions</strong></p>
<pre><code class="lang-sql">-- Add scope to permissions
ALTER TABLE role_permissions ADD COLUMN scope VARCHAR(50);
-- scope values: &quot;all&quot;, &quot;own&quot;, &quot;department&quot;
-- Check with scope
SELECT
p.action,
rp.scope
FROM user_roles ur
JOIN role_permissions rp ON ur.role_id = rp.role_id
JOIN permissions p ON rp.permission_id = p.id
WHERE ur.user_id = $1
AND p.resource = $2;</code></pre>
<pre><code class="lang-python">def check_resource_permission(user, resource, action, resource_obj):
perms = get_user_permissions(user, resource, action)
for perm in perms:
if perm.scope == &quot;all&quot;:
return True
elif perm.scope == &quot;own&quot; and resource_obj.owner_id == user.id:
return True
elif perm.scope == &quot;department&quot; and resource_obj.department == user.department:
return True
return False</code></pre>
<hr>
<h2>Hierarchical Roles</h2>
<h3>Role Inheritance</h3>
<p><strong>Example</strong>: Manager inherits all Employee permissions + additional permissions.</p>
<pre><code class="lang-sql">-- Add parent_role_id for hierarchy
ALTER TABLE roles ADD COLUMN parent_role_id INT REFERENCES roles(id);
-- Example hierarchy
INSERT INTO roles (name, parent_role_id) VALUES
(&#x27;employee&#x27;, NULL),
(&#x27;manager&#x27;, (SELECT id FROM roles WHERE name = &#x27;employee&#x27;)),
(&#x27;director&#x27;, (SELECT id FROM roles WHERE name = &#x27;manager&#x27;));</code></pre>
<p><strong>Permission check with inheritance</strong>:</p>
<pre><code class="lang-sql">-- Recursive CTE to get all inherited permissions
WITH RECURSIVE role_hierarchy AS (
-- Base: User&#x27;s direct roles
SELECT r.id, r.name, r.parent_role_id
FROM user_roles ur
JOIN roles r ON ur.role_id = r.id
WHERE ur.user_id = $1
UNION
-- Recursive: Parent roles
SELECT r.id, r.name, r.parent_role_id
FROM roles r
JOIN role_hierarchy rh ON r.id = rh.parent_role_id
)
SELECT EXISTS (
SELECT 1
FROM role_hierarchy rh
JOIN role_permissions rp ON rh.id = rp.role_id
JOIN permissions p ON rp.permission_id = p.id
WHERE p.resource = $2 AND p.action = $3
) AS has_permission;</code></pre>
<hr>
<h2>Policy Engines</h2>
<h3>Open Policy Agent (OPA)</h3>
<p><strong>What</strong>: Declarative policy engine using Rego language.</p>
<p><strong>Use case</strong>: Complex ABAC policies, Kubernetes admission control.</p>
<p><strong>Example policy</strong> (<code>policy.rego</code>):</p>
<pre><code class="lang-rego">package app.authz
# Allow if user is admin
allow {
input.user.role == &quot;admin&quot;
}
# Allow if user owns the resource
allow {
input.user.id == input.resource.owner_id
}
# Allow if user is in same department and resource is not confidential
allow {
input.user.department == input.resource.department
input.resource.confidential == false
}</code></pre>
<p><strong>Usage</strong> (Python):</p>
<pre><code class="lang-python">import requests
def check_permission(user, resource, action):
policy_input = {
&quot;user&quot;: {
&quot;id&quot;: user.id,
&quot;role&quot;: user.role,
&quot;department&quot;: user.department
},
&quot;resource&quot;: {
&quot;id&quot;: resource.id,
&quot;owner_id&quot;: resource.owner_id,
&quot;department&quot;: resource.department,
&quot;confidential&quot;: resource.confidential
},
&quot;action&quot;: action
}
response = requests.post(
&quot;http://opa:8181/v1/data/app/authz/allow&quot;,
json={&quot;input&quot;: policy_input}
)
return response.json().get(&quot;result&quot;, False)</code></pre>
<p><strong>Pros</strong>:</p>
<ul><li>Declarative (easy to read policies)</li><li>Centralized policy management</li><li>Language-agnostic (HTTP API)</li></ul>
<p><strong>Cons</strong>:</p>
<ul><li>Operational complexity (separate service)</li><li>Learning curve (Rego syntax)</li></ul>
<h3>Casbin</h3>
<p><strong>What</strong>: Authorization library with multiple models (RBAC, ABAC, ACL).</p>
<p><strong>Use case</strong>: Embed authorization in application code.</p>
<p><strong>Example</strong> (Python):</p>
<pre><code class="lang-python">import casbin
# Load model and policy
enforcer = casbin.Enforcer(&quot;model.conf&quot;, &quot;policy.csv&quot;)
# Check permission
if enforcer.enforce(&quot;alice&quot;, &quot;posts&quot;, &quot;write&quot;):
print(&quot;Allowed&quot;)
else:
print(&quot;Denied&quot;)</code></pre>
<p><strong>Model file</strong> (<code>model.conf</code>):</p>
<pre><code class="lang-ini">[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) &amp;&amp; r.obj == p.obj &amp;&amp; r.act == p.act</code></pre>
<p><strong>Policy file</strong> (<code>policy.csv</code>):</p>
<pre><code class="lang-csv">p, admin, posts, *
p, editor, posts, write
p, editor, posts, read
g, alice, admin
g, bob, editor</code></pre>
<p><strong>Pros</strong>:</p>
<ul><li>Embedded (no external service)</li><li>Supports multiple models</li><li>Good performance (in-memory)</li></ul>
<p><strong>Cons</strong>:</p>
<ul><li>Policy stored in CSV/DB (not as readable as OPA)</li></ul>
<hr>
<h2>Scope-Based Authorization</h2>
<h3>JWT with Scopes</h3>
<p><strong>What</strong>: Embed permissions in JWT token.</p>
<p><strong>Example</strong>:</p>
<pre><code class="lang-json">{
&quot;sub&quot;: &quot;alice&quot;,
&quot;role&quot;: &quot;editor&quot;,
&quot;scopes&quot;: [&quot;posts:read&quot;, &quot;posts:write&quot;, &quot;users:read&quot;]
}</code></pre>
<p><strong>Authorization middleware</strong>:</p>
<pre><code class="lang-python">def require_scope(required_scope: str):
def decorator(func):
@wraps(func)
async def wrapper(*args, token=Depends(get_token), **kwargs):
scopes = token.get(&quot;scopes&quot;, [])
if required_scope not in scopes:
raise HTTPException(status_code=403)
return await func(*args, **kwargs)
return wrapper
return decorator
@app.delete(&quot;/posts/{post_id}&quot;)
@require_scope(&quot;posts:delete&quot;)
async def delete_post(post_id: int):
pass</code></pre>
<p><strong>Pros</strong>:</p>
<ul><li>No database lookup (fast)</li><li>Stateless</li></ul>
<p><strong>Cons</strong>:</p>
<ul><li>Can&#x27;t revoke permissions until token expires</li><li>Token bloat (many scopes)</li><li>Security risk if token leaked (use short expiry)</li></ul>
<hr>
<h2>Common Authorization Pitfalls</h2>
<h3>Pitfall 1: Missing Authorization Checks</h3>
<p><strong>Problem</strong>: Implementing authentication but forgetting authorization.</p>
<pre><code class="lang-python"># ❌ BAD: Only checks authentication
@app.delete(&quot;/posts/{post_id}&quot;)
async def delete_post(post_id: int, current_user=Depends(get_current_user)):
await db.execute(&quot;DELETE FROM posts WHERE id = $1&quot;, [post_id])</code></pre>
<p><strong>Solution</strong>: Always check ownership or permissions.</p>
<pre><code class="lang-python"># ✅ GOOD: Checks both authentication and authorization
@app.delete(&quot;/posts/{post_id}&quot;)
async def delete_post(post_id: int, current_user=Depends(get_current_user)):
post = await db.fetch_one(&quot;SELECT * FROM posts WHERE id = $1&quot;, [post_id])
if not post:
raise HTTPException(status_code=404)
if post[&quot;author_id&quot;] != current_user.id and &quot;admin&quot; not in current_user.roles:
raise HTTPException(status_code=403)
await db.execute(&quot;DELETE FROM posts WHERE id = $1&quot;, [post_id])</code></pre>
<h3>Pitfall 2: Insecure Direct Object Reference (IDOR)</h3>
<p><strong>Problem</strong>: Using predictable IDs without authorization.</p>
<pre><code class="lang-python"># ❌ BAD: Anyone can access any invoice
@app.get(&quot;/invoices/{invoice_id}&quot;)
async def get_invoice(invoice_id: int, current_user=Depends(get_current_user)):
return await db.fetch_one(&quot;SELECT * FROM invoices WHERE id = $1&quot;, [invoice_id])</code></pre>
<p><strong>Solution</strong>: Check ownership.</p>
<pre><code class="lang-python"># ✅ GOOD: Only owner can access invoice
@app.get(&quot;/invoices/{invoice_id}&quot;)
async def get_invoice(invoice_id: int, current_user=Depends(get_current_user)):
invoice = await db.fetch_one(
&quot;SELECT * FROM invoices WHERE id = $1 AND user_id = $2&quot;,
[invoice_id, current_user.id]
)
if not invoice:
raise HTTPException(status_code=404) # Don&#x27;t leak existence
return invoice</code></pre>
<h3>Pitfall 3: Privilege Escalation</h3>
<p><strong>Problem</strong>: Users can assign themselves higher roles.</p>
<pre><code class="lang-python"># ❌ BAD: Users can make themselves admin
@app.put(&quot;/users/{user_id}/role&quot;)
async def update_role(user_id: int, role: str, current_user=Depends(get_current_user)):
await db.execute(&quot;UPDATE users SET role = $1 WHERE id = $2&quot;, [role, user_id])</code></pre>
<p><strong>Solution</strong>: Only admins can assign roles.</p>
<pre><code class="lang-python"># ✅ GOOD: Only admins can assign roles
@app.put(&quot;/users/{user_id}/role&quot;)
@require_permission(&quot;users&quot;, &quot;manage_roles&quot;)
async def update_role(user_id: int, role: str, current_user=Depends(get_current_user)):
await db.execute(&quot;UPDATE users SET role = $1 WHERE id = $2&quot;, [role, user_id])</code></pre>
<h3>Pitfall 4: Caching Permissions Too Long</h3>
<p><strong>Problem</strong>: Permissions cached in JWT or session, changes not reflected.</p>
<p><strong>Solution</strong>:</p>
<ul><li>Use short-lived tokens (15-30 min)</li><li>Implement token refresh</li><li>For critical permissions, query database</li></ul>
<pre><code class="lang-python"># Hybrid approach: Cache non-critical, query critical
if action in [&quot;delete&quot;, &quot;admin_access&quot;]:
# Always query database for critical actions
has_perm = await db.fetch_one(query)
else:
# Use cached permissions from token
has_perm = action in token[&quot;scopes&quot;]</code></pre>
<hr>
<h2>Best Practices</h2>
<h3>Do&#x27;s</h3>
<p>✅ <strong>Always check authorization</strong> (not just authentication) ✅ <strong>Fail closed</strong> (deny by default, explicit allow) ✅ <strong>Check ownership</strong> for resource-level permissions ✅ <strong>Log authorization failures</strong> (audit trail) ✅ <strong>Use principle of least privilege</strong> (minimal permissions) ✅ <strong>Test with different roles</strong> (ensure isolation)</p>
<h3>Don&#x27;ts</h3>
<p>❌ <strong>Don&#x27;t trust client-side authorization</strong> (always check server-side) ❌ <strong>Don&#x27;t leak information</strong> (404 instead of 403 for private resources) ❌ <strong>Don&#x27;t use GET for permission changes</strong> (CSRF risk) ❌ <strong>Don&#x27;t cache permissions indefinitely</strong> (use short TTL) ❌ <strong>Don&#x27;t expose internal role names</strong> (use display names)</p>
<hr>
<h2>Quick Reference</h2>
<h3>Authorization Checklist</h3>
<pre><code>[ ] Authentication verified (who is the user?)
[ ] Authorization verified (what can they do?)
[ ] Ownership checked (if resource-level)
[ ] Role/permissions cached (with TTL)
[ ] Authorization failures logged
[ ] Edge cases tested (no role, multiple roles, escalation)
[ ] IDOR vulnerabilities checked
[ ] Privilege escalation prevented</code></pre>
<h3>RBAC Implementation Checklist</h3>
<pre><code>[ ] Database schema (users, roles, permissions, mappings)
[ ] Permission check function/query
[ ] Authorization middleware/decorator
[ ] Resource-level checks (ownership)
[ ] Role hierarchy (if needed)
[ ] Audit logging
[ ] Unit tests (permission matrix)</code></pre>
<hr>
<h2>Related Skills</h2>
<ul><li><code>api-authentication.md</code> - JWT, OAuth, session management</li><li><code>database-security.md</code> - Row-level security, SQL injection prevention</li><li><code>api-rate-limiting.md</code> - Rate limiting per role/user</li><li><code>api-multi-tenancy.md</code> - Tenant isolation in authorization</li></ul>
<hr>
<p><strong>Last Updated</strong>: 2025-10-18 <strong>Format Version</strong>: 1.0 (Atomic)</p>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/api-api-authorization.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>