diff --git a/Cargo.lock b/Cargo.lock index c3ecb13..be4c717 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -289,7 +289,7 @@ checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "mailroom-logic" -version = "0.3.0" +version = "0.4.0" dependencies = [ "chrono", "pollster", @@ -300,7 +300,7 @@ dependencies = [ [[package]] name = "mailroom-worker" -version = "0.3.0" +version = "0.4.0" dependencies = [ "futures-util", "mailroom-logic", diff --git a/README.md b/README.md index 6f2719f..e759f28 100644 --- a/README.md +++ b/README.md @@ -107,12 +107,12 @@ Tags the poller adds itself: | --- | --- | | `routed:mention` | Discord: the message mentions the agent's bot. GitHub: the text contains `@`. | | `routed:reply` | Discord: the message replies to one of the bot's messages. | -| `routed:assigned` | GitHub: the agent is an assignee, or a trusted person put `assigned:` on the item (see Work handed over by label). | -| `routed:review` | GitHub: the PR carries `review_label` or the agent is a requested reviewer, or a trusted person put `review:` on the PR (see Work handed over by label). | +| `routed:assigned` | GitHub: the agent is an assignee, or a trusted labeler put `assigned:` on the item (see Work handed over by label). | +| `routed:review` | GitHub: the PR carries `review_label` or the agent is a requested reviewer, or a trusted labeler put `review:` on the PR (see Work handed over by label). | | `mine` | GitHub: a comment, review or event on an issue or PR the agent authored. | | `claimed` | GitHub: activity on an item handed to the agent by label (see Work handed over by label). | | `released` | GitHub: the closing note of such an item. Drop the claim. | -| `untrusted-label` | GitHub: the label was applied by someone GitHub does not report as having triage, write, maintain or admin access to that repository, or by any app or bot. Not followed. | +| `untrusted-label` | GitHub: the label was applied by someone GitHub does not report as having triage, write, maintain or admin access to that repository, or by an app or bot that is not in `labels.trusted_labelers`. Not followed. | Tags starting `routed:` are addressed to the agent. `mine` is activity on its own work. `claimed`, `released` and `untrusted-label` do not start with `routed:`, so they do not @@ -171,7 +171,7 @@ tick, and unknown fields are rejected. | `repos` | required | `owner/name`. No duplicates. Not empty unless `labels` is set. | | `every_secs` | `300` | Minimum `60`. | | `review_label` | none | A label that means "review this". When set it must not be empty, and with `labels` it must not be `assigned:` or `review:` (in any case): those labels already route, with a trust check. | -| `labels` | none | `{ "org": "your-org", "tag": "claude" }`. Also finds work handed over by label across the whole organisation; see Work handed over by label. `tag` is 1-32 characters of `a-z`, `0-9`, `-`. | +| `labels` | none | `{ "org": "your-org", "tag": "claude" }`. Also finds work handed over by label across the whole organisation; see Work handed over by label. `tag` is 1-32 characters of `a-z`, `0-9`, `-`. Optional `trusted_labelers`: logins (`name` or `name[bot]`) whose labels count whatever access GitHub reports for them. | | `skip_self` | `true` | As above. | | `keep` | `"all"` | `"all"` or `"tagged"`. | | `rules` | `[]` | See below. | @@ -259,10 +259,24 @@ shows the name as GitHub has it. **Who is trusted.** The label counts only when the person who applied it can write to the repository: GitHub reports their `permission` as `admin` or `write`, or their role as `admin`, `maintain`, `write` or `triage`. Anyone else, and anyone GitHub cannot find, is -untrusted. A GitHub App's bot is never a trusted labeler (GitHub reports no access for -it, and a login containing `[bot]` is untrusted without a lookup), so one agent cannot -hand work to another. There is no allowlist. A failed permission lookup fails the poll -and is retried; it never decides trust. +untrusted. GitHub reports no access for a GitHub App's bot, so an app's label is untrusted +(without a lookup) unless its login is listed in `trusted_labelers`: + +```jsonc +"labels": { "org": "your-org", "tag": "claude", + "trusted_labelers": ["your-other-agent[bot]"] } +``` + +A listed login is trusted for both labels, in any repository of the organisation, without +asking GitHub, so list only the agents that may hand work to this mailbox: whoever can +steer a listed agent can route work here. Entries are whole logins (`name` or `name[bot]`), +matched in any case. Without the list, one agent cannot hand work to another. A mailbox +that lists its own bot follows what that bot labels for itself, without a claim record +(`skip_self`). Trust is decided when a label is applied: editing the list affects labels +applied afterwards. Taking a login off the list does not take back work it already handed +over (remove the label to do that), and adding one does not promote an item that already +got `untrusted-label` (apply the label again). A failed permission lookup fails the poll and is retried; it never decides +trust. Trust is decided per label, by the item's events and never by the search alone. For each label that the search shows, the newest `labeled` event decides, and it counts only if no diff --git a/crates/logic/Cargo.toml b/crates/logic/Cargo.toml index 8726e70..f61dd5c 100644 --- a/crates/logic/Cargo.toml +++ b/crates/logic/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mailroom-logic" -version = "0.3.0" +version = "0.4.0" edition = "2021" license = "MIT" diff --git a/crates/logic/src/claims.rs b/crates/logic/src/claims.rs index 7d85438..0727489 100644 --- a/crates/logic/src/claims.rs +++ b/crates/logic/src/claims.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::de::IgnoredAny; use serde::{Deserialize, Serialize}; -use crate::config::GithubSource; +use crate::config::{GithubSource, LabelRouting}; use crate::feed::{get_json, FeedClient, FeedError, Identity, Poll, PollError}; use crate::github::{ event_record, gap_record, issue_comment_record, review_comment_record, review_record, Comment, Ctx, @@ -130,8 +130,17 @@ fn bad_status(e: &FeedError, codes: &[u16]) -> bool { matches!(e, FeedError::Status { status, .. } if codes.contains(status)) } -/// Whether `login` may hand work out in `repo`. Bots and missing users are not trusted. -async fn trusted_labeler(feed: &impl FeedClient, repo: &str, login: &str) -> Result { +/// Whether `login` may hand work out in `repo`: it is on the source's own list, or GitHub +/// reports triage access or more. A bot that is not listed and a missing user are not trusted. +async fn trusted_labeler( + feed: &impl FeedClient, + routing: &LabelRouting, + repo: &str, + login: &str, +) -> Result { + if routing.trusts(login) { + return Ok(true); + } if login.is_empty() || !login.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Ok(false); } @@ -453,7 +462,7 @@ pub async fn poll_claims( let ok = match trust.get(&slot) { Some(ok) => *ok, None => { - let ok = trusted_labeler(feed, repo, actor).await?; + let ok = trusted_labeler(feed, routing, repo, actor).await?; trust.insert(slot, ok); ok } diff --git a/crates/logic/src/config.rs b/crates/logic/src/config.rs index 280bceb..c195b10 100644 --- a/crates/logic/src/config.rs +++ b/crates/logic/src/config.rs @@ -79,6 +79,10 @@ pub struct LabelRouting { pub org: String, /// The tag in `assigned:` and `review:`. pub tag: String, + /// Logins whose labels count whatever access GitHub reports for them: the way to let + /// an app's bot (`name[bot]`), which GitHub gives no role, hand work to this mailbox. + #[serde(default)] + pub trusted_labelers: Vec, } impl LabelRouting { @@ -89,6 +93,13 @@ impl LabelRouting { pub fn review(&self) -> String { format!("review:{}", self.tag) } + + /// Whether `login` is on the list, whole and in any case. + pub fn trusts(&self, login: &str) -> bool { + self.trusted_labelers + .iter() + .any(|t| t.eq_ignore_ascii_case(login)) + } } /// What a GitHub target key of a source names. @@ -290,6 +301,22 @@ fn validate_source(agent: &str, index: usize, source: &SourceConfig) -> Result<( format!("{:?} must be 1-32 chars of a-z, 0-9, '-'", l.tag), ); } + let mut listed = BTreeSet::new(); + for login in &l.trusted_labelers { + // A GitHub login, optionally an app's bot user: "name" or "name[bot]". + let name = login.strip_suffix("[bot]").unwrap_or(login); + let login_ok = (1..=39).contains(&name.len()) + && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'); + if !login_ok { + return fail( + "labels.trusted_labelers", + format!("{login:?} must be a GitHub login, optionally ending in [bot]"), + ); + } + if !listed.insert(login.to_ascii_lowercase()) { + return fail("labels.trusted_labelers", format!("duplicate {login:?}")); + } + } } for r in &g.repos { let ok = matches!(r.split_once('/'), Some((o, n)) if !o.is_empty() && !n.is_empty() && !n.contains('/')); diff --git a/crates/logic/tests/claims.rs b/crates/logic/tests/claims.rs index 12a7d36..6b09755 100644 --- a/crates/logic/tests/claims.rs +++ b/crates/logic/tests/claims.rs @@ -265,6 +265,139 @@ fn a_bot_labeler_is_untrusted_without_a_lookup() { ); } +/// `opts` with the given logins allowed to hand work out whatever GitHub says of them. +fn opts_trusting(logins: &[&str], skip_self: bool) -> GithubSource { + let list = logins + .iter() + .map(|l| format!("\"{l}\"")) + .collect::>() + .join(","); + let json = format!( + r#"{{"broker":"B","repos":[],"skip_self":{skip_self},"labels":{{"org":"CycleFive","tag":"claude","trusted_labelers":[{list}]}}}}"# + ); + serde_json::from_str(&json).unwrap() +} + +#[test] +fn an_allowlisted_bot_is_trusted_without_a_lookup() { + let f = new_issue_feed("cycle-five-muse[bot]"); + let o = opts_trusting(&["Cycle-Five-Muse[bot]"], true); + let p = run_with(&f, &o, None).unwrap(); + let r = the_claim_record(&p); + assert_eq!(r.actor, "cycle-five-muse[bot]"); + assert_eq!(tags(r), ["routed:assigned"]); + assert!(p.state.claims[KEY7].trusted); + assert!( + !f.calls().iter().any(|c| c.contains("/collaborators/")), + "{:?}", + f.calls() + ); + // Trusted means followed: the activity since the label was read. + assert!( + f.calls().iter().any(|c| c.contains("/issues/7/comments")), + "{:?}", + f.calls() + ); +} + +#[test] +fn a_bot_that_is_not_on_the_list_stays_untrusted() { + let f = new_issue_feed("some-other-app[bot]"); + let o = opts_trusting(&["cycle-five-muse[bot]"], true); + let p = run_with(&f, &o, None).unwrap(); + assert_eq!(tags(the_claim_record(&p)), ["untrusted-label"]); + assert!(!p.state.claims[KEY7].trusted); +} + +#[test] +fn a_login_that_only_starts_like_an_allowlisted_one_stays_untrusted() { + // "cycle-five-muse" (a person's login) is not "cycle-five-muse[bot]": it is looked up like anyone. + let f = new_issue_feed("cycle-five-muse"); + perm(&f, "cycle-five-muse", "read", "read"); + let o = opts_trusting(&["cycle-five-muse[bot]"], true); + let p = run_with(&f, &o, None).unwrap(); + assert_eq!(tags(the_claim_record(&p)), ["untrusted-label"]); +} + +#[test] +fn the_mailboxs_own_allowlisted_bot_claims_without_mail() { + // The agent labelled the item itself: nothing to tell it, but the item is followed. + let f = new_issue_feed("claudeduet[bot]"); + let o = opts_trusting(&["claudeduet[bot]"], true); + let p = run_with(&f, &o, None).unwrap(); + assert!(p.records.is_empty(), "{:?}", ids(&p.records)); + assert!(p.state.claims[KEY7].trusted); +} + +#[test] +fn an_allowlisted_bot_can_ask_for_review() { + let f = FakeFeed::strict(); + search_items(&f, &[item_json(R, 4, U, &["review:claude"], true)]); + events( + &f, + R, + 4, + &[labeled(510, "review:claude", "cycle-five-muse[bot]", L)], + ); + comments_since(&f, R, 4, L, "[]"); + f.on( + &format!("/repos/{R}/pulls/4/comments?since={L}&per_page=100&page=1"), + "[]", + ); + f.on(&format!("/repos/{R}/pulls/4/reviews?per_page=100&page=1"), "[]"); + let o = opts_trusting(&["cycle-five-muse[bot]"], true); + let p = run_with(&f, &o, None).unwrap(); + assert_eq!(tags(the_claim_record(&p)), ["routed:review"]); + assert!(p.state.claims["CycleFive/kharon#4"].trusted); +} + +#[test] +fn a_relabel_by_an_allowlisted_bot_turns_an_untrusted_claim_trusted() { + let f = FakeFeed::strict(); + let (u2, relabel) = ("2026-11-20T11:00:00Z", "2026-11-20T10:30:00Z"); + search_items(&f, &[item_json(R, 7, u2, &["assigned:claude"], false)]); + events( + &f, + R, + 7, + &[ + labeled(500, "assigned:claude", "some-other-app[bot]", L), + labeled(600, "assigned:claude", "cycle-five-muse[bot]", relabel), + ], + ); + comments_since(&f, R, 7, relabel, "[]"); + let prev = state_of(vec![(KEY7, claim(false, U, U, &[("assigned:claude", 500)]))]); + let o = opts_trusting(&["cycle-five-muse[bot]"], true); + let p = run_with(&f, &o, Some(prev)).unwrap(); + let r = the_claim_record(&p); + assert_eq!(r.id, "gh:CycleFive/kharon:claim:600"); + assert_eq!(tags(r), ["routed:assigned"]); + assert!(p.state.claims[KEY7].trusted); +} + +#[test] +fn editing_the_list_does_not_touch_labels_already_handled() { + // Trust is decided when a label event is handled. A claim that was untrusted stays so + // after its labeler is added to the list, and a trusted one stays trusted after its + // labeler is taken off, until the label is applied again or removed. + for (stored, list) in [(false, vec!["cycle-five-muse[bot]"]), (true, vec![])] { + let f = FakeFeed::strict(); + let u2 = "2026-11-20T11:00:00Z"; + search_items(&f, &[item_json(R, 7, u2, &["assigned:claude"], false)]); + events( + &f, + R, + 7, + &[labeled(500, "assigned:claude", "cycle-five-muse[bot]", L)], + ); + comments_since(&f, R, 7, U, "[]"); + let prev = state_of(vec![(KEY7, claim(stored, U, U, &[("assigned:claude", 500)]))]); + let p = run_with(&f, &opts_trusting(&list, true), Some(prev)).unwrap(); + assert!(p.records.is_empty(), "{:?}", ids(&p.records)); + assert_eq!(p.state.claims[KEY7].trusted, stored); + } +} + #[test] fn a_missing_labeler_is_untrusted() { let f = new_issue_feed("ghost"); diff --git a/crates/logic/tests/config.rs b/crates/logic/tests/config.rs index 6a958e7..5dcbb61 100644 --- a/crates/logic/tests/config.rs +++ b/crates/logic/tests/config.rs @@ -351,3 +351,69 @@ fn target_works_for_a_source_without_repos() { )); assert_eq!(g.target("github:G:o/a"), None); } + +#[test] +fn trusted_labelers_default_to_none() { + let c = Config::parse(&github(r#""labels":{"org":"o","tag":"t"}"#)).unwrap(); + let l = github_source(&c).labels.clone().unwrap(); + assert!(l.trusted_labelers.is_empty()); + assert!(!l.trusts("cycle-five-muse[bot]")); +} + +#[test] +fn trusted_labelers_match_a_whole_login_in_any_case() { + let c = Config::parse(&github( + r#""labels":{"org":"o","tag":"t","trusted_labelers":["cycle-five-muse[bot]","some-person"]}"#, + )) + .unwrap(); + let l = github_source(&c).labels.clone().unwrap(); + assert!(l.trusts("cycle-five-muse[bot]")); + assert!(l.trusts("Cycle-Five-Muse[bot]")); + assert!(l.trusts("some-person")); + assert!(!l.trusts("cycle-five-muse")); + assert!(!l.trusts("cycle-five-muse[bot]x")); + assert!(!l.trusts("")); +} + +#[test] +fn trusted_labelers_accept_a_login_and_a_bot_login() { + let longest = "a".repeat(39); + let c = Config::parse(&github(&format!( + r#""labels":{{"org":"o","tag":"t","trusted_labelers":["a[bot]","b","{longest}","{longest}[bot]"]}}"# + ))) + .unwrap(); + assert_eq!( + github_source(&c).labels.clone().unwrap().trusted_labelers.len(), + 4 + ); +} + +#[test] +fn trusted_labelers_are_checked() { + let forty = "a".repeat(40); + for bad in [ + "", + "has space", + "x[bot]y", + "a/b", + "[bot]", + "name[BOT]", + "a[bot][bot]", + "trailing[bot] ", + "\u{e9}", + "\u{540d}[bot]", + forty.as_str(), + ] { + let e = err(&github(&format!( + r#""labels":{{"org":"o","tag":"t","trusted_labelers":["{bad}"]}}"# + ))); + assert!(e.contains("labels.trusted_labelers"), "{bad:?}: {e}"); + } + let e = err(&github( + r#""labels":{"org":"o","tag":"t","trusted_labelers":["a-bot[bot]","A-Bot[bot]"]}"#, + )); + assert!( + e.contains("labels.trusted_labelers") && e.contains("duplicate"), + "{e}" + ); +} diff --git a/crates/worker/Cargo.toml b/crates/worker/Cargo.toml index 4a2b2ea..0c1484c 100644 --- a/crates/worker/Cargo.toml +++ b/crates/worker/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mailroom-worker" -version = "0.3.0" +version = "0.4.0" edition = "2021" license = "MIT" diff --git a/crates/worker/wrangler.example.jsonc b/crates/worker/wrangler.example.jsonc index 1273605..fdfe8bc 100644 --- a/crates/worker/wrangler.example.jsonc +++ b/crates/worker/wrangler.example.jsonc @@ -60,7 +60,9 @@ // Optional: also search a whole organisation for open items labelled // "assigned:" or (pull requests only) "review:". With this set, // "repos" may be empty. org: GitHub login; tag: 1-32 chars of a-z, 0-9, '-'. - "labels": { "org": "your-org", "tag": "claude" } + // Optional "trusted_labelers": logins ("name" or "name[bot]") whose labels count + // whatever access GitHub reports; an app's bot is untrusted unless listed here. + "labels": { "org": "your-org", "tag": "claude", "trusted_labelers": ["your-other-agent[bot]"] } } ] }, diff --git a/docs/superpowers/specs/2026-11-20-label-claims-design.md b/docs/superpowers/specs/2026-11-20-label-claims-design.md index ba25aec..76e4475 100644 --- a/docs/superpowers/specs/2026-11-20-label-claims-design.md +++ b/docs/superpowers/specs/2026-11-20-label-claims-design.md @@ -30,7 +30,6 @@ over to match, so the behaviour here is the shared one. - Watching every repository of the organisation for all activity. - Webhooks, or anything that pushes to an agent. Mailroom still never wakes anyone. - Trusting comment text. The trust check is about who applied the label, nothing else. -- An allowlist of trusted bots. See Constraints. - Replacing `review_label`, assignee or requested-reviewer routing. ## Anti-goals @@ -56,8 +55,8 @@ over to match, so the behaviour here is the shared one. - `GET /repos/{repo}/collaborators/{login}/permission` reports a person's access: `permission` is `admin`, `write`, `read` or `none`, and `role_name` adds `maintain` and `triage`. For a GitHub App's bot user it reports `none` (checked with - `cycle-five-muse[bot]`). So a label applied by another agent is untrusted. That is kept - on purpose: it stops one misled agent handing work to another. + `cycle-five-muse[bot]`). So a label applied by another agent is untrusted + unless the mailbox lists that agent's bot in `trusted_labelers` (see Trust). - The GitHub broker's `Feed` reads `/repos/` paths only. It must also allow `/search/issues` (brokers 0.5.0, deployed before this). - The inbox stores a record once per `id` (`INSERT OR IGNORE`): the first writer wins, and @@ -104,8 +103,15 @@ case, as GitHub does. A counted item the mailbox is tracking is a *claim*. The labeler of a `labeled` event is trusted when GitHub reports `permission` `admin` or `write`, or `role_name` `admin`, `maintain`, `write` or `triage`, for them on that -repository. Anything else is untrusted: a missing user (404), and any login that is not -plain letters, digits and hyphens, which covers every app and bot, without a lookup. Any +repository, or when their login is in the source's `labels.trusted_labelers` (added +2026-11-20 at Lothrop's request, after an agent's review request by label turned up as +untrusted: GitHub reports no role for an app, so this list is the only way an agent can +hand work to another). A listed login is trusted for both labels without a lookup; entries +are whole logins, `name` or `name[bot]`, matched in any case. Like a person's access, the +list is consulted when a label event is handled: editing it changes nothing for labels +already handled. Anything else is untrusted: +a missing user (404), and any unlisted login that is not plain letters, digits and +hyphens, which covers every other app and bot, without a lookup. Any other failure of the lookup fails the poll, which is retried; it never decides trust. Trust is kept per label and follows that label's newest `labeled` event. A claim is @@ -194,7 +200,7 @@ broker; a new mailroom against an old broker would only fail the labels target. - `assigned:` counts on issues and pull requests; `review:` only on pull requests. - Items already labelled at rollout get their mail on the first poll. -- Bots are never trusted labelers; no allowlist. +- A bot is a trusted labeler only when the source lists it; the list covers both labels, not `review:` alone. - The claim record has its own id (`claim:`), not the per-repo poll's `event:` id, so in a watched repository the plain `labeled` event may also appear as context. A shared id would let whichever poll ran first decide whether the record carries the `routed:` tag. diff --git a/door/package-lock.json b/door/package-lock.json index 497f095..7d0e007 100644 --- a/door/package-lock.json +++ b/door/package-lock.json @@ -1,12 +1,12 @@ { "name": "mailroom", - "version": "0.3.0", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mailroom", - "version": "0.3.0", + "version": "0.4.0", "license": "MIT", "dependencies": { "@cloudflare/workers-oauth-provider": "1.2.4" diff --git a/door/package.json b/door/package.json index 83e0978..e5a05f6 100644 --- a/door/package.json +++ b/door/package.json @@ -1,6 +1,6 @@ { "name": "mailroom", - "version": "0.3.0", + "version": "0.4.0", "private": true, "license": "MIT", "description": "Public door for mailroom: an OAuth-protected MCP address per agent, forwarding MCP to mailroom-core", diff --git a/door/src/auth.ts b/door/src/auth.ts index dcaab7e..6c98635 100644 --- a/door/src/auth.ts +++ b/door/src/auth.ts @@ -14,7 +14,7 @@ import { import { publicUrl, type Env } from "./env"; export const SCOPE = "mailroom"; -export const VERSION = "0.3.0"; +export const VERSION = "0.4.0"; export const DISCORD_AUTHORIZE = "https://discord.com/oauth2/authorize"; diff --git a/door/test/flow.test.ts b/door/test/flow.test.ts index d8690da..5b84c86 100644 --- a/door/test/flow.test.ts +++ b/door/test/flow.test.ts @@ -184,7 +184,7 @@ describe("address per agent", () => { }); it("serves a banner", async () => { - expect(await (await call(env(), "/")).text()).toBe(`mailroom 0.3.0: the MCP address of a mailbox is ${BASE}//mcp\n`); + expect(await (await call(env(), "/")).text()).toBe(`mailroom 0.4.0: the MCP address of a mailbox is ${BASE}//mcp\n`); }); it("keeps the authorization server metadata", async () => {