Winche.Rules 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Winche.Rules --version 1.0.0
                    
NuGet\Install-Package Winche.Rules -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Winche.Rules" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Winche.Rules" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Winche.Rules" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Winche.Rules --version 1.0.0
                    
#r "nuget: Winche.Rules, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Winche.Rules@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Winche.Rules&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Winche.Rules&version=1.0.0
                    
Install as a Cake Tool

Winche.Rules

NuGet

A standalone, Firestore-faithful, JSON-serializable authorization rules engine for .NET. You define document access rules in C# (or load them as data from JSON), and the engine evaluates them in memory — no database call required. It is backend-agnostic: you connect it to your own document store and query model through three small adapter ports. Winche.Rules is the engine that powers Winche.Database's access control, but it carries no dependency on that library and can be used in any .NET project that works with documents at paths and caller claims.


Contents

  1. Core ideas
  2. The value model
  3. Defining rules
  4. Evaluating single-document operations
  5. Authorizing queries (list)
  6. Cross-document conditions (get / exists)
  7. Rules as data (JSON)
  8. Pluggability — connecting your project
  9. Composing rulesets
  10. Public API reference
  11. Requirements and license

Core ideas

Winche.Rules mirrors Firestore Security Rules' authorization model.

Allow-only, default-deny, OR semantics. Every rule is an allow — there is no deny. If no allow rule matches and evaluates to true, the operation is rejected. When multiple rules match a path, access is granted if any one of them evaluates to true.

Rules are not filters. This is the most important design point for list/query operations. The engine does not silently remove documents from a result set. Instead, it analyzes the query's constraints before execution and asks: "Does this query's shape provably guarantee that every result satisfies a read rule?" If yes, the query is allowed. If not, the query is rejected and the client must add the necessary constraints. This is the QueryAnalyzer, and it is sound: it only allows queries it can prove safe; it rejects anything it cannot prove, including rules that use get()/exists(), ternaries, or in.

Single-document operations (get, create, update, delete) are evaluated by loading the document and running the condition in memory. The engine never touches your database on its own; you hand it the pre-loaded document.

Evaluation semantics. A condition grants only when it evaluates to boolean true. Any other outcome — a missing field, a type mismatch, null navigation — denies rather than throws. Errors are swallowed by the evaluator (Firestore semantics).


The value model (RuleValue)

Everything the engine touches is a RuleValue — a neutral, JSON-ish value independent of any storage type. A document is a RuleValue.Map of field names to values.

using Winche.Rules;

// Scalar factories
RuleValue.Null
RuleValue.Bool(true)
RuleValue.Int(42L)
RuleValue.Double(3.14)
RuleValue.String("hello")
RuleValue.Bytes(byteArray)
RuleValue.Timestamp(DateTimeOffset.UtcNow)
RuleValue.Path("users/u1")

// Collections
RuleValue.List(new[] { RuleValue.String("a"), RuleValue.String("b") })
RuleValue.Map(new Dictionary<string, RuleValue>
{
    ["name"]  = RuleValue.String("Alice"),
    ["age"]   = RuleValue.Int(30),
})

RuleValueKind enumerates all kinds: Null, Bool, Int, Double, String, Bytes, Timestamp, Path, List, Map.

Numbers compare across Int/Double by numeric value (Firestore semantics). Comparison across other kinds is undefined and denies.


Defining rules (RulesetBuilder + Expr)

RulesetBuilder

Rules are built with the fluent RulesetBuilder.Build API. Each Match takes a path pattern and a configuration callback. Patterns support:

  • Literal segments — users
  • Single-segment capture — {userId} (binds one path segment to a param)
  • Recursive capture — {doc=**} (must be the last segment; matches the rest of the path at any depth — the current path itself and everything beneath it)

Allow takes a set of operations and a condition expression. Use RuleOperations.Read (= get + list), RuleOperations.Write (= create + update + delete), RuleOperations.All, or RuleOperations.Of(...) for an explicit set.

using Winche.Rules;
using Winche.Rules.Expressions;

var rules = RulesetBuilder.Build(r =>
    r.Match("users/{userId}", u =>
    {
        // Owner can read their own document
        u.Allow(RuleOperations.Read,  Expr.Resource("data", "ownerId").Eq(Expr.Auth("uid")));
        // Owner can write (create/update/delete) to their own path
        u.Allow(RuleOperations.Write, Expr.Auth("uid").Eq(Expr.Param("userId")));

        // Nested match — public posts under each user
        u.Match("posts/{postId}", p =>
            p.Allow(RuleOperations.Read, Expr.Const(true)));
    }));

The Expr vocabulary

Expr is a static fluent factory that mirrors Firestore's expression language.

Roots:

Factory What it maps to
Expr.Resource(...) resource then the given field path — the existing document
Expr.Request(...) request then the given path
Expr.RequestResource(...) request.resource then the given path — the incoming (post-write) document
Expr.Auth(...) request.auth then the given path — caller claims (uid, token.role, …)
Expr.Param("userId") A path-capture variable ({userId} from the match pattern)
Expr.Time() request.time
Expr.Method() request.method
Expr.Const(value) A literal (bool, string, long, or double)
Expr.Value(ruleValue) A literal from a RuleValue
Expr.Null The null literal

Navigation (on any expression)

expr.Field("fieldName")          // member access: expr.fieldName
expr.Index(indexExpr)            // index access:  expr[indexExpr]

Comparisons (extension methods, return a new expression)

expr.Eq(other)   expr.Ne(other)
expr.Lt(other)   expr.Le(other)
expr.Gt(other)   expr.Ge(other)
// Overloads accept a string, long, or bool constant directly:
Expr.Auth("uid").Eq("alice")

Membership and logic:

item.In(collection)              // item in list-or-map
expr.And(other)                  // binary AND
expr.Or(other)                   // binary OR
expr.Not()                       // logical NOT
Expr.All(expr1, expr2, ...)      // n-ary AND (vacuously true when empty)
Expr.Any(expr1, expr2, ...)      // n-ary OR  (vacuously false when empty)

Ternary:

new ConditionalExpr(condition, thenExpr, elseExpr)

Built-in functions:

Expr.Exists(pathExpr)            // exists(path) — requires IDocumentSource
Expr.Get(pathExpr)               // get(path)    — requires IDocumentSource
Expr.Size(valueExpr)             // size(string|list|map)

Examples:

// resource.data.public == true || resource.data.ownerId == request.auth.uid
Expr.Any(
    Expr.Resource("data", "public").Eq(true),
    Expr.Resource("data", "ownerId").Eq(Expr.Auth("uid")))

// Guard against unauthenticated callers before reading auth.uid
Expr.All(
    Expr.Auth().Ne(Expr.Null),
    Expr.Resource("data", "ownerId").Eq(Expr.Auth("uid")))

// request.auth.uid in resource.data.members
Expr.Auth("uid").In(Expr.Resource("data", "members"))

// size(resource.data.tags) <= 10
Expr.Size(Expr.Resource("data", "tags")).Le(Expr.Const(10L))

// Age gate
Expr.Resource("data", "age").Ge(Expr.Const(18L))

// Incoming document must set ownerId to the caller's uid
Expr.RequestResource("data", "ownerId").Eq(Expr.Auth("uid"))

Evaluating single-document operations

Use RulesetEvaluator.AllowsAsync for get, create, update, and delete. For list (queries), use QueryAnalyzer instead (see the next section).

using Winche.Rules;
using Winche.Rules.Evaluation;

bool allowed = await RulesetEvaluator.AllowsAsync(
    ruleset,
    RuleOperation.Get,
    "users/u1",         // the full document path being accessed
    context);

Building a RuleContext

RuleContext carries everything the condition needs. You build it from your own types by converting them to RuleValue.

var context = new RuleContext
{
    // The existing document as a map — convention: { data: {...}, id: "...", __name__: path }
    // Set to RuleValue.Null when the document does not exist (e.g. for a create).
    Resource = RuleValue.Map(new Dictionary<string, RuleValue>
    {
        ["data"]     = RuleValue.Map(new Dictionary<string, RuleValue>
        {
            ["ownerId"] = RuleValue.String("u1"),
        }),
        ["__name__"] = RuleValue.Path("users/u1"),
    }),

    // The request object — a map with at minimum "auth" and "method"
    Request = RuleValue.Map(new Dictionary<string, RuleValue>
    {
        ["method"]   = RuleValue.String("get"),
        ["auth"]     = RuleValue.Map(new Dictionary<string, RuleValue>
        {
            ["uid"]  = RuleValue.String("u1"),
        }),
        // Include "resource" (the post-write doc) for create/update
        ["resource"] = RuleValue.Null,
    }),

    // Optionally pass extra params (path captures added by the evaluator take precedence)
    Params = RuleContext.NoParams,

    // Implement IDocumentSource only when rules use get()/exists()
    Documents = null,
};

The evaluator matches the document path against each rule's path pattern, binds the captured segments (e.g. userId from users/{userId}) as params, then evaluates the condition. It returns true if any matching allow rule evaluates to true; otherwise false (default-deny).


Authorizing queries (list)

QueryAnalyzer.Allows performs static analysis: it proves that the query's constraints are sufficient to satisfy a read rule for every possible result. It never executes the query.

using Winche.Rules;
using Winche.Rules.Evaluation;
using Winche.Rules.Expressions;
using Winche.Rules.Querying;

// Rule: allow read if resource.data.ownerId == request.auth.uid
var rules = RulesetBuilder.Build(r =>
    r.Match("users/{userId}", u =>
        u.Allow(RuleOperations.Read,
            Expr.Resource("data", "ownerId").Eq(Expr.Auth("uid")))));

// Map each of your query's where-clauses to a QueryConstraint.
// Field path is relative to resource.data.
var constrainedQuery = new QueryConstraints(
    collection: "users",
    constraints: [new QueryConstraint(["ownerId"], CompareOp.Eq, RuleValue.String("u1"))]);

var openQuery = new QueryConstraints("users", []);

var context = new RuleContext
{
    Request = RuleValue.Map(new Dictionary<string, RuleValue>
    {
        ["method"] = RuleValue.String("list"),
        ["auth"]   = RuleValue.Map(new Dictionary<string, RuleValue>
        {
            ["uid"] = RuleValue.String("u1"),
        }),
    }),
};

bool allowed  = QueryAnalyzer.Allows(rules, constrainedQuery, context);  // true  — ownerId == uid proven
bool rejected = QueryAnalyzer.Allows(rules, openQuery,        context);  // false — unconstrained, rejected

A query is allowed only when the analyzer can prove, from the constraints alone, that the condition holds for every document the query could return. An unconstrained query against an owner-filtered rule is always rejected — the client must add the where clause.

The analyzer handles:

  • Equality pinning (ownerId == "u1" proves ownerId == auth.uid when uid == "u1")
  • Exact range match (query age >= 18 proves rule age >= 18)
  • Equality-derived range (query age == 20 proves rule age >= 18)
  • OR rules (a query that proves either branch is allowed)
  • Subcollections with bound parent captures
  • Recursive wildcards ({doc=**})

The analyzer rejects (returns false) for any rule or query it cannot prove, including those involving get()/exists(), in, ternaries, or per-result path wildcards compared against auth.uid.


Cross-document conditions (get / exists)

Rules can reference other documents via Expr.Get and Expr.Exists. You back these by implementing IDocumentSource:

using Winche.Rules.Evaluation;

public sealed class MyDocumentSource(IMyStore store) : IDocumentSource
{
    public async Task<bool> ExistsAsync(string path, CancellationToken ct = default)
        => await store.ExistsAsync(path, ct);

    public async Task<RuleValue> GetAsync(string path, CancellationToken ct = default)
    {
        var doc = await store.GetAsync(path, ct);
        if (doc is null) return RuleValue.Null;
        return RuleValue.Map(new Dictionary<string, RuleValue>
        {
            ["data"] = /* convert doc.Fields to RuleValue.Map */,
        });
    }
}

Pass an instance as RuleContext.Documents. When a rule calls exists(path) or get(path), the evaluator delegates to this interface. Reads should be scoped to the current request, cached, and capped to prevent unbounded lookups.

// Rule: allow read if the user's team document is active
var rules = RulesetBuilder.Build(r =>
    r.Match("docs/{id}", d =>
        d.Allow(RuleOperations.Read, Expr.All(
            Expr.Exists(Expr.Const("teams/t1")),
            Expr.Get(Expr.Const("teams/t1")).Field("data").Field("active").Eq(true)))));

var context = new RuleContext
{
    Request    = /* ... */,
    Documents  = new MyDocumentSource(store),
};

bool allowed = await RulesetEvaluator.AllowsAsync(rules, RuleOperation.Get, "docs/d1", context);

Note: QueryAnalyzer always rejects queries against rules that use get()/exists() — cross-document lookups cannot be proven statically.


Rules as data (JSON)

Rulesets and expressions are fully serializable. Use RuleJson for round-trips:

using Winche.Rules;
using Winche.Rules.Json;

// Serialize
string json = RuleJson.Serialize(ruleset);

// Deserialize
Ruleset restored = RuleJson.DeserializeRuleset(json);

// Expression round-trip
string exprJson    = RuleJson.Serialize(Expr.Resource("data", "ownerId").Eq(Expr.Auth("uid")));
RuleExpr restored  = RuleJson.DeserializeExpr(exprJson);

Expression nodes use a kind discriminator ("lit", "var", "member", "index", "compare", "and", "or", "not", "in", "cond", "call"). RuleValue uses natural JSON for common kinds and tagged single-key objects for kinds JSON cannot faithfully represent:

Kind JSON representation
Null null
Bool true / false
String "..."
List [...]
Map {...}
Int {"$int":"42"}
Double {"$double":3.14}
Timestamp {"$ts":"2025-01-01T00:00:00+00:00"}
Bytes {"$bytes":"<base64>"}
Path {"$path":"users/u1"}

Map field names must not begin with $ (Firestore reserves this prefix too).


Pluggability — connecting your project

The engine needs three adapters, all of which you provide:

  1. Entity → RuleValue — convert each document from your storage type to a RuleValue.Map with a data key (and optionally id, __name__). This is pure mapping code; no interface is required.

  2. Query → QueryConstraints — map each where clause of your query to a QueryConstraint(fieldPath, op, value) and wrap them in a QueryConstraints(collection, constraints).

  3. Store → IDocumentSource — implement ExistsAsync/GetAsync over your backing store. Only required when rules use get()/exists().

The engine fits any system that has documents at paths and per-request caller claims. The caller claims shape is whatever you put in request.auth; the conditions reference it with Expr.Auth(...).


Composing rulesets

Ruleset.Merge concatenates the match blocks from multiple rulesets into one. Because evaluation uses OR/default-deny semantics, block order does not affect the authorization decision — a request is allowed if any block grants it.

var merged = Ruleset.Merge([usersRuleset, ordersRuleset, adminRuleset]);

// An empty sequence returns a deny-all ruleset
var denyAll = Ruleset.Merge([]);

This is useful for assembling per-module rulesets at startup, or for merging a base ruleset with an override layer.


Public API reference

Winche.Rules

Type Role
RuleValue The universal value struct. Factories: Null, Bool, Int, Double, String, Bytes, Timestamp, Path, List, Map.
RuleValueKind Enum of all value kinds.
Ruleset Immutable record: IReadOnlyList<MatchBlock> Matches. static Merge(IEnumerable<Ruleset>).
MatchBlock (string Path, IReadOnlyList<AllowRule> Allow, IReadOnlyList<MatchBlock> Matches)
AllowRule (IReadOnlyList<RuleOperation> Operations, RuleExpr Condition)
RuleOperation Enum: Get, List, Create, Update, Delete.
RuleOperations Static sets: Read, Write, All, Of(params RuleOperation[]).
RulesetBuilder static Build(Action<RulesetBuilder>) + Match(path, configure).
MatchBuilder Allow(IEnumerable<RuleOperation>, RuleExpr) + Match(path, configure).
RulesetEvaluator static Task<bool> AllowsAsync(Ruleset, RuleOperation, string path, RuleContext, CancellationToken).

Winche.Rules.Expressions

Type Role
RuleExpr Abstract base record for all expression nodes.
LiteralExpr (RuleValue Value)
VarExpr (string Name)
MemberExpr (RuleExpr Target, string Name)
IndexExpr (RuleExpr Target, RuleExpr Index)
CompareExpr (RuleExpr Left, CompareOp Op, RuleExpr Right)
AndExpr (IReadOnlyList<RuleExpr> Operands)
OrExpr (IReadOnlyList<RuleExpr> Operands)
NotExpr (RuleExpr Operand)
InExpr (RuleExpr Item, RuleExpr Collection)
ConditionalExpr (RuleExpr Condition, RuleExpr Then, RuleExpr Else)
CallExpr (string Name, IReadOnlyList<RuleExpr> Args)
CompareOp Enum: Eq, Ne, Lt, Le, Gt, Ge.
Expr Static fluent factory — see Defining rules.
RuleExprExtensions Extension methods: Field, Index, Eq, Ne, Lt, Le, Gt, Ge, In, And, Or, Not.

Winche.Rules.Evaluation

Type Role
RuleEvaluator static Task<bool> EvaluateAsync(RuleExpr, RuleContext, CancellationToken).
RuleContext Resource, Request, Params, Documents. static NoParams.
IDocumentSource Task<bool> ExistsAsync(string, CancellationToken) + Task<RuleValue> GetAsync(string, CancellationToken).
RuleEvaluationException Thrown internally on evaluation errors; caught by RuleEvaluator which returns false.

Winche.Rules.Querying

Type Role
QueryAnalyzer static bool Allows(Ruleset, QueryConstraints, RuleContext).
QueryConstraints (string Collection, IReadOnlyList<QueryConstraint> Constraints).
QueryConstraint (IReadOnlyList<string> Field, CompareOp Op, RuleValue Value).

Winche.Rules.Json

Type Role
RuleJson Serialize(RuleExpr), DeserializeExpr(string), Serialize(Ruleset), DeserializeRuleset(string). static JsonSerializerOptions Options.
RuleValueJsonConverter System.Text.Json converter for RuleValue; applied automatically via [JsonConverter].

Requirements and license

Target framework: .NET 10 (net10.0)

License: Elastic License 2.0 — see LICENSE.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on Winche.Rules:

Package Downloads
Winche.Database

A JSON document database layer built on top of PostgreSQL. Store, query, and subscribe to JSON documents — with PostgreSQL as the storage backend via JSONB.

Winche.Storage

PostgreSQL-backed file metadata store with path-based access control, webhook hooks, and pluggable archive backends.

Winche.Console

An embeddable admin console for Winche.Database and Winche.Storage. Drop it into your ASP.NET Core app to browse and edit JSON documents and manage stored files through a web UI, with its own authentication and role-based access.

Winche.Assets

Versioned app content (translations, pages, media): releases on channels, per-path rules, stored once by hash in a configurable location.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.0.0 348 11/16/2026
4.0.0 181 11/12/2026
3.1.0 162 11/10/2026
3.0.0 687 7/5/2026
2.1.0 841 6/16/2026
2.0.0 273 6/14/2026
1.0.0 178 6/10/2026