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