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