feat(runner): decide and write ACPX credential refreshes back to a host file (#23339)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Paperclip Runner runs ACPX agents, such as Codex and Grok, from
an isolated copy of their login in each session
> - A refresh the provider makes in that copy rotates its refresh token,
and the execution host's own copy of the login is then spent
> - Returning the refresh to the host's file needs a rule for when the
refreshed copy may replace it, and a write that never leaves the file
torn or loosened
> - This pull request adds those rules and that write, matching Core's
local Codex and Grok adapters; nothing calls them yet
> - The benefit is that the rule that decides whether a host's login is
overwritten can be reviewed on its own

## Linked Issues or Issue Description

**Subsystem affected**

Paperclip Runner (`runner-core`), a new `credential_write_back` module.

**Problem or motivation**

An ACPX Codex or Grok session's refreshed `auth.json` stays in the
Runner's isolated home. Both providers rotate the refresh token on
refresh and refuse a rotated one, so writing a refresh back to a host
file must never replace a newer login with an older one, or one
account's login with another's.

**Proposed solution**

A module that decides, under the same rules as Core's local adapters,
whether a refreshed login replaces the host file, and that replaces it
atomically. A later change has the credential observer call it.

**Alternatives considered**

- Point the provider at the host's directory (as
`PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME` does for Claude), so it
refreshes the host file in place. Rejected: the Runner writes its
permission policy into the provider home for every session, and a shared
home would share session history between sessions.
- Write the refreshed file back unconditionally. Rejected: both
providers rotate the refresh token and refuse a rotated one, so an older
or another account's login must never replace the host's.

**Roadmap alignment**

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

**Additional context**

Codex and Grok rotate refresh tokens on refresh. The rules match the
Codex and Grok local adapters' own freshness checks, so Core, the Runner
and a host that applies the same rules agree on which copy wins.

## What Changed

- `write_back(provider, refreshed, host_file, now)` replaces the host
file only when both logins name the same account (Codex
`tokens.account_id`, Grok's `<issuer>::<uuid>` key) and the refreshed
one is strictly fresher: Codex `last_refresh`, at most five minutes
ahead of now; Grok `expires_at` in epoch seconds, milliseconds or RFC
3339, at most 400 days ahead. An API key, another account, a tie or an
unreadable time keeps the host file. Timestamps are parsed with the
`time` crate (already in the lockfile), truncated to milliseconds like
`Date.parse`.
- Both logins must be at most 256 KiB, the host file's own bound, so a
written refresh can always be read back. The host file must exist and be
a private regular file owned by the Runner user, opened without
following a final symlink. A missing host file is never created.
- The replacement is a synced temporary file in the same directory,
renamed over the host file with its mode carried over, followed by a
directory sync. The host file is private, so its group grants nothing
and is not carried over. If the host file changed after the decision
read, the replacement is abandoned and reported as `Raced`, so the
caller can decide again.
- A kept decision carries the host file's stamp (device, inode, size,
mtime, ctime), so a caller can tell when the host file changed and the
decision no longer holds.
- The module is marked `allow(dead_code)` until a caller uses it. It
carries no code comments, per CONTRIBUTING.md; this description holds
the explanations.

## Verification

- `cargo test -p paperclip-runner-core --lib credential_write_back`: 5
passed.
- A table of 21 freshness decisions for Codex and Grok: newer replaces
(including a timezone offset, epoch seconds, milliseconds and RFC 3339);
older, equal at millisecond precision, another account, implausibly far
ahead, unreadable, missing expiry and API-key logins are kept.
- The replacement is a new inode with the mode and owner kept, and no
temporary file remains; a second pass keeps the file.
- A missing, symlinked or group-readable host file is never created,
followed or written.
- A host file replaced after the decision read makes the replacement
`Raced`, leaves the new file in place and removes the temporary file.
- A refresh one byte over the 256 KiB bound keeps the host file; one at
the bound is written.
- `cargo fmt -p paperclip-runner-core -- --check`.
- Not run locally: clippy and the full Runner workspace tests. CI runs
them.

## Risks

- None at runtime: nothing calls the module in this change.
- The check before the rename is not atomic with the rename, so a small
race with an external writer remains; a caller that sees `Raced` decides
again.
- The host directory must let the Runner user create and rename files
beside the host file.
- On non-Unix hosts the module reports write-back as unsupported.

## 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
- [x] All Paperclip CI gates are green
- [x] 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:36 +00:00
1 parent caaa013a69
commit 2d745cf432
6 files changed
+550

No files matched your search

+1
View File
@@ -1855,6 +1855,7 @@ dependencies = [
"serde_json",
"sha1 0.10.7",
"sha2 0.10.9",
"time",
"tokio",
"toml_edit",
"tungstenite",
@@ -37,5 +37,6 @@ rustix = { version = "1.1", features = ["fs", "net", "process"] }
sha1 = "0.10"
tungstenite = { version = "0.28", default-features = false, features = ["handshake", "rustls-tls-native-roots"] }
toml_edit = "0.22"
time = { version = "0.3.55", default-features = false, features = ["parsing"] }
tokio = { version = "1.50", features = ["rt-multi-thread", "sync", "time"] }
uuid = { version = "1.22", features = ["v4"] }
@@ -32,6 +32,7 @@ rustix.workspace = true
sha1.workspace = true
tungstenite.workspace = true
toml_edit.workspace = true
time.workspace = true
tokio.workspace = true
uuid.workspace = true
@@ -0,0 +1,350 @@
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::Path;
use serde_json::Value;
pub(crate) const ACPX_AUTH_JSON_FILE_ENV: &str = "PAPERCLIP_ACPX_AUTH_JSON_FILE";
const MAX_BYTES: u64 = 256 * 1024;
const MAX_FUTURE_LAST_REFRESH_SKEW_MS: f64 = 5.0 * 60.0 * 1000.0;
const MAX_PLAUSIBLE_EXPIRY_MS: f64 = 400.0 * 24.0 * 60.0 * 60.0 * 1000.0;
const EPOCH_SECONDS_MAX: f64 = 1e12;
#[derive(Debug, PartialEq)]
enum Expiry {
Absent,
Unreadable,
At(f64),
}
#[derive(Debug, PartialEq)]
enum Freshness {
Unusable,
ApiKey,
Codex {
account: String,
last_refresh: Option<f64>,
},
Grok {
identity: String,
expires: Expiry,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct HostStamp {
dev: u64,
ino: u64,
len: u64,
mtime: (i64, i64),
ctime: (i64, i64),
}
#[cfg(unix)]
impl HostStamp {
fn of(metadata: &fs::Metadata) -> Self {
use std::os::unix::fs::MetadataExt;
Self {
dev: metadata.dev(),
ino: metadata.ino(),
len: metadata.len(),
mtime: (metadata.mtime(), metadata.mtime_nsec()),
ctime: (metadata.ctime(), metadata.ctime_nsec()),
}
}
}
#[cfg(unix)]
pub(crate) fn host_stamp(path: &Path) -> Option<HostStamp> {
fs::symlink_metadata(path)
.ok()
.map(|metadata| HostStamp::of(&metadata))
}
#[cfg(not(unix))]
pub(crate) fn host_stamp(_path: &Path) -> Option<HostStamp> {
None
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum WriteBack {
Written,
Kept(Option<HostStamp>),
Raced,
}
fn nonempty(value: &Value) -> Option<&str> {
value
.as_str()
.map(str::trim)
.filter(|value| !value.is_empty())
}
fn freshness(provider: &str, bytes: &[u8]) -> Freshness {
if bytes.len() as u64 > MAX_BYTES {
return Freshness::Unusable;
}
let Ok(value) = serde_json::from_slice::<Value>(bytes) else {
return Freshness::Unusable;
};
let Some(object) = value.as_object() else {
return Freshness::Unusable;
};
match provider {
"codex" => {
if nonempty(&value["OPENAI_API_KEY"]).is_some() {
return Freshness::ApiKey;
}
let tokens = &value["tokens"];
if !tokens.is_object() {
return Freshness::Unusable;
}
let Some(account) = nonempty(&tokens["account_id"]) else {
return Freshness::Unusable;
};
if ["id_token", "access_token", "refresh_token"]
.iter()
.all(|key| nonempty(&tokens[*key]).is_none())
{
return Freshness::Unusable;
}
Freshness::Codex {
account: account.to_owned(),
last_refresh: value["last_refresh"].as_str().and_then(parse_rfc3339_ms),
}
}
"grok" => {
if object.len() != 1 {
return Freshness::Unusable;
}
let (identity, auth) = object.iter().next().expect("one entry");
if !is_grok_identity(identity)
|| !auth.is_object()
|| nonempty(&auth["key"]).is_none()
|| nonempty(&auth["refresh_token"]).is_none()
{
return Freshness::Unusable;
}
let expires = match &auth["expires_at"] {
Value::Null => Expiry::Absent,
Value::String(raw) => parse_rfc3339_ms(raw).map_or(Expiry::Unreadable, Expiry::At),
Value::Number(raw) => match raw.as_f64() {
Some(raw) if raw.is_finite() => Expiry::At(if raw < EPOCH_SECONDS_MAX {
raw * 1000.0
} else {
raw
}),
_ => Expiry::Unreadable,
},
_ => Expiry::Unreadable,
};
Freshness::Grok {
identity: identity.clone(),
expires,
}
}
_ => Freshness::Unusable,
}
}
fn is_grok_identity(key: &str) -> bool {
let bytes = key.as_bytes();
if bytes.len() < 39 {
return false;
}
let (prefix, suffix) = bytes.split_at(bytes.len() - 38);
let uuid = &suffix[2..];
let uuid_valid = uuid.iter().enumerate().all(|(index, byte)| {
if matches!(index, 8 | 13 | 18 | 23) {
*byte == b'-'
} else {
byte.is_ascii_hexdigit()
}
});
let Ok(prefix) = std::str::from_utf8(prefix) else {
return false;
};
&suffix[..2] == b"::" && uuid_valid && !prefix.contains(['\n', '\r', '\u{2028}', '\u{2029}'])
}
fn prefer_source(source: &Freshness, destination: &Freshness, now_ms: f64) -> bool {
match (source, destination) {
(
Freshness::Codex {
account: source_account,
last_refresh: source_refresh,
},
Freshness::Codex {
account: destination_account,
last_refresh: destination_refresh,
},
) if source_account == destination_account => match (source_refresh, destination_refresh) {
(Some(source), Some(destination)) => {
source - now_ms <= MAX_FUTURE_LAST_REFRESH_SKEW_MS && source > destination
}
_ => false,
},
(
Freshness::Grok {
identity: source_identity,
expires: source_expiry,
},
Freshness::Grok {
identity: destination_identity,
expires: destination_expiry,
},
) if source_identity == destination_identity => match (source_expiry, destination_expiry) {
(Expiry::At(source), Expiry::At(destination)) => {
source - now_ms <= MAX_PLAUSIBLE_EXPIRY_MS && source > destination
}
_ => false,
},
_ => false,
}
}
fn parse_rfc3339_ms(value: &str) -> Option<f64> {
let instant =
time::OffsetDateTime::parse(value, &time::format_description::well_known::Rfc3339).ok()?;
Some(instant.unix_timestamp_nanos().div_euclid(1_000_000) as f64)
}
fn invalid(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message.to_owned())
}
#[cfg(unix)]
pub(crate) fn read_host_credential(path: &Path) -> io::Result<(Vec<u8>, fs::Metadata)> {
use rustix::fs::{open, Mode, OFlags};
use std::os::unix::fs::MetadataExt;
if !path.is_absolute() {
return Err(invalid("credential file path is not absolute"));
}
let fd = open(
path,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
)?;
let mut file = File::from(fd);
let before = file.metadata()?;
if !before.is_file()
|| before.len() == 0
|| before.len() > MAX_BYTES
|| before.mode() & 0o077 != 0
|| before.uid() != rustix::process::getuid().as_raw()
{
return Err(invalid(
"credential file is not a private, bounded regular file",
));
}
let mut bytes = Vec::new();
let read = (&mut file).take(MAX_BYTES + 1).read_to_end(&mut bytes);
let after = file.metadata()?;
if read.is_err()
|| after.len() != bytes.len() as u64
|| before.len() != after.len()
|| before.mtime() != after.mtime()
|| before.mtime_nsec() != after.mtime_nsec()
{
bytes.fill(0);
return Err(invalid("credential file changed while read"));
}
Ok((bytes, before))
}
#[cfg(not(unix))]
pub(crate) fn read_host_credential(_path: &Path) -> io::Result<(Vec<u8>, fs::Metadata)> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"credential files require Unix",
))
}
#[cfg(unix)]
pub(crate) fn write_back(
provider: &str,
source: &[u8],
destination: &Path,
now_ms: f64,
) -> io::Result<WriteBack> {
let source_freshness = freshness(provider, source);
if matches!(source_freshness, Freshness::Unusable | Freshness::ApiKey) {
return Ok(WriteBack::Kept(None));
}
let (mut current, metadata) = read_host_credential(destination)?;
let replace = prefer_source(&source_freshness, &freshness(provider, &current), now_ms);
current.fill(0);
if !replace {
return Ok(WriteBack::Kept(Some(HostStamp::of(&metadata))));
}
replace_if_unchanged(source, destination, &metadata)
}
#[cfg(unix)]
fn replace_if_unchanged(
source: &[u8],
destination: &Path,
metadata: &fs::Metadata,
) -> io::Result<WriteBack> {
use std::io::Write;
use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
let parent = destination
.parent()
.ok_or_else(|| invalid("credential file has no parent directory"))?;
let name = destination
.file_name()
.ok_or_else(|| invalid("credential file has no name"))?
.to_string_lossy();
let temporary = parent.join(format!(
".{name}.{}.{}.paperclip-refresh",
std::process::id(),
uuid::Uuid::new_v4().simple()
));
let result = (|| -> io::Result<WriteBack> {
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.custom_flags(rustix::fs::OFlags::NOFOLLOW.bits() as i32)
.open(&temporary)?;
file.set_permissions(fs::Permissions::from_mode(metadata.mode() & 0o7777))?;
file.write_all(source)?;
file.sync_all()?;
drop(file);
if HostStamp::of(&fs::symlink_metadata(destination)?) != HostStamp::of(metadata) {
return Ok(WriteBack::Raced);
}
fs::rename(&temporary, destination)?;
File::open(parent)?.sync_all()?;
Ok(WriteBack::Written)
})();
if !matches!(result, Ok(WriteBack::Written)) {
let _ = fs::remove_file(&temporary);
}
result
}
#[cfg(not(unix))]
pub(crate) fn write_back(
_provider: &str,
_source: &[u8],
_destination: &Path,
_now_ms: f64,
) -> io::Result<WriteBack> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"credential files require Unix",
))
}
pub(crate) fn now_ms() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0.0, |elapsed| elapsed.as_millis() as f64)
}
#[cfg(all(test, unix))]
#[path = "tests/credential_write_back.rs"]
mod tests;
@@ -19,6 +19,8 @@ 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;
pub mod durable;
@@ -0,0 +1,195 @@
use super::*;
use serde_json::json;
use std::os::unix::fs::{symlink, MetadataExt, PermissionsExt};
use std::path::PathBuf;
const NOW: f64 = 1_800_000_000_000.0;
const IDENTITY: &str = "https://issuer.example::12345678-1234-4234-8234-123456789abc";
const OTHER: &str = "https://issuer.example::87654321-4321-4321-4321-cba987654321";
struct Directory(PathBuf);
impl Directory {
fn new() -> Self {
let root =
std::env::temp_dir().join(format!("credential-write-back-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();
Self(fs::canonicalize(root).unwrap())
}
fn write(&self, name: &str, value: &Value, mode: u32) -> PathBuf {
let path = self.0.join(name);
fs::write(&path, bytes(value)).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(mode)).unwrap();
path
}
fn entries(&self) -> usize {
fs::read_dir(&self.0).unwrap().count()
}
}
impl Drop for Directory {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn codex(account: &str, last_refresh: &str) -> Value {
json!({"tokens":{"account_id":account, "access_token":"access", "refresh_token":"refresh"},
"last_refresh": last_refresh})
}
fn grok(identity: &str, expires_at: Value) -> Value {
json!({ identity: {"key":"access", "refresh_token":"refresh", "expires_at": expires_at}})
}
fn bytes(value: &Value) -> Vec<u8> {
serde_json::to_vec(value).unwrap()
}
#[test]
fn replacement_follows_the_adapter_freshness_rules() {
let codex_host = codex("account-1", "2027-01-15T07:59:00Z");
let grok_host = grok(IDENTITY, json!(1_800_003_600));
let api_key = json!({"OPENAI_API_KEY":"key"});
#[rustfmt::skip]
let cases = [
("codex newer", "codex", codex("account-1", "2027-01-15T07:59:59Z"), &codex_host, true),
("codex newer offset", "codex", codex("account-1", "2027-01-15T09:59:30+02:00"), &codex_host, true),
("codex within skew", "codex", codex("account-1", "2027-01-15T08:04:00Z"), &codex_host, true),
("codex implausible", "codex", codex("account-1", "2027-01-15T08:06:00Z"), &codex_host, false),
("codex older", "codex", codex("account-1", "2027-01-15T07:58:00Z"), &codex_host, false),
("codex equal", "codex", codex("account-1", "2027-01-15T07:59:00.000999Z"), &codex_host, false),
("codex other account", "codex", codex("account-2", "2027-01-15T07:59:59Z"), &codex_host, false),
("codex unparseable", "codex", codex("account-1", "recently"), &codex_host, false),
("codex api-key source", "codex", api_key.clone(), &codex_host, false),
("codex api-key host", "codex", codex("account-1", "2027-01-15T07:59:59Z"), &api_key, false),
("grok newer seconds", "grok", grok(IDENTITY, json!(1_800_003_660)), &grok_host, true),
("grok newer milliseconds", "grok", grok(IDENTITY, json!(1_800_003_660_000_u64)), &grok_host, true),
("grok newer ISO", "grok", grok(IDENTITY, json!("2027-01-15T09:01:00Z")), &grok_host, true),
("grok older", "grok", grok(IDENTITY, json!(1_800_003_540)), &grok_host, false),
("grok equal", "grok", grok(IDENTITY, json!(1_800_003_600_000_u64)), &grok_host, false),
("grok other identity", "grok", grok(OTHER, json!(1_800_003_660)), &grok_host, false),
("grok invalid identity", "grok", grok("issuer:12345678-1234-4234-8234-123456789abc", json!(1_800_003_660)), &grok_host, false),
("grok missing expiry", "grok", grok(IDENTITY, Value::Null), &grok_host, false),
("grok unreadable expiry", "grok", grok(IDENTITY, json!("tomorrow")), &grok_host, false),
("grok implausible", "grok", grok(IDENTITY, json!(1_800_000_000 + 401 * 86_400)), &grok_host, false),
("grok host expiry missing", "grok", grok(IDENTITY, json!(1_800_003_660)), &grok(IDENTITY, Value::Null), false),
];
for (name, provider, source, destination, expected) in cases {
let decision = prefer_source(
&freshness(provider, &bytes(&source)),
&freshness(provider, &bytes(destination)),
NOW,
);
assert_eq!(decision, expected, "{name}");
}
}
#[test]
fn replacement_is_atomic_and_keeps_the_file_mode() {
let directory = Directory::new();
let host = directory.write(
"auth.json",
&codex("account-1", "2027-01-15T07:59:00Z"),
0o400,
);
let before = fs::metadata(&host).unwrap();
let refreshed = bytes(&codex("account-1", "2027-01-15T07:59:59Z"));
assert_eq!(
write_back("codex", &refreshed, &host, NOW).unwrap(),
WriteBack::Written
);
let after = fs::metadata(&host).unwrap();
assert_ne!(after.ino(), before.ino());
assert_eq!(after.mode() & 0o7777, 0o400);
assert_eq!(after.uid(), before.uid());
assert_eq!(fs::read(&host).unwrap(), refreshed);
assert_eq!(directory.entries(), 1, "no temporary file remains");
assert_eq!(
write_back("codex", &refreshed, &host, NOW).unwrap(),
WriteBack::Kept(host_stamp(&host))
);
}
#[test]
fn never_creates_follows_or_writes_an_unsafe_host_file() {
let refreshed = bytes(&codex("account-1", "2027-01-15T07:59:59Z"));
let directory = Directory::new();
let missing = directory.0.join("auth.json");
assert!(write_back("codex", &refreshed, &missing, NOW).is_err());
assert!(!missing.exists());
let target = directory.write(
"target.json",
&codex("account-1", "2027-01-15T07:59:00Z"),
0o600,
);
let link = directory.0.join("link.json");
symlink(&target, &link).unwrap();
let open = directory.write(
"open.json",
&codex("account-1", "2027-01-15T07:59:00Z"),
0o644,
);
for path in [link, open] {
let before = fs::read(&path).unwrap();
assert!(write_back("codex", &refreshed, &path, NOW).is_err());
assert_eq!(fs::read(&path).unwrap(), before);
}
assert!(fs::symlink_metadata(directory.0.join("link.json"))
.unwrap()
.file_type()
.is_symlink());
}
#[test]
fn abandons_the_replacement_when_the_host_file_changes() {
let directory = Directory::new();
let host = directory.write(
"auth.json",
&codex("account-1", "2027-01-15T07:59:00Z"),
0o600,
);
let (_, decided) = read_host_credential(&host).unwrap();
let rewritten = directory.write(
"next.json",
&codex("account-1", "2027-01-15T07:59:30Z"),
0o600,
);
fs::rename(&rewritten, &host).unwrap();
let refreshed = bytes(&codex("account-1", "2027-01-15T07:59:59Z"));
assert_eq!(
replace_if_unchanged(&refreshed, &host, &decided).unwrap(),
WriteBack::Raced
);
assert_eq!(
fs::read(&host).unwrap(),
bytes(&codex("account-1", "2027-01-15T07:59:30Z"))
);
assert_eq!(
directory.entries(),
1,
"the abandoned replacement is removed"
);
}
#[test]
fn an_oversized_refresh_never_replaces_the_host_file() {
let directory = Directory::new();
let original = codex("account-1", "2027-01-15T07:59:00Z");
let host = directory.write("auth.json", &original, 0o600);
let mut padded = bytes(&codex("account-1", "2027-01-15T07:59:59Z"));
padded.extend(std::iter::repeat_n(
b' ',
MAX_BYTES as usize + 1 - padded.len(),
));
assert_eq!(
write_back("codex", &padded, &host, NOW).unwrap(),
WriteBack::Kept(None)
);
assert_eq!(fs::read(&host).unwrap(), bytes(&original));
padded.pop();
assert_eq!(
write_back("codex", &padded, &host, NOW).unwrap(),
WriteBack::Written
);
}