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

The Apps page names apps by their metadata and says changes in words

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:console/apps-words
.changeset/apps-by-their-names.mdnew+9−0
@@ -0,0 +1,9 @@
---
default: minor
---
# The Apps page names apps as they name themselves, and says what was done in words
The apps acting as a group are listed by the name and icon their client metadata gives (`client_name`, `logo_uri`), with the domain of their client ID beside the name, what their scope lets them do ("Can post and make changes as the group", or "Can read the group's profile and members, and see requests to join" for an app that only reads), and who approved them. The app's icon shows on the approval page too, where an app asks to sign in as a group. The host reads the icon itself and serves it at `/img/app?id=<client ID>`: only an `https` `logo_uri` on the client ID's own origin, a PNG, JPEG, GIF or WebP by its bytes, 256 KiB at most, kept ten minutes. An app with none is drawn as its initial.
The card under them is now "Changes made as the group", made by apps and by members in the console, each said as it is seen: "@alice.test made the group members-only", "Grain (grain.social) created the group's Grain profile". A change to a space names it by what the group keeps there (its profile, its members, its pool), never by its URI, and a change to who may read it says so. Another app's record is named by its app and kind, with its lexicon's description under it where the host can resolve the lexicon. `org.atgrp.internal.listGroupTokens` gives what these are said from: each app's `client`, a space change's `space`, and a write's `description`.
crates/group-host/src/apps.rsnew+173−0
@@ -0,0 +1,173 @@
//! Apps as the console shows them: each by what its OAuth client metadata
//! says of it, its name, its home page and its logo, and the logo served
//! from here, at `/img/app?id=<client_id>`, so that a reader's browser
//! never asks an app's own server for anything.
//!
//! A client's `client_uri` and `logo_uri` are shown only on the client
//! id's own origin, over https (or http, while the host is on http
//! itself), with no credentials or fragment; the loopback client names
//! neither. A logo is fetched from a public address, following no
//! redirect, at most 256 KiB, and served only when its bytes are a PNG,
//! JPEG, GIF or WebP image by their first bytes, whatever type its server
//! says: never SVG. A logo read, or found missing, is kept ten minutes.
use crate::Host;
use crate::api::Params;
use crate::index_api::capped;
use crate::time::now_millis;
use axum::body::Bytes;
use axum::extract::{Query, State};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use reqwest::Url;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
/// How long a logo read, or found missing, is kept.
const KEEP_FOR: i64 = 10 * 60_000;
/// How many apps' logos are kept at once.
const KEEP_AT_MOST: usize = 100;
/// The most bytes a logo may be.
const LOGO_AT_MOST: usize = 256 * 1024;
/// An app's logo: its type, as its bytes say, and its bytes.
#[derive(Debug, Clone, PartialEq)]
pub struct Logo {
pub kind: &'static str,
pub bytes: Bytes,
}
/// The logos read, by client id, and when: `None` for one not served.
#[derive(Default)]
pub struct Logos(Mutex<HashMap<String, (i64, Option<Logo>)>>);
impl Logos {
fn get(&self, id: &str, now: i64) -> Option<Option<Logo>> {
let kept = self.0.lock().expect("not poisoned");
let (at, logo) = kept.get(id).filter(|(at, _)| now - at < KEEP_FOR)?;
tracing::debug!(client = id, at, "kept");
Some(logo.clone())
}
fn keep(&self, id: &str, now: i64, logo: Option<Logo>) {
let mut kept = self.0.lock().expect("not poisoned");
if kept.len() >= KEEP_AT_MOST {
kept.clear();
}
kept.insert(id.into(), (now, logo));
}
}
/// Whether a page may show `url`, which the metadata of the client `id`
/// names as its home page or logo: an https URL (http too, `http_here`,
/// for a host on http itself) on the client id's origin, with no
/// credentials or fragment.
pub fn shown(id: &str, url: &str, http_here: bool) -> bool {
let (Ok(at), Ok(client)) = (Url::parse(url), Url::parse(id)) else {
return false;
};
let scheme = at.scheme() == "https" || (http_here && at.scheme() == "http");
let bare = at.username().is_empty() && at.password().is_none() && at.fragment().is_none();
scheme && bare && at.origin() == client.origin()
}
/// The type of image `bytes` are, by their first bytes: PNG, JPEG, GIF or
/// WebP, or none.
pub fn image_kind(bytes: &[u8]) -> Option<&'static str> {
match bytes {
[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, ..] => Some("image/png"),
[0xff, 0xd8, 0xff, ..] => Some("image/jpeg"),
[b'G', b'I', b'F', b'8', b'7' | b'9', b'a', ..] => Some("image/gif"),
[
b'R',
b'I',
b'F',
b'F',
_,
_,
_,
_,
b'W',
b'E',
b'B',
b'P',
..,
] => Some("image/webp"),
_ => None,
}
}
impl Host {
/// The app `id` as a page shows it, by what `metadata`, its client
/// metadata, says of it: its name, and its home page and logo where
/// a page may show them.
pub(crate) fn app_view(&self, id: &str, metadata: &Value) -> Value {
let http_here = self.config.public_url.starts_with("http://");
let url = |from: &str| metadata[from].as_str().filter(|u| shown(id, u, http_here));
let fields = [
("name", metadata["client_name"].as_str()),
("uri", url("client_uri")),
("logo", url("logo_uri")),
];
let mut view = json!({"clientId": id});
for (k, v) in fields.into_iter().filter_map(|(k, v)| Some((k, v?))) {
view[k] = json!(v);
}
view
}
/// The app `id` names, as a page shows it, if its client metadata can
/// be read: an OAuth client's, named by an https URL, or the loopback
/// client's.
pub(crate) async fn client_view(&self, id: &str, now: i64) -> Option<Value> {
let url = Some(id).filter(|i| i.starts_with("https://") || i.starts_with("http://"));
let client = self.client(url?, now).await.ok()?;
Some(self.app_view(id, &client.metadata))
}
/// The logo of the app `id` names, kept or read now: none for one
/// whose metadata names no logo a page may show, or whose logo is no
/// image.
pub async fn logo(&self, id: &str, now: i64) -> Option<Logo> {
if let Some(kept) = self.logos.get(id, now) {
return kept;
}
let logo = self.read_logo(id, now).await;
tracing::info!(client = id, found = logo.is_some(), "read a logo");
self.logos.keep(id, now, logo.clone());
logo
}
async fn read_logo(&self, id: &str, now: i64) -> Option<Logo> {
let view = self.client_view(id, now).await?;
let (pinned, at) = self.pinned(view["logo"].as_str()?).await.ok()?;
let res = pinned.get(at).send().await.ok()?;
let res = res.error_for_status().ok()?;
let bytes = capped(res, LOGO_AT_MOST).await?;
let kind = image_kind(&bytes)?;
Some(Logo {
kind,
bytes: bytes.into(),
})
}
}
/// The logo of the app `?id=` names, for a page to draw: nothing for one
/// the host does not serve.
pub async fn logo(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Response {
let id = p.get("id").map(String::as_str).unwrap_or_default();
let Some(logo) = host.logo(id, now_millis()).await else {
return StatusCode::NOT_FOUND.into_response();
};
let headers = [
(header::CONTENT_TYPE, logo.kind),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
(
header::CONTENT_SECURITY_POLICY,
"default-src 'none'; sandbox",
),
(header::CACHE_CONTROL, "private, max-age=600"),
];
(headers, logo.bytes).into_response()
}
crates/group-host/src/authorization.rs+1−10
@@ -166,16 +166,7 @@ pub async fn get_authorization(
let requested = requested(&request);
let metadata = host.client(&request.client_id, now_millis()).await;
let metadata = metadata.map(|c| c.metadata).unwrap_or_default();
let mut client = json!({"clientId": request.client_id});
for (k, from) in [
("name", "client_name"),
("uri", "client_uri"),
("logo", "logo_uri"),
] {
if let Some(v) = metadata[from].as_str() {
client[k] = json!(v);
}
}
let client = host.app_view(&request.client_id, &metadata);
let groups = match host.named_group(&request)? {
Some(named) => vec![named],
None => host.groups_of(&me)?,
crates/group-host/src/group_spaces.rs+8−1
@@ -314,11 +314,18 @@ impl Host {
// An app's grant whose member reads it no more ends its reads.
let ended = self.end_grant_reads(group).await;
ended.map_err(XrpcError::internal)?;
// Opened to anyone, or closed to those its policy names, or
// changed otherwise.
let done = match (now.public_read, next.public_read) {
(false, true) => "opened",
(true, false) => "closed",
_ => "updated",
};
let logged = self.record(
group,
member,
Some(&acting.grant.client_id),
&format!("updated space {uri}"),
&format!("{done} space {uri}"),
);
logged.map_err(XrpcError::internal)
}
crates/group-host/src/group_tokens.rs+93−7
@@ -8,8 +8,10 @@
//! password is involved, and there is nothing to refresh.
//!
//! `listGroupTokens` shows a group's configurers every grant that acts as
//! it, whose it is, and what was done with grants lately;
//! `revokeGroupToken` ends one.
//! it, whose it is, and what was done with grants lately: each app as its
//! client metadata names it (`apps.rs`), each write with what its kind of
//! record is as its lexicon describes it (`permission_sets.rs`), and each
//! change to a space as what it did. `revokeGroupToken` ends one.
use crate::Host;
use crate::api::{Params, invalid, param};
@@ -25,11 +27,12 @@ use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use atproto::jose;
use atproto::space::SpaceRef;
use atproto::syntax::is_nsid;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;
/// How long a group token lasts.
@@ -278,7 +281,7 @@ pub async fn get_group_auth(
/// collection and key, the space, if it was in one, and the DID of whom
/// it is about, if any: a record kept under someone's DID (a
/// membership), or one written in their inbox (an invite). Nothing, for
/// what was not a write.
/// what was not a write, a change to a space among it.
fn write_of(action: &str) -> Option<(Value, Option<String>)> {
let (done, rest) = action.split_once(' ')?;
let at = ["created", "updated", "deleted"]
@@ -287,7 +290,7 @@ fn write_of(action: &str) -> Option<(Value, Option<String>)> {
let (path, space) = rest
.split_once(" in ")
.map_or((rest, None), |(p, s)| (p, Some(s)));
let (collection, rkey) = path.split_once('/')?;
let (collection, rkey) = path.split_once('/').filter(|(c, _)| is_nsid(c))?;
let inbox = space.and_then(|s| SpaceRef::parse(s).ok()).filter(is_inbox);
let about = rkey.starts_with("did:").then(|| rkey.to_string());
let about = about.or(inbox.map(|s| s.authority));
@@ -303,6 +306,66 @@ fn write_of(action: &str) -> Option<(Value, Option<String>)> {
Some((write, about))
}
/// The words the log says a change to one of the group's spaces in, each
/// with its operation, and, for one that opened it to anyone or closed it
/// to those its policy names, whether anyone may read it now.
const SPACE_CHANGES: [(&str, &str, Option<bool>); 5] = [
("created", "create", None),
("updated", "update", None),
("deleted", "delete", None),
("opened", "update", Some(true)),
("closed", "update", Some(false)),
];
/// What a change to one of the group's spaces in its log was, as its
/// words say it (`opened space <uri>`): the space, the operation, and
/// whether anyone may read it now, where that changed. Nothing, for what
/// was not one.
fn space_of(action: &str) -> Option<Value> {
let (done, uri) = action.split_once(" space ")?;
let (_, operation, public_read) = SPACE_CHANGES.iter().find(|(d, ..)| *d == done)?;
let mut view = json!({"space": uri, "operation": operation});
if let Some(public_read) = public_read {
view["publicRead"] = json!(public_read);
}
Some(view)
}
impl Host {
/// The apps `ids` name, as a page shows them, where their metadata can
/// be read: each read once.
async fn client_views<'a>(
&self,
ids: impl Iterator<Item = &'a str>,
) -> HashMap<&'a str, Value> {
let now = now_millis();
let ids: BTreeSet<&str> = ids.collect();
let read = ids
.into_iter()
.map(async |id| (id, self.client_view(id, now).await));
let read = futures::future::join_all(read).await;
read.into_iter()
.filter_map(|(id, v)| Some((id, v?)))
.collect()
}
/// What each kind of record among `collections` is, as its lexicon
/// describes it, where that can be read: each read once.
async fn descriptions<'a>(
&self,
collections: impl Iterator<Item = &'a str>,
) -> HashMap<String, String> {
let collections: BTreeSet<&str> = collections.collect();
let read = collections
.into_iter()
.map(async |c| (c.to_string(), self.lexicon_description(c).await));
let read = futures::future::join_all(read).await;
read.into_iter()
.filter_map(|(c, d)| Some((c, d?)))
.collect()
}
}
/// Every grant that acts as the group, and what grants did lately, for
/// one who configures it.
pub async fn list_group_tokens(
@@ -330,6 +393,14 @@ pub async fn list_group_tokens(
.flatten()
.filter_map(|(_, about)| about.as_deref());
let actors = host.actor_views(members.chain(abouts)).await;
// The apps, as their metadata names them, and the kinds of record
// written, as their lexicons describe them.
let ids = grants.iter().map(|g| g.client_id.as_str());
let ids = ids.chain(log.iter().filter_map(|a| a.client_id.as_deref()));
let clients = host.client_views(ids).await;
let collections = writes.iter().flatten();
let collections = collections.filter_map(|(w, _)| w["collection"].as_str());
let descriptions = host.descriptions(collections).await;
let sessions: Vec<Value> = grants
.iter()
.map(|g| {
@@ -346,6 +417,9 @@ pub async fn list_group_tokens(
if let Some(used) = g.used_at {
view["lastUsedAt"] = json!(iso(used));
}
if let Some(client) = clients.get(g.client_id.as_str()) {
view["client"] = client.clone();
}
view
})
.collect();
@@ -358,14 +432,26 @@ pub async fn list_group_tokens(
json!({"member": a.member, "actor": actor, "action": a.action, "at": iso(a.at)});
if let Some(client) = &a.client_id {
view["clientId"] = json!(client);
if let Some(app) = clients.get(client.as_str()) {
view["client"] = app.clone();
}
}
// A write, said as its parts, and whom it is about.
if let Some((write, about)) = write {
// A write, said as its parts, with what its kind of record
// is, and whom it is about.
if let Some((mut write, about)) = write {
let kind = write["collection"].as_str();
if let Some(said) = kind.and_then(|c| descriptions.get(c)) {
write["description"] = json!(said);
}
view["write"] = write;
if let Some(about) = about {
view["subject"] = actors[&about].clone();
}
}
// A change to one of the group's spaces.
if let Some(space) = space_of(&a.action) {
view["space"] = space;
}
view
})
.collect();
crates/group-host/src/lib.rs+8−3
@@ -9,6 +9,7 @@ pub mod actors;
pub mod admin;
pub mod api;
pub mod app_passwords;
pub mod apps;
pub mod authority;
pub mod authority_api;
pub mod authorization;
@@ -95,8 +96,10 @@ pub struct Host {
pub(crate) clients: oauth_clients::Clients,
/// The handles the directory names, as last read for a search.
pub(crate) handles: actor_search::Handles,
/// Other apps' permission sets, as read.
pub(crate) sets: permission_sets::Read,
/// Other apps' lexicons, as read.
pub(crate) lexicons: permission_sets::Read,
/// Apps' logos, as read.
pub(crate) logos: apps::Logos,
/// The lines it logged, kept for its operators.
pub logs: Arc<logs::Logs>,
/// How it is used, counted for its operators.
@@ -133,7 +136,8 @@ impl Host {
index_wake: Default::default(),
clients: Default::default(),
handles: Default::default(),
sets: Default::default(),
lexicons: Default::default(),
logos: Default::default(),
logs: Arc::new(logs),
stats,
limits,
@@ -432,6 +436,7 @@ pub(crate) fn routes(host: Arc<Host>) -> Router {
"/console/client-metadata.json",
get(console_login::client_metadata),
)
.route("/img/app", get(apps::logo))
.route("/img/{did}/{cid}", get(blobs::image))
.route("/console/login", get(console_login::login))
.route("/console/move/login", get(account_move::login))
crates/group-host/src/permission_sets.rs+49−25
@@ -1,10 +1,13 @@
//! Other apps' permission sets, as an app signing in as a group asks for
//! one: `include:social.grain.authFull?aud=did:web:grain.social%23grain_appview`.
//! Each is read as atproto publishes lexicons: the TXT record
//! `_lexicon.<authority>` (the NSID's segments but the last, reversed)
//! names a DID, from `DNS_OVER_HTTPS`, and that DID's repo, at its PDS,
//! holds the set as the record `com.atproto.lexicon.schema/<nsid>`. A set
//! read, or found missing, is kept ten minutes.
//! Other apps' lexicons: their permission sets, as an app signing in as a
//! group asks for one
//! (`include:social.grain.authFull?aud=did:web:grain.social%23grain_appview`),
//! and what a kind of record an app wrote as the group is, as its lexicon
//! describes it. Each is read as atproto publishes lexicons: the TXT
//! record `_lexicon.<authority>` (the NSID's segments but the last,
//! reversed) names a DID, from `DNS_OVER_HTTPS`, and that DID's repo, at
//! its PDS, holds the lexicon as the record
//! `com.atproto.lexicon.schema/<nsid>`. A lexicon read, or found missing,
//! is kept ten minutes, for both.
//!
//! What an include gives is what atproto's permissions give of one: each
//! `repo` permission's collections and each `rpc` permission's methods,
@@ -24,9 +27,9 @@ use serde_json::{Value, json};
use std::collections::{BTreeMap, HashMap};
use std::sync::Mutex;
/// How long a set read, or found missing, is kept.
/// How long a lexicon read, or found missing, is kept.
const KEEP_FOR: i64 = 10 * 60_000;
/// How many sets are kept at once.
/// How many lexicons are kept at once.
const KEEP_AT_MOST: usize = 1000;
/// The collection a lexicon is published in.
const SCHEMA: &str = "com.atproto.lexicon.schema";
@@ -37,7 +40,9 @@ const TXT: u64 = 16;
/// `include:` scope that asked for it.
pub type Sets = BTreeMap<String, Value>;
/// The sets read, by NSID, and when: `None` for one that did not resolve.
/// The lexicons read, by NSID, and when: of each, its main def (`main`)
/// and its own description (`description`), or `None` for one that did
/// not resolve.
#[derive(Default)]
pub struct Read(Mutex<HashMap<String, (i64, Option<Value>)>>);
@@ -108,17 +113,17 @@ fn txt(data: &str) -> String {
impl Read {
fn get(&self, nsid: &str, now: i64) -> Option<Option<Value>> {
let kept = self.0.lock().expect("not poisoned");
let (at, set) = kept.get(nsid).filter(|(at, _)| now - at < KEEP_FOR)?;
let (at, lexicon) = kept.get(nsid).filter(|(at, _)| now - at < KEEP_FOR)?;
tracing::debug!(nsid, at, "kept");
Some(set.clone())
Some(lexicon.clone())
}
fn keep(&self, nsid: &str, now: i64, set: Option<Value>) {
fn keep(&self, nsid: &str, now: i64, lexicon: Option<Value>) {
let mut kept = self.0.lock().expect("not poisoned");
// Full, all of them go.
let full = kept.len() >= KEEP_AT_MOST;
kept.retain(|_, _| !full);
kept.insert(nsid.into(), (now, set));
kept.insert(nsid.into(), (now, lexicon));
}
}
@@ -137,20 +142,39 @@ impl Host {
sets
}
/// The set `nsid`, kept or read now.
/// The set `nsid`, its lexicon's main def, if it is one.
async fn permission_set(&self, nsid: &str) -> Option<Value> {
let lexicon = self.lexicon(nsid).await?;
let set = lexicon["main"]["type"] == "permission-set";
set.then(|| lexicon["main"].clone())
}
/// What the kind of record `collection`, another app's, is, as its
/// lexicon says: its main def's description, or else the lexicon's
/// own. None for one of this host's.
pub async fn lexicon_description(&self, collection: &str) -> Option<String> {
let theirs = Some(collection).filter(|c| !c.starts_with(&format!("{NS}.")));
let lexicon = self.lexicon(theirs?).await?;
let main = lexicon["main"]["description"].as_str();
let said = main.or(lexicon["description"].as_str())?;
Some(said.into())
}
/// The lexicon `nsid`, kept or read now.
async fn lexicon(&self, nsid: &str) -> Option<Value> {
let now = crate::time::now_millis();
if let Some(kept) = self.sets.get(nsid, now) {
if let Some(kept) = self.lexicons.get(nsid, now) {
return kept;
}
let set = self.read_set(nsid).await;
tracing::info!(nsid, resolved = set.is_some(), "read a permission set");
self.sets.keep(nsid, now, set.clone());
set
let lexicon = self.read_lexicon(nsid).await;
tracing::info!(nsid, resolved = lexicon.is_some(), "read a lexicon");
self.lexicons.keep(nsid, now, lexicon.clone());
lexicon
}
/// The set `nsid`, read from its publisher's repo.
async fn read_set(&self, nsid: &str) -> Option<Value> {
/// The lexicon `nsid`, read from its publisher's repo: its main def
/// and its description, all that is kept of it.
async fn read_lexicon(&self, nsid: &str) -> Option<Value> {
let publisher = self.lexicon_did(nsid).await?;
let doc = self.identity.document(&publisher).await.ok()?;
let pds = did::pds(&doc)?;
@@ -162,9 +186,9 @@ impl Host {
];
let url = Url::parse_with_params(&at, q).ok()?;
let record = self.public_json(url.as_str(), "a lexicon").await.ok()?;
let main = &record["value"]["defs"]["main"];
let set = record["value"]["id"] == nsid && main["type"] == "permission-set";
set.then(|| main.clone())
let lexicon = &record["value"];
let kept = json!({"main": lexicon["defs"]["main"], "description": lexicon["description"]});
(lexicon["id"] == nsid).then_some(kept)
}
/// The DID the `_lexicon` TXT record of `nsid`'s authority names: one
crates/group-host/tests/common/mod.rs+3−0
@@ -339,6 +339,9 @@ async fn start_on(
("PLC_URL", plc_url.as_str()),
("HANDLE_DOMAIN", ".groups.test"),
("PUBLIC_URL", "https://host.test"),
// No lexicon of another app's resolves but where a test serves
// one: the internet is never asked.
("DNS_OVER_HTTPS", "http://127.0.0.1:1/dns-query"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
crates/group-host/tests/group_spaces.rs+50−0
@@ -719,3 +719,53 @@ async fn an_admin_ends_a_space() {
.await;
assert_eq!(said.error(), (400, "SpaceNotFound"));
}
#[tokio::test]
async fn its_log_says_what_each_change_did_to_a_space() {
let h = start(&[], false).await;
let (did, [alice, ..]) = group(&h).await;
let rides = calendar(&did, "rides");
let grants = json!([{"role": "member", "read": true}]);
let closed = json!({"$type": POLICY, "grants": grants});
let open = json!({"$type": POLICY, "publicRead": true, "grants": grants});
let body = json!({"spaceType": CALENDAR, "skey": "rides", "policy": closed});
let said = method(&h, &alice, &did, &rides, "createSpace", body).await;
assert_eq!(said.status, 200, "{}", said.body);
// Opened to anyone, changed while open, then closed again.
for policy in [&open, &open, &closed] {
let body = json!({"space": rides, "policy": policy});
let said = method(&h, &alice, &did, &rides, "updateSpace", body).await;
assert_eq!(said.status, 200, "{}", said.body);
}
let body = json!({"space": rides});
let said = method(&h, &alice, &did, &rides, "deleteSpace", body).await;
assert_eq!(said.status, 200, "{}", said.body);
let lxm = format!("{INTERNAL}.listGroupTokens");
let query = format!("group={did}");
let (status, listed) = get(&h, &lxm, &query, &[auth(&h, &alice, &lxm)]).await;
assert_eq!(status, 200, "{listed}");
let changes: Vec<(&str, &Json)> = listed["activity"]
.as_array()
.unwrap()
.iter()
.filter(|a| a.get("space").is_some())
.map(|a| {
// A change to a space is no write.
assert_eq!(a.get("write"), None, "{a}");
(a["action"].as_str().unwrap(), &a["space"])
})
.collect();
let space = |operation: &str| json!({"space": rides, "operation": operation});
let switched = |public_read: bool| json!({"space": rides, "operation": "update", "publicRead": public_read});
assert_eq!(
changes,
[
(format!("deleted space {rides}").as_str(), &space("delete")),
(format!("closed space {rides}").as_str(), &switched(false)),
(format!("updated space {rides}").as_str(), &space("update")),
(format!("opened space {rides}").as_str(), &switched(true)),
(format!("created space {rides}").as_str(), &space("create")),
]
);
}
crates/group-host/tests/oauth_clients.rs+208−7
@@ -9,6 +9,7 @@ use atproto::{Curve, Keypair};
use axum::Router;
use axum::extract::{Path, State};
use axum::routing::get;
use common::groups::get as ask;
use common::groups::*;
use common::oauth::*;
use common::spaces::*;
@@ -37,16 +38,38 @@ async fn doc(
/// A server of client metadata documents, by name.
async fn documents() -> (Docs, String) {
let docs: Docs = Arc::default();
let url = serve(
Router::new()
.route("/{name}", get(doc))
.with_state(docs.clone()),
)
.await;
let (docs, _, url) = documents_and_files().await;
(docs, url)
}
type Files = Arc<Mutex<HashMap<String, (u16, Vec<u8>)>>>;
async fn file(
State(files): State<Files>,
Path(name): Path<String>,
) -> (axum::http::StatusCode, Vec<u8>) {
let found = files.lock().unwrap().get(&name).cloned();
let (status, body) = found.unwrap_or((404, Vec::new()));
(axum::http::StatusCode::from_u16(status).unwrap(), body)
}
/// A server of client metadata documents, by name, and of files, by name
/// under `/files/`, a client's logo among them.
async fn documents_and_files() -> (Docs, Files, String) {
let docs: Docs = Arc::default();
let files: Files = Arc::default();
let router = Router::new()
.route("/{name}", get(doc))
.with_state(docs.clone())
.merge(
Router::new()
.route("/files/{name}", get(file))
.with_state(files.clone()),
);
let url = serve(router).await;
(docs, files, url)
}
/// A confidential client's metadata, at `id`, with these keys.
fn confidential(id: &str, keys: &[(&str, &Keypair)]) -> Json {
let keys: Vec<Json> = keys
@@ -677,3 +700,181 @@ async fn keeps_what_it_read_a_while() {
let read = h.host.client(&id, now + 12 * 60_000).await.unwrap();
assert_eq!(read.metadata["client_name"], "Renamed again");
}
/// A public client's metadata, at `id`, named Rides, with its home page
/// and `logo`.
fn public_client(id: &str, logo: &str) -> Json {
let mut doc = confidential(id, &[]);
let fields = doc.as_object_mut().unwrap();
fields.remove("jwks");
fields.remove("token_endpoint_auth_signing_alg");
doc["token_endpoint_auth_method"] = json!("none");
doc["client_name"] = json!("Rides");
doc["client_uri"] = json!(format!("{}/", id.rsplit_once('/').unwrap().0));
doc["logo_uri"] = json!(logo);
doc
}
/// What `/img/app` answers for the client `id`, or with no id at all.
async fn logo_of(h: &Running, id: Option<&str>) -> reqwest::Response {
let asked = h.http.get(format!("{}/img/app", h.url));
let asked = match id {
Some(id) => asked.query(&[("id", id)]),
None => asked,
};
asked.send().await.unwrap()
}
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR";
#[tokio::test]
async fn shows_an_app_as_its_metadata_names_it_and_serves_its_logo() {
let h = start_reachable(&[]).await;
let (docs, files, url) = documents_and_files().await;
let put_file = |name: &str, status: u16, bytes: Vec<u8>| {
files.lock().unwrap().insert(name.into(), (status, bytes));
};
let put_client = |name: &str, logo: &str| {
let id = format!("{url}/{name}.json");
let doc = public_client(&id, logo).to_string();
docs.lock()
.unwrap()
.insert(format!("{name}.json"), (200, doc));
id
};
put_file("logo.png", 200, PNG.to_vec());
let logo = format!("{url}/files/logo.png");
let id = put_client("rides", &logo);
let (did, alice) = group(&h).await;
let app = App::new(&id);
let named = json!({"clientId": id, "name": "Rides", "uri": format!("{url}/"), "logo": logo});
// The approval page names it so.
let request_uri = app.push(&h, &[]).await;
let lxm = format!("{INTERNAL}.getAuthorization");
let query = format!("requestUri={request_uri}");
let (status, asked) = ask(&h, &lxm, &query, &[auth(&h, &alice, &lxm)]).await;
assert_eq!(status, 200, "{asked}");
assert_eq!(asked["client"], named);
// So does the list of what acts as the group: its session, and what
// it did.
app.sign_in(&h, &alice, &did).await;
let lxm = format!("{INTERNAL}.listGroupTokens");
let query = format!("group={did}");
let (status, listed) = ask(&h, &lxm, &query, &[auth(&h, &alice, &lxm)]).await;
assert_eq!(status, 200, "{listed}");
assert_eq!(listed["sessions"][0]["client"], named);
assert_eq!(listed["activity"][0]["clientId"], id.as_str());
assert_eq!(listed["activity"][0]["client"], named);
// Its logo, served from here as an image and nothing more.
let res = logo_of(&h, Some(&id)).await;
assert_eq!(res.status(), 200);
for (name, value) in [
("content-type", "image/png"),
("x-content-type-options", "nosniff"),
("content-security-policy", "default-src 'none'; sandbox"),
("cache-control", "private, max-age=600"),
] {
assert_eq!(res.headers()[name], value, "{name}");
}
assert_eq!(res.bytes().await.unwrap(), PNG);
// Nothing of a logo it may not show, that is no image, too large, or
// that cannot be read; nor for what is no app with metadata.
put_file(
"logo.svg",
200,
b"<svg xmlns='http://www.w3.org/2000/svg'/>".to_vec(),
);
put_file("big.png", 200, [PNG, &[0; 256 * 1024]].concat());
put_file("gone.png", 500, PNG.to_vec());
let mut unserved = vec![
put_client("svg", &format!("{url}/files/logo.svg")),
put_client("big", &format!("{url}/files/big.png")),
put_client("gone", &format!("{url}/files/gone.png")),
put_client("missing", &format!("{url}/files/missing.png")),
put_client("elsewhere", "https://elsewhere.test/logo.png"),
];
let elsewhere = h.host.client(&unserved[4], 0).await.unwrap();
assert_eq!(
elsewhere.metadata["logo_uri"],
"https://elsewhere.test/logo.png"
);
unserved.extend([
String::new(),
"getGroupAuth".into(),
"http://localhost".into(),
format!("{url}/nothing.json"),
]);
for id in &unserved {
assert_eq!(logo_of(&h, Some(id)).await.status(), 404, "{id}");
}
assert_eq!(logo_of(&h, None).await.status(), 404);
// Kept a while, and read again after.
let now = group_host::time::now_millis();
let kept = h.host.logo(&id, now).await.unwrap();
assert_eq!(kept.kind, "image/png");
let jpeg = b"\xff\xd8\xff\xe0\0\x10JFIF".to_vec();
put_file("logo.png", 200, jpeg.clone());
let kept = h.host.logo(&id, now + 60_000).await.unwrap();
assert_eq!(kept.kind, "image/png");
let read = h.host.logo(&id, now + 11 * 60_000).await.unwrap();
assert_eq!((read.kind, read.bytes.to_vec()), ("image/jpeg", jpeg));
// A hundred others, and it starts over.
put_file("logo.png", 200, b"GIF89a\x01\0\x01\0".to_vec());
for i in 0..100 {
let none = h.host.logo(&format!("x{i}"), now + 11 * 60_000).await;
assert_eq!(none, None);
}
let read = h.host.logo(&id, now + 12 * 60_000).await.unwrap();
assert_eq!(read.kind, "image/gif");
}
#[test]
fn shows_only_what_is_on_the_clients_own_origin() {
use group_host::apps::shown;
let id = "https://rides.test/client.json";
for (url, is) in [
("https://rides.test/logo.png", true),
("https://rides.test:443/a/b.png?size=2", true),
("https://cdn.rides.test/logo.png", false),
("https://rides.test:8443/logo.png", false),
("http://rides.test/logo.png", false),
("https://me@rides.test/logo.png", false),
("https://:secret@rides.test/logo.png", false),
("https://rides.test/logo.png#x", false),
("data:image/png;base64,AAAA", false),
("javascript:alert(1)", false),
("/logo.png", false),
] {
assert_eq!(shown(id, url, false), is, "{url}");
}
assert!(!shown("nonsense", "https://rides.test/logo.png", false));
// http, for a host on http itself.
let local = "http://127.0.0.1:2583/client.json";
assert!(shown(local, "http://127.0.0.1:2583/logo.png", true));
assert!(!shown(local, "http://127.0.0.1:2583/logo.png", false));
}
#[test]
fn knows_an_image_by_its_first_bytes() {
use group_host::apps::image_kind;
let cases: [(&[u8], Option<&str>); 10] = [
(PNG, Some("image/png")),
(b"\xff\xd8\xff\xdb", Some("image/jpeg")),
(b"GIF87a\x01\0", Some("image/gif")),
(b"GIF89a\x01\0", Some("image/gif")),
(b"RIFF\x24\0\0\0WEBPVP8 ", Some("image/webp")),
(b"RIFF\x24\0\0\0WAVEfmt ", None),
(b"<svg xmlns='http://www.w3.org/2000/svg'/>", None),
(b"<?xml version='1.0'?><svg/>", None),
(b"\x89PNG", None),
(b"", None),
];
for (bytes, kind) in cases {
assert_eq!(image_kind(bytes), kind, "{bytes:?}");
}
}
crates/group-host/tests/proxy.rs+73−1
docs/design/signing-in.md+34−7
docs/guides/shots/apps-activity-dark.png+0−0
A binary file, not shown.
docs/guides/shots/apps-activity.png+0−0
A binary file, not shown.
docs/guides/shots/apps-activity.txt+7−5
docs/guides/shots/apps-approve-dark.pngnew+0−0
A binary file, not shown.
docs/guides/shots/apps-approve.pngnew+0−0
A binary file, not shown.
docs/guides/shots/apps-approve.txtnew+19−0
docs/guides/shots/apps-dialog-dark.png+0−0
A binary file, not shown.
docs/guides/shots/apps-empty-dark.png+0−0
A binary file, not shown.
docs/guides/shots/apps-empty.png+0−0
A binary file, not shown.
docs/guides/shots/apps-empty.txt+4−4
docs/guides/shots/apps-made-dark.png+0−0
A binary file, not shown.
docs/guides/shots/apps-made.png+0−0
A binary file, not shown.
docs/guides/shots/apps-revoke-password-dark.png+0−0
A binary file, not shown.
docs/guides/shots/apps-revoke-password.png+0−0
A binary file, not shown.
docs/guides/shots/apps-signed-in-dark.png+0−0
A binary file, not shown.
docs/guides/shots/apps-signed-in.png+0−0
A binary file, not shown.
docs/guides/shots/apps-signed-in.txt+11−3
docs/guides/signing-in-as-a-group.md+44−11
docs/reference/api.md+3−2
harness/e2e/flows.spec.mjs+8−4
harness/e2e/pages.mjs+5−92
harness/look/seeds/nightshift-oauth.mjsnew+26−0
harness/look/look.mjs+10−3
harness/oauth-app.mjsnew+239−0
harness/shots.mjs+1−1
harness/world.mjs+7−1
lexicons/org/atgrp/internal/getAuthorization.json+4−2
lexicons/org/atgrp/internal/listGroupTokens.json+73−1
web/messages/en.json+44−17
web/src/lib/atoms/Avatar.svelte+15−10
web/src/lib/organisms/AuthorizeRequest.svelte+11−6
web/src/lib/organisms/GroupActivity.svelte+16−11
web/src/lib/organisms/GroupApps.svelte+29−18
web/src/lib/activity.ts+115−38
web/src/lib/images.ts+8−0
web/src/lib/permissions.ts+37−0
web/src/app.css+18−0