~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
204 lines · 14.9 KB Raw History
# Typed OAuth permissions in Zat

**Status** · Direct scope codec and matcher for [Zat #38](https://tangled.org/zat.dev/zat/issues/38). Pure Lexicon expansion is a follow-on design.

A Zat client should be able to construct a valid OAuth scope from typed inputs.
A PDS should be able to turn direct scopes and Lexicon permission entries into
the same permission values, then match those values against concrete
operations. The caller establishes who holds the permission and whether it is
effective. In ZDS that comes from the authenticated credential and its grant.

Zat already supplies identifier parsers, a strict percent decoder, and OAuth
client and proof helpers. ZDS shares its repo, blob and RPC parsers between
admission and enforcement. Other paths still interpret scope strings
independently. For example, the account matcher treats an omitted action as
sufficient for management where the protocol defaults to read. Johanna
Larsson's proposal for Tranquil motivates making the validated value the common
boundary. [Proposal for Tranquil](https://jola.dev/posts/tranquil-scopes-proposal) · [ZDS scope checks](https://tangled.org/zat.dev/zds/blob/fa82734/src/internal/scopes.zig) · [Permission specification](https://atproto.com/specs/permission)

## Public surface

`zat.oauth.permissions` supplies a single-token parser, validating
constructors, a canonical formatter, and per-clause matching. Client and
server callers use the same validated permission values.

| Value | Contract |
| --- | --- |
| `Scope` | One supported wire token. Its cases are a granular permission, an `include` reference, the `atproto` marker, and the specified transition markers. Each can be formatted. |
| `Permission` | One validated granular clause over repo, blob, RPC, account, or identity. Matching accepts only this type. |
| `Requirement` | One concrete operation with a resource-specific payload, such as an action on an exact collection or a call to an exact method on an exact service. It has no wildcard variants. |

Return malformed input and unsupported kinds separately. The caller processes
the list and selects its rejection or extension policy. The initial surface
has no scope-list container or cross-clause normalization. The `atproto`
marker identifies the OAuth profile and contributes zero granular permissions.
The application owns admission and transition-scope policy. [OAuth scopes](https://atproto.com/specs/oauth#authorization-scopes)

Use private tagged unions for the stored payloads. A public Zig struct with a
parser still admits field literals. The proposed design uses an opaque,
immutable owner and borrowed read-only views. A matcher consumes a sealed
permission handle. Views are for inspection. Validating constructors and the
parser share the same semantic checks. Use existing `Nsid.parse` and
`Did.parse` at trust boundaries. A caller-supplied value of either public
struct still needs validation before it can become part of a sealed value.

Successful parse and construction own their backing bytes. Borrowed views
expire with the owner. Provide paired destruction with the caller's allocator
and support arenas. Matching allocates nothing and performs no decoding or
I/O. Formatting writes to a caller-supplied writer and propagates errors.
The caller controls the enclosing byte and token budgets. Use existing
identifier length constraints. Measure long and repeated fields before
introducing any further limits. Avoid quadratic rescans or duplicate elimination on untrusted repeated parameters. [Zig opaque types](https://ziglang.org/documentation/0.17.0/#opaque)

## Permission semantics

| Resource | Representation and matching |
| --- | --- |
| Repo | An explicit all-collections variant or a nonempty set of exact collection NSIDs, paired with a nonempty action set. Omitted actions mean create, update and delete. Partial wildcards and positional/named collisions are invalid. |
| Blob | A nonempty set of exact media types, whole subtype wildcards such as `image/*`, or the explicit `*/*` wildcard. Normalize media type names to ASCII lowercase. Match a validated bare media type. MIME detection and HTTP Content-Type parsing belong to the caller. |
| RPC | Either nonempty exact methods with any audience, or a concrete DID service reference with any method or nonempty exact methods. Both wildcards are unrepresentable. An explicit scope audience requires a service fragment and matches the full reference. An any-audience scope can match a valid bare atproto DID or a valid service reference. |
| Account | A documented attribute, email or repo, and an access level. Omitted action means read. Manage includes read where that read operation exists. Repo read permits no operation. This version rejects `status` and repeated actions. The reference accepts both, while the published attribute list names email and repo and defines a scalar action. |
| Identity | Handle or full identity. Full identity includes handle. Missing attributes and unrecognized parameters are invalid. |
| Include | A permission-set NSID and an optional concrete DID service reference. The reference carries no directly matchable rights. |

Within a clause, use fixed field ordering, normalize equivalent spellings,
collapse redundant values and omit semantic defaults. Keep clauses independent.
Combining “create posts” with “delete likes” must never grant “delete posts.”
The same rule applies to RPC method and audience pairs.

Split wire delimiters before decoding. Decode each component once, reject
malformed escapes and controls, and validate the decoded value. Preserve an
encoded delimiter as data, including a percent escape that belongs to a
DID. The inner scope codec treats literal plus as data and writes
it as `%2B` in queries. The enclosing OAuth transport handles form decoding of
the complete scope parameter. Cover both layers with independent vectors.

Accept the empty query suffix shown in the spec, as in `identity:*?`.
Reject duplicate scalar parameters even when both values are equal. Reject a
positional selector combined with its named equivalent. An unsupported kind
must still have well-formed framing. A recognized kind with an unknown field or
value is malformed for that kind. It must never fall through to an extension
parser. Name matching is byte-exact after decoding, except for the specified
media type normalization.

Use the published spec as the contract and the reference implementation as
an independent compatibility oracle. The checked corpus covers the
reference's `account:status`, repeated account actions, query plus handling,
percent encoding, and MIME wildcard boundaries. The pinned reference uses
`URLSearchParams` for inner queries, which differs from Zat's literal-plus
decoder. The corpus compares accepted inputs and authorization decisions separately
from canonical bytes and records the acceptance differences. [Pinned reference scope implementation](https://github.com/bluesky-social/atproto/tree/3c154e9a63317ebab87f256e0fcfd0eba4086fa5/packages/oauth/oauth-scopes/src) · [Zat percent decoder](https://tangled.org/zat.dev/zat/blob/v0.7.0-alpha.12/src/internal/syntax/percent.zig)

### Initial review vectors

| Input | Expected result |
| --- | --- |
| `atproto` | A profile marker with no granular permission. |
| `account:email` | Matches email read only. |
| `account?attr=email&action=manage` | Canonicalizes to `account:email?action=manage` and matches email read and manage. |
| `identity:*?` | Canonicalizes to `identity:*`. |
| `repo?collection=app.example.post&action=create` | Same grant as `repo:app.example.post?action=create`. Update, delete and other collections fail. |
| `blob?accept=image/png&accept=image/*` | Canonicalizes to `blob:image/*`. Invalid media types and other top-level types fail. |
| `rpc:*?aud=did:web:api.example.com%23svc_appview` | Grants methods on that service only. Another fragment on the same DID fails. |
| `rpc:*?aud=%2A` | Invalid after decoding. |
| `repo:app.example.post?unrecognized=narrower` | Invalid. The matcher never receives a repo grant for this token. |

The request audience follows the [getServiceAuth lexicon](https://github.com/bluesky-social/atproto/blob/3c154e9a63317ebab87f256e0fcfd0eba4086fa5/lexicons/com/atproto/server/getServiceAuth.json).
A bare DID is sufficient for a request checked against `aud=*`. An exact
service grant remains tied to its full reference, including the fragment.
The shared RPC corpus checks these decisions against the reference matcher and
the reference endpoint's audience validation.

## Permission sets and the ZDS boundary

The first export covers direct scope values and the `include` reference. A
second candidate is pure expansion of an already authenticated Lexicon into the
same permission representation. Keep this entry point internal until a caller
demonstrates its input and ownership contract.

Check the expected Lexicon ID and primary definition kind. Validate each
complete repo or RPC entry before emitting any of it. An unknown resource or
field, an invalid value, or an out-of-namespace member invalidates that entry.
Keep valid neighbors and retain entry-level diagnostics separately. Use whole
NSID segments for namespace checks. Reject collection and method wildcards
inside sets. Allow an explicit wildcard RPC audience. An inherited audience
requires the include to supply it and the entry to omit its own audience.
Distinguish document errors, allocation failures and budget failures from
rejected entries. On those errors return no partial expansion. [Permission sets](https://atproto.com/specs/permission#permission-sets) · [Lexicon definitions](https://atproto.com/specs/lexicon#permission-set)

ZDS owns client registration, authenticated Lexicon fetching, caching, consent,
credential kind and token binding. It owns both the approved request, which
can retain `include` references for refresh, and the effective access-token
grant. If ZDS adopts refresh-time resolution, rotation and retries must
persist and return the corresponding token pair and grant consistently.
Previously flattened sessions have no recoverable include provenance. Keep
their fixed grants until reauthorization, with an explicit migration decision
for any legacy strings the standard parser rejects. Dashboard authorization,
delegation ceilings and experimental Spaces policy belong to the application.
[ZDS token issuance](https://tangled.org/zat.dev/zds/blob/fa82734/src/atproto/oauth.zig) · [ZDS Spaces grants](https://tangled.org/zat.dev/zds/blob/fa82734/docs/permissioned-data.md)

## Evidence required before export

Use the pinned Zig and Hegel versions and the existing campaign runner.
Every enabled resource needs positive, negative and boundary coverage.
Round trips establish codec consistency. A separate oracle establishes what
an accepted value can authorize.

| Boundary | Acceptance evidence |
| --- | --- |
| Standards and interoperability | Reviewed, source-attributed allow and deny vectors. A differential driver over the pinned reference compares acceptance and access decisions, with intentional differences enumerated. For expansion, add published permission-set fixtures with provenance and no network dependency during tests. |
| Grammar and formatting | Generate valid clauses independently of the parser. Assert semantic preservation and canonical byte idempotence. Generate equivalent positional and named forms, duplicates, missing selectors, repeated scalars, malformed escapes, literal plus, encoded delimiters, case variants and long fields. Exercise arbitrary bytes for safe failure. |
| Matching | Compare against an independently enumerated relation of concrete actions, collections, media types, methods and audiences. Probe allowed and denied tuples. Narrowing a selector cannot add access. Independent clauses cannot synthesize new tuples. Assert account defaults and compile-check that markers and references cannot go to the matcher. |
| Lexicon expansion | Generate same-group, descendant, sibling, ancestor and prefix-lookalike NSIDs. Mutate one member or field of a valid entry and show it contributes zero rights while valid neighbors survive. Cover audience inheritance and conflicts, mismatched document IDs, and equivalent direct scopes. This gate applies when expansion is considered for export. |
| Memory and errors | Inject failures at each allocation point and at partial writer output. Check cleanup. Overwrite the input after parsing to check ownership. Measure runtime and allocation counts on representative short, long and malformed inputs. Assert matching allocates nothing. |

Run `just check` and `zig build test --summary all`. Add a small per-change
Hegel campaign and separate calibration in `pbt/campaigns.zon`. Record
property keys, seeds, case counts, reached events and replay blobs. Require
behavioral kills for the corresponding mutants, including account read
defaulting to manage, the RPC double wildcard, ignoring an unknown
attenuator, accepting a namespace lookalike, double decoding, and merging
independent clauses. Exercise each mutant in a disposable worktree. Count a
compile error or unreached precondition separately from a behavioral kill.
Keep a deterministic regression for each confirmed defect.
[Zat campaign configuration](https://tangled.org/zat.dev/zat/blob/main/pbt/campaigns.zon)

ZDS issuance, storage and refresh changes require their own integration
evidence. The direct-scope campaign has no account, transport, or persisted grant
state. Bundle-specific namespace and entry rejection gates apply to the later
expansion work.

## Performance and Zig design review

The matcher can read an immutable grant through a borrowed handle with no
allocator argument. Only parse and construction allocate ownership storage.
Compare bytes against normalized selectors, using binary search for exact
names. Long lists sort once and compact in linear passes after sorting.
Pass a writer to formatting so callers can use a fixed buffer, an allocating
buffer or a stream. Zig's testing allocator checks partial allocations and the
unit test overwrites the original input before formatting.

A local Apple M5 Pro benchmark with Zig 0.17.0 ReleaseFast cycled six mixed
allow and deny cases covering repo, blob and RPC. Three runs of one million
decisions had identical checksums of 500,000 matches. The ZDS baseline was
`src/internal/scopes.zig` at `fa82734`.

| Path | Observed time |
| --- | --- |
| ZDS reparse and match | 94–101 ns/op |
| Zat match against a parsed scope | 16–18 ns/op |
| Zat validate, own, match and free with a fixed-buffer allocator | 155–160 ns/op |

This measures the parser/matcher in one process and excludes list admission,
token authentication, network I/O and disk access. The first match pays the
ownership cost. Keep the validated object when checking more operations against
the same scope.

Recheck against a checkout of the baseline ZDS source.

```sh
zig build-exe -O ReleaseFast --dep zat --dep legacy -Mroot=scripts/permission_match_bench.zig \
  -O ReleaseFast -Mzat=src/root.zig --dep zat -O ReleaseFast -Mlegacy=../zds/src/internal/scopes.zig \
  -femit-bin=/tmp/zat-permission-bench
/tmp/zat-permission-bench
```