Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 22 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,12 @@ Tags the poller adds itself:
| --- | --- |
| `routed:mention` | Discord: the message mentions the agent's bot. GitHub: the text contains `@<app slug>`. |
| `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:<tag>` 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:<tag>` on the PR (see Work handed over by label). |
| `routed:assigned` | GitHub: the agent is an assignee, or a trusted labeler put `assigned:<tag>` 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:<tag>` 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
Expand Down Expand Up @@ -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:<tag>` or `review:<tag>` (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. |
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion crates/logic/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "mailroom-logic"
version = "0.3.0"
version = "0.4.0"
edition = "2021"
license = "MIT"

Expand Down
17 changes: 13 additions & 4 deletions crates/logic/src/claims.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<bool, PollError> {
/// 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<bool, PollError> {
if routing.trusts(login) {
return Ok(true);
}
if login.is_empty() || !login.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
return Ok(false);
}
Expand Down Expand Up @@ -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
}
Expand Down
27 changes: 27 additions & 0 deletions crates/logic/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ pub struct LabelRouting {
pub org: String,
/// The tag in `assigned:<tag>` and `review:<tag>`.
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<String>,
}

impl LabelRouting {
Expand All @@ -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.
Expand Down Expand Up @@ -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('/'));
Expand Down
133 changes: 133 additions & 0 deletions crates/logic/tests/claims.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>()
.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");
Expand Down
66 changes: 66 additions & 0 deletions crates/logic/tests/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
);
}
2 changes: 1 addition & 1 deletion crates/worker/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "mailroom-worker"
version = "0.3.0"
version = "0.4.0"
edition = "2021"
license = "MIT"

Expand Down
4 changes: 3 additions & 1 deletion crates/worker/wrangler.example.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@
// Optional: also search a whole organisation for open items labelled
// "assigned:<tag>" or (pull requests only) "review:<tag>". 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]"] }
}
]
},
Expand Down
Loading
Loading