Skip to main content

🛡️ GuardNet

GuardNet is a graph-based, type-safe ReBAC (Relationship-Based Access Control) engine for Python 3.11+.

Inspired by distributed state machine patterns, GuardNet allows you to model complex authorization logic as a directed graph of Python classes. It solves the "spaghetti if-statement" problem in authorization by using recursive delegation, short-circuiting logical gates, and request-scoped memoization.


✨ Key Features

  • Code as Truth: Policies are standard Python classes. No custom DSLs, JSON, or YAML logic.
  • Context Awareness: Use Pydantic models to define exactly what data is needed for a specific check.
  • Relationship-Based (ReBAC): Easily model inheritance (e.g., Document -> Folder -> Organization) using the Delegate pattern.
  • Memoization: Identical checks within the same request context are executed only once, saving database overhead.
  • Short-Circuiting: AnyOf (OR) and AllOf (AND) gates stop execution as soon as a result is determined.
  • Static Validation: Detect circular dependencies and connectivity issues in your authorization graph before you deploy.

🚀 Quick Start

1. Define your Context and Nodes

Nodes are the building blocks of your policy. They receive a typed context and return a Decision.

from pydantic import BaseModel
from guardnet import GuardNode, Effect, AnyOf, PolicyEngine

class AuthCtx(BaseModel):
    user_id: str
    resource_id: str

class IsAdmin(GuardNode[AuthCtx]):
    async def evaluate(self, ctx: AuthCtx):
        # Direct boolean logic
        return Effect.ALLOW if ctx.user_id == "admin-1" else Effect.DENY

class IsOwner(GuardNode[AuthCtx]):
    async def evaluate(self, ctx: AuthCtx):
        # You can perform async DB calls here
        return Effect.ALLOW if ctx.resource_id == "owner-res" else Effect.DENY

class RootPolicy(GuardNode[AuthCtx]):
    async def evaluate(self, ctx: AuthCtx):
        # Logical composition with short-circuiting
        return AnyOf(branches=[IsAdmin, IsOwner])

2. Execute the Check

The PolicyEngine manages the evaluation and handles request-scoped caching.

engine = PolicyEngine(nodes=[RootPolicy, IsAdmin, IsOwner])

allowed = await engine.check(
    start_node=RootPolicy, 
    context=AuthCtx(user_id="user-1", resource_id="owner-res")
)

if allowed:
    print("Access Granted!")

🛠️ Advanced: ReBAC and Inheritance

GuardNet shines when resources inherit permissions from parents. Use Delegate to switch contexts mid-evaluation.

class CheckDocument(GuardNode[DocCtx]):
    async def evaluate(self, ctx: DocCtx):
        # Look up the parent folder ID
        parent_id = await db.get_parent_folder(ctx.doc_id)
        
        # Delegate checking to the Folder policy with a new context
        return Delegate(
            node_cls=CheckFolder,
            sub_context=FolderCtx(user_id=ctx.user_id, folder_id=parent_id)
        )

🔍 Static Analysis

Prevent infinite loops or broken logic in your security graph by validating it at startup or in CI/CD.

from guardnet import GraphAnalyzer

# This will raise a RecursionError if a cycle is found
GraphAnalyzer.validate(RootPolicy, engine._registry)

⚖️ License

MIT

Metadata

Release files for guardnet 0.1.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for guardnet 0.1.5
File Size Uploaded Provenance Actions
guardnet-0.1.5.tar.gz 4.4 kB Without provenance Details for guardnet-0.1.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for guardnet 0.1.5
File Interpreter ABI Platform Actions
guardnet-0.1.5-py3-none-any.whl Python 3 none any Details for guardnet-0.1.5-py3-none-any.whl

Total release size: 9.9 kB

Release files / guardnet-0.1.5.tar.gz

Download URL guardnet-0.1.5.tar.gz
Size 4.4 kB
Tags Source
SHA-256 checksum
How to use checksums
0a2cd406dca8a541e137230f360ff46a849608ec8aaa80bfb9eccbdb023b4c99
BLAKE2b-256 checksum
How to use checksums
f600cd01a321ed38fe1cca155dca70cc843d425fa0bd864381781432bba182ad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.13

Release files / guardnet-0.1.5-py3-none-any.whl

Download URL guardnet-0.1.5-py3-none-any.whl
Size 5.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e21c9281bb0643eec375459d5ece9dd0682ccb5c3c6d5d07a621fa7dbe3006aa
BLAKE2b-256 checksum
How to use checksums
e3c7a0d8b0f5190d4cabad586388b4a0360c06f0d49b187787a91605b5403875
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.13

Security for guardnet 0.1.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page