plexus_core/plexus/schema.rs
1/// JSON Schema types with strong typing
2///
3/// This module provides strongly-typed JSON Schema structures that plugins
4/// use to describe their methods and parameters.
5///
6/// Schema generation is fully automatic via schemars. By using proper types
7/// (uuid::Uuid instead of String) and doc comments, schemars generates complete
8/// schemas with format annotations, descriptions, and required arrays.
9
10use schemars::{JsonSchema, schema_for};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13
14use plexus_auth_core::{
15 AttachmentSite, CredentialFieldMarker, CredentialIssuer, CredentialKind, CredentialMetadata,
16};
17
18/// Re-exported so macro-generated code (R-1: `#[plexus::method(scope = "...")]`)
19/// can construct `RequiredCredential` scope values through `plexus-core`'s
20/// path alone — consumers don't need a direct `plexus-auth-core` dependency
21/// (the umbrella path `::plexus_rpc::core::plexus::schema::Scope` also
22/// resolves, per Z2H-2).
23pub use plexus_auth_core::Scope;
24
25use super::bidirectional::{StandardRequest, StandardResponse};
26use super::content_hash::{canonical_json, hash16, hash16_lines};
27
28// =============================================================================
29// Method Role
30// =============================================================================
31
32/// Describes how a method participates in the activation graph.
33///
34/// Every method on a plugin is exactly one of three kinds:
35///
36/// - `Rpc` — a regular RPC endpoint (the default).
37/// - `StaticChild` — the method returns a child activation by a static name
38/// (no lookup argument). Used by `#[child]`-annotated methods on hubs.
39/// - `DynamicChild { .. }` — the method gates a dynamic child keyed by its
40/// argument. `list_method` optionally names a sibling method that enumerates
41/// available keys, and `search_method` optionally names a sibling method
42/// that searches keys.
43///
44/// This tag is consumed by downstream tooling (synapse, synapse-cc,
45/// introspection clients) to reconstruct the child graph without a separate
46/// side-table. Today's macros emit `MethodRole::Rpc` for every method; IR-3
47/// populates child roles from `#[child]` annotations.
48///
49/// # Wire back-compat
50///
51/// Added in IR-2. Serde defaults to `Rpc` for pre-IR schemas.
52/// `#[non_exhaustive]` reserves space for future variants without breaking
53/// downstream match arms.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
55#[serde(tag = "kind", rename_all = "snake_case")]
56#[non_exhaustive]
57pub enum MethodRole {
58 /// Method is an RPC endpoint (the default for ordinary methods).
59 Rpc,
60 /// Method returns a child activation by static name (no lookup arg).
61 StaticChild,
62 /// Method gates a dynamic child keyed by its argument.
63 DynamicChild {
64 /// Optional sibling method that lists available keys.
65 #[serde(default, skip_serializing_if = "Option::is_none")]
66 list_method: Option<String>,
67 /// Optional sibling method that searches available keys.
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 search_method: Option<String>,
70 },
71}
72
73impl Default for MethodRole {
74 fn default() -> Self {
75 MethodRole::Rpc
76 }
77}
78
79// =============================================================================
80// Deprecation Info
81// =============================================================================
82
83/// Structured deprecation metadata attached to a `MethodSchema`.
84///
85/// Downstream consumers (CLI help, docs generators, IDEs) use these fields
86/// to surface migration guidance to users.
87///
88/// # Example
89///
90/// ```
91/// use plexus_core::DeprecationInfo;
92///
93/// let info = DeprecationInfo {
94/// since: "0.5".into(),
95/// removed_in: "0.6".into(),
96/// message: "Use `new_method` instead.".into(),
97/// };
98/// ```
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
100pub struct DeprecationInfo {
101 /// The plexus-core version at which deprecation began (e.g., `"0.5"`).
102 pub since: String,
103 /// The plexus-core version planned for removal (e.g., `"0.6"`).
104 ///
105 /// Not binding — serves as a consumer-visible hint.
106 pub removed_in: String,
107 /// Human-readable migration guidance.
108 pub message: String,
109}
110
111// =============================================================================
112// Param Schema
113// =============================================================================
114
115/// Per-parameter metadata for a method's parameters.
116///
117/// `MethodSchema.params` already carries the fine-grained JSON Schema for the
118/// combined parameter object. `ParamSchema` carries orthogonal, parameter-
119/// scoped metadata that doesn't fit on a JSON Schema node — currently just
120/// deprecation info (IR-5).
121///
122/// The `name` field matches the parameter identifier in the method signature
123/// so consumers can correlate entries against the `params` JSON Schema's
124/// `properties` map.
125///
126/// Added in IR-5. Defaults to an empty list on `MethodSchema` so pre-IR
127/// schemas deserialize cleanly.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
129pub struct ParamSchema {
130 /// Parameter name, matching the identifier in the method signature.
131 pub name: String,
132 /// If set, this parameter is deprecated.
133 ///
134 /// Populated by `#[deprecated(...)]` (+ optional
135 /// `#[plexus_macros::removed_in("...")]`) on the parameter in the
136 /// method signature (IR-5).
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub deprecation: Option<DeprecationInfo>,
139}
140
141impl ParamSchema {
142 /// Create a new `ParamSchema` carrying just a name and no metadata.
143 pub fn new(name: impl Into<String>) -> Self {
144 Self {
145 name: name.into(),
146 deprecation: None,
147 }
148 }
149
150 /// Attach deprecation metadata for this parameter.
151 pub fn with_deprecation(mut self, info: DeprecationInfo) -> Self {
152 self.deprecation = Some(info);
153 self
154 }
155}
156
157// =============================================================================
158// Credential projections (AUTHZ-CRED-CORE-3)
159// =============================================================================
160
161/// One entry per credential-bearing field in a method's return type.
162///
163/// Pinned by `AUTHZ-CRED-S01-output.md` §4 and `AUTHZ-CRED-CORE-3` §"Required
164/// behavior". Projected onto `MethodSchema.credentials` at schema-build time
165/// from the `CredentialFieldMarker` registry the `#[derive(Credentials)]` macro
166/// emits per credential-bearing type (`AUTHZ-CRED-MACRO-1`).
167///
168/// # Field path semantics (Tier B Q-IR-1)
169///
170/// `field_path` is the JSON-object path to the credential field within the
171/// method's return type. v1 always uses object-field paths (one segment per
172/// field name walked); array indices and JSON Pointer syntax are intentionally
173/// excluded because credentials always live on object fields in v1, never
174/// inside array elements.
175///
176/// Example: for a return type
177/// `struct LoginResult { session: Credential<String> }`, the field path is
178/// `["session"]`. For a nested case
179/// `struct LoginResult { auth: AuthBundle }` where `AuthBundle` itself
180/// declares a `#[plexus::credential(..)]` field `token: Credential<String>`,
181/// the field path is `["auth", "token"]`.
182///
183/// # Variant tagging
184///
185/// `variant_tag` is `Some(tag)` when the method's return type is an enum and
186/// the credential lives on a single variant. The tag matches the variant
187/// identifier as the macro registry records it (e.g. `"Issued"` for the
188/// `LoginEvent::Issued` variant). `None` means the return type is a struct,
189/// or the credential appears on every variant of the enum (rare).
190///
191/// # Wire back-compat
192///
193/// Added in `AUTHZ-CRED-CORE-3`. Pre-existing readers tolerate `credentials:
194/// []` (the default on `MethodSchema` when no credentials are declared) and
195/// pre-existing IRs that omit the field altogether decode cleanly via
196/// `#[serde(default)]` on the field site.
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
198pub struct CredentialFieldDecl {
199 /// JSON-object path to the credential field within the method's return
200 /// type. One segment per field-name walk; pinned to object paths (no
201 /// array indices, no JSON Pointer) per Tier B Q-IR-1.
202 pub field_path: Vec<String>,
203
204 /// Variant tag when the return type is an enum and the credential lives
205 /// on a single variant. `None` for structs.
206 #[serde(default, skip_serializing_if = "Option::is_none")]
207 pub variant_tag: Option<String>,
208
209 /// The credential's metadata (kind, attach site, scheme, scopes, expiry,
210 /// refresh/revoke hints, issuer, sensitivity). Carried verbatim so
211 /// consumers embed identical storage-and-attach logic to the runtime.
212 pub metadata: CredentialMetadata,
213}
214
215impl CredentialFieldDecl {
216 /// Construct a `CredentialFieldDecl` by composing a `CredentialFieldMarker`
217 /// from the macro-emitted registry with the runtime-supplied pieces
218 /// (`expires_at` known only at mint time; `issuer` known at schema-build
219 /// time from the originating method's `(Origin, MethodPath)`).
220 ///
221 /// `path_prefix` is the field-path walk to the marker's parent type — for
222 /// a flat struct it is empty; for a nested case where this marker lives
223 /// inside a field of the method's return type the prefix is the path to
224 /// that wrapping field. The marker's own `field` and `variant` are
225 /// appended.
226 pub fn from_marker(
227 marker: &CredentialFieldMarker,
228 path_prefix: &[&str],
229 issuer: CredentialIssuer,
230 ) -> Self {
231 let mut field_path: Vec<String> = path_prefix.iter().map(|s| (*s).to_owned()).collect();
232 field_path.push(marker.field.to_owned());
233 let variant_tag = marker.variant.map(|v| v.to_owned());
234 let metadata = marker.to_metadata(None, issuer);
235 Self {
236 field_path,
237 variant_tag,
238 metadata,
239 }
240 }
241}
242
243/// What a method requires on input — the implicit-derivation projection of
244/// scope tagging and credential-graph linkage onto a per-method filter.
245///
246/// Pinned by `AUTHZ-CRED-S01-output.md` §4 (Q-SELECT-1 resolution: implicit
247/// derivation from scope tagging plus refresh/revoke linkage) and
248/// `AUTHZ-CRED-CORE-3` §"Implicit derivation". This ticket explicitly does
249/// NOT add a `#[plexus::method(requires_credential = { .. })]` attribute
250/// surface — the proposal from `AUTHZ-CRED-S01-output` §10 is superseded by
251/// the implicit-derivation approach pinned here.
252///
253/// # Matching semantics (consumer-side)
254///
255/// A candidate credential matches this `RequiredCredential` iff:
256/// 1. `kind`: if `Some(k)`, the candidate's `CredentialMetadata.kind`
257/// matches `k` (or the kind-subsumption table per `AUTHZ-CRED-CORE-1`
258/// accepts the substitution; e.g. `OauthAccess <: Bearer`). If `None`,
259/// any kind whose scope set matches is acceptable.
260/// 2. `scopes`: each scope in this set must be wildcard-matched by the
261/// candidate's `CredentialMetadata.scopes`. The wildcard rules belong to
262/// the `Scope` type itself.
263/// 3. `site_hint`: when populated, prefers the candidate whose
264/// `CredentialMetadata.attach_as` equals the hint. Advisory only — a
265/// candidate without the hint is not rejected.
266///
267/// # Wire back-compat
268///
269/// Added in `AUTHZ-CRED-CORE-3`. Pre-existing readers tolerate
270/// `requires_credential: null` (omitted on the wire when `None`) and
271/// pre-existing IRs that omit the field altogether decode cleanly via
272/// `#[serde(default)]` on the field site.
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
274pub struct RequiredCredential {
275 /// Specific kind a candidate credential must have (e.g.,
276 /// `OauthRefresh`), or `None` for "any kind whose scope set matches".
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub kind: Option<CredentialKind>,
279
280 /// Required scope set. A candidate credential's metadata scopes must
281 /// wildcard-match each scope in this set.
282 #[serde(default, skip_serializing_if = "Vec::is_empty")]
283 pub scopes: Vec<Scope>,
284
285 /// Preferred attach site for the client to use when the candidate
286 /// credential has multiple alternates. Advisory only.
287 #[serde(default, skip_serializing_if = "Option::is_none")]
288 pub site_hint: Option<AttachmentSite>,
289}
290
291impl RequiredCredential {
292 /// Derive a `RequiredCredential` from a method's required scope tagging
293 /// (per `AUTHZ-S01-output` §4). The `kind` field is left `None` — any
294 /// kind whose scope set wildcard-matches `scope` is acceptable.
295 ///
296 /// Used when a method declares `#[plexus::method(scope = "...")]` (or
297 /// the framework derives an implicit scope from the method's path).
298 pub fn from_method_scope(scope: Scope) -> Self {
299 Self {
300 kind: None,
301 scopes: vec![scope],
302 site_hint: None,
303 }
304 }
305
306 /// Multi-scope variant of [`Self::from_method_scope`] for methods that
307 /// declare `scope = "..."` more than once (AUTHZ-CORE-2: the caller must
308 /// satisfy ALL listed scopes — conjunction, not alternation). The `kind`
309 /// field is left `None` — any kind whose scope set wildcard-matches every
310 /// listed scope is acceptable.
311 ///
312 /// Added in R-2 (`ir-credential-emission`) alongside the macro-side
313 /// population (R-1).
314 pub fn from_method_scopes(scopes: Vec<Scope>) -> Self {
315 Self {
316 kind: None,
317 scopes,
318 site_hint: None,
319 }
320 }
321
322 /// Derive a `RequiredCredential` for a method that appears as the target
323 /// of another credential's `metadata.refresh_via` or `metadata.revoke_via`
324 /// (per `AUTHZ-CRED-CORE-3` §"Implicit derivation" row 3). The `kind`
325 /// field narrows to the issuing credential's kind so the selection step
326 /// picks the right kind (e.g., `OauthRefresh` for the
327 /// `auth.refresh` call on an `OauthAccess` credential per the OAuth
328 /// flow described in `AUTHZ-CRED-S01-output` §7.2).
329 pub fn from_refresh_revoke_target(kind: CredentialKind, scopes: Vec<Scope>) -> Self {
330 Self {
331 kind: Some(kind),
332 scopes,
333 site_hint: None,
334 }
335 }
336
337 /// CA-1 (trak facet `ccc924ad-0e78-4d4b-b71f-0018d249d0bf`): fill
338 /// `site_hint` with the hub-derived attach site — but only when no hint
339 /// is already present. An explicitly-populated hint (e.g. a future
340 /// per-method override, or a refresh/revoke derivation that learned the
341 /// site from the issuing credential) always wins over the
342 /// capability-derived default.
343 pub fn fill_site_hint(&mut self, site: &AttachmentSite) {
344 if self.site_hint.is_none() {
345 self.site_hint = Some(site.clone());
346 }
347 }
348}
349
350// =============================================================================
351// Auth Posture
352// =============================================================================
353
354/// Declared auth-enforcement posture of the activation a method belongs to.
355///
356/// Mirrors `plexus-macros`' RED-6 `auth = "required" | "optional" | "mixed" |
357/// "none"` activation attribute, which until R-1/R-2 (the ROLES+AP merged
358/// wave) was parsed and compile-enforced but never emitted — invisible to
359/// every downstream IR consumer (synapse, hub-codegen, generated clients).
360///
361/// Semantics (compile-time enforcement lives in plexus-macros; this is the
362/// escaped declaration):
363///
364/// - `Required` — every method is auth-gated (`#[from_auth]`) or explicitly
365/// `public`.
366/// - `Optional` — no enforcement; auth may be asymmetric across methods.
367/// - `Mixed` — like `Optional`, but the asymmetry is explicitly acknowledged.
368/// - `None` — affirmatively public activation; no method takes auth.
369///
370/// # Wire back-compat
371///
372/// Added in R-2 (joint AP-1). Pre-existing readers tolerate the field's
373/// absence (`auth_posture` is omitted on the wire when the activation never
374/// declared a posture) and pre-existing IRs that omit the field decode
375/// cleanly via `#[serde(default)]` on the field site. `#[non_exhaustive]`
376/// reserves space for future postures without breaking downstream match arms.
377#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
378#[serde(rename_all = "snake_case")]
379#[non_exhaustive]
380pub enum AuthPosture {
381 /// Every method is auth-gated or explicitly public.
382 Required,
383 /// No enforcement; auth may be asymmetric across methods.
384 Optional,
385 /// Asymmetric auth, explicitly acknowledged.
386 Mixed,
387 /// Affirmatively public activation; no method takes auth.
388 None,
389}
390
391// =============================================================================
392// Cardinality
393// =============================================================================
394
395/// How many items a method yields: exactly one, or a stream of them.
396///
397/// Read from the method's signature (RETURNS-1 decision 2): a plain return
398/// type (`-> T`, `-> Result<T, E>`) is [`Cardinality::One`]; `-> impl
399/// Stream<Item = …>` is [`Cardinality::Many`]. A reader decides how to present
400/// a method (a single awaited value vs. a stream) from this field alone —
401/// never from the presence of a stream type or a guess at the item's shape.
402///
403/// Serialized as `"one"` / `"many"`.
404#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
405#[serde(rename_all = "snake_case")]
406pub enum Cardinality {
407 /// The method yields exactly one item.
408 One,
409 /// The method yields a stream of zero or more items.
410 Many,
411}
412
413// =============================================================================
414// HTTP Method Enum
415// =============================================================================
416
417/// HTTP method for REST endpoint routing
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
419#[serde(rename_all = "UPPERCASE")]
420pub enum HttpMethod {
421 /// GET: Idempotent read operations with no side effects
422 Get,
423 /// POST: Create operations or non-idempotent actions (default)
424 Post,
425 /// PUT: Replace/update operations (idempotent)
426 Put,
427 /// DELETE: Remove operations (idempotent)
428 Delete,
429 /// PATCH: Partial update operations
430 Patch,
431}
432
433impl Default for HttpMethod {
434 fn default() -> Self {
435 HttpMethod::Post
436 }
437}
438
439impl HttpMethod {
440 /// Parse from string (case-insensitive)
441 pub fn from_str(s: &str) -> Option<Self> {
442 match s.to_uppercase().as_str() {
443 "GET" => Some(HttpMethod::Get),
444 "POST" => Some(HttpMethod::Post),
445 "PUT" => Some(HttpMethod::Put),
446 "DELETE" => Some(HttpMethod::Delete),
447 "PATCH" => Some(HttpMethod::Patch),
448 _ => None,
449 }
450 }
451
452 /// Convert to uppercase string
453 pub fn as_str(&self) -> &'static str {
454 match self {
455 HttpMethod::Get => "GET",
456 HttpMethod::Post => "POST",
457 HttpMethod::Put => "PUT",
458 HttpMethod::Delete => "DELETE",
459 HttpMethod::Patch => "PATCH",
460 }
461 }
462}
463
464// ============================================================================
465// Plugin Schema
466// ============================================================================
467
468/// A plugin's schema with methods and child summaries.
469///
470/// Children are represented as summaries (namespace, description, hash) rather
471/// than full recursive schemas. This enables lazy traversal - clients can fetch
472/// child schemas individually via `{namespace}.schema`.
473///
474/// - Leaf plugins have `children = None`
475/// - Hub plugins have `children = Some([ChildSummary, ...])`
476#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
477pub struct PluginSchema {
478 /// The plugin's namespace (e.g., "echo", "plexus")
479 pub namespace: String,
480
481 /// The plugin's version (e.g., "1.0.0")
482 pub version: String,
483
484 /// Short description of the plugin (max 15 words)
485 pub description: String,
486
487 /// Detailed description of the plugin (optional)
488 #[serde(skip_serializing_if = "Option::is_none")]
489 pub long_description: Option<String>,
490
491 /// Hash of ONLY this plugin's methods (ignores children): of each
492 /// method's `hash`, so it changes whenever any method's schema changes
493 pub self_hash: String,
494
495 /// Hash of ONLY child plugin hashes (None for leaf plugins)
496 /// Changes when any child's hash changes (recursively)
497 #[serde(skip_serializing_if = "Option::is_none")]
498 pub children_hash: Option<String>,
499
500 /// Composite hash = hash(self_hash + children_hash)
501 /// Use this if you want a single hash for the entire subtree
502 pub hash: String,
503
504 /// Methods exposed by this plugin
505 pub methods: Vec<MethodSchema>,
506
507 /// Child plugin summaries (None = leaf plugin, Some = hub plugin)
508 ///
509 /// # Deprecated (IR-4)
510 ///
511 /// This side-table is deterministically derived from the method list's
512 /// `MethodRole` tags (one `ChildSummary` per non-`Rpc` method). It stays
513 /// on the wire for back-compat during the 0.5 transition window and is
514 /// slated for removal in 0.6.
515 ///
516 /// Consumers reading child metadata should switch to iterating
517 /// `methods` and filtering by `role != MethodRole::Rpc`. The name field
518 /// on each `MethodSchema` is the child's namespace.
519 #[serde(skip_serializing_if = "Option::is_none")]
520 #[deprecated(
521 since = "0.5",
522 note = "Derive from MethodRole on MethodSchema. Field will be removed in 0.7."
523 )]
524 pub children: Option<Vec<ChildSummary>>,
525
526 /// JSON Schema for the HTTP request type this activation extracts from incoming connections.
527 ///
528 /// Present when the activation declares `request = MyRequest` in `#[plexus::activation(...)]`.
529 /// The schema includes `x-plexus-source` extension fields on each property describing
530 /// where each field is sourced from (cookie, header, query param, peer address, etc.).
531 ///
532 /// Clients can use this to understand what request data the activation expects and
533 /// to generate appropriate authentication/context documentation.
534 #[serde(skip_serializing_if = "Option::is_none")]
535 pub request: Option<serde_json::Value>,
536
537 /// If set, this whole activation is deprecated.
538 ///
539 /// Added in IR-5. Defaults to `None` via `#[serde(default)]` so pre-IR
540 /// schemas deserialize cleanly.
541 ///
542 /// Populated by the `#[deprecated(...)]` attribute on the `impl
543 /// Activation for Foo` block (IR-5).
544 #[serde(default, skip_serializing_if = "Option::is_none")]
545 pub deprecation: Option<DeprecationInfo>,
546
547 /// AUTH-3: this activation's default roles — role name → the grants it
548 /// lists (`<activation>.<method>`, role inclusion already flattened), as
549 /// declared by `#[plexus_macros::activation(roles(...))]`. `admin` is
550 /// built in and never listed. Empty (and absent on the wire) when the
551 /// activation declares none.
552 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
553 pub roles: std::collections::BTreeMap<String, Vec<String>>,
554
555 /// AUTH-4: which view of a gated hub this schema answers from —
556 /// `anonymous` (only the door: the public methods) or `caller` (the
557 /// methods the caller holds). Absent from every schema a hub without a
558 /// gate answers, so those stay byte-identical.
559 #[serde(default, skip_serializing_if = "Option::is_none")]
560 pub view: Option<ViewKind>,
561}
562
563/// AUTH-4: the two views of a gated hub. On the wire, `"anonymous"` or
564/// `"caller"`.
565#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
566#[serde(rename_all = "snake_case")]
567pub enum ViewKind {
568 /// Not signed in: only how to sign in (the public methods).
569 Anonymous,
570 /// Signed in: the methods whose grant some held role lists.
571 Caller,
572}
573
574impl ViewKind {
575 /// `"anonymous"` / `"caller"`.
576 pub fn as_str(&self) -> &'static str {
577 match self {
578 Self::Anonymous => "anonymous",
579 Self::Caller => "caller",
580 }
581 }
582}
583
584/// Result of a schema query - either full plugin or single method
585#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
586#[serde(untagged)]
587pub enum SchemaResult {
588 /// Full plugin schema (when no method specified)
589 Plugin(PluginSchema),
590 /// Single method schema (when method specified)
591 Method(MethodSchema),
592}
593
594/// Schema for a single method exposed by a plugin
595#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
596pub struct MethodSchema {
597 /// Method name (e.g., "echo", "check")
598 pub name: String,
599
600 /// Human-readable description of what this method does
601 pub description: String,
602
603 /// Content hash of this method's schema (for cache invalidation): 16
604 /// lowercase hex, SHA-256 of every other field as canonical JSON, so it
605 /// changes whenever anything a client is generated from changes
606 pub hash: String,
607
608 /// JSON Schema for the method's parameters (None if no params)
609 #[serde(skip_serializing_if = "Option::is_none")]
610 #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
611 pub params: Option<schemars::Schema>,
612
613 /// JSON Schema for the method's item type `T` — what one success carries.
614 ///
615 /// Always present: every method has a return type. For a `Result<T, E>`
616 /// or `Progress<T, P>` item it is `T` alone — `E` and `P` have fields of
617 /// their own. [`MethodSchema::new`] starts it at the empty schema `{}`
618 /// (any value) until [`MethodSchema::with_returns`] sets it.
619 #[schemars(with = "serde_json::Value")] // a JSON Schema document: the JSON type
620 pub returns: schemars::Schema,
621
622 /// JSON Schema for the method's error type `E` — what the activation says
623 /// when it says no (`-> Result<T, E>`). Absent from the wire when the
624 /// method is infallible.
625 #[serde(default, skip_serializing_if = "Option::is_none")]
626 #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
627 pub error: Option<schemars::Schema>,
628
629 /// JSON Schema for the method's progress type `P` (an item of
630 /// `Progress<T, P>`), carried by progress frames. Absent from the wire
631 /// when the method reports no progress.
632 #[serde(default, skip_serializing_if = "Option::is_none")]
633 #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
634 pub progress: Option<schemars::Schema>,
635
636 /// Whether the method yields one item or many — `"one"` / `"many"`.
637 ///
638 /// Required on the wire: a schema that does not state its cardinality is
639 /// not a 0.7 schema, and guessing would reintroduce the disagreement this
640 /// field exists to end.
641 pub cardinality: Cardinality,
642
643 /// Whether this method supports bidirectional communication
644 ///
645 /// When true, the server can send requests to the client during method execution
646 /// and wait for responses (e.g., confirmations, prompts, selections).
647 #[serde(default)]
648 pub bidirectional: bool,
649
650 /// HTTP method for REST endpoints (GET, POST, PUT, DELETE, PATCH)
651 ///
652 /// This field is used by the HTTP gateway to determine which HTTP method
653 /// to use when exposing this method as a REST endpoint. Defaults to POST
654 /// for backward compatibility.
655 ///
656 /// - GET: Idempotent read operations (no side effects)
657 /// - POST: Create operations or non-idempotent actions (default)
658 /// - PUT: Replace/update operations (idempotent)
659 /// - DELETE: Remove operations (idempotent)
660 /// - PATCH: Partial update operations
661 #[serde(default)]
662 pub http_method: HttpMethod,
663
664 /// JSON Schema for the request type sent from server to client
665 ///
666 /// Only relevant when `bidirectional: true`. Describes the structure of
667 /// requests the server may send during method execution.
668 #[serde(skip_serializing_if = "Option::is_none")]
669 #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
670 pub request_type: Option<schemars::Schema>,
671
672 /// JSON Schema for the response type sent from client to server
673 ///
674 /// Only relevant when `bidirectional: true`. Describes the structure of
675 /// responses the client should send in reply to server requests.
676 #[serde(skip_serializing_if = "Option::is_none")]
677 #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
678 pub response_type: Option<schemars::Schema>,
679
680 /// How this method participates in the activation graph.
681 ///
682 /// Added in IR-2. Defaults to `MethodRole::Rpc` via `#[serde(default)]`
683 /// so pre-IR schemas deserialize cleanly.
684 ///
685 /// Populated by the `#[plexus::method]` / `#[child]` macros (IR-3).
686 #[serde(default)]
687 pub role: MethodRole,
688
689 /// If set, this method is deprecated.
690 ///
691 /// Added in IR-2. Defaults to `None` via `#[serde(default)]` so pre-IR
692 /// schemas deserialize cleanly.
693 ///
694 /// Populated by the `#[deprecated(...)]` attribute on the underlying
695 /// method (IR-5).
696 #[serde(default, skip_serializing_if = "Option::is_none")]
697 pub deprecation: Option<DeprecationInfo>,
698
699 /// Per-parameter metadata (currently just deprecation).
700 ///
701 /// Added in IR-5. Defaults to an empty vec via `#[serde(default)]` so
702 /// pre-IR schemas deserialize cleanly. Only parameters that carry
703 /// metadata appear in this list — absence means "no metadata" for that
704 /// parameter, not a bug.
705 ///
706 /// Populated by the `#[deprecated(...)]` attribute on individual
707 /// parameters (IR-5).
708 #[serde(default, skip_serializing_if = "Vec::is_empty")]
709 pub params_meta: Vec<ParamSchema>,
710
711 /// Credential-bearing fields in this method's return type.
712 ///
713 /// One entry per `#[plexus::credential(...)]`-annotated field on the
714 /// return-type struct/enum, in stable declaration order. Empty when
715 /// the return type contains no credentials.
716 ///
717 /// Added in `AUTHZ-CRED-CORE-3`. Defaults to an empty vec via
718 /// `#[serde(default)]` so pre-IR schemas deserialize cleanly. The
719 /// `skip_serializing_if = "Vec::is_empty"` clause keeps the wire JSON
720 /// shape unchanged for methods with no credential-bearing fields
721 /// (back-compat per the ticket's "Wire-format back-compat" table).
722 ///
723 /// Populated at schema-build time from the `CredentialFieldMarker`
724 /// registry emitted by `#[derive(Credentials)]` (`AUTHZ-CRED-MACRO-1`).
725 #[serde(default, skip_serializing_if = "Vec::is_empty")]
726 pub credentials: Vec<CredentialFieldDecl>,
727
728 /// What credential this method requires on input (if any).
729 ///
730 /// Derived implicitly from the method's scope tagging and the
731 /// credential-graph linkage at schema-build time (per
732 /// `AUTHZ-CRED-CORE-3` §"Implicit derivation"):
733 ///
734 /// - `scope = "..."` → `RequiredCredential::from_method_scope(scope)`.
735 /// - `public` method → `None` (the absence of this field).
736 /// - target of `refresh_via`/`revoke_via` of another credential →
737 /// `RequiredCredential::from_refresh_revoke_target(kind, scopes)`.
738 ///
739 /// Added in `AUTHZ-CRED-CORE-3`. Defaults to `None` via
740 /// `#[serde(default)]` so pre-IR schemas deserialize cleanly. The
741 /// `skip_serializing_if = "Option::is_none"` clause keeps the wire JSON
742 /// shape unchanged for public methods and methods with no scope-derived
743 /// requirement.
744 #[serde(default, skip_serializing_if = "Option::is_none")]
745 pub requires_credential: Option<RequiredCredential>,
746
747 /// Declared auth posture of the activation this method belongs to.
748 ///
749 /// Populated by `#[plexus_macros::activation(auth = "...")]` (R-1) —
750 /// stamped onto every RPC method of the activation. `None` means the
751 /// activation never declared a posture (pre-R-1 emissions and
752 /// posture-silent activations are byte-identical on the wire).
753 ///
754 /// Added in R-2 (joint AP-1). Defaults to `None` via `#[serde(default)]`
755 /// so pre-R IRs decode cleanly; `skip_serializing_if` keeps the wire
756 /// shape unchanged when unset.
757 #[serde(default, skip_serializing_if = "Option::is_none")]
758 pub auth_posture: Option<AuthPosture>,
759
760 /// Whether this method is explicitly public — exempt from the
761 /// default-deny gate (AUTHZ-CORE-2's `#[plexus::method(public)]`).
762 ///
763 /// `public` and a populated `requires_credential` are mutually exclusive
764 /// by construction: the macro rejects `public` + `scope = "..."` at
765 /// compile time.
766 ///
767 /// Added in R-2. Defaults to `false` via `#[serde(default)]` so pre-R
768 /// IRs decode cleanly; `skip_serializing_if` keeps the wire shape
769 /// unchanged for non-public methods (i.e., every pre-R method).
770 #[serde(default, skip_serializing_if = "is_false")]
771 pub public: bool,
772
773 /// AUTH-3: the grant this method is — `<activation>.<method>`, inherent
774 /// (AUTH-1: "every method should be its own grant"). The macro emits it
775 /// for every method; `None` only on a hand-built or pre-AUTH schema, and
776 /// a gate then takes the method's dotted path.
777 ///
778 /// Optional on the wire (`serde(default)`, skipped when unset) so older
779 /// schemas and clients parse unchanged.
780 #[serde(default, skip_serializing_if = "Option::is_none")]
781 pub grant: Option<String>,
782
783 /// AUTH-3: the param that locates what this call acts on
784 /// (`#[plexus_macros::method(target = "id")]`). A gate resolves its
785 /// value to the scopes it lives in and asks for the grant there; a
786 /// method without one is allowed where the grant is held anywhere and
787 /// answers only from there.
788 #[serde(default, skip_serializing_if = "Option::is_none")]
789 pub target: Option<String>,
790
791 /// AUTH-3: the method's `///` doc comment, when it says more than
792 /// `description` (the macro used to drop it whenever `description =
793 /// "..."` was given).
794 #[serde(default, skip_serializing_if = "Option::is_none")]
795 pub long_description: Option<String>,
796
797 /// AUTH-4: in a caller's view of a gated hub, where the caller holds this
798 /// method's grant (`["MENGER"]`, `["*"]`), within its session's ceiling.
799 /// Absent outside a caller's view (and on a public method the caller
800 /// holds nowhere).
801 #[serde(default, skip_serializing_if = "Option::is_none")]
802 pub held_on: Option<Vec<String>>,
803
804 /// SYNAPSE-13: the method's group in a listing (`"read"`, `"write"`, …)
805 /// — one group, like an OpenAPI operation's first tag. Clients list the
806 /// methods of a group together and alphabetically within it.
807 ///
808 /// Optional on the wire (`serde(default)`, skipped when unset) so older
809 /// schemas and clients parse unchanged.
810 #[serde(default, skip_serializing_if = "Option::is_none")]
811 pub group: Option<String>,
812
813 /// BIDIR-8: who may answer a question this method asks mid-call
814 /// (`#[method(answer_by = "person" | "grant:<g>")]`; BIDIR-1
815 /// `answerer`). Absent for the default, `caller` — the call's own
816 /// connection — so a method without the attribute is byte-identical.
817 #[serde(default, skip_serializing_if = "Option::is_none")]
818 pub answer_by: Option<String>,
819
820 /// SYNAPSE-13: worked calls of this method, each its params object and a
821 /// note saying what it does — OpenAPI's `examples`. A client renders them
822 /// as command lines (`synapse … --id MENGER-40 --status Coding`).
823 ///
824 /// Optional on the wire (`serde(default)`, skipped when empty).
825 #[serde(default, skip_serializing_if = "Vec::is_empty")]
826 pub examples: Vec<MethodExample>,
827
828 // BIDIR-6 fills this now. The doc comment below is left as it stands: it
829 // is this field's description in `{ns}.schema`'s own `returns`, so a word
830 // of it moves every service's hash, and with it the metadata of every item.
831 /// SYNAPSE-CC-9: reserved for BIDIR-6 — the JSON Schema of the items a
832 /// client streams *in* to this method (`Input<T>`). Always `None` until
833 /// BIDIR-6 fills it; absent from the wire while `None`, so a schema
834 /// without it is byte-identical to 0.6.1's.
835 #[serde(default, skip_serializing_if = "Option::is_none")]
836 #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
837 pub input: Option<schemars::Schema>,
838}
839
840/// SYNAPSE-13: one worked call of a method — the params it sends and a note
841/// saying what it does (`#[plexus_macros::method(example(note = "…", params
842/// = r#"{…}"#))]`).
843#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
844pub struct MethodExample {
845 /// The params object, as the method takes it.
846 pub params: serde_json::Value,
847 /// What the call does, in a line.
848 #[serde(default, skip_serializing_if = "Option::is_none")]
849 pub note: Option<String>,
850}
851
852impl MethodExample {
853 /// An example of these params, with no note.
854 pub fn new(params: serde_json::Value) -> Self {
855 Self { params, note: None }
856 }
857
858 /// An example of these params, with a note.
859 pub fn with_note(params: serde_json::Value, note: impl Into<String>) -> Self {
860 Self { params, note: Some(note.into()) }
861 }
862}
863
864/// SYNAPSE-13: the JSON Schema extension key on a param's property that lists
865/// the values it is meant to take — a hint for help and completion, never
866/// enforced (the server may accept synonyms, e.g. `active` for `Coding`).
867pub const X_PLEXUS_VALUES: &str = "x-plexus-values";
868
869/// SYNAPSE-CC-9: the JSON type — what a `serde_json::Value` is, the JSON sum
870/// type — as plexus spells it in a schema: `{"type": [these six]}`, in this
871/// order, inline (never a `$ref`), annotations beside it. schemars writes a
872/// `Value` as `true` (or annotations alone); [`spell_json_values`] rewrites
873/// each such position to this, and every `MethodSchema` schema setter applies
874/// it, so the schema says "any JSON value" one way, which a client reads as a
875/// type (SYNAPSE-CC-8's `RefJson`). The owner, 2026-10-29: nothing is opaque.
876pub const JSON_TYPES: [&str; 6] = ["null", "boolean", "number", "string", "array", "object"];
877
878/// SYNAPSE-CC-9: the closed list of keywords synapse reads in a type position
879/// (IR 2.1). Any other is reported by [`foreign_keywords`].
880pub const CONTRACT_KEYWORDS: &[&str] = &[
881 "type", "$ref", "properties", "required", "additionalProperties", "items", "prefixItems",
882 "oneOf", "anyOf", "enum", "const", "format", "minimum", "maximum", "exclusiveMinimum",
883 "exclusiveMaximum", "minLength", "maxLength", "pattern", "minItems", "maxItems", "default",
884 "description", "title", "examples", "deprecated", "$schema", "$defs", "definitions",
885 "x-plexus-source", "x-plexus-values",
886];
887
888/// The keywords that only annotate (or hold definitions): a schema of these
889/// alone accepts any JSON value.
890const ANNOTATIONS: &[&str] = &[
891 "description", "title", "default", "examples", "deprecated", "$schema", "$comment", "readOnly",
892 "writeOnly", "x-plexus-values", "$defs", "definitions",
893];
894
895/// SYNAPSE-CC-9: is this schema node "any JSON value" — `true`, `{}`,
896/// annotations alone, or the spelled JSON type? An injected parameter
897/// (`x-plexus-source`) is not a value a client sends, so never.
898pub fn is_json_type(v: &serde_json::Value) -> bool {
899 match v {
900 serde_json::Value::Bool(true) => true,
901 serde_json::Value::Object(o) => is_json_type_object(o),
902 _ => false,
903 }
904}
905
906fn is_json_type_object(o: &serde_json::Map<String, serde_json::Value>) -> bool {
907 if o.contains_key("x-plexus-source") {
908 return false;
909 }
910 let spelled = match o.get("type") {
911 None => true,
912 Some(serde_json::Value::Array(ts)) => {
913 let set: std::collections::BTreeSet<&str> = ts.iter().filter_map(|t| t.as_str()).collect();
914 ts.len() == JSON_TYPES.len() && JSON_TYPES.iter().all(|t| set.contains(t))
915 }
916 Some(_) => false,
917 };
918 spelled && o.keys().all(|k| k == "type" || ANNOTATIONS.contains(&k.as_str()))
919}
920
921/// SYNAPSE-CC-9: rewrite every "any JSON value" position in `schema` —
922/// `true`, `{}`, annotations alone — to the JSON type
923/// (`{"type": JSON_TYPES}`, annotations kept), through `properties`,
924/// `items`, `prefixItems`, `additionalProperties`, the unions and `$defs`.
925/// Idempotent; a typed node and an injected parameter are left as they are.
926/// In place: a schemars `Schema` is a JSON value, so nothing is copied.
927pub fn spell_json_values(schema: &mut schemars::Schema) {
928 if schema.as_bool() == Some(false) {
929 return; // accepts nothing: no value position
930 }
931 spell_object(schema.ensure_object()); // `true` becomes `{}`, then the JSON type
932}
933
934fn spell(v: &mut serde_json::Value) {
935 if matches!(v, serde_json::Value::Bool(true)) {
936 *v = serde_json::Value::Object(serde_json::Map::new());
937 }
938 if let serde_json::Value::Object(o) = v {
939 spell_object(o);
940 }
941}
942
943fn spell_object(o: &mut serde_json::Map<String, serde_json::Value>) {
944 use serde_json::Value;
945 let any = is_json_type_object(o);
946 for key in ["$defs", "definitions"] {
947 if let Some(Value::Object(m)) = o.get_mut(key) {
948 m.values_mut().for_each(spell);
949 }
950 }
951 if any {
952 o.insert("type".into(), Value::Array(JSON_TYPES.iter().map(|t| Value::String((*t).into())).collect()));
953 return;
954 }
955 if let Some(Value::Object(m)) = o.get_mut("properties") {
956 m.values_mut().for_each(spell);
957 }
958 for key in ["items", "additionalProperties"] {
959 if let Some(x) = o.get_mut(key) {
960 if !matches!(x, Value::Bool(false)) {
961 spell(x);
962 }
963 }
964 }
965 for key in ["prefixItems", "oneOf", "anyOf", "allOf"] {
966 if let Some(Value::Array(xs)) = o.get_mut(key) {
967 xs.iter_mut().for_each(spell);
968 }
969 }
970}
971
972/// SYNAPSE-CC-9: the params of every activation's `schema` method.
973#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
974pub struct SchemaParams {
975 /// One method's schema instead of the whole activation's.
976 #[serde(default, skip_serializing_if = "Option::is_none")]
977 pub method: Option<String>,
978}
979
980impl SchemaParams {
981 /// The params object as a method's `params` carries it: the struct's
982 /// schema without the document-level `$schema`, `title` and
983 /// `description` (a params object carries none; its properties do).
984 pub fn params_schema() -> schemars::Schema {
985 let mut s = schema_for!(SchemaParams);
986 if let Some(o) = s.as_object_mut() {
987 o.remove("$schema");
988 o.remove("title");
989 o.remove("description");
990 }
991 s
992 }
993}
994
995pub use super::schema_sites::{foreign_keywords, schema_untyped_sites, untyped_sites};
996
997/// `skip_serializing_if` helper: omit `false` booleans from the wire so
998/// additive flags keep pre-existing JSON byte-identical (see
999/// `MethodSchema::public`).
1000fn is_false(v: &bool) -> bool {
1001 !*v
1002}
1003
1004impl PluginSchema {
1005 /// Compute all three hashes (self, children, composite).
1006 ///
1007 /// RETURNS-10: SHA-256, 16 lowercase hex, each the
1008 /// [`hash16_lines`] of its inputs in order — one per line, so another
1009 /// language recomputes them from the JSON a server sends:
1010 ///
1011 /// - `self_hash` = `hash16_lines(methods[*].hash)`
1012 /// - `children_hash` = `hash16_lines(children[*].hash)`, `None` for a leaf
1013 /// - `hash` = `hash16_lines([self_hash, children_hash])`, the second only
1014 /// for a service
1015 ///
1016 /// Same structure and width as the `DefaultHasher` roll-up it replaces,
1017 /// whose output std does not promise across Rust releases.
1018 fn compute_hashes(
1019 methods: &[MethodSchema],
1020 children: Option<&[ChildSummary]>,
1021 ) -> (String, Option<String>, String) {
1022 let self_hash = hash16_lines(methods.iter().map(|m| m.hash.as_str()));
1023 let children_hash =
1024 children.map(|kids| hash16_lines(kids.iter().map(|c| c.hash.as_str())));
1025 let hash = hash16_lines(std::iter::once(self_hash.as_str()).chain(children_hash.as_deref()));
1026 (self_hash, children_hash, hash)
1027 }
1028
1029 /// Inspect each method's `returns` JSON Schema for the framework-
1030 /// reserved `_credentials` top-level field name; emit a tracing
1031 /// warning when a collision is detected (AUTHZ-CRED-CORE-2
1032 /// acceptance criterion #8). Returns the number of collisions found,
1033 /// so callers can chain into a metrics counter or assertion if they
1034 /// want one.
1035 ///
1036 /// The framework reserves the `_credentials` top-level field name
1037 /// for the credential sidecar (see
1038 /// `crate::plexus::credential_envelope`). Backends that define a
1039 /// domain field of the same name have it shadowed at dispatch time;
1040 /// the warning surfaces that fact at build time so backends can
1041 /// rename.
1042 /// PERF-15: [`Self::warn_on_credentials_field_collisions`] once for
1043 /// each schema a process builds — by namespace and hash — not in every
1044 /// constructor call. A service's `_info`, `hash` and `schema` built
1045 /// every activation's schema each time, and serializing each method's
1046 /// `returns` to lint it was 39 % of that (PERF-5). A schema whose
1047 /// methods change has another hash, and is linted again.
1048 fn lint_once(namespace: &str, hash: &str, methods: &[MethodSchema]) {
1049 static LINTED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<(String, String)>>> =
1050 std::sync::OnceLock::new();
1051 let first = LINTED
1052 .get_or_init(Default::default)
1053 .lock()
1054 .map(|mut seen| seen.insert((namespace.to_string(), hash.to_string())))
1055 .unwrap_or(true);
1056 if first {
1057 let _ = Self::warn_on_credentials_field_collisions(namespace, methods);
1058 }
1059 }
1060
1061 fn warn_on_credentials_field_collisions(
1062 namespace: &str,
1063 methods: &[MethodSchema],
1064 ) -> usize {
1065 let mut count = 0;
1066 for m in methods {
1067 let Ok(returns_json) = serde_json::to_value(&m.returns) else { continue };
1068 if super::credential_envelope::check_returns_schema_for_credentials_collision(
1069 namespace,
1070 &m.name,
1071 &returns_json,
1072 ) {
1073 count += 1;
1074 }
1075 }
1076 count
1077 }
1078
1079 /// Validate no name collisions exist within a plugin
1080 ///
1081 /// Checks for:
1082 /// - Duplicate method names
1083 /// - Duplicate child names (for hubs)
1084 /// - Method/child name collisions for `Rpc`-role methods (for hubs)
1085 ///
1086 /// Panics if a collision is detected (system error).
1087 ///
1088 /// # IR-4 relaxation
1089 ///
1090 /// As of IR-4, a method with `MethodRole::StaticChild` or
1091 /// `MethodRole::DynamicChild { .. }` that shares a name with a
1092 /// `ChildSummary` entry is **not** a collision — it's the same child
1093 /// surfaced via two wire representations (the role-tagged method list
1094 /// and the deprecated `children` side-table). Only `Rpc`-role methods
1095 /// whose name matches a child summary are flagged.
1096 fn validate_no_collisions(
1097 namespace: &str,
1098 methods: &[MethodSchema],
1099 children: Option<&[ChildSummary]>,
1100 ) {
1101 use std::collections::HashSet;
1102
1103 let mut seen: HashSet<&str> = HashSet::new();
1104
1105 // Check method names
1106 for m in methods {
1107 if !seen.insert(&m.name) {
1108 panic!(
1109 "Name collision in plugin '{}': duplicate method '{}'",
1110 namespace, m.name
1111 );
1112 }
1113 }
1114
1115 // Check child names (and collisions with methods)
1116 if let Some(kids) = children {
1117 for c in kids {
1118 if !seen.insert(&c.namespace) {
1119 // IR-4: a role-tagged child method whose name matches a
1120 // child summary is expected by construction (the two
1121 // wire-surfaces describe the same child). Skip silently.
1122 let colliding_method =
1123 methods.iter().find(|m| m.name == c.namespace);
1124 if let Some(m) = colliding_method {
1125 if matches!(
1126 m.role,
1127 MethodRole::StaticChild | MethodRole::DynamicChild { .. }
1128 ) {
1129 continue;
1130 }
1131 }
1132 // Could be duplicate child or collision with an Rpc-role method
1133 let collision_type = if colliding_method.is_some() {
1134 "method/child collision"
1135 } else {
1136 "duplicate child"
1137 };
1138 panic!(
1139 "Name collision in plugin '{}': {} for '{}'",
1140 namespace, collision_type, c.namespace
1141 );
1142 }
1143 }
1144 }
1145 }
1146
1147 /// Derive the deprecated `(children, is_hub)` side-table fields from a
1148 /// role-tagged method list.
1149 ///
1150 /// Added in IR-4 as the **centralized shim** that backfills the
1151 /// pre-IR `children: Option<Vec<ChildSummary>>` and `is_hub: bool`
1152 /// representations from the authoritative `MethodRole` on each
1153 /// `MethodSchema`.
1154 ///
1155 /// # Semantics
1156 ///
1157 /// One `ChildSummary` is produced per non-`Rpc` method, preserving the
1158 /// source order. The shim writes:
1159 ///
1160 /// | Field | Value |
1161 /// |---|---|
1162 /// | `namespace` | The method's name. |
1163 /// | `description` | The method's `description`. |
1164 /// | `hash` | Empty string — the shim does **not** compute child hashes. Callers that want per-child hashes must populate them out-of-band. |
1165 ///
1166 /// The returned `bool` matches [`PluginSchema::is_hub_by_role`] — `true`
1167 /// iff at least one method carries a child role.
1168 ///
1169 /// # Example
1170 ///
1171 /// ```
1172 /// use plexus_core::plexus::schema::{MethodRole, MethodSchema, PluginSchema};
1173 ///
1174 /// let methods = vec![
1175 /// MethodSchema::new("ping", "rpc", "h1"),
1176 /// MethodSchema::new("kid", "static child", "h2")
1177 /// .with_role(MethodRole::StaticChild),
1178 /// ];
1179 /// let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
1180 /// assert_eq!(children.len(), 1);
1181 /// assert_eq!(children[0].namespace, "kid");
1182 /// assert!(is_hub);
1183 /// ```
1184 pub fn derive_legacy_fields(
1185 methods: &[MethodSchema],
1186 ) -> (Vec<ChildSummary>, bool) {
1187 let children: Vec<ChildSummary> = methods
1188 .iter()
1189 .filter(|m| {
1190 matches!(
1191 m.role,
1192 MethodRole::StaticChild | MethodRole::DynamicChild { .. }
1193 )
1194 })
1195 .map(|m| ChildSummary {
1196 namespace: m.name.clone(),
1197 description: m.description.clone(),
1198 hash: String::new(),
1199 })
1200 .collect();
1201 let is_hub = !children.is_empty();
1202 (children, is_hub)
1203 }
1204
1205 /// Create a new leaf plugin schema (no children)
1206 #[allow(deprecated)]
1207 pub fn leaf(
1208 namespace: impl Into<String>,
1209 version: impl Into<String>,
1210 description: impl Into<String>,
1211 methods: Vec<MethodSchema>,
1212 ) -> Self {
1213 let namespace = namespace.into();
1214 Self::validate_no_collisions(&namespace, &methods, None);
1215 // AUTHZ-CRED-CORE-2 acceptance criterion #8: warn at schema-build
1216 // time when a method's return-type schema declares a top-level
1217 // field named `_credentials` (reserved by the framework's
1218 // credential sidecar) — once for each schema the process builds
1219 // (PERF-15, `lint_once`).
1220 let (self_hash, children_hash, hash) = Self::compute_hashes(&methods, None);
1221 Self::lint_once(&namespace, &hash, &methods);
1222 Self {
1223 namespace,
1224 version: version.into(),
1225 description: description.into(),
1226 long_description: None,
1227 self_hash,
1228 children_hash,
1229 hash,
1230 methods,
1231 children: None,
1232 request: None,
1233 deprecation: None,
1234 roles: std::collections::BTreeMap::new(),
1235 view: None,
1236 }
1237 }
1238
1239 /// Create a new leaf plugin schema with long description
1240 #[allow(deprecated)]
1241 pub fn leaf_with_long_description(
1242 namespace: impl Into<String>,
1243 version: impl Into<String>,
1244 description: impl Into<String>,
1245 long_description: impl Into<String>,
1246 methods: Vec<MethodSchema>,
1247 ) -> Self {
1248 let namespace = namespace.into();
1249 Self::validate_no_collisions(&namespace, &methods, None);
1250 // AUTHZ-CRED-CORE-2 AC #8: see PluginSchema::leaf.
1251 let (self_hash, children_hash, hash) = Self::compute_hashes(&methods, None);
1252 Self::lint_once(&namespace, &hash, &methods);
1253 Self {
1254 namespace,
1255 version: version.into(),
1256 description: description.into(),
1257 long_description: Some(long_description.into()),
1258 self_hash,
1259 children_hash,
1260 hash,
1261 methods,
1262 children: None,
1263 request: None,
1264 deprecation: None,
1265 roles: std::collections::BTreeMap::new(),
1266 view: None,
1267 }
1268 }
1269
1270 /// Create a new hub plugin schema (with child summaries)
1271 #[allow(deprecated)]
1272 pub fn hub(
1273 namespace: impl Into<String>,
1274 version: impl Into<String>,
1275 description: impl Into<String>,
1276 methods: Vec<MethodSchema>,
1277 children: Vec<ChildSummary>,
1278 ) -> Self {
1279 let namespace = namespace.into();
1280 Self::validate_no_collisions(&namespace, &methods, Some(&children));
1281 // AUTHZ-CRED-CORE-2 AC #8: see PluginSchema::leaf.
1282 let (self_hash, children_hash, hash) = Self::compute_hashes(&methods, Some(&children));
1283 Self::lint_once(&namespace, &hash, &methods);
1284 Self {
1285 namespace,
1286 version: version.into(),
1287 description: description.into(),
1288 long_description: None,
1289 self_hash,
1290 children_hash,
1291 hash,
1292 methods,
1293 children: Some(children),
1294 request: None,
1295 deprecation: None,
1296 roles: std::collections::BTreeMap::new(),
1297 view: None,
1298 }
1299 }
1300
1301 /// Create a new hub plugin schema with long description
1302 #[allow(deprecated)]
1303 pub fn hub_with_long_description(
1304 namespace: impl Into<String>,
1305 version: impl Into<String>,
1306 description: impl Into<String>,
1307 long_description: impl Into<String>,
1308 methods: Vec<MethodSchema>,
1309 children: Vec<ChildSummary>,
1310 ) -> Self {
1311 let namespace = namespace.into();
1312 Self::validate_no_collisions(&namespace, &methods, Some(&children));
1313 // AUTHZ-CRED-CORE-2 AC #8: see PluginSchema::leaf.
1314 let (self_hash, children_hash, hash) = Self::compute_hashes(&methods, Some(&children));
1315 Self::lint_once(&namespace, &hash, &methods);
1316 Self {
1317 namespace,
1318 version: version.into(),
1319 description: description.into(),
1320 long_description: Some(long_description.into()),
1321 self_hash,
1322 children_hash,
1323 hash,
1324 methods,
1325 children: Some(children),
1326 request: None,
1327 deprecation: None,
1328 roles: std::collections::BTreeMap::new(),
1329 view: None,
1330 }
1331 }
1332
1333 /// Check if this is a hub.
1334 ///
1335 /// Returns `true` iff the plugin exposes child activations. As of IR-2,
1336 /// this is derived from **either** source of truth:
1337 ///
1338 /// 1. Any method tagged with a child `MethodRole` (`StaticChild` or
1339 /// `DynamicChild { .. }`). This is the post-IR-3 authoritative signal.
1340 /// 2. The legacy `children: Option<Vec<ChildSummary>>` field is `Some`.
1341 /// Preserved for back-compat during the IR transition window —
1342 /// today's macros populate `children` but not yet `role`.
1343 ///
1344 /// # Deprecated (IR-4)
1345 ///
1346 /// The legacy transition-window fallback on `children.is_some()` is
1347 /// redundant now that `MethodRole` tags are authoritative. Callers
1348 /// should migrate to [`PluginSchema::is_hub_by_role`], which reads
1349 /// only role-tagged methods. This method will be removed in 0.7.
1350 #[deprecated(
1351 since = "0.5",
1352 note = "Use `PluginSchema::is_hub_by_role()` which reads MethodRole from methods. This method will be removed in 0.7."
1353 )]
1354 #[allow(deprecated)]
1355 pub fn is_hub(&self) -> bool {
1356 self.is_hub_by_role() || self.children.is_some()
1357 }
1358
1359 /// Returns `true` iff any method carries a child `MethodRole`.
1360 ///
1361 /// This is the **derived query** specified by IR-2: it reads only
1362 /// `self.methods`, ignoring the legacy `children` side channel. Use this
1363 /// when you want the post-IR-3 authoritative answer without the transition
1364 /// fallback that `is_hub()` provides.
1365 pub fn is_hub_by_role(&self) -> bool {
1366 self.methods.iter().any(|m| {
1367 matches!(
1368 m.role,
1369 MethodRole::StaticChild | MethodRole::DynamicChild { .. }
1370 )
1371 })
1372 }
1373
1374 /// Check if this is a leaf (no children)
1375 #[allow(deprecated)]
1376 pub fn is_leaf(&self) -> bool {
1377 self.children.is_none()
1378 }
1379
1380 /// Mark this plugin as deprecated.
1381 ///
1382 /// Added in IR-5. Populates the `deprecation` field with the provided
1383 /// `DeprecationInfo`. Populated by the `#[deprecated(...)]` attribute on
1384 /// an `impl Activation for Foo` block via `plexus-macros`.
1385 pub fn with_deprecation(mut self, info: DeprecationInfo) -> Self {
1386 self.deprecation = Some(info);
1387 self
1388 }
1389
1390 /// CA-1: fill `site_hint` on every method's `requires_credential` that
1391 /// lacks one, using the hub-derived attach site. Applied at
1392 /// schema-assembly time by [`DynamicHub`] when the backend's advertised
1393 /// auth capabilities imply a site — service authors write nothing.
1394 ///
1395 /// RETURNS-10: filled after the hashes are computed, so the hints are
1396 /// not covered by them — they come from the serving service's
1397 /// configuration, not the activation's code, and re-hashing on every
1398 /// schema response is the per-call cost the hashes are cached to avoid.
1399 ///
1400 /// [`DynamicHub`]: super::DynamicHub
1401 pub fn fill_site_hints(&mut self, site: &AttachmentSite) {
1402 for method in &mut self.methods {
1403 method.fill_site_hint(site);
1404 }
1405 }
1406}
1407
1408impl SchemaResult {
1409 /// CA-1: fill `site_hint`s across whichever schema shape this result
1410 /// carries — see [`PluginSchema::fill_site_hints`].
1411 pub fn fill_site_hints(&mut self, site: &AttachmentSite) {
1412 match self {
1413 SchemaResult::Plugin(plugin) => plugin.fill_site_hints(site),
1414 SchemaResult::Method(method) => method.fill_site_hint(site),
1415 }
1416 }
1417}
1418
1419/// Summary of a child plugin
1420#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1421pub struct ChildSummary {
1422 /// The child's namespace
1423 pub namespace: String,
1424
1425 /// Human-readable description
1426 pub description: String,
1427
1428 /// Content hash for cache invalidation
1429 pub hash: String,
1430}
1431
1432/// Schema summary containing only hashes (for cache validation)
1433#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1434pub struct PluginHashes {
1435 pub namespace: String,
1436 pub self_hash: String,
1437 #[serde(skip_serializing_if = "Option::is_none")]
1438 pub children_hash: Option<String>,
1439 pub hash: String,
1440 /// Child plugin hashes (for recursive checking)
1441 #[serde(skip_serializing_if = "Option::is_none")]
1442 pub children: Option<Vec<ChildHashes>>,
1443}
1444
1445#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1446pub struct ChildHashes {
1447 pub namespace: String,
1448 pub hash: String,
1449}
1450
1451impl MethodSchema {
1452 /// Create a new method schema with name, description, and hash
1453 ///
1454 /// RETURNS-10: a method's hash is its schema's
1455 /// [`content_hash`](Self::content_hash). Build the schema with `hash`
1456 /// empty and finish with [`with_content_hash`](Self::with_content_hash),
1457 /// as the code `#[plexus_macros::activation]` emits does.
1458 ///
1459 /// Starts as an infallible, progress-free [`Cardinality::One`] method
1460 /// whose `returns` is the empty schema `{}` (any value); the builders
1461 /// [`with_returns`](Self::with_returns), [`with_error`](Self::with_error),
1462 /// [`with_progress`](Self::with_progress) and
1463 /// [`with_cardinality`](Self::with_cardinality) state the real contract.
1464 pub fn new(
1465 name: impl Into<String>,
1466 description: impl Into<String>,
1467 hash: impl Into<String>,
1468 ) -> Self {
1469 Self {
1470 name: name.into(),
1471 description: description.into(),
1472 hash: hash.into(),
1473 params: None,
1474 returns: schemars::Schema::default(),
1475 error: None,
1476 progress: None,
1477 cardinality: Cardinality::One,
1478 bidirectional: false,
1479 http_method: HttpMethod::default(),
1480 request_type: None,
1481 response_type: None,
1482 role: MethodRole::Rpc,
1483 deprecation: None,
1484 params_meta: Vec::new(),
1485 credentials: Vec::new(),
1486 requires_credential: None,
1487 auth_posture: None,
1488 public: false,
1489 grant: None,
1490 target: None,
1491 long_description: None,
1492 held_on: None,
1493 group: None,
1494 answer_by: None,
1495 examples: Vec::new(),
1496 input: None,
1497 }
1498 }
1499
1500 /// SYNAPSE-CC-9: the entry of the `schema` method every activation
1501 /// answers — `params` `{method?: string}` ([`SchemaParams`]) and
1502 /// `returns` [`SchemaResult`] (this `PluginSchema`, or one `MethodSchema`
1503 /// when called with `{"method": …}`; RETURNS-26). The macro adds the
1504 /// activation's grant.
1505 pub fn auto_schema() -> Self {
1506 Self::new(
1507 "schema",
1508 "Get plugin or method schema. Pass {\"method\": \"name\"} for a specific method.",
1509 "auto_schema", // fixed: the entry is the same in every activation
1510 )
1511 .with_params(SchemaParams::params_schema())
1512 .with_returns(schema_for!(SchemaResult))
1513 }
1514
1515 /// Is this the `schema` entry every activation's macro adds
1516 /// ([`auto_schema`](Self::auto_schema))?
1517 ///
1518 /// RETURNS-36: known by what every 0.8.x build writes alike, never by a
1519 /// hash recomputed with this build (review #11): named `schema`, an Rpc
1520 /// of one item with no error and no progress, its params `{method?}`
1521 /// alone and its `returns` titled `SchemaResult` — or main's fixed
1522 /// marker hash, `"auto_schema"`, from a peer still sending it. A method
1523 /// an author named `schema` with other params or another return is not
1524 /// it.
1525 pub fn is_auto_schema(&self) -> bool {
1526 if self.name != "schema" || !matches!(self.role, MethodRole::Rpc) {
1527 return false;
1528 }
1529 if self.hash == "auto_schema" {
1530 return true;
1531 }
1532 let params_are_method_alone = self
1533 .params
1534 .as_ref()
1535 .and_then(|p| p.as_object())
1536 .and_then(|o| o.get("properties"))
1537 .and_then(|p| p.as_object())
1538 .is_some_and(|props| props.len() == 1 && props.contains_key("method"));
1539 let returns_schema_result = self
1540 .returns
1541 .as_object()
1542 .and_then(|o| o.get("title"))
1543 .and_then(|t| t.as_str())
1544 == Some("SchemaResult");
1545 self.cardinality == Cardinality::One
1546 && self.error.is_none()
1547 && self.progress.is_none()
1548 && params_are_method_alone
1549 && returns_schema_result
1550 }
1551
1552 /// SYNAPSE-CC-9: reserved for BIDIR-6 — the schema of the items a client
1553 /// streams in.
1554 pub fn with_input(mut self, mut input: schemars::Schema) -> Self {
1555 spell_json_values(&mut input);
1556 self.input = Some(input);
1557 self
1558 }
1559
1560 /// RETURNS-10: this method's content hash — 16 lowercase hex.
1561 ///
1562 /// The schema as it serializes, without its own `hash` field, written as
1563 /// [canonical JSON](canonical_json) (keys sorted, no whitespace, arrays
1564 /// in order) and hashed with [`hash16`] (SHA-256, first 8 bytes). It
1565 /// covers everything a client is generated from — name, description,
1566 /// params, `returns` / `error` / `progress` down to every nested field,
1567 /// variant and doc comment, cardinality, role, deprecation, credentials,
1568 /// auth posture — so one hash means one schema. A consumer recomputes it
1569 /// from the wire, e.g. in Python:
1570 ///
1571 /// ```text
1572 /// m = dict(method); del m["hash"]
1573 /// sha256(json.dumps(m, sort_keys=True, separators=(",", ":"),
1574 /// ensure_ascii=False).encode()).hexdigest()[:16]
1575 /// ```
1576 ///
1577 /// Costs one serialization and one SHA-256 pass over the schema: compute
1578 /// it once where schemas are cached, not per `plugin_schema()` call.
1579 pub fn content_hash(&self) -> String {
1580 let mut value = serde_json::to_value(self).expect("a MethodSchema serializes");
1581 if let Some(fields) = value.as_object_mut() {
1582 fields.remove("hash");
1583 }
1584 hash16(canonical_json(&value).as_bytes())
1585 }
1586
1587 /// RETURNS-10: set `hash` to [`content_hash`](Self::content_hash) —
1588 /// the last step of building a schema (a builder applied after it would
1589 /// change the schema without moving its hash).
1590 pub fn with_content_hash(mut self) -> Self {
1591 self.hash = self.content_hash();
1592 self
1593 }
1594
1595 /// Add parameter schema
1596 pub fn with_params(mut self, mut params: schemars::Schema) -> Self {
1597 spell_json_values(&mut params);
1598 self.params = Some(params);
1599 self
1600 }
1601
1602 /// Set the schema of the method's item type `T`.
1603 pub fn with_returns(mut self, mut returns: schemars::Schema) -> Self {
1604 spell_json_values(&mut returns);
1605 self.returns = returns;
1606 self
1607 }
1608
1609 /// Set the schema of the method's error type `E` (a fallible method,
1610 /// `Result<T, E>`).
1611 pub fn with_error(mut self, mut error: schemars::Schema) -> Self {
1612 spell_json_values(&mut error);
1613 self.error = Some(error);
1614 self
1615 }
1616
1617 /// Set the schema of the method's progress type `P` (an item of
1618 /// `Progress<T, P>`).
1619 pub fn with_progress(mut self, mut progress: schemars::Schema) -> Self {
1620 spell_json_values(&mut progress);
1621 self.progress = Some(progress);
1622 self
1623 }
1624
1625 /// Set whether the method yields one item or many.
1626 ///
1627 /// [`MethodSchema::new`] starts at [`Cardinality::One`].
1628 pub fn with_cardinality(mut self, cardinality: Cardinality) -> Self {
1629 self.cardinality = cardinality;
1630 self
1631 }
1632
1633 /// Set the HTTP method for REST endpoints
1634 ///
1635 /// Defaults to POST for backward compatibility.
1636 ///
1637 /// # Guidelines
1638 /// - GET: Idempotent read operations with no side effects
1639 /// - POST: Create operations or non-idempotent actions
1640 /// - PUT: Replace/update operations (idempotent)
1641 /// - DELETE: Remove operations (idempotent)
1642 /// - PATCH: Partial update operations
1643 pub fn with_http_method(mut self, http_method: HttpMethod) -> Self {
1644 self.http_method = http_method;
1645 self
1646 }
1647
1648 /// Set whether this method supports bidirectional communication
1649 ///
1650 /// When true, the server can send requests to the client during method
1651 /// execution and wait for responses.
1652 pub fn with_bidirectional(mut self, bidirectional: bool) -> Self {
1653 self.bidirectional = bidirectional;
1654 self
1655 }
1656
1657 /// Set the JSON Schema for server-to-client request types
1658 ///
1659 /// Only relevant when `bidirectional: true`. Use `schema_for!(YourRequestType)`
1660 /// to generate the schema.
1661 pub fn with_request_type(mut self, mut schema: schemars::Schema) -> Self {
1662 spell_json_values(&mut schema);
1663 self.request_type = Some(schema);
1664 self
1665 }
1666
1667 /// Set the JSON Schema for client-to-server response types
1668 ///
1669 /// Only relevant when `bidirectional: true`. Use `schema_for!(YourResponseType)`
1670 /// to generate the schema.
1671 pub fn with_response_type(mut self, mut schema: schemars::Schema) -> Self {
1672 spell_json_values(&mut schema);
1673 self.response_type = Some(schema);
1674 self
1675 }
1676
1677 /// Configure method for standard bidirectional communication
1678 ///
1679 /// Sets `bidirectional: true` and configures request/response types to use
1680 /// `StandardRequest` and `StandardResponse`, which support common UI patterns
1681 /// like confirmations, prompts, and selections.
1682 pub fn with_standard_bidirectional(self) -> Self {
1683 self.with_bidirectional(true)
1684 .with_request_type(schema_for!(StandardRequest).into())
1685 .with_response_type(schema_for!(StandardResponse).into())
1686 }
1687
1688 /// Set this method's role in the activation graph.
1689 ///
1690 /// Added in IR-2. Defaults to `MethodRole::Rpc`.
1691 pub fn with_role(mut self, role: MethodRole) -> Self {
1692 self.role = role;
1693 self
1694 }
1695
1696 /// Mark this method as deprecated.
1697 ///
1698 /// Added in IR-2. Populates the `deprecation` field with the provided
1699 /// `DeprecationInfo`.
1700 pub fn with_deprecation(mut self, info: DeprecationInfo) -> Self {
1701 self.deprecation = Some(info);
1702 self
1703 }
1704
1705 /// Attach per-parameter metadata for this method's parameters.
1706 ///
1707 /// Added in IR-5. Only parameters that carry metadata (e.g. a
1708 /// `#[deprecated]` annotation) need appear in `entries`; absence means
1709 /// "no metadata" for a given parameter. The consumer correlates entries
1710 /// against `self.params` by matching `ParamSchema.name` against the
1711 /// `properties` map of the JSON Schema.
1712 pub fn with_params_meta(mut self, entries: Vec<ParamSchema>) -> Self {
1713 self.params_meta = entries;
1714 self
1715 }
1716
1717 /// Attach the credential-field projection for this method's return type.
1718 ///
1719 /// Added in `AUTHZ-CRED-CORE-3`. The build-path supplies one
1720 /// `CredentialFieldDecl` per `#[plexus::credential(...)]`-annotated
1721 /// field in the return type, in stable declaration order. Absence (the
1722 /// default empty vec) means the return type carries no credentials.
1723 ///
1724 /// The constructor `CredentialFieldDecl::from_marker` composes one
1725 /// entry from a `CredentialFieldMarker` (emitted by the
1726 /// `#[derive(Credentials)]` macro) plus the runtime-known issuer.
1727 pub fn with_credentials(mut self, credentials: Vec<CredentialFieldDecl>) -> Self {
1728 self.credentials = credentials;
1729 self
1730 }
1731
1732 /// Attach the implicit-derived `requires_credential` filter for this
1733 /// method.
1734 ///
1735 /// Added in `AUTHZ-CRED-CORE-3`. The build-path supplies a
1736 /// `RequiredCredential` derived from either (a) the method's `scope`
1737 /// attribute or (b) the method's appearance as a `refresh_via` /
1738 /// `revoke_via` target of some other credential in the schema. Public
1739 /// methods leave this field as `None` (the default).
1740 ///
1741 /// `RequiredCredential::from_method_scope` and
1742 /// `RequiredCredential::from_refresh_revoke_target` are the two derivation
1743 /// entry points.
1744 pub fn with_requires_credential(mut self, req: RequiredCredential) -> Self {
1745 self.requires_credential = Some(req);
1746 self
1747 }
1748
1749 /// Stamp the activation-declared auth posture onto this method.
1750 ///
1751 /// Added in R-2 (joint AP-1). Populated by the `#[plexus_macros::
1752 /// activation(auth = "...")]` emission (R-1); only explicitly declared
1753 /// postures are stamped — activations that never declare `auth = "..."`
1754 /// leave this `None` so their wire output is byte-identical to pre-R
1755 /// emissions.
1756 pub fn with_auth_posture(mut self, posture: AuthPosture) -> Self {
1757 self.auth_posture = Some(posture);
1758 self
1759 }
1760
1761 /// Mark this method as explicitly public (AUTHZ-CORE-2's
1762 /// `#[plexus::method(public)]`) — exempt from the default-deny gate.
1763 ///
1764 /// Added in R-2. Populated by the macro emission (R-1); the macro
1765 /// rejects `public` + `scope = "..."` at compile time, so a public
1766 /// method never carries a scope-derived `requires_credential`.
1767 pub fn with_public(mut self, public: bool) -> Self {
1768 self.public = public;
1769 self
1770 }
1771
1772 /// AUTH-3: set the method's grant (`<activation>.<method>`).
1773 pub fn with_grant(mut self, grant: impl Into<String>) -> Self {
1774 self.grant = Some(grant.into());
1775 self
1776 }
1777
1778 /// AUTH-3: name the param that locates what this call acts on.
1779 pub fn with_target(mut self, target: impl Into<String>) -> Self {
1780 self.target = Some(target.into());
1781 self
1782 }
1783
1784 /// AUTH-3: the doc comment's fuller text.
1785 pub fn with_long_description(mut self, long_description: impl Into<String>) -> Self {
1786 self.long_description = Some(long_description.into());
1787 self
1788 }
1789
1790 /// BIDIR-8: who may answer a question this method asks mid-call, as
1791 /// `#[method(answer_by = "…")]` declares it (`person`, `grant:<g>`);
1792 /// the default (`caller`) is left unset.
1793 pub fn with_answer_by(mut self, answer_by: impl Into<String>) -> Self {
1794 self.answer_by = Some(answer_by.into());
1795 self
1796 }
1797
1798 /// BIDIR-8: the method's [`Answerer`](plexus_auth_core::duplex::Answerer)
1799 /// — [`answer_by`](Self::answer_by) read, absent the default (`caller`).
1800 /// A spelling the macro would refuse is an error, never a wider answerer.
1801 pub fn answerer(&self) -> Result<plexus_auth_core::duplex::Answerer, String> {
1802 plexus_auth_core::duplex::Answerer::of_schema(self.answer_by.as_deref())
1803 }
1804
1805 /// SYNAPSE-13: put this method in a listing group (`"read"`, `"write"`).
1806 pub fn with_group(mut self, group: impl Into<String>) -> Self {
1807 self.group = Some(group.into());
1808 self
1809 }
1810
1811 /// SYNAPSE-13: add a worked call of this method.
1812 pub fn with_example(mut self, example: MethodExample) -> Self {
1813 self.examples.push(example);
1814 self
1815 }
1816
1817 /// SYNAPSE-13: say which values `param` is meant to take, as
1818 /// [`X_PLEXUS_VALUES`] on its property in `params` — a hint, never
1819 /// enforced. A param the schema does not have is left alone.
1820 pub fn with_param_values<I, S>(mut self, param: &str, values: I) -> Self
1821 where
1822 I: IntoIterator<Item = S>,
1823 S: Into<String>,
1824 {
1825 let values: Vec<serde_json::Value> =
1826 values.into_iter().map(|v| serde_json::Value::String(v.into())).collect();
1827 if let Some(params) = self.params.take() {
1828 let mut value = serde_json::to_value(¶ms).unwrap_or_default();
1829 if let Some(prop) = value
1830 .get_mut("properties")
1831 .and_then(|p| p.get_mut(param))
1832 .and_then(|p| p.as_object_mut())
1833 {
1834 prop.insert(X_PLEXUS_VALUES.to_string(), serde_json::Value::Array(values));
1835 }
1836 self.params = Some(serde_json::from_value(value).unwrap_or(params));
1837 }
1838 self
1839 }
1840
1841 /// SYNAPSE-13: the values `param` is meant to take, when its property
1842 /// says them ([`X_PLEXUS_VALUES`]).
1843 pub fn param_values(&self, param: &str) -> Option<Vec<String>> {
1844 let value = serde_json::to_value(self.params.as_ref()?).ok()?;
1845 let list = value.get("properties")?.get(param)?.get(X_PLEXUS_VALUES)?.as_array()?;
1846 Some(list.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
1847 }
1848
1849 /// AUTH-2: the grant a gate asks for this method under `activation`:
1850 /// the schema's own `grant`, else `<activation>.<name>`.
1851 pub fn grant_or(&self, activation: &str) -> String {
1852 self.grant.clone().unwrap_or_else(|| format!("{activation}.{}", self.name))
1853 }
1854
1855 /// CA-1: fill `requires_credential.site_hint` with the hub-derived
1856 /// attach site when the method carries a requirement that lacks one.
1857 /// Methods without a `requires_credential` are untouched — derivation
1858 /// never *creates* a requirement (AUTHZ-CRED-CORE-3's implicit-only
1859 /// contract).
1860 pub fn fill_site_hint(&mut self, site: &AttachmentSite) {
1861 if let Some(req) = self.requires_credential.as_mut() {
1862 req.fill_site_hint(site);
1863 }
1864 }
1865}
1866
1867// ============================================================================
1868// JSON Schema Types
1869// ============================================================================
1870
1871/// A complete JSON Schema with metadata
1872#[derive(Debug, Clone, Serialize, Deserialize)]
1873pub struct Schema {
1874 /// The JSON Schema specification version
1875 #[serde(rename = "$schema", skip_serializing_if = "Option::is_none", default)]
1876 pub schema_version: Option<String>,
1877
1878 /// Title of the schema
1879 #[serde(skip_serializing_if = "Option::is_none")]
1880 pub title: Option<String>,
1881
1882 /// Description of what this schema represents
1883 #[serde(skip_serializing_if = "Option::is_none")]
1884 pub description: Option<String>,
1885
1886 /// The schema type (typically "object" for root, can be string or array)
1887 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
1888 pub schema_type: Option<serde_json::Value>,
1889
1890 /// Properties for object types
1891 #[serde(skip_serializing_if = "Option::is_none")]
1892 pub properties: Option<HashMap<String, SchemaProperty>>,
1893
1894 /// Required properties
1895 #[serde(skip_serializing_if = "Option::is_none")]
1896 pub required: Option<Vec<String>>,
1897
1898 /// Enum variants (for discriminated unions)
1899 #[serde(rename = "oneOf", skip_serializing_if = "Option::is_none")]
1900 pub one_of: Option<Vec<Schema>>,
1901
1902 /// Schema definitions (for $defs or definitions)
1903 #[serde(rename = "$defs", skip_serializing_if = "Option::is_none")]
1904 pub defs: Option<HashMap<String, serde_json::Value>>,
1905
1906 /// Any additional schema properties
1907 #[serde(flatten)]
1908 pub additional: HashMap<String, serde_json::Value>,
1909}
1910
1911/// Schema type enumeration
1912#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1913#[serde(rename_all = "lowercase")]
1914pub enum SchemaType {
1915 Object,
1916 Array,
1917 String,
1918 Number,
1919 Integer,
1920 Boolean,
1921 Null,
1922}
1923
1924/// A property definition in a schema
1925#[derive(Debug, Clone, Serialize, Deserialize)]
1926pub struct SchemaProperty {
1927 /// The type of this property (can be a single type or array of types for nullable)
1928 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
1929 pub property_type: Option<serde_json::Value>,
1930
1931 /// Description of this property
1932 #[serde(skip_serializing_if = "Option::is_none")]
1933 pub description: Option<String>,
1934
1935 /// Format hint (e.g., "uuid", "date-time", "email")
1936 #[serde(skip_serializing_if = "Option::is_none")]
1937 pub format: Option<String>,
1938
1939 /// For array types, the schema of items
1940 #[serde(skip_serializing_if = "Option::is_none")]
1941 pub items: Option<Box<SchemaProperty>>,
1942
1943 /// For object types, nested properties
1944 #[serde(skip_serializing_if = "Option::is_none")]
1945 pub properties: Option<HashMap<String, SchemaProperty>>,
1946
1947 /// Required properties (for object types)
1948 #[serde(skip_serializing_if = "Option::is_none")]
1949 pub required: Option<Vec<String>>,
1950
1951 /// Default value for this property
1952 #[serde(skip_serializing_if = "Option::is_none")]
1953 pub default: Option<serde_json::Value>,
1954
1955 /// Enum values if this is an enum
1956 #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
1957 pub enum_values: Option<Vec<serde_json::Value>>,
1958
1959 /// Reference to another schema definition
1960 #[serde(rename = "$ref", skip_serializing_if = "Option::is_none")]
1961 pub reference: Option<String>,
1962
1963 /// Any additional property metadata
1964 #[serde(flatten)]
1965 pub additional: HashMap<String, serde_json::Value>,
1966}
1967
1968impl Schema {
1969 /// Create a new schema with basic metadata
1970 pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
1971 Self {
1972 schema_version: Some("http://json-schema.org/draft-07/schema#".to_string()),
1973 title: Some(title.into()),
1974 description: Some(description.into()),
1975 schema_type: None,
1976 properties: None,
1977 required: None,
1978 one_of: None,
1979 defs: None,
1980 additional: HashMap::new(),
1981 }
1982 }
1983
1984 /// Create an object schema
1985 pub fn object() -> Self {
1986 Self {
1987 schema_version: Some("http://json-schema.org/draft-07/schema#".to_string()),
1988 title: None,
1989 description: None,
1990 schema_type: Some(serde_json::json!("object")),
1991 properties: Some(HashMap::new()),
1992 required: None,
1993 one_of: None,
1994 defs: None,
1995 additional: HashMap::new(),
1996 }
1997 }
1998
1999 /// Add a property to this schema
2000 pub fn with_property(mut self, name: impl Into<String>, property: SchemaProperty) -> Self {
2001 self.properties
2002 .get_or_insert_with(HashMap::new)
2003 .insert(name.into(), property);
2004 self
2005 }
2006
2007 /// Mark a property as required
2008 pub fn with_required(mut self, name: impl Into<String>) -> Self {
2009 self.required
2010 .get_or_insert_with(Vec::new)
2011 .push(name.into());
2012 self
2013 }
2014
2015 /// Set the description
2016 pub fn with_description(mut self, description: impl Into<String>) -> Self {
2017 self.description = Some(description.into());
2018 self
2019 }
2020
2021 /// Extract a single method's schema from the oneOf array
2022 ///
2023 /// Searches the oneOf variants for a method matching the given name.
2024 /// Returns the variant schema if found, None otherwise.
2025 pub fn get_method_schema(&self, method_name: &str) -> Option<Schema> {
2026 let variants = self.one_of.as_ref()?;
2027
2028 for variant in variants {
2029 // Check if this variant has a "method" property with const or enum
2030 if let Some(props) = &variant.properties {
2031 if let Some(method_prop) = props.get("method") {
2032 // Try "const" first (schemars uses this for literal values)
2033 if let Some(const_val) = method_prop.additional.get("const") {
2034 if const_val.as_str() == Some(method_name) {
2035 return Some(variant.clone());
2036 }
2037 }
2038 // Fall back to enum_values
2039 if let Some(enum_vals) = &method_prop.enum_values {
2040 if enum_vals.first().and_then(|v| v.as_str()) == Some(method_name) {
2041 return Some(variant.clone());
2042 }
2043 }
2044 }
2045 }
2046 }
2047 None
2048 }
2049
2050 /// List all method names from the oneOf array
2051 pub fn list_methods(&self) -> Vec<String> {
2052 let Some(variants) = &self.one_of else {
2053 return Vec::new();
2054 };
2055
2056 variants
2057 .iter()
2058 .filter_map(|variant| {
2059 let props = variant.properties.as_ref()?;
2060 let method_prop = props.get("method")?;
2061
2062 // Try "const" first
2063 if let Some(const_val) = method_prop.additional.get("const") {
2064 return const_val.as_str().map(String::from);
2065 }
2066 // Fall back to enum_values
2067 method_prop
2068 .enum_values
2069 .as_ref()?
2070 .first()?
2071 .as_str()
2072 .map(String::from)
2073 })
2074 .collect()
2075 }
2076}
2077
2078impl SchemaProperty {
2079 /// Create a string property
2080 pub fn string() -> Self {
2081 Self {
2082 property_type: Some(serde_json::json!("string")),
2083 description: None,
2084 format: None,
2085 items: None,
2086 properties: None,
2087 required: None,
2088 default: None,
2089 enum_values: None,
2090 reference: None,
2091 additional: HashMap::new(),
2092 }
2093 }
2094
2095 /// Create a UUID property (string with format)
2096 pub fn uuid() -> Self {
2097 Self {
2098 property_type: Some(serde_json::json!("string")),
2099 description: None,
2100 format: Some("uuid".to_string()),
2101 items: None,
2102 properties: None,
2103 required: None,
2104 default: None,
2105 enum_values: None,
2106 reference: None,
2107 additional: HashMap::new(),
2108 }
2109 }
2110
2111 /// Create an integer property
2112 pub fn integer() -> Self {
2113 Self {
2114 property_type: Some(serde_json::json!("integer")),
2115 description: None,
2116 format: None,
2117 items: None,
2118 properties: None,
2119 required: None,
2120 default: None,
2121 enum_values: None,
2122 reference: None,
2123 additional: HashMap::new(),
2124 }
2125 }
2126
2127 /// Create an object property
2128 pub fn object() -> Self {
2129 Self {
2130 property_type: Some(serde_json::json!("object")),
2131 description: None,
2132 format: None,
2133 items: None,
2134 properties: Some(HashMap::new()),
2135 required: None,
2136 default: None,
2137 enum_values: None,
2138 reference: None,
2139 additional: HashMap::new(),
2140 }
2141 }
2142
2143 /// Create an array property
2144 pub fn array(items: SchemaProperty) -> Self {
2145 Self {
2146 property_type: Some(serde_json::json!("array")),
2147 description: None,
2148 format: None,
2149 items: Some(Box::new(items)),
2150 properties: None,
2151 required: None,
2152 default: None,
2153 enum_values: None,
2154 reference: None,
2155 additional: HashMap::new(),
2156 }
2157 }
2158
2159 /// Add a description
2160 pub fn with_description(mut self, description: impl Into<String>) -> Self {
2161 self.description = Some(description.into());
2162 self
2163 }
2164
2165 /// Add a default value
2166 pub fn with_default(mut self, default: serde_json::Value) -> Self {
2167 self.default = Some(default);
2168 self
2169 }
2170
2171 /// Add nested properties (for object types)
2172 pub fn with_property(mut self, name: impl Into<String>, property: SchemaProperty) -> Self {
2173 self.properties
2174 .get_or_insert_with(HashMap::new)
2175 .insert(name.into(), property);
2176 self
2177 }
2178}
2179
2180#[cfg(test)]
2181#[allow(deprecated)]
2182mod tests {
2183 use super::*;
2184
2185 /// SYNAPSE-13: group, examples and a param's values on the wire, and
2186 /// absent when unset (an older client sees the shape it always did).
2187 #[test]
2188 fn synapse13_group_examples_values() {
2189 let params: schemars::Schema = serde_json::from_value(serde_json::json!({
2190 "type": "object",
2191 "properties": { "id": { "type": "string" }, "status": { "type": "string", "description": "New status" } },
2192 "required": ["id", "status"],
2193 }))
2194 .unwrap();
2195 let bare = MethodSchema::new("set_status", "Set a ticket's status", "h").with_params(params);
2196 let wire = serde_json::to_value(&bare).unwrap();
2197 assert!(wire.get("group").is_none() && wire.get("examples").is_none());
2198 assert_eq!(bare.param_values("status"), None);
2199
2200 let m = bare
2201 .with_group("write")
2202 .with_example(MethodExample::with_note(serde_json::json!({"id": "MENGER-40", "status": "Coding"}), "start work"))
2203 .with_param_values("status", ["Pending", "Ready"])
2204 .with_param_values("nope", ["x"]);
2205 assert_eq!(m.param_values("status"), Some(vec!["Pending".to_string(), "Ready".to_string()]));
2206 let wire = serde_json::to_value(&m).unwrap();
2207 assert_eq!(wire["group"], "write");
2208 assert_eq!(wire["examples"], serde_json::json!([{ "params": {"id": "MENGER-40", "status": "Coding"}, "note": "start work" }]));
2209 assert_eq!(wire["params"]["properties"]["status"]["x-plexus-values"], serde_json::json!(["Pending", "Ready"]));
2210 assert_eq!(wire["params"]["properties"]["status"]["description"], "New status");
2211 assert!(wire["params"]["properties"].get("nope").is_none());
2212 let back: MethodSchema = serde_json::from_value(wire).unwrap();
2213 assert_eq!(back.group.as_deref(), Some("write"));
2214 assert_eq!(back.examples, m.examples);
2215 }
2216
2217 #[test]
2218 fn test_schema_creation() {
2219 let schema = Schema::object()
2220 .with_property("id", SchemaProperty::uuid().with_description("The unique identifier"))
2221 .with_property("name", SchemaProperty::string().with_description("The name"))
2222 .with_required("id");
2223
2224 assert_eq!(schema.schema_type, Some(serde_json::json!("object")));
2225 assert!(schema.properties.is_some());
2226 assert_eq!(schema.required, Some(vec!["id".to_string()]));
2227 }
2228
2229 #[test]
2230 fn test_serialization() {
2231 let schema = Schema::object()
2232 .with_property("id", SchemaProperty::uuid());
2233
2234 let json = serde_json::to_string_pretty(&schema).unwrap();
2235 assert!(json.contains("uuid"));
2236 }
2237
2238 #[test]
2239 fn test_self_hash_changes_on_method_change() {
2240 let schema1 = PluginSchema::leaf(
2241 "test",
2242 "1.0",
2243 "desc",
2244 vec![MethodSchema::new("foo", "bar", "hash1")],
2245 );
2246
2247 let schema2 = PluginSchema::leaf(
2248 "test",
2249 "1.0",
2250 "desc",
2251 vec![MethodSchema::new("foo", "baz", "hash2")], // Changed description
2252 );
2253
2254 assert_ne!(schema1.self_hash, schema2.self_hash, "self_hash should change when methods change");
2255 assert_eq!(schema1.children_hash, schema2.children_hash, "children_hash should stay same (both None)");
2256 assert_ne!(schema1.hash, schema2.hash, "composite hash should change");
2257 }
2258
2259 #[test]
2260 fn test_children_hash_changes_on_child_change() {
2261 let child1 = ChildSummary {
2262 namespace: "child".into(),
2263 description: "desc".into(),
2264 hash: "old_hash".into(),
2265 };
2266
2267 let child2 = ChildSummary {
2268 namespace: "child".into(),
2269 description: "desc".into(),
2270 hash: "new_hash".into(),
2271 };
2272
2273 let schema1 = PluginSchema::hub(
2274 "parent",
2275 "1.0",
2276 "desc",
2277 vec![],
2278 vec![child1],
2279 );
2280
2281 let schema2 = PluginSchema::hub(
2282 "parent",
2283 "1.0",
2284 "desc",
2285 vec![],
2286 vec![child2],
2287 );
2288
2289 assert_eq!(schema1.self_hash, schema2.self_hash, "self_hash should stay same (no methods changed)");
2290 assert_ne!(schema1.children_hash, schema2.children_hash, "children_hash should change when child hash changes");
2291 assert_ne!(schema1.hash, schema2.hash, "composite hash should change");
2292 }
2293
2294 #[test]
2295 fn test_leaf_has_no_children_hash() {
2296 let schema = PluginSchema::leaf(
2297 "leaf",
2298 "1.0",
2299 "desc",
2300 vec![MethodSchema::new("method", "desc", "hash")],
2301 );
2302
2303 assert!(schema.children_hash.is_none(), "leaf plugin should have None for children_hash");
2304 assert_ne!(schema.self_hash, schema.hash, "leaf plugin's composite hash is hash(self_hash), not equal to self_hash");
2305 }
2306
2307 // =========================================================================
2308 // RETURNS-10: content hashes and the SHA-256 roll-up
2309 // =========================================================================
2310
2311 fn sample_method() -> MethodSchema {
2312 MethodSchema::new("get", "Fetch one", "")
2313 .with_returns(serde_json::from_value(serde_json::json!({
2314 "title": "Item", "type": "object",
2315 "properties": {"id": {"type": "string"}}, "required": ["id"]
2316 })).unwrap())
2317 }
2318
2319 #[test]
2320 fn returns10_content_hash_is_sha256_of_canonical_json_without_hash() {
2321 let m = sample_method();
2322 let mut v = serde_json::to_value(&m).unwrap();
2323 v.as_object_mut().unwrap().remove("hash");
2324 assert_eq!(m.content_hash(), hash16(canonical_json(&v).as_bytes()));
2325 assert_eq!(m.content_hash().len(), 16);
2326 // `hash` itself is not covered: sealing twice is a no-op.
2327 let sealed = m.clone().with_content_hash();
2328 assert_eq!(sealed.hash, m.content_hash());
2329 assert_eq!(sealed.clone().with_content_hash().hash, sealed.hash);
2330 let other_hash = MethodSchema { hash: "anything".into(), ..m.clone() };
2331 assert_eq!(other_hash.content_hash(), m.content_hash());
2332 }
2333
2334 #[test]
2335 fn returns10_content_hash_ignores_key_order_on_the_wire() {
2336 let m = sample_method().with_content_hash();
2337 let wire = serde_json::to_string(&m).unwrap();
2338 // The same method, its keys written in another order.
2339 let reordered: MethodSchema = serde_json::from_str(
2340 r#"{"returns":{"required":["id"],"properties":{"id":{"type":"string"}},"type":"object","title":"Item"},
2341 "cardinality":"one","role":{"kind":"rpc"},"http_method":"POST","bidirectional":false,
2342 "hash":"ignored","description":"Fetch one","name":"get"}"#,
2343 ).unwrap();
2344 assert_eq!(reordered.content_hash(), m.hash, "wire: {wire}");
2345 }
2346
2347 #[test]
2348 fn returns10_content_hash_moves_with_any_field() {
2349 let base = sample_method().content_hash();
2350 let variants = [
2351 ("description", MethodSchema { description: "Fetch two".into(), ..sample_method() }),
2352 ("name", MethodSchema { name: "fetch".into(), ..sample_method() }),
2353 ("cardinality", sample_method().with_cardinality(Cardinality::Many)),
2354 ("returns field", sample_method().with_returns(serde_json::from_value(serde_json::json!({
2355 "title": "Item", "type": "object",
2356 "properties": {"id": {"type": "integer"}}, "required": ["id"]
2357 })).unwrap())),
2358 ("error", sample_method().with_error(serde_json::from_value(serde_json::json!({"title": "E"})).unwrap())),
2359 ("progress", sample_method().with_progress(serde_json::from_value(serde_json::json!({"title": "P"})).unwrap())),
2360 ("http method", sample_method().with_http_method(HttpMethod::Get)),
2361 ("role", sample_method().with_role(MethodRole::StaticChild)),
2362 ];
2363 let mut seen = std::collections::HashSet::from([base.clone()]);
2364 for (what, m) in variants {
2365 assert!(seen.insert(m.content_hash()), "{what}: the hash moved to a new value");
2366 }
2367 }
2368
2369 /// RETURNS-36 (review #11): the `schema` entry is known by what every
2370 /// 0.8.x build writes alike — not by a hash recomputed with this build,
2371 /// which a peer whose plexus-core differs by a patch (a doc comment in
2372 /// `SchemaResult`, say) does not share.
2373 #[test]
2374 fn the_schema_entry_is_known_across_patches() {
2375 let ours = MethodSchema::auto_schema().with_grant("echo.schema").with_content_hash();
2376 assert!(ours.is_auto_schema());
2377 // Another patch's: the same entry, its `returns` documented otherwise.
2378 let mut theirs = MethodSchema::auto_schema().with_grant("echo.schema");
2379 let mut returns = serde_json::to_value(&theirs.returns).unwrap();
2380 returns["description"] = serde_json::json!("another patch's words");
2381 theirs.returns = serde_json::from_value(returns).unwrap();
2382 let theirs = theirs.with_content_hash();
2383 assert_ne!(theirs.hash, ours.hash);
2384 assert!(theirs.is_auto_schema(), "a 0.8.x peer's schema entry, another patch");
2385 // A method named `schema` that is not the entry: other params.
2386 let user = MethodSchema::new("schema", "mine", "").with_params(schema_for!(String)).with_content_hash();
2387 assert!(!user.is_auto_schema());
2388 }
2389
2390 #[test]
2391 fn returns10_rollup_is_sha256_of_the_hashes_one_per_line() {
2392 let a = MethodSchema::new("a", "", "aaaaaaaaaaaaaaaa");
2393 let b = MethodSchema::new("b", "", "bbbbbbbbbbbbbbbb");
2394 let leaf = PluginSchema::leaf("p", "1", "", vec![a.clone(), b.clone()]);
2395 assert_eq!(leaf.self_hash, hash16(b"aaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbb\n"));
2396 assert_eq!(leaf.hash, hash16(format!("{}\n", leaf.self_hash).as_bytes()));
2397 assert_eq!(leaf.children_hash, None);
2398
2399 let kid = ChildSummary { namespace: "k".into(), description: "".into(), hash: "cccccccccccccccc".into() };
2400 let service = PluginSchema::hub("p", "1", "", vec![a, b], vec![kid]);
2401 assert_eq!(service.self_hash, leaf.self_hash, "children don't touch self_hash");
2402 let children_hash = hash16(b"cccccccccccccccc\n");
2403 assert_eq!(service.children_hash.as_deref(), Some(children_hash.as_str()));
2404 assert_eq!(service.hash, hash16(format!("{}\n{}\n", service.self_hash, children_hash).as_bytes()));
2405 // Pinned (computed independently with Python's hashlib): the roll-up
2406 // is a wire contract — synapse-cc locks compare it across machines —
2407 // so its bytes may not drift.
2408 assert_eq!(
2409 (leaf.self_hash.as_str(), leaf.hash.as_str(), service.hash.as_str()),
2410 ("4140cd727c96fc78", "03a069b51ff1b744", "22db23bea1fbad28")
2411 );
2412 assert_eq!(children_hash, "f631be22675d9426");
2413 }
2414
2415 // =========================================================================
2416 // IR-2 tests: MethodRole, DeprecationInfo, is_hub derived query
2417 // =========================================================================
2418
2419 /// AC #5: Deserializing a JSON `MethodSchema` with no `role` or
2420 /// `deprecation` fields yields `MethodRole::Rpc` and `None`.
2421 ///
2422 /// 0.7 (RETURNS-5): the minimal method carries the two required fields,
2423 /// `returns` and `cardinality`; everything else still defaults.
2424 #[test]
2425 fn ir2_default_role_is_rpc_on_deserialize() {
2426 // Minimal MethodSchema shape (no role, no deprecation, no error/progress)
2427 let pre_ir_json = serde_json::json!({
2428 "name": "ping",
2429 "description": "pong",
2430 "hash": "abc",
2431 "returns": {},
2432 "cardinality": "one"
2433 });
2434
2435 let schema: MethodSchema = serde_json::from_value(pre_ir_json).unwrap();
2436 assert_eq!(schema.role, MethodRole::Rpc);
2437 assert!(schema.deprecation.is_none());
2438 assert!(schema.error.is_none());
2439 assert!(schema.progress.is_none());
2440 }
2441
2442 /// AC #5: And at the PluginSchema level — a full pre-IR schema with
2443 /// multiple methods (none carrying `role`) deserializes cleanly with every
2444 /// method defaulted to `Rpc` and no deprecation.
2445 #[test]
2446 fn ir2_plugin_schema_pre_ir_json_deserializes() {
2447 let pre_ir_json = serde_json::json!({
2448 "namespace": "test",
2449 "version": "1.0",
2450 "description": "legacy schema",
2451 "self_hash": "s1",
2452 "hash": "h1",
2453 "methods": [
2454 { "name": "a", "description": "alpha", "hash": "ah", "returns": {}, "cardinality": "one" },
2455 { "name": "b", "description": "beta", "hash": "bh", "returns": {}, "cardinality": "many" }
2456 ]
2457 });
2458
2459 let schema: PluginSchema = serde_json::from_value(pre_ir_json).unwrap();
2460 assert_eq!(schema.methods.len(), 2);
2461 for m in &schema.methods {
2462 assert_eq!(m.role, MethodRole::Rpc);
2463 assert!(m.deprecation.is_none());
2464 }
2465 }
2466
2467 /// AC #6: Serde round-trip covering all `MethodRole` variants —
2468 /// `Rpc`, `StaticChild`, and `DynamicChild { list_method, search_method }`.
2469 #[test]
2470 fn ir2_method_role_roundtrip_all_variants() {
2471 let original = PluginSchema::leaf(
2472 "rt",
2473 "1.0",
2474 "round-trip coverage",
2475 vec![
2476 MethodSchema::new("plain", "rpc", "h1"),
2477 MethodSchema::new("child_a", "static", "h2")
2478 .with_role(MethodRole::StaticChild),
2479 MethodSchema::new("child_b", "dynamic", "h3").with_role(
2480 MethodRole::DynamicChild {
2481 list_method: Some("list_x".into()),
2482 search_method: Some("search_x".into()),
2483 },
2484 ),
2485 ],
2486 );
2487
2488 let json = serde_json::to_string(&original).unwrap();
2489 let decoded: PluginSchema = serde_json::from_str(&json).unwrap();
2490
2491 assert_eq!(decoded.methods[0].role, MethodRole::Rpc);
2492 assert_eq!(decoded.methods[1].role, MethodRole::StaticChild);
2493 assert_eq!(
2494 decoded.methods[2].role,
2495 MethodRole::DynamicChild {
2496 list_method: Some("list_x".into()),
2497 search_method: Some("search_x".into()),
2498 }
2499 );
2500
2501 // Also survives when the DynamicChild has no list/search hints.
2502 let bare_dyn = MethodSchema::new("child_c", "dynamic-bare", "h4").with_role(
2503 MethodRole::DynamicChild {
2504 list_method: None,
2505 search_method: None,
2506 },
2507 );
2508 let j2 = serde_json::to_string(&bare_dyn).unwrap();
2509 let d2: MethodSchema = serde_json::from_str(&j2).unwrap();
2510 assert_eq!(
2511 d2.role,
2512 MethodRole::DynamicChild {
2513 list_method: None,
2514 search_method: None,
2515 }
2516 );
2517 }
2518
2519 /// AC #7: Serde round-trip for `DeprecationInfo` on a `MethodSchema`.
2520 #[test]
2521 fn ir2_deprecation_info_roundtrip() {
2522 let info = DeprecationInfo {
2523 since: "0.5".into(),
2524 removed_in: "0.6".into(),
2525 message: "use MethodRole".into(),
2526 };
2527 let method = MethodSchema::new("old", "legacy method", "hx")
2528 .with_deprecation(info.clone());
2529
2530 let json = serde_json::to_string(&method).unwrap();
2531 let decoded: MethodSchema = serde_json::from_str(&json).unwrap();
2532
2533 assert_eq!(decoded.deprecation, Some(info));
2534 }
2535
2536 /// AC #4: `PluginSchema::is_hub_by_role()` — the derived query reads only
2537 /// `methods`, not the legacy `children` field.
2538 ///
2539 /// Covers every row of the acceptance-criteria table.
2540 #[test]
2541 fn ir2_is_hub_by_role_derived_query() {
2542 // Row 1: all Rpc → false
2543 let all_rpc = PluginSchema::leaf(
2544 "p",
2545 "1.0",
2546 "all rpc",
2547 vec![
2548 MethodSchema::new("a", "d", "h1"),
2549 MethodSchema::new("b", "d", "h2"),
2550 ],
2551 );
2552 assert!(!all_rpc.is_hub_by_role());
2553 // And the back-compat `is_hub()` also returns false (no children).
2554 assert!(!all_rpc.is_hub());
2555
2556 // Row 2: at least one StaticChild → true
2557 let static_child = PluginSchema::leaf(
2558 "p",
2559 "1.0",
2560 "has static child",
2561 vec![
2562 MethodSchema::new("a", "d", "h1"),
2563 MethodSchema::new("kid", "d", "h2").with_role(MethodRole::StaticChild),
2564 ],
2565 );
2566 assert!(static_child.is_hub_by_role());
2567 assert!(static_child.is_hub());
2568
2569 // Row 3: at least one DynamicChild → true
2570 let dyn_child = PluginSchema::leaf(
2571 "p",
2572 "1.0",
2573 "has dynamic child",
2574 vec![MethodSchema::new("find", "d", "h1").with_role(
2575 MethodRole::DynamicChild {
2576 list_method: None,
2577 search_method: None,
2578 },
2579 )],
2580 );
2581 assert!(dyn_child.is_hub_by_role());
2582 assert!(dyn_child.is_hub());
2583
2584 // Row 4: Mix of Rpc + StaticChild → true
2585 let mixed = PluginSchema::leaf(
2586 "p",
2587 "1.0",
2588 "mixed",
2589 vec![
2590 MethodSchema::new("a", "d", "h1"),
2591 MethodSchema::new("b", "d", "h2"),
2592 MethodSchema::new("k", "d", "h3").with_role(MethodRole::StaticChild),
2593 ],
2594 );
2595 assert!(mixed.is_hub_by_role());
2596 assert!(mixed.is_hub());
2597
2598 // Row 5: empty methods → false
2599 let empty = PluginSchema::leaf("p", "1.0", "empty", vec![]);
2600 assert!(!empty.is_hub_by_role());
2601 assert!(!empty.is_hub());
2602 }
2603
2604 /// The derived query is independent of the legacy `children` side channel
2605 /// — a `PluginSchema::hub(...)` with only `Rpc` methods reports
2606 /// `is_hub_by_role() == false` (children don't count) while `is_hub()` is
2607 /// still `true` (transition-window fallback).
2608 #[test]
2609 fn ir2_is_hub_by_role_ignores_children_field() {
2610 let hub_with_rpc_only = PluginSchema::hub(
2611 "h",
2612 "1.0",
2613 "transition",
2614 vec![MethodSchema::new("a", "d", "ah")],
2615 vec![ChildSummary {
2616 namespace: "kid".into(),
2617 description: "child".into(),
2618 hash: "kh".into(),
2619 }],
2620 );
2621
2622 // The derived query reads only methods — no child role → false.
2623 assert!(!hub_with_rpc_only.is_hub_by_role());
2624 // Back-compat `is_hub()` still reports true via the children fallback.
2625 assert!(hub_with_rpc_only.is_hub());
2626 }
2627
2628 // =========================================================================
2629 // RETURNS-5 tests: schema 0.7 — returns · error · progress · cardinality
2630 // =========================================================================
2631
2632 fn returns_5_full_method() -> MethodSchema {
2633 MethodSchema::new("import", "imports tickets", "h_import")
2634 .with_returns(schemars::json_schema!({ "type": "string", "title": "Summary" }))
2635 .with_error(schemars::json_schema!({ "type": "object", "title": "ImportError" }))
2636 .with_progress(schemars::json_schema!({ "type": "integer", "title": "Step" }))
2637 .with_cardinality(Cardinality::Many)
2638 }
2639
2640 /// AC #1: a method with all four fields round-trips through serde, with
2641 /// the names and spellings of the 0.7 table.
2642 #[test]
2643 fn returns_5_all_four_fields_roundtrip() {
2644 let method = returns_5_full_method();
2645 let json = serde_json::to_value(&method).unwrap();
2646 let obj = json.as_object().unwrap();
2647
2648 assert_eq!(obj["returns"], serde_json::json!({ "type": "string", "title": "Summary" }));
2649 assert_eq!(obj["error"], serde_json::json!({ "type": "object", "title": "ImportError" }));
2650 assert_eq!(obj["progress"], serde_json::json!({ "type": "integer", "title": "Step" }));
2651 assert_eq!(obj["cardinality"], serde_json::json!("many"));
2652
2653 let decoded: MethodSchema = serde_json::from_value(json.clone()).unwrap();
2654 assert_eq!(decoded.returns, method.returns);
2655 assert_eq!(decoded.error, method.error);
2656 assert_eq!(decoded.progress, method.progress);
2657 assert_eq!(decoded.cardinality, Cardinality::Many);
2658 assert_eq!(serde_json::to_value(&decoded).unwrap(), json);
2659 }
2660
2661 /// AC #1: `error` and `progress` are absent — not `null` — when `None`;
2662 /// `returns` and `cardinality` are always present.
2663 #[test]
2664 fn returns_5_error_and_progress_absent_when_none() {
2665 let method = MethodSchema::new("get", "gets a ticket", "h_get")
2666 .with_returns(schemars::json_schema!({ "type": "string" }));
2667 let json = serde_json::to_value(&method).unwrap();
2668 let obj = json.as_object().unwrap();
2669
2670 assert!(!obj.contains_key("error"), "error must be omitted when None, got {json}");
2671 assert!(!obj.contains_key("progress"), "progress must be omitted when None, got {json}");
2672 assert_eq!(obj["returns"], serde_json::json!({ "type": "string" }));
2673 assert_eq!(obj["cardinality"], serde_json::json!("one"));
2674
2675 let decoded: MethodSchema = serde_json::from_value(json).unwrap();
2676 assert!(decoded.error.is_none());
2677 assert!(decoded.progress.is_none());
2678 assert_eq!(decoded.cardinality, Cardinality::One);
2679 }
2680
2681 /// `MethodSchema::new` starts as one item of any value, infallible and
2682 /// progress-free.
2683 #[test]
2684 fn returns_5_new_defaults() {
2685 let method = MethodSchema::new("ping", "pong", "h_ping");
2686 assert_eq!(method.returns, schemars::Schema::default());
2687 assert!(method.error.is_none());
2688 assert!(method.progress.is_none());
2689 assert_eq!(method.cardinality, Cardinality::One);
2690 assert_eq!(
2691 serde_json::to_value(&method).unwrap()["returns"],
2692 serde_json::json!({})
2693 );
2694 }
2695
2696 /// `Cardinality` spells `"one"` / `"many"` both ways and rejects anything else.
2697 #[test]
2698 fn returns_5_cardinality_spelling() {
2699 for (c, s) in [(Cardinality::One, "\"one\""), (Cardinality::Many, "\"many\"")] {
2700 assert_eq!(serde_json::to_string(&c).unwrap(), s);
2701 assert_eq!(serde_json::from_str::<Cardinality>(s).unwrap(), c);
2702 }
2703 assert!(serde_json::from_str::<Cardinality>("\"One\"").is_err());
2704 assert!(serde_json::from_str::<Cardinality>("true").is_err());
2705 }
2706
2707 /// `returns` and `cardinality` are required: a 0.6-shaped method (no
2708 /// `cardinality`, or no `returns`) does not parse.
2709 #[test]
2710 fn returns_5_required_fields_reject_0_6_shape() {
2711 let no_cardinality = serde_json::json!({
2712 "name": "ping", "description": "pong", "hash": "h",
2713 "returns": {}, "bidirectional": false
2714 });
2715 assert!(serde_json::from_value::<MethodSchema>(no_cardinality).is_err());
2716
2717 let no_returns = serde_json::json!({
2718 "name": "ping", "description": "pong", "hash": "h",
2719 "cardinality": "one"
2720 });
2721 assert!(serde_json::from_value::<MethodSchema>(no_returns).is_err());
2722 }
2723
2724 /// The fields sit where `returns` / the old flag sat: after `params`,
2725 /// before `bidirectional` — every other field keeps its place on the wire.
2726 #[test]
2727 fn returns_5_field_order_on_the_wire() {
2728 let method = returns_5_full_method()
2729 .with_params(schemars::json_schema!({ "type": "object" }));
2730 let text = serde_json::to_string(&method).unwrap();
2731 let pos = |k: &str| text.find(&format!("\"{k}\":")).unwrap_or_else(|| panic!("{k} missing in {text}"));
2732 let order = ["name", "description", "hash", "params", "returns", "error", "progress", "cardinality", "bidirectional", "http_method", "role"];
2733 for pair in order.windows(2) {
2734 assert!(pos(pair[0]) < pos(pair[1]), "{} must precede {} in {text}", pair[0], pair[1]);
2735 }
2736 }
2737
2738 // =========================================================================
2739 // IR-4 tests: derive_legacy_fields, relaxed validate_no_collisions,
2740 // deprecation markers.
2741 // =========================================================================
2742
2743 /// AC #4 (row 1): empty method list → no children, not a hub.
2744 #[test]
2745 fn ir4_derive_empty_methods() {
2746 let (children, is_hub) = PluginSchema::derive_legacy_fields(&[]);
2747 assert!(children.is_empty());
2748 assert!(!is_hub);
2749 }
2750
2751 /// AC #4 (row 2): a single `Rpc` method → no children, not a hub.
2752 #[test]
2753 fn ir4_derive_single_rpc_method() {
2754 let methods = vec![MethodSchema::new("ping", "rpc method", "h1")];
2755 let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
2756 assert!(children.is_empty());
2757 assert!(!is_hub);
2758 }
2759
2760 /// AC #4 (row 3): one `StaticChild` method named "body" → one child named
2761 /// "body", `is_hub == true`.
2762 #[test]
2763 fn ir4_derive_single_static_child() {
2764 let methods = vec![
2765 MethodSchema::new("body", "static child", "h1")
2766 .with_role(MethodRole::StaticChild),
2767 ];
2768 let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
2769 assert_eq!(children.len(), 1);
2770 assert_eq!(children[0].namespace, "body");
2771 assert_eq!(children[0].description, "static child");
2772 assert_eq!(children[0].hash, "");
2773 assert!(is_hub);
2774 }
2775
2776 /// AC #4 (row 4): one `DynamicChild` method named "planet" → one child
2777 /// named "planet", `is_hub == true`.
2778 #[test]
2779 fn ir4_derive_single_dynamic_child() {
2780 let methods = vec![
2781 MethodSchema::new("planet", "dynamic child", "h1").with_role(
2782 MethodRole::DynamicChild {
2783 list_method: Some("list_planets".into()),
2784 search_method: None,
2785 },
2786 ),
2787 ];
2788 let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
2789 assert_eq!(children.len(), 1);
2790 assert_eq!(children[0].namespace, "planet");
2791 assert!(is_hub);
2792 }
2793
2794 /// AC #4 (row 5): mix of Rpc + StaticChild → one child, `is_hub == true`.
2795 #[test]
2796 fn ir4_derive_mixed_roles_preserves_order() {
2797 let methods = vec![
2798 MethodSchema::new("ping", "rpc", "h1"),
2799 MethodSchema::new("kid_a", "static a", "h2")
2800 .with_role(MethodRole::StaticChild),
2801 MethodSchema::new("describe", "rpc too", "h3"),
2802 MethodSchema::new("kid_b", "static b", "h4")
2803 .with_role(MethodRole::StaticChild),
2804 ];
2805 let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
2806 // Source-order preservation: kid_a appears before kid_b.
2807 assert_eq!(children.len(), 2);
2808 assert_eq!(children[0].namespace, "kid_a");
2809 assert_eq!(children[1].namespace, "kid_b");
2810 assert!(is_hub);
2811 }
2812
2813 /// IR-4: `derive_legacy_fields`'s `is_hub` result matches
2814 /// [`PluginSchema::is_hub_by_role`] on every method list covered by the
2815 /// acceptance-criteria table.
2816 #[test]
2817 fn ir4_derive_is_hub_matches_is_hub_by_role() {
2818 // Empty methods.
2819 let empty_schema = PluginSchema::leaf("t", "1.0", "d", vec![]);
2820 let (_, is_hub) = PluginSchema::derive_legacy_fields(&empty_schema.methods);
2821 assert_eq!(is_hub, empty_schema.is_hub_by_role());
2822
2823 // All-Rpc methods.
2824 let rpc_schema = PluginSchema::leaf(
2825 "t",
2826 "1.0",
2827 "d",
2828 vec![
2829 MethodSchema::new("a", "d", "h1"),
2830 MethodSchema::new("b", "d", "h2"),
2831 ],
2832 );
2833 let (_, is_hub) = PluginSchema::derive_legacy_fields(&rpc_schema.methods);
2834 assert_eq!(is_hub, rpc_schema.is_hub_by_role());
2835
2836 // StaticChild present.
2837 let static_schema = PluginSchema::leaf(
2838 "t",
2839 "1.0",
2840 "d",
2841 vec![
2842 MethodSchema::new("a", "d", "h1"),
2843 MethodSchema::new("kid", "d", "h2").with_role(MethodRole::StaticChild),
2844 ],
2845 );
2846 let (_, is_hub) = PluginSchema::derive_legacy_fields(&static_schema.methods);
2847 assert_eq!(is_hub, static_schema.is_hub_by_role());
2848 assert!(is_hub);
2849
2850 // DynamicChild present.
2851 let dyn_schema = PluginSchema::leaf(
2852 "t",
2853 "1.0",
2854 "d",
2855 vec![MethodSchema::new("find", "d", "h1").with_role(
2856 MethodRole::DynamicChild {
2857 list_method: None,
2858 search_method: None,
2859 },
2860 )],
2861 );
2862 let (_, is_hub) = PluginSchema::derive_legacy_fields(&dyn_schema.methods);
2863 assert_eq!(is_hub, dyn_schema.is_hub_by_role());
2864 assert!(is_hub);
2865 }
2866
2867 /// IR-4 rule 2: `validate_no_collisions` no longer panics when a
2868 /// `StaticChild`-role method shares its name with a `ChildSummary` —
2869 /// that's expected by construction (two wire representations of the
2870 /// same child).
2871 #[test]
2872 fn ir4_no_collision_static_child_method_vs_summary() {
2873 // Same name on both surfaces — used to panic, now accepted.
2874 let schema = PluginSchema::hub(
2875 "hub",
2876 "1.0",
2877 "has static child",
2878 vec![
2879 MethodSchema::new("ping", "rpc", "h1"),
2880 MethodSchema::new("kid", "static child", "h2")
2881 .with_role(MethodRole::StaticChild),
2882 ],
2883 vec![ChildSummary {
2884 namespace: "kid".into(),
2885 description: "static child".into(),
2886 hash: "kh".into(),
2887 }],
2888 );
2889 // Child stayed on the wire.
2890 #[allow(deprecated)]
2891 let kids = schema.children.as_ref().expect("hub has children");
2892 assert_eq!(kids.len(), 1);
2893 assert_eq!(kids[0].namespace, "kid");
2894 // Method kept its role tag.
2895 assert!(matches!(
2896 schema.methods.iter().find(|m| m.name == "kid").unwrap().role,
2897 MethodRole::StaticChild
2898 ));
2899 }
2900
2901 /// IR-4 rule 2: `validate_no_collisions` also tolerates DynamicChild-role
2902 /// method names that appear in the child summary list.
2903 #[test]
2904 fn ir4_no_collision_dynamic_child_method_vs_summary() {
2905 let schema = PluginSchema::hub(
2906 "hub",
2907 "1.0",
2908 "has dynamic child",
2909 vec![MethodSchema::new("body", "gate", "h1").with_role(
2910 MethodRole::DynamicChild {
2911 list_method: Some("body_names".into()),
2912 search_method: None,
2913 },
2914 )],
2915 vec![ChildSummary {
2916 namespace: "body".into(),
2917 description: "gate".into(),
2918 hash: "bh".into(),
2919 }],
2920 );
2921 #[allow(deprecated)]
2922 let kids = schema.children.as_ref().unwrap();
2923 assert_eq!(kids.len(), 1);
2924 }
2925
2926 /// IR-4 rule 2: `validate_no_collisions` still panics when an `Rpc`-role
2927 /// method's name collides with a child summary — that's the case the
2928 /// validation was designed to catch.
2929 #[test]
2930 #[should_panic(expected = "method/child collision")]
2931 fn ir4_collision_rpc_method_vs_summary_still_panics() {
2932 let _ = PluginSchema::hub(
2933 "hub",
2934 "1.0",
2935 "bad hub",
2936 vec![MethodSchema::new("oops", "rpc", "h1")],
2937 vec![ChildSummary {
2938 namespace: "oops".into(),
2939 description: "shadowed".into(),
2940 hash: "oh".into(),
2941 }],
2942 );
2943 }
2944
2945 /// IR-4 AC #3 (spec): reading `PluginSchema.children` outside a
2946 /// `#[allow(deprecated)]` block emits a compiler warning. This fixture
2947 /// uses `#[allow(deprecated)]` to confirm the attribute is required —
2948 /// if it weren't, the `#[deprecated]` annotation is either missing or
2949 /// wrong.
2950 #[test]
2951 fn ir4_deprecated_field_access_requires_allow_attribute() {
2952 let schema = PluginSchema::leaf(
2953 "t",
2954 "1.0",
2955 "d",
2956 vec![MethodSchema::new("a", "b", "h")],
2957 );
2958 // Reading the deprecated field — under `#[allow(deprecated)]` from
2959 // the module-level attribute on the tests module. Removing that
2960 // allow would produce a compiler warning pointing at this line.
2961 let _children = schema.children.clone();
2962 // Calling the deprecated method — same rationale.
2963 let _is_hub = schema.is_hub();
2964 }
2965
2966 /// AUTHZ-CRED-CORE-2 AC #8: `PluginSchema::leaf` runs the
2967 /// schema-build warning hook for the framework-reserved
2968 /// `_credentials` top-level field name. The hook itself emits a
2969 /// `tracing::warn!` line, which is not directly assertable here
2970 /// without a tracing subscriber; we exercise the predicate path
2971 /// through schema construction (no panic, schema still constructed)
2972 /// and assert that the underlying check function is wired in.
2973 #[test]
2974 fn cred_core_2_ac8_leaf_constructor_does_not_panic_on_collision() {
2975 // Build a returns schema with a top-level `_credentials` field —
2976 // the framework-reserved name.
2977 let returns_collision_schema: schemars::Schema = serde_json::from_value(
2978 serde_json::json!({
2979 "type": "object",
2980 "properties": {
2981 "user_id": { "type": "string" },
2982 "_credentials": { "type": "object" }
2983 }
2984 }),
2985 )
2986 .unwrap();
2987
2988 // The leaf constructor consults the warning hook but does NOT
2989 // fail — the field is shadowed at dispatch time, and the
2990 // warning is the user-visible diagnostic. Constructing the
2991 // schema must still succeed (additive behavior).
2992 let schema = PluginSchema::leaf(
2993 "auth",
2994 "1.0",
2995 "test",
2996 vec![MethodSchema::new("login", "logs in", "h1").with_returns(returns_collision_schema)],
2997 );
2998 // Plugin still built.
2999 assert_eq!(schema.namespace, "auth");
3000 assert_eq!(schema.methods.len(), 1);
3001
3002 // And the inverse: a schema without the collision does not
3003 // panic either.
3004 let no_collision_schema: schemars::Schema = serde_json::from_value(
3005 serde_json::json!({ "type": "object", "properties": { "user_id": { "type": "string" } } }),
3006 )
3007 .unwrap();
3008 let schema_clean = PluginSchema::leaf(
3009 "auth",
3010 "1.0",
3011 "test",
3012 vec![MethodSchema::new("ping", "pings", "h2").with_returns(no_collision_schema)],
3013 );
3014 assert_eq!(schema_clean.methods.len(), 1);
3015 }
3016
3017 /// IR-4 AC #8: `PluginSchema.is_hub()` (deprecated) and
3018 /// `PluginSchema::is_hub_by_role()` agree on every shape currently
3019 /// emitted by substrate activations (methods with role tags, children
3020 /// field populated via hub constructor).
3021 #[test]
3022 fn ir4_is_hub_and_is_hub_by_role_agree_on_role_tagged_methods() {
3023 // Pure-leaf, all Rpc: both false.
3024 let leaf = PluginSchema::leaf(
3025 "t",
3026 "1.0",
3027 "d",
3028 vec![MethodSchema::new("a", "d", "h1")],
3029 );
3030 assert_eq!(leaf.is_hub(), leaf.is_hub_by_role());
3031 assert!(!leaf.is_hub());
3032
3033 // Hub with role-tagged methods (today's post-IR-3 shape): both true.
3034 let hub_with_roles = PluginSchema::hub(
3035 "h",
3036 "1.0",
3037 "d",
3038 vec![MethodSchema::new("kid", "d", "h1").with_role(MethodRole::StaticChild)],
3039 vec![ChildSummary {
3040 namespace: "kid".into(),
3041 description: "d".into(),
3042 hash: "".into(),
3043 }],
3044 );
3045 assert_eq!(hub_with_roles.is_hub(), hub_with_roles.is_hub_by_role());
3046 assert!(hub_with_roles.is_hub());
3047 }
3048
3049 // =========================================================================
3050 // AUTHZ-CRED-CORE-3 tests: CredentialFieldDecl, RequiredCredential,
3051 // MethodSchema.credentials / .requires_credential projections.
3052 // =========================================================================
3053
3054 use plexus_auth_core::{
3055 AttachmentSite, CredentialFieldMarker, CredentialIssuer, CredentialKind,
3056 CredentialMetadata, CredentialScheme, HeaderName, MethodPath, Origin, Scope,
3057 };
3058
3059 fn sample_issuer() -> CredentialIssuer {
3060 CredentialIssuer::new(
3061 Origin::new("ws://localhost:4444"),
3062 MethodPath::try_new("auth.login").unwrap(),
3063 )
3064 }
3065
3066 fn sample_marker_single() -> CredentialFieldMarker {
3067 CredentialFieldMarker::new(
3068 None,
3069 "session",
3070 CredentialKind::Bearer,
3071 AttachmentSite::Header {
3072 name: HeaderName::try_new("authorization").unwrap(),
3073 },
3074 Some(CredentialScheme::new("Bearer ")),
3075 vec![Scope::new("cone.send_message")],
3076 Some(MethodPath::try_new("auth.refresh").unwrap()),
3077 Some(MethodPath::try_new("auth.logout").unwrap()),
3078 )
3079 }
3080
3081 /// AC #1: A method whose return type contains one `Credential<T>` field
3082 /// produces a `MethodSchema` whose `credentials` field has one
3083 /// `CredentialFieldDecl` entry with the correct field path and metadata.
3084 #[test]
3085 fn cred_core_3_ac1_single_credential_projection() {
3086 let marker = sample_marker_single();
3087 let decl = CredentialFieldDecl::from_marker(&marker, &[], sample_issuer());
3088
3089 // Field path is the marker's single field name.
3090 assert_eq!(decl.field_path, vec!["session".to_string()]);
3091 // No variant tag for a struct return type.
3092 assert!(decl.variant_tag.is_none());
3093 // Metadata composes correctly from the marker.
3094 assert_eq!(decl.metadata.kind, CredentialKind::Bearer);
3095 assert_eq!(
3096 decl.metadata.attach_as,
3097 AttachmentSite::Header {
3098 name: HeaderName::try_new("authorization").unwrap(),
3099 }
3100 );
3101 assert_eq!(decl.metadata.scheme, Some(CredentialScheme::new("Bearer ")));
3102 assert_eq!(decl.metadata.scopes, vec![Scope::new("cone.send_message")]);
3103 assert_eq!(
3104 decl.metadata.refresh_via,
3105 Some(MethodPath::try_new("auth.refresh").unwrap())
3106 );
3107 assert_eq!(
3108 decl.metadata.revoke_via,
3109 Some(MethodPath::try_new("auth.logout").unwrap())
3110 );
3111 assert_eq!(decl.metadata.issuer, sample_issuer());
3112
3113 // Project into a MethodSchema and confirm the field is populated.
3114 let method = MethodSchema::new("login", "logs in", "h_login").with_credentials(vec![decl]);
3115 assert_eq!(method.credentials.len(), 1);
3116 assert_eq!(method.credentials[0].field_path, vec!["session".to_string()]);
3117 }
3118
3119 /// AC #2: A method whose return type contains multiple `Credential<T>`
3120 /// fields produces a `MethodSchema` whose `credentials` field has one
3121 /// entry per credential, in stable order.
3122 #[test]
3123 fn cred_core_3_ac2_multiple_credentials_stable_order() {
3124 let m1 = CredentialFieldMarker::new(
3125 None,
3126 "access",
3127 CredentialKind::OauthAccess,
3128 AttachmentSite::Header {
3129 name: HeaderName::try_new("authorization").unwrap(),
3130 },
3131 Some(CredentialScheme::new("Bearer ")),
3132 vec![Scope::new("cone.send")],
3133 Some(MethodPath::try_new("auth.refresh").unwrap()),
3134 None,
3135 );
3136 let m2 = CredentialFieldMarker::new(
3137 None,
3138 "refresh",
3139 CredentialKind::OauthRefresh,
3140 AttachmentSite::Header {
3141 name: HeaderName::try_new("authorization").unwrap(),
3142 },
3143 None,
3144 vec![Scope::new("auth.refresh")],
3145 None,
3146 None,
3147 );
3148
3149 let decls = vec![
3150 CredentialFieldDecl::from_marker(&m1, &[], sample_issuer()),
3151 CredentialFieldDecl::from_marker(&m2, &[], sample_issuer()),
3152 ];
3153 let method = MethodSchema::new("login", "logs in", "h_oauth").with_credentials(decls);
3154
3155 // Two entries, in declaration order.
3156 assert_eq!(method.credentials.len(), 2);
3157 assert_eq!(method.credentials[0].field_path, vec!["access".to_string()]);
3158 assert_eq!(method.credentials[0].metadata.kind, CredentialKind::OauthAccess);
3159 assert_eq!(method.credentials[1].field_path, vec!["refresh".to_string()]);
3160 assert_eq!(method.credentials[1].metadata.kind, CredentialKind::OauthRefresh);
3161 }
3162
3163 /// AC #3: A method whose return type is an enum with credentials only on
3164 /// one variant produces a `MethodSchema` with the correct `variant_tag`
3165 /// set on each entry.
3166 #[test]
3167 fn cred_core_3_ac3_enum_variant_tag_set() {
3168 let marker = CredentialFieldMarker::new(
3169 Some("Issued"),
3170 "session",
3171 CredentialKind::Bearer,
3172 AttachmentSite::Header {
3173 name: HeaderName::try_new("authorization").unwrap(),
3174 },
3175 Some(CredentialScheme::new("Bearer ")),
3176 vec![Scope::new("cone.send_message")],
3177 None,
3178 None,
3179 );
3180 let decl = CredentialFieldDecl::from_marker(&marker, &[], sample_issuer());
3181 assert_eq!(decl.variant_tag, Some("Issued".to_string()));
3182 assert_eq!(decl.field_path, vec!["session".to_string()]);
3183
3184 let method = MethodSchema::new("login", "logs in", "h_login").with_credentials(vec![decl]);
3185 assert_eq!(method.credentials[0].variant_tag, Some("Issued".to_string()));
3186 }
3187
3188 /// `CredentialFieldDecl::from_marker` honors a non-empty path prefix
3189 /// (nested-field walk).
3190 #[test]
3191 fn cred_core_3_from_marker_with_nested_path_prefix() {
3192 let marker = sample_marker_single();
3193 let decl = CredentialFieldDecl::from_marker(&marker, &["auth"], sample_issuer());
3194 assert_eq!(decl.field_path, vec!["auth".to_string(), "session".to_string()]);
3195 }
3196
3197 /// AC #4: A method tagged `#[plexus::method(public)]` produces a
3198 /// `MethodSchema` whose `requires_credential` is `None`.
3199 ///
3200 /// "Public" maps to "no implicit derivation occurs"; the schema-build
3201 /// surface simply doesn't call `with_requires_credential`, leaving the
3202 /// field at its `None` default.
3203 #[test]
3204 fn cred_core_3_ac4_public_method_requires_credential_none() {
3205 let method = MethodSchema::new("auth.login", "logs in", "h_login");
3206 assert!(method.requires_credential.is_none());
3207
3208 // After round-trip the field also serializes/deserializes as None
3209 // (omitted on the wire).
3210 let json = serde_json::to_value(&method).unwrap();
3211 assert!(
3212 !json
3213 .as_object()
3214 .unwrap()
3215 .contains_key("requires_credential"),
3216 "requires_credential must be omitted from wire JSON when None, got {json}"
3217 );
3218 let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3219 assert!(decoded.requires_credential.is_none());
3220 }
3221
3222 /// AC #5: A method tagged with a scope produces a `MethodSchema` whose
3223 /// `requires_credential.scopes` contains that scope and whose
3224 /// `requires_credential.kind` is `None`.
3225 #[test]
3226 fn cred_core_3_ac5_scoped_method_implicit_requires_credential() {
3227 let req = RequiredCredential::from_method_scope(Scope::new("cone.send_message"));
3228 assert!(req.kind.is_none());
3229 assert_eq!(req.scopes, vec![Scope::new("cone.send_message")]);
3230 assert!(req.site_hint.is_none());
3231
3232 let method = MethodSchema::new("send", "sends a message", "h_send")
3233 .with_requires_credential(req.clone());
3234 assert_eq!(method.requires_credential.as_ref().unwrap(), &req);
3235 }
3236
3237 /// AC #6: A method whose path appears as the `refresh_via` or
3238 /// `revoke_via` of any credential in the schema produces a `MethodSchema`
3239 /// whose `requires_credential.kind` matches the issuing credential's
3240 /// kind.
3241 #[test]
3242 fn cred_core_3_ac6_refresh_target_narrows_kind() {
3243 // The OAuth refresh flow: the access credential carries
3244 // `refresh_via = auth.refresh`. The implicit-derivation rule
3245 // narrows the requires_credential of `auth.refresh` to
3246 // `OauthRefresh`.
3247 let req = RequiredCredential::from_refresh_revoke_target(
3248 CredentialKind::OauthRefresh,
3249 vec![Scope::new("auth.refresh")],
3250 );
3251 assert_eq!(req.kind, Some(CredentialKind::OauthRefresh));
3252 assert_eq!(req.scopes, vec![Scope::new("auth.refresh")]);
3253
3254 let refresh_method =
3255 MethodSchema::new("refresh", "refreshes a token", "h_refresh")
3256 .with_requires_credential(req.clone());
3257 assert_eq!(
3258 refresh_method.requires_credential.as_ref().unwrap().kind,
3259 Some(CredentialKind::OauthRefresh)
3260 );
3261 }
3262
3263 /// AC #6 variant: site_hint can be threaded through if a build-path
3264 /// derivation step has a preferred attach site (e.g., the OAuth refresh
3265 /// path that knows the refresh token is attached via header).
3266 #[test]
3267 fn cred_core_3_required_credential_site_hint_preserved() {
3268 let mut req = RequiredCredential::from_refresh_revoke_target(
3269 CredentialKind::OauthRefresh,
3270 vec![Scope::new("auth.refresh")],
3271 );
3272 let hint = AttachmentSite::Header {
3273 name: HeaderName::try_new("authorization").unwrap(),
3274 };
3275 req.site_hint = Some(hint.clone());
3276 let method = MethodSchema::new("refresh", "refreshes", "h_refresh")
3277 .with_requires_credential(req);
3278
3279 let json = serde_json::to_string(&method).unwrap();
3280 let decoded: MethodSchema = serde_json::from_str(&json).unwrap();
3281 assert_eq!(
3282 decoded.requires_credential.as_ref().unwrap().site_hint,
3283 Some(hint)
3284 );
3285 }
3286
3287 /// AC #7: A pre-existing schema consumer (synapse IR builder,
3288 /// hub-codegen) decodes the new schema fields with their additive
3289 /// defaults and continues to function.
3290 ///
3291 /// Tested by deserializing a pre-CRED-CORE-3 JSON shape (no
3292 /// `credentials`, no `requires_credential` fields) and asserting the
3293 /// defaults are applied.
3294 ///
3295 /// 0.7 (RETURNS-5): the JSON carries the two required fields, `returns`
3296 /// and `cardinality`.
3297 #[test]
3298 fn cred_core_3_ac7_pre_ir_json_deserializes_with_empty_defaults() {
3299 let pre_ir_json = serde_json::json!({
3300 "name": "ping",
3301 "description": "pong",
3302 "hash": "abc",
3303 "returns": {},
3304 "cardinality": "one"
3305 });
3306 let schema: MethodSchema = serde_json::from_value(pre_ir_json).unwrap();
3307 assert!(schema.credentials.is_empty());
3308 assert!(schema.requires_credential.is_none());
3309 }
3310
3311 /// AC #7 variant: a pre-IR PluginSchema with multiple methods
3312 /// deserializes cleanly with every method's credential projections
3313 /// defaulted.
3314 #[test]
3315 fn cred_core_3_ac7_pre_ir_plugin_schema_deserializes() {
3316 let pre_ir_json = serde_json::json!({
3317 "namespace": "legacy",
3318 "version": "1.0",
3319 "description": "no credentials",
3320 "self_hash": "s1",
3321 "hash": "h1",
3322 "methods": [
3323 { "name": "a", "description": "alpha", "hash": "ah", "returns": {}, "cardinality": "one" },
3324 { "name": "b", "description": "beta", "hash": "bh", "returns": {}, "cardinality": "one" }
3325 ]
3326 });
3327 let plugin: PluginSchema = serde_json::from_value(pre_ir_json).unwrap();
3328 for m in &plugin.methods {
3329 assert!(m.credentials.is_empty());
3330 assert!(m.requires_credential.is_none());
3331 }
3332 }
3333
3334 /// AC #8: The `_info` capability advertisement carries the new fields
3335 /// when populated.
3336 ///
3337 /// `_info` reads `MethodSchema`'s serde representation directly. We
3338 /// verify the wire JSON contains the new fields when populated.
3339 #[test]
3340 fn cred_core_3_ac8_info_advertisement_carries_populated_fields() {
3341 let marker = sample_marker_single();
3342 let decl = CredentialFieldDecl::from_marker(&marker, &[], sample_issuer());
3343 let req = RequiredCredential::from_method_scope(Scope::new("cone.send_message"));
3344 let method = MethodSchema::new("login", "logs in", "h_login")
3345 .with_credentials(vec![decl])
3346 .with_requires_credential(req);
3347
3348 let json = serde_json::to_value(&method).unwrap();
3349 let obj = json.as_object().unwrap();
3350 assert!(
3351 obj.contains_key("credentials"),
3352 "populated credentials must appear in wire JSON"
3353 );
3354 assert!(
3355 obj.contains_key("requires_credential"),
3356 "populated requires_credential must appear in wire JSON"
3357 );
3358 // And the entry shape is decodeable.
3359 let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3360 assert_eq!(decoded.credentials.len(), 1);
3361 assert_eq!(decoded.credentials[0].field_path, vec!["session".to_string()]);
3362 assert_eq!(
3363 decoded.requires_credential.as_ref().unwrap().scopes,
3364 vec![Scope::new("cone.send_message")]
3365 );
3366 }
3367
3368 /// AC #11 (no regression): a method that does not return credentials and
3369 /// has no scope-derived requirement has identical wire JSON to a pre-IR
3370 /// schema for the same method (the new fields are omitted on the wire).
3371 #[test]
3372 fn cred_core_3_ac11_methods_without_credentials_have_unchanged_wire_shape() {
3373 let method = MethodSchema::new("ping", "pong", "h_ping");
3374 let json = serde_json::to_value(&method).unwrap();
3375 let obj = json.as_object().unwrap();
3376 // No credentials key, no requires_credential key.
3377 assert!(!obj.contains_key("credentials"));
3378 assert!(!obj.contains_key("requires_credential"));
3379
3380 // And the round-trip preserves the empty defaults.
3381 let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3382 assert!(decoded.credentials.is_empty());
3383 assert!(decoded.requires_credential.is_none());
3384 }
3385
3386 /// Round-trip coverage: a full `MethodSchema` with both projections
3387 /// populated round-trips through serde without losing fields.
3388 #[test]
3389 fn cred_core_3_full_method_roundtrip_preserves_credentials_and_requires() {
3390 let marker = sample_marker_single();
3391 let decl = CredentialFieldDecl::from_marker(&marker, &[], sample_issuer());
3392 let req = RequiredCredential::from_method_scope(Scope::new("cone.send_message"));
3393 let method = MethodSchema::new("login", "logs in", "h_login")
3394 .with_credentials(vec![decl.clone()])
3395 .with_requires_credential(req.clone());
3396
3397 let json = serde_json::to_string(&method).unwrap();
3398 let decoded: MethodSchema = serde_json::from_str(&json).unwrap();
3399
3400 assert_eq!(decoded.credentials.len(), 1);
3401 assert_eq!(decoded.credentials[0], decl);
3402 assert_eq!(decoded.requires_credential.as_ref().unwrap(), &req);
3403 }
3404
3405 /// `CredentialFieldDecl` round-trips via serde — pinned independently
3406 /// of MethodSchema so consumers reading the decl in isolation (e.g.
3407 /// `AUTHZ-CRED-IR-1` Haskell decoder testing parity) have a
3408 /// trustworthy shape contract.
3409 #[test]
3410 fn cred_core_3_credential_field_decl_roundtrip() {
3411 let marker = sample_marker_single();
3412 let original = CredentialFieldDecl::from_marker(&marker, &["envelope"], sample_issuer());
3413 let json = serde_json::to_string(&original).unwrap();
3414 let parsed: CredentialFieldDecl = serde_json::from_str(&json).unwrap();
3415 assert_eq!(parsed, original);
3416 }
3417
3418 // =========================================================================
3419 // R-2 wire snapshot tests: `auth_posture` + `public` on MethodSchema
3420 // (ROLES+AP merged wave; joint AP-1).
3421 //
3422 // "old" = the pre-R-2 wire shape (no `auth_posture`, no `public` keys).
3423 // "new" = the R-2 emitter.
3424 // =========================================================================
3425
3426 /// Old-decodes-new: a schema that never sets the R-2 fields serializes to
3427 /// JSON containing neither key — byte-identical to the pre-R-2 wire, so
3428 /// old readers (synapse, hub-codegen, pinned IRs) see exactly what they
3429 /// always saw.
3430 #[test]
3431 fn r2_unset_fields_are_omitted_from_wire() {
3432 let method = MethodSchema::new("ping", "pong", "h_ping");
3433 let json = serde_json::to_value(&method).unwrap();
3434 let obj = json.as_object().unwrap();
3435 assert!(
3436 !obj.contains_key("auth_posture"),
3437 "auth_posture must be omitted when never declared, got {json}"
3438 );
3439 assert!(
3440 !obj.contains_key("public"),
3441 "public must be omitted when false, got {json}"
3442 );
3443 }
3444
3445 /// New-decodes-old: a pinned pre-R-2 JSON snapshot (no `auth_posture`,
3446 /// no `public`) decodes cleanly with the additive defaults.
3447 #[test]
3448 fn r2_pre_r2_snapshot_decodes_with_defaults() {
3449 // Pinned old-wire shape: exactly what a pre-R-2 emitter produced for
3450 // a plain method (see `r2_unset_fields_are_omitted_from_wire`).
3451 // 0.7 (RETURNS-5): `returns` + `cardinality` replace the old flag.
3452 let old_wire = r#"{"name":"ping","description":"pong","hash":"h_ping","returns":{},"cardinality":"one","bidirectional":false,"http_method":"POST","role":{"kind":"rpc"}}"#;
3453 let decoded: MethodSchema = serde_json::from_str(old_wire).unwrap();
3454 assert!(decoded.auth_posture.is_none());
3455 assert!(!decoded.public);
3456 assert!(decoded.requires_credential.is_none());
3457 }
3458
3459 /// Populated round-trip: posture + public + requires_credential all
3460 /// surface in the wire JSON and decode back losslessly.
3461 #[test]
3462 fn r2_populated_fields_roundtrip() {
3463 let gated = MethodSchema::new("send", "sends", "h_send")
3464 .with_auth_posture(AuthPosture::Required)
3465 .with_requires_credential(RequiredCredential::from_method_scope(Scope::new(
3466 "cone.send_message",
3467 )));
3468 let json = serde_json::to_value(&gated).unwrap();
3469 assert_eq!(json["auth_posture"], "required");
3470 assert_eq!(
3471 json["requires_credential"]["scopes"],
3472 serde_json::json!(["cone.send_message"])
3473 );
3474 let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3475 assert_eq!(decoded.auth_posture, Some(AuthPosture::Required));
3476
3477 let public = MethodSchema::new("login", "logs in", "h_login")
3478 .with_auth_posture(AuthPosture::Mixed)
3479 .with_public(true);
3480 let json = serde_json::to_value(&public).unwrap();
3481 assert_eq!(json["auth_posture"], "mixed");
3482 assert_eq!(json["public"], true);
3483 let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3484 assert_eq!(decoded.auth_posture, Some(AuthPosture::Mixed));
3485 assert!(decoded.public);
3486 }
3487
3488 /// All four posture variants serialize to their snake_case wire names
3489 /// and round-trip.
3490 #[test]
3491 fn r2_auth_posture_wire_names() {
3492 for (posture, wire) in [
3493 (AuthPosture::Required, "\"required\""),
3494 (AuthPosture::Optional, "\"optional\""),
3495 (AuthPosture::Mixed, "\"mixed\""),
3496 (AuthPosture::None, "\"none\""),
3497 ] {
3498 let s = serde_json::to_string(&posture).unwrap();
3499 assert_eq!(s, wire);
3500 let back: AuthPosture = serde_json::from_str(&s).unwrap();
3501 assert_eq!(back, posture);
3502 }
3503 }
3504
3505 /// `RequiredCredential::from_method_scopes` (R-2): multi-scope
3506 /// conjunction — kind stays `None`, scope order preserved, round-trips.
3507 #[test]
3508 fn r2_from_method_scopes_multi_scope_conjunction() {
3509 let req = RequiredCredential::from_method_scopes(vec![
3510 Scope::new("facet.write"),
3511 Scope::new("facet.admin"),
3512 ]);
3513 assert!(req.kind.is_none());
3514 assert!(req.site_hint.is_none());
3515 assert_eq!(
3516 req.scopes,
3517 vec![Scope::new("facet.write"), Scope::new("facet.admin")]
3518 );
3519
3520 let method =
3521 MethodSchema::new("update", "updates", "h_update").with_requires_credential(req.clone());
3522 let json = serde_json::to_string(&method).unwrap();
3523 let decoded: MethodSchema = serde_json::from_str(&json).unwrap();
3524 assert_eq!(decoded.requires_credential.as_ref().unwrap(), &req);
3525 }
3526
3527 /// A populated `_info`-shaped PluginSchema carries the R-2 fields on its
3528 /// methods (serde emission is the `_info` path — PluginSchema embeds
3529 /// `Vec<MethodSchema>` verbatim).
3530 #[test]
3531 fn r2_plugin_schema_info_emission_carries_fields() {
3532 let plugin = PluginSchema::leaf(
3533 "fixture",
3534 "1.0",
3535 "r2 fixture",
3536 vec![
3537 MethodSchema::new("gated", "needs scope", "h1")
3538 .with_auth_posture(AuthPosture::Required)
3539 .with_requires_credential(RequiredCredential::from_method_scope(
3540 Scope::new("fixture.gated"),
3541 )),
3542 MethodSchema::new("open", "anonymous ok", "h2")
3543 .with_auth_posture(AuthPosture::Required)
3544 .with_public(true),
3545 ],
3546 );
3547 let json = serde_json::to_value(&plugin).unwrap();
3548 let methods = json["methods"].as_array().unwrap();
3549 assert_eq!(methods[0]["auth_posture"], "required");
3550 assert_eq!(
3551 methods[0]["requires_credential"]["scopes"],
3552 serde_json::json!(["fixture.gated"])
3553 );
3554 assert!(methods[0].get("public").is_none());
3555 assert_eq!(methods[1]["public"], true);
3556 assert!(methods[1].get("requires_credential").is_none());
3557 }
3558
3559 /// `RequiredCredential` round-trips via serde — pinned independently
3560 /// for the same cross-stack reason as `CredentialFieldDecl`.
3561 #[test]
3562 fn cred_core_3_required_credential_roundtrip() {
3563 let req = RequiredCredential {
3564 kind: Some(CredentialKind::OauthRefresh),
3565 scopes: vec![Scope::new("auth.refresh")],
3566 site_hint: Some(AttachmentSite::Header {
3567 name: HeaderName::try_new("authorization").unwrap(),
3568 }),
3569 };
3570 let json = serde_json::to_string(&req).unwrap();
3571 let parsed: RequiredCredential = serde_json::from_str(&json).unwrap();
3572 assert_eq!(parsed, req);
3573 }
3574
3575 /// `RequiredCredential` with `kind: None, scopes: [...], site_hint:
3576 /// None` (the `from_method_scope` shape) serializes to a compact wire
3577 /// form that omits the absent fields.
3578 #[test]
3579 fn cred_core_3_required_credential_compact_wire_shape() {
3580 let req = RequiredCredential::from_method_scope(Scope::new("cone.send"));
3581 let json = serde_json::to_value(&req).unwrap();
3582 let obj = json.as_object().unwrap();
3583 // Only the scopes field is present on the wire.
3584 assert!(!obj.contains_key("kind"));
3585 assert!(obj.contains_key("scopes"));
3586 assert!(!obj.contains_key("site_hint"));
3587 }
3588
3589 /// CA-1: `fill_site_hint` fills only an ABSENT hint — an existing one
3590 /// (e.g. a future explicit override) always wins over the
3591 /// capability-derived default.
3592 #[test]
3593 fn ca1_fill_site_hint_fills_absent_and_preserves_existing() {
3594 let derived = AttachmentSite::Cookie {
3595 name: plexus_auth_core::CookieName::try_new("access_token").unwrap(),
3596 };
3597
3598 // Absent → filled.
3599 let mut req = RequiredCredential::from_method_scope(Scope::new("cone.send"));
3600 req.fill_site_hint(&derived);
3601 assert_eq!(req.site_hint.as_ref(), Some(&derived));
3602
3603 // Present → preserved.
3604 let existing = AttachmentSite::Header {
3605 name: HeaderName::try_new("authorization").unwrap(),
3606 };
3607 let mut req = RequiredCredential::from_method_scope(Scope::new("cone.send"));
3608 req.site_hint = Some(existing.clone());
3609 req.fill_site_hint(&derived);
3610 assert_eq!(req.site_hint, Some(existing));
3611 }
3612
3613 /// CA-1: the plugin-level fill never CREATES a `requires_credential` —
3614 /// methods without one keep their pre-CA-1 wire shape exactly.
3615 #[test]
3616 fn ca1_plugin_fill_never_creates_requirements() {
3617 let derived = AttachmentSite::Header {
3618 name: HeaderName::try_new("authorization").unwrap(),
3619 };
3620 let mut plugin = PluginSchema::leaf(
3621 "fixture",
3622 "1.0",
3623 "ca-1 fixture",
3624 vec![
3625 MethodSchema::new("gated", "needs scope", "h1").with_requires_credential(
3626 RequiredCredential::from_method_scope(Scope::new("fixture.gated")),
3627 ),
3628 MethodSchema::new("open", "anonymous ok", "h2").with_public(true),
3629 ],
3630 );
3631 let before_open = serde_json::to_value(&plugin.methods[1]).unwrap();
3632
3633 plugin.fill_site_hints(&derived);
3634
3635 assert_eq!(
3636 plugin.methods[0]
3637 .requires_credential
3638 .as_ref()
3639 .unwrap()
3640 .site_hint
3641 .as_ref(),
3642 Some(&derived)
3643 );
3644 assert_eq!(
3645 serde_json::to_value(&plugin.methods[1]).unwrap(),
3646 before_open,
3647 "methods without a requirement must be byte-identical after the fill"
3648 );
3649 }
3650}