~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

The host holds what it is sent to the limits its lexicons set

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/input-checks
crates/group-host/src/api.rs+18−0
@@ -31,6 +31,24 @@ pub(crate) fn invalid(message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidRequest", message)
}
/// Refuses `text`, the `field` a caller gave, longer than its lexicon
/// lets it be: `bytes` bytes and `graphemes` characters at most. A
/// character is counted as a grapheme, so a text of combined characters
/// may be refused a little short of the lexicon's limit, never past it.
pub(crate) fn at_most(
field: &str,
text: &str,
bytes: usize,
graphemes: usize,
) -> Result<(), XrpcError> {
if text.len() > bytes || text.chars().count() > graphemes {
return Err(invalid(format!(
"{field} is {graphemes} characters and {bytes} bytes at most"
)));
}
Ok(())
}
/// The parameter `name`, which the method needs.
pub(crate) fn param<'a>(params: &'a Params, name: &str) -> Result<&'a str, XrpcError> {
params
crates/group-host/src/blobs.rs+2−2
@@ -146,8 +146,8 @@ fn collect(value: &Value, found: &mut Vec<Cid>) {
}
}
/// The kinds of image a page may be given.
const IMAGES: [&str; 5] = [
/// The kinds of image a page may be given, and a group's profile holds.
pub(crate) const IMAGES: [&str; 5] = [
"image/png",
"image/jpeg",
"image/webp",
crates/group-host/src/config.rs+12−3
@@ -81,19 +81,28 @@ impl Config {
var(name)
.unwrap_or_default()
.split(',')
.map(|c| c.trim().trim_end_matches('/').to_string())
.map(|c| c.trim().to_string())
.filter(|c| !c.is_empty())
.collect()
};
// A service's URL is one with or without its trailing slash; any
// other item is as written, as a client id ending in one is.
let urls = |name: &str| -> Vec<String> {
list(name)
.into_iter()
.map(|u| u.trim_end_matches('/').to_string())
.filter(|u| !u.is_empty())
.collect()
};
let group_founders = list("GROUP_FOUNDERS");
let mut handle_resolvers = list("HANDLE_RESOLVERS");
let mut handle_resolvers = urls("HANDLE_RESOLVERS");
if handle_resolvers.is_empty() {
handle_resolvers = vec![
"well-known:https".into(),
"https://public.api.bsky.app".into(),
];
}
let crawlers = list("PDS_CRAWLERS");
let crawlers = urls("PDS_CRAWLERS");
let blob_upload_limit = match var("BLOB_UPLOAD_LIMIT") {
Some(l) => l
.parse()
crates/group-host/src/group.rs+5−0
@@ -6,6 +6,7 @@
//! access record, against the reader's roles.
use crate::Host;
use crate::api::at_most;
use crate::rbac::{ACTIONS, Grant, NS, listed};
use crate::repo::{Write, invalid};
use crate::store::Record;
@@ -107,6 +108,10 @@ struct Shape {
/// What `new` asks of a group's first day, checked.
fn shape(new: &NewGroup) -> Result<Shape, XrpcError> {
let join = join_policy(new.join_policy.as_deref())?;
at_most("displayName", &new.display_name, 640, 64)?;
if let Some(d) = &new.description {
at_most("description", d, 3000, 300)?;
}
let readers = new
.meta_readable_by
.clone()
crates/group-host/src/group_config.rs+48−19
@@ -3,13 +3,15 @@
//! for a caller holding `group.configure`.
use crate::Host;
use crate::api::{Params, invalid, param};
use crate::api::{Params, at_most, invalid, param};
use crate::blobs::IMAGES;
use crate::group::{join_policy, members_space, meta_space};
use crate::group_api::{group_of, signed_in};
use crate::rbac::{NS, actions_for, grants, listed};
use crate::repo::Write;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use atproto::Cid;
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Query, State};
@@ -132,12 +134,13 @@ pub(crate) async fn put_in(
Ok(Json(json!({"uri": uri, "cid": kept.cid.to_string()})))
}
/// Words a profile lists, as `[{topic}]`: trimmed, each once, at most
/// `max`.
fn words(asked: &Value, field: &str, max: usize) -> Vec<String> {
/// Words a profile lists, as `[{topic}]`: trimmed, cut to `longest`
/// characters, each once, at most `max`.
fn words(asked: &Value, field: &str, longest: usize, max: usize) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for item in asked.as_array().into_iter().flatten() {
let word = item[field].as_str().unwrap_or_default().trim().to_string();
let word = item[field].as_str().unwrap_or_default().trim();
let word: String = word.chars().take(longest).collect();
if !word.is_empty() && !out.contains(&word) {
out.push(word);
}
@@ -164,6 +167,22 @@ fn blob(asked: &Value) -> Option<Value> {
Some(json!({"$type": "blob", "ref": {"$link": link}, "mimeType": mime, "size": size}))
}
/// The image `asked` names, as the group's profile holds it: one of its
/// own uploads, of a kind of image a page is given, its type and size as
/// the host kept them rather than as the caller says.
fn image(host: &Host, group: &str, key: &str, asked: &Value) -> Result<Value, XrpcError> {
let not_one = invalid(format!("{key} is an image uploadImage answered"));
let link = asked["ref"]["$link"].as_str().unwrap_or_default();
let Ok(cid) = Cid::parse(link) else {
return Err(not_one);
};
let kept = host.store.blob(group, &cid).map_err(XrpcError::internal)?;
let kept = kept.filter(|b| IMAGES.contains(&b.mime_type.as_str()));
let kept = kept.ok_or(not_one)?;
let (mime, size) = (kept.mime_type, kept.size);
Ok(json!({"$type": "blob", "ref": {"$link": link}, "mimeType": mime, "size": size}))
}
/// Replaces the group's profile. What finds it (where it meets, online,
/// topics, languages) is as given, none when left out; an image left out
/// is kept, and `null` clears it; its first `createdAt` is kept.
@@ -180,6 +199,7 @@ pub async fn update_profile(
if name.is_empty() {
return Err(invalid("displayName is required"));
}
at_most("displayName", name, 640, 64)?;
let meta = meta_space(&group);
let collection = format!("{NS}.profile");
let current = host
@@ -201,6 +221,7 @@ pub async fn update_profile(
});
let text = |k: &str| body[k].as_str().map(str::trim).filter(|t| !t.is_empty());
if let Some(d) = text("description") {
at_most("description", d, 3000, 300)?;
profile["description"] = json!(d);
}
// The site is replaced, as the description is: left out, it goes.
@@ -217,14 +238,14 @@ pub async fn update_profile(
if body["online"].as_bool() == Some(true) {
profile["online"] = json!(true);
}
let topics: Vec<Value> = words(&body["topics"], "topic", 10)
let topics: Vec<Value> = words(&body["topics"], "topic", 64, 10)
.into_iter()
.map(|t| json!({"topic": t.chars().take(64).collect::<String>()}))
.map(|t| json!({ "topic": t }))
.collect();
if !topics.is_empty() {
profile["topics"] = json!(topics);
}
let languages: Vec<Value> = words(&body["languages"], "language", 5)
let languages: Vec<Value> = words(&body["languages"], "language", usize::MAX, 5)
.into_iter()
.filter(|l| is_language(l))
.map(|l| json!({"language": l}))
@@ -235,7 +256,7 @@ pub async fn update_profile(
for key in ["avatar", "banner"] {
let image = match body.get(key) {
Some(Value::Null) => None,
Some(asked) => Some(blob(asked).ok_or_else(|| invalid(format!("{key} is a blob")))?),
Some(asked) => Some(image(&host, &group, key, asked)?),
None => current.get(key).and_then(blob),
};
if let Some(image) = image {
@@ -265,6 +286,9 @@ pub async fn upload_image(
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
if !IMAGES.contains(&mime) {
return Err(invalid(format!("an image is one of {}", IMAGES.join(", "))));
}
let blob = host.upload_blob(&group, &bytes, mime)?;
Ok(Json(json!({ "blob": blob })))
}
@@ -285,19 +309,24 @@ pub async fn put_rule(
if title.is_empty() {
return Err(invalid("title is required"));
}
let rkey = match body["rkey"]
.as_str()
.map(str::trim)
.filter(|k| !k.is_empty())
{
Some(k) => k.to_string(),
None => host.clock.next(),
};
at_most("title", title, 1000, 100)?;
let text = body["text"].as_str().unwrap_or_default().trim();
at_most("text", text, 20000, 2000)?;
let collection = format!("{NS}.rule");
let rules = host
.group_records(&group, &meta_space(&group), &collection)
.map_err(XrpcError::internal)?;
let current = rules.iter().find(|(k, _)| *k == rkey).map(|(_, r)| r);
// A key names a rule there is; a new one is keyed by the clock, as
// rules are.
let (rkey, current) = match body["rkey"].as_str() {
Some(k) => {
let found = rules.iter().find(|(key, _)| key == k);
let none = invalid(format!("no rule {k}: a new one is given no rkey"));
let found = found.ok_or(none)?;
(k.to_string(), Some(&found.1))
}
None => (host.clock.next(), None),
};
let last = rules.iter().filter_map(|(_, r)| r["order"].as_i64()).max();
let order = body["order"]
.as_i64()
@@ -312,7 +341,7 @@ pub async fn put_rule(
let rule = json!({
"$type": collection,
"title": title,
"text": body["text"].as_str().unwrap_or_default().trim(),
"text": text,
"order": order,
"createdAt": created,
});
crates/group-host/src/group_invites.rs+29−6
@@ -10,7 +10,7 @@
//! the group's join policy, with its default roles.
use crate::Host;
use crate::api::{Params, invalid, page, param};
use crate::api::{Params, at_most, invalid, page, param};
use crate::group::meta_space;
use crate::group_api::{caller, group_of, signed_in};
use crate::group_members::acting;
@@ -65,10 +65,14 @@ fn view(invite: &Invite) -> Value {
view
}
/// An RFC 3339 datetime in UTC (`2026-11-03T00:00:00Z`, fractions of a
/// second allowed), in milliseconds since 1970.
/// An RFC 3339 datetime, as atproto writes one: in UTC
/// (`2026-11-03T00:00:00Z`) or at an offset from it (`+01:00`, though not
/// `-00:00`), fractions of a second allowed. In milliseconds since 1970.
pub fn millis_of(text: &str) -> Option<i64> {
let text = text.strip_suffix('Z')?;
let (text, zone) = match text.strip_suffix('Z') {
Some(utc) => (utc, "+00:00"),
None => text.split_at_checked(text.len().checked_sub(6)?)?,
};
let (date, time) = text.split_once('T')?;
let (hms, frac) = time.split_once('.').unwrap_or((time, ""));
// Digits alone, of the widths RFC 3339 writes them.
@@ -87,6 +91,17 @@ pub fn millis_of(text: &str) -> Option<i64> {
.collect()
})?
};
let (sign, offset) = zone.split_at_checked(1)?;
let o = fields(offset, ':', &[2, 2])?;
let east = match sign {
"+" => 1,
"-" if offset != "00:00" => -1,
_ => return None,
};
if o[0] > 23 || o[1] > 59 {
return None;
}
let east = east * (o[0] * 60 + o[1]) * 60_000;
let d = fields(date, '-', &[4, 2, 2])?;
let t = fields(hms, ':', &[2, 2, 2])?;
let (y, m, day, h, min, s) = (d[0], d[1], d[2], t[0], t[1], t[2]);
@@ -119,7 +134,7 @@ pub fn millis_of(text: &str) -> Option<i64> {
let doy = (153 * m + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
Some(((days * 24 + h) * 60 + min) * 60_000 + s * 1000 + ms)
Some(((days * 24 + h) * 60 + min) * 60_000 + s * 1000 + ms - east)
}
impl Host {
@@ -175,6 +190,14 @@ pub async fn create_invite(
Some(at) => Some(millis_of(at).ok_or_else(|| invalid("expiresAt is a datetime"))?),
None => None,
};
// One that has lapsed already could admit nobody.
if expires_at.is_some_and(|at| at <= now_millis()) {
return Err(invalid("expiresAt is a time to come"));
}
let message = body["message"].as_str();
if let Some(m) = message {
at_most("message", m, 3000, 300)?;
}
let group = members.group.clone();
// One waiting is the one answered; one lapsed is taken back, and a
// fresh one written.
@@ -193,7 +216,7 @@ pub async fn create_invite(
group: group.clone(),
invitee: invitee.into(),
by: me.clone(),
message: body["message"].as_str().map(String::from),
message: message.map(String::from),
rkey: host.clock.next(),
created_at: now_millis(),
expires_at,
crates/group-host/src/group_join.rs+4−4
@@ -9,7 +9,7 @@
//! ask again and the group need not say.
use crate::Host;
use crate::api::{Params, invalid, page, param};
use crate::api::{Params, at_most, invalid, page, param};
use crate::group::meta_space;
use crate::group_api::{group_of, signed_in};
use crate::group_members::{Members, acting};
@@ -82,9 +82,8 @@ pub async fn request_join(
Some("invite") => Err(bad("InviteRequired", "this group joins by invite")),
_ => {
let message = body["message"].as_str();
// As the lexicon has it: 300 graphemes, 3000 bytes, at most.
if message.is_some_and(|m| m.len() > 3000 || m.chars().count() > 300) {
return Err(invalid("a message is 300 characters at most"));
if let Some(m) = message {
at_most("message", m, 3000, 300)?;
}
host.store
.ask(group, &me, message, now_millis())
@@ -173,6 +172,7 @@ pub async fn admit_member(
if roles.is_empty() {
return Err(invalid("roles names the roles to give"));
}
members.defined(&roles)?;
// The roles an admitter may give are those their `admit` grants may.
let assignable = members.assignable(&mine, "admit");
let blocked: Vec<&String> = roles.iter().filter(|r| !assignable.contains(*r)).collect();
crates/group-host/src/group_members.rs+37−23
@@ -11,7 +11,7 @@
//! wrote there.
use crate::Host;
use crate::api::invalid;
use crate::api::{at_most, invalid};
use crate::group::{did_rkey, members_space};
use crate::group_api::{group_of, signed_in};
use crate::group_config::put_in;
@@ -137,6 +137,16 @@ impl<'a> Members<'a> {
Ok(())
}
/// Refuses `roles` unless the group defines each.
pub(crate) fn defined(&self, roles: &[String]) -> Result<(), XrpcError> {
let defined: BTreeSet<String> = self.records("role")?.into_iter().map(|(k, _)| k).collect();
let undefined: Vec<&String> = roles.iter().filter(|r| !defined.contains(*r)).collect();
if !undefined.is_empty() {
return Err(invalid(format!("no such roles: {undefined:?}")));
}
Ok(())
}
/// Whether any member holds one of `roles`.
fn held(&self, roles: &BTreeSet<String>) -> Result<bool, XrpcError> {
let memberships = self.records("membership")?;
@@ -224,6 +234,11 @@ pub async fn put_role(
let name = body["name"]
.as_str()
.ok_or_else(|| invalid("name is required"))?;
at_most("name", name, 640, 64)?;
let description = body["description"].as_str();
if let Some(d) = description {
at_most("description", d, 3000, 300)?;
}
let actions: Vec<String> = body["actions"]
.as_array()
.ok_or_else(|| invalid("actions is required"))?
@@ -252,30 +267,37 @@ pub async fn put_role(
"nobody else holds a role that configures the group: give one to someone first",
));
}
// The roles it may give, as asked, or as they were: each one the group
// defines, or this one.
let previous = members.grants.iter().find(|g| g.role == role);
let assignable = match body.get("assignable") {
Some(_) => listed(&body, "assignable", "role"),
None => previous.map(|g| g.assignable.clone()).unwrap_or_default(),
};
let others: Vec<String> = assignable.iter().filter(|r| *r != role).cloned().collect();
members.defined(&others)?;
let collection = format!("{NS}.role");
let was = members
.records("role")?
.into_iter()
.find(|(k, _)| k == role)
.map(|(_, r)| r);
.map(|(_, r)| r)
.unwrap_or_default();
let mut record =
json!({"$type": collection, "displayName": name, "createdAt": iso(now_millis())});
if let Some(d) = body["description"].as_str() {
if let Some(d) = description {
record["description"] = json!(d);
}
// Left out, whether it is given on joining stays as it was.
let given = body["default"]
.as_bool()
.or_else(|| was.as_ref().and_then(|w| w["default"].as_bool()));
if given == Some(true) {
record["default"] = json!(true);
}
if body["bot"].as_bool() == Some(true) {
record["bot"] = json!(true);
// Left out, whether it is given on joining, and whether its people
// are bots, stay as they were.
for flag in ["default", "bot"] {
let kept = body[flag].as_bool().or(was[flag].as_bool());
if kept == Some(true) {
record[flag] = json!(true);
}
}
// Its grant: the actions as their scopes, beside any other scope it
// held; its public-repo collections as asked, or as they were.
let previous = members.grants.iter().find(|g| g.role == role);
let kept = previous.map(|g| g.scopes.clone()).unwrap_or_default();
let asked_collections = body
.get("repoCollections")
@@ -295,7 +317,7 @@ pub async fn put_role(
let grant = Grant {
role: role.into(),
scopes,
assignable: listed(&body, "assignable", "role"),
assignable,
};
let mut granted: Vec<Grant> = members
.grants
@@ -412,15 +434,7 @@ pub async fn assign_roles(
"everyone in the group holds member: to put someone out, eject them",
));
}
let defined: BTreeSet<String> = members
.records("role")?
.into_iter()
.map(|(k, _)| k)
.collect();
let undefined: Vec<&String> = roles.iter().filter(|r| !defined.contains(*r)).collect();
if !undefined.is_empty() {
return Err(invalid(format!("no such roles: {undefined:?}")));
}
members.defined(&roles)?;
let assignable = members.assignable(&mine, "role.assign");
let changed = roles
.iter()
crates/group-host/src/group_spaces.rs+15−5
@@ -8,7 +8,7 @@
//! of the index.
use crate::Host;
use crate::api::invalid;
use crate::api::{at_most, invalid};
use crate::group::{members_space, meta_space};
use crate::group_api::{group_of, signed_in};
use crate::group_config::put_in;
@@ -111,9 +111,15 @@ pub async fn create_space(
if !syntax::is_nsid(kind) {
return Err(invalid("spaceType is an NSID"));
}
let readers =
audience(&body, "readableBy")?.ok_or_else(|| invalid("readableBy is required"))?;
let readers = audience(&body, "readableBy")?.unwrap_or_default();
if readers.is_empty() {
return Err(invalid("readableBy names who reads the space"));
}
let writers = audience(&body, "writableBy")?;
let name = body["name"].as_str();
if let Some(name) = name {
at_most("name", name, 640, 64)?;
}
let skey = match body["skey"].as_str() {
Some(skey) => skey.to_string(),
None => host.clock.next(),
@@ -135,7 +141,7 @@ pub async fn create_space(
};
host.space_write(&group, &uri, &[access_write]).await?;
let mut entry = json!({"$type": format!("{NS}.space"), "space": uri, "createdAt": at});
if let Some(name) = body["name"].as_str() {
if let Some(name) = name {
entry["name"] = json!(name);
}
let indexed = Write::Create {
@@ -165,6 +171,10 @@ pub async fn update_space(
return Err(invalid("readableBy names who reads the space"));
}
let writers = audience(&body, "writableBy")?;
let name = body["name"].as_str();
if let Some(name) = name {
at_most("name", name, 640, 64)?;
}
let names = |list: &[Value]| -> Vec<String> {
list.iter()
.filter_map(|r| r["role"].as_str().map(String::from))
@@ -206,7 +216,7 @@ pub async fn update_space(
let declared = host.declare(&group, names(readers).iter().any(|r| r == PUBLIC));
declared.await?;
}
if let Some(name) = body["name"].as_str() {
if let Some(name) = name {
let (rkey, mut entry) = entry_of(&host, &group, &space)?;
entry["name"] = json!(name);
let put = put_in(&host, &group, &members, &space_collection, &rkey, entry);
crates/group-host/src/moderation.rs+20−5
@@ -12,7 +12,7 @@
//! group's spaces here.
use crate::Host;
use crate::api::{Params, invalid, page, param};
use crate::api::{Params, at_most, invalid, page, param};
use crate::group::members_space;
use crate::group_api::{group_of, signed_in};
use crate::rbac::NS;
@@ -21,7 +21,7 @@ use crate::store::Store;
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use anyhow::Result;
use atproto::syntax;
use atproto::{Cid, syntax};
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
@@ -208,6 +208,9 @@ fn subject_of(asked: &Value) -> Result<(Value, String), XrpcError> {
"a subject is an account's did, or a record's uri and cid",
));
};
if Cid::parse(cid).is_err() {
return Err(invalid("subject.cid is not a CID"));
}
Ok((
json!({"$type": "com.atproto.repo.strongRef", "uri": uri, "cid": cid}),
uri.to_string(),
@@ -239,6 +242,12 @@ impl Host {
.ok_or_else(|| invalid("group is required"))?;
let val = body["val"].as_str().filter(|v| !v.is_empty());
let val = val.ok_or_else(|| invalid("val is required"))?;
at_most("val", val, 128, 128)?;
// A rule is cited by its URI, a record's in the group's meta.
let rule = body["rule"].as_str();
if rule.is_some_and(|r| space_of(r).is_none()) {
return Err(invalid("rule is the URI of a rule"));
}
let action = if TAKEDOWN_VALS.contains(&val) {
"takedown"
} else {
@@ -265,7 +274,7 @@ impl Host {
if neg {
value["neg"] = json!(true);
}
if let Some(rule) = body["rule"].as_str() {
if let Some(rule) = rule {
value["rule"] = json!(rule);
}
let rkey = self.clock.next();
@@ -417,7 +426,13 @@ pub async fn resolve_subject(
let subject = body["subject"]
.as_str()
.ok_or_else(|| invalid("subject is required"))?;
let action = body["action"].as_str().unwrap_or_default();
let action = body["action"]
.as_str()
.ok_or_else(|| invalid("action is required"))?;
let note = body["note"].as_str();
if let Some(note) = note {
at_most("note", note, 3000, 300)?;
}
let status = match action {
"resolve" => Some("resolved"),
"escalate" => Some("escalated"),
@@ -446,7 +461,7 @@ pub async fn resolve_subject(
let event = Event {
kind: action.into(),
actor: Some(me),
note: body["note"].as_str().map(String::from),
note: note.map(String::from),
created_at: now,
..Event::default()
};
crates/group-host/tests/config.rs+14−3
crates/group-host/tests/group_config.rs+64−13
crates/group-host/tests/group_spaces.rs+19−2
crates/group-host/tests/groups.rs+11−0
crates/group-host/tests/invites.rs+34−4
crates/group-host/tests/joining.rs+24−0
crates/group-host/tests/members.rs+29−1
crates/group-host/tests/moderation.rs+41−5
docs/design/groups.md+17−2
docs/design/membership.md+13−1
docs/design/moderation.md+5−1
docs/reference/config.md+3−3
lexicons/fyi/opensocial/createInvite.json+2−1
lexicons/fyi/opensocial/profile.json+8−2
lexicons/fyi/opensocial/putRole.json+3−2
lexicons/fyi/opensocial/putRule.json+2−1
lexicons/fyi/opensocial/updateProfile.json+8−2