Skip to content

Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.

fix: improve subscription login compatibility and recovery (#79)

澄潭f29c663a7424
diff --git a/apps/desktop/src-tauri/src/bootstrap.rs b/apps/desktop/src-tauri/src/bootstrap.rs
index 24cd5552..c26a327d 100644
--- a/apps/desktop/src-tauri/src/bootstrap.rs
+++ b/apps/desktop/src-tauri/src/bootstrap.rs
@@ -9,7 +9,7 @@ use hiroute_diagnostics::event::{
};
use hiroute_diagnostics::runtime::DiagnosticsPort;
use serde::Deserialize;
-use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
+use std::os::unix::fs::OpenOptionsExt;
use std::{
collections::BTreeSet,
fs::{File, OpenOptions},
@@ -936,8 +936,11 @@ pub(crate) fn private_dir(path: &Path) -> Result<(), String> {
{
return Err("PRIVATE_PATH_INVALID".into());
}
- std::fs::create_dir_all(path).map_err(|_| "PRIVATE_PATH_UNAVAILABLE")?;
- std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
+ use std::os::unix::fs::DirBuilderExt;
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(path)
.map_err(|_| "PRIVATE_PATH_UNAVAILABLE".into())
}
diff --git a/apps/desktop/src-tauri/src/bridge/model_connections.rs b/apps/desktop/src-tauri/src/bridge/model_connections.rs
index f5f812ce..a95123ee 100644
--- a/apps/desktop/src-tauri/src/bridge/model_connections.rs
+++ b/apps/desktop/src-tauri/src/bridge/model_connections.rs
@@ -186,7 +186,7 @@ pub async fn release_subscription_check(
pub async fn compute_management_snapshot(
window: WebviewWindow,
state: State<'_, DesktopState>,
-) -> Result<ComputeManagementSnapshotV2, DesktopFailure> {
+) -> Result<ComputeManagementSnapshotV3, DesktopFailure> {
main_window(&window)?;
let client = state
.0
@@ -198,7 +198,10 @@ pub async fn compute_management_snapshot(
.clone();
envelope_data(
client
- .compute_management_snapshot(&crate::random_id()?, ComputeManagementQueryV2::default())
+ .compute_management_snapshot_v3(
+ &crate::random_id()?,
+ ComputeManagementQueryV2::default(),
+ )
.await?,
)
}
diff --git a/apps/desktop/src-tauri/src/bridge/worker_tasks.rs b/apps/desktop/src-tauri/src/bridge/worker_tasks.rs
index 855bbe1f..90a045c1 100644
--- a/apps/desktop/src-tauri/src/bridge/worker_tasks.rs
+++ b/apps/desktop/src-tauri/src/bridge/worker_tasks.rs
@@ -196,7 +196,7 @@ fn normalize_required_path(
let metadata = fs::metadata(&canonical).map_err(|_| "WORKER_DEPENDENCIES_UNAVAILABLE")?;
if !metadata.is_file()
|| (require_executable && !path_is_executable(&metadata))
- || (!require_executable && !path_is_readable(&metadata))
+ || (!require_executable && fs::File::open(&canonical).is_err())
{
return Err("WORKER_DEPENDENCIES_INVALID".into());
}
@@ -228,18 +228,6 @@ fn path_is_executable(metadata: &fs::Metadata) -> bool {
}
}
-fn path_is_readable(metadata: &fs::Metadata) -> bool {
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- metadata.permissions().mode() & 0o444 != 0
- }
- #[cfg(not(unix))]
- {
- metadata.is_file()
- }
-}
-
fn data<R>(envelope: MachineEnvelopeV2<R>) -> Result<R, DesktopFailure>
where
R: DeserializeOwned + Serialize,
diff --git a/apps/desktop/src-tauri/src/cli_entry.rs b/apps/desktop/src-tauri/src/cli_entry.rs
index 9f88a557..4827ee6e 100644
--- a/apps/desktop/src-tauri/src/cli_entry.rs
+++ b/apps/desktop/src-tauri/src/cli_entry.rs
@@ -244,12 +244,7 @@ fn owned_link_target(target: &Path, roots: &[PathBuf]) -> bool {
fn ensure_owned_directory(path: &Path) -> Result<(), String> {
match std::fs::symlink_metadata(path) {
Ok(metadata) => {
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
- if !metadata.is_dir()
- || metadata.file_type().is_symlink()
- || metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.permissions().mode() & 0o022 != 0
- {
+ if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err("CLI_ENTRY_DIRECTORY_UNSAFE".into());
}
}
@@ -279,7 +274,9 @@ mod tests {
impl Fixture {
fn new() -> Self {
let root = tempfile::tempdir().unwrap();
- let home = root.path().join("Users/test user");
+ // macOS tempfile roots use /var, while the installed CLI is canonicalized to /private/var.
+ let canonical_root = std::fs::canonicalize(root.path()).unwrap();
+ let home = canonical_root.join("Users/test user");
let applications = home.join("Applications");
let target = applications.join("HiRoute.app/Contents/MacOS/hiroute");
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
diff --git a/apps/desktop/src-tauri/src/resident_ownership.rs b/apps/desktop/src-tauri/src/resident_ownership.rs
index 943f3604..2edfabbb 100644
--- a/apps/desktop/src-tauri/src/resident_ownership.rs
+++ b/apps/desktop/src-tauri/src/resident_ownership.rs
@@ -64,19 +64,12 @@ pub(crate) fn validate_ancestors(path: &Path) -> Result<(), String> {
{
return Err("PRIVATE_PATH_INVALID".into());
}
- if ancestor == path && meta.uid() != nix::unistd::geteuid().as_raw() {
- return Err("PRIVATE_PATH_INVALID".into());
- }
}
Ok(())
}
pub(crate) fn validate_lock(file: &File) -> Result<(), String> {
let m = file.metadata().map_err(|_| "RESIDENT_LOCK_UNAVAILABLE")?;
- if !m.is_file()
- || m.uid() != nix::unistd::geteuid().as_raw()
- || m.mode() & 0o777 != 0o600
- || m.nlink() != 1
- {
+ if !m.is_file() || m.nlink() != 1 {
return Err("RESIDENT_LOCK_INVALID".into());
}
Ok(())
@@ -95,16 +88,13 @@ fn snapshot(
let dir = runtime.join("hiroute");
validate_ancestors(&dir)?;
let meta = std::fs::symlink_metadata(&dir).map_err(|_| "RESIDENT_ENDPOINT_INVALID")?;
- if !meta.is_dir() || meta.mode() & 0o777 != 0o700 {
+ if !meta.is_dir() {
return Err("RESIDENT_ENDPOINT_INVALID".into());
}
let mut sockets = Vec::new();
for path in paths(runtime) {
let m = std::fs::symlink_metadata(path).map_err(|_| "RESIDENT_ENDPOINT_INVALID")?;
- if !m.file_type().is_socket()
- || m.uid() != nix::unistd::geteuid().as_raw()
- || m.mode() & 0o777 != 0o600
- {
+ if !m.file_type().is_socket() {
return Err("RESIDENT_ENDPOINT_INVALID".into());
}
sockets.push(Identity::of(&m));
@@ -309,13 +299,17 @@ mod tests {
assert!(!recoverable(&mut lock, root.path()).unwrap());
}
#[test]
- fn replaced_symlinked_or_insecure_endpoint_is_never_reclaimed() {
+ fn replaced_or_symlinked_endpoint_is_never_reclaimed_but_modes_are_allowed() {
let (root, mut lock, listeners, pid) = fixture();
record(&mut lock, root.path(), pid, None).unwrap();
drop(listeners);
let endpoint = paths(root.path())[0].clone();
std::fs::set_permissions(&endpoint, std::fs::Permissions::from_mode(0o666)).unwrap();
- assert!(!recoverable(&mut lock, root.path()).unwrap());
+ assert!(recoverable(&mut lock, root.path()).unwrap());
+ assert_eq!(
+ std::fs::metadata(&endpoint).unwrap().permissions().mode() & 0o777,
+ 0o666
+ );
std::fs::set_permissions(&endpoint, std::fs::Permissions::from_mode(0o600)).unwrap();
let original = root.path().join("original.sock");
std::fs::rename(&endpoint, &original).unwrap();
diff --git a/apps/desktop/src/features/models/Models.tsx b/apps/desktop/src/features/models/Models.tsx
index 3e46e708..421157c5 100644
--- a/apps/desktop/src/features/models/Models.tsx
+++ b/apps/desktop/src/features/models/Models.tsx
@@ -118,6 +118,7 @@ export function Models(props: Props) {
const model = activeEntry?.model;
const access = source ? sourceAccess(source) : 'unknown';
const sourceLabel = source ? connectionLabel(source, props.language) : '';
+ const subscriptionMode = props.snapshot.subscription_modes?.find(item => item.source_id === source?.source_id && item.source_revision === source?.revision)?.mode;
const connectorManaged = source?.provenance === 'connector_owned';
const canManageCredentials = Boolean(props.mutable && source && !connectorManaged && access !== 'subscription'
&& source.authentication.kind !== 'none'
@@ -340,7 +341,7 @@ export function Models(props: Props) {
const sourceRechecking = Boolean(source && rechecking?.sourceId === source.source_id);
const reason = model?.presentation?.reason_code ?? null;
const subscriptionAttention = access === 'subscription'
- ? subscriptionAttentionCopy(reason, props.language)
+ ? subscriptionAttentionCopy(reason, props.language, subscriptionMode)
: null;
return <section className="models-feature" aria-label={text('我的模型', 'My models')}>
@@ -390,7 +391,7 @@ export function Models(props: Props) {
{status !== 'available' && <div className="callout warn"><UiIcon name="warning" /><div><strong>{subscriptionAttention?.title ?? (status === 'needs_credentials' ? text('添加 API Key 后即可使用', 'Add an API key to use this model') : text('这个接入需要处理', 'This connection needs attention'))}</strong><p>{sourceRechecking ? text('正在使用已保存的接入信息重新检查。', 'Checking again with the saved connection details.') : subscriptionAttention?.detail ?? text('其他已连接模型不受影响。', 'Other connected models are unaffected.')}</p></div>{sourceRechecking
? <button className="btn" type="button" onClick={cancelRecheck}>{text('取消检查', 'Cancel check')}</button>
: canReauthorize
- ? <button className="btn" type="button" onClick={() => props.onReauthorize?.(source.source_id)}>{access === 'subscription' ? text('重新检查订阅', 'Check subscription again') : text('重新检查接入', 'Check connection again')}</button>
+ ? <button className="btn" type="button" onClick={() => props.onReauthorize?.(source.source_id)}>{access === 'subscription' ? subscriptionMode === 'cpa_managed' ? text('重新独立登录', 'Sign in independently again') : text('重新检查订阅', 'Check subscription again') : text('重新检查接入', 'Check connection again')}</button>
: status !== 'needs_credentials' && canRecheck
? <button className="btn" type="button" onClick={() => void recheckSource()}>{text('检查接入', 'Check connection')}</button>
: canManageCredentials && <button className="btn" type="button" onClick={() => setDraft(createDraft(source))}>{text('管理凭据', 'Manage credentials')}</button>}</div>}
@@ -400,13 +401,17 @@ export function Models(props: Props) {
<section className="detail-section">
<div className="detail-section-head"><h3>{text('接入来源', 'Connection')}</h3>{canManageCredentials && <button className="btn btn-quiet" type="button" onClick={() => setDraft(createDraft(source))}>{text('管理凭据', 'Manage credentials')}</button>}</div>
<p className="muted">{access === 'subscription'
- ? text('使用订阅连接,无需重复填写 API Key。', 'Uses a subscription; no additional API key is needed.')
+ ? subscriptionMode === 'cpa_managed'
+ ? text('独立登录 · 由 HiRoute 自动续期,不依赖原生客户端。', 'Independent sign-in · HiRoute renews access without the native client.')
+ : subscriptionMode === 'native_borrowed'
+ ? text('复用本机登录 · 仅同步当前访问凭据,续期依赖原生客户端。', 'Local sign-in reuse · Syncs current access; renewal depends on the native client.')
+ : text('使用订阅连接,无需重复填写 API Key。', 'Uses a subscription; no additional API key is needed.')
: connectorManaged
? text('凭据由本机连接器管理,无需在 HiRoute 中填写 API Key。', 'Credentials are managed by the local connector; no API key is entered in HiRoute.')
: source.authentication.kind === 'none'
? text('此接入不需要用户提供 API Key。', 'No user-provided API key is required.')
: sourceLabel}</p>
- {access === 'subscription' && props.onManageSubscriptionLogin && <div className="actions"><button className="btn" type="button" disabled={!props.mutable} onClick={props.onManageSubscriptionLogin}>{text('管理订阅登录', 'Manage subscription sign-ins')}</button></div>}
+ {access === 'subscription' && props.onManageSubscriptionLogin && <div className="actions"><button className="btn" type="button" disabled={!props.mutable} onClick={props.onManageSubscriptionLogin}>{subscriptionMode === 'native_borrowed' ? text('改用独立登录', 'Use independent sign-in') : text('管理订阅登录', 'Manage subscription sign-ins')}</button></div>}
{source.provenance === 'user_configured' && props.onReconnect && <div className="actions"><button className="btn" type="button" disabled={!props.mutable || submitting} onClick={() => props.onReconnect?.(source)}>{text('编辑端点', 'Edit endpoints')}</button><span className="field-help">{text('一个来源的端点共用已保存的 API Key。', 'Endpoints in one connection share the saved API key.')}</span></div>}
{source.provenance !== 'connector_owned' && <div className="actions"><button className="btn" type="button" disabled={!props.mutable || submitting || !source.actions.includes(source.state === 'disabled' ? 'enable' : 'disable')} onClick={() => void changeSourceState(source.state === 'disabled')}>{submitting ? text('正在保存…', 'Saving…') : source.state === 'disabled' ? text('启用接入', 'Enable connection') : text('停用接入', 'Disable connection')}</button></div>}
{stateChangeError && <div className="callout bad" role="alert" data-error-code={stateChangeError}><UiIcon name="warning" /><span>{text('接入状态未修改;请刷新后重试。', 'The connection state was not changed. Refresh and try again.')}</span></div>}
diff --git a/apps/desktop/src/features/models/subscription-copy.ts b/apps/desktop/src/features/models/subscription-copy.ts
index 396577aa..35bef346 100644
--- a/apps/desktop/src/features/models/subscription-copy.ts
+++ b/apps/desktop/src/features/models/subscription-copy.ts
@@ -1,13 +1,33 @@
+import type { SubscriptionMode } from './types';
+
+export function managementLoadFailureCopy(code: string, language: 'zh' | 'en') {
+ const zh = language === 'zh';
+ const unsupported = ['unknown_command', 'cli.error.unknown_command'].includes(code.toLowerCase());
+ return {
+ detail: unsupported
+ ? zh ? '当前连接的 HiRoute 服务不支持此页面。请更新所连接的服务,然后重新连接。' : 'The connected HiRoute service does not support this page. Update that service, then reconnect.'
+ : zh ? '暂时无法读取模型,请重试。' : 'Models could not be loaded. Try again.',
+ retry: unsupported
+ ? zh ? '更新后重试' : 'Retry after updating'
+ : zh ? '重试' : 'Retry',
+ };
+}
+
export function subscriptionAttentionCopy(
reason: string | null | undefined,
language: 'zh' | 'en',
+ mode?: SubscriptionMode,
) {
const zh = language === 'zh';
switch (reason) {
case 'subscription_updating':
return { title: zh ? '正在更新订阅授权' : 'Updating subscription access', detail: zh ? '更新完成前不会使用旧授权发起新请求。' : 'New requests will not use the previous authorization while the update is pending.' };
case 'authentication_required':
- return { title: zh ? '需要更新订阅登录' : 'Subscription sign-in required', detail: zh ? '请更新对应的订阅登录,再重新检查。复用本机登录时,请在原生客户端中登录。' : 'Renew the subscription sign-in, then check again. For a reused local sign-in, sign in through the native client.' };
+ return { title: zh ? '需要更新订阅登录' : 'Subscription sign-in required', detail: mode === 'cpa_managed'
+ ? zh ? '请在 HiRoute 中重新独立登录,再检查并保存;现有模型和路由已保留。' : 'Sign in independently again in HiRoute, then check and save. Existing models and routes are retained.'
+ : mode === 'native_borrowed'
+ ? zh ? '请在原生客户端中更新登录后重新检查,或改用推荐的独立登录。' : 'Renew the native client sign-in and check again, or use the recommended independent sign-in.'
+ : zh ? '请更新对应的订阅登录,再重新检查。复用本机登录时,请在原生客户端中登录。' : 'Renew the subscription sign-in, then check again. For a reused local sign-in, sign in through the native client.' };
case 'model_not_allowed':
return { title: zh ? '当前订阅不再允许此模型' : 'Model unavailable for this subscription', detail: zh ? '模型和路由配置已保留;当前授权不会执行它。' : 'The model and routing configuration are retained, but current access cannot execute it.' };
case 'runtime_unavailable':
@@ -16,3 +36,27 @@ export function subscriptionAttentionCopy(
return { title: zh ? '订阅需要处理' : 'Subscription needs attention', detail: zh ? '其他已连接模型不受影响。' : 'Other connected models are unaffected.' };
}
}
+
+export function subscriptionFailureCopy(code: string, language: 'zh' | 'en'): string | null {
+ const zh = language === 'zh';
+ switch (code.toUpperCase()) {
+ case 'SUBSCRIPTION_NATIVE_STORE_UNSUPPORTED':
+ return zh ? '当前 Codex 凭据存储暂不支持复用。请使用推荐的独立登录。' : 'The selected Codex credential store cannot be reused. Use the recommended independent sign-in.';
+ case 'SUBSCRIPTION_NATIVE_LOGIN_UNSUPPORTED':
+ return zh ? '当前 Codex 登录不是可复用的 ChatGPT 订阅登录。请使用独立登录,API Key 可通过“连接 API”接入。' : 'This Codex sign-in is not a reusable ChatGPT subscription. Use independent sign-in, or Connect an API for an API key.';
+ case 'SUBSCRIPTION_NATIVE_ACCOUNT_MISSING':
+ return zh ? '无法识别当前 Codex 订阅账号。请在 Codex 中重新登录后重试,或使用独立登录。' : 'The Codex subscription account could not be identified. Sign in again in Codex and retry, or use independent sign-in.';
+ case 'SUBSCRIPTION_NATIVE_READ_FAILED':
+ return zh ? '无法读取本机登录。请确认凭据文件可访问,或解锁并允许读取钥匙串后重试;也可使用独立登录。' : 'The local sign-in could not be read. Check file access or unlock and allow Keychain access, then retry. Independent sign-in is also available.';
+ case 'SUBSCRIPTION_NATIVE_LOGIN_MISSING':
+ case 'SUBSCRIPTION_NATIVE_LOGIN_INVALID':
+ return zh ? '本机订阅登录缺失、已过期或格式不支持。请在原生客户端中重新登录后检查,或使用独立登录。' : 'The local subscription sign-in is missing, expired or unsupported. Sign in again in the native client and check, or use independent sign-in.';
+ case 'SUBSCRIPTION_NATIVE_CLIENT_UNAVAILABLE':
+ return zh ? '无法读取所选 Codex 客户端信息。请确认客户端可运行后重试,或使用独立登录。' : 'The selected Codex client information is unavailable. Check that the client runs and retry, or use independent sign-in.';
+ case 'SUBSCRIPTION_MANAGED_LOGIN_REQUIRED':
+ return zh ? '独立登录已失效或凭据不可用。请在 HiRoute 中重新独立登录,再检查并保存。' : 'The independent sign-in has expired or its credentials are unavailable. Sign in again in HiRoute, then check and save.';
+ case 'SUBSCRIPTION_RUNTIME_UNAVAILABLE':
+ return zh ? '订阅服务暂不可用。请检查本机服务和网络后重试;现有模型和路由已保留。' : 'The subscription service is unavailable. Check the local service and network, then retry. Existing models and routes are retained.';
+ default: return null;
+ }
+}
diff --git a/apps/desktop/src/features/models/types.ts b/apps/desktop/src/features/models/types.ts
index 2855277b..70507e34 100644
--- a/apps/desktop/src/features/models/types.ts
+++ b/apps/desktop/src/features/models/types.ts
@@ -76,11 +76,14 @@ export type ManagedSource = {
actions: ('edit' | 'add_key' | 'recheck' | 'reauthorize' | 'enable' | 'disable')[];
};
+export type SubscriptionMode = 'native_borrowed' | 'cpa_managed';
+
export type ManagementSnapshot = {
schema: string;
revisions: RevisionSet;
runtime_state: 'complete' | 'partial';
sources: ManagedSource[];
+ subscription_modes?: { source_id: string; source_revision: number; mode: SubscriptionMode }[];
};
export type KeyEdit =
diff --git a/apps/desktop/src/features/subscriptions/README.md b/apps/desktop/src/features/subscriptions/README.md
index fc408934..c9a6ddb6 100644
--- a/apps/desktop/src/features/subscriptions/README.md
+++ b/apps/desktop/src/features/subscriptions/README.md
@@ -20,3 +20,14 @@ Tests belong to the Desktop subscription suites and the production Pilot path; s
contract and protected callback admission regressions belong to Application API, CLI and
the daemon. Generated CLI schemas and Tauri permissions are finalized by the convergence
owner with the same candidate as the backend.
+
+Independent sign-in is the recommended entry. The saved-source view joins explicit V3
+subscription-mode records by source ID and revision; unavailable credentials never change
+a saved mode. Reauthorization opens independent sign-in for a CPA-managed source and
+native discovery for a borrowed source. Changing mode still requires Check and Save.
+The published CLI management queries retain their strict V2 responses.
+
+Codex borrowing uses file credentials only. A selected non-file credential store refuses
+stale auth.json and directs the user to independent sign-in; Claude keeps its existing
+file and explicit Keychain check. Error copy separates missing login, unsupported mode or
+store, unreadable credentials, missing account identity and runtime/network unavailability.
diff --git a/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx b/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx
index 20d2950c..27917767 100644
--- a/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx
+++ b/apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx
@@ -150,7 +150,7 @@ export function SubscriptionSignIn({ language, trustedAuthority, onReuseNative,
</div>)}
</div>;
})}
- <Disclosure label={text('复用本机登录', 'Reuse a local sign-in')} language={language}><p className="oc-meta">{text('本机 Codex / Claude Code 更新登录后,HiRoute 会定时同步访问令牌。续期依赖原生客户端;未更新时,连接可能因过期而暂停。', 'Syncs access periodically after the local Codex / Claude Code client updates its sign-in. Renewal depends on the native client; the connection may pause if it has not renewed access.')}</p><button className="btn" type="button" disabled={!trustedAuthority || Boolean(busy)} onClick={onReuseNative}>{text('扫描本机登录', 'Find local sign-ins')}</button></Disclosure>
+ <Disclosure label={text('复用本机登录', 'Reuse a local sign-in')} language={language}><p className="oc-meta">{text('本机 Codex / Claude Code 更新登录后,HiRoute 会定时同步访问令牌。续期依赖原生客户端;未更新时,连接可能因过期而暂停。', 'Syncs access periodically after the local Codex / Claude Code client updates its sign-in. Renewal depends on the native client; the connection may pause if it has not renewed access.')}</p><p className="oc-meta">{text('Codex 仅支持复用文件中的登录;钥匙串等存储请使用独立登录。Claude Code 支持现有文件及 macOS 钥匙串登录。', 'Codex reuse supports file-based sign-ins; use independent sign-in for Keychain or other stores. Claude Code supports its existing file and macOS Keychain sign-ins.')}</p><button className="btn" type="button" disabled={!trustedAuthority || Boolean(busy)} onClick={onReuseNative}>{text('扫描本机登录', 'Find local sign-ins')}</button></Disclosure>
{error && <div className="callout bad" role="alert" data-error-code={error}><UiIcon name="warning" /><span>{text('操作未完成,请重试。已接入的模型配置会保留。', 'The operation did not complete. Try again; existing model settings are retained.')}</span></div>}
</section>;
}
diff --git a/apps/desktop/src/features/subscriptions/model.ts b/apps/desktop/src/features/subscriptions/model.ts
index efc3f560..02c3ee78 100644
--- a/apps/desktop/src/features/subscriptions/model.ts
+++ b/apps/desktop/src/features/subscriptions/model.ts
@@ -1,3 +1,4 @@
+import { subscriptionFailureCopy } from '../models/subscription-copy.ts';
import type { SubscriptionCandidate, SubscriptionCheckResult, SubscriptionSaveIntent } from './types';
export function saveIntent(enable: boolean): SubscriptionSaveIntent {
@@ -49,6 +50,17 @@ export function canSave(candidate: SubscriptionCandidate, enable: boolean, selec
return selected.size > 0;
}
+export function repairSourceAfterLogin(sourceId: string | null, candidate: SubscriptionCandidate): string | null {
+ return sourceId !== null && candidate.existing_source_id === sourceId ? sourceId : null;
+}
+
+export function canSaveRepair(candidate: SubscriptionCandidate | null | undefined, saved: { source_id: string; models: readonly { model_ref: string }[] } | null | undefined, selected: ReadonlySet<string>): boolean {
+ return Boolean(candidate?.validation && candidate.fact_state !== 'pending_approval' && saved
+ && candidate.existing_source_id === saved.source_id
+ && selected.size === saved.models.length
+ && saved.models.every(model => selected.has(model.model_ref)));
+}
+
export function selectionRows(candidate: SubscriptionCandidate, selected: ReadonlySet<string>, saved: readonly { model_ref: string; display_name: string }[] = []) {
const rows = candidate.models.map(model => ({
model_ref: model.model_ref, display_name: model.display_name, selectable: model.selectable, missing: false,
@@ -91,11 +103,13 @@ export function statusText(candidate: SubscriptionCandidate, language: 'zh' | 'e
export function checkStatusText(check: SubscriptionCheckResult, language: 'zh' | 'en'): string {
const zh = language === 'zh';
+ const detail = subscriptionFailureCopy(check.reason ?? '', language);
+ if (detail && ['needs_auth', 'unavailable', 'failed'].includes(check.status)) return detail;
switch (check.status) {
case 'checking': return zh ? '正在检查订阅模型' : 'Checking subscription models';
case 'verified': return zh ? '检查完成,选择模型后仍需保存' : 'Check complete; select models and save';
case 'source_changed': return zh ? '登录来源已变化,请重新检查' : 'Login source changed; check again';
- case 'needs_auth': return zh ? '需要先在对应的 Agent 中重新登录' : 'Sign in again in the original agent first';
+ case 'needs_auth': return zh ? '请更新对应的订阅登录后重新检查' : 'Renew the corresponding subscription sign-in and check again';
case 'unavailable': return zh ? '订阅运行暂不可用,可稍后重试' : 'Subscription runtime unavailable; retry later';
case 'failed': return zh ? '订阅检查失败,可重试' : 'Subscription check failed; retry available';
case 'released': return zh ? '本次检查资源已释放' : 'Resources for this check were released';
diff --git a/apps/desktop/src/product/ModelManagementPage.tsx b/apps/desktop/src/product/ModelManagementPage.tsx
index 5037cd51..16a3f942 100644
--- a/apps/desktop/src/product/ModelManagementPage.tsx
+++ b/apps/desktop/src/product/ModelManagementPage.tsx
@@ -1,3 +1,4 @@
+import { managementLoadFailureCopy, subscriptionFailureCopy } from '../features/models/subscription-copy';
import { requestEditorReplacement } from '../ui/discard-guard';
import { useEffect, useMemo, useRef, useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
@@ -39,7 +40,7 @@ import type {
SubscriptionCandidate,
SubscriptionCheckResult,
} from '../features/subscriptions/types';
-import { canSave as canSaveSubscription, saveFailureDefinitelyPreAdmission, saveIntent, selectionRows, validatedSubscriptionCandidate } from '../features/subscriptions/model';
+import { canSave as canSaveSubscription, canSaveRepair, repairSourceAfterLogin, saveFailureDefinitelyPreAdmission, saveIntent, selectionRows, validatedSubscriptionCandidate } from '../features/subscriptions/model';
import { safeDiagnosticCode } from '../error-code';
type SubscriptionSaveSelection = {
@@ -69,6 +70,8 @@ function failureCode(error: unknown): string {
function subscriptionFailureMessage(failure: SubscriptionFailure, language: 'zh' | 'en'): string {
const zh = language === 'zh';
const code = failure.code.toLocaleUpperCase();
+ const detail = subscriptionFailureCopy(code, language);
+ if (detail) return detail;
if (code.includes('AUTH') || code.includes('LOGIN') || code.includes('CREDENTIAL') || code.includes('UNAUTHORIZED')) {
return zh ? '无法使用当前订阅登录。请更新对应的登录,再重新检查。' : 'The current subscription sign-in could not be used. Renew the corresponding sign-in, then check again.';
}
@@ -79,7 +82,7 @@ function subscriptionFailureMessage(failure: SubscriptionFailure, language: 'zh'
return zh ? '暂时无法扫描本机订阅,请确认本机服务正在运行后重试。' : 'Local subscriptions could not be scanned. Confirm the local service is running, then try again.';
}
if (failure.phase === 'check') {
- return zh ? '订阅检查未完成。请确认对应订阅已登录后重试。' : 'The subscription check did not complete. Confirm the subscription is signed in and try again.';
+ return zh ? '订阅检查未完成。请检查本机服务和网络后重试,也可在设置中开启调试日志帮助排查。' : 'The subscription check did not complete. Check the local service and network, then retry. Debug logs in Settings can help diagnose the failure.';
}
return zh ? '订阅接入未保存。请重新检查当前状态后再试,当前选择已保留。' : 'The subscription connection was not saved. Check the current state and try again; your selection is retained.';
}
@@ -933,7 +936,9 @@ export function ModelManagementPage({
setRepairingSubscriptionSource(sourceId);
setSubscriptionError(null);
setSubscriptionNotice('');
- setAddStage('scan');
+ const source = management?.sources.find(item => item.source_id === sourceId);
+ const mode = management?.subscription_modes?.find(item => item.source_id === sourceId && item.source_revision === source?.revision)?.mode;
+ setAddStage(mode === 'cpa_managed' ? 'subscription-login' : 'scan');
setAdding(true);
void Promise.all([refreshSubscriptions(), recoverSubscriptionCheck()]);
}
@@ -957,11 +962,7 @@ export function ModelManagementPage({
.includes(discoveryError.toLocaleLowerCase());
const discoveryFailureCanRetry = Boolean(discoveryError
&& !['compute.discovery_not_importable', 'registered_option_unavailable'].includes(discoveryError.toLocaleLowerCase()));
- const repairSelectionValid = Boolean(repairingSelectedSubscription
- && effectiveSubscription?.validation
- && repairingSource
- && selectedSubscriptionModels.size === repairingSource.models.length
- && repairingSource.models.every(model => selectedSubscriptionModels.has(model.model_ref)));
+ const repairSelectionValid = repairingSelectedSubscription && canSaveRepair(effectiveSubscription, repairingSource, selectedSubscriptionModels);
const scanFooter = scanWorking
? <button type="button" className="btn" disabled={subscriptionSaving || discoverySaving} onClick={closeScan}>{subscriptionSaving || discoverySaving
? (language === 'zh' ? '正在保存…' : 'Saving…')
@@ -1051,7 +1052,7 @@ export function ModelManagementPage({
setSubscriptions(result.candidates);
setSubscriptionDiscoveryState(result.discovery_state);
setSubscriptionLoading(false);
- setRepairingSubscriptionSource(null);
+ setRepairingSubscriptionSource(current => repairSourceAfterLogin(current, candidate));
openSubscription(candidate);
setAddStage('scan');
}} />}
@@ -1105,7 +1106,7 @@ export function ModelManagementPage({
</Dialog>
{(notice || modelNotice) && <div className="toast-stack" aria-live="polite"><div className="toast" role="status"><UiIcon name="check" /><span>{notice || modelNotice}</span></div></div>}
{loading && <div className="empty-state" role="status"><div><span className="oc-spinner" /><p>{text.loading}</p></div></div>}
- {error && <div className="callout bad" role="alert" data-error-code={error}><UiIcon name="warning" /><span>{language === 'zh' ? '暂时无法读取模型,请重试。' : 'Models could not be loaded. Try again.'}</span><button className="btn" type="button" onClick={() => void refreshManagement()}>{language === 'zh' ? '重试' : 'Retry'}</button></div>}
+ {error && <div className="callout bad" role="alert" data-error-code={error}><UiIcon name="warning" /><span>{managementLoadFailureCopy(error, language).detail}</span><button className="btn" type="button" onClick={() => void refreshManagement()}>{managementLoadFailureCopy(error, language).retry}</button></div>}
{management && !management.sources.length && !loading && !error && <div className="empty-state v3-empty"><div>
<span className="empty-icon"><UiIcon name="models" /></span>
<h3>{language === 'zh' ? '先连接一个模型' : 'Connect your first model'}</h3>
diff --git a/apps/desktop/tests/subscription-model-copy.test.mjs b/apps/desktop/tests/subscription-model-copy.test.mjs
index 82914dde..7edd195b 100644
--- a/apps/desktop/tests/subscription-model-copy.test.mjs
+++ b/apps/desktop/tests/subscription-model-copy.test.mjs
@@ -1,6 +1,19 @@
import assert from 'node:assert/strict';
import test from 'node:test';
-import { subscriptionAttentionCopy } from '../src/features/models/subscription-copy.ts';
+import { managementLoadFailureCopy, subscriptionAttentionCopy, subscriptionFailureCopy } from '../src/features/models/subscription-copy.ts';
+import { safeDiagnosticCode } from '../src/error-code.ts';
+
+test('unsupported management query gives update guidance through the real error-code boundary', () => {
+ const error = { source: 'backend', envelope: { status: 'failed', error: { code: 'UNKNOWN_COMMAND', message_key: 'cli.error.unknown_command' } } };
+ const code = safeDiagnosticCode(error, 'CLIENT_ERROR');
+ assert.match(managementLoadFailureCopy(code, 'zh').detail, /更新.*重新连接/);
+ assert.equal(managementLoadFailureCopy(code, 'zh').retry, '更新后重试');
+ assert.match(managementLoadFailureCopy('UNKNOWN_COMMAND', 'en').detail, /Update that service, then reconnect/);
+ for (const unrelated of ['RESOURCE_NOT_FOUND', 'TRANSPORT_UNAVAILABLE', 'UNKNOWN_COMMAND_EXTRA', 'FRAME_INVALID']) {
+ assert.equal(managementLoadFailureCopy(unrelated, 'en').retry, 'Retry');
+ assert.doesNotMatch(managementLoadFailureCopy(unrelated, 'en').detail, /Update/);
+ }
+});
test('subscription failures use distinct recovery copy and never request an API key', () => {
const updating = subscriptionAttentionCopy('subscription_updating', 'zh');
@@ -17,3 +30,19 @@ test('subscription failures use distinct recovery copy and never request an API
/API key/i,
);
});
+
+
+test('subscription repair follows saved mode and separates local and service failures', () => {
+ const managed = subscriptionAttentionCopy('authentication_required', 'zh', 'cpa_managed');
+ const borrowed = subscriptionAttentionCopy('authentication_required', 'zh', 'native_borrowed');
+ assert.match(managed.detail, /HiRoute.*独立登录/);
+ assert.doesNotMatch(managed.detail, /原生客户端/);
+ assert.match(borrowed.detail, /原生客户端/);
+ assert.match(subscriptionFailureCopy('SUBSCRIPTION_NATIVE_ACCOUNT_MISSING', 'zh'), /无法识别.*账号/);
+ assert.match(subscriptionFailureCopy('SUBSCRIPTION_NATIVE_STORE_UNSUPPORTED', 'en'), /credential store.*independent/);
+ assert.match(subscriptionFailureCopy('SUBSCRIPTION_MANAGED_LOGIN_REQUIRED', 'en'), /HiRoute/);
+ const runtime = subscriptionFailureCopy('SUBSCRIPTION_RUNTIME_UNAVAILABLE', 'zh');
+ assert.match(runtime, /服务和网络/);
+ assert.doesNotMatch(runtime, /重新登录|原生客户端/);
+ assert.equal(subscriptionFailureCopy('UNRELATED_ERROR', 'en'), null);
+});
diff --git a/apps/desktop/tests/subscriptions-state.test.mjs b/apps/desktop/tests/subscriptions-state.test.mjs
index a5f6c996..1f305c73 100644
--- a/apps/desktop/tests/subscriptions-state.test.mjs
+++ b/apps/desktop/tests/subscriptions-state.test.mjs
@@ -3,6 +3,8 @@ import test from 'node:test';
import {
canSave,
+ canSaveRepair,
+ repairSourceAfterLogin,
checkStatusText,
closeAction,
isCurrentResult,
@@ -105,7 +107,7 @@ test('close follows A ownership until B exists, then only observes B', () => {
test('backend failure classes remain distinct in user-facing status', () => {
const base = { candidate: candidate().candidate, approval_operation: operationA };
assert.match(checkStatusText({ ...base, status: 'source_changed' }, 'en'), /changed/i);
- assert.match(checkStatusText({ ...base, status: 'needs_auth' }, 'en'), /sign in/i);
+ assert.match(checkStatusText({ ...base, status: 'needs_auth' }, 'en'), /sign[- ]in/i);
assert.match(checkStatusText({ ...base, status: 'unavailable' }, 'en'), /unavailable/i);
assert.match(checkStatusText({ ...base, status: 'retained', save_operation: operationB }, 'en'), /retained/i);
});
@@ -185,3 +187,18 @@ test('a disappeared unsaved selection is also removable without granting eligibi
selected.delete(missing.model_ref);
assert.equal(canSave(checked, true, selected), true);
});
+
+
+test('independent re-login retains repair membership when an old model leaves the catalog', () => {
+ const saved = { source_id: 'source/managed-codex', models: [{ model_ref: 'model/retired', display_name: 'Retired model' }] };
+ const selected = new Set(saved.models.map(model => model.model_ref));
+ const checked = candidate({ existing_source_id: saved.source_id, models: [], validation });
+ const repairing = repairSourceAfterLogin(saved.source_id, checked);
+ assert.equal(repairing, saved.source_id);
+ assert.equal(canSave(checked, true, selected), false, 'ordinary addition cannot select a missing model');
+ assert.equal(canSaveRepair(checked, saved, selected), true, 'repair retains the exact saved membership');
+ assert.equal(selectionRows(checked, selected, saved.models)[0].missing, true);
+ assert.equal(repairSourceAfterLogin(saved.source_id, { ...checked, existing_source_id: 'source/other' }), null);
+ assert.equal(canSaveRepair({ ...checked, validation: null }, saved, selected), false);
+ assert.equal(canSaveRepair(checked, saved, new Set()), false, 'repair cannot silently drop models');
+});
diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.json
index 6395838d..9877f0d8 100644
--- a/contracts/compatibility-support.v1.json
+++ b/contracts/compatibility-support.v1.json
@@ -95,6 +95,7 @@
"hiroute.compute-management-preview/v2",
"hiroute.compute-management-query/v2",
"hiroute.compute-management-snapshot/v2",
+ "hiroute.compute-management-snapshot/v3",
"hiroute.compute-management-source/v3",
"hiroute.compute-management-target/v2",
"hiroute.compute-probe-lease/v1",
@@ -991,6 +992,17 @@
]
}
]
+ },
+ {
+ "subject": "compute_management_queries",
+ "audited_prefixes": [
+ "hiroute.compute-management-snapshot"
+ ],
+ "current_contracts": [
+ "hiroute.compute-management-snapshot/v2",
+ "hiroute.compute-management-snapshot/v3"
+ ],
+ "legacy_support": []
}
],
"forbidden_contracts": [
diff --git a/crates/application-api/src/compute_management_v3.rs b/crates/application-api/src/compute_management_v3.rs
new file mode 100644
index 00000000..3ff6ecc9
--- /dev/null
+++ b/crates/application-api/src/compute_management_v3.rs
@@ -0,0 +1,46 @@
+//! Versioned source presentation. V2 operations keep their strict published response shape.
+use crate::{ComputeManagedSourceViewV2, ComputeManagementRuntimeReadStateV2};
+use hiroute_domain::RevisionSetV1;
+use serde::{Deserialize, Serialize};
+
+pub const LIST_COMPUTE_OPERATION_V3: &str = "ListComputeV3";
+pub const GET_COMPUTE_OPERATION_V3: &str = "GetComputeV3";
+pub const COMPUTE_MANAGEMENT_SNAPSHOT_SCHEMA_V3: &str = "hiroute.compute-management-snapshot/v3";
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ComputeSubscriptionModeV1 {
+ NativeBorrowed,
+ CpaManaged,
+}
+
+/// Joined only to the same source revision; this presentation grants no access authority.
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct ComputeSubscriptionModeViewV1 {
+ pub source_id: String,
+ pub source_revision: u64,
+ pub mode: ComputeSubscriptionModeV1,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct ComputeManagementSnapshotV3 {
+ pub schema: String,
+ pub revisions: RevisionSetV1,
+ pub runtime_state: ComputeManagementRuntimeReadStateV2,
+ pub sources: Vec<ComputeManagedSourceViewV2>,
+ pub subscription_modes: Vec<ComputeSubscriptionModeViewV1>,
+}
+
+impl ComputeManagementSnapshotV3 {
+ /// Compatibility projection for the still-published ListCompute/GetCompute operations.
+ pub fn into_v2(self) -> crate::ComputeManagementSnapshotV2 {
+ crate::ComputeManagementSnapshotV2 {
+ schema: crate::COMPUTE_MANAGEMENT_SNAPSHOT_SCHEMA_V2.into(),
+ revisions: self.revisions,
+ runtime_state: self.runtime_state,
+ sources: self.sources,
+ }
+ }
+}
diff --git a/crates/application-api/src/lib.rs b/crates/application-api/src/lib.rs
index 4673cc61..65d0f5cb 100644
--- a/crates/application-api/src/lib.rs
+++ b/crates/application-api/src/lib.rs
@@ -26,6 +26,7 @@ pub use classifier_diagnostic::*;
pub use client_access::*;
mod compute_control;
mod compute_management;
+mod compute_management_v3;
mod compute_management_view;
mod generated;
mod model_catalog;
@@ -51,6 +52,7 @@ pub use commands::{
};
pub use compute_control::*;
pub use compute_management::*;
+pub use compute_management_v3::*;
pub use compute_management_view::*;
pub use generated::{GeneratedContractFile, generated_contract_files};
pub use hiroute_domain::delegation::{
diff --git a/crates/application/src/compute_management/dispatch.rs b/crates/application/src/compute_management/dispatch.rs
index 827710ba..46e6e11d 100644
--- a/crates/application/src/compute_management/dispatch.rs
+++ b/crates/application/src/compute_management/dispatch.rs
@@ -6,14 +6,14 @@ use hiroute_application_api::{
ComputeConnectionApplyRequestV1, ComputeManagementQueryV2, ComputeSavePreviewRequestV2,
ComputeSaveResultQueryV2, ComputeSubscriptionCheckPreviewRequestV2,
ComputeSubscriptionCheckResultQueryV2, ComputeValidationRefV2, ErrorCode, ErrorV1,
- GET_COMPUTE_CANDIDATE_OPERATION_V2, GET_COMPUTE_SAVE_RESULT_OPERATION_V2,
- GET_SUBSCRIPTION_CHECK_RESULT_OPERATION_V2, LIST_COMPUTE_SUBSCRIPTIONS_OPERATION_V2,
- LocalControlRequestV2, MachineEnvelopeV2, NativeModelConnectionCancelRequestV1,
- NativeModelConnectionCheckRequestV1, PREPARE_DISCOVERED_MODEL_CONNECTION_OPERATION_V1,
- PREVIEW_COMPUTE_SAVE_OPERATION_V2, PREVIEW_SUBSCRIPTION_CHECK_OPERATION_V2,
- PrepareDiscoveredModelConnectionRequestV1, PrincipalKind,
- RELEASE_SUBSCRIPTION_CHECK_OPERATION_V2, RegisteredModelConnectionCheckRequestV1,
- SavedModelConnectionCheckRequestV1,
+ GET_COMPUTE_CANDIDATE_OPERATION_V2, GET_COMPUTE_OPERATION_V3,
+ GET_COMPUTE_SAVE_RESULT_OPERATION_V2, GET_SUBSCRIPTION_CHECK_RESULT_OPERATION_V2,
+ LIST_COMPUTE_OPERATION_V3, LIST_COMPUTE_SUBSCRIPTIONS_OPERATION_V2, LocalControlRequestV2,
+ MachineEnvelopeV2, NativeModelConnectionCancelRequestV1, NativeModelConnectionCheckRequestV1,
+ PREPARE_DISCOVERED_MODEL_CONNECTION_OPERATION_V1, PREVIEW_COMPUTE_SAVE_OPERATION_V2,
+ PREVIEW_SUBSCRIPTION_CHECK_OPERATION_V2, PrepareDiscoveredModelConnectionRequestV1,
+ PrincipalKind, RELEASE_SUBSCRIPTION_CHECK_OPERATION_V2,
+ RegisteredModelConnectionCheckRequestV1, SavedModelConnectionCheckRequestV1,
};
use hiroute_domain::WorkspaceId;
use serde_json::Value;
@@ -26,6 +26,8 @@ pub(crate) fn is_compute_management_operation(operation: &str) -> bool {
operation,
"ListCompute"
| "GetCompute"
+ | LIST_COMPUTE_OPERATION_V3
+ | GET_COMPUTE_OPERATION_V3
| GET_COMPUTE_CANDIDATE_OPERATION_V2
| PREVIEW_COMPUTE_SAVE_OPERATION_V2
| APPLY_COMPUTE_SAVE_OPERATION_V2
@@ -172,6 +174,19 @@ pub(crate) fn dispatch_compute_management(
request_id,
)
}
+ LIST_COMPUTE_OPERATION_V3 | GET_COMPUTE_OPERATION_V3 => {
+ if request.protected_grant.is_some() {
+ return failed(ErrorCode::CapabilityDenied, request_id);
+ }
+ let Ok(query) = serde_json::from_value::<ComputeManagementQueryV2>(request.payload)
+ else {
+ return failed(ErrorCode::InvalidArguments, request_id);
+ };
+ result(
+ management.compute_management_snapshot_v3(&query),
+ request_id,
+ )
+ }
"ListCompute" | "GetCompute" => {
if request.protected_grant.is_some() {
return failed(ErrorCode::CapabilityDenied, request_id);
diff --git a/crates/application/src/compute_management/mod.rs b/crates/application/src/compute_management/mod.rs
index ead767b7..b0441dd4 100644
--- a/crates/application/src/compute_management/mod.rs
+++ b/crates/application/src/compute_management/mod.rs
@@ -25,11 +25,13 @@ mod dispatch;
mod mutation_support;
mod mutations;
mod query;
+mod query_v3;
pub use candidates::TrustedComputeCandidateRegistry;
pub use compilation::*;
pub use mutations::*;
pub use query::*;
+pub use query_v3::*;
pub(crate) use dispatch::{dispatch_compute_management, is_compute_management_operation};
diff --git a/crates/application/src/compute_management/query.rs b/crates/application/src/compute_management/query.rs
index 5257d5eb..30a5b61f 100644
--- a/crates/application/src/compute_management/query.rs
+++ b/crates/application/src/compute_management/query.rs
@@ -82,6 +82,15 @@ where
T: ComputeRuntimeStateStoreV1,
{
let snapshot = repository.compute_management_snapshot(workspace)?;
+ project_snapshot(snapshot, runtime, query, presentation)
+}
+
+pub(super) fn project_snapshot<T: ComputeRuntimeStateStoreV1>(
+ snapshot: hiroute_domain::ComputeManagementStoredSnapshotV2,
+ runtime: &T,
+ query: &ComputeManagementQueryV2,
+ presentation: Option<&ComputeManagementPresentationFactsV1>,
+) -> Result<ComputeManagementSnapshotV2, ComputeManagementQueryErrorV2> {
let presentation_complete = presentation.is_none_or(|facts| {
facts.complete && facts.revisions.as_ref() == Some(&snapshot.revisions)
});
diff --git a/crates/application/src/compute_management/query_v3.rs b/crates/application/src/compute_management/query_v3.rs
new file mode 100644
index 00000000..e21aa96d
--- /dev/null
+++ b/crates/application/src/compute_management/query_v3.rs
@@ -0,0 +1,72 @@
+//! Saved subscription mode is derived from the committed selection, even while offline.
+use super::{ComputeManagementPresentationFactsV1, ComputeManagementQueryErrorV2};
+use hiroute_application_api::{
+ COMPUTE_MANAGEMENT_SNAPSHOT_SCHEMA_V3, ComputeManagementQueryV2, ComputeManagementSnapshotV3,
+ ComputeSubscriptionModeV1, ComputeSubscriptionModeViewV1,
+};
+use hiroute_domain::{
+ ComputeManagementProvenanceV2, ComputeManagementRepositoryPort, ComputeRuntimeStateStoreV1,
+ WorkspaceId,
+};
+
+pub fn query_compute_management_v3<
+ R: ComputeManagementRepositoryPort,
+ T: ComputeRuntimeStateStoreV1,
+>(
+ repository: &R,
+ runtime: &T,
+ workspace: &WorkspaceId,
+ query: &ComputeManagementQueryV2,
+ presentation: Option<&ComputeManagementPresentationFactsV1>,
+) -> Result<ComputeManagementSnapshotV3, ComputeManagementQueryErrorV2> {
+ let snapshot = repository.compute_management_snapshot(workspace)?;
+ let mut modes = snapshot
+ .sources
+ .iter()
+ .filter(|source| {
+ query
+ .source_id
+ .as_ref()
+ .is_none_or(|id| id == &source.source_id)
+ })
+ .filter_map(|source| {
+ let ComputeManagementProvenanceV2::ConnectorOwned { connector_id, .. } =
+ &source.provenance
+ else {
+ return None;
+ };
+ let provider = match connector_id.as_str() {
+ "connector.cpa.codex" => "codex",
+ "connector.cpa.claude" => "claude",
+ _ => return None,
+ };
+ let suffix = source
+ .last_candidate_ref
+ .strip_prefix(&format!("candidate/cpa/{provider}/"))?;
+ let mode = if suffix
+ .strip_prefix("managed/")
+ .is_some_and(|account| !account.is_empty() && !account.contains('/'))
+ {
+ ComputeSubscriptionModeV1::CpaManaged
+ } else if !suffix.is_empty() && !suffix.contains('/') {
+ ComputeSubscriptionModeV1::NativeBorrowed
+ } else {
+ return None;
+ };
+ Some(ComputeSubscriptionModeViewV1 {
+ source_id: source.source_id.clone(),
+ source_revision: source.revision,
+ mode,
+ })
+ })
+ .collect::<Vec<_>>();
+ modes.sort_by(|a, b| a.source_id.cmp(&b.source_id));
+ let view = super::query::project_snapshot(snapshot, runtime, query, presentation)?;
+ Ok(ComputeManagementSnapshotV3 {
+ schema: COMPUTE_MANAGEMENT_SNAPSHOT_SCHEMA_V3.into(),
+ revisions: view.revisions,
+ runtime_state: view.runtime_state,
+ sources: view.sources,
+ subscription_modes: modes,
+ })
+}
diff --git a/crates/application/src/compute_management/tests.rs b/crates/application/src/compute_management/tests.rs
index 47c3facb..2f6a911d 100644
--- a/crates/application/src/compute_management/tests.rs
+++ b/crates/application/src/compute_management/tests.rs
@@ -14,6 +14,7 @@ use super::*;
mod codex_checked_account;
mod connector_owned_availability;
+mod subscription_modes;
fn unknown<T>() -> ComputeCandidateFactValueV2<T> {
ComputeCandidateFactValueV2 {
diff --git a/crates/application/src/compute_management/tests/subscription_modes.rs b/crates/application/src/compute_management/tests/subscription_modes.rs
new file mode 100644
index 00000000..18e16f3d
--- /dev/null
+++ b/crates/application/src/compute_management/tests/subscription_modes.rs
@@ -0,0 +1,120 @@
+use super::*;
+use hiroute_application_api::{
+ ComputeManagementQueryV2, ComputeManagementSnapshotV2, ComputeSubscriptionModeV1,
+};
+
+fn connector_source(connector: &str, candidate: &str) -> hiroute_domain::ComputeManagementSourceV2 {
+ let mut source = complete_management_source();
+ source.provenance = hiroute_domain::ComputeManagementProvenanceV2::ConnectorOwned {
+ connector_id: connector.into(),
+ account_ref: "account/private".into(),
+ };
+ source.validation = Some(hiroute_domain::ComputeManagementValidationV2 {
+ approval_operation_id: "operation/approval".into(),
+ validation_ref: "validation/connector".into(),
+ validation_revision: 1,
+ });
+ source.last_candidate_ref = candidate.into();
+ source.validate().unwrap();
+ source
+}
+
+#[test]
+fn saved_subscription_mode_survives_unavailable_credentials_and_v2_stays_strict() {
+ for provider in ["codex", "claude"] {
+ for (suffix, expected) in [
+ ("managed/account", ComputeSubscriptionModeV1::CpaManaged),
+ ("native-account", ComputeSubscriptionModeV1::NativeBorrowed),
+ ] {
+ let source = connector_source(
+ &format!("connector.cpa.{provider}"),
+ &format!("candidate/cpa/{provider}/{suffix}"),
+ );
+ // The saved selection is authoritative even without live credential or runtime facts.
+ let repository = OneSourceRepository(source.clone());
+ let result = query_compute_management_v3(
+ &repository,
+ &FailingRuntimeRead,
+ &hiroute_domain::WorkspaceId::default(),
+ &ComputeManagementQueryV2::default(),
+ None,
+ )
+ .unwrap();
+ assert_eq!(result.subscription_modes.len(), 1);
+ assert_eq!(result.subscription_modes[0].mode, expected);
+ assert_eq!(
+ result.subscription_modes[0].source_revision,
+ source.revision
+ );
+ assert_eq!(result.subscription_modes[0].source_id, source.source_id);
+ let encoded_v3 = serde_json::to_value(&result).unwrap();
+ assert!(serde_json::from_value::<ComputeManagementSnapshotV2>(encoded_v3).is_err());
+ let v2 = result.into_v2();
+ let old = query_compute_management(
+ &repository,
+ &FailingRuntimeRead,
+ &hiroute_domain::WorkspaceId::default(),
+ &ComputeManagementQueryV2::default(),
+ )
+ .unwrap();
+ assert_eq!(v2, old);
+ let encoded_v2 = serde_json::to_value(&v2).unwrap();
+ assert!(encoded_v2.get("subscription_modes").is_none());
+ assert_eq!(
+ serde_json::from_value::<ComputeManagementSnapshotV2>(encoded_v2).unwrap(),
+ old
+ );
+ let filtered = query_compute_management_v3(
+ &repository,
+ &FailingRuntimeRead,
+ &hiroute_domain::WorkspaceId::default(),
+ &ComputeManagementQueryV2 {
+ source_id: Some(source.source_id.clone()),
+ },
+ None,
+ )
+ .unwrap();
+ assert_eq!(filtered.sources, old.sources);
+ assert_eq!(filtered.subscription_modes.len(), 1);
+ assert_eq!(filtered.subscription_modes[0].source_id, source.source_id);
+ assert!(matches!(
+ query_compute_management_v3(
+ &repository,
+ &FailingRuntimeRead,
+ &hiroute_domain::WorkspaceId::default(),
+ &ComputeManagementQueryV2 {
+ source_id: Some("source/other".into())
+ },
+ None,
+ ),
+ Err(ComputeManagementQueryErrorV2::NotFound)
+ ));
+ }
+ }
+}
+
+#[test]
+fn mode_requires_matching_connector_and_committed_candidate_not_a_display_label() {
+ for (connector, candidate) in [
+ ("connector.other", "candidate/cpa/codex/managed/account"),
+ (
+ "connector.cpa.codex",
+ "candidate/cpa/claude/managed/account",
+ ),
+ ("connector.cpa.codex", "candidate/cpa/codex/"),
+ ("connector.cpa.codex", "candidate/cpa/codex/managed/"),
+ ("connector.cpa.codex", "candidate/cpa/codex/unknown/account"),
+ ] {
+ let mut source = connector_source(connector, candidate);
+ source.display_name = "Independent sign-in / 独立登录".into();
+ let result = query_compute_management_v3(
+ &OneSourceRepository(source),
+ &RuntimeFacts::default(),
+ &hiroute_domain::WorkspaceId::default(),
+ &ComputeManagementQueryV2::default(),
+ None,
+ )
+ .unwrap();
+ assert!(result.subscription_modes.is_empty());
+ }
+}
diff --git a/crates/application/src/control/mod.rs b/crates/application/src/control/mod.rs
index 11353019..614f9e9c 100644
--- a/crates/application/src/control/mod.rs
+++ b/crates/application/src/control/mod.rs
@@ -513,6 +513,14 @@ pub trait ComputeManagementControlPort: Send + Sync {
query: &ComputeManagementQueryV2,
) -> Result<ComputeManagementSnapshotV2, ComputeManagementControlError>;
+ fn compute_management_snapshot_v3(
+ &self,
+ _query: &ComputeManagementQueryV2,
+ ) -> Result<hiroute_application_api::ComputeManagementSnapshotV3, ComputeManagementControlError>
+ {
+ Err(ComputeManagementControlError::Unavailable)
+ }
+
fn preview_compute_save(
&self,
change: hiroute_application_api::ComputeManagementChangeV2,
diff --git a/crates/application/src/operations/mod.rs b/crates/application/src/operations/mod.rs
index f6b70799..4db6580e 100644
--- a/crates/application/src/operations/mod.rs
+++ b/crates/application/src/operations/mod.rs
@@ -1019,6 +1019,30 @@ impl TransactionError {
{
"SUBSCRIPTION_SOURCE_CHANGED"
}
+ Self::Port(error) if error.context == "subscription.native.store-unsupported" => {
+ "SUBSCRIPTION_NATIVE_STORE_UNSUPPORTED"
+ }
+ Self::Port(error) if error.context == "subscription.native.login-unsupported" => {
+ "SUBSCRIPTION_NATIVE_LOGIN_UNSUPPORTED"
+ }
+ Self::Port(error) if error.context == "subscription.native.account-missing" => {
+ "SUBSCRIPTION_NATIVE_ACCOUNT_MISSING"
+ }
+ Self::Port(error) if error.context == "subscription.native.login-missing" => {
+ "SUBSCRIPTION_NATIVE_LOGIN_MISSING"
+ }
+ Self::Port(error) if error.context == "subscription.native.read-failed" => {
+ "SUBSCRIPTION_NATIVE_READ_FAILED"
+ }
+ Self::Port(error) if error.context == "subscription.native.login-invalid" => {
+ "SUBSCRIPTION_NATIVE_LOGIN_INVALID"
+ }
+ Self::Port(error) if error.context == "subscription.native.client-unavailable" => {
+ "SUBSCRIPTION_NATIVE_CLIENT_UNAVAILABLE"
+ }
+ Self::Port(error) if error.context == "subscription.managed.login-required" => {
+ "SUBSCRIPTION_MANAGED_LOGIN_REQUIRED"
+ }
Self::Port(error) if error.context == "subscription.authentication" => {
"SUBSCRIPTION_NEEDS_AUTH"
}
diff --git a/crates/cli/src/client.rs b/crates/cli/src/client.rs
index a659f1e7..bacfc4aa 100644
--- a/crates/cli/src/client.rs
+++ b/crates/cli/src/client.rs
@@ -87,7 +87,6 @@ impl LocalControlClient {
validate_protected_endpoint(&endpoint)?;
let mut stream =
UnixStream::connect(endpoint).map_err(|_| LocalControlClientError::Transport)?;
- validate_peer_owner(&stream)?;
stream
.set_read_timeout(Some(self.timeout))
.and_then(|_| stream.set_write_timeout(Some(self.timeout)))
@@ -174,7 +173,6 @@ impl LocalControlClient {
validate_protected_endpoint(&endpoint)?;
let mut stream =
UnixStream::connect(endpoint).map_err(|_| LocalControlClientError::Transport)?;
- validate_peer_owner(&stream)?;
stream
.set_read_timeout(Some(self.timeout))
.map_err(|_| LocalControlClientError::Transport)?;
@@ -220,66 +218,6 @@ impl LocalControlClient {
}
}
-#[cfg(all(
- unix,
- any(
- target_os = "dragonfly",
- target_os = "freebsd",
- target_os = "ios",
- target_os = "macos",
- target_os = "netbsd",
- target_os = "openbsd",
- target_os = "tvos",
- target_os = "visionos",
- target_os = "watchos"
- )
-))]
-fn validate_peer_owner(
- stream: &std::os::unix::net::UnixStream,
-) -> Result<(), LocalControlClientError> {
- let (peer_uid, _) =
- nix::unistd::getpeereid(stream).map_err(|_| LocalControlClientError::Protocol)?;
- if peer_uid != nix::unistd::geteuid() {
- return Err(LocalControlClientError::Protocol);
- }
- Ok(())
-}
-
-#[cfg(all(unix, any(target_os = "android", target_os = "linux")))]
-fn validate_peer_owner(
- stream: &std::os::unix::net::UnixStream,
-) -> Result<(), LocalControlClientError> {
- let credentials =
- nix::sys::socket::getsockopt(stream, nix::sys::socket::sockopt::PeerCredentials)
- .map_err(|_| LocalControlClientError::Protocol)?;
- if credentials.uid() != nix::unistd::geteuid().as_raw() {
- return Err(LocalControlClientError::Protocol);
- }
- Ok(())
-}
-
-#[cfg(all(
- unix,
- not(any(
- target_os = "android",
- target_os = "dragonfly",
- target_os = "freebsd",
- target_os = "ios",
- target_os = "linux",
- target_os = "macos",
- target_os = "netbsd",
- target_os = "openbsd",
- target_os = "tvos",
- target_os = "visionos",
- target_os = "watchos"
- ))
-))]
-fn validate_peer_owner(
- _stream: &std::os::unix::net::UnixStream,
-) -> Result<(), LocalControlClientError> {
- Err(LocalControlClientError::Protocol)
-}
-
pub(crate) struct AgentGrantMaterial(Vec<u8>);
impl AgentGrantMaterial {
@@ -299,7 +237,7 @@ impl Drop for AgentGrantMaterial {
#[cfg(unix)]
fn validate_protected_endpoint(endpoint: &Path) -> Result<(), LocalControlClientError> {
- use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
+ use std::os::unix::fs::FileTypeExt;
let parent = endpoint
.parent()
@@ -308,14 +246,9 @@ fn validate_protected_endpoint(endpoint: &Path) -> Result<(), LocalControlClient
.map_err(|_| LocalControlClientError::LocatorUnavailable)?;
let socket_metadata = std::fs::symlink_metadata(endpoint)
.map_err(|_| LocalControlClientError::LocatorUnavailable)?;
- let effective_uid = nix::unistd::geteuid().as_raw();
if !parent_metadata.is_dir()
|| parent_metadata.file_type().is_symlink()
- || parent_metadata.permissions().mode() & 0o777 != 0o700
- || parent_metadata.uid() != effective_uid
|| !socket_metadata.file_type().is_socket()
- || socket_metadata.permissions().mode() & 0o777 != 0o600
- || socket_metadata.uid() != effective_uid
{
return Err(LocalControlClientError::Protocol);
}
diff --git a/crates/cli/src/managed_launch.rs b/crates/cli/src/managed_launch.rs
index 84002e71..aacc8dec 100644
--- a/crates/cli/src/managed_launch.rs
+++ b/crates/cli/src/managed_launch.rs
@@ -199,8 +199,6 @@ fn validated_managed_path(
trusted_hiroute_executable: &Path,
inherited: Option<OsString>,
) -> Option<OsString> {
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
-
if !home.is_absolute() || !trusted_hiroute_executable.is_absolute() {
return None;
}
@@ -220,11 +218,7 @@ fn validated_managed_path(
}
let bin = home.join(".local/bin");
let metadata = std::fs::symlink_metadata(&bin).ok()?;
- if !metadata.is_dir()
- || metadata.file_type().is_symlink()
- || metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.permissions().mode() & 0o022 != 0
- {
+ if !metadata.is_dir() || metadata.file_type().is_symlink() {
return None;
}
let entry = bin.join("hiroute");
@@ -674,15 +668,18 @@ mod tests {
std::os::unix::fs::symlink(&target, bin.join("hiroute")).unwrap();
let inherited = std::env::join_paths([PathBuf::from("/usr/bin"), bin.clone()]).unwrap();
- std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o770)).unwrap();
- assert!(validated_managed_path(&home, &target, Some(inherited.clone())).is_none());
-
- std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o700)).unwrap();
- let path = validated_managed_path(&home, &target, Some(inherited)).unwrap();
- assert_eq!(
- std::env::split_paths(&path).collect::<Vec<_>>(),
- [bin.clone(), PathBuf::from("/usr/bin")]
- );
+ for mode in [0o770, 0o700] {
+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(mode)).unwrap();
+ let path = validated_managed_path(&home, &target, Some(inherited.clone())).unwrap();
+ assert_eq!(
+ std::env::split_paths(&path).collect::<Vec<_>>(),
+ [bin.clone(), PathBuf::from("/usr/bin")]
+ );
+ assert_eq!(
+ std::fs::metadata(&bin).unwrap().permissions().mode() & 0o777,
+ mode
+ );
+ }
std::fs::remove_file(bin.join("hiroute")).unwrap();
std::os::unix::fs::symlink("/usr/bin/false", bin.join("hiroute")).unwrap();
assert!(validated_managed_path(&home, &target, None).is_none());
diff --git a/crates/cli/src/worker/receipt.rs b/crates/cli/src/worker/receipt.rs
index fad6d2f3..7309649c 100644
--- a/crates/cli/src/worker/receipt.rs
+++ b/crates/cli/src/worker/receipt.rs
@@ -152,18 +152,20 @@ fn receipt_root() -> Option<PathBuf> {
}
fn prepare_private_directory(path: &Path) -> Result<(), ReceiptError> {
- std::fs::create_dir_all(path).map_err(|_| ReceiptError::Unavailable)?;
+ let mut builder = std::fs::DirBuilder::new();
+ builder.recursive(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::DirBuilderExt;
+ builder.mode(0o700);
+ }
+ builder
+ .create(path)
+ .map_err(|_| ReceiptError::Unavailable)?;
#[cfg(unix)]
{
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
- std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
- .map_err(|_| ReceiptError::Unavailable)?;
let metadata = std::fs::symlink_metadata(path).map_err(|_| ReceiptError::Unavailable)?;
- if !metadata.is_dir()
- || metadata.file_type().is_symlink()
- || metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.mode() & 0o777 != 0o700
- {
+ if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(ReceiptError::Unavailable);
}
}
@@ -248,15 +250,6 @@ fn validate_private_file(path: &Path) -> Result<(), ReceiptError> {
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err(ReceiptError::Unavailable);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
- if metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.permissions().mode() & 0o777 != 0o600
- {
- return Err(ReceiptError::Unavailable);
- }
- }
Ok(())
}
diff --git a/crates/client-core/src/compute_management.rs b/crates/client-core/src/compute_management.rs
index 543fd0ce..5972c678 100644
--- a/crates/client-core/src/compute_management.rs
+++ b/crates/client-core/src/compute_management.rs
@@ -28,4 +28,19 @@ impl Client {
};
self.query(operation, request_id, &query).await
}
+ pub async fn compute_management_snapshot_v3(
+ &self,
+ request_id: &str,
+ query: ComputeManagementQueryV2,
+ ) -> Result<
+ MachineEnvelopeV2<hiroute_application_api::ComputeManagementSnapshotV3>,
+ ClientFailure,
+ > {
+ let operation = if query.source_id.is_some() {
+ hiroute_application_api::GET_COMPUTE_OPERATION_V3
+ } else {
+ hiroute_application_api::LIST_COMPUTE_OPERATION_V3
+ };
+ self.query(operation, request_id, &query).await
+ }
}
diff --git a/crates/client-core/src/endpoint.rs b/crates/client-core/src/endpoint.rs
index dc6c40ec..73184f19 100644
--- a/crates/client-core/src/endpoint.rs
+++ b/crates/client-core/src/endpoint.rs
@@ -29,20 +29,13 @@ impl LocalEndpoint {
#[cfg(unix)]
pub(crate) fn validate_path(&self) -> Result<(), FailureCode> {
- use std::os::unix::fs::{FileTypeExt, MetadataExt};
+ use std::os::unix::fs::FileTypeExt;
let parent = self.path.parent().ok_or(FailureCode::LocatorUnavailable)?;
let directory =
std::fs::symlink_metadata(parent).map_err(|_| FailureCode::LocatorUnavailable)?;
let socket =
std::fs::symlink_metadata(&self.path).map_err(|_| FailureCode::LocatorUnavailable)?;
- let uid = nix::unistd::geteuid().as_raw();
- if !directory.is_dir()
- || directory.uid() != uid
- || directory.mode() & 0o777 != 0o700
- || !socket.file_type().is_socket()
- || socket.uid() != uid
- || socket.mode() & 0o777 != 0o600
- {
+ if !directory.is_dir() || !socket.file_type().is_socket() {
return Err(FailureCode::PeerRejected);
}
let absolute = std::path::absolute(parent).map_err(|_| FailureCode::LocatorUnavailable)?;
@@ -69,16 +62,16 @@ impl LocalEndpoint {
#[cfg(unix)]
pub(crate) fn validate_peer(&self, stream: &tokio::net::UnixStream) -> Result<(), FailureCode> {
- let credentials = stream.peer_cred().map_err(|_| FailureCode::PeerRejected)?;
- if credentials.uid() != nix::unistd::geteuid().as_raw() {
- return Err(FailureCode::PeerRejected);
- }
if let Some(expected) = self.expected_pid {
#[cfg(target_os = "macos")]
let pid = nix::sys::socket::getsockopt(stream, nix::sys::socket::sockopt::LocalPeerPid)
.map_err(|_| FailureCode::PeerRejected)? as u32;
#[cfg(any(target_os = "linux", target_os = "android"))]
- let pid = credentials.pid().ok_or(FailureCode::PeerRejected)? as u32;
+ let pid = stream
+ .peer_cred()
+ .map_err(|_| FailureCode::PeerRejected)?
+ .pid()
+ .ok_or(FailureCode::PeerRejected)? as u32;
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "android")))]
let pid = {
return Err(FailureCode::PeerRejected);
diff --git a/crates/client-core/tests/transport.rs b/crates/client-core/tests/transport.rs
index 3635dd7b..6544bb7a 100644
--- a/crates/client-core/tests/transport.rs
+++ b/crates/client-core/tests/transport.rs
@@ -710,17 +710,83 @@ async fn write_backpressure_uses_the_same_bounded_submission_deadline() {
server.abort();
}
#[tokio::test]
-async fn writable_private_directory_or_socket_is_rejected() {
+async fn writable_directory_or_socket_keeps_handshake_and_child_pid_checks() {
for directory in [true, false] {
- let (root, _listener, client) = setup();
+ let (root, listener, client) = setup();
let path = if directory {
root.path().join("hiroute")
} else {
client.endpoint().path().to_owned()
};
- std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o777)).unwrap();
- let failure = client.call_wire(request()).await.unwrap_err();
- assert_eq!(failure.code, FailureCode::PeerRejected);
- assert_eq!(failure.submission, SubmissionState::NotSent);
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o777)).unwrap();
+ let server = tokio::spawn(async move {
+ let mut stream = handshake(listener).await;
+ let request = receive(&mut stream).await;
+ write(
+ stream.get_mut(),
+ &MachineEnvelopeV2::succeeded(json!({"ok":true}), Some(request.request_id)),
+ )
+ .await;
+ });
+ assert!(client.call_wire(request()).await.is_ok());
+ server.await.unwrap();
+ assert_eq!(
+ std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
+ 0o777
+ );
+ }
+}
+
+#[tokio::test]
+async fn management_query_versions_use_distinct_operations_over_the_same_handshake() {
+ for (source_id, operation_v2, operation_v3) in [
+ (None, "ListCompute", "ListComputeV3"),
+ (Some("source/test".to_owned()), "GetCompute", "GetComputeV3"),
+ ] {
+ for v3 in [false, true] {
+ let (_root, listener, client) = setup();
+ let expected_operation = if v3 { operation_v3 } else { operation_v2 };
+ let expected_source = source_id.clone();
+ let server = tokio::spawn(async move {
+ let mut stream = handshake(listener).await;
+ let request = receive(&mut stream).await;
+ assert_eq!(request.operation_id, expected_operation);
+ assert_eq!(request.schema_version, LOCAL_CONTROL_SCHEMA_V2);
+ let query: ComputeManagementQueryV2 =
+ serde_json::from_value(request.payload).unwrap();
+ assert_eq!(query.source_id, expected_source);
+ let mut response = json!({"schema": if v3 { "hiroute.compute-management-snapshot/v3" } else { "hiroute.compute-management-snapshot/v2" }, "revisions":{"target":1,"dependencies":{}}, "runtime_state":"complete", "sources":[]});
+ if v3 {
+ response["subscription_modes"] = json!([]);
+ }
+ write(
+ stream.get_mut(),
+ &MachineEnvelopeV2::succeeded(response, Some(request.request_id)),
+ )
+ .await;
+ });
+ let query = ComputeManagementQueryV2 {
+ source_id: source_id.clone(),
+ };
+ if v3 {
+ let result = client
+ .compute_management_snapshot_v3("v3-query", query)
+ .await
+ .unwrap()
+ .data
+ .unwrap();
+ assert_eq!(result.schema, COMPUTE_MANAGEMENT_SNAPSHOT_SCHEMA_V3);
+ assert!(result.subscription_modes.is_empty());
+ } else {
+ let result = client
+ .compute_management_snapshot("v2-query", query)
+ .await
+ .unwrap()
+ .data
+ .unwrap();
+ assert_eq!(result.schema, COMPUTE_MANAGEMENT_SNAPSHOT_SCHEMA_V2);
+ }
+ server.await.unwrap();
+ }
}
}
diff --git a/crates/cpa-bridge/src/borrowed_claude_tests.rs b/crates/cpa-bridge/src/borrowed_claude_tests.rs
index f40ccb7d..4eee8b41 100644
--- a/crates/cpa-bridge/src/borrowed_claude_tests.rs
+++ b/crates/cpa-bridge/src/borrowed_claude_tests.rs
@@ -291,13 +291,20 @@ fn expired_or_deleted_native_auth_does_not_reuse_cached_access() {
#[cfg(unix)]
#[test]
-fn symlinks_and_shared_read_permissions_are_rejected() {
+fn shared_read_permissions_are_preserved_and_symlinks_are_rejected() {
use std::os::unix::fs::{PermissionsExt, symlink};
let root = tempfile::tempdir().unwrap();
let spec = source(root.path(), "access-first", "account-one");
fs::set_permissions(spec.source_path(), fs::Permissions::from_mode(0o644)).unwrap();
- assert!(spec.inspect().is_err());
- fs::set_permissions(spec.source_path(), fs::Permissions::from_mode(0o600)).unwrap();
+ assert!(spec.inspect().is_ok());
+ assert_eq!(
+ fs::metadata(spec.source_path())
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o644
+ );
let alias = root.path().join("alias");
symlink(spec.source_path(), &alias).unwrap();
assert!(read_private(&alias).is_err());
diff --git a/crates/cpa-bridge/src/borrowed_codex.rs b/crates/cpa-bridge/src/borrowed_codex.rs
index 300bed36..2e975534 100644
--- a/crates/cpa-bridge/src/borrowed_codex.rs
+++ b/crates/cpa-bridge/src/borrowed_codex.rs
@@ -31,12 +31,13 @@ pub use evidence::BorrowedCodexEvidence;
/// A Codex CLI auth file borrowed by the managed CPA runtime.
///
-/// The source must be an absolute, owner-only regular file. Only its current access lease is
+/// The source must be an absolute regular file. Only its current access lease is
/// materialized for CPA; the source remains responsible for OAuth refresh.
#[derive(Clone, Eq, PartialEq)]
pub struct BorrowedCodexAuthSpec {
source_path: PathBuf,
executable: PathBuf,
+ store_config: Option<PathBuf>,
}
impl std::fmt::Debug for BorrowedCodexAuthSpec {
@@ -50,9 +51,16 @@ impl BorrowedCodexAuthSpec {
Self {
source_path: source_path.into(),
executable: PathBuf::from("codex"),
+ store_config: None,
}
}
+ /// The native config is re-read before every lease refresh; an explicit auth file omits it.
+ pub fn with_store_config(mut self, config: Option<PathBuf>) -> Self {
+ self.store_config = config;
+ self
+ }
+
pub fn with_executable(mut self, executable: PathBuf) -> Self {
self.executable = executable;
self
@@ -64,8 +72,10 @@ impl BorrowedCodexAuthSpec {
/// Reads stable, non-secret evidence without creating a lease, directory, or managed file.
pub fn inspect(&self) -> Result<BorrowedCodexEvidence, CpaLifecycleError> {
+ validate_store(self.store_config.as_deref())?;
let canonical_source = canonical_private_source(self.source_path())?;
let source = read_nested_source(&canonical_source)?;
+ validate_store(self.store_config.as_deref())?;
BorrowedCodexEvidence::from_source(&canonical_source, &source)
}
}
@@ -203,6 +213,7 @@ impl ManagedAuthLease {
struct BorrowedCodexLease {
canonical_source: PathBuf,
+ store_config: Option<PathBuf>,
executable: PathBuf,
client_version: Option<String>,
source_path_digest: String,
@@ -218,6 +229,7 @@ impl BorrowedCodexLease {
source: &BorrowedCodexAuthSpec,
expected: Option<&BorrowedCodexEvidence>,
) -> Result<Self, CpaLifecycleError> {
+ validate_store(source.store_config.as_deref())?;
let canonical_source = canonical_private_source(source.source_path())?;
let source_path_digest = path_digest(&canonical_source);
if expected.is_some_and(|value| value.source_path_digest() != source_path_digest) {
@@ -228,6 +240,7 @@ impl BorrowedCodexLease {
let source_lock = acquire_lock(&lease_root.join(format!("{source_path_digest}.lock")))?;
let mut lease = Self {
canonical_source,
+ store_config: source.store_config.clone(),
executable: source.executable.clone(),
client_version: if expected.is_none() {
hiroute_integrations::codex_subscription_client_version(&source.executable)
@@ -249,6 +262,7 @@ impl BorrowedCodexLease {
expected: Option<&BorrowedCodexEvidence>,
expected_account_digest: Option<&str>,
) -> Result<ManagedAccountIdentity, CpaLifecycleError> {
+ validate_store(self.store_config.as_deref())?;
let source = read_nested_source(&self.canonical_source)?;
let observed = BorrowedCodexEvidence::from_source(&self.canonical_source, &source)?;
if expected.is_some_and(|value| !value.matches(&observed)) {
@@ -280,6 +294,8 @@ impl BorrowedCodexLease {
}
let prefix = "hiroute-codex-current".to_owned();
let rendered = render_access_only_auth(&source, &prefix, self.client_version.as_deref())?;
+ // A client-version probe may outlive a native store switch. Recheck before materializing.
+ validate_store(self.store_config.as_deref())?;
let revision_digest = revision_digest(&source);
let changed = previous.as_ref().is_none_or(|state| {
@@ -354,23 +370,29 @@ struct SourceStamp {
#[derive(Deserialize)]
struct NestedAuth<'a> {
#[serde(borrow)]
- auth_mode: &'a str,
+ auth_mode: Option<&'a str>,
#[serde(rename = "OPENAI_API_KEY", default)]
api_key: Option<&'a str>,
- #[serde(borrow)]
- last_refresh: &'a str,
- #[serde(borrow)]
+ #[serde(default, borrow)]
+ last_refresh: Option<&'a str>,
+ #[serde(default)]
+ personal_access_token: Option<serde::de::IgnoredAny>,
+ #[serde(default)]
+ bedrock_api_key: Option<serde::de::IgnoredAny>,
+ #[serde(default)]
+ bedrock_access_keys: Option<serde::de::IgnoredAny>,
+ #[serde(default, borrow)]
tokens: NestedTokens<'a>,
}
-#[derive(Deserialize)]
+#[derive(Default, Deserialize)]
struct NestedTokens<'a> {
- #[serde(borrow)]
+ #[serde(default, borrow)]
access_token: &'a str,
#[serde(borrow)]
- id_token: &'a str,
+ id_token: Option<&'a str>,
#[serde(borrow)]
- account_id: &'a str,
+ account_id: Option<&'a str>,
}
#[derive(Serialize)]
@@ -434,6 +456,17 @@ struct BorrowedState {
refresh_token_present: bool,
}
+fn validate_store(config: Option<&Path>) -> Result<(), CpaLifecycleError> {
+ if let Some(config) = config {
+ match hiroute_integrations::agents::codex_subscription_uses_file_store(config) {
+ Ok(true) => {}
+ Ok(false) => return Err(CpaLifecycleError::BorrowedCodexStoreUnsupported),
+ Err(_) => return Err(CpaLifecycleError::BorrowedCodexAuthIo),
+ }
+ }
+ Ok(())
+}
+
fn read_nested_source(path: &Path) -> Result<OwnedNestedSource, CpaLifecycleError> {
read_nested_source_after_read(path, || {})
}
@@ -463,15 +496,15 @@ fn read_nested_source_after_read(
let stamp = source_stamp(&after)?;
let parsed: NestedAuth<'_> = serde_json::from_slice(bytes.as_slice())
.map_err(|_| CpaLifecycleError::InvalidBorrowedCodexAuth)?;
- validate_nested(&parsed)?;
+ let account_id = validate_nested(&parsed)?;
// The returned references must not outlive the zeroized input. Consume the parsed fields
// immediately into a second zeroizing buffer in the caller-facing representation.
return Ok(OwnedNestedSource {
access_token: Zeroizing::new(parsed.tokens.access_token.to_owned()),
- id_token: Zeroizing::new(parsed.tokens.id_token.to_owned()),
- account_id: Zeroizing::new(parsed.tokens.account_id.to_owned()),
- last_refresh: Zeroizing::new(parsed.last_refresh.to_owned()),
+ id_token: Zeroizing::new(parsed.tokens.id_token.unwrap_or_default().to_owned()),
+ account_id: Zeroizing::new(account_id),
+ last_refresh: Zeroizing::new(parsed.last_refresh.unwrap_or_default().to_owned()),
stamp,
});
}
@@ -486,17 +519,74 @@ struct OwnedNestedSource {
stamp: SourceStamp,
}
-fn validate_nested(value: &NestedAuth<'_>) -> Result<(), CpaLifecycleError> {
- if value.auth_mode != "chatgpt"
- || value.api_key.is_some()
- || !valid_secret(value.tokens.access_token, MAX_TOKEN_BYTES)
- || !valid_secret(value.tokens.id_token, MAX_TOKEN_BYTES)
- || !valid_text(value.tokens.account_id, MAX_ACCOUNT_ID_BYTES)
- || !valid_text(value.last_refresh, MAX_LAST_REFRESH_BYTES)
+fn validate_nested(value: &NestedAuth<'_>) -> Result<String, CpaLifecycleError> {
+ // Match Codex's resolved_mode: an explicit mode wins over supplementary API keys.
+ let chatgpt = match value.auth_mode {
+ Some(mode) => mode == "chatgpt",
+ None => {
+ value.api_key.is_none()
+ && value.personal_access_token.is_none()
+ && value.bedrock_api_key.is_none()
+ && value.bedrock_access_keys.is_none()
+ }
+ };
+ if !chatgpt {
+ return Err(CpaLifecycleError::BorrowedCodexLoginUnsupported);
+ }
+ if !valid_secret(value.tokens.access_token, MAX_TOKEN_BYTES)
+ || value
+ .tokens
+ .id_token
+ .is_some_and(|v| !v.is_empty() && !valid_secret(v, MAX_TOKEN_BYTES))
+ || value
+ .last_refresh
+ .is_some_and(|v| !v.is_empty() && !valid_text(v, MAX_LAST_REFRESH_BYTES))
{
return Err(CpaLifecycleError::InvalidBorrowedCodexAuth);
}
- Ok(())
+ if let Some(account) = value.tokens.account_id.filter(|v| !v.is_empty()) {
+ return if valid_text(account, MAX_ACCOUNT_ID_BYTES) {
+ Ok(account.to_owned())
+ } else {
+ Err(CpaLifecycleError::InvalidBorrowedCodexAuth)
+ };
+ }
+ value
+ .tokens
+ .id_token
+ .and_then(account_claim)
+ .or_else(|| account_claim(value.tokens.access_token))
+ .ok_or(CpaLifecycleError::BorrowedCodexAccountMissing)
+}
+
+// A claim is an identity hint from a local credential, not signature or authorization proof.
+// CPA still authenticates the current access token with the provider.
+fn account_claim(token: &str) -> Option<String> {
+ use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
+ #[derive(Deserialize)]
+ struct Claims<'a> {
+ #[serde(rename = "https://api.openai.com/auth", borrow)]
+ auth: Option<AccountClaim<'a>>,
+ }
+ #[derive(Deserialize)]
+ struct AccountClaim<'a> {
+ #[serde(borrow)]
+ chatgpt_account_id: Option<&'a str>,
+ }
+ if token.len() > MAX_TOKEN_BYTES {
+ return None;
+ }
+ let mut parts = token.split('.');
+ parts.next()?;
+ let payload = parts.next()?;
+ parts.next()?;
+ if parts.next().is_some() {
+ return None;
+ }
+ let decoded = Zeroizing::new(URL_SAFE_NO_PAD.decode(payload).ok()?);
+ let claims: Claims<'_> = serde_json::from_slice(&decoded).ok()?;
+ let account = claims.auth?.chatgpt_account_id?;
+ valid_text(account, MAX_ACCOUNT_ID_BYTES).then(|| account.to_owned())
}
fn valid_secret(value: &str, max: usize) -> bool {
@@ -600,12 +690,7 @@ fn canonical_private_source(path: &Path) -> Result<PathBuf, CpaLifecycleError> {
#[cfg(unix)]
pub(super) fn validate_source_metadata(metadata: &fs::Metadata) -> Result<(), CpaLifecycleError> {
use std::os::unix::fs::MetadataExt as _;
- if !metadata.is_file()
- || metadata.file_type().is_symlink()
- || metadata.mode() & 0o077 != 0
- || metadata.uid() != rustix::process::geteuid().as_raw()
- || metadata.nlink() != 1
- {
+ if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.nlink() != 1 {
return Err(CpaLifecycleError::InvalidBorrowedCodexAuth);
}
Ok(())
diff --git a/crates/cpa-bridge/src/borrowed_codex/tests.rs b/crates/cpa-bridge/src/borrowed_codex/tests.rs
index 4116687f..d6f8c88f 100644
--- a/crates/cpa-bridge/src/borrowed_codex/tests.rs
+++ b/crates/cpa-bridge/src/borrowed_codex/tests.rs
@@ -363,7 +363,7 @@ fn duplicated_auth_descriptor_retains_managed_writer_exclusion_until_final_close
#[cfg(unix)]
#[test]
-fn symlink_hardlink_and_non_owner_only_sources_fail_closed() {
+fn symlink_and_hardlink_sources_fail_but_readable_modes_are_preserved() {
use std::os::unix::fs::{PermissionsExt as _, symlink};
let (temp, auth_dir, source) = setup();
@@ -388,8 +388,123 @@ fn symlink_hardlink_and_non_owner_only_sources_fail_closed() {
fs::set_permissions(&source, fs::Permissions::from_mode(0o640)).unwrap();
let third_auth = ensure_private_dir(&temp.path().join("mode-cpa-auth")).unwrap();
+ let original = fs::read(&source).unwrap();
+ let _lease =
+ ManagedAuthLease::acquire(&third_auth, Some(&BorrowedCodexAuthSpec::new(&source))).unwrap();
+ assert_eq!(fs::read(&source).unwrap(), original);
+ assert_eq!(
+ fs::metadata(&source).unwrap().permissions().mode() & 0o777,
+ 0o640
+ );
+}
+
+#[test]
+fn native_modes_and_optional_metadata_preserve_account_and_access_only_lease() {
+ let (_temp, _auth_dir, path) = setup();
+ let original = fs::read(&path).unwrap();
+ let expected = BorrowedCodexAuthSpec::new(&path)
+ .inspect()
+ .unwrap()
+ .account_ref();
+ for mode in [None, Some(serde_json::Value::Null), Some(json!("chatgpt"))] {
+ let mut value: Value = serde_json::from_slice(&original).unwrap();
+ value.as_object_mut().unwrap().remove("auth_mode");
+ if let Some(mode) = mode {
+ value["auth_mode"] = mode;
+ }
+ value.as_object_mut().unwrap().remove("last_refresh");
+ value["tokens"].as_object_mut().unwrap().remove("id_token");
+ fs::write(&path, serde_json::to_vec(&value).unwrap()).unwrap();
+ let source = read_nested_source(&path).unwrap();
+ assert_eq!(
+ BorrowedCodexAuthSpec::new(&path)
+ .inspect()
+ .unwrap()
+ .account_ref(),
+ expected
+ );
+ let flat = render_access_only_auth(&source, "fixture", None).unwrap();
+ assert!(!String::from_utf8_lossy(&flat).contains(REFRESH_SENTINEL));
+ value["auth_mode"] = json!("chatgpt");
+ value["OPENAI_API_KEY"] = json!("supplementary-api-key");
+ fs::write(&path, serde_json::to_vec(&value).unwrap()).unwrap();
+ assert_eq!(
+ BorrowedCodexAuthSpec::new(&path)
+ .inspect()
+ .unwrap()
+ .account_ref(),
+ expected
+ );
+ value.as_object_mut().unwrap().remove("auth_mode");
+ fs::write(&path, serde_json::to_vec(&value).unwrap()).unwrap();
+ assert!(matches!(
+ BorrowedCodexAuthSpec::new(&path).inspect(),
+ Err(CpaLifecycleError::BorrowedCodexLoginUnsupported)
+ ));
+ }
+}
+
+#[test]
+fn account_claim_fallback_never_invents_an_account() {
+ use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
+ let (_temp, _auth_dir, path) = setup();
+ let original: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
+ let expected = BorrowedCodexAuthSpec::new(&path)
+ .inspect()
+ .unwrap()
+ .account_ref();
+ let claims = URL_SAFE_NO_PAD.encode(br#"{"https://api.openai.com/auth":{"chatgpt_account_id":"account-one"},"email":"[email protected]"}"#);
+ for field in ["id_token", "access_token"] {
+ let mut value = original.clone();
+ value["tokens"]
+ .as_object_mut()
+ .unwrap()
+ .remove("account_id");
+ value["tokens"][field] = json!(format!("e30.{claims}.fixture"));
+ fs::write(&path, serde_json::to_vec(&value).unwrap()).unwrap();
+ assert_eq!(
+ BorrowedCodexAuthSpec::new(&path)
+ .inspect()
+ .unwrap()
+ .account_ref(),
+ expected
+ );
+ }
+ let mut value = original;
+ value["tokens"]["account_id"] = Value::Null;
+ fs::write(&path, serde_json::to_vec(&value).unwrap()).unwrap();
assert!(matches!(
- ManagedAuthLease::acquire(&third_auth, Some(&BorrowedCodexAuthSpec::new(source))),
- Err(CpaLifecycleError::InvalidBorrowedCodexAuth)
+ BorrowedCodexAuthSpec::new(&path).inspect(),
+ Err(CpaLifecycleError::BorrowedCodexAccountMissing)
));
}
+
+#[test]
+fn native_store_changes_never_borrow_a_stale_file_and_explicit_override_wins() {
+ let (temp, auth_dir, path) = setup();
+ let config = temp.path().join("config.toml");
+ let spec = BorrowedCodexAuthSpec::new(&path).with_store_config(Some(config.clone()));
+ let mut lease = ManagedAuthLease::acquire(&auth_dir, Some(&spec)).unwrap();
+ let original = fs::read(&path).unwrap();
+ let flat = fs::read(auth_dir.join(MANAGED_FILE_NAME)).unwrap();
+ for store in ["keyring", "auto", "ephemeral", "future-store"] {
+ fs::write(
+ &config,
+ format!("cli_auth_credentials_store = \"{store}\"\n"),
+ )
+ .unwrap();
+ assert!(matches!(
+ spec.inspect(),
+ Err(CpaLifecycleError::BorrowedCodexStoreUnsupported)
+ ));
+ assert!(matches!(
+ lease.refresh(),
+ Err(CpaLifecycleError::BorrowedCodexStoreUnsupported)
+ ));
+ assert!(BorrowedCodexAuthSpec::new(&path).inspect().is_ok());
+ assert_eq!(fs::read(&path).unwrap(), original);
+ assert_eq!(fs::read(auth_dir.join(MANAGED_FILE_NAME)).unwrap(), flat);
+ }
+ fs::write(&config, "cli_auth_credentials_store = \"file\"\n").unwrap();
+ assert!(lease.refresh().is_ok());
+}
diff --git a/crates/cpa-bridge/src/config.rs b/crates/cpa-bridge/src/config.rs
index 8a800f91..ecc912f1 100644
--- a/crates/cpa-bridge/src/config.rs
+++ b/crates/cpa-bridge/src/config.rs
@@ -455,8 +455,14 @@ pub(crate) fn ensure_private_dir(path: &Path) -> Result<PathBuf, CpaConfigError>
if !path.is_absolute() {
return Err(CpaConfigError::InvalidPrivatePath);
}
- fs::create_dir_all(path).map_err(CpaConfigError::Io)?;
- set_private_dir_permissions(path)?;
+ let mut builder = fs::DirBuilder::new();
+ builder.recursive(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::DirBuilderExt;
+ builder.mode(0o700);
+ }
+ builder.create(path).map_err(CpaConfigError::Io)?;
validate_private_dir(path)?;
path.canonicalize().map_err(CpaConfigError::Io)
}
@@ -485,26 +491,10 @@ pub(crate) fn private_atomic_write(path: &Path, bytes: &[u8]) -> Result<(), CpaC
result
}
-#[cfg(unix)]
-fn set_private_dir_permissions(path: &Path) -> Result<(), CpaConfigError> {
- use std::os::unix::fs::PermissionsExt as _;
- fs::set_permissions(path, fs::Permissions::from_mode(0o700)).map_err(CpaConfigError::Io)
-}
-
-#[cfg(not(unix))]
-fn set_private_dir_permissions(_path: &Path) -> Result<(), CpaConfigError> {
- Ok(())
-}
-
#[cfg(unix)]
fn validate_private_dir(path: &Path) -> Result<(), CpaConfigError> {
- use std::os::unix::fs::MetadataExt as _;
let metadata = fs::symlink_metadata(path).map_err(CpaConfigError::Io)?;
- if !metadata.is_dir()
- || metadata.file_type().is_symlink()
- || metadata.mode() & 0o077 != 0
- || metadata.uid() != rustix::process::geteuid().as_raw()
- {
+ if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(CpaConfigError::InsecurePermissions);
}
Ok(())
@@ -532,12 +522,7 @@ fn set_private_file_create_mode(_options: &mut OpenOptions) {}
pub(crate) fn validate_private_file(path: &Path) -> Result<(), CpaConfigError> {
use std::os::unix::fs::MetadataExt as _;
let metadata = fs::symlink_metadata(path).map_err(CpaConfigError::Io)?;
- if !metadata.is_file()
- || metadata.file_type().is_symlink()
- || metadata.mode() & 0o077 != 0
- || metadata.uid() != rustix::process::geteuid().as_raw()
- || metadata.nlink() != 1
- {
+ if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.nlink() != 1 {
return Err(CpaConfigError::InsecurePermissions);
}
Ok(())
@@ -562,7 +547,7 @@ pub enum CpaConfigError {
InvalidCapability,
#[error("CPA private path is not absolute")]
InvalidPrivatePath,
- #[error("CPA state/config permissions are not owner-only")]
+ #[error("CPA state/config path is not a safe regular file or directory")]
InsecurePermissions,
#[error("CPA state/config I/O failed: {0}")]
Io(std::io::Error),
diff --git a/crates/cpa-bridge/src/errors.rs b/crates/cpa-bridge/src/errors.rs
index 8919398e..4f6eb9c7 100644
--- a/crates/cpa-bridge/src/errors.rs
+++ b/crates/cpa-bridge/src/errors.rs
@@ -62,6 +62,12 @@ pub enum CpaLifecycleError {
InvalidAccountState,
#[error("CPA account state I/O failed: {0}")]
AccountStateIo(std::io::Error),
+ #[error("Codex login mode cannot be borrowed; use independent subscription sign-in")]
+ BorrowedCodexLoginUnsupported,
+ #[error("Codex credential store cannot be borrowed; use independent subscription sign-in")]
+ BorrowedCodexStoreUnsupported,
+ #[error("Codex account cannot be identified; sign in again and retry")]
+ BorrowedCodexAccountMissing,
#[error("borrowed Codex authentication is invalid or unsafe")]
InvalidBorrowedCodexAuth,
#[error("borrowed Codex authentication source is missing")]
@@ -85,3 +91,50 @@ pub enum CpaLifecycleError {
#[error(transparent)]
Process(#[from] CpaProcessError),
}
+
+impl CpaLifecycleError {
+ /// Closed, non-secret causes shared by Check/Save and access-lease materialization.
+ pub fn subscription_failure(&self) -> Option<hiroute_domain::PortError> {
+ use hiroute_domain::{PortError, PortErrorCode};
+ let (code, context) = match self {
+ Self::BorrowedCodexStoreUnsupported => (
+ PortErrorCode::InvalidData,
+ "subscription.native.store-unsupported",
+ ),
+ Self::BorrowedCodexLoginUnsupported => (
+ PortErrorCode::InvalidData,
+ "subscription.native.login-unsupported",
+ ),
+ Self::BorrowedCodexAccountMissing => (
+ PortErrorCode::InvalidData,
+ "subscription.native.account-missing",
+ ),
+ Self::BorrowedCodexAuthMissing | Self::BorrowedClaudeAuthMissing => (
+ PortErrorCode::PermissionDenied,
+ "subscription.native.login-missing",
+ ),
+ Self::BorrowedCodexAuthIo | Self::BorrowedClaudeAuthUnavailable => (
+ PortErrorCode::Unavailable,
+ "subscription.native.read-failed",
+ ),
+ Self::InvalidBorrowedCodexAuth
+ | Self::InvalidBorrowedClaudeAuth
+ | Self::BorrowedCodexAuthUnavailable => (
+ PortErrorCode::PermissionDenied,
+ "subscription.native.login-invalid",
+ ),
+ Self::BorrowedCodexClientVersionUnavailable => (
+ PortErrorCode::Unavailable,
+ "subscription.native.client-unavailable",
+ ),
+ Self::ManagedOAuthCredentialsMissing
+ | Self::ManagedOAuthAuthenticationRequired
+ | Self::InvalidManagedOAuthCredentials => (
+ PortErrorCode::PermissionDenied,
+ "subscription.managed.login-required",
+ ),
+ _ => return None,
+ };
+ Some(PortError::new(code, context))
+ }
+}
diff --git a/crates/cpa-bridge/src/managed_oauth.rs b/crates/cpa-bridge/src/managed_oauth.rs
index a5897945..f8283153 100644
--- a/crates/cpa-bridge/src/managed_oauth.rs
+++ b/crates/cpa-bridge/src/managed_oauth.rs
@@ -1,6 +1,6 @@
//! Read-only projections of credentials owned and refreshed exclusively by CPA.
//! No token is returned to the daemon, and no token file is rewritten by this adapter.
-use std::fs::{self, File};
+use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
@@ -128,13 +128,6 @@ fn validate_auth_directory(path: &Path) -> Result<(), CpaLifecycleError> {
if !path.is_absolute() || !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(invalid());
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt as _;
- if metadata.uid() != rustix::process::geteuid().as_raw() || metadata.mode() & 0o077 != 0 {
- return Err(invalid());
- }
- }
Ok(())
}
@@ -147,7 +140,7 @@ fn read_credential(
for _ in 0..3 {
let file = crate::borrowed_codex::open_source_nofollow(&path).map_err(|_| invalid())?;
let before = file.metadata().map_err(|_| invalid())?;
- secure_credential_file(&file, &before)?;
+ secure_credential_file(&before)?;
if before.len() > MAX_CREDENTIAL_BYTES {
return Err(invalid());
}
@@ -174,22 +167,16 @@ fn read_credential(
Err(invalid())
}
-fn secure_credential_file(file: &File, metadata: &fs::Metadata) -> Result<(), CpaLifecycleError> {
+fn secure_credential_file(metadata: &fs::Metadata) -> Result<(), CpaLifecycleError> {
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err(invalid());
}
#[cfg(unix)]
{
- use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
- if metadata.uid() != rustix::process::geteuid().as_raw() || metadata.nlink() != 1 {
+ use std::os::unix::fs::MetadataExt as _;
+ if metadata.nlink() != 1 {
return Err(invalid());
}
- // CPA's token-storage branch creates files with the process umask. The enclosing
- // store is already private; narrow this descriptor without writing token bytes.
- if metadata.mode() & 0o077 != 0 {
- file.set_permissions(fs::Permissions::from_mode(0o600))
- .map_err(|_| invalid())?;
- }
}
Ok(())
}
diff --git a/crates/cpa-bridge/src/runtime.rs b/crates/cpa-bridge/src/runtime.rs
index d990f69e..ebd56425 100644
--- a/crates/cpa-bridge/src/runtime.rs
+++ b/crates/cpa-bridge/src/runtime.rs
@@ -185,6 +185,8 @@ struct InstanceLayout {
auth_dir: PathBuf,
}
+mod credential_diagnostics;
+
impl ManagedCpaRuntime {
pub fn managed_kind(&self) -> Option<crate::CpaAccountKind> {
if let Some(kind) = self.spec.managed_oauth {
@@ -200,28 +202,10 @@ impl ManagedCpaRuntime {
pub fn inspect_subscription_for_check(
&self,
) -> Result<BorrowedSubscriptionEvidence, CpaLifecycleError> {
- let _scope = self.operation_context().enter();
- if let Some(spec) = &self.spec.borrowed_claude_auth {
- return spec.inspect_for_check().map(Into::into);
- }
- self.inspect_subscription()
+ self.inspect_subscription_with_diagnostics(true)
}
pub fn inspect_subscription(&self) -> Result<BorrowedSubscriptionEvidence, CpaLifecycleError> {
- let _scope = self.operation_context().enter();
- if let Some(source) = self.managed_oauth_source() {
- let evidence = source.inspect()?;
- self.inspect_managed_authentication(&evidence)?;
- return Ok(BorrowedSubscriptionEvidence::Managed(evidence));
- }
- if let Some(spec) = &self.spec.borrowed_claude_auth {
- return spec.inspect().map(Into::into);
- }
- self.spec
- .borrowed_codex_auth
- .as_ref()
- .ok_or(CpaLifecycleError::InvalidSpec)?
- .inspect()
- .map(Into::into)
+ self.inspect_subscription_with_diagnostics(false)
}
pub fn new(
@@ -766,7 +750,7 @@ impl ManagedCpaRuntime {
&transferred.binary_version,
self.spec.control_timeout,
)
- .map_err(map_control_error)?;
+ .map_err(|error| self.map_control_error(error))?;
let mut process = self.backend.attach_authenticated(transferred.cpa_pid)?;
self.control
.probe_ready(
@@ -775,7 +759,7 @@ impl ManagedCpaRuntime {
&transferred.binary_version,
self.spec.control_timeout,
)
- .map_err(map_control_error)?;
+ .map_err(|error| self.map_control_error(error))?;
if process.pid() != transferred.cpa_pid || process.try_exit()?.is_some() {
return Err(CpaLifecycleError::UntrustedOrphan);
}
@@ -1028,7 +1012,7 @@ impl ManagedCpaRuntime {
&live.artifact.version().to_string(),
self.spec.control_timeout,
)
- .map_err(map_control_error)?;
+ .map_err(|error| self.map_control_error(error))?;
crate::request_context::check()?;
live.last_health = Some(Instant::now());
self.health_invalidated.store(false, Ordering::Release);
@@ -1175,7 +1159,7 @@ impl ManagedCpaRuntime {
&live.artifact.version().to_string(),
self.spec.control_timeout,
)
- .map_err(map_control_error)?;
+ .map_err(|error| self.map_control_error(error))?;
}
process
.shutdown(crate::request_context::remaining(
@@ -1340,18 +1324,26 @@ fn ready_health(live: &LiveRuntime, restart_count: u64) -> CpaHealth {
}
}
-fn map_control_error(error: AccountDiscoveryError) -> CpaLifecycleError {
- match error {
- AccountDiscoveryError::AuthenticationRequired => {
- CpaLifecycleError::ManagedOAuthAuthenticationRequired
- }
- AccountDiscoveryError::AccountDisappeared => {
- CpaLifecycleError::BorrowedCodexAuthUnavailable
+impl ManagedCpaRuntime {
+ fn map_control_error(&self, error: AccountDiscoveryError) -> CpaLifecycleError {
+ match error {
+ AccountDiscoveryError::AuthenticationRequired
+ | AccountDiscoveryError::AccountDisappeared => {
+ if self.is_managed_oauth() {
+ CpaLifecycleError::ManagedOAuthAuthenticationRequired
+ } else if self.spec.borrowed_claude_auth.is_some() {
+ CpaLifecycleError::InvalidBorrowedClaudeAuth
+ } else {
+ CpaLifecycleError::BorrowedCodexAuthUnavailable
+ }
+ }
+ AccountDiscoveryError::SecretBearingResponse
+ | AccountDiscoveryError::NonSubscriptionAccount
+ | AccountDiscoveryError::RunningVersionMismatch => {
+ CpaLifecycleError::UnsafeControlResponse
+ }
+ _ => CpaLifecycleError::ControlUnavailable,
}
- AccountDiscoveryError::SecretBearingResponse
- | AccountDiscoveryError::NonSubscriptionAccount
- | AccountDiscoveryError::RunningVersionMismatch => CpaLifecycleError::UnsafeControlResponse,
- _ => CpaLifecycleError::ControlUnavailable,
}
}
diff --git a/crates/cpa-bridge/src/runtime/credential_diagnostics.rs b/crates/cpa-bridge/src/runtime/credential_diagnostics.rs
new file mode 100644
index 00000000..c874f369
--- /dev/null
+++ b/crates/cpa-bridge/src/runtime/credential_diagnostics.rs
@@ -0,0 +1,78 @@
+//! Credential inspection emits only closed failure categories, never paths or input bytes.
+use super::*;
+
+impl ManagedCpaRuntime {
+ pub(super) fn inspect_subscription_with_diagnostics(
+ &self,
+ interactive: bool,
+ ) -> Result<BorrowedSubscriptionEvidence, CpaLifecycleError> {
+ let _scope = self.operation_context().enter();
+ let started = std::time::Instant::now();
+ let stage = if self.is_managed_oauth() {
+ CpaStageKind::ManagedCredentialRead
+ } else {
+ CpaStageKind::NativeCredentialRead
+ };
+ // These are source reads, independent of any CPA process generation.
+ self.emit_stage(stage, CpaStageOutcome::Entered, 0, 0);
+ let result = (|| {
+ if let Some(source) = self.managed_oauth_source() {
+ let evidence = source.inspect()?;
+ self.inspect_managed_authentication(&evidence)?;
+ return Ok(BorrowedSubscriptionEvidence::Managed(evidence));
+ }
+ if let Some(spec) = &self.spec.borrowed_claude_auth {
+ return if interactive {
+ spec.inspect_for_check()
+ } else {
+ spec.inspect()
+ }
+ .map(Into::into);
+ }
+ self.spec
+ .borrowed_codex_auth
+ .as_ref()
+ .ok_or(CpaLifecycleError::InvalidSpec)?
+ .inspect()
+ .map(Into::into)
+ })();
+ let outcome = match &result {
+ Ok(_) => CpaStageOutcome::Completed,
+ Err(error) => CpaStageOutcome::Failed {
+ code: credential_failure_code(error),
+ },
+ };
+ self.emit_stage(
+ stage,
+ outcome,
+ started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
+ 0,
+ );
+ result
+ }
+}
+
+fn credential_failure_code(error: &CpaLifecycleError) -> CpaFailureCode {
+ match error {
+ CpaLifecycleError::BorrowedCodexAuthMissing
+ | CpaLifecycleError::BorrowedClaudeAuthMissing => CpaFailureCode::CredentialSourceMissing,
+ CpaLifecycleError::BorrowedCodexAuthIo
+ | CpaLifecycleError::BorrowedClaudeAuthUnavailable => CpaFailureCode::CredentialReadFailed,
+ CpaLifecycleError::BorrowedCodexStoreUnsupported => {
+ CpaFailureCode::CredentialStoreUnsupported
+ }
+ CpaLifecycleError::BorrowedCodexLoginUnsupported => {
+ CpaFailureCode::CredentialLoginUnsupported
+ }
+ CpaLifecycleError::BorrowedCodexAccountMissing => CpaFailureCode::CredentialAccountMissing,
+ CpaLifecycleError::InvalidBorrowedCodexAuth
+ | CpaLifecycleError::InvalidBorrowedClaudeAuth
+ | CpaLifecycleError::BorrowedCodexAuthUnavailable => CpaFailureCode::CredentialInvalid,
+ CpaLifecycleError::ManagedOAuthCredentialsMissing
+ | CpaLifecycleError::InvalidManagedOAuthCredentials
+ | CpaLifecycleError::ManagedOAuthAuthenticationRequired => {
+ CpaFailureCode::ManagedLoginRequired
+ }
+ _ => CpaFailureCode::Unknown,
+ }
+}
diff --git a/crates/cpa-bridge/src/runtime/recovery.rs b/crates/cpa-bridge/src/runtime/recovery.rs
index 377bd5e6..cd70a276 100644
--- a/crates/cpa-bridge/src/runtime/recovery.rs
+++ b/crates/cpa-bridge/src/runtime/recovery.rs
@@ -84,7 +84,7 @@ impl ManagedCpaRuntime {
&stale.binary_version,
self.spec.control_timeout,
)
- .map_err(map_control_error)?;
+ .map_err(|error| self.map_control_error(error))?;
let mut process = self.backend.attach_authenticated(stale.cpa_pid)?;
self.control
.probe_ready(
@@ -93,7 +93,7 @@ impl ManagedCpaRuntime {
&stale.binary_version,
self.spec.control_timeout,
)
- .map_err(map_control_error)?;
+ .map_err(|error| self.map_control_error(error))?;
if process.pid() != stale.cpa_pid {
return Err(CpaLifecycleError::UntrustedOrphan);
}
diff --git a/crates/cpa-bridge/src/runtime/routing_batch.rs b/crates/cpa-bridge/src/runtime/routing_batch.rs
index e4d86264..27535c0b 100644
--- a/crates/cpa-bridge/src/runtime/routing_batch.rs
+++ b/crates/cpa-bridge/src/runtime/routing_batch.rs
@@ -306,7 +306,7 @@ impl ManagedCpaRuntime {
};
self.invalidate_live_accounts(live, affected_kind);
let _ = save_account_state(&layout.accounts_path, &live.accounts);
- return Err(map_control_error(error));
+ return Err(self.map_control_error(error));
}
};
crate::request_context::check()?;
diff --git a/crates/cpa-bridge/src/runtime/tests.rs b/crates/cpa-bridge/src/runtime/tests.rs
index a7b009d7..b379bdd9 100644
--- a/crates/cpa-bridge/src/runtime/tests.rs
+++ b/crates/cpa-bridge/src/runtime/tests.rs
@@ -53,6 +53,8 @@ mod borrowed_stock;
mod cancelled_start;
#[path = "tests/control_races.rs"]
mod control_races;
+#[path = "tests/credential_diagnostics.rs"]
+mod credential_diagnostics;
#[path = "tests/fixture_isolation.rs"]
mod fixture_isolation;
#[path = "tests/managed_recovery.rs"]
diff --git a/crates/cpa-bridge/src/runtime/tests/credential_diagnostics.rs b/crates/cpa-bridge/src/runtime/tests/credential_diagnostics.rs
new file mode 100644
index 00000000..57ae9ab9
--- /dev/null
+++ b/crates/cpa-bridge/src/runtime/tests/credential_diagnostics.rs
@@ -0,0 +1,66 @@
+use super::*;
+
+#[test]
+fn credential_inspection_reports_closed_causes_without_input_or_paths() {
+ for (case, expected) in [
+ ("missing", "credential_source_missing"),
+ ("mode", "credential_login_unsupported"),
+ ("account", "credential_account_missing"),
+ ("store", "credential_store_unsupported"),
+ ("invalid", "credential_invalid"),
+ ] {
+ let root = tempfile::tempdir().unwrap();
+ let logs = tempfile::tempdir().unwrap();
+ let diagnostics_root = logs.path().join("d");
+ let report = DiagnosticRuntime::start(RuntimeConfig {
+ root: diagnostics_root.clone(),
+ role: hiroute_diagnostics::event::ProcessRole::Daemon,
+ component: hiroute_diagnostics::record::Component::Cpa,
+ parent_session_id: None,
+ level_override: Some(hiroute_diagnostics::level::DiagnosticLevel::Debug),
+ });
+ let mut runtime = fixture_runtime(
+ &root,
+ Arc::new(FakeBackend::default()),
+ Arc::new(FakeControl::default()),
+ 2,
+ )
+ .with_diagnostics(report.port());
+ let path = root.path().join("credential-path-sentinel.json");
+ let mut auth = json!({"auth_mode":"chatgpt", "tokens":{"access_token":"credential-access-sentinel", "account_id":"credential-account-sentinel"}, "refresh_token":"credential-refresh-sentinel"});
+ match case {
+ "mode" => auth["auth_mode"] = json!("apikey"),
+ "account" => {
+ auth["tokens"].as_object_mut().unwrap().remove("account_id");
+ }
+ "invalid" => auth["tokens"]["access_token"] = json!(""),
+ _ => {}
+ }
+ if case != "missing" {
+ std::fs::write(&path, serde_json::to_vec(&auth).unwrap()).unwrap();
+ }
+ let mut spec = BorrowedCodexAuthSpec::new(path);
+ if case == "store" {
+ let config = root.path().join("config-path-sentinel.toml");
+ std::fs::write(&config, "cli_auth_credentials_store = \"keyring\"\n").unwrap();
+ spec = spec.with_store_config(Some(config));
+ }
+ runtime.spec.borrowed_codex_auth = Some(spec);
+ assert!(runtime.inspect_subscription_for_check().is_err());
+ report.shutdown();
+ let log = std::fs::read_to_string(diagnostics_root.join("daemon/current.jsonl")).unwrap();
+ let stages = stage_records(&log);
+ assert_eq!(stages.len(), 2);
+ assert_eq!(stages[0].stage, "native_credential_read");
+ assert_eq!(stages[0].outcome, "\"entered\"");
+ assert!(
+ stages[1].outcome.contains(expected),
+ "missing {expected}: {stages:?}"
+ );
+ assert!(!log.contains("sentinel"), "credential or path leaked");
+ assert!(
+ !log.contains(&root.path().display().to_string()),
+ "source root leaked"
+ );
+ }
+}
diff --git a/crates/cpa-bridge/src/runtime/tests/request_io.rs b/crates/cpa-bridge/src/runtime/tests/request_io.rs
index 87cf2dd9..22f4e4a0 100644
--- a/crates/cpa-bridge/src/runtime/tests/request_io.rs
+++ b/crates/cpa-bridge/src/runtime/tests/request_io.rs
@@ -788,3 +788,35 @@ fn controlled_io_cleanup_preserves_a_timeout_or_poisoning_panic() {
worker.join().unwrap();
}
}
+
+#[test]
+fn cpa_auth_rejection_preserves_native_or_independent_repair_mode() {
+ for kind in [
+ SourceKind::NativeCodex,
+ SourceKind::NativeClaude,
+ SourceKind::ManagedCodex,
+ ] {
+ let fixture = active_fixture(kind);
+ *fixture.control.inner.discovery_error.lock() =
+ Some(AccountDiscoveryError::AuthenticationRequired);
+ let Err(error) = fixture.runtime.discover_materializations(None) else {
+ panic!("CPA rejects this credential");
+ };
+ let failure = error
+ .subscription_failure()
+ .expect("closed credential cause");
+ assert_eq!(
+ failure.context,
+ match kind {
+ SourceKind::ManagedCodex => "subscription.managed.login-required",
+ SourceKind::NativeCodex | SourceKind::NativeClaude =>
+ "subscription.native.login-invalid",
+ }
+ );
+ assert_eq!(
+ crate::cpa_subscription_availability(Err(&error)),
+ crate::CpaSubscriptionAvailability::NeedsAuthentication
+ );
+ fixture.runtime.shutdown().unwrap();
+ }
+}
diff --git a/crates/cpa-bridge/src/subscription.rs b/crates/cpa-bridge/src/subscription.rs
index 73794419..3f3bd5e9 100644
--- a/crates/cpa-bridge/src/subscription.rs
+++ b/crates/cpa-bridge/src/subscription.rs
@@ -433,6 +433,9 @@ fn invalid_materialization() -> PortError {
}
fn map_lifecycle_error(error: CpaLifecycleError) -> PortError {
+ if let Some(failure) = error.subscription_failure() {
+ return failure;
+ }
let (code, context) = match error {
CpaLifecycleError::BorrowedCodexAuthSourceChanged
| CpaLifecycleError::BorrowedClaudeAuthSourceChanged
@@ -442,18 +445,6 @@ fn map_lifecycle_error(error: CpaLifecycleError) -> PortError {
CpaLifecycleError::StaleSourceManagement => {
(PortErrorCode::Conflict, "cpa-subscription-management-stale")
}
- CpaLifecycleError::BorrowedClaudeAuthMissing
- | CpaLifecycleError::ManagedOAuthCredentialsMissing
- | CpaLifecycleError::InvalidManagedOAuthCredentials
- | CpaLifecycleError::ManagedOAuthAuthenticationRequired
- | CpaLifecycleError::BorrowedClaudeAuthUnavailable
- | CpaLifecycleError::InvalidBorrowedClaudeAuth
- | CpaLifecycleError::BorrowedCodexAuthMissing
- | CpaLifecycleError::BorrowedCodexAuthUnavailable
- | CpaLifecycleError::InvalidBorrowedCodexAuth => (
- PortErrorCode::PermissionDenied,
- "cpa-subscription-needs-auth",
- ),
CpaLifecycleError::InvalidMaterialization | CpaLifecycleError::InvalidSpec => (
PortErrorCode::InvalidData,
"cpa-subscription-materialization",
@@ -496,6 +487,9 @@ pub fn cpa_subscription_availability(
| CpaLifecycleError::InvalidBorrowedClaudeAuth
| CpaLifecycleError::BorrowedClaudeAuthSourceChanged
| CpaLifecycleError::BorrowedCodexAuthMissing
+ | CpaLifecycleError::BorrowedCodexStoreUnsupported
+ | CpaLifecycleError::BorrowedCodexLoginUnsupported
+ | CpaLifecycleError::BorrowedCodexAccountMissing
| CpaLifecycleError::BorrowedCodexAuthUnavailable
| CpaLifecycleError::InvalidBorrowedCodexAuth
| CpaLifecycleError::BorrowedCodexAuthSourceChanged,
diff --git a/crates/cpa-bridge/src/subscription/tests.rs b/crates/cpa-bridge/src/subscription/tests.rs
index 4f8d4482..3122b4b8 100644
--- a/crates/cpa-bridge/src/subscription/tests.rs
+++ b/crates/cpa-bridge/src/subscription/tests.rs
@@ -437,6 +437,9 @@ fn artifact_auth_and_runtime_failures_have_distinct_subscription_states() {
CpaLifecycleError::InvalidBorrowedClaudeAuth,
CpaLifecycleError::BorrowedClaudeAuthSourceChanged,
CpaLifecycleError::BorrowedCodexAuthSourceChanged,
+ CpaLifecycleError::BorrowedCodexStoreUnsupported,
+ CpaLifecycleError::BorrowedCodexLoginUnsupported,
+ CpaLifecycleError::BorrowedCodexAccountMissing,
] {
assert_eq!(
cpa_subscription_availability(Err(&error)),
diff --git a/crates/daemon/src/control/bin.rs b/crates/daemon/src/control/bin.rs
index 2c47caa1..e6a0f37e 100644
--- a/crates/daemon/src/control/bin.rs
+++ b/crates/daemon/src/control/bin.rs
@@ -488,18 +488,15 @@ fn standalone_host_target() -> String {
#[cfg(unix)]
fn standalone_private_directory(path: &std::path::Path) -> Result<(), String> {
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
-
- std::fs::create_dir_all(path).map_err(|_| "standalone directory is unavailable")?;
- std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
+ use std::os::unix::fs::DirBuilderExt;
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(path)
.map_err(|_| "standalone directory is unavailable")?;
let metadata =
std::fs::symlink_metadata(path).map_err(|_| "standalone directory is unavailable")?;
- if !metadata.is_dir()
- || metadata.file_type().is_symlink()
- || metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.permissions().mode() & 0o777 != 0o700
- {
+ if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err("standalone directory is unsafe".into());
}
Ok(())
diff --git a/crates/daemon/src/control/managed.rs b/crates/daemon/src/control/managed.rs
index bbbcf232..1127520d 100644
--- a/crates/daemon/src/control/managed.rs
+++ b/crates/daemon/src/control/managed.rs
@@ -12,7 +12,7 @@ use hiroute_application_api::{
use super::{
AgentGrantResolverPort, ControlConnectionAdmission, ControlConnectionBudgets, EndpointGuard,
- LocalControlDaemon, bind_listener, same_uid, spawn_control_connection,
+ LocalControlDaemon, bind_listener, spawn_control_connection,
};
const ACCEPT_POLL: Duration = Duration::from_millis(20);
@@ -194,9 +194,6 @@ fn run_listener(
while !shutdown.load(Ordering::Acquire) {
match listener.accept() {
Ok((stream, _)) => {
- if !same_uid(&stream)? {
- continue;
- }
// Some Unix implementations inherit O_NONBLOCK from the listener. Frame reads
// use an absolute socket deadline and therefore require a blocking accepted fd.
stream
@@ -214,9 +211,6 @@ fn run_listener(
if let (Some(raw_listener), Some(resolver)) = (&raw_listener, &resolver) {
match raw_listener.accept() {
Ok((stream, _)) => {
- if !same_uid(&stream)? {
- continue;
- }
stream
.set_nonblocking(false)
.map_err(|error| error.to_string())?;
@@ -255,7 +249,7 @@ fn bind_agent_grant_listener(
runtime_root: &Path,
) -> Result<(std::os::unix::net::UnixListener, EndpointGuard), String> {
use std::fs;
- use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
+ use std::os::unix::fs::{FileTypeExt, PermissionsExt};
use std::os::unix::net::{UnixListener, UnixStream};
let path = runtime_root.join("hiroute/agent-grant-v1.sock");
@@ -263,15 +257,11 @@ fn bind_agent_grant_listener(
.parent()
.ok_or_else(|| "Agent grant endpoint has no parent".to_owned())?;
let parent_metadata = fs::symlink_metadata(parent).map_err(|error| error.to_string())?;
- if parent_metadata.file_type().is_symlink()
- || !parent_metadata.file_type().is_dir()
- || parent_metadata.permissions().mode() & 0o777 != 0o700
- || parent_metadata.uid() != nix::unistd::geteuid().as_raw()
- {
- return Err("Agent grant runtime directory is not owner-only".to_owned());
+ if parent_metadata.file_type().is_symlink() || !parent_metadata.file_type().is_dir() {
+ return Err("Agent grant runtime path is not a regular directory".to_owned());
}
if let Ok(metadata) = fs::symlink_metadata(&path) {
- if !metadata.file_type().is_socket() || metadata.uid() != nix::unistd::geteuid().as_raw() {
+ if !metadata.file_type().is_socket() {
return Err("refusing to replace an unowned Agent grant endpoint".to_owned());
}
match UnixStream::connect(&path) {
@@ -289,10 +279,7 @@ fn bind_agent_grant_listener(
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))
.map_err(|error| error.to_string())?;
let metadata = fs::symlink_metadata(&path).map_err(|error| error.to_string())?;
- if !metadata.file_type().is_socket()
- || metadata.permissions().mode() & 0o777 != 0o600
- || metadata.uid() != nix::unistd::geteuid().as_raw()
- {
+ if !metadata.file_type().is_socket() {
let _ = fs::remove_file(&path);
return Err("Agent grant endpoint is not owner-only".to_owned());
}
diff --git a/crates/daemon/src/control/mod.rs b/crates/daemon/src/control/mod.rs
index f1856213..4a55ea62 100644
--- a/crates/daemon/src/control/mod.rs
+++ b/crates/daemon/src/control/mod.rs
@@ -413,7 +413,7 @@ fn bind_listener(
),
String,
> {
- use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
+ use std::os::unix::fs::{FileTypeExt, PermissionsExt};
use std::os::unix::net::{UnixListener, UnixStream};
let endpoint = ControlEndpoint::from_runtime_root(runtime_root);
@@ -421,19 +421,18 @@ fn bind_listener(
.path()
.parent()
.ok_or_else(|| "Local Control endpoint has no parent".to_owned())?;
- fs::create_dir_all(parent).map_err(|error| error.to_string())?;
- fs::set_permissions(parent, fs::Permissions::from_mode(0o700))
+ use std::os::unix::fs::DirBuilderExt;
+ fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(parent)
.map_err(|error| error.to_string())?;
let parent_metadata = fs::symlink_metadata(parent).map_err(|error| error.to_string())?;
- if parent_metadata.file_type().is_symlink()
- || !parent_metadata.file_type().is_dir()
- || parent_metadata.permissions().mode() & 0o077 != 0
- || parent_metadata.uid() != nix::unistd::geteuid().as_raw()
- {
- return Err("Local Control runtime directory is not owner-only".to_owned());
+ if parent_metadata.file_type().is_symlink() || !parent_metadata.file_type().is_dir() {
+ return Err("Local Control runtime path is not a regular directory".to_owned());
}
if let Ok(metadata) = fs::symlink_metadata(endpoint.path()) {
- if !metadata.file_type().is_socket() || metadata.uid() != nix::unistd::geteuid().as_raw() {
+ if !metadata.file_type().is_socket() {
return Err("refusing to replace an unowned Local Control endpoint".to_owned());
}
match UnixStream::connect(endpoint.path()) {
@@ -552,9 +551,6 @@ fn serve_listener_with_budgets(
break;
}
let stream = stream.map_err(|error| error.to_string())?;
- if !same_uid(&stream)? {
- continue;
- }
let Some(admission) = budgets.try_accept() else {
continue;
};
@@ -652,39 +648,6 @@ fn write_frame(writer: &mut impl Write, value: &impl serde::Serialize) -> Result
writer.flush().map_err(|error| error.to_string())
}
-#[cfg(target_os = "linux")]
-fn same_uid(stream: &std::os::unix::net::UnixStream) -> Result<bool, String> {
- let credentials =
- nix::sys::socket::getsockopt(stream, nix::sys::socket::sockopt::PeerCredentials)
- .map_err(|error| error.to_string())?;
- Ok(credentials.uid() == nix::unistd::geteuid().as_raw())
-}
-
-#[cfg(any(
- target_os = "macos",
- target_os = "freebsd",
- target_os = "openbsd",
- target_os = "netbsd"
-))]
-fn same_uid(stream: &std::os::unix::net::UnixStream) -> Result<bool, String> {
- let (uid, _) = nix::unistd::getpeereid(stream).map_err(|error| error.to_string())?;
- Ok(uid == nix::unistd::geteuid())
-}
-
-#[cfg(all(
- unix,
- not(any(
- target_os = "linux",
- target_os = "macos",
- target_os = "freebsd",
- target_os = "openbsd",
- target_os = "netbsd"
- ))
-))]
-fn same_uid(_stream: &std::os::unix::net::UnixStream) -> Result<bool, String> {
- Err("peer credentials are unsupported on this Unix target".to_owned())
-}
-
#[cfg(unix)]
struct EndpointGuard(PathBuf);
diff --git a/crates/daemon/src/control/runtime.rs b/crates/daemon/src/control/runtime.rs
index 678d8283..444e51e6 100644
--- a/crates/daemon/src/control/runtime.rs
+++ b/crates/daemon/src/control/runtime.rs
@@ -1493,14 +1493,9 @@ fn create_owner_key(path: &Path, key: &[u8; 32]) -> Result<(), String> {
#[cfg(unix)]
fn validate_owner_key(path: &Path) -> Result<(), String> {
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
let metadata = fs::symlink_metadata(path).map_err(|error| error.to_string())?;
- if !metadata.file_type().is_file()
- || metadata.file_type().is_symlink()
- || metadata.permissions().mode() & 0o077 != 0
- || metadata.uid() != nix::unistd::geteuid().as_raw()
- {
- return Err("observation authority key is not owner-only".to_owned());
+ if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {
+ return Err("observation authority key is not a regular file".to_owned());
}
Ok(())
}
diff --git a/crates/daemon/src/control/runtime/collaboration_installation.rs b/crates/daemon/src/control/runtime/collaboration_installation.rs
index 16bb800c..c831b7be 100644
--- a/crates/daemon/src/control/runtime/collaboration_installation.rs
+++ b/crates/daemon/src/control/runtime/collaboration_installation.rs
@@ -138,13 +138,6 @@ fn read_private(path: &std::path::Path) -> PortResult<Zeroizing<String>> {
if metadata.file_type().is_symlink() || !metadata.is_file() {
return Err(error());
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw() || metadata.mode() & 0o077 != 0 {
- return Err(error());
- }
- }
let mut encoded = Zeroizing::new(String::new());
let mut file: Take<fs::File> = fs::File::open(path).map_err(|_| error())?.take(4097);
file.read_to_string(&mut encoded).map_err(|_| error())?;
diff --git a/crates/daemon/src/control/runtime/delegation_maintenance_tests.rs b/crates/daemon/src/control/runtime/delegation_maintenance_tests.rs
index 1d20ca91..512784ca 100644
--- a/crates/daemon/src/control/runtime/delegation_maintenance_tests.rs
+++ b/crates/daemon/src/control/runtime/delegation_maintenance_tests.rs
@@ -27,7 +27,6 @@ const SUCCESS_TEST: &str = "control::runtime::delegation_maintenance::tests::own
#[derive(Clone, Copy)]
enum BlockedFixture {
ReplacedIdentity,
- NonPrivatePermissions,
MarkerFinalizationInterrupted,
}
@@ -46,7 +45,6 @@ fn blocked_native_deletion_remains_claimed_and_unacknowledged() {
return;
}
assert_blocked_cleanup(BlockedFixture::ReplacedIdentity, "identity");
- assert_blocked_cleanup(BlockedFixture::NonPrivatePermissions, "permissions");
assert_blocked_cleanup(
BlockedFixture::MarkerFinalizationInterrupted,
"marker-interrupted",
@@ -67,11 +65,6 @@ fn assert_blocked_cleanup(fixture: BlockedFixture, suffix: &str) {
private_directory(&cleanup.native_root);
true
}
- BlockedFixture::NonPrivatePermissions => {
- std::fs::set_permissions(&cleanup.native_root, std::fs::Permissions::from_mode(0o755))
- .unwrap();
- true
- }
BlockedFixture::MarkerFinalizationInterrupted => {
std::fs::remove_file(
cleanup
@@ -130,7 +123,14 @@ fn owned_native_deletion_commits_removed_before_exact_ack() {
if crate::test_support::isolated_agent_home(SUCCESS_TEST) {
return;
}
- let cleanup = cleanup_fixture("success");
+ for mode in [0o700, 0o755] {
+ assert_owned_cleanup(mode);
+ }
+}
+
+fn assert_owned_cleanup(mode: u32) {
+ let cleanup = cleanup_fixture(&format!("success-{mode}"));
+ std::fs::set_permissions(&cleanup.native_root, std::fs::Permissions::from_mode(mode)).unwrap();
std::fs::write(cleanup.native_root.join("history.jsonl"), b"native history").unwrap();
let mut remaining = DELETE_BUDGET;
cleanup
diff --git a/crates/daemon/src/control/runtime/model_connections.rs b/crates/daemon/src/control/runtime/model_connections.rs
index 64f9e23d..2460dbee 100644
--- a/crates/daemon/src/control/runtime/model_connections.rs
+++ b/crates/daemon/src/control/runtime/model_connections.rs
@@ -1,7 +1,6 @@
use hiroute_application::compute_management::{
ComputeCandidatePort, ComputeManagementPlanner, ComputeManagementPlanningErrorV2,
ComputeManagementPresentationFactsV1, ProtectedInputSourceDescriptorV1,
- query_compute_management_with_presentation,
};
use hiroute_application::control::{ComputeManagementControlError, ComputeManagementControlPort};
use hiroute_application::subscriptions::{
@@ -521,6 +520,15 @@ impl ComputeManagementControlPort for LocalControlAdapter {
&self,
query: &ComputeManagementQueryV2,
) -> Result<ComputeManagementSnapshotV2, ComputeManagementControlError> {
+ self.compute_management_snapshot_v3(query)
+ .map(|view| view.into_v2())
+ }
+
+ fn compute_management_snapshot_v3(
+ &self,
+ query: &ComputeManagementQueryV2,
+ ) -> Result<hiroute_application_api::ComputeManagementSnapshotV3, ComputeManagementControlError>
+ {
// Price/catalog collection takes the same storage mutex internally. Capture those safe
// facts first, then take one repository snapshot without nesting the writer lock.
let presentation = match self.compute_management_presentation_facts() {
@@ -534,7 +542,7 @@ impl ComputeManagementControlPort for LocalControlAdapter {
let stores = self
.stores_lock()
.map_err(|_| ComputeManagementControlError::Unavailable)?;
- query_compute_management_with_presentation(
+ hiroute_application::compute_management::query_compute_management_v3(
stores.control(),
stores.runtime(),
&WorkspaceId::default(),
diff --git a/crates/daemon/src/control/runtime/model_connections/presentation.rs b/crates/daemon/src/control/runtime/model_connections/presentation.rs
index 3f943f18..ed6b3eea 100644
--- a/crates/daemon/src/control/runtime/model_connections/presentation.rs
+++ b/crates/daemon/src/control/runtime/model_connections/presentation.rs
@@ -33,6 +33,52 @@ enum ConnectorRuntimeRead {
}
impl LocalControlAdapter {
+ /// Diagnose only a missing saved subscription join, before taking the storage lock.
+ /// Reuse management's exact provider read and source maintenance projection.
+ pub(in crate::control::runtime) fn subscription_routing_unavailability(
+ &self,
+ source: &ComputeManagementSourceV2,
+ ) -> hiroute_application_api::PlanCandidateUnavailableReasonV1 {
+ use hiroute_application_api::PlanCandidateUnavailableReasonV1 as Reason;
+ if let Some(maintenance) = self.subscription_maintenance_presentation(&source.source_id) {
+ return match maintenance {
+ SubscriptionMaintenancePresentation::AuthenticationRequired => {
+ Reason::CredentialUnavailable
+ }
+ SubscriptionMaintenancePresentation::Updating
+ | SubscriptionMaintenancePresentation::RuntimeUnavailable => {
+ Reason::RuntimeUnavailable
+ }
+ };
+ }
+ let ComputeManagementProvenanceV2::ConnectorOwned {
+ connector_id,
+ account_ref,
+ } = &source.provenance
+ else {
+ return Reason::InvalidConfiguration;
+ };
+ let Some(kind) = CpaAccountKind::from_connector(connector_id) else {
+ return Reason::InvalidConfiguration;
+ };
+ match connector_runtime_read(self, kind) {
+ ConnectorRuntimeRead::AuthenticationRequired => Reason::CredentialUnavailable,
+ ConnectorRuntimeRead::Sources(sources)
+ if !sources.iter().any(|registered| {
+ registered.source.connector_id == *connector_id
+ && registered.source.connection_option_id == kind.connection_option_id()
+ && registered.source.identity.account_subject_ref == *account_ref
+ }) =>
+ {
+ Reason::CredentialUnavailable
+ }
+ // A later successful read cannot grant execution to the earlier failed batch.
+ ConnectorRuntimeRead::Sources(_) | ConnectorRuntimeRead::RuntimeUnavailable => {
+ Reason::RuntimeUnavailable
+ }
+ }
+ }
+
pub(super) fn compute_management_presentation_facts(
&self,
) -> Result<ComputeManagementPresentationFactsV1, ComputeManagementControlError> {
diff --git a/crates/daemon/src/control/runtime/routing.rs b/crates/daemon/src/control/runtime/routing.rs
index 8ea2b2cb..77377735 100644
--- a/crates/daemon/src/control/runtime/routing.rs
+++ b/crates/daemon/src/control/runtime/routing.rs
@@ -286,6 +286,37 @@ impl LocalControlAdapter {
.transpose()?
.unwrap_or_default();
let cpa_targets = cpa_batch.as_ref();
+ // Batch discovery intentionally preserves healthy siblings. Diagnose each missing
+ // saved provider separately, outside the storage lock, without changing its facts.
+ let connector_failures = management
+ .sources
+ .iter()
+ .filter_map(|source| {
+ let hiroute_domain::ComputeManagementProvenanceV2::ConnectorOwned {
+ connector_id,
+ account_ref,
+ } = &source.provenance
+ else {
+ return None;
+ };
+ (source.state == MaterializationState::Ready
+ && cpa_targets
+ .and_then(|batch| {
+ unique_live_cpa_source(
+ batch.sources(),
+ connector_id,
+ account_ref,
+ )
+ })
+ .is_none())
+ .then(|| {
+ (
+ source.source_id.clone(),
+ self.subscription_routing_unavailability(source),
+ )
+ })
+ })
+ .collect::<std::collections::BTreeMap<_, _>>();
let stores = self.stores_lock().map_err(super::map_port)?;
let control = stores.control();
let mut inventory_refs = Vec::new();
@@ -583,22 +614,13 @@ impl LocalControlAdapter {
if let Some(candidate) = candidate {
candidates.push(candidate);
} else {
- let runtime_unavailable = match &fact.provenance {
- hiroute_domain::ComputeManagementProvenanceV2::ConnectorOwned {
- connector_id,
- account_ref,
- } => cpa_targets
- .and_then(|batch| {
- unique_live_cpa_source(
- batch.sources(),
- connector_id,
- account_ref,
- )
- })
- .is_none(),
- _ => false,
- };
- diagnostics.materialization_failed(fact, runtime_unavailable);
+ diagnostics.materialization_failed(
+ fact,
+ connector_failures
+ .get(&source.source_id)
+ .copied()
+ .unwrap_or(UnavailableReason::InvalidConfiguration),
+ );
}
}
}
diff --git a/crates/daemon/src/control/runtime/routing_candidates.rs b/crates/daemon/src/control/runtime/routing_candidates.rs
index efe6fd10..92250bbf 100644
--- a/crates/daemon/src/control/runtime/routing_candidates.rs
+++ b/crates/daemon/src/control/runtime/routing_candidates.rs
@@ -121,15 +121,10 @@ impl CandidateDiagnostics {
pub(super) fn materialization_failed(
&mut self,
fact: &ComputeManagementCompilationFactV2,
- runtime_unavailable: bool,
+ reason: Reason,
) {
- // Only the live-source join proves runtime absence. Other preparation failures do not
- // establish a provider/network/credential failure.
- let reason = if runtime_unavailable {
- Reason::RuntimeUnavailable
- } else {
- Reason::InvalidConfiguration
- };
+ // The caller supplies a closed source-specific diagnosis; other preparation failures
+ // do not establish a provider/network/credential failure.
self.insert(&fact.binding_id, &fact.display_name, reason);
}
diff --git a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
index 70f5aba0..d550019e 100644
--- a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
@@ -678,9 +678,9 @@ fn qoder_pending_file_tail_keeps_collaboration_preview_independent_and_retries_e
}
#[test]
-fn qoder_managed_bearer_permission_drift_revokes_live_eligibility_but_allows_restore() {
+fn qoder_managed_bearer_mode_change_preserves_live_eligibility_and_restore() {
if crate::test_support::isolated_agent_home(
- "control::runtime::native_model::tests::settings_entry_tests::qoder::models::qoder_managed_bearer_permission_drift_revokes_live_eligibility_but_allows_restore",
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::models::qoder_managed_bearer_mode_change_preserves_live_eligibility_and_restore",
) {
return;
}
@@ -704,10 +704,19 @@ fn qoder_managed_bearer_permission_drift_revokes_live_eligibility_but_allows_res
0o600
);
fs::set_permissions(&fixture.native_config, fs::Permissions::from_mode(0o644)).unwrap();
- let drift = model_status(&fixture);
- assert_eq!(drift["state"], "drift");
- assert_eq!(drift["model_verified"], false);
- assert!(drift["live_check_targets"].is_null() || drift["live_check_targets"] == json!([]));
+ let current = model_status(&fixture);
+ assert_eq!(current["state"], "configured");
+ assert_eq!(current["model_verified"], status["model_verified"]);
+ assert_eq!(current["live_check_targets"], status["live_check_targets"]);
+ assert!(!current["live_check_targets"].as_array().unwrap().is_empty());
+ assert_eq!(
+ fs::metadata(&fixture.native_config)
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o644
+ );
apply(
&fixture.service,
&fixture.runtime,
diff --git a/crates/daemon/src/control/runtime/settings_facts/codex_models.rs b/crates/daemon/src/control/runtime/settings_facts/codex_models.rs
index b1b4921c..0f8ed7cf 100644
--- a/crates/daemon/src/control/runtime/settings_facts/codex_models.rs
+++ b/crates/daemon/src/control/runtime/settings_facts/codex_models.rs
@@ -194,6 +194,9 @@ impl LocalControlAdapter {
.flatten()
.and_then(|source| {
BorrowedCodexAuthSpec::new(source.source_path())
+ .with_store_config(
+ source.codex_store_config().map(std::path::Path::to_owned),
+ )
.inspect()
.ok()
})?
diff --git a/crates/daemon/src/control/runtime/subscriptions.rs b/crates/daemon/src/control/runtime/subscriptions.rs
index 692f9283..775bed5f 100644
--- a/crates/daemon/src/control/runtime/subscriptions.rs
+++ b/crates/daemon/src/control/runtime/subscriptions.rs
@@ -1029,11 +1029,26 @@ fn subscription_operation_status(
if !operation.state.is_terminal() {
return ComputeSubscriptionCheckStatusV2::Checking;
}
- match operation.safe_error_code.as_deref() {
+ subscription_error_status(operation.safe_error_code.as_deref())
+}
+
+fn subscription_error_status(code: Option<&str>) -> ComputeSubscriptionCheckStatusV2 {
+ match code {
Some("SUBSCRIPTION_SOURCE_CHANGED" | "CHANGE_PREVIEW_STALE") => {
ComputeSubscriptionCheckStatusV2::SourceChanged
}
- Some("SUBSCRIPTION_NEEDS_AUTH") => ComputeSubscriptionCheckStatusV2::NeedsAuth,
+ Some(
+ "SUBSCRIPTION_NEEDS_AUTH"
+ | "SUBSCRIPTION_NATIVE_LOGIN_MISSING"
+ | "SUBSCRIPTION_NATIVE_LOGIN_INVALID"
+ | "SUBSCRIPTION_NATIVE_ACCOUNT_MISSING"
+ | "SUBSCRIPTION_NATIVE_STORE_UNSUPPORTED"
+ | "SUBSCRIPTION_NATIVE_LOGIN_UNSUPPORTED"
+ | "SUBSCRIPTION_MANAGED_LOGIN_REQUIRED",
+ ) => ComputeSubscriptionCheckStatusV2::NeedsAuth,
+ Some("SUBSCRIPTION_NATIVE_READ_FAILED" | "SUBSCRIPTION_NATIVE_CLIENT_UNAVAILABLE") => {
+ ComputeSubscriptionCheckStatusV2::Unavailable
+ }
Some("SUBSCRIPTION_RUNTIME_UNAVAILABLE") => ComputeSubscriptionCheckStatusV2::Unavailable,
_ => ComputeSubscriptionCheckStatusV2::Failed,
}
diff --git a/crates/daemon/src/control/runtime/subscriptions/error.rs b/crates/daemon/src/control/runtime/subscriptions/error.rs
index 8a6b52fd..d5a462e0 100644
--- a/crates/daemon/src/control/runtime/subscriptions/error.rs
+++ b/crates/daemon/src/control/runtime/subscriptions/error.rs
@@ -16,21 +16,13 @@ pub(super) fn map_preparation(error: SubscriptionPreparationError) -> PortError
}
pub(super) fn map_cpa(error: CpaLifecycleError) -> PortError {
+ if let Some(failure) = error.subscription_failure() {
+ return failure;
+ }
match error {
CpaLifecycleError::BorrowedCodexAuthSourceChanged
| CpaLifecycleError::BorrowedClaudeAuthSourceChanged
| CpaLifecycleError::ManagedOAuthAccountChanged => conflict("subscription.source.changed"),
- CpaLifecycleError::BorrowedClaudeAuthMissing
- | CpaLifecycleError::ManagedOAuthCredentialsMissing
- | CpaLifecycleError::ManagedOAuthAuthenticationRequired
- | CpaLifecycleError::BorrowedClaudeAuthUnavailable
- | CpaLifecycleError::InvalidBorrowedClaudeAuth
- | CpaLifecycleError::BorrowedCodexAuthMissing
- | CpaLifecycleError::BorrowedCodexAuthUnavailable
- | CpaLifecycleError::InvalidBorrowedCodexAuth => PortError::new(
- PortErrorCode::PermissionDenied,
- "subscription.authentication",
- ),
_ => unavailable("subscription.cpa.unavailable"),
}
}
diff --git a/crates/daemon/src/control/runtime/subscriptions/lifecycle.rs b/crates/daemon/src/control/runtime/subscriptions/lifecycle.rs
index aa4e27a1..9e5e462b 100644
--- a/crates/daemon/src/control/runtime/subscriptions/lifecycle.rs
+++ b/crates/daemon/src/control/runtime/subscriptions/lifecycle.rs
@@ -202,10 +202,14 @@ impl LocalControlAdapter {
"SUBSCRIPTION_SOURCE_CHANGED",
)));
}
- Err(CpaLifecycleError::ManagedOAuthCredentialsMissing) => {
+ Err(
+ CpaLifecycleError::ManagedOAuthCredentialsMissing
+ | CpaLifecycleError::InvalidManagedOAuthCredentials
+ | CpaLifecycleError::ManagedOAuthAuthenticationRequired,
+ ) => {
return Ok(Some((
ComputeSubscriptionCheckStatusV2::NeedsAuth,
- "SUBSCRIPTION_NEEDS_AUTH",
+ "SUBSCRIPTION_MANAGED_LOGIN_REQUIRED",
)));
}
Err(_) => {
diff --git a/crates/daemon/src/control/runtime/subscriptions/maintenance.rs b/crates/daemon/src/control/runtime/subscriptions/maintenance.rs
index e28c9033..47ec2faf 100644
--- a/crates/daemon/src/control/runtime/subscriptions/maintenance.rs
+++ b/crates/daemon/src/control/runtime/subscriptions/maintenance.rs
@@ -149,6 +149,11 @@ impl LocalControlAdapter {
return housekeeping;
}
+ let cycle_started = std::time::Instant::now();
+ self.emit_subscription_maintenance_cycle(
+ hiroute_diagnostics::event::CpaStageOutcome::Entered,
+ 0,
+ );
for source in sources {
if shutdown_failures.contains(&source.source_id) {
self.set_subscription_maintenance_status(
@@ -231,14 +236,7 @@ impl LocalControlAdapter {
Ok(false) => continue,
Err(error) => {
self.suspend_saved_subscription_execution(&source);
- let status = match error {
- hiroute_cpa_bridge::CpaLifecycleError::ManagedOAuthAccountChanged
- | hiroute_cpa_bridge::CpaLifecycleError::ManagedOAuthAuthenticationRequired
- | hiroute_cpa_bridge::CpaLifecycleError::ManagedOAuthCredentialsMissing => {
- SubscriptionMaintenancePresentation::AuthenticationRequired
- }
- _ => SubscriptionMaintenancePresentation::RuntimeUnavailable,
- };
+ let status = lifecycle_failure_presentation(&error);
self.set_subscription_maintenance_status(&source.source_id, status, None)?;
continue;
}
@@ -257,15 +255,8 @@ impl LocalControlAdapter {
{
None
}
- Ok(_)
- | Err(hiroute_cpa_bridge::CpaLifecycleError::ManagedOAuthAccountChanged)
- | Err(
- hiroute_cpa_bridge::CpaLifecycleError::ManagedOAuthAuthenticationRequired,
- )
- | Err(hiroute_cpa_bridge::CpaLifecycleError::ManagedOAuthCredentialsMissing) => {
- Some(SubscriptionMaintenancePresentation::AuthenticationRequired)
- }
- Err(_) => Some(SubscriptionMaintenancePresentation::RuntimeUnavailable),
+ Ok(_) => Some(SubscriptionMaintenancePresentation::AuthenticationRequired),
+ Err(error) => Some(lifecycle_failure_presentation(&error)),
};
if let Some(status) = status {
self.suspend_saved_subscription_execution(&source);
@@ -299,11 +290,11 @@ impl LocalControlAdapter {
}
// A newer save already won; this old scan has no lifecycle effect.
Ok(false) => {}
- Err(_) => {
+ Err(error) => {
self.suspend_saved_subscription_execution(&source);
self.set_subscription_maintenance_status(
&source.source_id,
- SubscriptionMaintenancePresentation::RuntimeUnavailable,
+ lifecycle_failure_presentation(&error),
None,
)?;
}
@@ -346,9 +337,34 @@ impl LocalControlAdapter {
)?,
}
}
+ self.emit_subscription_maintenance_cycle(
+ hiroute_diagnostics::event::CpaStageOutcome::Completed,
+ cycle_started
+ .elapsed()
+ .as_millis()
+ .min(u128::from(u64::MAX)) as u64,
+ );
housekeeping
}
+ // A completed cycle records that saved-source maintenance ran, not that every source is ready.
+ // Closed stage data contains no source/account reference, path or credential material.
+ fn emit_subscription_maintenance_cycle(
+ &self,
+ outcome: hiroute_diagnostics::event::CpaStageOutcome,
+ elapsed_ms: u64,
+ ) {
+ use hiroute_diagnostics::event::{CpaStage, CpaStageKind};
+ if let Ok(port) = self.publication_diagnostics.lock() {
+ port.emit(hiroute_diagnostics::DiagnosticEvent::CpaStage(CpaStage {
+ stage: CpaStageKind::SubscriptionMaintenance,
+ outcome,
+ elapsed_ms,
+ restart_generation: 0,
+ }));
+ }
+ }
+
fn suspend_subscription_execution(&self) {
for kind in [CpaAccountKind::Codex, CpaAccountKind::Claude] {
self.suspend_subscription_execution_for(kind);
@@ -477,10 +493,7 @@ impl LocalControlAdapter {
.map_err(|_| MaintenanceFailure::RuntimeUnavailable)?
};
if checked.status != ComputeSubscriptionCheckStatusV2::Verified {
- return Err(match checked.reason.as_deref() {
- Some("SUBSCRIPTION_NEEDS_AUTH") => MaintenanceFailure::AuthenticationRequired,
- _ => MaintenanceFailure::RuntimeUnavailable,
- });
+ return Err(check_failure(checked.status));
}
let checked_candidate = checked
.checked_candidate
@@ -747,16 +760,70 @@ fn ensure_operation_succeeded(
if operation.state == OperationState::Succeeded {
return Ok(());
}
- Err(match operation.safe_error_code.as_deref() {
- Some("SUBSCRIPTION_NEEDS_AUTH") => MaintenanceFailure::AuthenticationRequired,
- _ => MaintenanceFailure::RuntimeUnavailable,
- })
+ Err(check_failure(super::subscription_operation_status(
+ operation,
+ )))
+}
+
+fn check_failure(status: ComputeSubscriptionCheckStatusV2) -> MaintenanceFailure {
+ if status == ComputeSubscriptionCheckStatusV2::NeedsAuth {
+ MaintenanceFailure::AuthenticationRequired
+ } else {
+ MaintenanceFailure::RuntimeUnavailable
+ }
+}
+
+fn lifecycle_failure_presentation(
+ error: &hiroute_cpa_bridge::CpaLifecycleError,
+) -> SubscriptionMaintenancePresentation {
+ use hiroute_cpa_bridge::{CpaSubscriptionAvailability, cpa_subscription_availability};
+ if cpa_subscription_availability(Err(error)) == CpaSubscriptionAvailability::NeedsAuthentication
+ {
+ SubscriptionMaintenancePresentation::AuthenticationRequired
+ } else {
+ SubscriptionMaintenancePresentation::RuntimeUnavailable
+ }
}
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn native_credential_causes_keep_authentication_presentation_through_maintenance() {
+ use hiroute_cpa_bridge::CpaLifecycleError as E;
+ for error in [
+ E::BorrowedCodexStoreUnsupported,
+ E::BorrowedCodexLoginUnsupported,
+ E::BorrowedCodexAccountMissing,
+ E::ManagedOAuthAuthenticationRequired,
+ ] {
+ assert_eq!(
+ lifecycle_failure_presentation(&error),
+ SubscriptionMaintenancePresentation::AuthenticationRequired
+ );
+ }
+ for code in [
+ "SUBSCRIPTION_NEEDS_AUTH",
+ "SUBSCRIPTION_NATIVE_STORE_UNSUPPORTED",
+ "SUBSCRIPTION_NATIVE_LOGIN_UNSUPPORTED",
+ "SUBSCRIPTION_NATIVE_ACCOUNT_MISSING",
+ "SUBSCRIPTION_MANAGED_LOGIN_REQUIRED",
+ ] {
+ assert_eq!(
+ check_failure(super::super::subscription_error_status(Some(code))).presentation(),
+ SubscriptionMaintenancePresentation::AuthenticationRequired
+ );
+ }
+ assert_eq!(
+ check_failure(super::super::subscription_error_status(Some(
+ "SUBSCRIPTION_NATIVE_READ_FAILED"
+ )))
+ .presentation(),
+ SubscriptionMaintenancePresentation::RuntimeUnavailable
+ );
+ }
+
#[test]
fn committed_evidence_restores_or_retries_without_looping_the_same_failure() {
let committed = CanonicalDigest::of_bytes(b"committed");
diff --git a/crates/daemon/src/control/standalone.rs b/crates/daemon/src/control/standalone.rs
index 81184c25..9cf21c06 100644
--- a/crates/daemon/src/control/standalone.rs
+++ b/crates/daemon/src/control/standalone.rs
@@ -15,7 +15,7 @@ use zeroize::{Zeroize, Zeroizing};
const IO_TIMEOUT: Duration = Duration::from_secs(2);
-/// Same-user credential input shared by standalone and Desktop-owned role-all processes.
+/// Local credential input shared by standalone and Desktop-owned role-all processes.
pub(super) struct ProtectedInputServer {
listener: UnixListener,
path: PathBuf,
@@ -92,7 +92,6 @@ fn handle_connection(
role: &hiroute_daemon::RoleAllHandle,
mut stream: UnixStream,
) -> Result<(), String> {
- validate_peer_owner(&stream)?;
stream
.set_read_timeout(Some(IO_TIMEOUT))
.map_err(|_| "protected input read timeout setup failed")?;
@@ -196,83 +195,25 @@ fn valid_candidate_ref(value: &str) -> bool {
}
fn validate_private_directory(path: &Path) -> Result<(), String> {
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
let metadata = std::fs::symlink_metadata(path)
.map_err(|_| "protected input socket directory is unavailable")?;
- if !metadata.is_dir()
- || metadata.file_type().is_symlink()
- || metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.permissions().mode() & 0o777 != 0o700
- {
+ if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err("protected input socket directory is unsafe".into());
}
Ok(())
}
fn remove_stale_socket(path: &Path) -> Result<(), String> {
- use std::os::unix::fs::{FileTypeExt, MetadataExt};
+ use std::os::unix::fs::FileTypeExt;
match std::fs::symlink_metadata(path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(_) => Err("protected input socket state is unavailable".into()),
- Ok(metadata)
- if metadata.file_type().is_socket()
- && metadata.uid() == nix::unistd::geteuid().as_raw() =>
- {
- std::fs::remove_file(path)
- .map_err(|_| "protected input stale socket cannot be removed".into())
- }
+ Ok(metadata) if metadata.file_type().is_socket() => std::fs::remove_file(path)
+ .map_err(|_| "protected input stale socket cannot be removed".into()),
Ok(_) => Err("protected input socket path conflicts with another entry".into()),
}
}
-#[cfg(any(target_os = "android", target_os = "linux"))]
-fn validate_peer_owner(stream: &UnixStream) -> Result<(), String> {
- let credentials =
- nix::sys::socket::getsockopt(stream, nix::sys::socket::sockopt::PeerCredentials)
- .map_err(|_| "protected input peer ownership unavailable")?;
- if credentials.uid() != nix::unistd::geteuid().as_raw() {
- return Err("protected input peer ownership mismatch".into());
- }
- Ok(())
-}
-
-#[cfg(any(
- target_os = "dragonfly",
- target_os = "freebsd",
- target_os = "ios",
- target_os = "macos",
- target_os = "netbsd",
- target_os = "openbsd",
- target_os = "tvos",
- target_os = "visionos",
- target_os = "watchos"
-))]
-fn validate_peer_owner(stream: &UnixStream) -> Result<(), String> {
- let (uid, _) = nix::unistd::getpeereid(stream)
- .map_err(|_| "protected input peer ownership unavailable")?;
- if uid != nix::unistd::geteuid() {
- return Err("protected input peer ownership mismatch".into());
- }
- Ok(())
-}
-
-#[cfg(not(any(
- target_os = "android",
- target_os = "dragonfly",
- target_os = "freebsd",
- target_os = "ios",
- target_os = "linux",
- target_os = "macos",
- target_os = "netbsd",
- target_os = "openbsd",
- target_os = "tvos",
- target_os = "visionos",
- target_os = "watchos"
-)))]
-fn validate_peer_owner(_stream: &UnixStream) -> Result<(), String> {
- Err("protected input peer ownership unavailable".into())
-}
-
fn shutdown_signal() -> Result<Receiver<()>, String> {
let (sender, receiver) = mpsc::sync_channel(1);
std::thread::Builder::new()
@@ -350,8 +291,7 @@ mod tests {
layout.runtime_root = runtime;
let server = ProtectedInputServer::bind(&layout).unwrap();
let _client = UnixStream::connect(layout.protected_input_socket()).unwrap();
- let (peer, _) = server.listener.accept().unwrap();
- validate_peer_owner(&peer).unwrap();
+ let (_peer, _) = server.listener.accept().unwrap();
drop(server);
assert!(!layout.protected_input_socket().exists());
}
diff --git a/crates/daemon/src/delegation/installation.rs b/crates/daemon/src/delegation/installation.rs
index 7d5fc05e..9175b41c 100644
--- a/crates/daemon/src/delegation/installation.rs
+++ b/crates/daemon/src/delegation/installation.rs
@@ -250,15 +250,7 @@ fn create_private_child(parent: &Path, name: &str) -> Result<PathBuf, Delegation
}
fn private(metadata: &fs::Metadata) -> bool {
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- metadata.uid() == nix::unistd::geteuid().as_raw() && metadata.mode() & 0o077 == 0
- }
- #[cfg(not(unix))]
- {
- metadata.is_dir()
- }
+ metadata.is_dir()
}
pub(crate) struct ManagedWorkerProfileSource {
@@ -631,8 +623,16 @@ mod tests {
)
.unwrap();
assert_eq!(
- create_private_child(root.path(), "public"),
- Err(DelegationErrorV1::PermissionDenied)
+ create_private_child(root.path(), "public").unwrap(),
+ root.path().join("public")
+ );
+ assert_eq!(
+ fs::metadata(root.path().join("public"))
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o755
);
}
}
diff --git a/crates/daemon/src/delegation/installation/discovery.rs b/crates/daemon/src/delegation/installation/discovery.rs
index 4ed11deb..14906832 100644
--- a/crates/daemon/src/delegation/installation/discovery.rs
+++ b/crates/daemon/src/delegation/installation/discovery.rs
@@ -667,7 +667,7 @@ fn inspect(path: &Path, require_executable: bool) -> MetadataFact {
reason: Some("worker.dependencies.not_executable"),
};
}
- if !require_executable && !readable(&metadata) {
+ if !require_executable && fs::File::open(&canonical).is_err() {
return MetadataFact {
canonical: Some(canonical),
state: WorkerDependencyCandidateStateV1::Invalid,
@@ -772,18 +772,6 @@ fn executable(metadata: &fs::Metadata) -> bool {
}
}
-fn readable(metadata: &fs::Metadata) -> bool {
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- metadata.permissions().mode() & 0o444 != 0
- }
- #[cfg(not(unix))]
- {
- metadata.is_file()
- }
-}
-
fn platform() -> &'static str {
#[cfg(target_os = "macos")]
{
diff --git a/crates/daemon/src/delegation/installation/installation_probe.rs b/crates/daemon/src/delegation/installation/installation_probe.rs
index 981bf5af..d714c92b 100644
--- a/crates/daemon/src/delegation/installation/installation_probe.rs
+++ b/crates/daemon/src/delegation/installation/installation_probe.rs
@@ -596,13 +596,6 @@ fn private_directory(path: &Path) -> Result<(), DelegationErrorV1> {
if !path.is_absolute() || !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(DelegationErrorV1::PermissionDenied);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw() || metadata.mode() & 0o077 != 0 {
- return Err(DelegationErrorV1::PermissionDenied);
- }
- }
Ok(())
}
diff --git a/crates/daemon/src/delegation/native_cleanup.rs b/crates/daemon/src/delegation/native_cleanup.rs
index d795d7b1..5813d031 100644
--- a/crates/daemon/src/delegation/native_cleanup.rs
+++ b/crates/daemon/src/delegation/native_cleanup.rs
@@ -286,10 +286,7 @@ mod unix {
let metadata = child
.metadata()
.map_err(|_| DelegationNativeCleanupFailureKindV1::IoUnavailable)?;
- if metadata.uid() != rustix::process::geteuid().as_raw()
- || metadata.dev() != root_device
- || metadata.ino() != stat.st_ino as u64
- {
+ if metadata.dev() != root_device || metadata.ino() != stat.st_ino as u64 {
return Err(DelegationNativeCleanupFailureKindV1::IdentityMismatch);
}
if !remove_children(&child, root_device, remaining, depth + 1, false)? {
@@ -376,9 +373,7 @@ mod unix {
if !metadata.is_file() || metadata.len() > 4096 {
return Err(DelegationNativeCleanupFailureKindV1::UnsafeEntry);
}
- if metadata.uid() != rustix::process::geteuid().as_raw()
- || metadata.mode() & 0o077 != 0
- || metadata.dev() != expected.marker_device
+ if metadata.dev() != expected.marker_device
|| metadata.ino() != expected.marker_inode
|| metadata.dev() != expected.root_device
{
@@ -470,8 +465,6 @@ mod unix {
fn private_directory(metadata: &std::fs::Metadata) -> bool {
metadata.is_dir()
- && metadata.uid() == rustix::process::geteuid().as_raw()
- && metadata.mode() & 0o077 == 0
}
fn utf8_name(name: &CStr) -> Option<&str> {
diff --git a/crates/daemon/src/delegation/native_cleanup_tests.rs b/crates/daemon/src/delegation/native_cleanup_tests.rs
index 385f6376..4438ba9f 100644
--- a/crates/daemon/src/delegation/native_cleanup_tests.rs
+++ b/crates/daemon/src/delegation/native_cleanup_tests.rs
@@ -197,7 +197,7 @@ fn excessive_directory_depth_is_bounded_and_retained() {
}
#[test]
-fn replacement_identity_and_non_private_permissions_block_deletion() {
+fn replacement_identity_blocks_deletion_but_accessible_modes_do_not() {
let directory = tempfile::tempdir().unwrap();
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
let base_path = std::fs::canonicalize(directory.path()).unwrap();
@@ -224,14 +224,11 @@ fn replacement_identity_and_non_private_permissions_block_deletion() {
let permitted = claimed_root(&base_path, &root_path);
std::fs::set_permissions(&root_path, std::fs::Permissions::from_mode(0o755)).unwrap();
- assert_eq!(
+ assert!(matches!(
delete_native_root_batch(&permitted, 64),
- NativeDeletionOutcome::Blocked {
- kind: DelegationNativeCleanupFailureKindV1::IdentityMismatch,
- processed_entries: 0,
- }
- );
- assert!(root_path.join("replacement").exists());
+ NativeDeletionOutcome::Removed { .. }
+ ));
+ assert!(!root_path.exists());
}
#[test]
diff --git a/crates/daemon/src/delegation/profile/materials.rs b/crates/daemon/src/delegation/profile/materials.rs
index 5f69b07b..4793f2be 100644
--- a/crates/daemon/src/delegation/profile/materials.rs
+++ b/crates/daemon/src/delegation/profile/materials.rs
@@ -178,13 +178,6 @@ impl TaskSessionRoot {
if linked(&metadata) || !metadata.is_file() || metadata.len() > 4096 {
return Err(DelegationErrorV1::ResumeUnavailable);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw() || metadata.mode() & 0o077 != 0 {
- return Err(DelegationErrorV1::ResumeUnavailable);
- }
- }
use std::io::Read;
let mut bytes = Vec::with_capacity(metadata.len() as usize);
file.take(4097)
@@ -266,15 +259,6 @@ impl TaskSessionRoot {
if linked(&metadata) || !metadata.is_file() {
return Err(DelegationErrorV1::PermissionDenied);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.mode() & 0o077 != 0
- {
- return Err(DelegationErrorV1::PermissionDenied);
- }
- }
let mut actual = String::new();
fs::File::open(path)
.and_then(|file| file.take(4097).read_to_string(&mut actual))
@@ -337,10 +321,7 @@ impl TaskSessionRoot {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.mode() & 0o077 != 0
- || metadata.nlink() != 1
- {
+ if metadata.nlink() != 1 {
return Err(DelegationErrorV1::PermissionDenied);
}
}
@@ -399,13 +380,6 @@ fn legacy_native_history(
if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(DelegationErrorV1::ResumeUnavailable);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw() || metadata.mode() & 0o077 != 0 {
- return Err(DelegationErrorV1::ResumeUnavailable);
- }
- }
let durable_root = root.join(match harness {
WorkerHarnessV1::CodexCli => "sessions",
WorkerHarnessV1::ClaudeCode => "projects",
@@ -547,13 +521,6 @@ fn checked_directory(path: &Path) -> Result<PathBuf, DelegationErrorV1> {
if linked(&metadata) || !metadata.is_dir() {
return Err(DelegationErrorV1::PermissionDenied);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw() || metadata.mode() & 0o077 != 0 {
- return Err(DelegationErrorV1::PermissionDenied);
- }
- }
// As with the existing non-Unix managed directory checks, Windows roots must be supplied
// from the already owner-controlled daemon store. This helper is not a new ACL provider.
fs::canonicalize(path).map_err(|_| DelegationErrorV1::CapabilityUnavailable)
diff --git a/crates/daemon/src/delegation/profile/materials_tests.rs b/crates/daemon/src/delegation/profile/materials_tests.rs
index f9472ffe..ed45563a 100644
--- a/crates/daemon/src/delegation/profile/materials_tests.rs
+++ b/crates/daemon/src/delegation/profile/materials_tests.rs
@@ -387,5 +387,9 @@ fn filesystem_aliases_and_history_links_cannot_bypass_checks() {
Err(DelegationErrorV1::ResumeUnavailable)
));
fs::set_permissions(session.path(), fs::Permissions::from_mode(0o755)).unwrap();
- assert!(checked_run_root(&fixture.path().join("run"), &session).is_err());
+ assert!(checked_run_root(&fixture.path().join("run"), &session).is_ok());
+ assert_eq!(
+ fs::metadata(session.path()).unwrap().permissions().mode() & 0o777,
+ 0o755
+ );
}
diff --git a/crates/daemon/src/delegation/profile/native_history.rs b/crates/daemon/src/delegation/profile/native_history.rs
index c5e31116..8dc85adf 100644
--- a/crates/daemon/src/delegation/profile/native_history.rs
+++ b/crates/daemon/src/delegation/profile/native_history.rs
@@ -370,10 +370,7 @@ fn read_owned_json<T: DeserializeOwned>(root: &Path, name: &str) -> Result<T, De
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.mode() & 0o077 != 0
- || metadata.nlink() != 1
- {
+ if metadata.nlink() != 1 {
return Err(DelegationErrorV1::ResumeUnavailable);
}
}
diff --git a/crates/daemon/src/delegation/profile/pi_worker_bridge.mjs b/crates/daemon/src/delegation/profile/pi_worker_bridge.mjs
index b918eeff..8e26083a 100644
--- a/crates/daemon/src/delegation/profile/pi_worker_bridge.mjs
+++ b/crates/daemon/src/delegation/profile/pi_worker_bridge.mjs
@@ -128,9 +128,7 @@ function ownedFile(path, root) {
stat.isSymbolicLink() ||
stat.nlink !== 1 ||
realpathSync(path) !== path ||
- dirname(path) !== root ||
- stat.uid !== process.getuid() ||
- (stat.mode & 0o077) !== 0
+ dirname(path) !== root
)
throw new Error();
if (stat.size > 64 * 1024 * 1024) throw new Error();
diff --git a/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs b/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs
index 7ac4f4d7..846d2abb 100644
--- a/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs
+++ b/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs
@@ -10,6 +10,7 @@ import {
existsSync,
rmSync,
copyFileSync,
+ chmodSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -338,6 +339,7 @@ for (const operation of ["prompt", "load"]) {
if (operation === "prompt") await f.ready();
else await f.send("initialize", { protocolVersion: 1 });
editedHistory(f, replacement);
+ chmodSync(join(f.root, "native-pi.jsonl"), 0o644);
const response =
operation === "load"
? await f.send("session/load", {
diff --git a/crates/daemon/src/role_all.rs b/crates/daemon/src/role_all.rs
index 154fd861..c1ea3056 100644
--- a/crates/daemon/src/role_all.rs
+++ b/crates/daemon/src/role_all.rs
@@ -555,12 +555,18 @@ fn start_cpa(
borrowed_claude_auth: None,
managed_oauth: None,
borrowed_codex_auth: selected_codex_auth().ok().map(|source| {
- BorrowedCodexAuthSpec::new(source).with_executable(
- config
- .codex_desktop_engine
- .clone()
- .unwrap_or_else(|| PathBuf::from("codex")),
- )
+ BorrowedCodexAuthSpec::new(&source)
+ .with_store_config(
+ std::env::var_os("HIROUTE_CODEX_AUTH_SOURCE")
+ .is_none()
+ .then(|| source.with_file_name("config.toml")),
+ )
+ .with_executable(
+ config
+ .codex_desktop_engine
+ .clone()
+ .unwrap_or_else(|| PathBuf::from("codex")),
+ )
}),
bindings: vec![CpaProfileBinding {
account_kind: CpaAccountKind::Codex,
diff --git a/crates/daemon/tests/subscription_management_product.rs b/crates/daemon/tests/subscription_management_product.rs
index 409a2d0d..8f3af30f 100644
--- a/crates/daemon/tests/subscription_management_product.rs
+++ b/crates/daemon/tests/subscription_management_product.rs
@@ -273,6 +273,41 @@ fn assert_subscription_snapshot(
assert!(!public.contains("account/cpa/"));
}
+async fn assert_subscription_route_reason(
+ daemon: &ProductDaemon,
+ binding_id: &str,
+ expected: Option<hiroute_application_api::PlanCandidateUnavailableReasonV1>,
+) {
+ let options = succeeded(
+ daemon
+ .client
+ .query::<_, hiroute_application_api::PlanEditorOptionsV1>(
+ "GetPlanEditorOptions",
+ "subscription-route-reason",
+ &hiroute_application_api::PlanEditorOptionsRequestV1 {
+ include_unavailable: true,
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap(),
+ );
+ let reason = options
+ .unavailable_candidates
+ .iter()
+ .find(|candidate| candidate.binding_id == binding_id)
+ .map(|candidate| candidate.reason);
+ assert_eq!(reason, expected, "saved subscription route reason");
+ assert_eq!(
+ options
+ .candidates
+ .iter()
+ .any(|candidate| candidate.binding_id == binding_id),
+ expected.is_none(),
+ "saved subscription route eligibility"
+ );
+}
+
fn corrupt_saved_display_name(root: &Path, source_id: &str) {
let connection = Connection::open(root.join("storage/live/control.db")).unwrap();
let encoded: String = connection
@@ -859,6 +894,12 @@ async fn hirouted_client_core_subscription_save_snapshot_and_restart_are_closed(
ComputeModelAvailabilityV1::Unavailable,
Some(ComputeModelAvailabilityReasonV1::RuntimeUnavailable),
);
+ assert_subscription_route_reason(
+ &runtime_unavailable,
+ &runtime_snapshot.sources[0].models[0].binding_id,
+ Some(hiroute_application_api::PlanCandidateUnavailableReasonV1::RuntimeUnavailable),
+ )
+ .await;
runtime_unavailable.stop();
fs::set_permissions(&binary, fs::Permissions::from_mode(0o700)).unwrap();
diff --git a/crates/daemon/tests/support/subscription_cache_regression.rs b/crates/daemon/tests/support/subscription_cache_regression.rs
index a35ab6da..26a3dfc1 100644
--- a/crates/daemon/tests/support/subscription_cache_regression.rs
+++ b/crates/daemon/tests/support/subscription_cache_regression.rs
@@ -4,8 +4,7 @@ use hiroute_application_api::ComputeCandidateFactStateV2;
fn cache_fixture() -> (tempfile::TempDir, TcpListener, ProductDaemon) {
let directory = tempfile::tempdir().unwrap();
- // tempfile inherits umask for directories. A group-writable ancestor makes the
- // production diagnostics writer reject this otherwise isolated fixture root.
+ // Keep fixture credentials and diagnostics private, independent of the caller's umask.
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).unwrap();
configure_product_root(directory.path());
let (binary, sha256) = install_subscription_fixture(directory.path());
@@ -472,3 +471,127 @@ async fn cached_checked_candidate_does_not_hide_same_source_lineage_replacement(
);
daemon.stop();
}
+
+fn maintenance_cycle_count(root: &Path) -> usize {
+ fs::read_to_string(root.join("storage/diagnostics/daemon/current.jsonl"))
+ .unwrap_or_default()
+ .lines()
+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
+ .filter(|record| {
+ record["event"]["cpa_stage"]["stage"] == "subscription_maintenance"
+ && record["event"]["cpa_stage"]["outcome"] == "completed"
+ })
+ .count()
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn saved_borrowed_mode_and_membership_survive_native_credential_failures() {
+ let (directory, _proxy, mut daemon) = cache_fixture();
+ let auth_path = directory.path().join("home/.codex/auth.json");
+ let minimal = serde_json::json!({"tokens": {"account_id": "subscription-product-account", "access_token": ACCESS_SENTINEL}});
+ let auth = serde_json::to_vec(&minimal).unwrap();
+ fs::write(&auth_path, &auth).unwrap();
+ fs::set_permissions(&auth_path, fs::Permissions::from_mode(0o644)).unwrap();
+ let checked = check_current(&mut daemon, "compatible-native").await;
+ let saved = save_checked(
+ &daemon,
+ &checked,
+ ComputeManagementIntentV2::SaveReady,
+ "compatible-save",
+ )
+ .await;
+ let source = &saved.sources[0];
+ let stored = saved_source_json(directory.path(), &source.source_id);
+ let config_path = directory.path().join("home/.codex/config.toml");
+ let config = fs::read(&config_path).unwrap_or_default();
+ for case in ["store", "account", "login"] {
+ let mut cycles_before_change = maintenance_cycle_count(directory.path());
+ match case {
+ "store" => {
+ let mut changed = b"cli_auth_credentials_store = \"keyring\"\n".to_vec();
+ changed.extend_from_slice(&config);
+ fs::write(&config_path, changed).unwrap();
+ }
+ "account" => fs::write(&auth_path, serde_json::to_vec(&serde_json::json!({"tokens":{"access_token":ACCESS_SENTINEL}})).unwrap()).unwrap(),
+ _ => fs::write(&auth_path, serde_json::to_vec(&serde_json::json!({"auth_mode":"apikey", "OPENAI_API_KEY":"fixture-api-sentinel"})).unwrap()).unwrap(),
+ }
+ for needs_auth in [true, false] {
+ if !needs_auth {
+ cycles_before_change = maintenance_cycle_count(directory.path());
+ fs::write(&config_path, &config).unwrap();
+ fs::write(&auth_path, &auth).unwrap();
+ }
+ // Two completed cycles cover a cycle already in progress when the source changed.
+ // Do not query first: direct inspection can hide an incorrect maintenance projection.
+ let maintenance_deadline = Instant::now() + Duration::from_secs(25);
+ while maintenance_cycle_count(directory.path()) < cycles_before_change + 2 {
+ assert!(
+ Instant::now() < maintenance_deadline,
+ "saved-source maintenance did not execute for {case}"
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ let snapshot = succeeded(
+ daemon
+ .client
+ .compute_management_snapshot_v3(
+ "saved-credential-mode",
+ ComputeManagementQueryV2 {
+ source_id: Some(source.source_id.clone()),
+ },
+ )
+ .await
+ .unwrap(),
+ );
+ assert_eq!(snapshot.subscription_modes.len(), 1);
+ assert_eq!(
+ snapshot.subscription_modes[0].mode,
+ hiroute_application_api::ComputeSubscriptionModeV1::NativeBorrowed
+ );
+ assert_eq!(
+ snapshot.subscription_modes[0].source_revision,
+ source.revision
+ );
+ let current = &snapshot.sources[0];
+ assert_eq!(current.revision, source.revision);
+ assert_eq!(current.models[0].binding_id, source.models[0].binding_id);
+ let expected = if needs_auth {
+ ComputeModelAvailabilityV1::NeedsCredentials
+ } else {
+ ComputeModelAvailabilityV1::Available
+ };
+ if current.models[0].presentation.availability == expected {
+ if needs_auth {
+ assert_eq!(
+ current.models[0].presentation.reason_code,
+ Some(ComputeModelAvailabilityReasonV1::AuthenticationRequired)
+ );
+ }
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "{case}, needs_auth={needs_auth}: {:?}",
+ current.models[0].presentation
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ assert_subscription_route_reason(
+ &daemon,
+ &source.models[0].binding_id,
+ needs_auth.then_some(
+ hiroute_application_api::PlanCandidateUnavailableReasonV1::CredentialUnavailable,
+ ),
+ )
+ .await;
+ assert_eq!(
+ saved_source_json(directory.path(), &source.source_id),
+ stored
+ );
+ }
+ }
+ assert_eq!(fs::read(auth_path).unwrap(), auth);
+ daemon.stop();
+}
diff --git a/crates/diagnostics/src/event/cpa.rs b/crates/diagnostics/src/event/cpa.rs
index 7872e8f4..c676e062 100644
--- a/crates/diagnostics/src/event/cpa.rs
+++ b/crates/diagnostics/src/event/cpa.rs
@@ -54,6 +54,9 @@ pub struct CpaStage {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CpaStageKind {
+ SubscriptionMaintenance,
+ NativeCredentialRead,
+ ManagedCredentialRead,
ArtifactLocate,
ArtifactValidate,
ProcessSpawn,
@@ -79,6 +82,13 @@ pub enum CpaStageOutcome {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CpaFailureCode {
+ CredentialSourceMissing,
+ CredentialReadFailed,
+ CredentialStoreUnsupported,
+ CredentialLoginUnsupported,
+ CredentialAccountMissing,
+ CredentialInvalid,
+ ManagedLoginRequired,
/// The trusted artifact could not be located or verified.
ArtifactUnavailable,
/// The artifact was found but refused by the bridge contract.
diff --git a/crates/diagnostics/src/files.rs b/crates/diagnostics/src/files.rs
index 53fcc3d2..627b559e 100644
--- a/crates/diagnostics/src/files.rs
+++ b/crates/diagnostics/src/files.rs
@@ -2,8 +2,7 @@
//!
//! On Unix every operation goes through an already-open directory handle (`openat`,
//! `mkdirat`, `renameat`, `unlinkat`) with `O_NOFOLLOW`, and each opened file is verified
-//! by `fstat`: regular file, exactly one hard link, owned by the current user, no group or
-//! other permission bits. Directory and file identities (`dev`, `ino`) are re-checked
+//! by `fstat`: regular file, exactly one hard link, with no owner or mode admission gate. Directory and file identities (`dev`, `ino`) are re-checked
//! before destructive operations, so a replaced path is refused instead of followed.
//!
//! Platforms without equivalent private-path primitives report
@@ -114,8 +113,8 @@ mod unix {
use fs2::FileExt;
use nix::fcntl::{OFlag, open, openat, renameat};
- use nix::sys::stat::{FileStat, Mode, SFlag, fchmod, fstat, mkdirat};
- use nix::unistd::{Uid, UnlinkatFlags, fsync, unlinkat};
+ use nix::sys::stat::{FileStat, Mode, SFlag, fstat, mkdirat};
+ use nix::unistd::{UnlinkatFlags, fsync, unlinkat};
use super::{FileSafetyError, FileSafetyError as E};
@@ -135,18 +134,9 @@ mod unix {
}
}
- fn current_uid() -> u32 {
- Uid::current().as_raw()
- }
-
- fn private_mode(stat: &FileStat) -> bool {
- // Owner-private: no group or other bits at all.
- stat.st_mode & 0o077 == 0
- }
-
fn verify_directory(stat: &FileStat) -> Result<(), FileSafetyError> {
- let is_dir = SFlag::from_bits_truncate(stat.st_mode).contains(SFlag::S_IFDIR);
- if !is_dir || stat.st_uid != current_uid() || !private_mode(stat) {
+ let is_dir = SFlag::from_bits_truncate(stat.st_mode) & SFlag::S_IFMT == SFlag::S_IFDIR;
+ if !is_dir {
return Err(E::UnsafeDirectory);
}
Ok(())
@@ -154,14 +144,14 @@ mod unix {
fn verify_file(stat: &FileStat) -> Result<(), FileSafetyError> {
let kind = SFlag::from_bits_truncate(stat.st_mode);
- let regular = kind.contains(SFlag::S_IFREG);
- if !regular || stat.st_nlink != 1 || stat.st_uid != current_uid() || !private_mode(stat) {
+ let regular = kind & SFlag::S_IFMT == SFlag::S_IFREG;
+ if !regular || stat.st_nlink != 1 {
return Err(E::UnsafeFile);
}
Ok(())
}
- /// A verified, owner-private directory handle. All file operations are relative to
+ /// A verified directory handle. All file operations are relative to
/// this handle, so a path swapped after verification is not followed.
#[derive(Debug)]
pub struct PrivateDir {
@@ -176,8 +166,7 @@ mod unix {
/// and `/var` to `/private/*`) are resolved, using the same rule as the resident
/// ownership validator; nothing else is canonicalized.
///
- /// Intermediate levels must be directories that group/other cannot write, unless they
- /// carry the sticky bit; they are never chmodded. The final level must be owner-private.
+ /// Intermediate levels must be real directories. Every level retains its existing permissions.
/// With `create`, missing levels below the nearest existing ancestor are created 0700,
/// which is how a first start reaches its own root; existing levels are left as they are.
fn open_directory(path: &Path, create: bool) -> Result<PrivateDir, FileSafetyError> {
@@ -197,9 +186,7 @@ mod unix {
Mode::empty(),
)
.map_err(map_errno)?;
- let mut created_final = false;
for (index, name) in names.iter().enumerate() {
- let last = index + 1 == names.len();
let name = Path::new(name);
let child = match openat(
&fd,
@@ -222,7 +209,7 @@ mod unix {
}
Err(nix::errno::Errno::ENOENT) if create => {
match mkdirat(&fd, name, Mode::from_bits_truncate(0o700)) {
- Ok(()) => created_final = last,
+ Ok(()) => {}
// A creation race: the winner's directory is opened and checked.
Err(nix::errno::Errno::EEXIST) => {}
Err(errno) => return Err(map_errno(errno)),
@@ -242,19 +229,6 @@ mod unix {
Err(nix::errno::Errno::ENOENT) => return Err(E::NotFound),
Err(errno) => return Err(map_errno(errno)),
};
- let stat = fstat(child.as_fd()).map_err(map_errno)?;
- if last {
- if !private_mode(&stat) {
- if !created_final {
- // A pre-existing non-private level is refused, never chmodded.
- return Err(E::UnsafeDirectory);
- }
- make_private_created(&child)?;
- }
- } else if stat.st_mode & 0o022 != 0 && stat.st_mode & 0o1000 == 0 {
- // Anyone who may write this level can replace the entry below it.
- return Err(E::UnsafeDirectory);
- }
fd = child;
}
let stat = fstat(fd.as_fd()).map_err(map_errno)?;
@@ -310,37 +284,8 @@ mod unix {
}
}
- /// A level created by this call may have lost its 0700 mode to a creation race with a
- /// wider umask. Correct it only when it is empty and owned by us; anything else is
- /// refused instead of repaired.
- fn make_private_created(fd: &OwnedFd) -> Result<(), FileSafetyError> {
- let stat = fstat(fd.as_fd()).map_err(map_errno)?;
- if private_mode(&stat) {
- return Ok(());
- }
- if stat.st_uid != current_uid() || !directory_is_empty(fd)? {
- return Err(E::UnsafeDirectory);
- }
- fchmod(fd.as_fd(), Mode::from_bits_truncate(0o700)).map_err(map_errno)?;
- let stat = fstat(fd.as_fd()).map_err(map_errno)?;
- verify_directory(&stat)
- }
-
- fn directory_is_empty(fd: &OwnedFd) -> Result<bool, FileSafetyError> {
- let duplicate = fd.try_clone().map_err(map_io)?;
- let mut dir = nix::dir::Dir::from_fd(duplicate).map_err(map_errno)?;
- for entry in dir.iter() {
- let entry = entry.map_err(map_errno)?;
- let name = entry.file_name().to_string_lossy().into_owned();
- if name != "." && name != ".." {
- return Ok(false);
- }
- }
- Ok(true)
- }
-
impl PrivateDir {
- /// Open an existing directory and require private ownership and mode.
+ /// Open an existing directory and verify its type and stable identity.
pub fn open_existing(path: &Path) -> Result<Self, FileSafetyError> {
open_directory(path, false)
}
@@ -353,13 +298,6 @@ mod unix {
open_directory(path, true)
}
- /// When another process won a creation race with a wider umask, the freshly
- /// created directory may lack 0700. Correct it only when it is empty and owned by
- /// us, then re-verify the handle.
- fn make_private_if_raced(&self) -> Result<(), FileSafetyError> {
- make_private_created(&self.fd)
- }
-
pub fn path(&self) -> &Path {
&self.path
}
@@ -383,11 +321,10 @@ mod unix {
if !is_plain_component(name) {
return Err(E::UnsafeDirectory);
}
- let existed = match fstatat_child(&self.fd, name) {
- Ok(_) => true,
+ match fstatat_child(&self.fd, name) {
+ Ok(_) => {}
Err(E::NotFound) => {
mkdirat(&self.fd, name, Mode::from_bits_truncate(0o700)).map_err(map_errno)?;
- false
}
Err(other) => return Err(other),
};
@@ -406,9 +343,6 @@ mod unix {
fd,
identity,
};
- if !existed {
- child.make_private_if_raced()?;
- }
Ok(child)
}
diff --git a/crates/diagnostics/src/writer.rs b/crates/diagnostics/src/writer.rs
index 66787737..3d152741 100644
--- a/crates/diagnostics/src/writer.rs
+++ b/crates/diagnostics/src/writer.rs
@@ -598,7 +598,6 @@ mod tests {
use crate::queue::bounded_queue;
use crate::record::Component;
use crate::shared::Shared;
- use std::os::unix::fs::PermissionsExt;
fn record_bytes() -> Vec<u8> {
DiagnosticRecordV1 {
@@ -698,7 +697,7 @@ mod tests {
assert!(counters.bytes_written() > 0);
let log_path = root.join(CURRENT_LOG_FILE);
- std::fs::set_permissions(&log_path, std::fs::Permissions::from_mode(0o644)).expect("chmod");
+ std::fs::hard_link(&log_path, root.join("foreign-link")).expect("hardlink");
assert!(
sender
.try_push(DiagnosticLevel::Debug, record_bytes())
@@ -714,8 +713,7 @@ mod tests {
// The environment is repaired; the writer reopens and its exit record becomes
// writable again.
- std::fs::set_permissions(&log_path, std::fs::Permissions::from_mode(0o600))
- .expect("restore");
+ std::fs::remove_file(root.join("foreign-link")).expect("restore single link");
let deadline = Instant::now() + Duration::from_secs(10);
while health.snapshot().is_some() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(25));
diff --git a/crates/diagnostics/tests/files_safety.rs b/crates/diagnostics/tests/files_safety.rs
index 4992300e..d6471cd7 100644
--- a/crates/diagnostics/tests/files_safety.rs
+++ b/crates/diagnostics/tests/files_safety.rs
@@ -100,15 +100,15 @@ fn hard_linked_log_file_is_refused() {
}
#[test]
-fn group_readable_file_and_directory_are_refused() {
+fn readable_file_and_directory_modes_are_preserved() {
let (temp, root) = private_root();
let _outside = sentinel(&temp);
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o755)).expect("chmod dir");
+ PrivateDir::open_existing(&root).expect("accessible directory");
assert_eq!(
- PrivateDir::open_existing(&root).expect_err("dir mode must be refused"),
- FileSafetyError::UnsafeDirectory
+ std::fs::metadata(&root).unwrap().permissions().mode() & 0o777,
+ 0o755
);
- std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).expect("chmod dir");
let dir = PrivateDir::open_existing(&root).expect("open root");
let mut file = dir.create_new(SETTINGS_FILE).expect("create");
file.append(b"x").expect("append");
@@ -120,8 +120,19 @@ fn group_readable_file_and_directory_are_refused() {
.expect("chmod file");
assert_eq!(
dir.open_read(SETTINGS_FILE)
- .expect_err("file mode must be refused"),
- FileSafetyError::UnsafeFile
+ .unwrap()
+ .unwrap()
+ .read_prefix(10)
+ .unwrap(),
+ b"x"
+ );
+ assert_eq!(
+ std::fs::metadata(root.join(SETTINGS_FILE))
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o644
);
}
@@ -275,19 +286,26 @@ fn missing_parent_chain_is_created_without_touching_existing_levels() {
assert_eq!(dir.path(), root.as_path());
}
-/// A world/group writable ancestor without the sticky bit lets anyone replace the entry
-/// we are about to trust, so it is refused instead of used or repaired.
+/// Existing local directory permissions are not an admission or automatic chmod trigger.
#[test]
-fn writable_non_sticky_ancestor_is_refused() {
+fn writable_non_sticky_ancestor_is_accepted_without_chmod() {
let temp = support::private_tempdir();
let loose = temp.path().join("loose-parent");
std::fs::create_dir(&loose).expect("create loose parent");
std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(0o777)).expect("chmod");
+ PrivateDir::open_or_create(&loose.join("diagnostics")).unwrap();
assert_eq!(
- PrivateDir::open_or_create(&loose.join("diagnostics")).expect_err("must refuse"),
- FileSafetyError::UnsafeDirectory
+ std::fs::metadata(&loose).unwrap().permissions().mode() & 0o777,
+ 0o777
+ );
+ assert_eq!(
+ std::fs::metadata(loose.join("diagnostics"))
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o700
);
- assert!(!loose.join("diagnostics").exists());
}
/// An ancestor replaced by a symlink must be refused before anything is opened or created
@@ -332,8 +350,7 @@ fn ancestor_symlink_to_external_private_directory_is_refused() {
);
}
-/// An already-open handle must not keep writing after the file becomes group readable or
-/// multiply linked; the next append re-checks the open descriptor.
+/// Chmod does not block an open handle; hardlink replacement still prevents further writes.
#[test]
fn append_rechecks_the_open_file_after_chmod_and_hardlink() {
let (_temp, root) = private_root();
@@ -345,20 +362,18 @@ fn append_rechecks_the_open_file_after_chmod_and_hardlink() {
std::fs::Permissions::from_mode(0o644),
)
.expect("chmod");
- assert_eq!(
- file.append(b"second\n").expect_err("chmodded file refused"),
- FileSafetyError::UnsafeFile
- );
+ file.append(b"second\n")
+ .expect("chmod does not revoke access");
std::fs::set_permissions(
root.join(CURRENT_LOG_FILE),
std::fs::Permissions::from_mode(0o600),
)
.expect("chmod back");
file.append(b"third\n").expect("append after repair");
- // The raw bytes show that the refused writes never reached the file.
+ // Both permission modes allow writing to the same stable file.
assert_eq!(
std::fs::read(root.join(CURRENT_LOG_FILE)).expect("raw read"),
- b"first\nthird\n"
+ b"first\nsecond\nthird\n"
);
std::fs::hard_link(root.join(CURRENT_LOG_FILE), root.join("outside-link.jsonl"))
.expect("hard link");
@@ -370,7 +385,7 @@ fn append_rechecks_the_open_file_after_chmod_and_hardlink() {
drop(file);
assert_eq!(
std::fs::read(root.join(CURRENT_LOG_FILE)).expect("raw read"),
- b"first\nthird\n",
+ b"first\nsecond\nthird\n",
"the multiply linked file stayed untouched"
);
}
diff --git a/crates/diagnostics/tests/writer_bounds.rs b/crates/diagnostics/tests/writer_bounds.rs
index 3b08cf76..bbef5b58 100644
--- a/crates/diagnostics/tests/writer_bounds.rs
+++ b/crates/diagnostics/tests/writer_bounds.rs
@@ -408,11 +408,12 @@ fn writer_enforces_single_record_size_limit() {
}
#[test]
-fn unsafe_role_directory_is_reported_instead_of_blocking_startup() {
+fn symlinked_role_directory_is_reported_instead_of_blocking_startup() {
let temp = support::private_tempdir();
let root = temp.path().join("diagnostics");
- std::fs::create_dir(&root).expect("create root");
- std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o755)).expect("chmod");
+ let outside = temp.path().join("outside");
+ std::fs::create_dir(&outside).unwrap();
+ std::os::unix::fs::symlink(&outside, &root).unwrap();
let runtime = DiagnosticRuntime::start(RuntimeConfig {
root,
role: ProcessRole::Desktop,
@@ -621,13 +622,12 @@ fn shutdown_drain_counts_records_it_cannot_write() {
}
assert!(counters.bytes_written() > 0, "the first record is written");
- // Another owner breaks the open file's privacy: every later append must be refused, so
- // the records still queued when the queue closes are the ones the drain cannot write.
- std::fs::set_permissions(
+ // A hardlink violates stable single-file ownership even though broad modes are allowed.
+ std::fs::hard_link(
dir.path().join(CURRENT_LOG_FILE),
- std::fs::Permissions::from_mode(0o644),
+ dir.path().join("foreign-link"),
)
- .expect("chmod");
+ .unwrap();
for sequence in 10..14 {
let _ = sender.try_push(DiagnosticLevel::Debug, record_bytes(sequence, now_ms()));
}
diff --git a/crates/gateway/src/replay/secure_path/unix.rs b/crates/gateway/src/replay/secure_path/unix.rs
index fc6768f2..041d6cc8 100644
--- a/crates/gateway/src/replay/secure_path/unix.rs
+++ b/crates/gateway/src/replay/secure_path/unix.rs
@@ -233,16 +233,8 @@ fn identity_at(parent: &File, name: &str) -> Result<(FileIdentity, bool), Replay
fn validate(file: &File, directory: bool) -> Result<(), ReplayError> {
let metadata = file.metadata()?;
- if metadata.is_dir() != directory
- || metadata.is_file() == directory
- || metadata.uid() != rustix::process::geteuid().as_raw()
- || metadata.mode() & 0o077 != 0
- {
- return Err(if metadata.mode() & 0o077 != 0 {
- ReplayError::UnsafePermissions
- } else {
- ReplayError::UnsafePath
- });
+ if metadata.is_dir() != directory || metadata.is_file() == directory {
+ return Err(ReplayError::UnsafePath);
}
Ok(())
}
diff --git a/crates/gateway/src/replay/tests.rs b/crates/gateway/src/replay/tests.rs
index c9553120..c74a00b7 100644
--- a/crates/gateway/src/replay/tests.rs
+++ b/crates/gateway/src/replay/tests.rs
@@ -291,17 +291,18 @@ fn equal_length_plaintext_changes_are_inside_the_owner_trust_boundary() {
#[cfg(unix)]
#[test]
-fn permissions_symlinks_and_path_escape_fail_closed() {
+fn accessible_modes_work_while_symlinks_and_path_escape_fail_closed() {
use std::os::unix::fs::{PermissionsExt, symlink};
let unsafe_root = TestRoot::new("permissions-root");
fs::create_dir(&unsafe_root.0).expect("create unsafe root");
fs::set_permissions(&unsafe_root.0, fs::Permissions::from_mode(0o755))
.expect("set unsafe root mode");
- assert!(matches!(
- ReplayManager::open(config(&unsafe_root.0, 64, 16)),
- Err(ReplayError::UnsafePermissions)
- ));
+ assert!(ReplayManager::open(config(&unsafe_root.0, 64, 16)).is_ok());
+ assert_eq!(
+ fs::metadata(&unsafe_root.0).unwrap().permissions().mode() & 0o777,
+ 0o755
+ );
let target = TestRoot::new("symlink-target");
fs::create_dir(&target.0).expect("create target");
@@ -321,10 +322,17 @@ fn permissions_symlinks_and_path_escape_fail_closed() {
let reference = writer.seal().expect("seal");
let path = store.stream_path(&reference).expect("disk path");
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("loosen file mode");
- assert!(matches!(
- store.prevalidate(std::slice::from_ref(&reference)),
- Err(ReplayError::UnsafePermissions)
- ));
+ let original_spill = fs::File::open(&path).expect("retain spill metadata handle");
+ store.prevalidate(std::slice::from_ref(&reference)).unwrap();
+ assert_eq!(read_all(&store, &reference), vec![7_u8; 256]);
+ assert_eq!(
+ original_spill.metadata().unwrap().permissions().mode() & 0o777,
+ 0o644
+ );
+ assert!(
+ !path.exists(),
+ "prevalidation retains a handle and unlinks the spill"
+ );
let escaped = root.0.join("child").join("..").join("other");
assert!(matches!(
diff --git a/crates/gateway/src/runtime/stream_capture.rs b/crates/gateway/src/runtime/stream_capture.rs
index f6b35968..88974c3d 100644
--- a/crates/gateway/src/runtime/stream_capture.rs
+++ b/crates/gateway/src/runtime/stream_capture.rs
@@ -104,11 +104,7 @@ fn read_private(path: &Path, limit: u64) -> io::Result<Vec<u8>> {
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(path)?;
let metadata = file.metadata()?;
- if !metadata.is_file()
- || metadata.mode() & 0o777 != 0o600
- || metadata.uid() != rustix::process::geteuid().as_raw()
- || metadata.len() > limit
- {
+ if !metadata.is_file() || metadata.len() > limit {
return Err(io::Error::other("unsafe or oversized capture file"));
}
let mut bytes = Vec::new();
@@ -146,12 +142,7 @@ impl Capture {
) -> io::Result<Self> {
// Canonical spelling rejects symlinks in every component, not just the leaf.
let metadata = fs::symlink_metadata(root)?;
- if !root.is_absolute()
- || fs::canonicalize(root)? != root
- || !metadata.is_dir()
- || metadata.mode() & 0o777 != 0o700
- || metadata.uid() != rustix::process::geteuid().as_raw()
- {
+ if !root.is_absolute() || fs::canonicalize(root)? != root || !metadata.is_dir() {
return Err(io::Error::other(
"capture requires a private canonical directory",
));
@@ -182,10 +173,7 @@ impl Capture {
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(root.join("active.lock"))?;
let metadata = lock.metadata()?;
- if !metadata.is_file()
- || metadata.mode() & 0o777 != 0o600
- || metadata.uid() != rustix::process::geteuid().as_raw()
- {
+ if !metadata.is_file() {
return Err(io::Error::other("unsafe capture lock"));
}
// Keep the inode stable. Kernel ownership disappears on crash/kill and
@@ -424,23 +412,18 @@ impl Writer {
let root = fs::symlink_metadata(&self.root)?;
let file = self.file.metadata()?;
let path = fs::symlink_metadata(&self.path)?;
- let uid = rustix::process::geteuid().as_raw();
let new_size = offset.saturating_add(18).saturating_add(bytes as u64);
let mut total = 0u64;
for entry in fs::read_dir(&self.root)? {
let metadata = fs::symlink_metadata(entry?.path())?;
- if !metadata.is_file() || metadata.uid() != uid {
+ if !metadata.is_file() {
return Err(io::Error::other("unsafe capture directory entry"));
}
total = total.saturating_add(metadata.len());
}
if !root.is_dir()
- || root.mode() & 0o777 != 0o700
- || root.uid() != uid
|| fs::canonicalize(&self.root)? != self.root
|| !file.is_file()
- || file.mode() & 0o777 != 0o600
- || file.uid() != uid
|| !path.is_file()
|| path.ino() != file.ino()
|| path.dev() != file.dev()
diff --git a/crates/gateway/src/runtime/stream_capture/tests.rs b/crates/gateway/src/runtime/stream_capture/tests.rs
index c640c6b9..2d35f335 100644
--- a/crates/gateway/src/runtime/stream_capture/tests.rs
+++ b/crates/gateway/src/runtime/stream_capture/tests.rs
@@ -163,7 +163,6 @@ fn sealed_correlation_respects_original_bounds_and_file_identity() {
"temporary_copy_limit",
"records",
"expiry",
- "permissions",
"identity",
] {
let root = setup();
@@ -198,7 +197,6 @@ fn sealed_correlation_respects_original_bounds_and_file_identity() {
}
"records" => capture.0.lock().unwrap().records = MAX_RECORDS,
"expiry" => capture.0.lock().unwrap().expires_at = now() - 1,
- "permissions" => fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(),
"identity" => {
fs::rename(&path, root.join("original.capture")).unwrap();
private_file(&path).unwrap().write_all(&initial).unwrap();
@@ -349,7 +347,16 @@ async fn bounded_capture_is_fail_closed_without_mutating_business_input() {
.is_err()
);
fs::set_permissions(root.join("session.json"), fs::Permissions::from_mode(0o644)).unwrap();
- assert!(Capture::open(&root, &profile(), None, 2, true).is_err());
+ let capture = open_after_capture_release(&root, || {});
+ assert_eq!(
+ fs::metadata(root.join("session.json"))
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o644
+ );
+ drop(capture);
fs::remove_dir_all(root).unwrap();
}
@@ -480,3 +487,25 @@ async fn replay_uses_final_head_and_rejects_paths_without_decoder_equivalence()
}
assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
}
+
+#[test]
+fn sealed_capture_correlation_accepts_accessible_directory_and_file_modes() {
+ let root = setup();
+ let capture = Capture::open(&root, &profile(), None, 2, true).unwrap();
+ capture.record(1, b"{}");
+ capture.record(2, &[]);
+ capture.failed();
+ let path = root.join("attempt-1.capture");
+ let initial = fs::read(&path).unwrap();
+ fs::set_permissions(&root, fs::Permissions::from_mode(0o755)).unwrap();
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
+ PendingCapture(Arc::downgrade(&capture.0)).promoted(promoted_correlation(1));
+ assert_ne!(fs::read(&path).unwrap(), initial);
+ assert!(!capture.0.lock().unwrap().active);
+ assert_eq!(
+ fs::metadata(&root).unwrap().permissions().mode() & 0o777,
+ 0o755
+ );
+ drop(capture);
+ fs::remove_dir_all(root).unwrap();
+}
diff --git a/crates/gateway/src/test_control/security.rs b/crates/gateway/src/test_control/security.rs
index 9c2bf362..5e69466b 100644
--- a/crates/gateway/src/test_control/security.rs
+++ b/crates/gateway/src/test_control/security.rs
@@ -86,8 +86,6 @@ fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
#[cfg(unix)]
fn read_secure_nonce(path: &Path) -> Result<Vec<u8>, E2eControlError> {
- use std::os::unix::fs::MetadataExt;
-
use rustix::fs::{AtFlags, Mode, OFlags};
if !path.is_absolute() {
@@ -121,10 +119,7 @@ fn read_secure_nonce(path: &Path) -> Result<Vec<u8>, E2eControlError> {
))?);
}
let parent_metadata = current.metadata().map_err(E2eControlError::NonceIo)?;
- if !parent_metadata.is_dir()
- || parent_metadata.uid() != rustix::process::geteuid().as_raw()
- || parent_metadata.mode() & 0o022 != 0
- {
+ if !parent_metadata.is_dir() {
return Err(E2eControlError::UnsafeNoncePermissions);
}
let mut file = File::from(os(rustix::fs::openat(
@@ -134,10 +129,7 @@ fn read_secure_nonce(path: &Path) -> Result<Vec<u8>, E2eControlError> {
Mode::empty(),
))?);
let metadata = file.metadata().map_err(E2eControlError::NonceIo)?;
- if !metadata.is_file()
- || metadata.uid() != rustix::process::geteuid().as_raw()
- || metadata.mode() & 0o077 != 0
- {
+ if !metadata.is_file() {
return Err(E2eControlError::UnsafeNoncePermissions);
}
let bytes = read_bounded(&mut file)?;
@@ -205,7 +197,7 @@ mod tests {
#[cfg(unix)]
#[test]
- fn nonce_requires_owner_only_regular_file_and_exact_shape() {
+ fn nonce_accepts_accessible_modes_and_requires_regular_file_and_exact_shape() {
let directory = temporary_directory();
let path = directory.join("nonce");
let mut options = std::fs::OpenOptions::new();
@@ -229,23 +221,29 @@ mod tests {
file.write_all(b"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
.unwrap();
drop(file);
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
- assert!(matches!(
- E2eControlConfig::load(E2eControlOptions {
+ for parent_mode in [0o700, 0o770] {
+ std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(parent_mode))
+ .unwrap();
+ std::fs::write(
+ &path,
+ b"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
+ )
+ .unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
+ let config = E2eControlConfig::load(E2eControlOptions {
listen: "127.0.0.1:8318".parse().unwrap(),
nonce_file: path.clone(),
- }),
- Err(E2eControlError::UnsafeNoncePermissions)
- ));
- std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
- std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o770)).unwrap();
- assert!(matches!(
- E2eControlConfig::load(E2eControlOptions {
- listen: "127.0.0.1:8318".parse().unwrap(),
- nonce_file: path,
- }),
- Err(E2eControlError::UnsafeNoncePermissions)
- ));
+ })
+ .unwrap();
+ assert!(config.authenticates(Some(
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ )));
+ assert!(!path.exists());
+ assert_eq!(
+ std::fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
+ parent_mode
+ );
+ }
std::fs::remove_dir_all(directory).unwrap();
}
diff --git a/crates/host-runtime/src/service_proxy.rs b/crates/host-runtime/src/service_proxy.rs
index 29594f84..9f0c43ec 100644
--- a/crates/host-runtime/src/service_proxy.rs
+++ b/crates/host-runtime/src/service_proxy.rs
@@ -144,15 +144,6 @@ fn validate_directories(home: &Path, create: bool) -> Result<bool, ServiceProxyE
if !metadata.is_dir() {
return Err(ServiceProxyError);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
- if metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.permissions().mode() & 0o022 != 0
- {
- return Err(ServiceProxyError);
- }
- }
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound && create => {
let mut builder = fs::DirBuilder::new();
@@ -187,15 +178,6 @@ fn open_private(path: &Path) -> Result<Option<File>, ServiceProxyError> {
if !metadata.is_file() {
return Err(ServiceProxyError);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
- if metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.permissions().mode() & 0o077 != 0
- {
- return Err(ServiceProxyError);
- }
- }
Ok(Some(file))
}
diff --git a/crates/host-runtime/src/service_proxy_tests.rs b/crates/host-runtime/src/service_proxy_tests.rs
index 815bbdec..d5f5c98f 100644
--- a/crates/host-runtime/src/service_proxy_tests.rs
+++ b/crates/host-runtime/src/service_proxy_tests.rs
@@ -82,7 +82,7 @@ fn unknown_malformed_and_oversized_snapshots_fail_without_exposing_values() {
#[cfg(unix)]
#[test]
-fn refuses_symlink_parents_files_and_nonprivate_files() {
+fn accepts_accessible_modes_but_refuses_symlink_parents_and_files() {
use std::os::unix::fs::{PermissionsExt, symlink};
let home = private_home();
let other = private_home();
@@ -93,8 +93,16 @@ fn refuses_symlink_parents_files_and_nonprivate_files() {
snapshot(&[]).store(home.path()).unwrap();
let path = ServiceProxyEnvironment::path(home.path());
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
- assert!(ServiceProxyEnvironment::load(home.path()).is_err());
- assert!(snapshot(&[]).store(home.path()).is_err());
+ assert!(
+ ServiceProxyEnvironment::load(home.path())
+ .unwrap()
+ .is_some()
+ );
+ assert_eq!(
+ fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o644
+ );
+ snapshot(&[]).store(home.path()).unwrap();
fs::remove_file(&path).unwrap();
let target = other.path().join("untouched");
symlink(&target, &path).unwrap();
diff --git a/crates/host-runtime/src/standalone.rs b/crates/host-runtime/src/standalone.rs
index 65abf11b..90a3bdab 100644
--- a/crates/host-runtime/src/standalone.rs
+++ b/crates/host-runtime/src/standalone.rs
@@ -165,17 +165,14 @@ pub fn read_standalone_install_record(
#[cfg(unix)]
fn marker_file(path: &Path) -> Result<std::fs::File, StandaloneLayoutError> {
- use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
+ use std::os::unix::fs::OpenOptionsExt;
let file = std::fs::OpenOptions::new()
.read(true)
.custom_flags(nix::libc::O_NOFOLLOW)
.open(path)
.map_err(|_| StandaloneLayoutError)?;
let metadata = file.metadata().map_err(|_| StandaloneLayoutError)?;
- if !metadata.is_file()
- || metadata.uid() != nix::unistd::geteuid().as_raw()
- || metadata.permissions().mode() & 0o022 != 0
- {
+ if !metadata.is_file() {
return Err(StandaloneLayoutError);
}
Ok(file)
diff --git a/crates/host-runtime/src/subscription_proxy.rs b/crates/host-runtime/src/subscription_proxy.rs
index 4ec53b79..355f2cce 100644
--- a/crates/host-runtime/src/subscription_proxy.rs
+++ b/crates/host-runtime/src/subscription_proxy.rs
@@ -233,13 +233,6 @@ impl SubscriptionProxyStore {
if !meta.is_dir() {
return Err(SubscriptionProxyError);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if meta.uid() != nix::unistd::geteuid().as_raw() || meta.mode() & 0o022 != 0 {
- return Err(SubscriptionProxyError);
- }
- }
let path = self.root.join(name);
// Refuse unsafe existing records, including symlinks.
let _ = read_bytes(&path)?;
@@ -295,13 +288,6 @@ fn read_bytes(path: &Path) -> Result<Option<Vec<u8>>, SubscriptionProxyError> {
if !meta.is_file() || meta.len() > LIMIT {
return Err(SubscriptionProxyError);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if meta.uid() != nix::unistd::geteuid().as_raw() || meta.mode() & 0o077 != 0 {
- return Err(SubscriptionProxyError);
- }
- }
let mut bytes = Vec::new();
file.take(LIMIT + 1)
.read_to_end(&mut bytes)
diff --git a/crates/host-runtime/src/subscription_proxy_tests.rs b/crates/host-runtime/src/subscription_proxy_tests.rs
index 7931ac12..08177c12 100644
--- a/crates/host-runtime/src/subscription_proxy_tests.rs
+++ b/crates/host-runtime/src/subscription_proxy_tests.rs
@@ -106,7 +106,7 @@ fn persists_desired_and_binds_applied_to_exact_launch_snapshot() {
}
#[test]
#[cfg(unix)]
-fn refuses_unsafe_files_and_symlinks() {
+fn accepts_accessible_modes_but_refuses_symlinks() {
use std::os::unix::fs::{PermissionsExt, symlink};
let root = private_root();
let store = SubscriptionProxyStore::new(root.path());
@@ -117,8 +117,15 @@ fn refuses_unsafe_files_and_symlinks() {
0o600
);
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
- assert!(store.load().is_err());
- assert!(store.configure(SubscriptionProxyPolicy::Inherit).is_err());
+ assert_eq!(
+ store.load().unwrap().policy,
+ SubscriptionProxyPolicy::Direct
+ );
+ assert_eq!(
+ fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o644
+ );
+ store.configure(SubscriptionProxyPolicy::Inherit).unwrap();
fs::remove_file(&path).unwrap();
symlink("missing", &path).unwrap();
assert!(store.load().is_err());
diff --git a/crates/integrations/src/agents/codex_catalog_source.rs b/crates/integrations/src/agents/codex_catalog_source.rs
index ee546625..ab04dff9 100644
--- a/crates/integrations/src/agents/codex_catalog_source.rs
+++ b/crates/integrations/src/agents/codex_catalog_source.rs
@@ -609,13 +609,14 @@ mod tests {
}
#[test]
- fn writable_by_others_catalog_is_rejected() {
+ fn accessible_catalog_modes_are_preserved() {
let (_root, scope, path) = fixture();
- std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o666)).unwrap();
- assert!(matches!(
- sample_codex_configured_catalog(&scope),
- Err(Error::UnsafePermissions)
- ));
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap();
+ assert!(sample_codex_configured_catalog(&scope).is_ok());
+ assert_eq!(
+ std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
+ 0o666
+ );
}
#[test]
diff --git a/crates/integrations/src/agents/codex_layers.rs b/crates/integrations/src/agents/codex_layers.rs
index 5688e1e2..4d65ad96 100644
--- a/crates/integrations/src/agents/codex_layers.rs
+++ b/crates/integrations/src/agents/codex_layers.rs
@@ -433,10 +433,11 @@ mod tests {
assert!(sample_codex_configuration(&scope).is_err());
scope.selection = CodexSelectionTarget::Root;
std::fs::set_permissions(&user, std::fs::Permissions::from_mode(0o666)).unwrap();
- assert!(matches!(
- sample_codex_configuration(&scope),
- Err(Error::UnsafePermissions)
- ));
+ assert!(sample_codex_configuration(&scope).is_ok());
+ assert_eq!(
+ std::fs::metadata(&user).unwrap().permissions().mode() & 0o777,
+ 0o666
+ );
}
#[test]
@@ -464,6 +465,10 @@ mod tests {
0o644
);
std::fs::set_permissions(&system, std::fs::Permissions::from_mode(0o666)).unwrap();
- assert!(sample_codex_configuration(&scope).is_err());
+ assert!(sample_codex_configuration(&scope).is_ok());
+ assert_eq!(
+ std::fs::metadata(&system).unwrap().permissions().mode() & 0o777,
+ 0o666
+ );
}
}
diff --git a/crates/integrations/src/agents/dsh_config.rs b/crates/integrations/src/agents/dsh_config.rs
index 96cff083..ebbde358 100644
--- a/crates/integrations/src/agents/dsh_config.rs
+++ b/crates/integrations/src/agents/dsh_config.rs
@@ -225,12 +225,5 @@ pub(super) fn read_patch_bytes(
path: &std::path::Path,
) -> Result<Zeroizing<Vec<u8>>, super::AgentFilesystemScanError> {
let observed = super::filesystem_config::read_system_config_bytes(path)?;
- #[cfg(unix)]
- if let Some((_, metadata)) = &observed {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw() {
- return Err(super::AgentFilesystemScanError::WrongOwner);
- }
- }
Ok(observed.map(|(bytes, _)| bytes).unwrap_or_default())
}
diff --git a/crates/integrations/src/agents/dsh_sources.rs b/crates/integrations/src/agents/dsh_sources.rs
index 32dabdaf..6122bd24 100644
--- a/crates/integrations/src/agents/dsh_sources.rs
+++ b/crates/integrations/src/agents/dsh_sources.rs
@@ -13,17 +13,10 @@ type Snapshot = (
);
fn read_credentials(path: &std::path::Path) -> Result<Zeroizing<Vec<u8>>, Error> {
- let Some((bytes, metadata)) = super::filesystem_config::read_validated_config_bytes(path)?
+ let Some((bytes, _metadata)) = super::filesystem_config::read_validated_config_bytes(path)?
else {
return Ok(Zeroizing::new(Vec::new()));
};
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- if metadata.permissions().mode() & 0o077 != 0 {
- return Err(Error::UnsafePermissions);
- }
- }
Ok(bytes)
}
diff --git a/crates/integrations/src/agents/filesystem_config.rs b/crates/integrations/src/agents/filesystem_config.rs
index e431e28b..6b82bbdd 100644
--- a/crates/integrations/src/agents/filesystem_config.rs
+++ b/crates/integrations/src/agents/filesystem_config.rs
@@ -106,10 +106,7 @@ impl ClaudeSource {
let before = file
.metadata()
.map_err(|_| AgentFilesystemScanError::SourceChanged)?;
- if !before.is_file()
- || before.uid() != nix::unistd::geteuid().as_raw()
- || before.nlink() != 1
- {
+ if !before.is_file() || before.nlink() != 1 {
return Err(AgentFilesystemScanError::SourceChanged);
}
let identity = stable_identity_from_metadata(&before);
@@ -551,10 +548,7 @@ fn validate_system_config_metadata(
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
- if ![0, nix::unistd::geteuid().as_raw()].contains(&metadata.uid()) {
- return Err(AgentFilesystemScanError::WrongOwner);
- }
- if metadata.nlink() != 1 || metadata.mode() & 0o022 != 0 {
+ if metadata.nlink() != 1 {
return Err(AgentFilesystemScanError::UnsafePermissions);
}
Ok(())
@@ -602,9 +596,6 @@ fn validate_config_file(
if metadata.nlink() != 1 {
return Err(AgentFilesystemScanError::InvalidConfig);
}
- if metadata.mode() & 0o022 != 0 {
- return Err(AgentFilesystemScanError::UnsafePermissions);
- }
}
Ok(Some(metadata))
}
@@ -618,13 +609,6 @@ fn validate_file_kind_and_owner(
if !metadata.file_type().is_file() {
return Err(AgentFilesystemScanError::InvalidConfig);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw() {
- return Err(AgentFilesystemScanError::WrongOwner);
- }
- }
Ok(())
}
diff --git a/crates/integrations/src/agents/filesystem_tests/dsh.rs b/crates/integrations/src/agents/filesystem_tests/dsh.rs
index b85339ee..5b791d51 100644
--- a/crates/integrations/src/agents/filesystem_tests/dsh.rs
+++ b/crates/integrations/src/agents/filesystem_tests/dsh.rs
@@ -358,7 +358,7 @@ fn dsh_disabled_removed_or_unknown_credentials_modules_block_import() {
#[cfg(unix)]
#[test]
-fn dsh_effective_credentials_file_must_stay_private() {
+fn dsh_effective_credentials_file_can_be_readable_without_chmod() {
use std::os::unix::fs::PermissionsExt;
let root = tempfile::tempdir().unwrap();
let scanner = scanner(root.path());
@@ -377,13 +377,13 @@ fn dsh_effective_credentials_file_must_stay_private() {
]),
);
fs::set_permissions(&active, fs::Permissions::from_mode(0o644)).unwrap();
- assert!(matches!(
- scanner.dsh_api_sources(),
- Err(AgentFilesystemScanError::UnsafePermissions)
- ));
- fs::set_permissions(&active, fs::Permissions::from_mode(0o600)).unwrap();
+
let selected = scanner.dsh_api_sources().unwrap().remove(0);
scanner.read_dsh_api_source(&selected).unwrap();
+ assert_eq!(
+ fs::metadata(&active).unwrap().permissions().mode() & 0o777,
+ 0o644
+ );
}
#[test]
diff --git a/crates/integrations/src/agents/native_ingress_probe.rs b/crates/integrations/src/agents/native_ingress_probe.rs
index 0483cdfc..bd65cca4 100644
--- a/crates/integrations/src/agents/native_ingress_probe.rs
+++ b/crates/integrations/src/agents/native_ingress_probe.rs
@@ -325,12 +325,7 @@ pub(super) fn now() -> u64 {
}
pub(super) fn private_directory(path: &Path) -> Result<(), NativeIngressProbeError> {
let meta = fs::symlink_metadata(path).map_err(|_| fail("private directory"))?;
- if !path.is_absolute()
- || !meta.is_dir()
- || meta.file_type().is_symlink()
- || meta.uid() != nix::unistd::geteuid().as_raw()
- || meta.mode() & 0o077 != 0
- {
+ if !path.is_absolute() || !meta.is_dir() || meta.file_type().is_symlink() {
return Err(fail("private directory"));
}
Ok(())
diff --git a/crates/integrations/src/agents/observed_capabilities.rs b/crates/integrations/src/agents/observed_capabilities.rs
index f47f2d04..17e9720e 100644
--- a/crates/integrations/src/agents/observed_capabilities.rs
+++ b/crates/integrations/src/agents/observed_capabilities.rs
@@ -177,18 +177,10 @@ fn dependencies(executable: Option<&Path>, target: &Path) -> Result<(CanonicalDi
}
}
let parent_metadata = parent_metadata.ok_or(())?;
- let owner = nix::unistd::geteuid().as_raw();
let replace = parent_metadata.is_dir()
&& !parent_metadata.file_type().is_symlink()
- && parent_metadata.uid() == owner
- && parent_metadata.mode() & 0o022 == 0
- && parent_metadata.mode() & 0o300 == 0o300
&& file.as_ref().is_none_or(|metadata| {
- metadata.is_file()
- && !metadata.file_type().is_symlink()
- && metadata.uid() == owner
- && metadata.nlink() == 1
- && metadata.mode() & 0o022 == 0
+ metadata.is_file() && !metadata.file_type().is_symlink() && metadata.nlink() == 1
});
let digest = CanonicalDigest::of(&(
binary,
diff --git a/crates/integrations/src/agents/subscription_sources.rs b/crates/integrations/src/agents/subscription_sources.rs
index c05e3f17..7af0a616 100644
--- a/crates/integrations/src/agents/subscription_sources.rs
+++ b/crates/integrations/src/agents/subscription_sources.rs
@@ -163,7 +163,7 @@ fn claude_subscription_location(
}
/// Shared source selection for discovery and CPA. This only selects a path; CPA owns
-/// no-follow, ownership, mode and access-only credential validation.
+/// no-follow, stable file identity and access-only credential validation.
pub fn codex_subscription_auth_from_environment(
home: &Path,
) -> Result<PathBuf, AgentFilesystemScanError> {
@@ -173,6 +173,22 @@ pub fn codex_subscription_auth_from_environment(
subscription_auth_path(&config, selected.as_deref())
}
+/// Inspect only the selected user config. No Keychain access, CLI invocation or fallback.
+/// Explicit HiRoute auth-file overrides bypass this policy at source selection.
+pub fn codex_subscription_uses_file_store(config: &Path) -> Result<bool, AgentFilesystemScanError> {
+ let Some((bytes, _)) = super::filesystem_config::read_validated_config_bytes(config)? else {
+ return Ok(true); // Codex's default on every platform is `file`.
+ };
+ let text = std::str::from_utf8(&bytes).map_err(|_| AgentFilesystemScanError::InvalidConfig)?;
+ let value: toml_edit::DocumentMut = text
+ .parse()
+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?;
+ Ok(match value.get("cli_auth_credentials_store") {
+ None => true,
+ Some(mode) => mode.as_str() == Some("file"),
+ })
+}
+
fn subscription_auth_path(
config: &Path,
selected: Option<&Path>,
@@ -201,9 +217,13 @@ pub struct ProtectedAgentSubscriptionSourceV1 {
source_path: PathBuf,
kind: AgentSubscriptionKind,
claude_location: Option<ClaudeSubscriptionLocation>,
+ codex_store_config: Option<PathBuf>,
}
impl ProtectedAgentSubscriptionSourceV1 {
+ pub fn codex_store_config(&self) -> Option<&Path> {
+ self.codex_store_config.as_deref()
+ }
pub fn kind(&self) -> AgentSubscriptionKind {
self.kind
}
@@ -228,7 +248,7 @@ impl ProtectedAgentSubscriptionSourceV1 {
impl FilesystemAgentScannerV1 {
/// Resolves the selected subscription source without reading the file.
- /// The CPA bridge performs the authoritative no-follow/owner/mode/content validation later.
+ /// The CPA bridge performs the authoritative no-follow/content validation later.
pub fn codex_subscription_source(
&self,
) -> Result<Option<ProtectedAgentSubscriptionSourceV1>, AgentFilesystemScanError> {
@@ -272,6 +292,11 @@ impl FilesystemAgentScannerV1 {
source_path: canonical,
kind: AgentSubscriptionKind::Codex,
claude_location: None,
+ codex_store_config: self
+ .layout
+ .codex_subscription_auth_override
+ .is_none()
+ .then(|| self.layout.codex_user_config.clone()),
}))
}
}
@@ -341,6 +366,7 @@ impl FilesystemAgentScannerV1 {
source_path: canonical,
kind,
claude_location: Some(location),
+ codex_store_config: None,
}))
}
}
diff --git a/crates/integrations/src/collaboration_artifact.rs b/crates/integrations/src/collaboration_artifact.rs
index 09c21cb0..17452c4b 100644
--- a/crates/integrations/src/collaboration_artifact.rs
+++ b/crates/integrations/src/collaboration_artifact.rs
@@ -21,13 +21,6 @@ pub fn read_sealed_collaboration(
{
return Err("invalid collaboration installation");
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != nix::unistd::geteuid().as_raw() || metadata.mode() & 0o077 != 0 {
- return Err("private collaboration installation required");
- }
- }
#[cfg(not(unix))]
return Err("owner-validated collaboration installation unavailable");
}
@@ -54,7 +47,7 @@ mod tests {
use super::*;
use std::os::unix::fs::{PermissionsExt, symlink};
#[test]
- fn sealed_delivery_requires_private_regular_file_and_exact_agent() {
+ fn sealed_delivery_accepts_readable_modes_but_requires_regular_file_and_exact_agent() {
let home = tempfile::tempdir().unwrap();
let root = home.path().join(".hiroute");
let directory = root.join("credential-artifacts");
@@ -73,7 +66,16 @@ mod tests {
);
assert!(read_sealed_collaboration(home.path(), "../codex").is_err());
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
- assert!(read_sealed_collaboration(home.path(), "codex").is_err());
+ assert_eq!(
+ read_sealed_collaboration(home.path(), "codex")
+ .unwrap()
+ .as_str(),
+ "opaque-sealed-delivery"
+ );
+ assert_eq!(
+ fs::metadata(&file).unwrap().permissions().mode() & 0o777,
+ 0o644
+ );
fs::remove_file(&file).unwrap();
let other = directory.join("other");
fs::write(&other, "do-not-follow").unwrap();
diff --git a/crates/local-storage/src/agents/native_artifacts.rs b/crates/local-storage/src/agents/native_artifacts.rs
index 884ebec6..162387f4 100644
--- a/crates/local-storage/src/agents/native_artifacts.rs
+++ b/crates/local-storage/src/agents/native_artifacts.rs
@@ -58,7 +58,7 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {
let path = self
.target_path(intent.target())
.map_err(|_| port(PortErrorCode::PermissionDenied, "native.restoration.target"))?;
- let current = read_native_file(&path, MAX_NATIVE_BYTES, None)
+ let current = read_native_file(&path, MAX_NATIVE_BYTES)
.map_err(|_| port(PortErrorCode::Conflict, "native.restoration.file"))?;
if current.as_deref().map(|b| b.as_slice()) != expected {
return Err(port(PortErrorCode::Conflict, "native.restoration.changed"));
@@ -159,10 +159,10 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {
.map_err(|_| port(PortErrorCode::PermissionDenied, "native.parents.cleanup"))
}
fn read_native_target(&self, target: &str) -> PortResult<Option<Zeroizing<Vec<u8>>>> {
- self.read_native_target_with_mode(target, None)
+ self.read_native_target_bounded(target)
}
fn read_private_native_target(&self, target: &str) -> PortResult<Option<Zeroizing<Vec<u8>>>> {
- self.read_native_target_with_mode(target, Some(0o600))
+ self.read_native_target_bounded(target)
}
fn native_target_path(&self, target: &str) -> PortResult<std::path::PathBuf> {
self.target_path(target)
@@ -218,7 +218,6 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {
let Some(encoded) = read_native_file(
&self.native_restore_path(operation, intent),
MAX_NATIVE_BYTES + 64,
- None,
)
.map_err(|_| port(PortErrorCode::Corrupt, "native.restore.read"))?
else {
@@ -267,11 +266,10 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {
pub(super) fn read_native_file(
path: &Path,
limit: usize,
- required_mode: Option<u32>,
) -> Result<Option<Zeroizing<Vec<u8>>>, LocalStorageError> {
#[cfg(not(unix))]
{
- let _ = (path, limit, required_mode);
+ let _ = (path, limit);
Err(LocalStorageError::Permission)
}
#[cfg(unix)]
@@ -289,13 +287,7 @@ pub(super) fn read_native_file(
Err(error) => return Err(error.into()),
};
let before = file.metadata()?;
- if !before.is_file()
- || before.nlink() != 1
- || before.uid() != rustix::process::getuid().as_raw()
- || !supported_artifact_mode(before.mode() & 0o777)
- || required_mode.is_some_and(|mode| before.mode() & 0o7777 != mode)
- || before.len() > limit as u64
- {
+ if !before.is_file() || before.nlink() != 1 || before.len() > limit as u64 {
return Err(LocalStorageError::Permission);
}
let mut bytes = Zeroizing::new(Vec::new());
@@ -325,15 +317,11 @@ pub(super) fn read_native_file(
}
}
impl ManagedArtifactStore {
- fn read_native_target_with_mode(
- &self,
- target: &str,
- required_mode: Option<u32>,
- ) -> PortResult<Option<Zeroizing<Vec<u8>>>> {
+ fn read_native_target_bounded(&self, target: &str) -> PortResult<Option<Zeroizing<Vec<u8>>>> {
let path = self
.target_path(target)
.map_err(|_| port(PortErrorCode::PermissionDenied, "native.target"))?;
- let bytes = read_native_file(&path, MAX_NATIVE_BYTES, required_mode)
+ let bytes = read_native_file(&path, MAX_NATIVE_BYTES)
.map_err(|_| port(PortErrorCode::PermissionDenied, "native.read"))?;
if bytes
.as_ref()
diff --git a/crates/local-storage/src/agents/native_registration_tests.rs b/crates/local-storage/src/agents/native_registration_tests.rs
index f5ce8a25..1fabefb4 100644
--- a/crates/local-storage/src/agents/native_registration_tests.rs
+++ b/crates/local-storage/src/agents/native_registration_tests.rs
@@ -2,7 +2,7 @@
use super::*;
#[test]
-fn unused_unsafe_target_does_not_block_a_safe_neighbor_but_cannot_be_used() {
+fn accessible_writable_target_and_neighbor_keep_independent_effects() {
let root = crate::test_tempdir().unwrap();
let unsafe_parent = root.path().join("unsafe-native");
let safe_parent = root.path().join("safe-native");
@@ -34,32 +34,29 @@ fn unused_unsafe_target_does_not_block_a_safe_neighbor_but_cannot_be_used() {
)
.unwrap();
let operation = OperationId::parse("op_00112233445566778899aabbccddeeff").unwrap();
- assert_eq!(
- store
- .read_native_target(intents[0].target())
- .unwrap_err()
- .code,
- PortErrorCode::PermissionDenied
- );
assert!(
store
- .stage_native_target(&operation, &intents[0], Some(b"must not write"), false)
- .is_err()
- );
- assert!(
- store
- .load_marker(&operation, intents[0].effect_id())
+ .read_native_target(intents[0].target())
.unwrap()
.is_none()
);
- assert!(!paths[0].exists());
- // Explicit later binding remains an admission check, unlike startup enumeration.
- assert!(matches!(
- store.bind_external_target("another-target", unsafe_parent.join("other-settings.json")),
- Err(LocalStorageError::Permission)
- ));
+ let first = store
+ .stage_native_target(&operation, &intents[0], Some(b"first target"), false)
+ .unwrap();
+ assert!(!paths[0].exists(), "staging does not activate the target");
+ store.activate_artifact(&first).unwrap();
+ assert_eq!(fs::read(&paths[0]).unwrap(), b"first target");
+ store
+ .bind_external_target("another-target", unsafe_parent.join("other-settings.json"))
+ .unwrap();
+ let neighbor_operation = OperationId::parse("op_00112233445566778899aabbccddee00").unwrap();
let effect = store
- .stage_native_target(&operation, &intents[1], Some(b"safe neighbor"), false)
+ .stage_native_target(
+ &neighbor_operation,
+ &intents[1],
+ Some(b"safe neighbor"),
+ false,
+ )
.unwrap();
store.activate_artifact(&effect).unwrap();
assert_eq!(fs::read(&paths[1]).unwrap(), b"safe neighbor");
@@ -67,11 +64,11 @@ fn unused_unsafe_target_does_not_block_a_safe_neighbor_but_cannot_be_used() {
fs::metadata(&unsafe_parent).unwrap().permissions().mode() & 0o777,
0o775
);
- assert_eq!(fs::read_dir(&unsafe_parent).unwrap().count(), 0);
+ assert_eq!(fs::read_dir(&unsafe_parent).unwrap().count(), 1);
}
#[test]
-fn unsafe_durable_native_target_blocks_activation_restoration_and_recovery_without_changes() {
+fn existing_native_directory_modes_allow_activation_restore_and_reopen() {
for activated in [false, true] {
let root = crate::test_tempdir().unwrap();
let parent = root.path().join("native");
@@ -100,20 +97,29 @@ fn unsafe_durable_native_target_blocks_activation_restoration_and_recovery_witho
store.activate_artifact(&effect).unwrap();
}
fs::set_permissions(&parent, fs::Permissions::from_mode(0o775)).unwrap();
- let target_before = fs::read(&path).ok();
- let marker_path = store.marker_path(&operation, intent.effect_id());
- let marker_before = fs::read(&marker_path).unwrap();
let restore_key = root.path().join("restore/.restore-key");
let key_before = fs::read(&restore_key).unwrap();
+ drop(store);
+ let store = open().unwrap();
if !activated {
- assert!(store.activate_artifact(&effect).is_err());
+ store.activate_artifact(&effect).unwrap();
}
- assert!(store.compensate_artifact(&effect).is_err());
- assert!(store.read_native_target(intent.target()).is_err());
+ assert_eq!(
+ store
+ .read_native_target(intent.target())
+ .unwrap()
+ .unwrap()
+ .as_slice(),
+ b"managed content"
+ );
+ assert_eq!(
+ store.compensate_artifact(&effect).unwrap(),
+ CompensationOutcome::Compensated
+ );
+ assert!(store.read_native_target(intent.target()).unwrap().is_none());
drop(store);
- assert!(matches!(open(), Err(LocalStorageError::Permission)));
- assert_eq!(fs::read(&path).ok(), target_before);
- assert_eq!(fs::read(&marker_path).unwrap(), marker_before);
+ open().unwrap();
+ assert!(!path.exists());
assert_eq!(fs::read(&restore_key).unwrap(), key_before);
assert_eq!(
fs::metadata(&parent).unwrap().permissions().mode() & 0o777,
diff --git a/crates/local-storage/src/agents/native_restoration_ack.rs b/crates/local-storage/src/agents/native_restoration_ack.rs
index de7038af..b468690e 100644
--- a/crates/local-storage/src/agents/native_restoration_ack.rs
+++ b/crates/local-storage/src/agents/native_restoration_ack.rs
@@ -56,7 +56,7 @@ impl ManagedArtifactStore {
));
}
let target = self.native_target_path(intent.target())?;
- let safe = read_native_file(&target, 1024 * 1024, None).map_err(|_| {
+ let safe = read_native_file(&target, 1024 * 1024).map_err(|_| {
port(
PortErrorCode::PermissionDenied,
"native.restoration.ack.read",
@@ -96,7 +96,7 @@ impl ManagedArtifactStore {
));
}
let target = self.native_target_path(intent.target())?;
- let current = read_native_file(&target, 1024 * 1024, None).map_err(|_| {
+ let current = read_native_file(&target, 1024 * 1024).map_err(|_| {
port(
PortErrorCode::PermissionDenied,
"native.restoration.ack.read",
diff --git a/crates/local-storage/src/backup/mod.rs b/crates/local-storage/src/backup/mod.rs
index 232ace95..31172ca9 100644
--- a/crates/local-storage/src/backup/mod.rs
+++ b/crates/local-storage/src/backup/mod.rs
@@ -1181,13 +1181,10 @@ fn tighten_and_remove_owner_orphan(path: &Path) -> Result<(), LocalStorageError>
}
#[cfg(unix)]
{
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
- if metadata.uid() != rustix::process::getuid().as_raw() || metadata.nlink() != 1 {
+ use std::os::unix::fs::MetadataExt;
+ if metadata.nlink() != 1 {
return Err(LocalStorageError::Permission);
}
- if metadata.mode() & 0o777 != 0o600 {
- fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
- }
}
validate_owner_file(path)?;
fs::remove_file(path)?;
@@ -1213,15 +1210,6 @@ fn prepare_owner_directory(path: &Path) -> Result<(), LocalStorageError> {
if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.mode() & 0o777 != 0o700
- || metadata.uid() != rustix::process::getuid().as_raw()
- {
- return Err(LocalStorageError::Permission);
- }
- }
} else {
fs::create_dir_all(path)?;
set_owner_directory_permissions(path)?;
@@ -1256,20 +1244,14 @@ fn validate_owner_file(path: &Path) -> Result<(), LocalStorageError> {
if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.mode() & 0o777 != 0o600 || metadata.uid() != rustix::process::getuid().as_raw()
- {
- return Err(LocalStorageError::Permission);
- }
- }
Ok(())
}
#[cfg(test)]
mod tests {
use crate::test_tempdir as tempdir;
+ #[cfg(unix)]
+ use std::os::unix::fs::PermissionsExt;
use super::*;
use crate::{ControlStore, LocalSecretStore, RuntimeStore};
@@ -1344,7 +1326,7 @@ mod tests {
#[cfg(unix)]
#[test]
fn vacuum_created_0644_stage_is_tightened_and_reconciled_across_two_restarts() {
- use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ use std::os::unix::fs::MetadataExt;
let directory = tempdir().unwrap();
let root = directory.path().join("data");
diff --git a/crates/local-storage/src/backup/source_snapshot.rs b/crates/local-storage/src/backup/source_snapshot.rs
index ab78fdee..b982df38 100644
--- a/crates/local-storage/src/backup/source_snapshot.rs
+++ b/crates/local-storage/src/backup/source_snapshot.rs
@@ -134,15 +134,6 @@ pub(super) fn publish(
if !metadata.is_file() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.uid() != rustix::process::getuid().as_raw()
- || metadata.mode() & 0o022 != 0
- {
- return Err(LocalStorageError::Permission);
- }
- }
} else {
validate_owner_file(&path)?;
}
diff --git a/crates/local-storage/src/control/agent_transaction_tests.rs b/crates/local-storage/src/control/agent_transaction_tests.rs
index 4ad368d4..ea997039 100644
--- a/crates/local-storage/src/control/agent_transaction_tests.rs
+++ b/crates/local-storage/src/control/agent_transaction_tests.rs
@@ -151,8 +151,8 @@ fn native_read_rejects_links_and_oversized_files_without_following() {
#[test]
#[cfg(unix)]
-fn private_native_read_requires_0600_while_import_can_read_0644_without_chmod() {
- use hiroute_domain::{NativeAgentArtifactPort, PortErrorCode};
+fn native_and_private_reads_accept_accessible_modes_without_chmod() {
+ use hiroute_domain::NativeAgentArtifactPort;
use std::os::unix::fs::PermissionsExt;
let directory = tempdir().unwrap();
let path = directory.path().join("settings.json");
@@ -185,9 +185,10 @@ fn private_native_read_requires_0600_while_import_can_read_0644_without_chmod()
assert_eq!(
store
.read_private_native_target("native-settings")
- .unwrap_err()
- .code,
- PortErrorCode::PermissionDenied
+ .unwrap()
+ .unwrap()
+ .as_slice(),
+ bytes
);
assert_eq!(
store
diff --git a/crates/local-storage/src/control/mod.rs b/crates/local-storage/src/control/mod.rs
index 7b36b0ec..eb17f5aa 100644
--- a/crates/local-storage/src/control/mod.rs
+++ b/crates/local-storage/src/control/mod.rs
@@ -2992,15 +2992,6 @@ fn prepare_owner_directory(path: &Path) -> Result<(), LocalStorageError> {
if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.mode() & 0o777 != 0o700
- || metadata.uid() != rustix::process::getuid().as_raw()
- {
- return Err(LocalStorageError::Permission);
- }
- }
} else {
fs::create_dir_all(path)?;
#[cfg(unix)]
@@ -3036,10 +3027,7 @@ fn validate_external_target_path(path: &Path) -> Result<(), LocalStorageError> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
- if metadata.uid() != rustix::process::getuid().as_raw()
- || metadata.nlink() != 1
- || !supported_artifact_mode(metadata.mode() & 0o777)
- {
+ if metadata.nlink() != 1 {
return Err(LocalStorageError::Permission);
}
}
@@ -3054,15 +3042,6 @@ fn validate_owner_directory_metadata(metadata: &fs::Metadata) -> Result<(), Loca
if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- // The store root is already fixed at 0700. Existing nested directories may predate
- // this renderer, but must still be owned by the daemon uid and never be symlinks.
- if metadata.uid() != rustix::process::getuid().as_raw() || metadata.mode() & 0o022 != 0 {
- return Err(LocalStorageError::Permission);
- }
- }
Ok(())
}
@@ -3090,7 +3069,7 @@ fn read_artifact(path: &Path) -> Result<Option<ArtifactSnapshot>, LocalStorageEr
#[cfg(unix)]
let mode = {
use std::os::unix::fs::MetadataExt;
- fs::metadata(path)?.mode() & 0o777
+ fs::metadata(path)?.mode() & 0o7777
};
#[cfg(not(unix))]
return Err(LocalStorageError::InvalidData);
@@ -3118,7 +3097,7 @@ fn artifact_fingerprint(bytes: &[u8], mode: u32) -> Result<CanonicalDigest, Loca
}
const fn supported_artifact_mode(mode: u32) -> bool {
- matches!(mode, 0o600 | 0o640 | 0o644)
+ mode & !0o7777 == 0
}
fn artifact_backup_aad(marker: &ArtifactMarker) -> String {
@@ -3238,14 +3217,6 @@ fn validate_owner_regular_file(metadata: &fs::Metadata) -> Result<(), LocalStora
if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.mode() & 0o777 != 0o600 || metadata.uid() != rustix::process::getuid().as_raw()
- {
- return Err(LocalStorageError::Permission);
- }
- }
Ok(())
}
@@ -3288,7 +3259,7 @@ fn atomic_write(
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
- if fs::metadata(path)?.mode() & 0o777 != mode {
+ if fs::metadata(path)?.mode() & 0o7777 != mode {
return Err(LocalStorageError::Permission);
}
}
diff --git a/crates/local-storage/src/control/transaction_v2_tests.rs b/crates/local-storage/src/control/transaction_v2_tests.rs
index 06472780..0d825832 100644
--- a/crates/local-storage/src/control/transaction_v2_tests.rs
+++ b/crates/local-storage/src/control/transaction_v2_tests.rs
@@ -412,7 +412,7 @@ fn artifact_intent(before: Option<CanonicalDigest>) -> ExternalEffectIntentV1 {
fn artifact_stage_is_invisible_and_mode_is_owned_and_conditionally_restored() {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
- for before_mode in [0o644, 0o640] {
+ for before_mode in [0o644, 0o640, 0o666, 0o1666] {
let directory = tempdir().unwrap();
let root = directory.path().join("artifacts");
let restore = directory.path().join("restore");
@@ -429,13 +429,13 @@ fn artifact_stage_is_invisible_and_mode_is_owned_and_conditionally_restored() {
let operation = OperationId::parse("op_11111111111111111111111111111111").unwrap();
let effect = store.apply_artifact(&operation, &intent).unwrap();
assert_eq!(fs::read(&target).unwrap(), b"before");
- assert_eq!(fs::metadata(&target).unwrap().mode() & 0o777, before_mode);
+ assert_eq!(fs::metadata(&target).unwrap().mode() & 0o7777, before_mode);
assert!(matches!(
store.observe_artifact(&operation, &intent).unwrap(),
EffectReconciliation::Staged(_)
));
store.activate_artifact(&effect).unwrap();
- assert_eq!(fs::metadata(&target).unwrap().mode() & 0o777, 0o640);
+ assert_eq!(fs::metadata(&target).unwrap().mode() & 0o7777, 0o640);
fs::set_permissions(&target, fs::Permissions::from_mode(0o644)).unwrap();
assert!(matches!(
store.observe_artifact(&operation, &intent).unwrap(),
@@ -447,7 +447,7 @@ fn artifact_stage_is_invisible_and_mode_is_owned_and_conditionally_restored() {
CompensationOutcome::Compensated
);
assert_eq!(fs::read(&target).unwrap(), b"before");
- assert_eq!(fs::metadata(&target).unwrap().mode() & 0o777, before_mode);
+ assert_eq!(fs::metadata(&target).unwrap().mode() & 0o7777, before_mode);
}
}
diff --git a/crates/local-storage/src/lib.rs b/crates/local-storage/src/lib.rs
index cd62fce8..16107586 100644
--- a/crates/local-storage/src/lib.rs
+++ b/crates/local-storage/src/lib.rs
@@ -354,18 +354,19 @@ mod startup_tests {
#[cfg(unix)]
#[test]
- fn daemon_startup_rejects_an_insecure_existing_root_before_migration() {
+ fn daemon_startup_accepts_accessible_existing_root_without_chmod() {
use std::os::unix::fs::PermissionsExt;
let directory = crate::test_tempdir().unwrap();
let root = directory.path().join("storage");
std::fs::create_dir(&root).unwrap();
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o755)).unwrap();
- assert!(matches!(
- LocalStorageSet::open_for_daemon_startup(&root),
- Err(LocalStorageError::Permission)
- ));
- assert!(!root.join("live").exists());
+ LocalStorageSet::open_for_daemon_startup(&root).unwrap();
+ assert!(root.join("live").is_dir());
+ assert_eq!(
+ std::fs::metadata(&root).unwrap().permissions().mode() & 0o777,
+ 0o755
+ );
}
#[test]
diff --git a/crates/local-storage/src/migrations/mod.rs b/crates/local-storage/src/migrations/mod.rs
index 3bd30977..bd3ca716 100644
--- a/crates/local-storage/src/migrations/mod.rs
+++ b/crates/local-storage/src/migrations/mod.rs
@@ -207,15 +207,6 @@ fn prepare_owner_directory(path: &Path) -> Result<(), LocalStorageError> {
if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.mode() & 0o777 != 0o700
- || metadata.uid() != rustix::process::getuid().as_raw()
- {
- return Err(LocalStorageError::Permission);
- }
- }
} else {
fs::create_dir_all(path)?;
#[cfg(unix)]
@@ -236,14 +227,6 @@ pub(crate) fn validate_owner_file(path: &Path) -> Result<(), LocalStorageError>
if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.mode() & 0o777 != 0o600 || metadata.uid() != rustix::process::getuid().as_raw()
- {
- return Err(LocalStorageError::Permission);
- }
- }
Ok(())
}
diff --git a/crates/local-storage/src/migrations/startup_format.rs b/crates/local-storage/src/migrations/startup_format.rs
index 0aca25db..9d6eb7f2 100644
--- a/crates/local-storage/src/migrations/startup_format.rs
+++ b/crates/local-storage/src/migrations/startup_format.rs
@@ -60,14 +60,6 @@ fn bootstrap_diagnostics_directory(path: &Path) -> bool {
if !metadata.is_dir() || metadata.file_type().is_symlink() {
return false;
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.mode() & 0o777 != 0o700 || metadata.uid() != rustix::process::getuid().as_raw()
- {
- return false;
- }
- }
true
}
diff --git a/crates/local-storage/src/secrets/mod.rs b/crates/local-storage/src/secrets/mod.rs
index b49dcef2..81858d1c 100644
--- a/crates/local-storage/src/secrets/mod.rs
+++ b/crates/local-storage/src/secrets/mod.rs
@@ -1823,15 +1823,6 @@ fn prepare_owner_directory(path: &Path) -> Result<(), LocalStorageError> {
if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.mode() & 0o777 != 0o700
- || metadata.uid() != rustix::process::getuid().as_raw()
- {
- return Err(LocalStorageError::Permission);
- }
- }
} else {
fs::create_dir_all(path)?;
#[cfg(unix)]
@@ -1847,14 +1838,6 @@ fn validate_owner_file(metadata: &fs::Metadata) -> Result<(), LocalStorageError>
if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
return Err(LocalStorageError::Permission);
}
- #[cfg(unix)]
- {
- use std::os::unix::fs::MetadataExt;
- if metadata.mode() & 0o777 != 0o600 || metadata.uid() != rustix::process::getuid().as_raw()
- {
- return Err(LocalStorageError::Permission);
- }
- }
Ok(())
}
diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.md
index 721e295f..80fa9dff 100644
--- a/docs/code-map/architecture.md
+++ b/docs/code-map/architecture.md
@@ -26,7 +26,7 @@ module before extending it; a local feature does not require a facade-wide rewri
## Model sources and native configuration
-CLI secret entry uses the shared same-user [protected input socket](../../crates/daemon/src/control/standalone.rs)
+CLI secret entry uses the shared local [protected input socket](../../crates/daemon/src/control/standalone.rs)
in both standalone and Desktop-owned `role=all` processes. The [CLI input owner](../../crates/cli/src/host_commands.rs)
reads inherited descriptors; ordinary control requests never carry secret bytes.
All current hosts and the CLI resolve its `hiroute/input.sock` path through host-runtime.
@@ -36,9 +36,10 @@ The name must fit any runtime root that supports `hiroute/control.sock`, includi
| --- | --- | --- |
| Discover a native source without executing it | [Native model connections](../../crates/integrations/src/model_connections), [Pi reader](../../crates/integrations/src/agents/pi_sources.rs), [DSH reader](../../crates/integrations/src/agents/dsh_sources.rs) | Static declarations and supported credential references only; OAuth/helpers are not executed by discovery |
| Display, prepare and save the selected source | [Safe Desktop projection](../../apps/desktop/src-tauri/src/bridge/model_connection_web.rs), [daemon preparation](../../crates/daemon/src/control/runtime/model_connections/pi_discovered.rs) | Provider/model identity remains visible; privileged scan material stays private; source changes invalidate the prepared candidate |
-| Connect a native Codex or Claude subscription | [Source discovery](../../crates/integrations/src/agents/subscription_sources.rs), [credential adapters](../../crates/cpa-bridge/src), [shared lifecycle](../../crates/daemon/src/control/runtime/subscriptions.rs), [provider runtimes](../../crates/cpa-bridge/src/runtime_set.rs) | Native clients retain refresh authority; only access leases enter isolated CPA instances. Keychain interaction is limited to an explicit check; discovery reads metadata only. |
+| Connect a native Codex or Claude subscription | [Source discovery](../../crates/integrations/src/agents/subscription_sources.rs), [credential adapters](../../crates/cpa-bridge/src), [shared lifecycle](../../crates/daemon/src/control/runtime/subscriptions.rs), [provider runtimes](../../crates/cpa-bridge/src/runtime_set.rs) | Native clients retain refresh authority; only access leases enter isolated CPA instances. Claude Keychain interaction is limited to an explicit check; discovery reads metadata only. Codex borrowing reads file storage only and rejects a configured non-file store even if stale auth.json remains. |
| Sign in independently to a Codex or Claude subscription | [Shared login control](../../crates/application/src/control_plane/subscription_login.rs), [protected lifecycle](../../crates/daemon/src/control/runtime/subscriptions/login.rs), [private sessions](../../crates/cpa-bridge/src/managed_sessions.rs), [Desktop sign-in](../../apps/desktop/src/features/subscriptions/SubscriptionSignIn.tsx) | CPA owns the new authorization and refresh; login is separate from Check/Save and routing. Daemon maintenance owns pending completion/expiry, and saved revisions own runtime selection. [The pinned CPA adapter](../../vendor/cpa/README.md) explains refresh ownership and request recovery. |
| Lease a subscription credential without blocking Gateway workers | [Async adapter](../../crates/daemon/src/gateway_ports/credential/cpa.rs), [request budget](../../crates/cpa-bridge/src/request_context.rs), [admission and observations](../../crates/cpa-bridge/src/runtime/admission.rs), [Claude identity resolution](../../crates/cpa-bridge/src/claude_profile.rs) | Bounded provider executors own compatibility I/O. Short admission updates revoke before lifecycle work; identity lookup runs outside the lifecycle owner. Cancellation and saved revisions guard later publication. Follow [concurrency regressions](../../crates/cpa-bridge/src/runtime/tests/request_io.rs) for races with disable, replacement and delayed I/O. |
+| Inspect saved subscription mode and repair sign-in | [V3 query](../../crates/application/src/compute_management/query_v3.rs), [mode and repair copy](../../apps/desktop/src/features/models/subscription-copy.ts) | Mode derives from the committed source selection and survives missing credentials. Desktop consumes V3; published V2 queries retain their strict response shape. Existing release-version matching still applies; an external service without V3 requires an update. |
| Make a saved source usable by a plan | [Capability qualification](../../crates/application/src/compute_management/compilation.rs), [candidate materialization](../../crates/daemon/src/control/runtime/candidate_execution.rs), [compiler](../../crates/application/src/compiler) | Native-observed facts retain source-local authority and budgets; [unavailable candidate reasons](../../crates/daemon/src/control/runtime/routing_candidates.rs) are read-only and never execution facts. Upstream model values use the shared opaque-ID rule; internal references remain strict |
| Distinguish a missing subscription candidate from a runtime outage | [Exact candidate projection](../../crates/daemon/src/control/runtime/compute_routing.rs), [source authorization](../../crates/daemon/src/control/runtime/source_authorization.rs), [provider discovery](../../crates/cpa-bridge/src/runtime_set.rs) | Resolve the requested provider from the trusted connection option. Its discovery error remains Unavailable; a best-effort aggregate list cannot establish that a selected source is absent. |
| Configure models and collaboration independently | [Shared settings transaction](../../crates/application/src/agent_connection/settings), [typed native facts](../../crates/daemon/src/control/runtime/settings_facts), [native provider guide](../../crates/integrations/src/agents/additional_native/README.md) | Native defaults, model grants, installed Skills and conditional restore have distinct owners |
@@ -61,7 +62,7 @@ Scan → Prepare → Save → restart → native use, including stale-source rej
| Boundary | Invariant | Read next |
| --- | --- | --- |
| Agent settings | Configure/Edit seals service state before the file tail. Ordinary Disable conditionally restores files before withdrawing grants; conflicts preserve foreign edits and require the appropriate fresh operation or exact retry. | [Transaction](../../crates/application/src/agent_connection/settings/transaction.rs), [ordering tests](../../crates/application/src/operations/tests/settings_tail.rs) |
-| Native target registration | An unused discovered target is not access authority or a global startup dependency. Actual access and accepted-operation recovery still verify paths and permissions. | [Registration tests](../../crates/local-storage/src/agents/native_registration_tests.rs), [startup journey](../../crates/daemon/tests/publication_process.rs) |
+| Native target registration | An unused discovered target is not access authority or a global startup dependency. Actual access and accepted-operation recovery retain path identity and safe-write checks; OS I/O determines accessibility. | [Registration tests](../../crates/local-storage/src/agents/native_registration_tests.rs), [startup journey](../../crates/daemon/tests/publication_process.rs) |
| Operation journal | Domain checkpoints and stored journals agree before publication or native effects; immutable plan bytes and generation/identity guards remain authoritative. JSON member ordering is distinct from a content change. | [Checkpoint](../../crates/domain/src/operation/journal.rs), [verification](../../crates/local-storage/src/control/journal.rs), [transaction guards](../../crates/local-storage/src/control/transaction_v2_tests.rs) |
| Profile deletion | Untouched proof binds the current store instance and exact marker; a stage directory alone cannot prove deletion never began. | [Profile lifecycle](../../crates/daemon/src/control/runtime/settings_profile_tests.rs) |
| Worker/content lifetime | Result completion, process stop, body availability and permission to Continue are separate facts; cleanup requires exact ownership. | [Worker map](worker-context.md#state-and-lifetime), [managed-text contract](../../crates/observation/src/managed_text/README.md) |
diff --git a/docs/local-user-configuration.md b/docs/local-user-configuration.md
index 1888d642..67a8f82e 100644
--- a/docs/local-user-configuration.md
+++ b/docs/local-user-configuration.md
@@ -1,9 +1,11 @@
# Local configuration saves
-HiRoute's owner-only Local Control socket admits processes running as the same OS user as
-`hirouted`. Desktop and CLI use this one local-user scope for configuration saves and Operation
-recovery. They do not need a Desktop/CLI-specific Apply capability or a second authorization
-confirmation. A Save, Publish, or Use this installation click is the ordinary user intent.
+HiRoute's Local Control socket uses the operating system's local access permissions.
+HiRoute adds no file-owner, permission-bit or peer-UID admission check. New private files and
+directories still default to 0600/0700. Desktop and CLI use this local scope for configuration
+saves and Operation recovery. They do not need a Desktop/CLI-specific Apply capability or a
+second authorization confirmation. A Save, Publish, or Use this installation click is the
+ordinary user intent.
The daemon still validates the exact normalized change, digest, resource revisions, idempotency
key, and durable writer admission. On a conflict, refresh the current state and submit the
@@ -22,7 +24,7 @@ configuration is being edited; only a successful lifecycle change enables calls.
## Codex CLI profile
For an isolated instance, set `HOME` and `CODEX_HOME` to its private directories.
-`HIROUTE_CODEX_AUTH_SOURCE` may independently select an absolute, owner-only Codex
+`HIROUTE_CODEX_AUTH_SOURCE` may independently select an absolute, readable Codex
`auth.json` for subscription discovery and CPA's access-only lease. Set it on the
process that starts the daemon. Without this override, the source remains
`CODEX_HOME/auth.json` (or `HOME/.codex/auth.json`). An explicit invalid or missing
@@ -31,6 +33,13 @@ the override does not select the native Agent configuration or Worker history ro
CPA never receives the source's refresh token and never refreshes or rewrites the
source. The original Codex retains refresh ownership.
+Independent sign-in through HiRoute is the recommended Codex and Claude subscription entry;
+CPA then owns that authorization and refresh. When reusing Codex's native login without an
+explicit auth-file override, HiRoute accepts file storage only. A non-file
+`cli_auth_credentials_store` selection is reported as unsupported even if an old `auth.json`
+remains. Use independent sign-in in that case. Borrowing requires a current access token and
+an identifiable account; an ID token or refresh timestamp is not required.
+
An isolated acceptance process must also clear inherited provider credentials,
model-routing variables and Claude context overrides. A private `HOME` alone does
not remove higher-precedence process settings. A settings preview must explain
@@ -64,7 +73,7 @@ including formatting, must be undone before retry; after cleanup you can reapply
edits. HiRoute never force-overwrites a conflict. A newly created profile containing user-added
settings is retained after the managed fields are removed.
-Same-user CLI callers can resume that same operation through `agents connect apply` with:
+Local CLI callers can resume that same operation through `agents connect apply` with:
```json
{"schema":"hiroute.agent-settings-retry/v1","context_id":"<discovered context>","operation_id":"<pending Operation>"}
diff --git a/docs/standalone-cli.md b/docs/standalone-cli.md
index 286dfe9b..2283a62a 100644
--- a/docs/standalone-cli.md
+++ b/docs/standalone-cli.md
@@ -4,7 +4,7 @@
Standalone is the single-user mode that does not install Desktop. The production `hiroute`
CLI, role-all `hirouted` daemon, Local Control, Gateway, business storage, and observation
-form one control and execution loop. It uses the same-UID local trust boundary, needs no
+form one control and execution loop. It uses the local control socket's OS access permissions, needs no
second “CLI management token,” and exposes no second Agent-management API.
Standalone and HiRoute Desktop must not manage the same user installation at the same time. It does not
@@ -415,7 +415,7 @@ hiroute agents check agent_codex_default \
--scope native-authentication --output json
```
-`configuration`, `native-authentication`, and `collaboration` are bounded same-UID local
+`configuration`, `native-authentication`, and `collaboration` are bounded local
checks. They use no second authorization token and make no upstream model call. `live` does
make a real model request and still requires the command help's explicit consent and a
protected probe grant.
diff --git a/docs/standalone-cli.zh-CN.md b/docs/standalone-cli.zh-CN.md
index 36031f61..86e3a809 100644
--- a/docs/standalone-cli.zh-CN.md
+++ b/docs/standalone-cli.zh-CN.md
@@ -3,8 +3,8 @@
[English](standalone-cli.md)
Standalone 是不安装 Desktop 时的单用户运行方式。正式 `hiroute` CLI、`hirouted`
-role-all daemon、Local Control、Gateway、业务存储和观测共同组成控制与运行闭环。它沿用同 UID
-本机信任边界,不需要额外的“CLI 管理 token”,也不提供第二套 Agent 管理 API。
+role-all daemon、Local Control、Gateway、业务存储和观测共同组成控制与运行闭环。本机控制入口使用
+操作系统对 socket 的访问权限,不需要额外的“CLI 管理 token”,也不提供第二套 Agent 管理 API。
Standalone 与 HiRoute Desktop 不应同时管理同一用户的安装,不提供系统级多用户安装、Windows 安装、
运行时下载或自动更新。macOS 可使用相同候选包机制,但本页验证与 Quickstart 以 Linux 为准。
@@ -389,7 +389,7 @@ hiroute agents check agent_codex_default \
--scope native-authentication --output json
```
-`configuration`、`native-authentication` 和 `collaboration` 是同 UID 本地有界检查,不使用第二个
+`configuration`、`native-authentication` 和 `collaboration` 是本地有界检查,不使用第二个
授权 token,也不产生上游模型调用。`live` 会产生真实模型请求,仍要求命令 help 声明的明确同意
与受保护 probe grant。
diff --git a/e2e/matrix/p0-gateway-coverage.json b/e2e/matrix/p0-gateway-coverage.json
index 88dbb90c..050c382c 100644
--- a/e2e/matrix/p0-gateway-coverage.json
+++ b/e2e/matrix/p0-gateway-coverage.json
@@ -202,13 +202,14 @@
{
"assertion_binding": "declaration",
"assertion_ids": [
- "replay.owner_only_permission",
- "replay.zero_provider_on_permission"
+ "replay.accessible_root",
+ "replay.existing_root_mode_preserved",
+ "replay.provider_call"
],
"execution": "real_hirouted_native_provider",
- "id": "replay.owner_only_permission",
+ "id": "replay.accessible_root",
"source": "tools/e2e-harness/tests/p0_gateway_replay.rs",
- "symbol": "real_hirouted_rejects_non_owner_only_replay_root",
+ "symbol": "real_hirouted_accepts_accessible_replay_root_without_chmod",
"test_target": "p0_gateway_replay"
},
{
@@ -301,7 +302,7 @@
"test_target": "p0_gateway_privacy"
}
],
- "registry_digest": "sha256:32438a229a8518a05a1f02ad0ebfa8ed031a6ddc1410120bbc3b6ed5668dad8a",
+ "registry_digest": "sha256:740c86272080c8c807a88cc6322056a3eb579138645d17ef07596d4f5f9cc0e0",
"rows": [
{
"id": "publication.incompatible_or_gap",
@@ -554,11 +555,11 @@
{
"id": "replay.storage_and_capacity",
"receipt_ids": [
- "replay.owner_only_permission",
+ "replay.accessible_root",
"replay.request_capacity",
"replay.local_plaintext"
],
- "scenario": "replay uses one owner-only plaintext backing and preserves request capacity gates",
+ "scenario": "replay honors OS access, uses one private plaintext backing and preserves request capacity gates",
"spec_id": "SPEC-20006"
},
{
diff --git a/e2e/product/golden/control/control-shell-boundary.v1.json b/e2e/product/golden/control/control-shell-boundary.v1.json
index 0068e4b6..83ae5f6f 100644
--- a/e2e/product/golden/control/control-shell-boundary.v1.json
+++ b/e2e/product/golden/control/control-shell-boundary.v1.json
@@ -2,7 +2,7 @@
"schema": "hiroute.control-shell-boundary/v1",
"process": "PROCESS-25016",
"daemon_role": "control_only",
- "transport": "owner_only_uds_peer_uid_v1",
+ "transport": "local_uds_os_access_v1",
"application_entrypoints": 1,
"cli_direct_adapter_dependencies": [],
"preview_writes": 0,
diff --git a/scripts/install-standalone.py b/scripts/install-standalone.py
index 1b5f709e..c80ef9d3 100755
--- a/scripts/install-standalone.py
+++ b/scripts/install-standalone.py
@@ -294,8 +294,7 @@ def prepare_skill_parent(home, destination):
current = current / part
if current.exists() or current.is_symlink():
metadata = current.lstat()
- if (current.is_symlink() or not current.is_dir()
- or metadata.st_uid != os.geteuid() or metadata.st_mode & 0o022):
+ if current.is_symlink() or not current.is_dir():
raise ValueError(f"Agent Skill parent is unsafe: {current}")
continue
current.mkdir(mode=0o700)
@@ -337,16 +336,14 @@ def service_bytes(paths, daemon, cpa, cpa_digest):
def prepare_service_directory(home):
"""Make the fixed proxy snapshot path safe before any recursive mkdir uses umask."""
metadata = home.lstat()
- if (not stat.S_ISDIR(metadata.st_mode)
- or metadata.st_uid != os.geteuid() or metadata.st_mode & 0o022):
+ if not stat.S_ISDIR(metadata.st_mode):
raise ValueError("standalone service HOME is unsafe")
current = home
for part in (".local", "share", "hiroute", "service"):
current = current / part
if current.exists() or current.is_symlink():
metadata = current.lstat()
- if (not stat.S_ISDIR(metadata.st_mode)
- or metadata.st_uid != os.geteuid() or metadata.st_mode & 0o022):
+ if not stat.S_ISDIR(metadata.st_mode):
raise ValueError(f"standalone service parent is unsafe: {current}")
else:
current.mkdir(mode=0o700)
@@ -364,10 +361,7 @@ def prepare_state_directory(paths):
current = current / part
if current.exists() or current.is_symlink():
metadata = current.lstat()
- writable = metadata.st_mode & 0o022
- if (not stat.S_ISDIR(metadata.st_mode)
- or (writable and not metadata.st_mode & 0o1000)
- or (current == state and (metadata.st_uid != os.geteuid() or writable))):
+ if not stat.S_ISDIR(metadata.st_mode):
raise ValueError(f"standalone state parent is unsafe: {current}")
else:
current.mkdir(mode=0o700)
@@ -433,9 +427,6 @@ def read_marker(paths):
marker_path = paths["marker"]
if marker_path.is_symlink() or not marker_path.is_file() or marker_path.stat().st_size > MAX_MANIFEST:
raise ValueError("standalone ownership marker is invalid")
- marker_metadata = marker_path.stat()
- if marker_metadata.st_uid != os.geteuid() or stat.S_IMODE(marker_metadata.st_mode) & 0o022:
- raise ValueError("standalone ownership marker is unsafe")
marker = load_json_bytes(marker_path.read_bytes())
validate_marker(paths, marker)
return marker
@@ -489,7 +480,7 @@ def installation_lock(paths):
descriptor = os.open(lock_path, flags, 0o600)
try:
metadata = os.fstat(descriptor)
- if metadata.st_uid != os.geteuid() or stat.S_IMODE(metadata.st_mode) & 0o077:
+ if not stat.S_ISREG(metadata.st_mode):
raise ValueError("standalone install lock is unsafe")
try:
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
@@ -593,8 +584,6 @@ def install(args):
paths["state"].mkdir(parents=True, exist_ok=True, mode=0o700)
paths["runtime"].mkdir(parents=True, exist_ok=True, mode=0o700)
- paths["state"].chmod(0o700)
- paths["runtime"].chmod(0o700)
if platform.system() == "Darwin":
(paths["state"] / "logs").mkdir(parents=True, exist_ok=True, mode=0o700)
diff --git a/scripts/private-stream-capture.py b/scripts/private-stream-capture.py
index ade0e51a..b69d1785 100644
--- a/scripts/private-stream-capture.py
+++ b/scripts/private-stream-capture.py
@@ -194,7 +194,7 @@ def supervise_candidate(args, root, binary, command, source, report):
def capture_lock(root):
fd = os.open(root / "active.lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
info = os.fstat(fd)
- if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_uid != os.geteuid():
+ if not stat.S_ISREG(info.st_mode):
os.close(fd)
raise ValueError("unsafe capture lock")
return os.fdopen(fd, "rb+")
@@ -210,8 +210,8 @@ def capture_active(root):
def cleanup(root, require_expired=True, lock_wait_seconds=0):
- # Only this exact, expired, owner-only session. Never walk a general evidence tree.
- if root.is_symlink() or root.resolve() != root or root.stat().st_uid != os.geteuid() or stat.S_IMODE(root.stat().st_mode) != 0o700:
+ # Only this exact, expired session. Never walk a general evidence tree.
+ if root.is_symlink() or root.resolve() != root or not root.is_dir():
raise ValueError("unsafe root")
with capture_lock(root) as lock:
deadline = time.monotonic() + max(0, lock_wait_seconds)
diff --git a/scripts/test-private-stream-capture.py b/scripts/test-private-stream-capture.py
index e2a82a04..30aad841 100644
--- a/scripts/test-private-stream-capture.py
+++ b/scripts/test-private-stream-capture.py
@@ -43,6 +43,8 @@ class CaptureSessionTest(unittest.TestCase):
with patch.object(capture.time, "time", return_value=100000):
with self.assertRaises(ValueError):
capture.cleanup(root)
+ root.chmod(0o755)
+ (root / "active.lock").chmod(0o644)
# The stable inode remains; only live kernel ownership blocks cleanup.
with patch.object(capture.time, "time", return_value=100000):
capture.cleanup(root)
diff --git a/scripts/test-standalone-install.py b/scripts/test-standalone-install.py
index af7a1bf5..ef4df22f 100755
--- a/scripts/test-standalone-install.py
+++ b/scripts/test-standalone-install.py
@@ -178,14 +178,13 @@ class MacInstallerTests(StandaloneFixture):
@unittest.skipUnless(os.name == "posix" and os.uname().sysname == "Linux", "Linux layout test")
class InstallerTests(StandaloneFixture):
- def test_unsafe_service_home_is_rejected_without_permission_changes(self):
+ def test_accessible_service_home_preserves_permissions(self):
manifest, archive = self.build()
self.home.chmod(0o775)
with self.environment(), patch.object(installer.subprocess, "run"), patch("builtins.print"):
- with self.assertRaisesRegex(ValueError, "service HOME is unsafe"):
- installer.install(self.install_args(manifest, archive))
+ installer.install(self.install_args(manifest, archive))
self.assertEqual(self.home.stat().st_mode & 0o777, 0o775)
- self.assertFalse((self.home / ".local").exists())
+ self.assertTrue((self.home / ".local").is_dir())
def test_service_parents_are_private_even_with_group_writable_umask(self):
manifest, archive = self.build()
@@ -206,8 +205,7 @@ class InstallerTests(StandaloneFixture):
local.unlink()
local.mkdir()
local.chmod(0o775)
- with self.assertRaisesRegex(ValueError, "service parent is unsafe"):
- installer.prepare_service_directory(self.home)
+ installer.prepare_service_directory(self.home)
self.assertEqual(local.stat().st_mode & 0o777, 0o775)
def test_default_state_parents_are_private_with_group_writable_umask(self):
@@ -254,7 +252,7 @@ class InstallerTests(StandaloneFixture):
self.assertEqual(list(shared.iterdir()), [])
self.assertFalse((local / "bin/hiroute").exists())
- def test_install_rejects_group_writable_state_parent_without_chmod(self):
+ def test_install_accepts_group_writable_state_parent_without_chmod(self):
manifest, archive = self.build()
state = self.home / ".local/state"
state.parent.mkdir(mode=0o700)
@@ -263,10 +261,9 @@ class InstallerTests(StandaloneFixture):
with patch.dict(os.environ, {"HOME": str(self.home)}, clear=True), patch.object(
installer.subprocess, "run"
), patch("builtins.print"):
- with self.assertRaisesRegex(ValueError, "state parent is unsafe"):
- installer.install(self.install_args(manifest, archive))
+ installer.install(self.install_args(manifest, archive))
self.assertEqual(state.stat().st_mode & 0o777, 0o775)
- self.assertFalse((self.home / ".local/bin/hiroute").exists())
+ self.assertTrue((self.home / ".local/bin/hiroute").exists())
def test_safe_existing_state_parent_permissions_are_preserved(self):
manifest, archive = self.build()
@@ -395,15 +392,15 @@ class InstallerTests(StandaloneFixture):
self.assertFalse((claude_skill / "extra.txt").exists())
self.assertEqual((sibling / "SKILL.md").read_text(), "preserve\n")
- def test_install_rejects_group_writable_agent_skill_parent(self):
+ def test_install_accepts_group_writable_agent_skill_parent(self):
manifest, archive = self.build()
parent = self.home / ".agents"
parent.mkdir(mode=0o700)
parent.chmod(0o770)
with self.environment(), patch.object(installer.subprocess, "run"), patch("builtins.print"):
- with self.assertRaisesRegex(ValueError, "Skill parent is unsafe"):
- installer.install(self.install_args(manifest, archive))
- self.assertFalse((self.home / ".local/bin/hiroute").exists())
+ installer.install(self.install_args(manifest, archive))
+ self.assertTrue((self.home / ".local/bin/hiroute").exists())
+ self.assertEqual(parent.stat().st_mode & 0o777, 0o770)
def test_checksum_failure_makes_no_installation_writes(self):
manifest, archive = self.build()
diff --git a/tools/e2e-harness/src/p0/coverage.rs b/tools/e2e-harness/src/p0/coverage.rs
index ee2654f9..0762d68b 100644
--- a/tools/e2e-harness/src/p0/coverage.rs
+++ b/tools/e2e-harness/src/p0/coverage.rs
@@ -288,13 +288,14 @@ pub const RECEIPTS: &[FrozenReceipt] = &[
]
),
receipt!(
- "replay.owner_only_permission",
+ "replay.accessible_root",
"p0_gateway_replay",
- "real_hirouted_rejects_non_owner_only_replay_root",
+ "real_hirouted_accepts_accessible_replay_root_without_chmod",
"tools/e2e-harness/tests/p0_gateway_replay.rs",
[
- "replay.owner_only_permission",
- "replay.zero_provider_on_permission"
+ "replay.accessible_root",
+ "replay.existing_root_mode_preserved",
+ "replay.provider_call"
]
),
receipt!(
@@ -558,9 +559,9 @@ pub const REQUIRED_ROWS: &[FrozenScenarioRow] = &[
row!(
"replay.storage_and_capacity",
"SPEC-20006",
- "replay uses one owner-only plaintext backing and preserves request capacity gates",
+ "replay honors OS access, uses one private plaintext backing and preserves request capacity gates",
[
- "replay.owner_only_permission",
+ "replay.accessible_root",
"replay.request_capacity",
"replay.local_plaintext"
]
diff --git a/tools/e2e-harness/tests/p0_gateway_replay.rs b/tools/e2e-harness/tests/p0_gateway_replay.rs
index d27477d2..a8b1b5ab 100644
--- a/tools/e2e-harness/tests/p0_gateway_replay.rs
+++ b/tools/e2e-harness/tests/p0_gateway_replay.rs
@@ -473,19 +473,42 @@ fn real_hirouted_cleans_exhaustion_deadline_disconnect_and_restart_orphan() {
#[cfg(unix)]
#[test]
-fn real_hirouted_rejects_non_owner_only_replay_root() {
+fn real_hirouted_accepts_accessible_replay_root_without_chmod() {
+ use std::os::unix::fs::PermissionsExt;
+
hiroute_e2e::p0_execution_receipt!(
- "replay.owner_only_permission",
+ "replay.accessible_root",
[
- "replay.owner_only_permission",
- "replay.zero_provider_on_permission"
+ "replay.accessible_root",
+ "replay.existing_root_mode_preserved",
+ "replay.provider_call"
]
);
- let forbidden = NativeProvider::start(vec![success()]);
- let fixture = RuntimeFixture::launch_with_unsafe_replay_root(&[&forbidden], 1);
- let response = fixture.request();
- assert_eq!(response.status, 503);
- assert_eq!(forbidden.calls(), 0);
+ let provider = NativeProvider::start(vec![success()]);
+ let fixture = RuntimeFixture::launch_with_permissive_replay_root(&[&provider], 1);
+ assert_eq!(
+ fs::metadata(&fixture.replay_root)
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o755,
+ "startup must preserve existing replay root permissions"
+ );
+ let body = request_document("permissive replay ".repeat(8_192));
+ let response = fixture.request_body(&body);
+ assert_eq!(response.status, 200);
+ assert_eq!(provider.calls(), 1);
+ wait_replay_empty(&fixture.replay_root);
+ assert_eq!(
+ fs::metadata(&fixture.replay_root)
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o755,
+ "request admission and cleanup must preserve existing replay root permissions"
+ );
}
#[test]
diff --git a/tools/e2e-harness/tests/runtime_support/mod.rs b/tools/e2e-harness/tests/runtime_support/mod.rs
index 1ba79d7d..dd29f8b6 100644
--- a/tools/e2e-harness/tests/runtime_support/mod.rs
+++ b/tools/e2e-harness/tests/runtime_support/mod.rs
@@ -533,7 +533,7 @@ impl ObservationFaults {
#[derive(Clone, Copy, Eq, PartialEq)]
enum ReplayRootMode {
Normal,
- UnsafePermissions,
+ PermissivePermissions,
SeedOrphan,
}
@@ -1055,7 +1055,7 @@ impl RuntimeFixture {
}
#[cfg(unix)]
- pub fn launch_with_unsafe_replay_root(
+ pub fn launch_with_permissive_replay_root(
providers: &[&NativeProvider],
max_attempts: u32,
) -> Self {
@@ -1066,7 +1066,7 @@ impl RuntimeFixture {
None,
None,
RuntimeLaunchOptions {
- replay_root_mode: ReplayRootMode::UnsafePermissions,
+ replay_root_mode: ReplayRootMode::PermissivePermissions,
..RuntimeLaunchOptions::default()
},
)
@@ -1572,13 +1572,13 @@ fn reserve_address() -> SocketAddr {
fn prepare_replay_root(path: &Path, mode: ReplayRootMode) {
match mode {
ReplayRootMode::Normal => {}
- ReplayRootMode::UnsafePermissions => {
- std::fs::create_dir(path).expect("create unsafe replay root");
+ ReplayRootMode::PermissivePermissions => {
+ std::fs::create_dir(path).expect("create permissive replay root");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))
- .expect("set unsafe replay permissions");
+ .expect("set permissive replay permissions");
}
}
ReplayRootMode::SeedOrphan => {
diff --git a/tools/product-e2e/src/smoke/fixtures.rs b/tools/product-e2e/src/smoke/fixtures.rs
index d2239cac..ceb7d25a 100644
--- a/tools/product-e2e/src/smoke/fixtures.rs
+++ b/tools/product-e2e/src/smoke/fixtures.rs
@@ -78,8 +78,7 @@ pub fn discovery(root: &Path, secret: &str) -> Result<(PathBuf, PathBuf)> {
let bin = root.join("agent-bin");
fs::create_dir_all(home.join(".claude"))?;
fs::create_dir_all(&bin)?;
- // These are synthetic homes; native artifact registration rejects writable
- // parents. Do not inherit the caller's umask for this fixture contract.
+ // Keep synthetic homes private without depending on the caller's umask.
for directory in [&home, &home.join(".claude"), &bin] {
fs::set_permissions(directory, fs::Permissions::from_mode(0o700))?;
}
diff --git a/tools/product-e2e/tests/control_shell.rs b/tools/product-e2e/tests/control_shell.rs
index 1bcb8c30..139da1a1 100644
--- a/tools/product-e2e/tests/control_shell.rs
+++ b/tools/product-e2e/tests/control_shell.rs
@@ -576,7 +576,7 @@ fn assert_boundary(golden: &BoundaryGolden) {
assert_eq!(golden.schema, "hiroute.control-shell-boundary/v1");
assert_eq!(golden.process, "PROCESS-25016");
assert_eq!(golden.daemon_role, "control_only");
- assert_eq!(golden.transport, "owner_only_uds_peer_uid_v1");
+ assert_eq!(golden.transport, "local_uds_os_access_v1");
assert_eq!(golden.application_entrypoints, 1);
assert!(golden.cli_direct_adapter_dependencies.is_empty());
assert_eq!(golden.preview_writes, 0);