Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
6ff7e2a
feat(ap-core): hold verdict, path_patterns, approval/notify config, n…
chaodu-agent Nov 17, 2026
8c088d4
feat(ap-proxy): hold table, entry state machine, digest and HoldRec a…
chaodu-agent Nov 17, 2026
83bd421
feat(ap-proxy): hold path in the passthrough pipeline
chaodu-agent Nov 17, 2026
dc6d0d3
feat(ap-proxy): approval plane listener, Basic auth, CSRF and page
chaodu-agent Nov 17, 2026
d55811e
feat(ap-proxy): ntfy notifier for new hold entries
chaodu-agent Nov 17, 2026
24e73e8
feat(ap-proxy): reload ticker, SIGTERM drain and stage 2 black-box ma…
chaodu-agent Nov 17, 2026
ada1b03
test(ap-proxy): sentinel leak suite, refusal table and stage 2 docs
chaodu-agent Nov 17, 2026
1b419fb
chore: stage 2 CI convergence run, no fixes needed
chaodu-agent Nov 17, 2026
73046dd
fix(ap-proxy): shutdown cancels approved requests before forward_star…
chaodu-agent Nov 17, 2026
461ab9a
fix(ap-proxy): start claim and forward_started write are one step und…
chaodu-agent Nov 17, 2026
056c358
Merge origin/main into feat/muse-stage2
chaodu-agent Nov 17, 2026
4890dfa
fix(ap-proxy): close the caller-key echo and the escaped-unreserved h…
chaodu-agent Nov 17, 2026
d16a838
Merge origin/main into feat/muse-stage2
chaodu-agent Nov 17, 2026
6a14134
docs: sidecar matrix row count is 59 after the merge (59/59 PASS, pas…
chaodu-agent Nov 17, 2026
6f3e678
fix(ap-proxy,ap-core): ignore proxy env, re-check holds on reload and…
chaodu-agent Nov 17, 2026
e7818ad
fix(ap-proxy): approve reads the policy under the table lock and agai…
chaodu-agent Nov 17, 2026
8db9126
fix(ap-proxy): compare policy bytes, not mtime and length, on every read
chaodu-agent Nov 18, 2026
5f77c7f
fix: bind the startup policy snapshot to the bytes it was parsed from
chaodu-agent Nov 18, 2026
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
15 changes: 12 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ jobs:
- name: Clippy (stage1-probe)
run: cargo clippy -p ap-proxy --all-targets --features stage1-probe -- -D warnings

- name: Clippy (matrix-upstream)
run: cargo clippy -p ap-proxy --all-targets --features matrix-upstream,stage1-probe -- -D warnings

- name: Unit and integration tests
run: cargo test --workspace

Expand All @@ -56,6 +59,9 @@ jobs:
if grep -q __ap_test_panic target/release/auth-proxy; then
echo "panic-injection string found in the release auth-proxy"; exit 1
fi
if grep -q AP_TEST_HOLD_PAUSE target/release/auth-proxy; then
echo "hold-pause test hook string found in the release auth-proxy"; exit 1
fi
if grep -q AP_TEST_UPSTREAM_CA target/release/auth-proxy; then
echo "test hook strings found in the release auth-proxy"; exit 1
fi
Expand Down Expand Up @@ -83,13 +89,16 @@ jobs:
set -o pipefail
python3 tests/matrix/matrix.py --bin target/debug --json matrix.json | tee matrix.txt

- name: Passthrough matrix cargo target (Muse gate, stage 1)
run: cargo test -p ap-proxy --features matrix-upstream,stage1-probe --test matrix_passthrough
- name: Build the matrix binary without stage1-probe (separate target dir)
run: CARGO_TARGET_DIR=target/noprobe cargo build -p ap-proxy --features matrix-upstream

- name: Passthrough matrix cargo target (Muse gate; both builds)
run: AP_MATRIX_NOPROBE_BIN="$PWD/target/noprobe/debug" cargo test -p ap-proxy --features matrix-upstream,stage1-probe --test matrix_passthrough

- name: Passthrough matrix driver (writes matrix-pt.json and matrix-pt.txt)
run: |
set -o pipefail
python3 tests/matrix/passthrough.py --bin target/debug --json matrix-pt.json | tee matrix-pt.txt
python3 tests/matrix/passthrough.py --bin target/debug --noprobe-bin target/noprobe/debug --json matrix-pt.json | tee matrix-pt.txt

- name: Upload matrix results
if: always()
Expand Down
33 changes: 33 additions & 0 deletions Cargo.lock

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

18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,24 @@ The gate constrains the agent, not the Muse platform: Muse's egress holds the re
can call Discord directly. See `docs/design/muse-gated-passthrough.md`, `docs/runbooks/muse-stage1.md`
and `deploy/muse/pilot-policy.example.toml`.

## Muse gated passthrough (stage 2, pilot)

Stage 2 adds a third verdict, `hold`, for writes the owner wants to approve one by one. A held request
keeps its connection open. The gate tells the owner a request is waiting (a fixed text and a link, never
the content), the owner opens a separate approval page, and only an explicit approve forwards the request.
Deny, expiry (`hold_secs`), a caller who gives up, a policy reload that drops the identity, and shutdown
all end the request with a refusal and nothing sent upstream. The connection is the state: there is no
queue, and a restart forgets every held request.

The gate constrains the agent, not the Muse platform. Muse's egress holds the real Discord token and can
call Discord directly. A stolen caller key lets someone send requests as that identity (the per-identity
cap and the cooldown bound the prompt spam) and does not give them approval rights.

Not claimed: exactly-once delivery (if the request was forwarded and the response was lost, a retry can be
approved and forwarded again), protection against Muse itself, a measured end-to-end hold window through the
real front, or a measured disconnect signal through the front. See `docs/runbooks/muse-stage2.md`
and `docs/design/muse-gated-passthrough.md`.

## Features

Implemented and tested in Phase 1:
Expand Down
1 change: 1 addition & 0 deletions crates/ap-client/tests/roundtrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ async fn start_server(root: &Path, caller_sha: &str) -> Server {
let app = App::new(
cfg_path,
cfg,
&text,
root.join("tokens"),
ap_broker::expiry::file_in(&root.join("tokens")),
Arc::new(FileStore::new(root.join("secrets"))),
Expand Down
125 changes: 125 additions & 0 deletions crates/ap-core/src/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,64 @@ impl AuditRec {
}
}

/// Transitions a held request can write (design 3.9). The record type has no free-text field.
pub const HOLD_TRANSITIONS: &[&str] = &[
"held",
"approved",
"denied",
"expired",
"abandoned",
"superseded",
"dropped_on_reload",
"forward_started",
"completed",
"abandoned_after_approve",
"connect_failed",
"audit_unavailable",
"notify_failed",
];

/// One audit line for a transition of a held request. Every key is always present (null when it
/// has no value), so the key set is fixed. There is no field for a header value, a query, a body,
/// a key or a notification target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HoldRec {
/// The hold entry id, which names the request across its transitions.
pub request_id: String,
pub identity: String,
pub route: Option<String>,
pub method: String,
/// Route-relative path. Query and fragment are dropped and token segments redacted on write.
pub path: String,
/// Credential-blind digest of the outbound request (hex sha256).
pub digest: Option<String>,
/// One of [`HOLD_TRANSITIONS`].
pub transition: &'static str,
/// Approver identity, on decisions only.
pub approver: Option<String>,
pub code: Option<String>,
pub status: Option<u16>,
pub duration_ms: u64,
/// Whether the request carried an `Authorization` header.
pub auth_present: bool,
/// `scheme://host:port` the request goes to, on the `held` record only.
pub upstream: Option<String>,
/// The policy generation the request was admitted under, on the `held` record only.
pub policy_generation: Option<u64>,
}

impl HoldRec {
/// Serialize as one JSON line with a trailing newline. The path is cut to its path part and
/// its `webhooks`/`interactions` token segments are redacted here, so no caller has to.
pub fn to_json_line(&self) -> String {
let mut rec = self.clone();
rec.path = crate::canon::redact_path(&path_only(&rec.path));
let mut line = serde_json::to_string(&rec).unwrap_or_else(|_| "{}".to_string());
line.push('\n');
line
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -137,4 +195,71 @@ mod tests {
assert_eq!(v["code"], "policy_denied");
assert!(v["aws_target"].is_null());
}

fn hold_sample() -> HoldRec {
HoldRec {
request_id: "0123abcd".into(),
identity: "muse".into(),
route: Some("discord".into()),
method: "POST".into(),
path: "/channels/1/messages?x=1".into(),
digest: Some("ab".repeat(32)),
transition: "held",
approver: None,
code: None,
status: None,
duration_ms: 3,
auth_present: true,
upstream: Some("https://discord.example.test:443".into()),
policy_generation: Some(1),
}
}

#[test]
fn hold_json_keys_are_exactly_the_allowed_set() {
let v: serde_json::Value =
serde_json::from_str(hold_sample().to_json_line().trim_end()).unwrap();
let mut keys: Vec<&str> = v.as_object().unwrap().keys().map(String::as_str).collect();
keys.sort_unstable();
assert_eq!(
keys,
vec![
"approver",
"auth_present",
"code",
"digest",
"duration_ms",
"identity",
"method",
"path",
"policy_generation",
"request_id",
"route",
"status",
"transition",
"upstream",
]
);
}

#[test]
fn hold_line_drops_query_and_redacts_tokens() {
let mut r = hold_sample();
r.path = "/webhooks/123/SECRETTOKEN/messages?wait=true#f".into();
let line = r.to_json_line();
assert!(!line.contains("SECRETTOKEN"));
assert!(!line.contains("wait=true"));
assert!(line.contains("/webhooks/123/<redacted>/messages"));
assert_eq!(line.matches('\n').count(), 1);
}

#[test]
fn every_hold_transition_serializes() {
for t in HOLD_TRANSITIONS {
let mut r = hold_sample();
r.transition = t;
let v: serde_json::Value = serde_json::from_str(r.to_json_line().trim_end()).unwrap();
assert_eq!(v["transition"], *t);
}
}
}
76 changes: 76 additions & 0 deletions crates/ap-core/src/canon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,21 @@ const MAX_DECODE_LAYERS: usize = 4;
/// percent-encode (non-ASCII, controls, space, DEL, `"`, `<`, `>`, backtick, `{`, `}`) are
/// refused too, because for those the matched path would not be the path that is sent.
pub fn path_ambiguous(p: &str) -> bool {
path_ambiguous_with(p, false)
}

/// [`path_ambiguous`] plus one more refusal, used where a `hold` grant can be overridden by a
/// broader allow match (the passthrough pipeline): a percent-escape of an RFC 3986 unreserved
/// byte (`A-Z a-z 0-9 - . _ ~`), in any decode layer. `%6D` and `m` name the same resource, and
/// hold patterns compare raw bytes, so the spelling would let a caller pick the verdict. Refusing
/// keeps the form that policy matches byte-identical to the form that is sent and shown. The
/// sidecar pipeline has no hold verdict and no precedence between grants, so an unmatched spelling
/// there is a plain `no_grant`, and it keeps accepting these escapes.
pub fn path_ambiguous_passthrough(p: &str) -> bool {
path_ambiguous_with(p, true)
}

fn path_ambiguous_with(p: &str, refuse_unreserved: bool) -> bool {
if p.contains('\\')
|| p.bytes()
.any(|b| b <= 0x20 || b >= 0x7f || b"\"<>`{}".contains(&b))
Expand Down Expand Up @@ -149,6 +164,7 @@ pub fn path_ambiguous(p: &str) -> bool {
if b < 0x20
|| b == 0x7f
|| matches!(b, b'.' | b'/' | b'\\')
|| (refuse_unreserved && is_unreserved(b))
|| (depth >= 2 && b == b';')
{
return true;
Expand All @@ -173,6 +189,66 @@ pub fn path_ambiguous(p: &str) -> bool {
(0..cur.len()).any(|i| cur[i] == b'%' && hex_pair(&cur, i).is_some())
}

/// RFC 3986 section 2.3 unreserved characters.
fn is_unreserved(b: u8) -> bool {
b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')
}

/// Most percent-decode layers a caller-key search looks through. Deeper than the path check
/// goes, so the search never gives up before `path_ambiguous` would have.
const KEY_SEARCH_LAYERS: usize = MAX_DECODE_LAYERS + 4;

/// True when `s` (a route-relative path or a query string) carries an `apk_` caller key, in
/// any percent-encoded spelling.
///
/// `s` is searched raw, then after each percent-decode layer up to a fixed point (hex digits in
/// either case, decoded by value like [`path_ambiguous`]). On every layer the match is ASCII
/// case-insensitive and finds either the authenticated `key`'s 64 hex digits (the `apk_` prefix
/// may itself be encoded, so the digits are the needle) or any well-formed `apk_<64 hex>` key.
/// A string still decodable after [`KEY_SEARCH_LAYERS`] layers counts as carrying one: the
/// answer is fail-closed, never "not found". The key is never copied into a message.
pub fn echoes_caller_key(s: &str, key: &str) -> bool {
let digits = key.strip_prefix("apk_").unwrap_or(key).as_bytes();
let mut cur = s.as_bytes().to_vec();
for _ in 0..=KEY_SEARCH_LAYERS {
if has_key_text(&cur, digits) {
return true;
}
let mut out = Vec::with_capacity(cur.len());
let mut decoded = false;
let mut i = 0;
while i < cur.len() {
if cur[i] == b'%' {
if let Some(b) = hex_pair(&cur, i) {
out.push(b);
decoded = true;
i += 3;
continue;
}
}
out.push(cur[i]);
i += 1;
}
if !decoded {
return false;
}
cur = out;
}
true
}

fn has_key_text(hay: &[u8], digits: &[u8]) -> bool {
if !digits.is_empty()
&& hay
.windows(digits.len())
.any(|w| w.eq_ignore_ascii_case(digits))
{
return true;
}
hay.windows(4 + 64)
.any(|w| w[..4].eq_ignore_ascii_case(b"apk_") && w[4..].iter().all(u8::is_ascii_hexdigit))
}

fn hex_pair(b: &[u8], i: usize) -> Option<u8> {
let d = |j: usize| b.get(j).and_then(|c| (*c as char).to_digit(16));
u8::try_from(d(i + 1)? * 16 + d(i + 2)?).ok()
Expand Down
Loading
Loading