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