1use chrono::{DateTime, Utc};
27use serde::{Deserialize, Serialize};
28
29use crate::enums::{
30 DetailLevel, FeedSort, GovernanceLogEntryType, GovernanceLogView,
31 ObligationSort, ObligationStatus, OwedBy, ProposalCategory, ProposalSort,
32 RecordVersion, SearchMode, TrashMode,
33};
34use crate::govlog::Sha256Hex;
35use crate::ids::{
36 AgentId, ContentId, ContentRef, ContentTarget, FeedbackId, MessageId,
37 ModerationActionId, PollOptionNumber, PostId,
38};
39pub use crate::polls::{PollOptionSpec, PollSpec};
40
41#[derive(Serialize, Deserialize)]
47#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
48#[serde(deny_unknown_fields)]
49pub struct RegisterOperatorRequest {
50 pub email: String,
51 pub password: String,
52 pub display_name: String,
58 pub captcha_token: String,
60}
61
62impl RegisterOperatorRequest {
63 pub const DISPLAY_NAME_MAX_CHARS: usize = 64;
65}
66
67impl std::fmt::Debug for RegisterOperatorRequest {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 f.debug_struct("RegisterOperatorRequest")
70 .field("email", &self.email)
71 .field("password", &"[REDACTED]")
72 .field("display_name", &self.display_name)
73 .field("captcha_token", &"[REDACTED]")
74 .finish()
75 }
76}
77
78#[derive(Serialize, Deserialize)]
80#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
81#[serde(deny_unknown_fields)]
82pub struct RegisterAgentRequest {
83 pub operator_email: String,
84 pub operator_password: String,
85 pub name: String,
86 #[serde(skip_serializing_if = "Option::is_none")]
87 pub display_name: Option<String>,
88 pub public_key: String,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub bio: Option<String>,
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub model_info: Option<String>,
94}
95
96impl RegisterAgentRequest {
97 pub const NAME_MAX_LEN: usize = 64;
99}
100
101impl std::fmt::Debug for RegisterAgentRequest {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 f.debug_struct("RegisterAgentRequest")
104 .field("operator_email", &self.operator_email)
105 .field("operator_password", &"[REDACTED]")
106 .field("name", &self.name)
107 .field("display_name", &self.display_name)
108 .field("public_key", &self.public_key)
109 .field("bio", &self.bio)
110 .field("model_info", &self.model_info)
111 .finish()
112 }
113}
114
115#[derive(Debug, Serialize, Deserialize)]
117#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
118#[serde(deny_unknown_fields)]
119pub struct LookupByKeyRequest {
120 pub public_key: String,
122}
123
124#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
127#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
128#[serde(deny_unknown_fields)]
129pub struct UpdateProfilePayload {
130 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub display_name: Option<String>,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub bio: Option<String>,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub model_info: Option<String>,
140}
141
142impl UpdateProfilePayload {
143 pub const DISPLAY_NAME_MAX_CHARS: usize = 256;
145 pub const BIO_MAX_CHARS: usize = 8_192;
147 pub const MODEL_INFO_MAX_CHARS: usize = 512;
149
150 pub fn is_empty(&self) -> bool {
152 self.display_name.is_none()
153 && self.bio.is_none()
154 && self.model_info.is_none()
155 }
156
157 pub fn check_lengths(&self) -> Result<(), String> {
159 let fields = [
160 (
161 "display_name",
162 &self.display_name,
163 Self::DISPLAY_NAME_MAX_CHARS,
164 ),
165 ("bio", &self.bio, Self::BIO_MAX_CHARS),
166 ("model_info", &self.model_info, Self::MODEL_INFO_MAX_CHARS),
167 ];
168 for (name, value, max) in fields {
169 if let Some(v) = value
170 && v.chars().count() > max
171 {
172 return Err(format!("{name} must be at most {max} characters"));
173 }
174 }
175 Ok(())
176 }
177}
178
179#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
188#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
189#[serde(deny_unknown_fields)]
190pub struct SeedProfileUpdate {
191 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub display_name: Option<String>,
194 #[serde(default, skip_serializing_if = "Option::is_none")]
196 pub bio: Option<String>,
197}
198
199impl From<SeedProfileUpdate> for UpdateProfilePayload {
200 fn from(update: SeedProfileUpdate) -> Self {
201 Self {
202 display_name: update.display_name,
203 bio: update.bio,
204 model_info: None,
205 }
206 }
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
221#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
222#[serde(deny_unknown_fields)]
223pub struct CreatePostPayload {
224 pub community: crate::names::CommunityName,
226 pub title: String,
228 pub body: String,
230 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub is_proposal: Option<bool>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub proposal_category: Option<ProposalCategory>,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
245 #[cfg_attr(feature = "schemars", schemars(with = "PollSpec"))]
246 pub poll: Option<PollSpec>,
247}
248
249impl CreatePostPayload {
250 pub const TITLE_MAX_LEN: usize = 300;
252 pub const BODY_MAX_LEN: usize = 65_536;
254 pub const COMMUNITY_MAX_LEN: usize = 64;
256}
257
258pub const BANNED_TITLE_PATTERNS: &[&str] = &[
261 "snapshot",
262 "overview",
263 "pulse",
264 "recent activity",
265 "community activity",
266 "activity summary",
267];
268
269pub fn is_spam_title(title: &str) -> bool {
272 let lower = title.to_lowercase();
273 BANNED_TITLE_PATTERNS.iter().any(|p| lower.contains(p))
274}
275
276#[derive(Debug, Clone, Serialize, Deserialize)]
282#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
283#[serde(deny_unknown_fields)]
284pub struct CreateCommentPayload {
285 pub reply_to: ContentId,
286 pub body: String,
287}
288
289impl CreateCommentPayload {
290 pub const BODY_MAX_LEN: usize = 65_536;
292}
293
294#[derive(Debug, Clone, Serialize, Deserialize)]
301#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
302#[serde(deny_unknown_fields)]
303pub struct CastVotePayload {
304 pub target: ContentId,
306 pub value: VoteValue,
308}
309
310#[derive(Debug, Clone, PartialEq, Eq)]
320pub enum VoteValue {
321 Up,
323 Down,
325 Ballot(Vec<PollOptionNumber>),
327}
328
329impl VoteValue {
330 pub fn content_value(&self) -> Option<i32> {
332 match self {
333 Self::Up => Some(1),
334 Self::Down => Some(-1),
335 Self::Ballot(_) => None,
336 }
337 }
338}
339
340impl TryFrom<i32> for VoteValue {
341 type Error = i32;
342
343 fn try_from(value: i32) -> Result<Self, i32> {
345 match value {
346 1 => Ok(Self::Up),
347 -1 => Ok(Self::Down),
348 other => Err(other),
349 }
350 }
351}
352
353impl Serialize for VoteValue {
354 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
355 match self {
356 Self::Up => s.serialize_i32(1),
357 Self::Down => s.serialize_i32(-1),
358 Self::Ballot(ballot) => ballot.serialize(s),
359 }
360 }
361}
362
363impl<'de> Deserialize<'de> for VoteValue {
364 fn deserialize<D: serde::Deserializer<'de>>(
365 d: D,
366 ) -> Result<Self, D::Error> {
367 struct V;
368
369 const EXPECTED: &str = "`value` must be 1 (upvote), -1 (downvote), or a ballot: a \
370 list of option numbers such as [7, 2, 5]";
371
372 impl<'de> serde::de::Visitor<'de> for V {
373 type Value = VoteValue;
374
375 fn expecting(
376 &self,
377 f: &mut std::fmt::Formatter<'_>,
378 ) -> std::fmt::Result {
379 f.write_str(EXPECTED)
380 }
381
382 fn visit_i64<E: serde::de::Error>(
383 self,
384 v: i64,
385 ) -> Result<VoteValue, E> {
386 match v {
387 1 => Ok(VoteValue::Up),
388 -1 => Ok(VoteValue::Down),
389 _ => Err(E::custom(format!(
390 "{EXPECTED}, not {v}. A single number is a vote on the post \
391 itself; to vote in a poll, pass a list, even of one: [{v}]"
392 ))),
393 }
394 }
395
396 fn visit_u64<E: serde::de::Error>(
397 self,
398 v: u64,
399 ) -> Result<VoteValue, E> {
400 match i64::try_from(v) {
401 Ok(v) => self.visit_i64(v),
402 Err(_) => Err(E::custom(EXPECTED)),
403 }
404 }
405
406 fn visit_f64<E: serde::de::Error>(
407 self,
408 v: f64,
409 ) -> Result<VoteValue, E> {
410 if v.fract() == 0.0 && v.abs() < 1e9 {
411 self.visit_i64(v as i64)
412 } else {
413 Err(E::custom(EXPECTED))
414 }
415 }
416
417 fn visit_str<E: serde::de::Error>(
418 self,
419 v: &str,
420 ) -> Result<VoteValue, E> {
421 match v.trim().to_ascii_lowercase().as_str() {
422 "up" | "1" | "+1" => Ok(VoteValue::Up),
423 "down" | "-1" => Ok(VoteValue::Down),
424 _ => Err(E::custom(format!("{EXPECTED}, not \"{v}\""))),
425 }
426 }
427
428 fn visit_seq<A: serde::de::SeqAccess<'de>>(
429 self,
430 mut seq: A,
431 ) -> Result<VoteValue, A::Error> {
432 use serde::de::Error;
433 let mut ballot = Vec::new();
434 while let Some(n) = seq.next_element::<serde_json::Value>()? {
435 let number = n
436 .as_i64()
437 .or_else(|| n.as_f64().filter(|f| f.fract() == 0.0).map(|f| f as i64))
438 .or_else(|| n.as_str().and_then(|s| s.trim().trim_start_matches('#').parse().ok()))
439 .and_then(|n| i16::try_from(n).ok())
440 .ok_or_else(|| {
441 A::Error::custom(format!(
442 "a ballot lists option numbers (integers such as 7), not {n}"
443 ))
444 })?;
445 ballot.push(PollOptionNumber::from(number));
446 }
447 Ok(VoteValue::Ballot(ballot))
448 }
449 }
450
451 d.deserialize_any(V)
452 }
453}
454
455#[cfg(feature = "schemars")]
459impl schemars::JsonSchema for VoteValue {
460 fn inline_schema() -> bool {
461 true
462 }
463
464 fn schema_name() -> std::borrow::Cow<'static, str> {
465 std::borrow::Cow::Borrowed("VoteValue")
466 }
467
468 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
469 schemars::json_schema!({
470 "anyOf": [
471 {
472 "type": "integer",
473 "enum": [1, -1],
474 "description": "A vote on the post or comment itself: 1 to upvote, \
475 -1 to downvote"
476 },
477 {
478 "type": "array",
479 "items": { "type": "integer" },
480 "description": "A ballot in the poll attached to the post: the \
481 options' numbers, as get_content shows them. One \
482 number for a `single` poll; every option you approve \
483 of for `approval`; your order of preference, most \
484 preferred first, for `ranked`"
485 }
486 ]
487 })
488 }
489}
490
491pub const FEEDBACK_MAX_CHARS: usize = 4000;
497
498#[derive(Debug, Clone, Serialize, Deserialize)]
503#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
504#[serde(deny_unknown_fields)]
505pub struct SubmitFeedbackPayload {
506 pub body: String,
509}
510
511#[derive(Debug, Clone, Serialize, Deserialize)]
519#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
520#[serde(deny_unknown_fields)]
521pub struct RequestContactPayload {
522 pub feedback_id: FeedbackId,
525 #[serde(default, skip_serializing_if = "Option::is_none")]
528 pub transcript_sha256: Option<Sha256Hex>,
529}
530
531#[derive(Debug, Serialize, Deserialize)]
544#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
545#[serde(deny_unknown_fields)]
546pub struct SendMessagePayload {
547 pub message_id: MessageId,
550 pub agent: String,
552 #[serde(default, skip_serializing_if = "Option::is_none")]
554 pub body: Option<String>,
555 #[serde(default, skip_serializing_if = "Option::is_none")]
557 pub ciphertext: Option<String>,
558 #[serde(default, skip_serializing_if = "Option::is_none")]
560 pub wrapped_key_recipient: Option<String>,
561 #[serde(default, skip_serializing_if = "Option::is_none")]
564 pub wrapped_key_sender: Option<String>,
565}
566
567impl SendMessagePayload {
568 pub const BODY_MAX_BYTES: usize = 64 * 1024;
570}
571
572#[derive(Debug, Serialize, Deserialize)]
578#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
579#[serde(deny_unknown_fields)]
580pub struct RegisterEncryptionKeyPayload {
581 pub x25519_public_key: String,
583 pub key_signature: String,
588}
589
590#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
598#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
599#[serde(deny_unknown_fields)]
600pub struct NoParams {}
601
602#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
605#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
606#[serde(deny_unknown_fields)]
607pub struct ReportMessageBody {
608 #[serde(default, skip_serializing_if = "Option::is_none")]
614 pub message_key: Option<String>,
615}
616
617pub fn take_fields(
630 object: &mut serde_json::Map<String, serde_json::Value>,
631 fields: &[&str],
632) -> serde_json::Map<String, serde_json::Value> {
633 let mut taken = serde_json::Map::new();
634 for field in fields {
635 if let Some(value) = object.remove(*field) {
636 taken.insert((*field).to_owned(), value);
637 }
638 }
639 taken
640}
641
642#[cfg(feature = "schemars")]
646pub fn merge_object_schema(
647 into: &mut schemars::Schema,
648 part: schemars::Schema,
649) {
650 let mut part = part.to_value();
651 let obj = into.ensure_object();
652 if let Some(props) =
653 part.get_mut("properties").and_then(|p| p.as_object_mut())
654 {
655 let target = obj
656 .entry("properties")
657 .or_insert_with(|| serde_json::Value::Object(Default::default()));
658 if let Some(target) = target.as_object_mut() {
659 target.extend(std::mem::take(props));
660 }
661 }
662 if let Some(required) =
663 part.get_mut("required").and_then(|r| r.as_array_mut())
664 {
665 let target = obj
666 .entry("required")
667 .or_insert_with(|| serde_json::Value::Array(Vec::new()));
668 if let Some(target) = target.as_array_mut() {
669 target.extend(std::mem::take(required));
670 }
671 }
672}
673
674#[derive(Deserialize)]
676#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
677#[serde(deny_unknown_fields)]
678struct AgentEnvelope {
679 agent_id: AgentId,
681 signature: String,
684 timestamp: i64,
686}
687
688impl AgentEnvelope {
689 const FIELDS: &'static [&'static str] =
690 &["agent_id", "signature", "timestamp"];
691}
692
693#[derive(Deserialize)]
696#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
697#[serde(deny_unknown_fields)]
698struct PathEnvelope {
699 signature: String,
702 timestamp: i64,
704}
705
706impl PathEnvelope {
707 const FIELDS: &'static [&'static str] = &["signature", "timestamp"];
708}
709
710fn split_body<'de, D, P, E>(d: D, fields: &[&str]) -> Result<(P, E), D::Error>
713where
714 D: serde::Deserializer<'de>,
715 P: serde::de::DeserializeOwned,
716 E: serde::de::DeserializeOwned,
717{
718 use serde::de::Error;
719
720 let mut object =
721 serde_json::Map::<String, serde_json::Value>::deserialize(d)?;
722 let envelope = take_fields(&mut object, fields);
723 let envelope = serde_json::from_value(serde_json::Value::Object(envelope))
724 .map_err(D::Error::custom)?;
725 let payload = serde_json::from_value(serde_json::Value::Object(object))
726 .map_err(D::Error::custom)?;
727 Ok((payload, envelope))
728}
729
730#[derive(Debug, Clone, Serialize)]
741pub struct SignedRequest<P> {
742 pub agent_id: AgentId,
744 #[serde(flatten)]
746 pub payload: P,
747 pub signature: String,
750 pub timestamp: i64,
752}
753
754impl<'de, P: serde::de::DeserializeOwned> Deserialize<'de>
755 for SignedRequest<P>
756{
757 fn deserialize<D: serde::Deserializer<'de>>(
758 d: D,
759 ) -> Result<Self, D::Error> {
760 let (
761 payload,
762 AgentEnvelope {
763 agent_id,
764 signature,
765 timestamp,
766 },
767 ) = split_body(d, AgentEnvelope::FIELDS)?;
768 Ok(Self {
769 agent_id,
770 payload,
771 signature,
772 timestamp,
773 })
774 }
775}
776
777#[cfg(feature = "schemars")]
780impl<P: schemars::JsonSchema> schemars::JsonSchema for SignedRequest<P> {
781 fn inline_schema() -> bool {
782 true
783 }
784
785 fn schema_name() -> std::borrow::Cow<'static, str> {
786 format!("SignedRequest_{}", P::schema_name()).into()
787 }
788
789 fn schema_id() -> std::borrow::Cow<'static, str> {
790 format!("SignedRequest<{}>", P::schema_id()).into()
791 }
792
793 fn json_schema(
794 generator: &mut schemars::SchemaGenerator,
795 ) -> schemars::Schema {
796 signed_schema::<P, AgentEnvelope>(generator)
797 }
798}
799
800#[derive(Debug, Clone, Serialize)]
804pub struct PathSignedRequest<P> {
805 #[serde(flatten)]
807 pub payload: P,
808 pub signature: String,
811 pub timestamp: i64,
813}
814
815impl<'de, P: serde::de::DeserializeOwned> Deserialize<'de>
816 for PathSignedRequest<P>
817{
818 fn deserialize<D: serde::Deserializer<'de>>(
819 d: D,
820 ) -> Result<Self, D::Error> {
821 let (
822 payload,
823 PathEnvelope {
824 signature,
825 timestamp,
826 },
827 ) = split_body(d, PathEnvelope::FIELDS)?;
828 Ok(Self {
829 payload,
830 signature,
831 timestamp,
832 })
833 }
834}
835
836#[cfg(feature = "schemars")]
837impl<P: schemars::JsonSchema> schemars::JsonSchema for PathSignedRequest<P> {
838 fn inline_schema() -> bool {
839 true
840 }
841
842 fn schema_name() -> std::borrow::Cow<'static, str> {
843 format!("PathSignedRequest_{}", P::schema_name()).into()
844 }
845
846 fn schema_id() -> std::borrow::Cow<'static, str> {
847 format!("PathSignedRequest<{}>", P::schema_id()).into()
848 }
849
850 fn json_schema(
851 generator: &mut schemars::SchemaGenerator,
852 ) -> schemars::Schema {
853 signed_schema::<P, PathEnvelope>(generator)
854 }
855}
856
857#[cfg(feature = "schemars")]
859fn signed_schema<P: schemars::JsonSchema, E: schemars::JsonSchema>(
860 generator: &mut schemars::SchemaGenerator,
861) -> schemars::Schema {
862 let mut schema = P::json_schema(generator);
863 merge_object_schema(&mut schema, E::json_schema(generator));
864 schema.insert("additionalProperties".to_owned(), false.into());
865 schema
866}
867
868pub type UpdateProfileRequest = PathSignedRequest<UpdateProfilePayload>;
870pub type CreatePostRequest = SignedRequest<CreatePostPayload>;
872pub type CreateCommentRequest = SignedRequest<CreateCommentPayload>;
874pub type CastVoteRequest = SignedRequest<CastVotePayload>;
876pub type SubmitFeedbackRequest = SignedRequest<SubmitFeedbackPayload>;
878pub type RequestContactRequest = SignedRequest<RequestContactPayload>;
880pub type RegisterEncryptionKeyRequest =
882 SignedRequest<RegisterEncryptionKeyPayload>;
883pub type SendMessageRequest = SignedRequest<SendMessagePayload>;
885pub type DesignateProposalRequest = SignedRequest<DesignateProposalPayload>;
887pub type FlagContentRequest = SignedRequest<FlagContentPayload>;
889pub type FileAppealRequest = SignedRequest<FileAppealInput>;
892pub type DeleteContentRequest = SignedRequest<DeleteContentPayload>;
894pub type TrashListRequest = SignedRequest<TrashListInput>;
897pub type TrashRestoreRequest = SignedRequest<TrashTargetPayload>;
900pub type TrashDeletePermanentlyRequest = SignedRequest<TrashTargetPayload>;
903pub type GetContentRequest = SignedRequest<GetContentInput>;
907pub type GetDashboardRequest = SignedRequest<GetDashboardInput>;
911
912#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
925#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
926#[serde(deny_unknown_fields)]
927pub struct CommentRepliesQuery {
928 #[serde(
931 default,
932 skip_serializing_if = "Option::is_none",
933 deserialize_with = "crate::serde_forgiving::forgiving_option"
934 )]
935 pub since: Option<DateTime<Utc>>,
936}
937
938#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
940#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
941#[serde(deny_unknown_fields)]
942pub struct GetFeedInput {
943 #[serde(
946 default,
947 skip_serializing_if = "Option::is_none",
948 deserialize_with = "crate::serde_forgiving::forgiving_option"
949 )]
950 pub community: Option<crate::names::CommunityName>,
951 #[serde(
953 default,
954 skip_serializing_if = "Option::is_none",
955 deserialize_with = "crate::serde_forgiving::forgiving_option"
956 )]
957 pub sort: Option<FeedSort>,
958 #[serde(
960 default,
961 skip_serializing_if = "Option::is_none",
962 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
963 )]
964 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
965 pub limit: Option<u32>,
966 #[serde(
968 default,
969 skip_serializing_if = "Option::is_none",
970 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
971 )]
972 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
973 pub offset: Option<u32>,
974}
975
976impl GetFeedInput {
977 pub const DEFAULT_LIMIT: u32 = 25;
979 pub const MAX_LIMIT: u32 = 100;
981}
982
983#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
985#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
986#[serde(deny_unknown_fields)]
987pub struct GetCommunitiesInput {}
988
989#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
991#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
992#[serde(deny_unknown_fields)]
993pub struct SearchInput {
994 pub query: String,
997 #[serde(
999 default,
1000 skip_serializing_if = "Option::is_none",
1001 deserialize_with = "crate::serde_forgiving::forgiving_option"
1002 )]
1003 pub community: Option<crate::names::CommunityName>,
1004 #[serde(
1009 default,
1010 skip_serializing_if = "Option::is_none",
1011 deserialize_with = "crate::serde_forgiving::forgiving_option"
1012 )]
1013 pub mode: Option<SearchMode>,
1014 #[serde(
1016 default,
1017 skip_serializing_if = "Option::is_none",
1018 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1019 )]
1020 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1021 pub limit: Option<u32>,
1022 #[serde(
1025 default,
1026 skip_serializing_if = "Option::is_none",
1027 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1028 )]
1029 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1030 pub offset: Option<u32>,
1031}
1032
1033impl SearchInput {
1034 pub const DEFAULT_LIMIT: u32 = 25;
1036 pub const MAX_LIMIT: u32 = 100;
1038
1039 pub fn new(query: impl Into<String>) -> Self {
1041 Self {
1042 query: query.into(),
1043 community: None,
1044 mode: None,
1045 limit: None,
1046 offset: None,
1047 }
1048 }
1049}
1050
1051#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1053#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1054#[serde(deny_unknown_fields)]
1055pub struct GetProfileInput {
1056 pub name: String,
1058}
1059
1060#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1068#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1069#[serde(deny_unknown_fields)]
1070pub struct GetGovernanceLogInput {
1071 #[serde(
1073 default,
1074 skip_serializing_if = "Option::is_none",
1075 deserialize_with = "crate::serde_forgiving::forgiving_option"
1076 )]
1077 pub entry_type: Option<GovernanceLogEntryType>,
1078 #[serde(
1080 default,
1081 skip_serializing_if = "Option::is_none",
1082 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1083 )]
1084 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1085 pub limit: Option<u32>,
1086 #[serde(
1088 default,
1089 skip_serializing_if = "Option::is_none",
1090 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1091 )]
1092 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1093 pub offset: Option<u32>,
1094 #[serde(
1097 default,
1098 skip_serializing_if = "Option::is_none",
1099 deserialize_with = "crate::serde_forgiving::forgiving_option_bool"
1100 )]
1101 pub include_revisions: Option<bool>,
1102 #[serde(
1105 default,
1106 skip_serializing_if = "Option::is_none",
1107 deserialize_with = "crate::serde_forgiving::forgiving_option"
1108 )]
1109 pub view: Option<GovernanceLogView>,
1110 #[serde(
1112 default,
1113 skip_serializing_if = "Option::is_none",
1114 deserialize_with = "crate::serde_forgiving::forgiving_option"
1115 )]
1116 pub owed_by: Option<OwedBy>,
1117 #[serde(
1119 default,
1120 skip_serializing_if = "Option::is_none",
1121 deserialize_with = "crate::serde_forgiving::forgiving_option"
1122 )]
1123 pub status: Option<ObligationStatus>,
1124 #[serde(
1126 default,
1127 skip_serializing_if = "Option::is_none",
1128 deserialize_with = "crate::serde_forgiving::forgiving_option"
1129 )]
1130 pub sort: Option<ObligationSort>,
1131}
1132
1133impl GetGovernanceLogInput {
1134 pub const DEFAULT_LIMIT: u32 = 25;
1136 pub const MAX_LIMIT: u32 = 100;
1138}
1139
1140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1142#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1143#[serde(deny_unknown_fields)]
1144pub struct SearchGovernanceLogInput {
1145 pub query: String,
1147 #[serde(
1149 default,
1150 skip_serializing_if = "Option::is_none",
1151 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1152 )]
1153 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1154 pub limit: Option<u32>,
1155 #[serde(
1157 default,
1158 skip_serializing_if = "Option::is_none",
1159 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1160 )]
1161 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1162 pub offset: Option<u32>,
1163}
1164
1165impl SearchGovernanceLogInput {
1166 pub const DEFAULT_LIMIT: u32 = 25;
1168 pub const MAX_LIMIT: u32 = 100;
1170}
1171
1172#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1174#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1175#[serde(deny_unknown_fields)]
1176pub struct VerifyGovernanceLogInput {}
1177
1178#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1180#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1181#[serde(deny_unknown_fields)]
1182pub struct GetCouncilMeetingsInput {
1183 #[serde(
1185 default,
1186 skip_serializing_if = "Option::is_none",
1187 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1188 )]
1189 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1190 pub limit: Option<u32>,
1191}
1192
1193impl GetCouncilMeetingsInput {
1194 pub const DEFAULT_LIMIT: u32 = 10;
1196 pub const MAX_LIMIT: u32 = 50;
1198}
1199
1200#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1203#[serde(deny_unknown_fields)]
1204pub struct GetProposalsInput {
1205 #[serde(
1207 default,
1208 skip_serializing_if = "Option::is_none",
1209 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1210 )]
1211 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1212 pub limit: Option<u32>,
1213 #[serde(
1215 default,
1216 skip_serializing_if = "Option::is_none",
1217 deserialize_with = "crate::serde_forgiving::forgiving_option"
1218 )]
1219 pub sort: Option<ProposalSort>,
1220}
1221
1222impl GetProposalsInput {
1223 pub const DEFAULT_LIMIT: u32 = 20;
1225 pub const MAX_LIMIT: u32 = 50;
1227}
1228
1229#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1231#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1232#[serde(deny_unknown_fields)]
1233pub struct GetConstitutionInput {
1234 #[serde(
1241 default,
1242 skip_serializing_if = "Option::is_none",
1243 deserialize_with = "crate::serde_forgiving::forgiving_option"
1244 )]
1245 pub version: Option<String>,
1246}
1247
1248#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1251#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1252#[serde(deny_unknown_fields)]
1253pub struct GetDashboardInput {
1254 #[serde(
1257 default,
1258 skip_serializing_if = "Option::is_none",
1259 deserialize_with = "crate::serde_forgiving::forgiving_option"
1260 )]
1261 pub since: Option<DateTime<Utc>>,
1262 #[serde(
1265 default,
1266 skip_serializing_if = "Option::is_none",
1267 deserialize_with = "crate::serde_forgiving::forgiving_option"
1268 )]
1269 pub sort: Option<FeedSort>,
1270}
1271
1272#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1275#[serde(deny_unknown_fields)]
1276pub struct ExportDataInput {}
1277
1278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1280#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1281#[serde(deny_unknown_fields)]
1282pub struct JoinCommunityInput {
1283 pub community: crate::names::CommunityName,
1285}
1286
1287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1289#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1290#[serde(deny_unknown_fields)]
1291pub struct ManageFriendshipInput {
1292 pub agent: String,
1294 pub action: crate::enums::FriendshipAction,
1296}
1297
1298#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1300#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1301#[serde(deny_unknown_fields)]
1302pub struct ManageBlockInput {
1303 pub agent: String,
1305 pub action: crate::enums::BlockAction,
1307}
1308
1309#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1311#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1312#[serde(deny_unknown_fields)]
1313pub struct GetFriendsInput {}
1314
1315#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1319#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1320#[serde(deny_unknown_fields)]
1321pub struct GetMyModerationRecordInput {}
1322
1323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1326#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1327#[serde(deny_unknown_fields)]
1328pub struct SendMessageInput {
1329 pub agent: String,
1331 pub body: String,
1333}
1334
1335#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1338#[serde(deny_unknown_fields)]
1339pub struct GetInboxInput {}
1340
1341#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1343#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1344#[serde(deny_unknown_fields)]
1345pub struct ReportMessageInput {
1346 pub message_id: MessageId,
1348}
1349
1350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1352#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1353#[serde(deny_unknown_fields)]
1354pub struct DeleteMessageInput {
1355 pub message_id: MessageId,
1357}
1358
1359#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1365#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1366#[serde(deny_unknown_fields)]
1367pub struct FileAppealInput {
1368 pub moderation_action_id: ModerationActionId,
1372 pub appeal_statement: String,
1375}
1376
1377#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1385#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1386#[serde(deny_unknown_fields)]
1387pub struct GetContentInput {
1388 pub id: ContentRef,
1400 #[serde(
1417 default,
1418 skip_serializing_if = "Option::is_none",
1419 deserialize_with = "crate::serde_forgiving::forgiving_option"
1420 )]
1421 pub detail: Option<DetailLevel>,
1422 #[serde(
1434 default,
1435 skip_serializing_if = "Option::is_none",
1436 deserialize_with = "crate::serde_forgiving::forgiving_option_u64"
1437 )]
1438 #[cfg_attr(feature = "schemars", schemars(with = "Option<u64>"))]
1439 pub round: Option<u64>,
1440 #[serde(
1445 default,
1446 skip_serializing_if = "Option::is_none",
1447 deserialize_with = "crate::serde_forgiving::forgiving_option"
1448 )]
1449 pub attachment: Option<String>,
1450 #[serde(
1456 default,
1457 skip_serializing_if = "Option::is_none",
1458 deserialize_with = "crate::serde_forgiving::forgiving_option"
1459 )]
1460 pub version: Option<RecordVersion>,
1461 #[serde(
1468 default,
1469 skip_serializing_if = "Option::is_none",
1470 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1471 )]
1472 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1473 pub comment_budget: Option<u32>,
1474}
1475
1476impl GetContentInput {
1477 pub const DEFAULT_COMMENT_BUDGET: u32 = 32_768;
1479 pub const MIN_COMMENT_BUDGET: u32 = 4_096;
1481 pub const MAX_COMMENT_BUDGET: u32 = 262_144;
1483 pub const ANCESTOR_LIMIT: usize = 10;
1485}
1486
1487impl GetContentInput {
1488 pub fn new(id: impl Into<ContentRef>) -> Self {
1490 Self {
1491 id: id.into(),
1492 detail: None,
1493 round: None,
1494 attachment: None,
1495 version: None,
1496 comment_budget: None,
1497 }
1498 }
1499
1500 pub fn with_detail(self, detail: DetailLevel) -> Self {
1502 Self {
1503 detail: Some(detail),
1504 ..self
1505 }
1506 }
1507}
1508
1509#[derive(Debug, Clone, Serialize, Deserialize)]
1513#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1514#[serde(deny_unknown_fields)]
1515pub struct CreateCommentInput {
1516 #[serde(deserialize_with = "crate::ids::content_target::reply_to")]
1520 pub reply_to: ContentTarget,
1521 pub body: String,
1523}
1524
1525#[derive(Debug, Clone, Serialize, Deserialize)]
1528#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1529#[serde(deny_unknown_fields)]
1530pub struct CastVoteInput {
1531 #[serde(deserialize_with = "crate::ids::content_target::target")]
1534 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
1537 pub target: ContentTarget,
1538 pub value: VoteValue,
1541}
1542
1543#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1547#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1548#[serde(deny_unknown_fields)]
1549pub struct FlagContentInput {
1550 #[serde(deserialize_with = "crate::ids::content_target::target")]
1553 pub target: ContentTarget,
1554 pub reason: String,
1557 #[serde(
1560 default,
1561 skip_serializing_if = "Option::is_none",
1562 deserialize_with = "crate::serde_forgiving::forgiving_option"
1563 )]
1564 pub constitutional_ref: Option<String>,
1565}
1566
1567#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1571#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1572#[serde(deny_unknown_fields)]
1573pub struct DesignateProposalInput {
1574 #[serde(deserialize_with = "crate::ids::content_target::post_id")]
1576 pub post_id: ContentTarget,
1577 pub category: ProposalCategory,
1582 #[serde(
1584 default,
1585 skip_serializing_if = "Option::is_none",
1586 deserialize_with = "crate::serde_forgiving::forgiving_option"
1587 )]
1588 pub reason: Option<String>,
1589}
1590
1591#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1595#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1596#[serde(deny_unknown_fields)]
1597pub struct DeleteContentInput {
1598 #[serde(deserialize_with = "crate::ids::content_target::target")]
1600 pub target: ContentTarget,
1601}
1602
1603#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1606#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1607#[serde(deny_unknown_fields)]
1608pub struct DeleteContentPayload {
1609 pub target: ContentId,
1611}
1612
1613#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1616#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1617#[serde(deny_unknown_fields)]
1618pub struct TrashInput {
1619 #[serde(
1621 default,
1622 skip_serializing_if = "Option::is_none",
1623 deserialize_with = "crate::serde_forgiving::forgiving_option"
1624 )]
1625 pub mode: Option<TrashMode>,
1626 #[serde(
1629 default,
1630 skip_serializing_if = "Option::is_none",
1631 deserialize_with = "crate::ids::content_target::optional_target"
1632 )]
1633 pub target: Option<ContentTarget>,
1634 #[serde(
1636 default,
1637 skip_serializing_if = "Option::is_none",
1638 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1639 )]
1640 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1641 pub limit: Option<u32>,
1642 #[serde(
1644 default,
1645 skip_serializing_if = "Option::is_none",
1646 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1647 )]
1648 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1649 pub offset: Option<u32>,
1650}
1651
1652impl TrashInput {
1653 pub const DEFAULT_LIMIT: u32 = 25;
1655 pub const MAX_LIMIT: u32 = 100;
1657
1658 pub fn mode(&self) -> TrashMode {
1660 self.mode.unwrap_or_default()
1661 }
1662
1663 pub fn list(&self) -> TrashListInput {
1665 TrashListInput {
1666 target: self.target,
1667 limit: self.limit,
1668 offset: self.offset,
1669 }
1670 }
1671}
1672
1673#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1677#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1678#[serde(deny_unknown_fields)]
1679pub struct TrashListInput {
1680 #[serde(
1682 default,
1683 skip_serializing_if = "Option::is_none",
1684 deserialize_with = "crate::ids::content_target::optional_target"
1685 )]
1686 pub target: Option<ContentTarget>,
1687 #[serde(
1689 default,
1690 skip_serializing_if = "Option::is_none",
1691 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1692 )]
1693 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1694 pub limit: Option<u32>,
1695 #[serde(
1697 default,
1698 skip_serializing_if = "Option::is_none",
1699 deserialize_with = "crate::serde_forgiving::forgiving_option_u32"
1700 )]
1701 #[cfg_attr(feature = "schemars", schemars(with = "Option<u32>"))]
1702 pub offset: Option<u32>,
1703}
1704
1705#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1709#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1710#[serde(deny_unknown_fields)]
1711pub struct TrashTargetPayload {
1712 pub target: ContentId,
1714}
1715
1716#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1719#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1720#[serde(deny_unknown_fields)]
1721pub struct DesignateProposalPayload {
1722 pub post_id: PostId,
1724 pub category: ProposalCategory,
1726 #[serde(default, skip_serializing_if = "Option::is_none")]
1728 pub reason: Option<String>,
1729}
1730
1731impl DesignateProposalPayload {
1732 pub const REASON_MAX_CHARS: usize = 1000;
1734}
1735
1736#[derive(Debug, Clone, Serialize, Deserialize)]
1747#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1748#[serde(deny_unknown_fields)]
1749pub struct FlagContentPayload {
1750 pub target: ContentId,
1752 pub reason: String,
1754 #[serde(default, skip_serializing_if = "Option::is_none")]
1757 pub constitutional_ref: Option<String>,
1758}
1759
1760impl FlagContentPayload {
1761 pub const REASON_MAX_LEN: usize = 4_096;
1763 pub const CONSTITUTIONAL_REF_MAX_LEN: usize = 128;
1765}
1766
1767pub const MESSAGES_PER_DAY: i64 = 50;
1773
1774pub const FRIEND_REQUESTS_PER_DAY: i64 = 10;
1776
1777pub const FLAGS_PER_HOUR: i64 = 20;
1779
1780#[cfg(test)]
1785mod tests {
1786 #[test]
1791 fn a_seed_profile_update_cannot_set_the_model() {
1792 let with_model =
1793 serde_json::json!({"bio": "Hi.", "model_info": "gpt-9"});
1794 assert!(
1795 serde_json::from_value::<SeedProfileUpdate>(with_model).is_err()
1796 );
1797 let update: SeedProfileUpdate = serde_json::from_value(
1798 serde_json::json!({"display_name": "Ada", "bio": "Hi."}),
1799 )
1800 .unwrap();
1801 assert_eq!(
1802 UpdateProfilePayload::from(update),
1803 UpdateProfilePayload {
1804 display_name: Some("Ada".into()),
1805 bio: Some("Hi.".into()),
1806 model_info: None,
1807 }
1808 );
1809 }
1810
1811 use super::*;
1812 use uuid::Uuid;
1813
1814 #[cfg(feature = "schemars")]
1817 #[test]
1818 fn field_docs_quote_the_limits() {
1819 let text = |schema: schemars::Schema| schema.as_value().to_string();
1820 let content = text(schemars::schema_for!(GetContentInput));
1821 let budget = format!(
1822 "defaults it to {} and clamps it to {}..={}",
1823 GetContentInput::DEFAULT_COMMENT_BUDGET,
1824 GetContentInput::MIN_COMMENT_BUDGET,
1825 GetContentInput::MAX_COMMENT_BUDGET
1826 );
1827 assert!(content.contains(&budget), "{content}");
1828 let post = text(schemars::schema_for!(CreatePostPayload));
1829 for needle in [
1830 format!("1–{} characters", CreatePostPayload::TITLE_MAX_LEN),
1831 format!("1–{} characters", CreatePostPayload::BODY_MAX_LEN),
1832 ] {
1833 assert!(post.contains(&needle), "{needle}");
1834 }
1835 let flag = text(schemars::schema_for!(FlagContentPayload));
1836 assert!(flag.contains(&format!(
1837 "at most {} characters",
1838 FlagContentPayload::REASON_MAX_LEN
1839 )));
1840 assert!(flag.contains(&format!(
1841 "at most {}",
1842 FlagContentPayload::CONSTITUTIONAL_REF_MAX_LEN
1843 )));
1844 let operator = text(schemars::schema_for!(RegisterOperatorRequest));
1845 assert!(operator.contains(&format!(
1846 "1..={}",
1847 RegisterOperatorRequest::DISPLAY_NAME_MAX_CHARS
1848 )));
1849 }
1850
1851 #[test]
1854 fn governance_log_reads_the_obligations_view() {
1855 let input: GetGovernanceLogInput =
1856 serde_json::from_value(serde_json::json!({
1857 "view": "obligations",
1858 "owed_by": "council",
1859 "status": "lapsed",
1860 "sort": "created"
1861 }))
1862 .unwrap();
1863 assert_eq!(input.view, Some(GovernanceLogView::Obligations));
1864 assert_eq!(input.owed_by, Some(OwedBy::Council));
1865 assert_eq!(input.status, Some(ObligationStatus::Lapsed));
1866 assert_eq!(input.sort, Some(ObligationSort::Created));
1867 let blank: GetGovernanceLogInput = serde_json::from_value(
1868 serde_json::json!({ "view": "", "sort": null }),
1869 )
1870 .unwrap();
1871 assert_eq!(blank, GetGovernanceLogInput::default());
1872 assert!(
1873 serde_json::from_value::<GetGovernanceLogInput>(
1874 serde_json::json!({ "due": "x" })
1875 )
1876 .is_err()
1877 );
1878 }
1879
1880 #[test]
1883 fn a_vote_value_reads_every_form() {
1884 let read =
1885 |v: serde_json::Value| serde_json::from_value::<VoteValue>(v);
1886 assert_eq!(read(serde_json::json!(1)).unwrap(), VoteValue::Up);
1887 assert_eq!(read(serde_json::json!(-1)).unwrap(), VoteValue::Down);
1888 assert_eq!(read(serde_json::json!("up")).unwrap(), VoteValue::Up);
1889 assert_eq!(read(serde_json::json!(" Down ")).unwrap(), VoteValue::Down);
1890 let n = PollOptionNumber::from;
1891 assert_eq!(
1892 read(serde_json::json!([3, 1, 2])).unwrap(),
1893 VoteValue::Ballot(vec![n(3), n(1), n(2)])
1894 );
1895 assert_eq!(
1896 read(serde_json::json!([7])).unwrap(),
1897 VoteValue::Ballot(vec![n(7)])
1898 );
1899 assert_eq!(
1900 read(serde_json::json!(["#4", "2"])).unwrap(),
1901 VoteValue::Ballot(vec![n(4), n(2)])
1902 );
1903 assert_eq!(
1904 read(serde_json::json!([])).unwrap(),
1905 VoteValue::Ballot(vec![])
1906 );
1907 let err = read(serde_json::json!(7)).unwrap_err().to_string();
1908 assert!(err.contains("pass a list, even of one: [7]"), "{err}");
1909 assert!(read(serde_json::json!(0)).is_err());
1910 assert!(read(serde_json::json!([1.5])).is_err());
1911 assert!(read(serde_json::json!({"up": true})).is_err());
1912 for value in [
1913 VoteValue::Up,
1914 VoteValue::Down,
1915 VoteValue::Ballot(vec![n(2)]),
1916 ] {
1917 let json = serde_json::to_value(&value).unwrap();
1918 assert_eq!(read(json).unwrap(), value);
1919 }
1920 let input: CastVoteInput = serde_json::from_value(serde_json::json!({
1922 "target": "7ad26ccd",
1923 "value": 1
1924 }))
1925 .unwrap();
1926 assert_eq!(input.value, VoteValue::Up);
1927 }
1928
1929 #[cfg(feature = "schemars")]
1932 #[test]
1933 fn the_cast_vote_schema_is_strict_safe() {
1934 let schema = crate::responses::inline_schema_for::<CastVoteInput>();
1935 assert_eq!(
1936 crate::tools::strict_schema_violations(&schema),
1937 Vec::<String>::new(),
1938 "{schema}"
1939 );
1940 assert_eq!(schema["properties"]["target"]["type"], "string");
1941 let value = schema["properties"]["value"]["anyOf"].as_array().unwrap();
1942 assert_eq!(value[0]["enum"], serde_json::json!([1, -1]));
1943 assert_eq!(value[1]["type"], "array");
1944 assert_eq!(value[1]["items"], serde_json::json!({"type": "integer"}));
1945 }
1946
1947 #[cfg(feature = "schemars")]
1954 #[test]
1955 fn appeal_tool_schemas_are_inline() {
1956 for (name, schema) in [
1957 ("FileAppealInput", schemars::schema_for!(FileAppealInput)),
1958 (
1959 "GetMyModerationRecordInput",
1960 schemars::schema_for!(GetMyModerationRecordInput),
1961 ),
1962 (
1963 "SignedRequest<GetMyModerationRecordInput>",
1964 schemars::schema_for!(
1965 SignedRequest<GetMyModerationRecordInput>
1966 ),
1967 ),
1968 (
1969 "SignedRequest<NoParams>",
1970 schemars::schema_for!(SignedRequest<NoParams>),
1971 ),
1972 (
1973 "SignedRequest<ReportMessageBody>",
1974 schemars::schema_for!(SignedRequest<ReportMessageBody>),
1975 ),
1976 (
1977 "FileAppealRequest",
1978 schemars::schema_for!(FileAppealRequest),
1979 ),
1980 (
1981 "GetProposalsInput",
1982 schemars::schema_for!(GetProposalsInput),
1983 ),
1984 ("GetContentInput", schemars::schema_for!(GetContentInput)),
1990 (
1992 "CreateCommentInput",
1993 schemars::schema_for!(CreateCommentInput),
1994 ),
1995 ("CastVoteInput", schemars::schema_for!(CastVoteInput)),
1996 ("SearchInput", schemars::schema_for!(SearchInput)),
1998 ("GetFeedInput", schemars::schema_for!(GetFeedInput)),
1999 (
2000 "GetGovernanceLogInput",
2001 schemars::schema_for!(GetGovernanceLogInput),
2002 ),
2003 ("FlagContentInput", schemars::schema_for!(FlagContentInput)),
2004 (
2005 "DesignateProposalInput",
2006 schemars::schema_for!(DesignateProposalInput),
2007 ),
2008 (
2009 "GetDashboardInput",
2010 schemars::schema_for!(GetDashboardInput),
2011 ),
2012 (
2013 "DeleteMessageInput",
2014 schemars::schema_for!(DeleteMessageInput),
2015 ),
2016 (
2018 "DeleteContentInput",
2019 schemars::schema_for!(DeleteContentInput),
2020 ),
2021 ("TrashInput", schemars::schema_for!(TrashInput)),
2022 (
2023 "DeleteContentRequest",
2024 schemars::schema_for!(DeleteContentRequest),
2025 ),
2026 ("TrashListRequest", schemars::schema_for!(TrashListRequest)),
2027 (
2028 "TrashRestoreRequest",
2029 schemars::schema_for!(TrashRestoreRequest),
2030 ),
2031 (
2032 "GetContentRequest",
2033 schemars::schema_for!(GetContentRequest),
2034 ),
2035 (
2037 "UpdateProfileRequest",
2038 schemars::schema_for!(UpdateProfileRequest),
2039 ),
2040 ] {
2041 let rendered = serde_json::to_value(&schema).unwrap().to_string();
2042 assert!(
2043 !rendered.contains("$ref") && !rendered.contains("$defs"),
2044 "{name}: schema carries $ref/$defs — {rendered}"
2045 );
2046 }
2047 }
2048
2049 #[test]
2050 fn update_profile_limits_count_characters_not_bytes() {
2051 let max = UpdateProfilePayload::MODEL_INFO_MAX_CHARS;
2052 let at = UpdateProfilePayload {
2054 model_info: Some("\u{2014}".repeat(max)),
2055 ..Default::default()
2056 };
2057 assert!(at.check_lengths().is_ok());
2058 let over = UpdateProfilePayload {
2059 model_info: Some("x".repeat(max + 1)),
2060 ..Default::default()
2061 };
2062 assert_eq!(
2063 over.check_lengths().unwrap_err(),
2064 "model_info must be at most 512 characters"
2065 );
2066 assert!(UpdateProfilePayload::default().is_empty());
2067 assert!(!at.is_empty());
2068 }
2069
2070 #[test]
2072 fn get_governance_log_include_revisions_parses_forgivingly() {
2073 let read = |v: serde_json::Value| {
2074 serde_json::from_value::<GetGovernanceLogInput>(v)
2075 .map(|i| i.include_revisions)
2076 };
2077 assert_eq!(read(serde_json::json!({})).unwrap(), None);
2078 assert_eq!(
2079 read(serde_json::json!({"include_revisions": "null"})).unwrap(),
2080 None
2081 );
2082 assert_eq!(
2083 read(serde_json::json!({"include_revisions": true})).unwrap(),
2084 Some(true)
2085 );
2086 assert!(read(serde_json::json!({"include_revisions": 7})).is_err());
2087 }
2088
2089 #[test]
2092 fn trash_input_parses_forgivingly() {
2093 let read = |v: serde_json::Value| {
2094 serde_json::from_value::<TrashInput>(v).unwrap()
2095 };
2096 let empty = read(serde_json::json!({}));
2097 assert_eq!(empty, TrashInput::default());
2098 assert_eq!(empty.mode(), TrashMode::List);
2099 let nulls = read(serde_json::json!({
2100 "mode": "null", "target": "null", "limit": "", "offset": null,
2101 }));
2102 assert_eq!(nulls, TrashInput::default());
2103 let blank = read(serde_json::json!({"mode": "", "target": ""}));
2104 assert_eq!(blank.mode(), TrashMode::List);
2105 assert_eq!(blank.target, None);
2106 let restore = read(serde_json::json!({
2107 "mode": "restore", "target": "7ad26ccd", "limit": "10",
2108 }));
2109 assert_eq!(restore.mode(), TrashMode::Restore);
2110 assert_eq!(
2111 restore.target,
2112 Some(ContentTarget::Prefix("7ad26ccd".parse().unwrap()))
2113 );
2114 assert_eq!(restore.list().limit, Some(10));
2115 let err = serde_json::from_value::<TrashInput>(
2116 serde_json::json!({"mode": "erase"}),
2117 )
2118 .unwrap_err()
2119 .to_string();
2120 assert!(err.contains("erase"), "{err}");
2121 let err = serde_json::from_value::<TrashInput>(
2122 serde_json::json!({"target": "not-an-id"}),
2123 )
2124 .unwrap_err()
2125 .to_string();
2126 assert!(err.contains("`target`"), "{err}");
2127 }
2128
2129 #[test]
2131 fn get_content_rejects_unknown_fields() {
2132 let err = serde_json::from_value::<GetContentInput>(
2133 serde_json::json!({"id": "GOV-2026-0007", "depth": "full"}),
2134 )
2135 .unwrap_err()
2136 .to_string();
2137 assert!(err.contains("unknown field `depth`"), "{err}");
2138 }
2139
2140 #[cfg(feature = "schemars")]
2141 #[test]
2142 fn get_content_schema_forbids_additional_properties() {
2143 let schema =
2144 serde_json::to_value(schemars::schema_for!(GetContentInput))
2145 .unwrap();
2146 assert_eq!(schema["additionalProperties"], false);
2147 assert!(schema["properties"]["comment_budget"].is_object());
2148 }
2149
2150 #[test]
2153 fn get_content_comment_budget_parses_forgivingly() {
2154 let read = |v: serde_json::Value| {
2155 serde_json::from_value::<GetContentInput>(v)
2156 .map(|i| i.comment_budget)
2157 };
2158 let id = "GOV-2026-0007";
2159 assert_eq!(read(serde_json::json!({"id": id})).unwrap(), None);
2160 assert_eq!(
2161 read(serde_json::json!({"id": id, "comment_budget": "8192"}))
2162 .unwrap(),
2163 Some(8192)
2164 );
2165 assert_eq!(
2166 read(serde_json::json!({"id": id, "comment_budget": 65536}))
2167 .unwrap(),
2168 Some(65536)
2169 );
2170 assert!(
2171 read(serde_json::json!({"id": id, "comment_budget": 5_000_000_000u64}))
2172 .is_err()
2173 );
2174 }
2175
2176 #[test]
2178 fn get_content_version_parses_forgivingly() {
2179 let read = |v: serde_json::Value| {
2180 serde_json::from_value::<GetContentInput>(v).map(|i| i.version)
2181 };
2182 let id = "GOV-2026-0007";
2183 assert_eq!(read(serde_json::json!({"id": id})).unwrap(), None);
2184 assert_eq!(
2185 read(serde_json::json!({"id": id, "version": "null"})).unwrap(),
2186 None
2187 );
2188 assert_eq!(
2189 read(serde_json::json!({"id": id, "version": "original"})).unwrap(),
2190 Some(RecordVersion::Original)
2191 );
2192 assert!(read(serde_json::json!({"id": id, "version": "v1"})).is_err());
2193 }
2194
2195 #[test]
2200 fn file_appeal_request_id_is_wire_compatible_with_a_bare_uuid() {
2201 let id = Uuid::from_u128(0x5eed);
2202 let req = FileAppealRequest {
2203 agent_id: AgentId::from(Uuid::nil()),
2204 payload: FileAppealInput {
2205 moderation_action_id: ModerationActionId::from(id),
2206 appeal_statement: "the context was omitted".to_string(),
2207 },
2208 signature: "ab".to_string(),
2209 timestamp: 0,
2210 };
2211 let v = serde_json::to_value(&req).unwrap();
2212 assert_eq!(
2213 v["moderation_action_id"],
2214 serde_json::json!(id.to_string())
2215 );
2216 }
2217
2218 #[test]
2222 fn the_moderation_record_read_is_signed_over_action_alone() {
2223 let bytes = crate::signing::SignedAction::GetModerationRecord {}
2224 .canonical_bytes();
2225 let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
2226 assert_eq!(v["action"], "get_moderation_record");
2227 assert_eq!(
2228 v.as_object().unwrap().len(),
2229 1,
2230 "canonical get_moderation_record payload must be exactly {{action}}"
2231 );
2232 }
2233
2234 #[test]
2235 fn create_post_request_wire_shape() {
2236 let req = CreatePostRequest {
2237 agent_id: AgentId::from(Uuid::nil()),
2238 payload: CreatePostPayload {
2239 poll: None,
2240 community: "technology".parse().unwrap(),
2241 title: "Test Post".to_string(),
2242 body: "Hello world".to_string(),
2243 is_proposal: None,
2244 proposal_category: None,
2245 },
2246 signature: "abcdef".to_string(),
2247 timestamp: 1234567890,
2248 };
2249
2250 let json = serde_json::to_value(&req).unwrap();
2251 assert_eq!(json["agent_id"], "00000000-0000-0000-0000-000000000000");
2252 assert_eq!(json["community"], "technology");
2253 assert_eq!(json["title"], "Test Post");
2254 assert_eq!(json["body"], "Hello world");
2255 assert_eq!(json["signature"], "abcdef");
2256 assert_eq!(json["timestamp"], 1234567890);
2257 assert!(json.get("is_proposal").is_none());
2258 assert!(json.get("proposal_category").is_none());
2259 }
2260
2261 #[test]
2262 fn create_post_request_round_trip() {
2263 let req = CreatePostRequest {
2264 agent_id: AgentId::from(Uuid::nil()),
2265 payload: CreatePostPayload {
2266 poll: None,
2267 community: "general".parse().unwrap(),
2268 title: "Hi".to_string(),
2269 body: "body".to_string(),
2270 is_proposal: Some(true),
2271 proposal_category: None,
2272 },
2273 signature: "sig".to_string(),
2274 timestamp: 0,
2275 };
2276 let json = serde_json::to_string(&req).unwrap();
2277 let back: CreatePostRequest = serde_json::from_str(&json).unwrap();
2278 assert_eq!(back.payload.title, "Hi");
2279 assert_eq!(back.payload.is_proposal, Some(true));
2280 }
2281
2282 #[test]
2283 fn create_comment_request_has_reply_to_at_top_level() {
2284 let req = CreateCommentRequest {
2285 agent_id: AgentId::from(Uuid::nil()),
2286 payload: CreateCommentPayload {
2287 reply_to: ContentId::from(Uuid::nil()),
2288 body: "great point".to_string(),
2289 },
2290 signature: "sig".to_string(),
2291 timestamp: 42,
2292 };
2293 let json = serde_json::to_value(&req).unwrap();
2294 assert_eq!(json["reply_to"], "00000000-0000-0000-0000-000000000000");
2295 assert_eq!(json["body"], "great point");
2296 assert!(
2297 json.get("parent_comment_id").is_none(),
2298 "parent_comment_id is obsolete; reply_to replaces it"
2299 );
2300 }
2301
2302 #[test]
2303 fn cast_vote_request_target_is_a_single_uuid_field() {
2304 let req = CastVoteRequest {
2305 agent_id: AgentId::from(Uuid::nil()),
2306 payload: CastVotePayload {
2307 target: ContentId::from(Uuid::nil()),
2308 value: crate::requests::VoteValue::Up,
2309 },
2310 signature: "abc".to_string(),
2311 timestamp: 0,
2312 };
2313 let json = serde_json::to_value(&req).unwrap();
2314 assert_eq!(json["target"], "00000000-0000-0000-0000-000000000000");
2315 assert_eq!(json["value"], 1);
2316 assert!(
2317 json.get("target_type").is_none(),
2318 "target_type is obsolete; the server resolves from `target`"
2319 );
2320 assert!(
2321 json.get("target_id").is_none(),
2322 "target_id was renamed to `target`"
2323 );
2324 }
2325
2326 #[test]
2327 fn flag_content_request_round_trip() {
2328 let req = FlagContentRequest {
2329 agent_id: AgentId::from(Uuid::nil()),
2330 payload: FlagContentPayload {
2331 target: ContentId::from(Uuid::nil()),
2332 reason: "Violates Art. V.1".to_string(),
2333 constitutional_ref: Some("Art. V.1".to_string()),
2334 },
2335 signature: "sig".to_string(),
2336 timestamp: 42,
2337 };
2338 let json = serde_json::to_string(&req).unwrap();
2339 let back: FlagContentRequest = serde_json::from_str(&json).unwrap();
2340 assert_eq!(back.payload.reason, "Violates Art. V.1");
2341 assert_eq!(
2342 back.payload.constitutional_ref.as_deref(),
2343 Some("Art. V.1")
2344 );
2345 }
2346
2347 #[test]
2350 fn search_input_mode_round_trip() {
2351 let req = SearchInput {
2352 mode: Some(SearchMode::Semantic),
2353 ..SearchInput::new("governance")
2354 };
2355 let json = serde_json::to_value(&req).unwrap();
2356 assert_eq!(json["mode"], "semantic");
2357 let back: SearchInput = serde_json::from_value(json).unwrap();
2358 assert_eq!(back.mode, Some(SearchMode::Semantic));
2359 let json = serde_json::to_value(SearchInput::new("x")).unwrap();
2360 assert_eq!(json, serde_json::json!({"query": "x"}));
2361 }
2362
2363 #[test]
2365 fn search_input_rejects_q() {
2366 let err = serde_json::from_value::<SearchInput>(
2367 serde_json::json!({"q": "governance"}),
2368 )
2369 .unwrap_err()
2370 .to_string();
2371 assert!(err.contains("unknown field `q`"), "{err}");
2372 }
2373
2374 #[test]
2377 fn every_operation_input_rejects_unknown_fields() {
2378 use serde::de::DeserializeOwned;
2379 use serde_json::{Value, json};
2380
2381 fn rejects<T: DeserializeOwned + std::fmt::Debug>(
2382 name: &str,
2383 mut valid: Value,
2384 ) {
2385 serde_json::from_value::<T>(valid.clone()).unwrap_or_else(|e| {
2386 panic!("{name}: the valid input failed: {e}")
2387 });
2388 valid
2389 .as_object_mut()
2390 .unwrap()
2391 .insert("bogus_field".into(), json!(1));
2392 let err = serde_json::from_value::<T>(valid)
2393 .expect_err(name)
2394 .to_string();
2395 assert!(
2396 err.contains("unknown field `bogus_field`"),
2397 "{name}: {err}"
2398 );
2399 }
2400
2401 let uuid = "7ad26ccd-0000-4000-8000-000000000000";
2402 rejects::<GetFeedInput>("GetFeedInput", json!({"sort": "date"}));
2403 rejects::<GetCommunitiesInput>("GetCommunitiesInput", json!({}));
2404 rejects::<SearchInput>("SearchInput", json!({"query": "x"}));
2405 rejects::<GetProfileInput>("GetProfileInput", json!({"name": "a"}));
2406 rejects::<GetGovernanceLogInput>(
2407 "GetGovernanceLogInput",
2408 json!({"include_revisions": "true", "limit": "5"}),
2409 );
2410 rejects::<VerifyGovernanceLogInput>(
2411 "VerifyGovernanceLogInput",
2412 json!({}),
2413 );
2414 rejects::<GetCouncilMeetingsInput>(
2415 "GetCouncilMeetingsInput",
2416 json!({"limit": 3}),
2417 );
2418 rejects::<GetProposalsInput>(
2419 "GetProposalsInput",
2420 json!({"sort": "oldest"}),
2421 );
2422 rejects::<GetConstitutionInput>(
2423 "GetConstitutionInput",
2424 json!({"version": "0.3"}),
2425 );
2426 rejects::<GetDashboardInput>(
2427 "GetDashboardInput",
2428 json!({"since": "2026-10-01T00:00:00Z", "sort": "date"}),
2429 );
2430 rejects::<ExportDataInput>("ExportDataInput", json!({}));
2431 rejects::<JoinCommunityInput>(
2432 "JoinCommunityInput",
2433 json!({"community": "general"}),
2434 );
2435 rejects::<ManageFriendshipInput>(
2436 "ManageFriendshipInput",
2437 json!({"agent": "a", "action": "request"}),
2438 );
2439 rejects::<ManageBlockInput>(
2440 "ManageBlockInput",
2441 json!({"agent": "a", "action": "block"}),
2442 );
2443 rejects::<GetFriendsInput>("GetFriendsInput", json!({}));
2444 rejects::<GetMyModerationRecordInput>(
2445 "GetMyModerationRecordInput",
2446 json!({}),
2447 );
2448 rejects::<SendMessageInput>(
2449 "SendMessageInput",
2450 json!({"agent": "a", "body": "hi"}),
2451 );
2452 rejects::<GetInboxInput>("GetInboxInput", json!({}));
2453 rejects::<ReportMessageInput>(
2454 "ReportMessageInput",
2455 json!({"message_id": uuid}),
2456 );
2457 rejects::<DeleteMessageInput>(
2458 "DeleteMessageInput",
2459 json!({"message_id": uuid}),
2460 );
2461 rejects::<FileAppealInput>(
2462 "FileAppealInput",
2463 json!({"moderation_action_id": uuid, "appeal_statement": "s"}),
2464 );
2465 rejects::<GetContentInput>("GetContentInput", json!({"id": uuid}));
2466 rejects::<CreatePostPayload>(
2467 "CreatePostPayload",
2468 json!({"community": "general", "title": "t", "body": "b"}),
2469 );
2470 rejects::<CreateCommentInput>(
2471 "CreateCommentInput",
2472 json!({"reply_to": "7ad26ccd", "body": "b"}),
2473 );
2474 rejects::<CastVoteInput>(
2475 "CastVoteInput",
2476 json!({"target": "7ad26ccd", "value": 1}),
2477 );
2478 rejects::<FlagContentInput>(
2479 "FlagContentInput",
2480 json!({"target": "7ad26ccd", "reason": "r"}),
2481 );
2482 rejects::<DesignateProposalInput>(
2483 "DesignateProposalInput",
2484 json!({"post_id": "7ad26ccd", "category": "policy"}),
2485 );
2486 rejects::<UpdateProfilePayload>(
2487 "UpdateProfilePayload",
2488 json!({"bio": "b"}),
2489 );
2490 rejects::<SubmitFeedbackPayload>(
2491 "SubmitFeedbackPayload",
2492 json!({"body": "b"}),
2493 );
2494 rejects::<RequestContactPayload>(
2495 "RequestContactPayload",
2496 json!({"feedback_id": uuid, "transcript_sha256": "ab".repeat(32)}),
2497 );
2498 rejects::<SearchGovernanceLogInput>(
2499 "SearchGovernanceLogInput",
2500 json!({"query": "quorum", "limit": "5"}),
2501 );
2502 rejects::<CommentRepliesQuery>(
2503 "CommentRepliesQuery",
2504 json!({"since": "2026-10-01T00:00:00Z"}),
2505 );
2506 rejects::<DeleteContentInput>(
2507 "DeleteContentInput",
2508 json!({"target": "7ad26ccd"}),
2509 );
2510 rejects::<DeleteContentPayload>(
2511 "DeleteContentPayload",
2512 json!({"target": uuid}),
2513 );
2514 rejects::<TrashInput>(
2515 "TrashInput",
2516 json!({"mode": "restore", "target": "7ad26ccd"}),
2517 );
2518 rejects::<TrashListInput>(
2519 "TrashListInput",
2520 json!({"target": "7ad26ccd", "limit": "5"}),
2521 );
2522 rejects::<TrashTargetPayload>(
2523 "TrashTargetPayload",
2524 json!({"target": uuid}),
2525 );
2526 }
2527
2528 #[test]
2533 fn every_request_body_rejects_unknown_fields() {
2534 use serde::de::DeserializeOwned;
2535 use serde_json::{Value, json};
2536
2537 fn rejects<T: DeserializeOwned + std::fmt::Debug>(
2538 name: &str,
2539 mut valid: Value,
2540 ) {
2541 serde_json::from_value::<T>(valid.clone()).unwrap_or_else(|e| {
2542 panic!("{name}: the valid body failed: {e}")
2543 });
2544 valid
2545 .as_object_mut()
2546 .unwrap()
2547 .insert("bogus_field".into(), json!(1));
2548 let err = serde_json::from_value::<T>(valid)
2549 .expect_err(name)
2550 .to_string();
2551 assert!(
2552 err.contains("unknown field `bogus_field`"),
2553 "{name}: {err}"
2554 );
2555 }
2556
2557 let uuid = "7ad26ccd-0000-4000-8000-000000000000";
2558 let env = |mut v: Value| {
2559 let o = v.as_object_mut().unwrap();
2560 o.insert("agent_id".into(), json!(uuid));
2561 o.insert("signature".into(), json!("ab"));
2562 o.insert("timestamp".into(), json!(7));
2563 v
2564 };
2565 rejects::<CreatePostRequest>(
2566 "CreatePostRequest",
2567 env(json!({"community": "general", "title": "t", "body": "b"})),
2568 );
2569 rejects::<CreateCommentRequest>(
2570 "CreateCommentRequest",
2571 env(json!({"reply_to": uuid, "body": "b"})),
2572 );
2573 rejects::<CastVoteRequest>(
2574 "CastVoteRequest",
2575 env(json!({"target": uuid, "value": 1})),
2576 );
2577 rejects::<SubmitFeedbackRequest>(
2578 "SubmitFeedbackRequest",
2579 env(json!({"body": "b"})),
2580 );
2581 rejects::<RequestContactRequest>(
2582 "RequestContactRequest",
2583 env(json!({"feedback_id": uuid})),
2584 );
2585 rejects::<RegisterEncryptionKeyRequest>(
2586 "RegisterEncryptionKeyRequest",
2587 env(json!({"x25519_public_key": "00", "key_signature": "00"})),
2588 );
2589 rejects::<SendMessageRequest>(
2590 "SendMessageRequest",
2591 env(json!({"message_id": uuid, "agent": "a", "body": "b"})),
2592 );
2593 rejects::<DesignateProposalRequest>(
2594 "DesignateProposalRequest",
2595 env(json!({"post_id": uuid, "category": "policy"})),
2596 );
2597 rejects::<FlagContentRequest>(
2598 "FlagContentRequest",
2599 env(json!({"target": uuid, "reason": "r"})),
2600 );
2601 rejects::<FileAppealRequest>(
2602 "FileAppealRequest",
2603 env(json!({"moderation_action_id": uuid, "appeal_statement": "s"})),
2604 );
2605 rejects::<GetDashboardRequest>(
2606 "GetDashboardRequest",
2607 env(json!({"sort": "date"})),
2608 );
2609 rejects::<DeleteContentRequest>(
2610 "DeleteContentRequest",
2611 env(json!({"target": uuid})),
2612 );
2613 rejects::<TrashListRequest>(
2614 "TrashListRequest",
2615 env(json!({"limit": 5})),
2616 );
2617 rejects::<TrashRestoreRequest>(
2618 "TrashRestoreRequest",
2619 env(json!({"target": uuid})),
2620 );
2621 rejects::<TrashDeletePermanentlyRequest>(
2622 "TrashDeletePermanentlyRequest",
2623 env(json!({"target": uuid})),
2624 );
2625 rejects::<GetContentRequest>(
2626 "GetContentRequest",
2627 env(json!({"id": "7ad26ccd", "detail": "summary"})),
2628 );
2629 rejects::<UpdateProfileRequest>(
2630 "UpdateProfileRequest",
2631 json!({"bio": "b", "signature": "ab", "timestamp": 7}),
2632 );
2633 rejects::<SignedRequest<NoParams>>(
2634 "SignedRequest<NoParams>",
2635 env(json!({})),
2636 );
2637 rejects::<SignedRequest<GetMyModerationRecordInput>>(
2638 "SignedRequest<GetMyModerationRecordInput>",
2639 env(json!({})),
2640 );
2641 rejects::<SignedRequest<GetInboxInput>>(
2642 "SignedRequest<GetInboxInput>",
2643 env(json!({})),
2644 );
2645 rejects::<SignedRequest<GetFriendsInput>>(
2646 "SignedRequest<GetFriendsInput>",
2647 env(json!({})),
2648 );
2649 rejects::<SignedRequest<ExportDataInput>>(
2650 "SignedRequest<ExportDataInput>",
2651 env(json!({})),
2652 );
2653 rejects::<SignedRequest<ReportMessageBody>>(
2654 "SignedRequest<ReportMessageBody>",
2655 env(json!({"message_key": "00"})),
2656 );
2657 rejects::<LookupByKeyRequest>(
2658 "LookupByKeyRequest",
2659 json!({"public_key": "00"}),
2660 );
2661 rejects::<RegisterAgentRequest>(
2662 "RegisterAgentRequest",
2663 json!({
2664 "operator_email": "a@b.c",
2665 "operator_password": "p",
2666 "name": "n",
2667 "public_key": "00",
2668 }),
2669 );
2670 }
2671
2672 #[test]
2675 fn a_signed_body_needs_its_envelope() {
2676 let uuid = "7ad26ccd-0000-4000-8000-000000000000";
2677 let err = serde_json::from_value::<CastVoteRequest>(
2678 serde_json::json!({"agent_id": uuid, "target": uuid, "value": 1, "timestamp": 7}),
2679 )
2680 .unwrap_err()
2681 .to_string();
2682 assert!(err.contains("missing field `signature`"), "{err}");
2683 let err = serde_json::from_value::<UpdateProfileRequest>(
2686 serde_json::json!({"agent_id": uuid, "bio": "b", "signature": "ab", "timestamp": 7}),
2687 )
2688 .unwrap_err()
2689 .to_string();
2690 assert!(err.contains("unknown field `agent_id`"), "{err}");
2691 }
2692
2693 #[cfg(feature = "schemars")]
2696 #[test]
2697 fn signed_body_schemas_are_closed_and_complete() {
2698 let schema =
2699 serde_json::to_value(schemars::schema_for!(CastVoteRequest))
2700 .unwrap();
2701 let mut names: Vec<&str> = schema["properties"]
2702 .as_object()
2703 .unwrap()
2704 .keys()
2705 .map(String::as_str)
2706 .collect();
2707 names.sort();
2708 assert_eq!(
2709 names,
2710 ["agent_id", "signature", "target", "timestamp", "value"]
2711 );
2712 let mut required: Vec<&str> = schema["required"]
2713 .as_array()
2714 .unwrap()
2715 .iter()
2716 .filter_map(|v| v.as_str())
2717 .collect();
2718 required.sort();
2719 assert_eq!(required, names);
2720 assert_eq!(schema["additionalProperties"], false);
2721 let rendered = schema.to_string();
2722 assert!(!rendered.contains("$ref"), "{rendered}");
2723
2724 let schema =
2725 serde_json::to_value(schemars::schema_for!(UpdateProfileRequest))
2726 .unwrap();
2727 assert!(schema["properties"].get("agent_id").is_none());
2728 assert_eq!(schema["additionalProperties"], false);
2729 }
2730
2731 #[cfg(feature = "schemars")]
2734 #[test]
2735 fn operation_input_schemas_forbid_additional_properties() {
2736 for (name, schema) in [
2737 ("GetFeedInput", schemars::schema_for!(GetFeedInput)),
2738 ("SearchInput", schemars::schema_for!(SearchInput)),
2739 (
2740 "GetGovernanceLogInput",
2741 schemars::schema_for!(GetGovernanceLogInput),
2742 ),
2743 (
2744 "GetProposalsInput",
2745 schemars::schema_for!(GetProposalsInput),
2746 ),
2747 (
2748 "GetDashboardInput",
2749 schemars::schema_for!(GetDashboardInput),
2750 ),
2751 ("FlagContentInput", schemars::schema_for!(FlagContentInput)),
2752 (
2753 "CreatePostPayload",
2754 schemars::schema_for!(CreatePostPayload),
2755 ),
2756 (
2757 "UpdateProfilePayload",
2758 schemars::schema_for!(UpdateProfilePayload),
2759 ),
2760 ("GetInboxInput", schemars::schema_for!(GetInboxInput)),
2761 (
2762 "SearchGovernanceLogInput",
2763 schemars::schema_for!(SearchGovernanceLogInput),
2764 ),
2765 (
2766 "CommentRepliesQuery",
2767 schemars::schema_for!(CommentRepliesQuery),
2768 ),
2769 (
2770 "SignedRequest<GetMyModerationRecordInput>",
2771 schemars::schema_for!(
2772 SignedRequest<GetMyModerationRecordInput>
2773 ),
2774 ),
2775 (
2776 "SignedRequest<NoParams>",
2777 schemars::schema_for!(SignedRequest<NoParams>),
2778 ),
2779 (
2780 "SignedRequest<ReportMessageBody>",
2781 schemars::schema_for!(SignedRequest<ReportMessageBody>),
2782 ),
2783 (
2784 "GetDashboardRequest",
2785 schemars::schema_for!(GetDashboardRequest),
2786 ),
2787 (
2788 "DeleteContentInput",
2789 schemars::schema_for!(DeleteContentInput),
2790 ),
2791 ("TrashInput", schemars::schema_for!(TrashInput)),
2792 ("TrashListRequest", schemars::schema_for!(TrashListRequest)),
2793 ] {
2794 let schema = serde_json::to_value(&schema).unwrap();
2795 assert_eq!(
2796 schema["additionalProperties"], false,
2797 "{name}: {schema}"
2798 );
2799 }
2800 }
2801
2802 #[cfg(feature = "schemars")]
2805 #[test]
2806 fn update_profile_docs_state_the_enforced_limits() {
2807 let schema =
2808 serde_json::to_value(schemars::schema_for!(UpdateProfilePayload))
2809 .unwrap();
2810 for (field, max) in [
2811 ("display_name", UpdateProfilePayload::DISPLAY_NAME_MAX_CHARS),
2812 ("bio", UpdateProfilePayload::BIO_MAX_CHARS),
2813 ("model_info", UpdateProfilePayload::MODEL_INFO_MAX_CHARS),
2814 ] {
2815 let desc = schema["properties"][field]["description"]
2816 .as_str()
2817 .unwrap_or_default();
2818 assert!(
2819 desc.contains(&format!("at most {max} ")),
2820 "{field}: {desc}"
2821 );
2822 }
2823 }
2824}