Side B fixes a real production bug (cloud IPs getting blocked by Reddit's public API, requiring OAuth with proper 401/403 retry-and-refresh logic) plus adds a unit test and config fix, directly improving reliability. Side A adds a new feature (RoomList) with solid test coverage, but it's incremental scope addition rather than fixing an existing correctness/reliability issue, making B's fix marginally more consequential to production stability.
constitution · epochs · watch · epoch 3
c_552f408ae0da (tommy-mor) vs c_ca9169f732b8 (tommy-mor)
download prompt · raw event · cmp_aaa3464b609f46
council reasoning
B fixes a load-bearing production failure: when Reddit credentials exist it never falls back to www.reddit.com (blocked from cloud IPs), adds AuthRejected handling with forced token refresh/retry, and hardens OAuth error paths—directly keeping core fetch working. A adds a useful but thin RoomList vertical slice (grant filter + CLI + isolation tests) that expands the API without the same operational necessity.
Side B fixes a production reliability issue by requiring OAuth when credentials exist, retrying once after 401/403 with a forced token refresh, improving error propagation, and avoiding fallback to blocked public Reddit endpoints; it also adds a focused test for error truncation. Side A adds a useful RoomList RPC, CLI subcommand, response type, and comprehensive integration tests, but it is primarily a new feature, whereas Side B addresses a deeper operational correctness problem that prevents fetch failures in deployed environments.
sides
A — c_552f408ae0da (tommy-mor)
message
[9acdf18a] feat: add RoomList RPC command and CLI room list subcommand Returns all rooms the authenticated principal has a grant in. Includes integration tests proving per-user isolation: users only see rooms they have been explicitly granted, not all rooms in the system. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
diff preview
diff --git a/bb.edn b/bb.edn
index f7c53eb2d5def514a8f2c480ac420416205db14e..8dc6a5be7321de198cbb5939842a33b8c5d52625 100644
--- a/bb.edn
+++ b/bb.edn
@@ -47,16 +47,18 @@
"RUST_LOG" "info"})})))}
test
- {:doc "Full test suite: integration + auth + grants + invites"
+ {:doc "Full test suite: integration + auth + grants + invites + room-list"
:requires ([test.integration :as integration]
[test.auth :as auth]
[test.grants :as grants]
- [test.invites :as invites])
+ [test.invites :as invites]
+ [test.room-list :as room-list])
:task (do
(integration/integration)
(auth/auth-test)
(grants/grants-test)
- (invites/invites-test))}
+ (invites/invites-test)
+ (room-list/room-list-test))}
walkthrough-fixture
{:doc "Run local server + mock OAuth + seeded walkthrough data for manual browser demos"
diff --git a/cli/src/main.rs b/cli/src/main.rs
index 69492cb5417a0a19c38f8cacbeadd103bd905b6f..b008cf377bb360aaae666d2dfd4b5e13dedb204a 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -219,6 +219,12 @@ enum RoomCmd {
#[arg(long)]
json: bool,
},
+ /// List rooms the authenticated user has access to
+ List {
+ /// Output as JSON for agent parsing
+ #[arg(long)]
+ json: bool,
+ },
}
#[derive(Subcommand, Debug)]
@@ -1319,6 +1325,38 @@ async fn main() -> Result<()> {
_ => return Err(anyhow!("unexpected RPC result")),
}
}
+ RoomCmd::List { json } => {
+ let client = http_client()?;
+ let bearer = effective_bearer().ok_or_else(|| {
+ anyhow!(
+ "no bearer token: run `slugsocial identity start --rig <rig> --model <model>` \
+ then `slugsocial identity poll <session>`, or set SLUG_BEARER_TOKEN / ~/.config/slugsocial/token"
+ )
+ })?;
+ let batch = send_rpc(
+ &client,
+ base,
+ Some(&bearer),
+ vec![RpcCommand::RoomList],
+ )
+ .await?;
+ match rpc_line_ok(&batch.results[0])? {
+ RpcResult::RoomList(resp) => {
+ if json {
+ println!("{}", serde_json::to_string_pretty(&resp)?);
+ } else {
+ if resp.rooms.is_empty() {
+ println!("no rooms");
+ } else {
+ for room in &resp.rooms {
+ println!("{room}");
+ }
+ }
+ }
+ }
+ _ => return Err(anyhow!("unexpected RPC result")),
+ }
+ }
},
Command::Healthz { json } => {
diff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs
index ed4800e7cbdeaf04e72192c191e71354e603c1fe..f1ee6d35b95a1a28490823e907b8f4dc5c091b94 100644
--- a/server/src/api/rpc.rs
+++ b/server/src/api/rpc.rs
@@ -1345,6 +1345,25 @@ pub async fn handle_rpc_batch(
}
}
}
+ RpcCommand::RoomList => {
+ let principal = {
+ let reduced = state.reduced.read().await;
+ verify_bearer_principal(&headers, &*reduced)
+ };
+ match principal {
+ Err((_, m)) => line_err(m, None),
+ Ok(principal) => {
+ let reduced = state.reduced.read().await;
+ let rooms: Vec<String> = reduced
+ .grants
+ .iter()
+ .filter(|(_, members)| members.contains_key(&principal))
+ .map(|(room, _)| room.clone())
+ .collect();
+ line_ok(RpcResult::RoomList(RoomListResponse { rooms }))
+ }
+ }
+ }
RpcCommand::RoomRevoke {
room,
username,
diff --git a/test/room_list.clj b/test/room_list.clj
new file mode 100644
index 0000000000000000000000000000000000000000..a089a722ac8d5f822f47d5511a46f671d61d46cf
--- /dev/null
+++ b/test/room_list.clj
@@ -0,0 +1,158 @@
+(ns test.room-list
+ "Room list integration test: list rooms user has access to via POST /api/v0/rpc.
+
+ Covers:
+ - user with no rooms -> empty list
+ - user with one room -> list contains that room
+ - user with multiple rooms -> list contains all rooms"
+ (:require [babashka.fs :as fs]
+ [cheshire.core :as json]
+ [clojure.set :as set]
+ [test.common :as common]
+ [test.oauth :as oauth]))
+
+(def ^:private counts (atom {:pass 0 :fail 0}))
+
+(defn- assert! [pred msg]
+ (common/test-assert! counts pred msg))
+
+(defn- bearer [token] {"Authorization" (str "Bearer " token)})
+
+(defn- rpc-batch! [base-url token cmds]
+ (let [resp (oauth/http-post-json (str base-url "/api/v0/rpc") cmds :headers (bearer token))]
+ {:status (:status resp)
+ :parsed (json/parse-string (:body resp) false)}))
+
+(defn- rpc-line-ok? [parsed]
+ (true? (get-in parsed ["results" 0 "ok"])))
+
+(defn- register-user! [base-url session-agent username]
+ (oauth/complete-registration! base-url
+ :agent session-agent
+ :username username
+ :assert! (fn [pred msg] (assert! pred msg))))
+
+(defn room-list-test [& _args]
+ (println "\n━━━ room list integration check ━━━\n")
+ (reset! counts {:pass 0 :fail 0})
+
+ (println "building server binary…")
+ (common/letlocals
+ (bind build (common/run-cargo-build-release! ["slugsocial-server"]))
+ (assert! (zero? (:exit build)) "cargo build succeeds")
+ (bind server-bin "target/release/slugsocial-server")
+
+ (bind tmp-dir (str (fs/create-temp-dir {:prefix "slug-room-list-"})))
+ (bind slug-port (common/pick-port))
+ (bind google-port (common/pick-port))
+ (bind base-url (str "http://127.0.0.1:" slug-port))
+ (bind google-url (str "http://127.0.0.1:" google-port))
+
+ (bind !server (atom nil))
+ (bind !google (atom nil))
+
+ (bind server-env (common/slug-server-env tmp-dir base-url google-url slug-port))
+ (try
+ (println (str "starting mock google on :" google-port))
+ (reset! !google (oauth/start-mock-google google-port
+ :google-users ["google-user-alice"
+ "google-user-bob"
+ "google-user-carol"]))
+
+ (println (str "starting server on :" slug-port))
+ (reset! !server (common/start-server server-bin server-env))
+ (assert! (common/wait-for-server base-url 10000) "server responds to /healthz")
+
+ (println "\nregistering alice, bob, carol…")
+ (let [alice-token (register-user! base-url
+ "00000000-0000-0000-0000-000000000001:test:local/dev"
+ "alice")
+ bob-token (register-user! base-url
+ "00000000-0000-0000-0000-000000000002:test:local/dev"
+ "bob")
+ carol-token (register-user! base-url
+ "00000000-0000-0000-0000-000000000003:test:local/dev"
+ "carol")
+
+ ;; Alice creates two private rooms
+ _ (println "\nalice creates two rooms…")
+ room-id-1 (-> (rpc-batch! base-url alice-token [{"RoomCreate" {"slug" "alice-room-one"}}])
+ (get-in [:parsed "results" 0 "result" "RoomCreated" "room_id"]))
+ _ (assert! (some? room-id-1) "alice room-one created")
+ room-id-2 (-> (rpc-batch! base-url alice-token [{"RoomCreate" {"slug" "alice-room-two"}}])
+ (get-in [:parsed "results" 0 "result" "RoomCreated" "room_id"]))
+ _ (assert! (some? room-id-2) "alice room-two created")
+
+ ;; Carol creates her own room
+ _ (println "carol creates her own room…")
+ carol-room (-> (rpc-batch! base-url carol-token [{"RoomCreate" {"slug" "carol-room"}}])
+ (get-in [:parsed "results" 0 "result" "RoomCreated" "room_id"]))
+ _ (assert! (some? carol-room) "carol room created")]
+
+ ;; --- isolation: alice only sees her rooms, not carol's ---
+ (println "\nalice sees her 2 rooms but not carol's…")
+ (let [rooms (-> (rpc-batch! base-url alice-token ["RoomList"])
+ (get-in [:parsed "results" 0 "result" "RoomList" "rooms"])
+ set)]
+ (assert! (= #{room-id-1 room-id-2} rooms)
+ "alice sees exactly her 2 rooms")
+ (assert! (not (contains? rooms carol-room))
+ "alice does NOT see carol's room"))
+
+ ;; --- isolation: carol only sees her room, not alice's ---
+ (println "carol sees only her room…")
+ (let [rooms (-> (rpc-batch! base-url carol-token ["RoomList"])
+ (get-in [:parsed "results" 0 "result" "RoomList" "rooms"])
+ set)]
+ (assert! (= #{carol-room} rooms)
+ "carol sees exactly her own room")
+ (assert! (not (contains? rooms room-id-1))
+ "carol does NOT see alice's room-one")
+ (assert! (not (contains? rooms room-id-2))
+ "carol does NOT see alice's room-two"))
+
+ ;; --- bob sees nothing yet: alice has 3 rooms total but bob is in none ---
+ (println "bob (no grants) sees no rooms despite 3 existing…")
+ (let [rooms (-> (rpc-batch! base-url bob-token ["RoomList"])
+ (get-in [:parsed "results" 0 "result" "RoomList" "rooms"]))]
+ (assert! (zero? (count rooms))
+ "bob sees 0 rooms even though 3 exist in the system"))
+
+ ;; --- partial grant: alice grants bob room-one only ---
+ (println "\nalice grants bob view on room-one only…")
+ (assert! (rpc-line-ok? (:parsed (rpc-batch! base-url alice-token
+ [{"RoomGrant" {"room" room-id-1
+ "username" "bob"
+ "capabilities" ["view"]}}])))
+ "grant ok")
+
+ ;; bob sees room-one but NOT room-two or carol's room
+ (println "bob sees room-one but not room-two or carol's room…")
+ (let [rooms (-> (rpc-batch! base-url bob-token ["RoomList"])
+ (get-in [:parsed "results" 0 "result" "RoomList" "rooms"])
+ set)]
+ (assert! (= #{room-id-1} rooms)
+ "bob sees exactly room-one")
+ (assert! (not (contains? rooms room-id-2))
+ "bob does NOT see alice's room-two (not granted)")
+ (assert! (not (contains? rooms carol-room))
+ "bob does NOT see carol's room (not granted)"))
+
+ ;; alice's view is unchanged
+ (println "alice's view unchanged after granting bob…")
+ (let [rooms (-> (rpc-batch! base-url alice-token ["RoomList"])
+ (get-in [:parsed "results" 0 "result" "RoomList" "rooms"])
+ set)]
+ (assert! (= #{room-id-1 room-id-2} rooms)
+ "alice still sees exactly her 2 rooms after granting bob")))
+
+ (fin
… preview truncated; 2,078 characters omittedB — c_ca9169f732b8 (tommy-mor)
message
[8f69c309] Require Reddit OAuth when credentials are set and refresh on 401/403. Avoid falling back to the public www.reddit.com API from cloud IPs, which returns Reddit's network-security block page. Also pin SORTER2_BASE_URL in fly.toml. Co-authored-by: Cursor <cursoragent@cursor.com>
diff preview
diff --git a/fly.toml b/fly.toml
index f0c6a39f643c204987debc177234d95a8ef44b65..ca7e0088a7efd7d58d29d808f8d89080b2bff233 100644
--- a/fly.toml
+++ b/fly.toml
@@ -5,6 +5,7 @@ primary_region = "iad"
dockerfile = "Dockerfile"
[env]
+ SORTER2_BASE_URL = "https://reddit.sorter.social"
SORTER2_DATA_DIR = "/data"
SORTER2_EVENT_LOG = "/data/events.jsonl"
PORT = "8080"
diff --git a/server/src/reddit.rs b/server/src/reddit.rs
index a874814f8927192ee62cab2d0db1efd27dcd57b7..f409764c1e1f36216f1b08107043c2eab905694c 100644
--- a/server/src/reddit.rs
+++ b/server/src/reddit.rs
@@ -283,26 +283,35 @@ async fn reddit_worker(
);
tokio::time::sleep(current_delay).await;
- if let Some(c) = &creds {
- oauth = ensure_oauth_token(&client, &oauth_token_base, c, oauth.take()).await;
- }
-
- let token = oauth.as_ref().map(|t| t.access_token.as_str());
- let fetch_base = if token.is_some() {
- tracing::debug!(
- item = %fetch_id,
- base = %oauth_api_base,
- "reddit fetch using OAuth bearer"
- );
- &oauth_api_base
- } else {
- &api_base
- };
- let url = match kind {
- FetchKind::SelfEntity => map_item_to_reddit_api(&fetch_id, fetch_base),
- FetchKind::Children => map_children_url(&fetch_id, fetch_base),
+ let outcome = match &creds {
+ Some(c) => {
+ // OAuth is required when credentials are configured — never fall
+ // back to the public www.reddit.com JSON endpoints (cloud IPs
+ // get blocked with a 403 HTML interstitial).
+ fetch_with_oauth(
+ &client,
+ &oauth_token_base,
+ &oauth_api_base,
+ c,
+ &mut oauth,
+ &fetch_id,
+ kind,
+ )
+ .await
+ }
+ None => {
+ let url = match kind {
+ FetchKind::SelfEntity => map_item_to_reddit_api(&fetch_id, &api_base),
+ FetchKind::Children => map_children_url(&fetch_id, &api_base),
+ };
+ match do_fetch(&client, &url, &fetch_id, None).await {
+ Ok(FetchOutcome::AuthRejected { status, detail }) => {
+ Err(format!("Reddit API {status}: {detail}"))
+ }
+ other => other,
+ }
+ }
};
- let outcome = do_fetch(&client, &url, &fetch_id, token).await;
match outcome {
Ok(FetchOutcome::Payload(payload)) => {
@@ -342,6 +351,12 @@ async fn reddit_worker(
current_delay = (current_delay * 2).min(Duration::from_secs(60));
notify(done, FetchJobResult::RateLimited { reset_secs });
}
+ Ok(FetchOutcome::AuthRejected { status, detail }) => {
+ let e = format!("Reddit API {status}: {detail}");
+ tracing::warn!(item = %fetch_id, err = %e, "reddit fetch auth rejected");
+ current_delay = (current_delay * 2).min(Duration::from_secs(60));
+ notify(done, FetchJobResult::Failed(e));
+ }
Err(e) => {
tracing::warn!(item = %fetch_id, err = %e, "reddit fetch failed");
current_delay = (current_delay * 2).min(Duration::from_secs(60));
@@ -357,6 +372,60 @@ enum FetchOutcome {
Payload(Value),
NotFound,
RateLimited { reset_secs: u64 },
+ /// Bearer rejected — caller should drop the cached token and retry once.
+ AuthRejected { status: StatusCode, detail: String },
+}
+
+async fn fetch_with_oauth(
+ client: &Client,
+ oauth_token_base: &str,
+ oauth_api_base: &str,
+ creds: &RedditCredentials,
+ oauth: &mut Option<OAuthToken>,
+ fetch_id: &ItemId,
+ kind: FetchKind,
+) -> Result<FetchOutcome, String> {
+ for attempt in 0..2 {
+ let force_refresh = attempt > 0;
+ *oauth = Some(
+ ensure_oauth_token(client, oauth_token_base, creds, oauth.take(), force_refresh)
+ .await?,
+ );
+ let token = oauth
+ .as_ref()
+ .expect("token set above")
+ .access_token
+ .clone();
+
+ tracing::debug!(
+ item = %fetch_id,
+ base = %oauth_api_base,
+ attempt,
+ "reddit fetch using OAuth bearer"
+ );
+
+ let url = match kind {
+ FetchKind::SelfEntity => map_item_to_reddit_api(fetch_id, oauth_api_base),
+ FetchKind::Children => map_children_url(fetch_id, oauth_api_base),
+ };
+ match do_fetch(client, &url, fetch_id, Some(&token)).await? {
+ FetchOutcome::AuthRejected { status, detail } if attempt == 0 => {
+ tracing::warn!(
+ item = %fetch_id,
+ %status,
+ %detail,
+ "reddit OAuth rejected; refreshing token and retrying"
+ );
+ *oauth = None;
+ continue;
+ }
+ FetchOutcome::AuthRejected { status, detail } => {
+ return Err(format!("Reddit API {status}: {detail}"));
+ }
+ other => return Ok(other),
+ }
+ }
+ unreachable!("loop always returns")
}
async fn ensure_oauth_token(
@@ -364,35 +433,35 @@ async fn ensure_oauth_token(
oauth_base: &str,
creds: &RedditCredentials,
existing: Option<OAuthToken>,
-) -> Option<OAuthToken> {
- if let Some(t) = existing {
- if Instant::now() < t.expires_at - Duration::from_secs(60) {
- tracing::debug!("reddit OAuth token still valid");
- return Some(t);
+ force_refresh: bool,
+) -> Result<OAuthToken, String> {
+ if !force_refresh {
+ if let Some(t) = existing {
+ if Instant::now() < t.expires_at - Duration::from_secs(60) {
+ tracing::debug!("reddit OAuth token still valid");
+ return Ok(t);
+ }
}
}
let url = format!("{}/api/v1/access_token", oauth_base.trim_end_matches('/'));
- tracing::debug!(%url, "reddit OAuth token request");
+ tracing::debug!(%url, force_refresh, "reddit OAuth token request");
let resp = client
.post(&url)
.basic_auth(&creds.client_id, Some(&creds.client_secret))
.form(&[("grant_type", "client_credentials")])
.send()
- .await;
-
- let resp = match resp {
- Ok(r) => r,
- Err(e) => {
- tracing::warn!("reddit OAuth token request failed: {e}");
- return None;
- }
- };
+ .await
+ .map_err(|e| format!("Reddit OAuth token request failed: {e}"))?;
if !resp.status().is_success() {
- tracing::warn!("reddit OAuth token HTTP {}", resp.status());
- return None;
+ let status = resp.status();
+ let body = resp.text().await.unwrap_or_default();
+ return Err(format!(
+ "Reddit OAuth token HTTP {status}: {}",
+ truncate_for_error(&body)
+ ));
}
#[derive(Deserialize)]
@@ -401,21 +470,40 @@ async fn ensure_oauth_token(
expires_in: u64,
}
- let body: TokenResponse = match resp.json().await {
- Ok(b) => b,
- Err(e) => {
- tracing::warn!("reddit OAuth token parse failed: {e}");
- return None;
- }
- };
+ let body: TokenResponse = resp
+ .json()
+ .await
+ .map_err(|e| format!("Reddit OAuth token parse failed: {e}"))?;
- tracing::debug!(expires_in = body.expires_in, "reddit OAuth token acquired");
- Some(OAuthToken {
+ tracing::info!(expires_in = body.expires_in, "reddit OAuth token acquired");
+ Ok(OAuthToken {
access_token: body.access_token,
expires_at: Instant::now() + Duration::from_secs(body.expires_in),
})
}
+fn truncate_for_error(body: &str) -> String {
+ let compact: String = body.split_whitespace().collect::<Vec<_>>().join(" ");
+ if compact.is_empty() {
+ return "(empty body)".into();
+ }
+ // Prefer the human-readable block message over dumping Reddit's CSS.
+ if let Some(idx) = compact.find("You've been blocked") {
+ let slice: String = compact.chars().skip(idx).take(160).collect();
+ return if compact.chars().count() > idx + 160 {
+ format!("{slice}…")
+ } else {
+ slice
+ };
+ }
+ let chars: String = compact.chars().take(200).collect();
+ if compact.chars().count() > 200 {
+ format!("{chars}…")
+ } else {
+ chars
+ }
+}
+
async fn do_fetch(
client: &Client,
url: &str,
@@ -460,15 +548,16 @@ async fn do_fetch(
if !status.is_success() {
let body = resp.text().await.unwrap_or_default();
+ let detail = truncate_for_error(&body);
tracing::debug!(
item = %id,
%status,
body_len = body.len(),
- body_prefix = %body.chars().take(240).collect::<String>(),
+ %detail,
"reddit non-success body"
);
if status == StatusCode::FORBIDDEN || status == StatusCode::UNAUTHORIZED {
- return Err(format!("Reddit API {status}: {body}"));
+ return Ok(FetchOutcome::AuthRejected { status, detail });
}
return Ok(FetchOutcome::NotFound);
}
@@ -716,6 +805,15 @@ fn reddit_direct_image_url(url: &str) -> bool {
mod tests {
use super::*;
+ #[test]
+ fn truncate_error_prefers_block_message() {
+ let html = r#"<style>.x{color:red}</style><div>You've been blocked by network security. To continue, log in</div>"#;
+ let msg = truncate_for_error(html);
+ assert!(msg.starts_with("You've been blocked"));
+ assert!(msg.len() < 200);
+ assert!(!msg.contains(".x{color"));
+ }
+
#[test]
fn map_subreddit_about_url() {
let id = ItemId::from_url("https://reddit.com/r/rust").unwrap();
Hardlinks — judgments / attempts / prompt
judgments
attempts
Prompt text is loaded only by the download route.