feat(runner): write ACPX credential refreshes back to the host's file (#23340)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Runner's credential observer watches an ACPX Codex or Grok
session's isolated login and reports refreshes to Core
> - The execution host's own copy of the login stays at the token the
session started from, so it is spent once the provider rotates its
refresh token
> - With write-back rules in place (#23339), the observer can return
each refresh to a host file the Runner is given
> - This pull request has the observer write refreshes back to the file
named in `PAPERCLIP_ACPX_AUTH_JSON_FILE`
> - The benefit is that a host's login file stays current through every
session that uses it

## Linked Issues or Issue Description

**Subsystem affected**

Paperclip Runner (`runner-core`): the credential observer and the native
provider backend's pre-stop poll.

**Problem or motivation**

A refresh an ACPX Codex or Grok session makes stays in the Runner's
isolated home. A host that keeps the login in its own file never
receives it, and the next session starts from a token the provider has
already rotated.

**Proposed solution**

When the Runner process names a host file, the observer writes each
refresh back to it through the write-back rules, during the session and
at close.

**Alternatives considered**

Write back only once, at session close. Rejected: a long session can
refresh several times, and a crash before close would lose every rotated
token.

**Roadmap alignment**

None in `ROADMAP.md`; this extends the Runner's existing credential
observer.

**Additional context**

Builds on #23339. Nothing names a host file until the Runner seeds
sessions from one, in the change stacked above this.

## What Changed

- With `PAPERCLIP_ACPX_AUTH_JSON_FILE` set, the observer writes each
refresh back during the session and at close (the provider's
`auth-refresh.json` handoff). Each poll also offers a retained
`auth-refresh.json` to the rules even while `auth.json` exists, so a
refresh made while an old provider shut down still reaches the host file
after a warm `run.attach` or idle restart reseeds the home. Write-back
does not wait for an update event's acknowledgement, and a binding
without the `observeCredentials` opt-in writes back without emitting
events.
- The host file seeds the observer's baseline, so a refresh during
provider startup is still caught.
- A host file that changes during a replacement is decided again at
once, up to three times. A kept decision holds only while the host file
keeps its stamp, so a repaired or replaced host file is compared again.
- A failed write-back, or a host file that keeps changing, fails the
poll, and with it the command or turn, with an error that carries no
credential. The poll before a stop ignores that failure so the provider
still stops; the poll after it reports.
- A recovered Runner follows the host file it is given now: it adopts a
new one, switches to a changed one, and stops writing back when none is
named. Revision, baseline and any pending event are unchanged.
- A host file is refused for any session other than an ACPX Codex or
Grok one.
- Saved observer state gains two optional fields (`host_file`,
`silent`), omitted when unset, so existing state loads unchanged.
- No code comments are added, per CONTRIBUTING.md.

## Verification

- `cargo test -p paperclip-runner-core --lib credential_`: 28 passed.
New observer tests cover write-back during the session and at close with
and without events; a shutdown refresh written back after a restart
reseeds `auth.json`; a failed write-back that fails the poll without the
credential in the error and succeeds once the host file is back; a host
file repaired after a kept decision receiving the refresh; the binding's
path checks, provider checks and seeded baseline; recovery adopting,
switching and dropping a host file; and a native Codex home refused.
- `cargo test -p paperclip-runner-core --test native_provider_backend`:
47 passed.
- `cargo fmt -p paperclip-runner-core -- --check`.
- Not run locally: clippy and the full Runner workspace tests. CI runs
them.

## Risks

- A host file that cannot be written, for example on a full or read-only
volume, fails the command or turn that observed it instead of being
logged. Such a host is already broken, and failing visibly keeps a
rotated refresh token from being lost without notice.
- Copies of one sign-in share its refresh token wherever they live. When
two copies refresh separately, the later refresh can fail that command
or turn, or the provider can revoke the sign-in and the user signs in
again.
- On non-Unix hosts write-back is unsupported, like the credential
observer itself.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, cargo runs) and extended thinking.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 15:55:37 +00:00
1 parent 2d745cf432
commit 8607b27e39
4 files changed
+771 -332

No files matched your search

@@ -12,6 +12,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use crate::credential_write_back::{self, WriteBack, ACPX_AUTH_JSON_FILE_ENV};
use crate::durable::{
create_private_temporary_file, open_private_regular_file, verify_private_directory,
DurableRunnerError, EventPriority, PolledEvent,
@@ -22,6 +23,9 @@ const SCHEMA: &str = "paperclip.runner.credential-observer.v1";
const MAX_BYTES: u64 = 256 * 1024;
const MAX_REVISION: u64 = 9_007_199_254_740_991;
const SCAN_INTERVAL: Duration = Duration::from_secs(1);
const WRITE_BACK_ATTEMPTS: usize = 3;
const KEPT_DECISION_TTL: Duration = Duration::from_secs(60);
const KEPT_DECISIONS: usize = 2;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
@@ -41,6 +45,10 @@ struct State {
revision: u64,
armed: bool,
pending: Option<PolledEvent>,
#[serde(default, skip_serializing_if = "Option::is_none")]
host_file: Option<PathBuf>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
silent: bool,
}
pub(crate) struct CredentialObserver {
@@ -51,6 +59,8 @@ pub(crate) struct CredentialObserver {
watcher: Option<RecommendedWatcher>,
dirty: Arc<AtomicBool>,
last_scan: Instant,
now_ms: fn() -> f64,
written: Vec<(String, Option<credential_write_back::HostStamp>, Instant)>,
}
impl CredentialObserver {
@@ -63,10 +73,19 @@ impl CredentialObserver {
watcher: None,
dirty: Arc::new(AtomicBool::new(true)),
last_scan: Instant::now() - SCAN_INTERVAL,
now_ms: credential_write_back::now_ms,
written: Vec::new(),
}
}
pub(crate) fn restore(&mut self) -> Result<(), DurableRunnerError> {
self.restore_with_host_file(host_credential_file)
}
fn restore_with_host_file(
&mut self,
host_file: impl FnOnce() -> Result<Option<PathBuf>, DurableRunnerError>,
) -> Result<(), DurableRunnerError> {
if self.loaded {
return Ok(());
}
@@ -104,20 +123,63 @@ impl CredentialObserver {
.as_ref()
.is_some_and(|s| !valid_digest(&s.identity) || !valid_digest(&s.fingerprint))
|| state.pending.as_ref().is_some_and(|event| {
event != &update_event(&state.provider, state.revision) || state.revision == 0
event != &update_event(&state.provider, state.revision)
|| state.revision == 0
|| state.silent
})
|| state
.host_file
.as_ref()
.is_some_and(|path| !path.is_absolute())
{
return Err(observer_error("state has an invalid session binding"));
}
self.state = Some(state);
self.reconcile_host_file(host_file()?)?;
self.loaded = true;
self.watch_directory();
Ok(())
}
fn reconcile_host_file(
&mut self,
host_file: Option<PathBuf>,
) -> Result<(), DurableRunnerError> {
let Some(state) = self.state.as_ref() else {
return Ok(());
};
if state.host_file == host_file {
return Ok(());
}
if host_file.is_some() && !is_acpx_credential_path(&state.provider, &state.path) {
return Err(observer_error(
"credential file requires a Codex or Grok ACPX session",
));
}
let mut next = state.clone();
next.host_file = host_file;
self.save(&next)?;
self.state = Some(next);
self.written.clear();
self.dirty.store(true, Ordering::Relaxed);
Ok(())
}
pub(crate) fn configure(&mut self, payload: &Value) -> Result<(), DurableRunnerError> {
self.restore()?;
if self.state.is_some() || payload.get("observeCredentials") != Some(&Value::Bool(true)) {
if self.state.is_some() {
return Ok(());
}
self.configure_with_host_file(payload, host_credential_file()?)
}
fn configure_with_host_file(
&mut self,
payload: &Value,
host_file: Option<PathBuf>,
) -> Result<(), DurableRunnerError> {
let observe = payload.get("observeCredentials") == Some(&Value::Bool(true));
if !observe && host_file.is_none() {
return Ok(());
}
let provider = &payload["provider"];
@@ -125,7 +187,14 @@ impl CredentialObserver {
.get("kind")
.or_else(|| provider.get("provider"))
.and_then(Value::as_str);
let (name, path, seed) = match kind {
let acpx_file_agent =
kind == Some("acpx") && (provider["agent"] == "grok" || provider["agent"] == "codex");
if host_file.is_some() && kind.is_some() && !acpx_file_agent {
return Err(observer_error(
"credential file requires a Codex or Grok ACPX session",
));
}
let (name, path, mut seed) = match kind {
Some("codex") => {
let Some(home) = std::env::var_os("CODEX_HOME") else {
return Ok(());
@@ -158,8 +227,14 @@ impl CredentialObserver {
.join(acpx_session_directory(session))
.join(format!("{name}-home"))
.join("auth.json");
let seed = if name == "grok" {
std::env::var("PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET").ok()
let seed = if let Some(file) = host_file.as_deref() {
credential_write_back::read_host_credential(file)
.ok()
.map(|(bytes, _)| bytes)
} else if name == "grok" {
std::env::var("PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET")
.ok()
.map(String::into_bytes)
} else {
None
};
@@ -170,7 +245,6 @@ impl CredentialObserver {
if !path.is_absolute() {
return Err(observer_error("credential home is not absolute"));
}
let mut seed = seed.map(String::into_bytes);
let snapshot = seed
.as_ref()
.and_then(|bytes| parse_snapshot(name, bytes))
@@ -187,6 +261,8 @@ impl CredentialObserver {
revision: 0,
armed: false,
pending: None,
host_file,
silent: !observe,
};
self.save(&state)?;
self.state = Some(state);
@@ -213,11 +289,9 @@ impl CredentialObserver {
pub(crate) fn poll(&mut self, force: bool) -> Result<(), DurableRunnerError> {
self.restore()?;
if self
.state
.as_ref()
.is_none_or(|state| !state.armed || state.pending.is_some())
{
if self.state.as_ref().is_none_or(|state| {
!state.armed || (state.host_file.is_none() && (state.pending.is_some() || state.silent))
}) {
return Ok(());
}
if !force
@@ -229,18 +303,35 @@ impl CredentialObserver {
self.last_scan = Instant::now();
self.watch_directory();
let state = self.state.as_ref().expect("configured observer");
let snapshot = read_snapshot(&state.provider, &state.path).or_else(|| {
fs::symlink_metadata(&state.path)
.is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound)
.then(|| {
read_snapshot(
&state.provider,
&state.path.with_file_name("auth-refresh.json"),
)
})
let auth = read_private_credential(&state.path);
let auth_missing = auth.is_none()
&& fs::symlink_metadata(&state.path)
.is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound);
let refresh = (auth_missing || state.host_file.is_some())
.then(|| read_private_credential(&state.path.with_file_name("auth-refresh.json")))
.flatten();
let (mut bytes, mut retained) = if auth_missing {
(refresh, None)
} else {
(auth, refresh)
};
let host_file = state.host_file.clone();
let provider = state.provider.clone();
let written = host_file.map_or(Ok(()), |host_file| {
[retained.as_deref(), bytes.as_deref()]
.into_iter()
.flatten()
.try_for_each(|candidate| self.write_back(&provider, candidate, &host_file))
});
let Some(snapshot) = snapshot else {
let snapshot = bytes
.as_deref()
.and_then(|bytes| parse_snapshot(&provider, bytes));
for buffer in [bytes.as_mut(), retained.as_mut()].into_iter().flatten() {
buffer.fill(0);
}
written?;
let state = self.state.as_ref().expect("configured observer");
let Some(snapshot) = snapshot.filter(|_| !state.silent && state.pending.is_none()) else {
return Ok(());
};
if state.snapshot.as_ref() == Some(&snapshot) {
@@ -261,6 +352,50 @@ impl CredentialObserver {
Ok(())
}
fn write_back(
&mut self,
provider: &str,
bytes: &[u8],
host_file: &Path,
) -> Result<(), DurableRunnerError> {
let digest = format!("{:x}", Sha256::digest(bytes));
if self.written.iter().any(|(written, stamp, decided)| {
*written == digest
&& decided.elapsed() < KEPT_DECISION_TTL
&& stamp.as_ref().is_none_or(|stamp| {
credential_write_back::host_stamp(host_file).as_ref() == Some(stamp)
})
}) {
return Ok(());
}
for _ in 0..WRITE_BACK_ATTEMPTS {
match credential_write_back::write_back(provider, bytes, host_file, (self.now_ms)()) {
Ok(WriteBack::Kept(stamp)) => {
self.written.retain(|(written, ..)| *written != digest);
if self.written.len() == KEPT_DECISIONS {
self.written.remove(0);
}
self.written.push((digest, stamp, Instant::now()));
return Ok(());
}
Ok(WriteBack::Written) => {
self.written.clear();
return Ok(());
}
Ok(WriteBack::Raced) => {}
Err(error) => {
return Err(observer_error(&format!(
"{provider} write-back to the host credential file failed ({:?})",
error.kind()
)))
}
}
}
Err(observer_error(&format!(
"{provider} write-back to the host credential file failed: the file kept changing"
)))
}
pub(crate) fn pending(&self) -> Option<PolledEvent> {
self.state.as_ref().and_then(|state| state.pending.clone())
}
@@ -320,6 +455,17 @@ fn update_event(provider: &str, revision: u64) -> PolledEvent {
}
}
fn is_acpx_credential_path(provider: &str, path: &Path) -> bool {
let home = path.parent();
home.and_then(Path::file_name)
.is_some_and(|name| name == format!("{provider}-home").as_str())
&& home
.and_then(Path::parent)
.and_then(Path::parent)
.and_then(Path::file_name)
.is_some_and(|name| name == "acpx")
}
fn acpx_session_directory(session: &str) -> String {
let readable: String = session
.chars()
@@ -393,8 +539,32 @@ fn parse_snapshot(provider: &str, bytes: &[u8]) -> Option<Snapshot> {
})
}
#[cfg(unix)]
fn read_snapshot(provider: &str, path: &Path) -> Option<Snapshot> {
let mut bytes = read_private_credential(path)?;
let snapshot = parse_snapshot(provider, &bytes);
bytes.fill(0);
snapshot
}
fn host_credential_file() -> Result<Option<PathBuf>, DurableRunnerError> {
parse_host_credential_file(std::env::var_os(ACPX_AUTH_JSON_FILE_ENV))
}
fn parse_host_credential_file(
value: Option<std::ffi::OsString>,
) -> Result<Option<PathBuf>, DurableRunnerError> {
let Some(path) = value.filter(|value| !value.is_empty()) else {
return Ok(None);
};
let path = PathBuf::from(path);
if !path.is_absolute() {
return Err(observer_error("credential file is not absolute"));
}
Ok(Some(path))
}
#[cfg(unix)]
fn read_private_credential(path: &Path) -> Option<Vec<u8>> {
use rustix::fs::{open, openat, Mode, OFlags};
use std::os::unix::fs::MetadataExt;
let parent = path.parent()?;
@@ -440,320 +610,19 @@ fn read_snapshot(provider: &str, path: &Path) -> Option<Snapshot> {
&& before.mtime() == after.mtime()
&& before.mtime_nsec() == after.mtime_nsec()
});
let snapshot = if read.is_ok() && stable {
parse_snapshot(provider, &bytes)
if read.is_ok() && stable {
Some(bytes)
} else {
bytes.fill(0);
None
};
bytes.fill(0);
snapshot
}
}
#[cfg(not(unix))]
fn read_snapshot(_provider: &str, _path: &Path) -> Option<Snapshot> {
fn read_private_credential(_path: &Path) -> Option<Vec<u8>> {
None
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::os::unix::fs::{symlink, PermissionsExt};
struct Fixture {
root: PathBuf,
observer: CredentialObserver,
}
impl Fixture {
fn new(provider: &str, seed: &Value) -> Self {
let root =
std::env::temp_dir().join(format!("credential-observer-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();
let root = fs::canonicalize(root).unwrap();
let mut observer = CredentialObserver::new(&root, "session");
observer.loaded = true;
observer.state = Some(State {
schema: SCHEMA.to_owned(),
session_id: "session".to_owned(),
provider: provider.to_owned(),
path: root.join("auth.json"),
snapshot: parse_snapshot(provider, &serde_json::to_vec(seed).unwrap()),
revision: 0,
armed: false,
pending: None,
});
observer.save(observer.state.as_ref().unwrap()).unwrap();
Self { root, observer }
}
fn write(&self, name: &str, value: &Value) {
let path = self.root.join(name);
fs::write(&path, serde_json::to_vec(value).unwrap()).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
}
}
impl Drop for Fixture {
fn drop(&mut self) {
self.observer.watcher = None;
let _ = fs::remove_dir_all(&self.root);
}
}
fn codex(marker: &str) -> Value {
json!({"tokens":{"account_id":"account-1", "access_token":format!("access-{marker}"),
"refresh_token":format!("refresh-{marker}"), "id_token":format!("identity-{marker}")}, "last_refresh":"metadata"})
}
fn grok(marker: &str) -> Value {
json!({"https://issuer.example::12345678-1234-1234-1234-123456789abc":{
"key":format!("access-{marker}"), "refresh_token":format!("refresh-{marker}"), "expires_at":1234}})
}
#[test]
fn refresh_is_durable_replayable_content_free_and_monotonic() {
let mut f = Fixture::new("codex", &codex("before"));
f.write("auth.json", &codex("before"));
f.observer.activate().unwrap();
assert!(f.observer.pending().is_none());
f.write("auth.json", &codex("after"));
f.observer.poll(true).unwrap();
let event = f.observer.pending().unwrap();
assert_eq!(event, update_event("codex", 1));
let persisted = fs::read_to_string(f.root.join(STATE_FILE)).unwrap();
for secret in [
"access-before",
"refresh-before",
"identity-before",
"access-after",
"refresh-after",
"identity-after",
] {
assert!(!persisted.contains(secret));
assert!(!event.payload.to_string().contains(secret));
}
let mut recovered = CredentialObserver::new(&f.root, "session");
recovered.restore().unwrap();
assert_eq!(recovered.pending(), Some(event));
f.write("auth.json", &codex("newest"));
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event("codex", 1)));
recovered.acknowledge(1).unwrap();
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event("codex", 2)));
recovered.acknowledge(1).unwrap();
recovered.poll(true).unwrap();
assert!(recovered.pending().is_none());
assert_eq!(recovered.state.as_ref().unwrap().revision, 2);
}
#[test]
fn directory_watch_handles_atomic_replacement() {
let mut f = Fixture::new("codex", &codex("before"));
f.write("auth.json", &codex("before"));
f.observer.activate().unwrap();
f.observer.dirty.store(false, Ordering::Relaxed);
f.write("auth.tmp", &codex("after"));
fs::rename(f.root.join("auth.tmp"), f.root.join("auth.json")).unwrap();
let deadline = Instant::now() + Duration::from_secs(3);
while f.observer.pending().is_none() && Instant::now() < deadline {
f.observer.poll(false).unwrap();
std::thread::sleep(Duration::from_millis(10));
}
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
}
#[test]
fn periodic_reread_works_without_native_notifications() {
let mut f = Fixture::new("codex", &codex("before"));
f.write("auth.json", &codex("before"));
f.observer.activate().unwrap();
f.write("auth.json", &codex("after"));
f.observer.watcher = None;
f.observer.dirty.store(false, Ordering::Relaxed);
f.observer.last_scan = Instant::now() - SCAN_INTERVAL;
f.observer.poll(false).unwrap();
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
}
#[test]
fn ignores_metadata_partial_writes_and_deletion() {
let mut f = Fixture::new("codex", &codex("before"));
f.write("auth.json", &codex("before"));
f.observer.activate().unwrap();
let mut metadata = codex("before");
metadata["last_refresh"] = json!("new metadata");
f.write("auth.json", &metadata);
f.observer.poll(true).unwrap();
assert!(f.observer.pending().is_none());
fs::write(f.root.join("auth.json"), "{partial").unwrap();
f.observer.poll(true).unwrap();
assert!(f.observer.pending().is_none());
fs::remove_file(f.root.join("auth.json")).unwrap();
f.observer.poll(true).unwrap();
f.write("auth.json", &codex("after"));
f.observer.poll(true).unwrap();
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
}
#[test]
fn account_changes_and_later_refreshes_survive_recovery_without_exposing_identity() {
for provider in ["codex", "grok"] {
let original = if provider == "codex" {
codex("before")
} else {
grok("before")
};
let mut f = Fixture::new(provider, &original);
f.write("auth.json", &original);
f.observer.activate().unwrap();
let mut changed = original.clone();
let account = if provider == "codex" {
changed["tokens"]["account_id"] = json!("different-account");
"different-account"
} else {
let auth = changed
.as_object()
.unwrap()
.values()
.next()
.unwrap()
.clone();
changed =
json!({"https://issuer.example::87654321-4321-4321-4321-cba987654321": auth});
"87654321-4321-4321-4321-cba987654321"
};
f.write("auth.json", &changed);
f.observer.poll(true).unwrap();
assert_eq!(f.observer.pending(), Some(update_event(provider, 1)));
let persisted = fs::read_to_string(f.root.join(STATE_FILE)).unwrap();
assert!(!persisted.contains(account));
assert!(!f
.observer
.pending()
.unwrap()
.payload
.to_string()
.contains(account));
let mut recovered = CredentialObserver::new(&f.root, "session");
recovered.restore().unwrap();
assert_eq!(recovered.pending(), Some(update_event(provider, 1)));
if provider == "codex" {
changed["tokens"]["access_token"] = json!("refreshed-access");
} else {
changed
.as_object_mut()
.unwrap()
.values_mut()
.next()
.unwrap()["key"] = json!("refreshed-access");
}
f.write("auth.json", &changed);
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event(provider, 1)));
recovered.acknowledge(1).unwrap();
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event(provider, 2)));
recovered.acknowledge(1).unwrap();
recovered.poll(true).unwrap();
assert!(recovered.pending().is_none());
f.write("auth.json", &original);
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event(provider, 3)));
}
}
#[test]
fn grok_seed_catches_pre_start_refresh_and_close_handoff() {
let mut f = Fixture::new("grok", &grok("seed"));
f.observer.poll(true).unwrap();
assert!(f.observer.pending().is_none());
f.write("auth.json", &grok("startup"));
f.observer.activate().unwrap();
assert_eq!(f.observer.pending(), Some(update_event("grok", 1)));
f.observer.acknowledge(1).unwrap();
f.write("auth-refresh.json", &grok("close"));
fs::remove_file(f.root.join("auth.json")).unwrap();
f.observer.poll(true).unwrap();
assert_eq!(f.observer.pending(), Some(update_event("grok", 2)));
}
#[test]
fn codex_close_handoff_preserves_shutdown_refresh() {
let mut f = Fixture::new("codex", &codex("seed"));
f.write("auth.json", &codex("seed"));
f.observer.activate().unwrap();
assert!(f.observer.pending().is_none());
f.write("auth-refresh.json", &codex("close"));
fs::remove_file(f.root.join("auth.json")).unwrap();
f.observer.poll(true).unwrap();
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
f.observer.acknowledge(1).unwrap();
f.observer.poll(true).unwrap();
assert!(f.observer.pending().is_none());
}
#[test]
fn rejects_symlinks_unsafe_permissions_and_oversized_stores() {
let f = Fixture::new("codex", &codex("seed"));
f.write("auth.json", &codex("seed"));
symlink(f.root.join("auth.json"), f.root.join("symlink.json")).unwrap();
assert!(read_snapshot("codex", &f.root.join("symlink.json")).is_none());
symlink(&f.root, f.root.join("parent-link")).unwrap();
assert!(read_snapshot("codex", &f.root.join("parent-link/auth.json")).is_none());
fs::set_permissions(f.root.join("auth.json"), fs::Permissions::from_mode(0o644)).unwrap();
assert!(read_snapshot("codex", &f.root.join("auth.json")).is_none());
fs::set_permissions(f.root.join("auth.json"), fs::Permissions::from_mode(0o600)).unwrap();
fs::write(f.root.join("auth.json"), vec![b' '; MAX_BYTES as usize + 1]).unwrap();
assert!(read_snapshot("codex", &f.root.join("auth.json")).is_none());
}
#[test]
fn observer_requires_opt_in_and_rejects_cross_session_recovery() {
let f = Fixture::new("codex", &codex("seed"));
let mut wrong_session = CredentialObserver::new(&f.root, "different-session");
assert!(wrong_session.restore().is_err());
let path = f.root.join("unused");
fs::create_dir(&path).unwrap();
let mut disabled = CredentialObserver::new(&path, "session");
disabled
.configure(&json!({"provider":{"kind":"codex"}}))
.unwrap();
assert!(disabled.state.is_none());
disabled
.configure(&json!({"observeCredentials":true,"provider":{"kind":"opencode"}}))
.unwrap();
assert!(disabled.state.is_none());
}
#[test]
fn fresh_acpx_observers_create_a_private_runtime_directory() {
let f = Fixture::new("codex", &codex("seed"));
for provider in ["codex", "grok"] {
let state_dir = f.root.join(provider);
fs::create_dir(&state_dir).unwrap();
fs::set_permissions(&state_dir, fs::Permissions::from_mode(0o700)).unwrap();
let runtime = state_dir.join("runtime");
assert!(!runtime.exists());
let mut observer = CredentialObserver::new(&state_dir, "session");
observer.configure(&json!({"observeCredentials":true,"provider":{
"kind":"acpx", "agent":provider, "runtimeDirectory":runtime, "normalizedSessionId":"session"
}})).unwrap();
assert_eq!(
fs::metadata(&runtime).unwrap().permissions().mode() & 0o777,
0o700
);
assert_eq!(observer.state.as_ref().unwrap().provider, provider);
assert!(observer.pending().is_none());
observer.activate().unwrap();
assert!(observer.pending().is_none());
}
}
#[test]
fn acpx_directory_matches_the_typescript_session_layout() {
assert_eq!(
acpx_session_directory("session-1"),
"session-1-84097828fc31a8c8"
);
let session = "...";
assert!(acpx_session_directory(session).starts_with("session-"));
}
}
#[path = "tests/credential_observer.rs"]
mod tests;
@@ -19,7 +19,6 @@ mod codex_startup_trust;
mod codex_usage;
mod configured_environment;
mod credential_observer;
#[allow(dead_code)]
mod credential_write_back;
mod cursor_cloud_proxy;
pub mod dot_provider_backend;
@@ -477,7 +477,7 @@ impl CommandExecutor for NativeProviderCommandExecutor {
| "turn.stop"
| "run.cancel"
) {
self.credentials.poll(true)?;
let _ = self.credentials.poll(true);
}
let mut result = self
.selected
@@ -0,0 +1,571 @@
use super::*;
use std::os::unix::fs::{symlink, PermissionsExt};
struct Fixture {
root: PathBuf,
observer: CredentialObserver,
}
impl Fixture {
fn new(provider: &str, seed: &Value) -> Self {
let root =
std::env::temp_dir().join(format!("credential-observer-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();
let root = fs::canonicalize(root).unwrap();
let mut observer = CredentialObserver::new(&root, "session");
observer.loaded = true;
observer.state = Some(State {
schema: SCHEMA.to_owned(),
session_id: "session".to_owned(),
provider: provider.to_owned(),
path: root.join("auth.json"),
snapshot: parse_snapshot(provider, &serde_json::to_vec(seed).unwrap()),
revision: 0,
armed: false,
pending: None,
host_file: None,
silent: false,
});
observer.save(observer.state.as_ref().unwrap()).unwrap();
Self { root, observer }
}
fn write(&self, name: &str, value: &Value) {
let path = self.root.join(name);
fs::write(&path, serde_json::to_vec(value).unwrap()).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
}
}
impl Drop for Fixture {
fn drop(&mut self) {
self.observer.watcher = None;
let _ = fs::remove_dir_all(&self.root);
}
}
fn codex(marker: &str) -> Value {
json!({"tokens":{"account_id":"account-1", "access_token":format!("access-{marker}"),
"refresh_token":format!("refresh-{marker}"), "id_token":format!("identity-{marker}")}, "last_refresh":"metadata"})
}
fn grok(marker: &str) -> Value {
json!({"https://issuer.example::12345678-1234-1234-1234-123456789abc":{
"key":format!("access-{marker}"), "refresh_token":format!("refresh-{marker}"), "expires_at":1234}})
}
#[test]
fn refresh_is_durable_replayable_content_free_and_monotonic() {
let mut f = Fixture::new("codex", &codex("before"));
f.write("auth.json", &codex("before"));
f.observer.activate().unwrap();
assert!(f.observer.pending().is_none());
f.write("auth.json", &codex("after"));
f.observer.poll(true).unwrap();
let event = f.observer.pending().unwrap();
assert_eq!(event, update_event("codex", 1));
let persisted = fs::read_to_string(f.root.join(STATE_FILE)).unwrap();
for secret in [
"access-before",
"refresh-before",
"identity-before",
"access-after",
"refresh-after",
"identity-after",
] {
assert!(!persisted.contains(secret));
assert!(!event.payload.to_string().contains(secret));
}
let mut recovered = CredentialObserver::new(&f.root, "session");
recovered.restore().unwrap();
assert_eq!(recovered.pending(), Some(event));
f.write("auth.json", &codex("newest"));
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event("codex", 1)));
recovered.acknowledge(1).unwrap();
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event("codex", 2)));
recovered.acknowledge(1).unwrap();
recovered.poll(true).unwrap();
assert!(recovered.pending().is_none());
assert_eq!(recovered.state.as_ref().unwrap().revision, 2);
}
#[test]
fn directory_watch_handles_atomic_replacement() {
let mut f = Fixture::new("codex", &codex("before"));
f.write("auth.json", &codex("before"));
f.observer.activate().unwrap();
f.observer.dirty.store(false, Ordering::Relaxed);
f.write("auth.tmp", &codex("after"));
fs::rename(f.root.join("auth.tmp"), f.root.join("auth.json")).unwrap();
let deadline = Instant::now() + Duration::from_secs(3);
while f.observer.pending().is_none() && Instant::now() < deadline {
f.observer.poll(false).unwrap();
std::thread::sleep(Duration::from_millis(10));
}
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
}
#[test]
fn periodic_reread_works_without_native_notifications() {
let mut f = Fixture::new("codex", &codex("before"));
f.write("auth.json", &codex("before"));
f.observer.activate().unwrap();
f.write("auth.json", &codex("after"));
f.observer.watcher = None;
f.observer.dirty.store(false, Ordering::Relaxed);
f.observer.last_scan = Instant::now() - SCAN_INTERVAL;
f.observer.poll(false).unwrap();
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
}
#[test]
fn ignores_metadata_partial_writes_and_deletion() {
let mut f = Fixture::new("codex", &codex("before"));
f.write("auth.json", &codex("before"));
f.observer.activate().unwrap();
let mut metadata = codex("before");
metadata["last_refresh"] = json!("new metadata");
f.write("auth.json", &metadata);
f.observer.poll(true).unwrap();
assert!(f.observer.pending().is_none());
fs::write(f.root.join("auth.json"), "{partial").unwrap();
f.observer.poll(true).unwrap();
assert!(f.observer.pending().is_none());
fs::remove_file(f.root.join("auth.json")).unwrap();
f.observer.poll(true).unwrap();
f.write("auth.json", &codex("after"));
f.observer.poll(true).unwrap();
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
}
#[test]
fn account_changes_and_later_refreshes_survive_recovery_without_exposing_identity() {
for provider in ["codex", "grok"] {
let original = if provider == "codex" {
codex("before")
} else {
grok("before")
};
let mut f = Fixture::new(provider, &original);
f.write("auth.json", &original);
f.observer.activate().unwrap();
let mut changed = original.clone();
let account = if provider == "codex" {
changed["tokens"]["account_id"] = json!("different-account");
"different-account"
} else {
let auth = changed
.as_object()
.unwrap()
.values()
.next()
.unwrap()
.clone();
changed = json!({"https://issuer.example::87654321-4321-4321-4321-cba987654321": auth});
"87654321-4321-4321-4321-cba987654321"
};
f.write("auth.json", &changed);
f.observer.poll(true).unwrap();
assert_eq!(f.observer.pending(), Some(update_event(provider, 1)));
let persisted = fs::read_to_string(f.root.join(STATE_FILE)).unwrap();
assert!(!persisted.contains(account));
assert!(!f
.observer
.pending()
.unwrap()
.payload
.to_string()
.contains(account));
let mut recovered = CredentialObserver::new(&f.root, "session");
recovered.restore().unwrap();
assert_eq!(recovered.pending(), Some(update_event(provider, 1)));
if provider == "codex" {
changed["tokens"]["access_token"] = json!("refreshed-access");
} else {
changed
.as_object_mut()
.unwrap()
.values_mut()
.next()
.unwrap()["key"] = json!("refreshed-access");
}
f.write("auth.json", &changed);
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event(provider, 1)));
recovered.acknowledge(1).unwrap();
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event(provider, 2)));
recovered.acknowledge(1).unwrap();
recovered.poll(true).unwrap();
assert!(recovered.pending().is_none());
f.write("auth.json", &original);
recovered.poll(true).unwrap();
assert_eq!(recovered.pending(), Some(update_event(provider, 3)));
}
}
#[test]
fn grok_seed_catches_pre_start_refresh_and_close_handoff() {
let mut f = Fixture::new("grok", &grok("seed"));
f.observer.poll(true).unwrap();
assert!(f.observer.pending().is_none());
f.write("auth.json", &grok("startup"));
f.observer.activate().unwrap();
assert_eq!(f.observer.pending(), Some(update_event("grok", 1)));
f.observer.acknowledge(1).unwrap();
f.write("auth-refresh.json", &grok("close"));
fs::remove_file(f.root.join("auth.json")).unwrap();
f.observer.poll(true).unwrap();
assert_eq!(f.observer.pending(), Some(update_event("grok", 2)));
}
#[test]
fn codex_close_handoff_preserves_shutdown_refresh() {
let mut f = Fixture::new("codex", &codex("seed"));
f.write("auth.json", &codex("seed"));
f.observer.activate().unwrap();
assert!(f.observer.pending().is_none());
f.write("auth-refresh.json", &codex("close"));
fs::remove_file(f.root.join("auth.json")).unwrap();
f.observer.poll(true).unwrap();
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
f.observer.acknowledge(1).unwrap();
f.observer.poll(true).unwrap();
assert!(f.observer.pending().is_none());
}
#[test]
fn rejects_symlinks_unsafe_permissions_and_oversized_stores() {
let f = Fixture::new("codex", &codex("seed"));
f.write("auth.json", &codex("seed"));
symlink(f.root.join("auth.json"), f.root.join("symlink.json")).unwrap();
assert!(read_snapshot("codex", &f.root.join("symlink.json")).is_none());
symlink(&f.root, f.root.join("parent-link")).unwrap();
assert!(read_snapshot("codex", &f.root.join("parent-link/auth.json")).is_none());
fs::set_permissions(f.root.join("auth.json"), fs::Permissions::from_mode(0o644)).unwrap();
assert!(read_snapshot("codex", &f.root.join("auth.json")).is_none());
fs::set_permissions(f.root.join("auth.json"), fs::Permissions::from_mode(0o600)).unwrap();
fs::write(f.root.join("auth.json"), vec![b' '; MAX_BYTES as usize + 1]).unwrap();
assert!(read_snapshot("codex", &f.root.join("auth.json")).is_none());
}
#[test]
fn observer_requires_opt_in_and_rejects_cross_session_recovery() {
let f = Fixture::new("codex", &codex("seed"));
let mut wrong_session = CredentialObserver::new(&f.root, "different-session");
assert!(wrong_session.restore().is_err());
let path = f.root.join("unused");
fs::create_dir(&path).unwrap();
let mut disabled = CredentialObserver::new(&path, "session");
disabled
.configure(&json!({"provider":{"kind":"codex"}}))
.unwrap();
assert!(disabled.state.is_none());
disabled
.configure(&json!({"observeCredentials":true,"provider":{"kind":"opencode"}}))
.unwrap();
assert!(disabled.state.is_none());
}
#[test]
fn fresh_acpx_observers_create_a_private_runtime_directory() {
let f = Fixture::new("codex", &codex("seed"));
for provider in ["codex", "grok"] {
let state_dir = f.root.join(provider);
fs::create_dir(&state_dir).unwrap();
fs::set_permissions(&state_dir, fs::Permissions::from_mode(0o700)).unwrap();
let runtime = state_dir.join("runtime");
assert!(!runtime.exists());
let mut observer = CredentialObserver::new(&state_dir, "session");
observer.configure(&json!({"observeCredentials":true,"provider":{
"kind":"acpx", "agent":provider, "runtimeDirectory":runtime, "normalizedSessionId":"session"
}})).unwrap();
assert_eq!(
fs::metadata(&runtime).unwrap().permissions().mode() & 0o777,
0o700
);
assert_eq!(observer.state.as_ref().unwrap().provider, provider);
assert!(observer.pending().is_none());
observer.activate().unwrap();
assert!(observer.pending().is_none());
}
}
fn codex_at(marker: &str, last_refresh: &str) -> Value {
let mut value = codex(marker);
value["last_refresh"] = json!(last_refresh);
value
}
fn bytes(value: &Value) -> Vec<u8> {
serde_json::to_vec(value).unwrap()
}
fn with_host_file(f: &mut Fixture, silent: bool) -> PathBuf {
let host = f.root.join("host").join("auth.json");
fs::create_dir(host.parent().unwrap()).unwrap();
let state = f.observer.state.as_mut().unwrap();
state.host_file = Some(host.clone());
state.silent = silent;
let state = state.clone();
f.observer.save(&state).unwrap();
host
}
#[test]
fn host_file_receives_refreshes_during_the_session_and_at_close() {
for silent in [false, true] {
let seed = codex_at("seed", "2026-01-01T00:00:00Z");
let mut f = Fixture::new("codex", &seed);
let host = with_host_file(&mut f, silent);
f.write("host/auth.json", &seed);
f.write("auth.json", &seed);
f.observer.activate().unwrap();
assert!(f.observer.pending().is_none());
for (marker, at) in [
("refreshed", "2026-02-01T00:00:00Z"),
("later", "2026-03-01T00:00:00Z"),
] {
f.write("auth.json", &codex_at(marker, at));
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&codex_at(marker, at)));
let expected = (!silent).then(|| update_event("codex", 1));
assert_eq!(f.observer.pending(), expected, "silent={silent}");
}
let closed = codex_at("closed", "2026-04-01T00:00:00Z");
f.write("auth-refresh.json", &closed);
fs::remove_file(f.root.join("auth.json")).unwrap();
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&closed));
}
}
#[test]
fn host_file_receives_a_shutdown_refresh_after_a_restart_reseeds_the_home() {
let seed = codex_at("seed", "2026-01-01T00:00:00Z");
let mut f = Fixture::new("codex", &seed);
let host = with_host_file(&mut f, true);
f.write("host/auth.json", &seed);
f.write("auth.json", &seed);
f.observer.activate().unwrap();
let closed = codex_at("closed", "2026-02-01T00:00:00Z");
f.write("auth-refresh.json", &closed);
f.write("auth.json", &seed);
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&closed));
f.write("auth.json", &closed);
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&closed));
let later = codex_at("later", "2026-03-01T00:00:00Z");
f.write("auth.json", &later);
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&later));
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&later));
}
#[test]
fn a_failed_write_back_fails_the_poll_without_exposing_the_credential() {
let seed = codex_at("seed", "2026-01-01T00:00:00Z");
let mut f = Fixture::new("codex", &seed);
let host = with_host_file(&mut f, true);
f.write("host/auth.json", &seed);
f.write("auth.json", &seed);
f.observer.activate().unwrap();
fs::remove_file(&host).unwrap();
let refreshed = codex_at("refreshed", "2026-02-01T00:00:00Z");
f.write("auth.json", &refreshed);
let error = f.observer.poll(true).unwrap_err().to_string();
assert!(error.contains("write-back to the host credential file failed"));
assert!(!error.contains("refreshed"));
assert!(!host.exists());
f.write("host/auth.json", &seed);
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&refreshed));
}
#[test]
fn a_repaired_host_file_receives_the_refresh_it_was_kept_from() {
let seed = codex_at("seed", "2026-01-01T00:00:00Z");
let mut f = Fixture::new("codex", &seed);
let host = with_host_file(&mut f, true);
f.write("host/auth.json", &seed);
f.write("auth.json", &seed);
f.observer.activate().unwrap();
let refreshed = codex_at("refreshed", "2026-02-01T00:00:00Z");
f.write("auth.json", &refreshed);
fs::write(&host, b"{\"tokens\":").unwrap();
fs::set_permissions(&host, fs::Permissions::from_mode(0o600)).unwrap();
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), b"{\"tokens\":");
f.write("host/auth.json", &seed);
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&refreshed));
}
#[test]
fn host_file_binding_seeds_the_baseline_and_needs_an_acpx_file_session() {
assert!(parse_host_credential_file(Some("relative/auth.json".into())).is_err());
assert_eq!(parse_host_credential_file(Some("".into())).unwrap(), None);
let f = Fixture::new("codex", &codex("seed"));
let seed = codex_at("seed", "2026-01-01T00:00:00Z");
let host = f.root.join("host-auth.json");
f.write("host-auth.json", &seed);
let runtime = f.root.join("runtime");
for (provider, accepted) in [
(json!({"kind":"codex"}), false),
(
json!({"kind":"acpx", "agent":"claude", "runtimeDirectory":runtime, "normalizedSessionId":"session"}),
false,
),
(
json!({"kind":"acpx", "agent":"codex", "runtimeDirectory":runtime, "normalizedSessionId":"session"}),
true,
),
] {
let state_dir = f.root.join(format!("state-{}", uuid::Uuid::new_v4()));
fs::create_dir(&state_dir).unwrap();
fs::set_permissions(&state_dir, fs::Permissions::from_mode(0o700)).unwrap();
let mut observer = CredentialObserver::new(&state_dir, "session");
observer.loaded = true;
let result =
observer.configure_with_host_file(&json!({"provider":provider}), Some(host.clone()));
if !accepted {
let error = result.unwrap_err();
assert!(error.to_string().contains("Codex or Grok ACPX"), "{error}");
assert!(observer.state.is_none());
continue;
}
result.unwrap();
let state = observer.state.as_ref().unwrap();
assert!(state.silent);
assert_eq!(state.host_file, Some(host.clone()));
assert_eq!(state.snapshot, parse_snapshot("codex", &bytes(&seed)));
}
}
#[test]
fn acpx_directory_matches_the_typescript_session_layout() {
assert_eq!(
acpx_session_directory("session-1"),
"session-1-84097828fc31a8c8"
);
let session = "...";
assert!(acpx_session_directory(session).starts_with("session-"));
}
fn acpx_recovery_fixture(f: &Fixture, host_file: Option<PathBuf>) -> PathBuf {
let home = f.root.join("runtime/acpx/session-dir/codex-home");
fs::create_dir_all(&home).unwrap();
for directory in [
f.root.join("runtime"),
f.root.join("runtime/acpx"),
f.root.join("runtime/acpx/session-dir"),
home.clone(),
] {
fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).unwrap();
}
let seed = codex_at("seed", "2026-01-01T00:00:00Z");
let mut state = f.observer.state.clone().unwrap();
state.path = home.join("auth.json");
state.snapshot = parse_snapshot("codex", &serde_json::to_vec(&seed).unwrap());
state.revision = 1;
state.armed = true;
state.pending = Some(update_event("codex", 1));
state.host_file = host_file;
f.observer.save(&state).unwrap();
fs::write(
home.join("auth.json"),
serde_json::to_vec(&codex_at("refreshed", "2026-02-01T00:00:00Z")).unwrap(),
)
.unwrap();
fs::set_permissions(home.join("auth.json"), fs::Permissions::from_mode(0o600)).unwrap();
home
}
fn write_host(path: &Path, value: &Value) {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, serde_json::to_vec(value).unwrap()).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
}
#[test]
fn recovery_follows_the_host_file_the_runner_names() {
let seed = codex_at("seed", "2026-01-01T00:00:00Z");
let refreshed = codex_at("refreshed", "2026-02-01T00:00:00Z");
for (saved, current) in [
(None, Some("host-a")),
(Some("host-a"), Some("host-b")),
(Some("host-a"), None),
] {
let f = Fixture::new("codex", &codex("seed"));
let path = |name: &str| f.root.join(name).join("auth.json");
for name in ["host-a", "host-b"] {
write_host(&path(name), &seed);
}
acpx_recovery_fixture(&f, saved.map(path));
let current = current.map(path);
let mut recovered = CredentialObserver::new(&f.root, "session");
recovered
.restore_with_host_file(|| Ok(current.clone()))
.unwrap();
let persisted: State =
serde_json::from_slice(&fs::read(f.root.join(STATE_FILE)).unwrap()).unwrap();
assert_eq!(persisted.host_file, current);
assert_eq!(persisted.revision, 1);
recovered.poll(true).unwrap();
for name in ["host-a", "host-b"] {
let expected = if current == Some(path(name)) {
&refreshed
} else {
&seed
};
assert_eq!(fs::read(path(name)).unwrap(), bytes(expected), "{name}");
}
assert_eq!(recovered.pending(), Some(update_event("codex", 1)));
}
}
#[test]
fn recovery_rejects_a_host_file_for_a_native_codex_home() {
let f = Fixture::new("codex", &codex("seed"));
let mut recovered = CredentialObserver::new(&f.root, "session");
let error = recovered
.restore_with_host_file(|| Ok(Some(f.root.join("host/auth.json"))))
.err()
.expect("a native home has no file credential");
assert!(error.to_string().contains("Codex or Grok ACPX"), "{error}");
}
static CLOCK_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn controlled_now_ms() -> f64 {
CLOCK_MS.load(Ordering::Relaxed) as f64
}
#[test]
fn a_kept_refresh_is_decided_again_once_its_decision_expires() {
let identity = "https://issuer.example::12345678-1234-1234-1234-123456789abc";
let grok_at = |marker: &str, expires_at: u64| json!({ identity: {"key":format!("access-{marker}"), "refresh_token":format!("refresh-{marker}"), "expires_at": expires_at}});
let now_s: u64 = 1_800_000_000;
CLOCK_MS.store(now_s * 1000, Ordering::Relaxed);
let bound_s = 400 * 24 * 60 * 60;
let seed = grok_at("seed", now_s);
let ahead = grok_at("ahead", now_s + bound_s + 60);
let mut f = Fixture::new("grok", &seed);
f.observer.now_ms = controlled_now_ms;
let host = with_host_file(&mut f, true);
f.write("host/auth.json", &seed);
f.write("auth.json", &seed);
f.observer.activate().unwrap();
f.write("auth.json", &ahead);
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&seed));
CLOCK_MS.store((now_s + 120) * 1000, Ordering::Relaxed);
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&seed));
for decision in &mut f.observer.written {
decision.2 -= KEPT_DECISION_TTL;
}
f.observer.poll(true).unwrap();
assert_eq!(fs::read(&host).unwrap(), bytes(&ahead));
}