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: save managed key order and bind requests to current credentials (#114)

澄潭32bfa71f2c85
diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs
index 86f3f1c1..dae7e1ae 100644
--- a/apps/desktop/src-tauri/build.rs
+++ b/apps/desktop/src-tauri/build.rs
@@ -34,6 +34,7 @@ fn main() {
"model_reference_query",
"effective_price_query",
"compute_management_snapshot",
+ "compute_key_masks",
"compute_scan",
"prepare_discovered_model_connection",
"compute_connection_options",
diff --git a/apps/desktop/src-tauri/capabilities/main.json b/apps/desktop/src-tauri/capabilities/main.json
index 360699dd..9f5a3d1b 100644
--- a/apps/desktop/src-tauri/capabilities/main.json
+++ b/apps/desktop/src-tauri/capabilities/main.json
@@ -20,6 +20,7 @@
"allow-model-reference-query",
"allow-effective-price-query",
"allow-compute-management-snapshot",
+ "allow-compute-key-masks",
"allow-compute-scan",
"allow-prepare-discovered-model-connection",
"allow-compute-connection-options",
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/compute_key_masks.toml b/apps/desktop/src-tauri/permissions/autogenerated/compute_key_masks.toml
new file mode 100644
index 00000000..723a5f97
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/compute_key_masks.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-compute-key-masks"
+description = "Enables the compute_key_masks command without any pre-configured scope."
+commands.allow = ["compute_key_masks"]
+
+[[permission]]
+identifier = "deny-compute-key-masks"
+description = "Denies the compute_key_masks command without any pre-configured scope."
+commands.deny = ["compute_key_masks"]
diff --git a/apps/desktop/src-tauri/src/bridge.rs b/apps/desktop/src-tauri/src/bridge.rs
index 3fdd4c0e..26163628 100644
--- a/apps/desktop/src-tauri/src/bridge.rs
+++ b/apps/desktop/src-tauri/src/bridge.rs
@@ -1017,6 +1017,7 @@ pub fn run() {
model_reference_query,
effective_price_query,
compute_management_snapshot,
+ compute_key_masks,
compute_scan,
prepare_discovered_model_connection,
compute_connection_options,
diff --git a/apps/desktop/src-tauri/src/bridge/model_connections.rs b/apps/desktop/src-tauri/src/bridge/model_connections.rs
index 5a666887..1675a3da 100644
--- a/apps/desktop/src-tauri/src/bridge/model_connections.rs
+++ b/apps/desktop/src-tauri/src/bridge/model_connections.rs
@@ -17,6 +17,8 @@ use super::model_connection_web::{
#[derive(Serialize)]
pub struct ProtectedModelInputRegistration {
input_candidate: ComputeCandidateRefV2,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ key_id: Option<String>,
}
fn erase_envelope<T: Serialize>(
@@ -180,6 +182,24 @@ pub async fn release_subscription_check(
.map(Into::into)
}
+#[tauri::command]
+pub async fn compute_key_masks(
+ window: WebviewWindow,
+ state: State<'_, DesktopState>,
+ query: ComputeKeyMasksQueryV1,
+) -> Result<ComputeKeyMasksViewV1, DesktopFailure> {
+ main_window(&window)?;
+ let client = state
+ .0
+ .lock()
+ .await
+ .as_ref()
+ .ok_or("RESIDENT_UNAVAILABLE")?
+ .client
+ .clone();
+ crate::session::query(&client, GET_COMPUTE_KEY_MASKS_OPERATION_V1, &query).await
+}
+
#[tauri::command]
pub async fn compute_management_snapshot(
window: WebviewWindow,
@@ -301,6 +321,7 @@ pub async fn register_protected_model_input(
window: WebviewWindow,
state: State<'_, DesktopState>,
secret: String,
+ source_id: Option<String>,
) -> Result<ProtectedModelInputRegistration, DesktopFailure> {
main_window(&window)?;
#[cfg(unix)]
@@ -313,13 +334,19 @@ pub async fn register_protected_model_input(
.ok_or("RESIDENT_UNAVAILABLE")?
.resident
.register_model_input(zeroize::Zeroizing::new(secret))?;
+ let key_id = source_id
+ .as_deref()
+ .map(|source| hiroute_domain::managed_key_id(source, &candidate.candidate_ref))
+ .transpose()
+ .map_err(|_| "CREDENTIAL_INPUT_INVALID")?;
Ok(ProtectedModelInputRegistration {
input_candidate: candidate,
+ key_id,
})
}
#[cfg(not(unix))]
{
- let _ = (state, secret);
+ let _ = (state, secret, source_id);
Err("TRUSTED_AUTHORITY_UNAVAILABLE".into())
}
}
@@ -555,7 +582,8 @@ pub async fn apply_compute_save(
.await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
- .prepare_model_save_confirmation(request, language)?;
+ .prepare_model_save_confirmation(request, language)
+ .await?;
match confirm(
&window,
&state,
diff --git a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs
index cd0458aa..1e1e0396 100644
--- a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs
+++ b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs
@@ -3,6 +3,7 @@ use hiroute_application_api::{CanonicalDigest, ClientOperationViewV1};
const MODEL_CONNECTION_COMMANDS: &[&str] = &[
"compute_management_snapshot",
+ "compute_key_masks",
"compute_scan",
"prepare_discovered_model_connection",
"register_protected_model_input",
diff --git a/apps/desktop/src-tauri/src/session/model_save.rs b/apps/desktop/src-tauri/src/session/model_save.rs
index 0830cf34..47d9c071 100644
--- a/apps/desktop/src-tauri/src/session/model_save.rs
+++ b/apps/desktop/src-tauri/src/session/model_save.rs
@@ -35,7 +35,7 @@ pub struct ModelSaveAccepted {
pub operation: OperationReferenceV1,
}
impl Session {
- pub fn prepare_model_save_confirmation(
+ pub async fn prepare_model_save_confirmation(
&mut self,
request: ComputeConnectionApplyRequestV1,
language: String,
@@ -72,11 +72,19 @@ impl Session {
| ComputeKeyEditV2::SetEnabled { .. }
)
});
- let message = if language == "en" {
+ let mut message = if language == "en" {
"Change existing source credentials?\nThis will replace, remove or change the availability/order of the credentials selected in the editor. Future calls will use the saved settings."
} else {
"修改既有来源凭据?\n将替换、移除或调整编辑器中选定凭据的可用性或顺序。后续调用将使用保存后的设置。"
}.to_owned();
+ if requires_confirmation {
+ let masks = self.confirmation_key_masks(&change).await;
+ message.push_str(&confirmation_key_details(
+ &change,
+ masks.as_ref(),
+ language == "en",
+ ));
+ }
Ok(ModelSaveConfirmation {
requires_confirmation,
permit: self.confirmation.begin()?,
@@ -87,6 +95,38 @@ impl Session {
})
}
+ async fn confirmation_key_masks(
+ &self,
+ change: &ComputeManagementChangeV2,
+ ) -> Option<ComputeKeyMasksViewV1> {
+ let ComputeManagementSubjectV2::SavedSource { source_id } = &change.subject else {
+ return None;
+ };
+ let snapshot = self
+ .client
+ .compute_management_snapshot_v3(
+ &crate::random_id().ok()?,
+ ComputeManagementQueryV2::default(),
+ )
+ .await
+ .ok()?
+ .data?;
+ let source = snapshot
+ .sources
+ .iter()
+ .find(|source| &source.source_id == source_id)?;
+ super::query(
+ &self.client,
+ GET_COMPUTE_KEY_MASKS_OPERATION_V1,
+ &ComputeKeyMasksQueryV1 {
+ source_id: source_id.clone(),
+ expected_source_revision: source.revision,
+ },
+ )
+ .await
+ .ok()
+ }
+
pub async fn finish_model_save_confirmation(
&mut self,
context: ModelSaveConfirmation,
@@ -204,6 +244,84 @@ impl Session {
}
}
+fn confirmation_key_details(
+ change: &ComputeManagementChangeV2,
+ masks: Option<&ComputeKeyMasksViewV1>,
+ english: bool,
+) -> String {
+ let label = |id: &str, generation: Option<u64>| {
+ let mask = masks
+ .and_then(|view| {
+ view.keys.iter().find(|key| {
+ key.key_id == id
+ && generation.is_none_or(|generation| generation == key.generation)
+ })
+ })
+ .map(|key| key.masked_key.as_str());
+ let suffix: String = id
+ .chars()
+ .rev()
+ .take(8)
+ .collect::<Vec<_>>()
+ .into_iter()
+ .rev()
+ .collect();
+ mask.map_or_else(
+ || format!("ID {suffix}"),
+ |mask| format!("{mask} · {suffix}"),
+ )
+ };
+ let mut details = String::new();
+ for edit in &change.key_edits {
+ let (action, labels) = match edit {
+ ComputeKeyEditV2::Remove {
+ key_id,
+ expected_generation,
+ } => (
+ if english { "Remove" } else { "移除" },
+ label(key_id, Some(*expected_generation)),
+ ),
+ ComputeKeyEditV2::Replace {
+ key_id,
+ expected_generation,
+ ..
+ } => (
+ if english { "Replace" } else { "替换" },
+ label(key_id, Some(*expected_generation)),
+ ),
+ ComputeKeyEditV2::SetEnabled {
+ key_id,
+ expected_generation,
+ enabled,
+ } => (
+ if *enabled {
+ if english { "Enable" } else { "启用" }
+ } else if english {
+ "Disable"
+ } else {
+ "停用"
+ },
+ label(key_id, Some(*expected_generation)),
+ ),
+ ComputeKeyEditV2::SetOrder { key_ids } => (
+ if english {
+ "Keep in order"
+ } else {
+ "保存后保留的顺序"
+ },
+ key_ids
+ .iter()
+ .map(|id| label(id, None))
+ .collect::<Vec<_>>()
+ .join(" → "),
+ ),
+ _ => continue,
+ };
+ details.push_str(&format!("\n{action}: {labels}"));
+ }
+ details
+}
+
fn operation_reference(operation: &ClientOperationViewV1) -> OperationReferenceV1 {
OperationReferenceV1 {
operation_id: operation.operation_id.clone(),
diff --git a/apps/desktop/src/features/models/Models.tsx b/apps/desktop/src/features/models/Models.tsx
index dda67323..0a1be8ac 100644
--- a/apps/desktop/src/features/models/Models.tsx
+++ b/apps/desktop/src/features/models/Models.tsx
@@ -8,17 +8,17 @@ import { Dialog, UiIcon } from '../../ui';
import { confirmDiscard, useDiscardGuard } from '../../ui/discard-guard';
import type { PriceDisplay } from '../model-reference/types';
import { clientOperationId } from '../model-connections/state';
-import { addDraftKey, clearSecrets, createDraft, moveDraftKey, type ModelDraft } from './model-draft';
+import { addDraftKey, buildCredentialEdits, clearSecrets, createDraft, maskEnteredKey, moveDraftKey, type ModelDraft } from './model-draft';
import { subscriptionAttentionCopy } from './subscription-copy';
import { ConnectionLifecycleDialog } from './ConnectionLifecycleDialog';
import type {
- CandidateRef,
- KeyEdit,
ManagedModel,
ManagedSource,
ManagementChange,
ManagementSnapshot,
ProtectedKeyInput,
+ PreparedKeyInput,
+ KeyMasks,
SavePreview,
} from './types';
@@ -28,7 +28,8 @@ type Props = {
initialSourceId?: string | null;
busy?: boolean;
onRefresh(): Promise<void>;
- onPrepareKeyInput(sourceId: string, input: ProtectedKeyInput): Promise<CandidateRef>;
+ onPrepareKeyInput(sourceId: string, input: ProtectedKeyInput): Promise<PreparedKeyInput>;
+ onReadKeyMasks?(source: ManagedSource): Promise<KeyMasks>;
onPreview(change: ManagementChange): Promise<SavePreview>;
onApply(preview: SavePreview): Promise<'saved' | 'uncertain'>;
onDiscardProtectedInputs(): void;
@@ -215,34 +216,7 @@ export function Models(props: Props) {
setSubmitting(true);
setErrorCode('');
try {
- const edits: KeyEdit[] = [];
- for (const key of draft.keys) {
- if (key.removed && key.keyId) {
- edits.push({ action: 'remove', key_id: key.keyId, expected_generation: key.expectedGeneration });
- continue;
- }
- if (key.removed) continue;
- if (key.replacement) {
- const candidate = await props.onPrepareKeyInput(source.source_id, {
- draft_id: key.draftId,
- key_id: key.keyId,
- expected_generation: key.expectedGeneration,
- value: key.replacement,
- });
- edits.push(key.keyId
- ? { action: 'replace', key_id: key.keyId, expected_generation: key.expectedGeneration, input_candidate: candidate }
- : { action: 'add', input_candidate: candidate });
- }
- const original = source.keys.find(item => item.key_id === key.keyId);
- if (key.keyId && original && original.enabled !== key.enabled) {
- edits.push({ action: 'set_enabled', key_id: key.keyId, expected_generation: key.expectedGeneration, enabled: key.enabled });
- }
- }
- const retainedIds = draft.keys.filter(key => !key.removed && key.keyId).map(key => key.keyId!);
- const originalIds = source.keys.map(key => key.key_id);
- if (retainedIds.length === originalIds.length && retainedIds.some((id, index) => id !== originalIds[index])) {
- edits.push({ action: 'set_order', key_ids: retainedIds });
- }
+ const edits = await buildCredentialEdits(source, draft, props.onPrepareKeyInput);
const change: ManagementChange = {
schema: 'hiroute.compute-management-change/v2',
subject: { kind: 'saved_source', source_id: source.source_id },
@@ -470,7 +444,7 @@ export function Models(props: Props) {
onClose={() => { if (!submitting) cancelCredentials(); }}
footer={<><button className="btn" type="button" disabled={submitting} onClick={cancelCredentials}>{text('取消', 'Cancel')}</button><span className="mc-footer-spacer" /><button className="btn btn-primary" type="button" disabled={submitting || !props.mutable || !draft?.selectedModels.length} onClick={() => void saveCredentials()}>{submitting ? text('正在保存…', 'Saving…') : text('保存凭据', 'Save credentials')}</button></>}
>
- {source && draft && <CredentialEditor language={props.language} source={source} model={model} draft={draft} errorCode={errorCode} onChange={setDraft} onEditingChange={setCredentialEditing} />}
+ {source && draft && <CredentialEditor language={props.language} source={source} model={model} draft={draft} errorCode={errorCode} onChange={setDraft} onEditingChange={setCredentialEditing} readKeyMasks={props.onReadKeyMasks} />}
</Dialog>
</section>;
}
@@ -560,7 +534,7 @@ function ModelPriceSummary({ language, model, billing, contexts }: {
return <div className="v3-price"><strong>{currency}{trim(rates[0])} / {currency}{trim(rates[1])}</strong><span>{zh ? '输入 / 输出 · 每 100 万 tokens' : 'Input / output · per million tokens'} · {context.currency} · {origin === 'manual' ? (zh ? '人工费率' : 'Manual rates') : (zh ? '目录或参考费率' : 'Catalog or reference rates')}</span></div>;
}
-function CredentialEditor({ language, source, model, draft, errorCode, onChange, onEditingChange }: {
+function CredentialEditor({ language, source, model, draft, errorCode, onChange, onEditingChange, readKeyMasks }: {
language: 'zh' | 'en';
source: ManagedSource;
model: ManagedModel | undefined;
@@ -568,12 +542,30 @@ function CredentialEditor({ language, source, model, draft, errorCode, onChange,
errorCode: string;
onChange(value: ModelDraft): void;
onEditingChange(value: boolean): void;
+ readKeyMasks?: Props['onReadKeyMasks'];
}) {
const zh = language === 'zh';
const text = (cn: string, en: string) => zh ? cn : en;
const [editing, setEditing] = useState<{ kind: 'add' } | { kind: 'replace'; draftId: string } | null>(null);
const [secretError, setSecretError] = useState('');
+ const [showSecret, setShowSecret] = useState(false);
+ const [masks, setMasks] = useState<KeyMasks['keys']>([]);
+ useEffect(() => {
+ let active = true;
+ setMasks([]);
+ void readKeyMasks?.(source).then(value => {
+ if (active && value.source_id === source.source_id && value.source_revision === source.revision) setMasks(value.keys);
+ }).catch(() => { /* A mask read never changes save authority or blocks editing. */ });
+ return () => { active = false; };
+ }, [source.source_id, source.revision, readKeyMasks]);
+ useEffect(() => { setShowSecret(false); }, [editing]);
const visibleKeys = draft.keys.filter(key => !key.removed);
+ function keyLabel(key: ModelDraft['keys'][number]) {
+ return key.replacement ? maskEnteredKey(key.replacement)
+ : masks.find(item => item.key_id === key.keyId && item.generation === key.expectedGeneration)?.masked_key
+ ?? text(`标识 ${key.keyId?.slice(-8) ?? key.draftId.slice(-8)} · 遮罩暂不可用`,
+ `ID ${key.keyId?.slice(-8) ?? key.draftId.slice(-8)} · Mask unavailable`);
+ }
const affected = source.models.map(item => item.display_name).join('、');
function updateKey(draftId: string, update: (key: ModelDraft['keys'][number]) => ModelDraft['keys'][number]) {
@@ -624,7 +616,7 @@ function CredentialEditor({ language, source, model, draft, errorCode, onChange,
if (event.altKey && event.key === 'ArrowDown') { event.preventDefault(); onChange(moveDraftKey(draft, key.draftId, 1)); }
}}>
<span className="candidate-index">{index + 1}</span>
- <div className="row-main"><strong>{text(`Key ${index + 1}`, `Key ${index + 1}`)}</strong><p className="oc-meta">{key.keyId ? availability : text('新增,尚未保存', 'New, not saved')}</p></div>
+ <div className="row-main"><strong>{text(`Key ${index + 1}`, `Key ${index + 1}`)}</strong><p className="oc-key-mask" title={key.keyId ? text(`标识 ${key.keyId.slice(-8)}`, `ID ${key.keyId.slice(-8)}`) : undefined}>{keyLabel(key)}</p><p className="oc-meta">{key.keyId ? availability : text('新增,尚未保存', 'New, not saved')}</p></div>
<div className="oc-key-actions">
<button className="icon-btn" type="button" aria-label={text('上移', 'Move up')} disabled={index === 0} onClick={() => onChange(moveDraftKey(draft, key.draftId, -1))}><UiIcon name="arrowUp" /></button>
<button className="icon-btn" type="button" aria-label={text('下移', 'Move down')} disabled={index === visibleKeys.length - 1} onClick={() => onChange(moveDraftKey(draft, key.draftId, 1))}><UiIcon name="arrowDown" /></button>
@@ -634,9 +626,14 @@ function CredentialEditor({ language, source, model, draft, errorCode, onChange,
</div>;
})}
{!visibleKeys.length && <p className="oc-meta">{text('还没有凭据,添加后可用于这个接入。', 'No credentials yet. Add one for this connection.')}</p>}
+ {draft.keys.some(key => key.removed && key.keyId) && <div className="callout warn">
+ <strong>{text('保存后移除', 'Removed on save')}</strong>
+ {draft.keys.filter(key => key.removed && key.keyId).map(key => <p key={key.draftId}>{keyLabel(key)}</p>)}
+ </div>}
{editing ? <div className="field">
<label className="field-label" htmlFor="credential-secret">{editing.kind === 'replace' ? text('替换 API Key', 'Replace API key') : 'API Key'}</label>
- <input id="credential-secret" data-autofocus className="input" type="password" autoComplete="new-password" aria-invalid={Boolean(secretError)} aria-describedby={secretError ? 'credential-secret-error' : undefined} value={editing.kind === 'add' ? draft.addedSecret : draft.keys.find(key => key.draftId === editing.draftId)?.replacement ?? ''} onChange={event => { setSecretError(''); if (editing.kind === 'add') onChange({ ...draft, addedSecret: event.target.value }); else updateKey(editing.draftId, key => ({ ...key, replacement: event.target.value })); }} />
+ <input id="credential-secret" data-autofocus className="input" type={showSecret ? 'text' : 'password'} autoComplete="new-password" aria-invalid={Boolean(secretError)} aria-describedby={secretError ? 'credential-secret-error' : undefined} value={editing.kind === 'add' ? draft.addedSecret : draft.keys.find(key => key.draftId === editing.draftId)?.replacement ?? ''} onChange={event => { setSecretError(''); if (editing.kind === 'add') onChange({ ...draft, addedSecret: event.target.value }); else updateKey(editing.draftId, key => ({ ...key, replacement: event.target.value })); }} />
+ <button className="btn btn-quiet" type="button" aria-pressed={showSecret} onClick={() => setShowSecret(value => !value)}>{showSecret ? text('隐藏', 'Hide') : text('显示', 'Show')}</button>
{secretError && <p id="credential-secret-error" className="oc-inline-error" role="alert">{secretError}</p>}
<div className="task-actions"><button className="btn" type="button" onClick={stopEditing}>{text('取消', 'Cancel')}</button><button className="btn btn-primary" type="button" onClick={acceptSecret}>{text('加入待保存修改', 'Add to changes')}</button></div>
</div> : source.actions.includes('add_key') && <button className="btn" type="button" onClick={() => { setEditing({ kind: 'add' }); setSecretError(''); onEditingChange(true); }}><UiIcon name="plus" />{text('添加 API Key', 'Add API key')}</button>}
diff --git a/apps/desktop/src/features/models/model-draft.ts b/apps/desktop/src/features/models/model-draft.ts
index 33ba5e14..f5920824 100644
--- a/apps/desktop/src/features/models/model-draft.ts
+++ b/apps/desktop/src/features/models/model-draft.ts
@@ -1,4 +1,4 @@
-import type { ManagedSource, ProtectedKeyInput } from './types';
+import type { KeyEdit, ManagedSource, PreparedKeyInput, ProtectedKeyInput } from './types';
export type DraftKey = {
draftId: string;
@@ -60,6 +60,14 @@ export function moveDraftKey(draft: ModelDraft, draftId: string, offset: -1 | 1)
return { ...draft, keys };
}
+/** Only the currently entered value; saved material is masked by the service. */
+export function maskEnteredKey(value: string): string {
+ const chars = [...value];
+ if (chars.length <= 2 || /[\u0000-\u001f\u007f-\u009f]/.test(value)) return '••••••••';
+ if (chars.length <= 12) return `••••••••${chars.slice(-2).join('')}`;
+ return `${chars.slice(0, 4).join('')}••••••••${chars.slice(-4).join('')}`;
+}
+
export function protectedInputs(draft: ModelDraft): ProtectedKeyInput[] {
return draft.keys
.filter(key => !key.removed && key.replacement.length > 0)
@@ -78,3 +86,42 @@ export function clearSecrets(draft: ModelDraft): ModelDraft {
keys: draft.keys.map(key => ({ ...key, replacement: '' })),
};
}
+
+/** Submit the entire final membership and order in the same atomic save. */
+export async function buildCredentialEdits(
+ source: ManagedSource,
+ draft: ModelDraft,
+ prepare: (sourceId: string, input: ProtectedKeyInput) => Promise<PreparedKeyInput>,
+): Promise<KeyEdit[]> {
+ const edits: KeyEdit[] = [];
+ const orderedIds: string[] = [];
+ for (const key of draft.keys) {
+ if (key.removed) {
+ if (key.keyId) edits.push({ action: 'remove', key_id: key.keyId, expected_generation: key.expectedGeneration });
+ continue;
+ }
+ let keyId = key.keyId;
+ if (key.replacement) {
+ const prepared = await prepare(source.source_id, {
+ draft_id: key.draftId, key_id: key.keyId,
+ expected_generation: key.expectedGeneration, value: key.replacement,
+ });
+ if (!prepared.key_id) throw new Error('CREDENTIAL_INPUT_INVALID');
+ keyId ??= prepared.key_id;
+ edits.push(key.keyId
+ ? { action: 'replace', key_id: key.keyId, expected_generation: key.expectedGeneration, input_candidate: prepared.input_candidate }
+ : { action: 'add', input_candidate: prepared.input_candidate });
+ }
+ if (!keyId) throw new Error('CREDENTIAL_INPUT_INVALID');
+ orderedIds.push(keyId);
+ const original = source.keys.find(item => item.key_id === key.keyId);
+ if (original ? original.enabled !== key.enabled : !key.enabled) {
+ edits.push({ action: 'set_enabled', key_id: keyId,
+ expected_generation: original ? key.expectedGeneration : 1, enabled: key.enabled });
+ }
+ }
+ if (edits.length || orderedIds.some((id, index) => id !== source.keys[index]?.key_id)) {
+ edits.push({ action: 'set_order', key_ids: orderedIds });
+ }
+ return edits;
+}
diff --git a/apps/desktop/src/features/models/types.ts b/apps/desktop/src/features/models/types.ts
index 1418a130..2d853c7c 100644
--- a/apps/desktop/src/features/models/types.ts
+++ b/apps/desktop/src/features/models/types.ts
@@ -1,5 +1,8 @@
export type RevisionSet = { target: number; dependencies: Record<string, number> };
export type CandidateRef = { candidate_ref: string; candidate_revision: number };
+export type PreparedKeyInput = { input_candidate: CandidateRef; key_id: string };
+export type KeyMasks = { source_id: string; source_revision: number;
+ keys: { key_id: string; generation: number; masked_key: string }[] };
export type MaterializationState = 'needs_credential' | 'needs_authorization' | 'ready' | 'disabled';
export type Provenance = 'registered' | 'user_configured' | 'connector_owned';
export type KeyAvailability = 'available' | 'cooling_down' | 'disabled' | 'unavailable' | 'unknown';
diff --git a/apps/desktop/src/occami/styles/occami.css b/apps/desktop/src/occami/styles/occami.css
index 2364b522..358afde2 100644
--- a/apps/desktop/src/occami/styles/occami.css
+++ b/apps/desktop/src/occami/styles/occami.css
@@ -27,6 +27,7 @@
.oc-meta {font-size:calc(12px * var(--hr-text-scale));color:var(--text-muted);line-height:1.8;}
.oc-key-row {display:flex;align-items:center;gap:12px;padding:16px;border:1px solid var(--border);border-radius:10px;margin-bottom:10px;}
.oc-key-row>.row-main {flex:1;}
+.oc-key-mask {margin:5px 0 0;font-family:var(--font-mono,monospace);font-size:calc(12px * var(--hr-text-scale));color:var(--text-muted);overflow-wrap:anywhere;}
.oc-key-actions {display:flex;gap:4px;}
.oc-inline-error {color:var(--red);font-size:calc(12px * var(--hr-text-scale));margin:8px 0;}
.oc-spinner {display:inline-block;width:16px;height:16px;flex:0 0 16px;border:2px solid var(--border-strong);border-top-color:var(--accent);border-radius:50%;animation:oc-spin .8s linear infinite;}
diff --git a/apps/desktop/src/product/ModelManagementPage.tsx b/apps/desktop/src/product/ModelManagementPage.tsx
index 50bbb88f..05982148 100644
--- a/apps/desktop/src/product/ModelManagementPage.tsx
+++ b/apps/desktop/src/product/ModelManagementPage.tsx
@@ -708,10 +708,16 @@ export function ModelManagementPage({
}
}
- async function prepareKeyInput(_sourceId: string, input: ProtectedKeyInput): Promise<CandidateRef> {
- const registration = await backend.registerProtectedInput(input.value);
+ const readKeyMasks = useMemo(() => (source: ManagedSource) => invoke<import('../features/models/types').KeyMasks>(
+ 'compute_key_masks', { query: { source_id: source.source_id, expected_source_revision: source.revision } },
+ ), []);
+
+ async function prepareKeyInput(sourceId: string, input: ProtectedKeyInput) {
+ const registration = await invoke<ProtectedInputRegistration & { key_id: string }>(
+ 'register_protected_model_input', { secret: input.value, sourceId },
+ );
protectedInputs.current.push(registration.input_candidate);
- return registration.input_candidate;
+ return registration;
}
async function applyExisting(preview: SavePreview): Promise<'saved' | 'uncertain'> {
@@ -1200,6 +1206,7 @@ export function ModelManagementPage({
busy={loading}
onRefresh={refreshManagement}
onPrepareKeyInput={prepareKeyInput}
+ onReadKeyMasks={readKeyMasks}
onPreview={(change: ManagementChange) => invoke<SavePreview>('preview_compute_save', { change })}
onApply={applyExisting}
onDiscardProtectedInputs={discardProtectedInputs}
diff --git a/apps/desktop/tests/model-credential-order.test.mjs b/apps/desktop/tests/model-credential-order.test.mjs
new file mode 100644
index 00000000..23d99fd8
--- /dev/null
+++ b/apps/desktop/tests/model-credential-order.test.mjs
@@ -0,0 +1,44 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { addDraftKey, buildCredentialEdits, createDraft, moveDraftKey } from '../src/features/models/model-draft.ts';
+
+const source = (ids = ['A']) => ({ source_id: 'source/test', state: 'ready', models: [],
+ keys: ids.map((key_id, ordinal) => ({ key_id, ordinal, enabled: true, generation: 3, fingerprint_hint: key_id })) });
+const candidate = { candidate_ref: 'input/B', candidate_revision: 1 };
+const prepare = async () => ({ key_id: 'B', input_candidate: candidate });
+
+test('adding B then moving it before A saves complete membership in one change', async () => {
+ const saved = source();
+ let draft = addDraftKey({ ...createDraft(saved), addedSecret: 'test-key-B' });
+ draft = moveDraftKey(draft, draft.keys[1].draftId, -1);
+ assert.deepEqual(await buildCredentialEdits(saved, draft, prepare), [
+ { action: 'add', input_candidate: candidate }, { action: 'set_order', key_ids: ['B', 'A'] },
+ ]);
+ assert.deepEqual(saved.keys.map(key => key.key_id), ['A']);
+});
+
+test('removal and reorder submit only the surviving complete set', async () => {
+ const saved = source(['A', 'B', 'C']);
+ let draft = createDraft(saved);
+ draft.keys[1].removed = true;
+ draft = moveDraftKey(moveDraftKey(draft, 'C', -1), 'C', -1);
+ assert.deepEqual(await buildCredentialEdits(saved, draft, prepare), [
+ { action: 'remove', key_id: 'B', expected_generation: 3 },
+ { action: 'set_order', key_ids: ['C', 'A'] },
+ ]);
+});
+
+test('replacement retains identity and new disabled Key uses its first generation', async () => {
+ const saved = source();
+ let draft = addDraftKey({ ...createDraft(saved), addedSecret: 'test-key-B' });
+ draft.keys[0].replacement = 'replacement-A';
+ draft.keys[0].enabled = false;
+ draft.keys[1].enabled = false;
+ const edits = await buildCredentialEdits(saved, draft, prepare);
+ assert.equal(edits[0].key_id, 'A');
+ assert.deepEqual(edits.filter(edit => edit.action === 'set_enabled'), [
+ { action: 'set_enabled', key_id: 'A', expected_generation: 3, enabled: false },
+ { action: 'set_enabled', key_id: 'B', expected_generation: 1, enabled: false },
+ ]);
+ assert.deepEqual(edits.at(-1), { action: 'set_order', key_ids: ['A', 'B'] });
+});
diff --git a/apps/desktop/tests/v3/browser/connection-flow.tsx b/apps/desktop/tests/v3/browser/connection-flow.tsx
index b8f58a40..3eda5d65 100644
--- a/apps/desktop/tests/v3/browser/connection-flow.tsx
+++ b/apps/desktop/tests/v3/browser/connection-flow.tsx
@@ -51,7 +51,7 @@ function Harness() {
source.provenance === 'registered' ? { ...source, display_name: savedName || '团队模型服务' } : source) }), [savedName]);
return <PresentationRoot language={language} theme={params.get('theme') === 'dark' ? 'dark' : 'light'} textScale={params.get('scale') === '2' ? 2 : 1}>
<Models language={language} snapshot={management} mutable onRefresh={async () => undefined}
- onPrepareKeyInput={async () => ({ candidate_ref: 'input/saved', candidate_revision: 1 })}
+ onPrepareKeyInput={async () => ({ input_candidate: { candidate_ref: 'input/saved', candidate_revision: 1 }, key_id: 'credential/test-saved' })}
onPreview={async () => { throw new Error('Credential editing is outside this fixture'); }}
onApply={async () => 'saved'} onDiscardProtectedInputs={() => undefined} />
{open && <ModelConnectionForm language={language} initialDraft={initial} expectedRevisions={readyManagement.revisions} mutable backend={backend}
diff --git a/apps/desktop/tests/v3/browser/product-fixtures.ts b/apps/desktop/tests/v3/browser/product-fixtures.ts
index d096ae7f..65d656ab 100644
--- a/apps/desktop/tests/v3/browser/product-fixtures.ts
+++ b/apps/desktop/tests/v3/browser/product-fixtures.ts
@@ -464,6 +464,12 @@ export function mockProductInvoke(command: string, payload: Record<string, any>
fixtureTrace.requests.push({ command, payload: structuredClone(payload) });
const fresh = scenario === 'fresh';
if (command === 'compute_management_snapshot') return fresh ? { ...readyManagement, sources: [] } : readyManagement;
+ if (command === 'compute_key_masks') {
+ const query = payload?.query as { source_id: string; expected_source_revision: number };
+ const source = readyManagement.sources.find(source => source.source_id === query.source_id);
+ return { source_id: query.source_id, source_revision: query.expected_source_revision,
+ keys: source?.keys.map(key => ({ key_id: key.key_id, generation: key.generation, masked_key: 'sk-t••••••••72D1' })) ?? [] };
+ }
if (command === 'compute_connection_options') return {
schema: 'hiroute.compute-connection-options/v1',
catalog: {
@@ -826,6 +832,6 @@ export function mockProductInvoke(command: string, payload: Record<string, any>
};
}
if (command === 'release_protected_model_input' || command === 'cancel_model_connection_check') return undefined;
- if (command === 'register_protected_model_input') return { input_candidate: { candidate_ref: 'candidate/protected', candidate_revision: 1 } };
+ if (command === 'register_protected_model_input') return { input_candidate: { candidate_ref: 'candidate/protected', candidate_revision: 1 }, key_id: 'credential/fixture-protected' };
throw new Error(`Unexpected V3 fixture command: ${command}`);
}
diff --git a/crates/application-api/src/compute_key_masks.rs b/crates/application-api/src/compute_key_masks.rs
new file mode 100644
index 00000000..297a98d0
--- /dev/null
+++ b/crates/application-api/src/compute_key_masks.rs
@@ -0,0 +1,28 @@
+//! A separate safe projection: published compute snapshots retain their fingerprint semantics.
+
+use serde::{Deserialize, Serialize};
+
+pub const GET_COMPUTE_KEY_MASKS_OPERATION_V1: &str = "GetComputeKeyMasksV1";
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct ComputeKeyMasksQueryV1 {
+ pub source_id: String,
+ pub expected_source_revision: u64,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct ComputeKeyMaskViewV1 {
+ pub key_id: String,
+ pub generation: u64,
+ pub masked_key: String,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct ComputeKeyMasksViewV1 {
+ pub source_id: String,
+ pub source_revision: u64,
+ pub keys: Vec<ComputeKeyMaskViewV1>,
+}
diff --git a/crates/application-api/src/lib.rs b/crates/application-api/src/lib.rs
index b8d69dbd..a2f5c33a 100644
--- a/crates/application-api/src/lib.rs
+++ b/crates/application-api/src/lib.rs
@@ -25,9 +25,11 @@ mod commands;
pub use classifier_diagnostic::*;
pub use client_access::*;
mod compute_control;
+mod compute_key_masks;
mod compute_management;
mod compute_management_v3;
mod compute_management_view;
+pub use compute_key_masks::*;
mod generated;
mod model_catalog;
mod model_connections;
diff --git a/crates/application/src/compute_management/dispatch.rs b/crates/application/src/compute_management/dispatch.rs
index 4763be68..a9d5ef86 100644
--- a/crates/application/src/compute_management/dispatch.rs
+++ b/crates/application/src/compute_management/dispatch.rs
@@ -28,6 +28,7 @@ pub(crate) fn is_compute_management_operation(operation: &str) -> bool {
| "GetCompute"
| LIST_COMPUTE_OPERATION_V3
| GET_COMPUTE_OPERATION_V3
+ | hiroute_application_api::GET_COMPUTE_KEY_MASKS_OPERATION_V1
| GET_COMPUTE_CANDIDATE_OPERATION_V2
| PREVIEW_COMPUTE_SAVE_OPERATION_V2
| APPLY_COMPUTE_SAVE_OPERATION_V2
@@ -174,6 +175,17 @@ pub(crate) fn dispatch_compute_management(
request_id,
)
}
+ hiroute_application_api::GET_COMPUTE_KEY_MASKS_OPERATION_V1 => {
+ if request.protected_grant.is_some() {
+ return failed(ErrorCode::CapabilityDenied, request_id);
+ }
+ let Ok(query) = serde_json::from_value::<hiroute_application_api::ComputeKeyMasksQueryV1>(
+ request.payload,
+ ) else {
+ return failed(ErrorCode::InvalidArguments, request_id);
+ };
+ result(management.compute_key_masks(&query), request_id)
+ }
LIST_COMPUTE_OPERATION_V3 | GET_COMPUTE_OPERATION_V3 => {
if request.protected_grant.is_some() {
return failed(ErrorCode::CapabilityDenied, request_id);
diff --git a/crates/application/src/compute_management/mutation_support.rs b/crates/application/src/compute_management/mutation_support.rs
index 2c7424c0..d749bc68 100644
--- a/crates/application/src/compute_management/mutation_support.rs
+++ b/crates/application/src/compute_management/mutation_support.rs
@@ -428,13 +428,8 @@ pub(super) fn managed_key_id(
source_id: &str,
candidate: &ComputeCandidateRefV2,
) -> Result<String, ComputeManagementPlanningErrorV2> {
- let digest = CanonicalDigest::of(&(
- "hiroute.compute-management-key/v2",
- source_id,
- &candidate.candidate_ref,
- ))
- .map_err(|_| ComputeManagementPlanningErrorV2::InvalidKeyEdit)?;
- Ok(format!("credential/managed-{}", digest_suffix(&digest, 24)))
+ hiroute_domain::managed_key_id(source_id, &candidate.candidate_ref)
+ .map_err(|_| ComputeManagementPlanningErrorV2::InvalidKeyEdit)
}
pub(super) fn managed_binding_id(
diff --git a/crates/application/src/control/mod.rs b/crates/application/src/control/mod.rs
index f991435e..e5a3eeea 100644
--- a/crates/application/src/control/mod.rs
+++ b/crates/application/src/control/mod.rs
@@ -438,6 +438,13 @@ pub enum ComputeManagementControlError {
/// Production adapter boundary for the source-level model connection aggregate. Public payloads
/// remain closed DTOs; candidate facts and protected input slots stay behind this port.
pub trait ComputeManagementControlPort: Send + Sync {
+ fn compute_key_masks(
+ &self,
+ _query: &hiroute_application_api::ComputeKeyMasksQueryV1,
+ ) -> Result<hiroute_application_api::ComputeKeyMasksViewV1, ComputeManagementControlError> {
+ Err(ComputeManagementControlError::Unavailable)
+ }
+
fn manage_subscription_login(
&self,
_request: hiroute_application_api::ComputeSubscriptionLoginRequestV1,
diff --git a/crates/daemon/src/control/runtime.rs b/crates/daemon/src/control/runtime.rs
index f198421f..d8cfda24 100644
--- a/crates/daemon/src/control/runtime.rs
+++ b/crates/daemon/src/control/runtime.rs
@@ -826,6 +826,17 @@ pub(crate) struct ControlNativeCredentialAuthority {
}
impl NativeCredentialAuthorityV1 for ControlNativeCredentialAuthority {
+ fn current_native_credential_refs(
+ &self,
+ request: &NativeCredentialLeaseRequestV1,
+ ) -> Result<Option<Vec<String>>, hiroute_domain::NativeCredentialLeaseErrorV1> {
+ self.adapter
+ .stores
+ .lock()
+ .map_err(|_| PortError::new(PortErrorCode::Unavailable, "control.runtime.pool_lock"))?
+ .current_native_credential_refs(request)
+ }
+
fn lease_native_credential(
&self,
request: &NativeCredentialLeaseRequestV1,
diff --git a/crates/daemon/src/control/runtime/model_connections.rs b/crates/daemon/src/control/runtime/model_connections.rs
index 0c888185..939a701b 100644
--- a/crates/daemon/src/control/runtime/model_connections.rs
+++ b/crates/daemon/src/control/runtime/model_connections.rs
@@ -34,6 +34,7 @@ use super::LocalControlAdapter;
mod discovered;
mod key_inputs;
+mod key_masks;
mod pi_discovered;
mod presentation;
mod registered;
@@ -524,6 +525,13 @@ impl ComputeManagementControlPort for LocalControlAdapter {
.map(|view| view.into_v2())
}
+ fn compute_key_masks(
+ &self,
+ query: &hiroute_application_api::ComputeKeyMasksQueryV1,
+ ) -> Result<hiroute_application_api::ComputeKeyMasksViewV1, ComputeManagementControlError> {
+ self.saved_key_masks(query)
+ }
+
fn compute_management_snapshot_v3(
&self,
query: &ComputeManagementQueryV2,
diff --git a/crates/daemon/src/control/runtime/model_connections/key_masks.rs b/crates/daemon/src/control/runtime/model_connections/key_masks.rs
new file mode 100644
index 00000000..4487addf
--- /dev/null
+++ b/crates/daemon/src/control/runtime/model_connections/key_masks.rs
@@ -0,0 +1,92 @@
+//! Bounded display masks generated under the coordinated Secret authority.
+
+use hiroute_application::control::ComputeManagementControlError as Error;
+use hiroute_application_api::{
+ ComputeKeyMaskViewV1, ComputeKeyMasksQueryV1, ComputeKeyMasksViewV1,
+};
+use hiroute_domain::{ComputeManagementRepositoryPort, SecretStorePort, VerifiedSecretSubjectV1};
+
+impl super::LocalControlAdapter {
+ pub(super) fn saved_key_masks(
+ &self,
+ query: &ComputeKeyMasksQueryV1,
+ ) -> Result<ComputeKeyMasksViewV1, Error> {
+ let stores = self.stores_lock().map_err(|_| Error::Unavailable)?;
+ let source = stores
+ .control()
+ .compute_management_source(&query.source_id)
+ .map_err(super::map_port)?
+ .ok_or(Error::NotFound)?;
+ if source.revision != query.expected_source_revision {
+ return Err(Error::Conflict);
+ }
+ if !source.provenance.is_native() {
+ return Err(Error::Invalid);
+ }
+ let subject = VerifiedSecretSubjectV1::from_authenticated_transport(
+ "hirouted",
+ format!("source/{}", source.source_id),
+ )
+ .map_err(|_| Error::Corrupt)?;
+ let destination = source
+ .target
+ .credential_destination()
+ .map_err(|_| Error::Corrupt)?;
+ let mut keys = Vec::with_capacity(source.credentials.len());
+ for key in &source.credentials {
+ let generation = key.credential.generation();
+ let secret = stores
+ .secrets()
+ .resolve_secret(
+ &subject,
+ &key.credential,
+ "provider-auth",
+ &destination,
+ generation,
+ )
+ .map_err(super::map_port)?;
+ let value = std::str::from_utf8(secret.expose()).map_err(|_| Error::Corrupt)?;
+ let masked_key = mask(value);
+ keys.push(ComputeKeyMaskViewV1 {
+ key_id: key.key_id.clone(),
+ generation,
+ masked_key,
+ });
+ }
+ Ok(ComputeKeyMasksViewV1 {
+ source_id: source.source_id,
+ source_revision: source.revision,
+ keys,
+ })
+ }
+}
+
+fn mask(value: &str) -> String {
+ let chars: Vec<_> = value.chars().collect();
+ if chars.iter().any(|ch| ch.is_control()) || chars.len() <= 2 {
+ return "••••••••".into();
+ }
+ if chars.len() <= 12 {
+ return format!(
+ "••••••••{}",
+ chars[chars.len() - 2..].iter().collect::<String>()
+ );
+ }
+ format!(
+ "{}••••••••{}",
+ chars[..4].iter().collect::<String>(),
+ chars[chars.len() - 4..].iter().collect::<String>()
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn masks_never_reveal_short_keys_and_bound_long_keys() {
+ for value in ["a", "ab", "abc", "123456789012"] {
+ assert!(!super::mask(value).contains(value));
+ }
+ assert_eq!(super::mask("sk-test-secret-value-9f03"), "sk-t••••••••9f03");
+ assert_eq!(super::mask("test\ncontrol-key"), "••••••••");
+ }
+}
diff --git a/crates/daemon/src/gateway_ports/credential.rs b/crates/daemon/src/gateway_ports/credential.rs
index 23fb1f80..dae26f8c 100644
--- a/crates/daemon/src/gateway_ports/credential.rs
+++ b/crates/daemon/src/gateway_ports/credential.rs
@@ -54,6 +54,19 @@ where
Err(PortError::Unavailable("exact CredentialResolver required"))
}
+ fn current_credential_refs(
+ &self,
+ request: CredentialLeaseRequest<'_>,
+ ) -> Result<Option<Vec<String>>, PortError> {
+ if request.connector_runtime != ConnectorRuntimeKind::BuiltinNative {
+ return Ok(None);
+ }
+ let target = validate_request(&request)?;
+ self.native
+ .current_native_credential_refs(&native_request(&request, target)?)
+ .map_err(native_error)
+ }
+
async fn lease_exact(
&self,
request: CredentialLeaseRequest<'_>,
@@ -66,36 +79,7 @@ where
if request.authentication == &AuthenticationSemantics::None {
return Err(PortError::Rejected);
}
- let native_request = NativeCredentialLeaseRequestV1 {
- schema_version: NATIVE_CREDENTIAL_LEASE_REQUEST_SCHEMA_V1.into(),
- stable_binding_id: request.stable_binding_id.into(),
- credential_id: request.credential_ref.into(),
- credential_destination_ref: request.credential_destination_ref.into(),
- excluded_key_ids: request
- .excluded_key_ids
- .iter()
- .map(ToString::to_string)
- .collect(),
- connector_runtime: request.connector_runtime,
- connector_id: request.connector_id.into(),
- upstream_protocol: domain_protocol(request.upstream_protocol),
- upstream_model_id: request.upstream_model_id.into(),
- native_transport_model: request.native_transport_model.into(),
- logical_endpoint: request.logical_endpoint.into(),
- operational_target: target,
- operational_target_digest: CanonicalDigest::parse(
- request.operational_target_digest,
- )
- .map_err(|_| PortError::Rejected)?,
- request_path: request.request_path.into(),
- runtime_epoch: request.runtime_epoch,
- target_epoch: request.target_epoch,
- protocol_profile_digest: CanonicalDigest::parse(
- request.protocol_profile_digest,
- )
- .map_err(|_| PortError::Rejected)?,
- authentication: domain_authentication(request.authentication)?,
- };
+ let native_request = native_request(&request, target)?;
let Some(lease) = self
.native
.lease_native_credential(&native_request)
@@ -232,6 +216,54 @@ where
}
}
+fn native_error(error: hiroute_domain::NativeCredentialLeaseErrorV1) -> PortError {
+ match error {
+ hiroute_domain::NativeCredentialLeaseErrorV1::Denied(reason) => {
+ PortError::CredentialDenied(reason)
+ }
+ hiroute_domain::NativeCredentialLeaseErrorV1::Authority(error) => match error.code {
+ hiroute_domain::PortErrorCode::Unavailable => {
+ PortError::Unavailable("NativeCredentialAuthorityV1")
+ }
+ _ => PortError::Rejected,
+ },
+ }
+}
+
+fn native_request(
+ request: &CredentialLeaseRequest<'_>,
+ target: GatewayOperationalTargetV1,
+) -> Result<NativeCredentialLeaseRequestV1, PortError> {
+ let native_request = NativeCredentialLeaseRequestV1 {
+ schema_version: NATIVE_CREDENTIAL_LEASE_REQUEST_SCHEMA_V1.into(),
+ stable_binding_id: request.stable_binding_id.into(),
+ credential_id: request.credential_ref.into(),
+ credential_destination_ref: request.credential_destination_ref.into(),
+ excluded_key_ids: request
+ .excluded_key_ids
+ .iter()
+ .map(ToString::to_string)
+ .collect(),
+ connector_runtime: request.connector_runtime,
+ connector_id: request.connector_id.into(),
+ upstream_protocol: domain_protocol(request.upstream_protocol),
+ upstream_model_id: request.upstream_model_id.into(),
+ native_transport_model: request.native_transport_model.into(),
+ logical_endpoint: request.logical_endpoint.into(),
+ operational_target: target,
+ operational_target_digest: CanonicalDigest::parse(request.operational_target_digest)
+ .map_err(|_| PortError::Rejected)?,
+ request_path: request.request_path.into(),
+ runtime_epoch: request.runtime_epoch,
+ target_epoch: request.target_epoch,
+ protocol_profile_digest: CanonicalDigest::parse(request.protocol_profile_digest)
+ .map_err(|_| PortError::Rejected)?,
+ authentication: domain_authentication(request.authentication)?,
+ };
+ native_request.validate().map_err(|_| PortError::Rejected)?;
+ Ok(native_request)
+}
+
fn validate_request(
request: &CredentialLeaseRequest<'_>,
) -> Result<GatewayOperationalTargetV1, PortError> {
diff --git a/crates/daemon/tests/publication_process.rs b/crates/daemon/tests/publication_process.rs
index c79fb4a7..d70f983e 100644
--- a/crates/daemon/tests/publication_process.rs
+++ b/crates/daemon/tests/publication_process.rs
@@ -60,6 +60,16 @@ fn real_process_native_model_save_publishes_and_reaches_gateway() {
run_script("model_connections_product.py");
}
+#[test]
+fn real_process_current_credential_pool_relays_without_republishing() {
+ run_script("credential_pool_product.py");
+}
+
+#[test]
+fn real_process_filtered_credential_pool_preserves_current_candidate_history() {
+ run_script_case("credential_pool_product.py", Some("filtered-history"));
+}
+
#[test]
fn real_process_route_options_preserve_opaque_ids_and_isolate_unavailable_models() {
run_script("route_options_product.py");
diff --git a/crates/daemon/tests/support/credential_pool_product.py b/crates/daemon/tests/support/credential_pool_product.py
new file mode 100644
index 00000000..07a5edd5
--- /dev/null
+++ b/crates/daemon/tests/support/credential_pool_product.py
@@ -0,0 +1,189 @@
+"""Current managed Key order through production save, exact leases and Gateway relay."""
+import hashlib
+import http.client
+import json
+import sys
+from model_connections_product import (
+ MODEL, NATIVE_TOKEN, NativeUpstream, control, gateway_request,
+ publish_plan_and_agent, save_native_source,
+)
+from publication_product import Product, encoded
+from plan_content_process import read_content
+
+
+def save_source(product, saved, edits, label, disabled=False):
+ snapshot = control(product, 'ListCompute', {})['data']
+ source = next(row for row in snapshot['sources'] if row['source_id'] == saved['source_id'])
+ change = {
+ 'schema': 'hiroute.compute-management-change/v2',
+ 'subject': {'kind': 'saved_source', 'source_id': saved['source_id']},
+ 'expected_revisions': snapshot['revisions'],
+ 'selected_model_refs': [model['model_ref'] for model in source['models']],
+ 'intent': 'save_disabled' if disabled else 'save_ready', 'key_edits': edits,
+ }
+ preview = control(product, 'PreviewComputeSave', {'change': change})['data']
+ applied = control(product, 'ApplyComputeSave', {
+ 'spec': preview['spec'], 'accept_digest': preview['accept_digest'],
+ 'expected_revisions': preview['expected_revisions'], 'idempotency_key': 'pool-' + label,
+ })
+ result = control(product, 'GetComputeSaveResult', {'operation': applied['operation']})['data']
+ assert result['disposition'] == 'saved', result
+
+
+def run(repository):
+ product = Product(repository)
+ upstream = NativeUpstream()
+ product.install_codex_fixture(MODEL, 'medium', upstream.base_url, NATIVE_TOKEN)
+ try:
+ product.start()
+ saved = save_native_source(product, upstream, NATIVE_TOKEN)
+ publish_plan_and_agent(product, saved['binding_id'])
+ frozen_content = read_content(product)
+
+ def source_snapshot():
+ snapshot = control(product, 'ListCompute', {})['data']
+ source = next(row for row in snapshot['sources'] if row['source_id'] == saved['source_id'])
+ return snapshot, source
+
+ def save(edits, label, disabled=False):
+ save_source(product, saved, edits, label, disabled)
+ assert read_content(product) == frozen_content, 'source save rewrote the frozen Plan'
+ return source_snapshot()[1]
+
+ def register(label, token):
+ candidate = {'candidate_ref': 'candidate/pool/' + label, 'candidate_revision': 1}
+ product.secrets.add(token)
+ product.register_protected_frame({
+ 'schema': 'hiroute.protected-input/v1',
+ 'registration_id': hashlib.sha256(label.encode()).hexdigest(),
+ **candidate, 'secret': token,
+ })
+ return candidate
+
+ first = source_snapshot()[1]['keys'][0]['key_id']
+ token_b = 'fixture-rejected-key-b-903b'
+ upstream.rejected_token = token_b
+ candidate_b = register('add-b', token_b)
+ second = 'credential/managed-' + hashlib.sha256(encoded([
+ 'hiroute.compute-management-key/v2', saved['source_id'], candidate_b['candidate_ref'],
+ ])).hexdigest()[:24]
+ after = save([
+ {'action': 'add', 'input_candidate': candidate_b},
+ {'action': 'set_order', 'key_ids': [second, first]},
+ ], 'add-b-before-a')
+ assert [key['key_id'] for key in after['keys']] == [second, first], after
+ def request_keys(expected):
+ with upstream.lock:
+ before = len(upstream.requests)
+ gateway_request(product, allowed=bool(expected))
+ with upstream.lock:
+ observed = upstream.requests[before:]
+ assert [row['authorization'] for row in observed] == [
+ 'Bearer ' + token for token in expected
+ ], observed
+
+ # Run before querying the new masks API, so the old runtime fails on the
+ # actual missing B401 -> A200 relay rather than an unknown query operation.
+ request_keys([token_b, NATIVE_TOKEN])
+ masks = control(product, 'GetComputeKeyMasksV1', {
+ 'source_id': saved['source_id'], 'expected_source_revision': after['revision'],
+ })['data']
+ assert [key['key_id'] for key in masks['keys']] == [second, first], masks
+ assert masks['keys'][0]['masked_key'] == 'fixt••••••••903b', masks
+ assert all(token not in json.dumps(masks) for token in (NATIVE_TOKEN, token_b))
+ control(product, 'GetComputeKeyMasksV1', {
+ 'source_id': saved['source_id'], 'expected_source_revision': after['revision'] - 1,
+ }, expected_error='REVISION_CONFLICT')
+
+ after = save([{'action': 'set_order', 'key_ids': [first, second]}], 'a-before-b')
+ request_keys([NATIVE_TOKEN])
+ # A previous 401 retains its existing cooldown. Rotate B to a healthy
+ # generation before verifying the restored B-first pool.
+ replacement = 'fixture-replacement-key-b-47af'
+ after = save([
+ {'action': 'replace', 'key_id': second, 'expected_generation': 1,
+ 'input_candidate': register('replace-b', replacement)},
+ {'action': 'set_order', 'key_ids': [second, first]},
+ ], 'b-before-a-again')
+ request_keys([replacement])
+ after = save([], 'disable-source', disabled=True)
+ request_keys([])
+ product.stop()
+ product.start()
+ request_keys([])
+ after = save([], 'restore-source')
+ request_keys([replacement])
+ after = save([{'action': 'remove', 'key_id': second, 'expected_generation': 2}], 'remove-b')
+ request_keys([NATIVE_TOKEN])
+ assert [key['key_id'] for key in after['keys']] == [first], after
+ assert read_content(product) == frozen_content
+ print(json.dumps({'scenario': 'current-key-pool-with-frozen-plan', 'state': 'green',
+ 'one_save_order': True, 'relay_401_then_200': True,
+ 'plan_republished': False, 'restored_order_after_restart': True,
+ 'replacement_and_removal': True, 'saved_key_masks': True}), flush=True)
+ finally:
+ product.close()
+ upstream.close()
+
+
+def run_filtered_history(repository):
+ """An unavailable economy source cannot authorize cleanup on the prior primary."""
+ product = Product(repository)
+ economy, primary = NativeUpstream(), NativeUpstream()
+ product.install_codex_fixture(MODEL, 'medium', primary.base_url, NATIVE_TOKEN)
+
+ def message(text):
+ return {'type': 'message', 'role': 'user',
+ 'content': [{'type': 'input_text', 'text': text}]}
+
+ def request_history(items):
+ client = http.client.HTTPConnection('127.0.0.1', product.port, timeout=30)
+ try:
+ client.request('POST', '/v1/responses', body=encoded({
+ 'model': product.model_alias, 'input': items, 'stream': False,
+ }), headers={
+ 'X-HiRoute-Token': product.bearer(product.agent_connection),
+ 'Content-Type': 'application/json', 'session-id': 'filtered-pool-history',
+ })
+ response = client.getresponse()
+ product.outputs.append(response.read())
+ return response.status
+ finally:
+ client.close()
+
+ try:
+ product.start()
+ a = save_native_source(product, economy, 'fixture-history-key-a', variant='history-a')
+ b = save_native_source(product, primary, 'fixture-history-key-b', variant='history-b')
+ publish_plan_and_agent(product, b['binding_id'], native_model_mode='hiroute_only',
+ economy_binding=a['binding_id'])
+ frozen_content = read_content(product)
+ assert request_history([message('complex-route initial work')]) == 200
+ assert not [row for row in economy.requests if row['method'] == 'POST']
+ assert len([row for row in primary.requests if row['method'] == 'POST']) == 1
+ save_source(product, a, [], 'disable-history-a', disabled=True)
+ assert read_content(product) == frozen_content
+ primary.reject_reasoning_history = True
+ history = [{'type': 'reasoning', 'summary': [],
+ 'encrypted_content': 'keep-for-current-b'}, message('rename after compaction')]
+ assert request_history(history) >= 400, 'same candidate unexpectedly cleaned history'
+ assert not [row for row in economy.requests if row['method'] == 'POST']
+ posts = [row for row in primary.requests if row['method'] == 'POST']
+ assert len(posts) == 2, 'same candidate received an unauthorized cleanup retry'
+ assert posts[-1]['body']['input'][0]['encrypted_content'] == 'keep-for-current-b'
+ assert read_content(product) == frozen_content
+ print(json.dumps({'scenario': 'filtered-key-pool-preserves-current-candidate-history',
+ 'state': 'green', 'disabled_source_posts': 0,
+ 'current_candidate_posts': 1, 'unauthorized_cleanup_retry': False,
+ 'history_preserved': True, 'plan_republished': False}), flush=True)
+ finally:
+ product.close()
+ economy.close()
+ primary.close()
+
+
+if __name__ == '__main__':
+ if len(sys.argv) > 2 and sys.argv[2] == 'filtered-history':
+ run_filtered_history(sys.argv[1])
+ else:
+ run(sys.argv[1])
diff --git a/crates/daemon/tests/support/model_connections_product.py b/crates/daemon/tests/support/model_connections_product.py
index 6fd62f50..9089b80b 100644
--- a/crates/daemon/tests/support/model_connections_product.py
+++ b/crates/daemon/tests/support/model_connections_product.py
@@ -25,6 +25,8 @@ V2 = {'major': 2, 'minor': 0}
class NativeUpstream:
def __init__(self):
self.requests = []
+ self.rejected_token = None
+ self.reject_reasoning_history = False
self.lock = threading.Lock()
owner = self
@@ -63,6 +65,16 @@ class NativeUpstream:
self.record(body)
assert self.path == '/v1/responses', self.path
assert body['model'] == MODEL, body
+ if self.headers.get('Authorization') == 'Bearer ' + str(owner.rejected_token):
+ self.send_json(401, {'error': {'message': 'fixture rejected key', 'type': 'invalid_api_key'}})
+ return
+ if owner.reject_reasoning_history and any(
+ isinstance(item, dict) and item.get('encrypted_content')
+ for item in body.get('input', [])
+ ):
+ self.send_json(400, {'error': {'code': 'invalid_encrypted_content',
+ 'message': 'fixture history rejected'}})
+ return
self.send_json(200, {
'id': 'resp_native_product',
'object': 'response',
@@ -414,7 +426,8 @@ def assert_saved_recheck_fences_before_network(product, upstream, saved):
assert len(upstream.requests) == before, upstream.requests
-def publish_plan_and_agent(product, binding_id, native_model_mode='preserve_available'):
+def publish_plan_and_agent(product, binding_id, native_model_mode='preserve_available',
+ *, economy_binding=None):
assert native_model_mode in ('preserve_available', 'hiroute_only')
product.editor = {
'schema': 'hiroute.plan-editor/v2',
@@ -431,6 +444,16 @@ def publish_plan_and_agent(product, binding_id, native_model_mode='preserve_avai
'limits': {'maximum_attempts': 2, 'request_timeout_ms': 30000,
'attempt_timeout_ms': 30000},
}
+ if economy_binding is not None:
+ product.editor['mode'] = 'smart_saving'
+ product.editor['candidates'] = []
+ product.editor['smart'].update({
+ 'economy': [{'binding_id': economy_binding}],
+ 'primary': [{'binding_id': binding_id}],
+ 'reselect_on_user_message': True,
+ 'complex_keywords': ['complex-route'],
+ })
+ product.editor['limits']['maximum_attempts'] = 3
change = {
'schema': 'hiroute.plan-content-change/v2',
'target': {'intent': 'create', 'creation_key': 'native-product-plan'},
@@ -468,6 +491,7 @@ def gateway_request(product, allowed=True, stream=False):
}), headers={
'X-HiRoute-Token': product.bearer(product.agent_connection),
'Content-Type': 'application/json',
+ 'session-id': 'native-product-permission-switches',
})
response = client.getresponse()
body = response.read()
@@ -539,7 +563,9 @@ def assert_live_credential_switches(product, upstream, saved):
gateway_request(product)
-def assert_session_record(product, started_ms):
+def assert_session_record(product, started_ms, denied_binding=None):
+ # Grants survive daemon restarts; the reopened query needs a fresh capability.
+ grant_key = 'native-product-reopened' if denied_binding is not None else 'native-product'
query = {
'schema': 'hiroute.observation.query/v2',
'intent': {'view': 'sessions', 'query': {
@@ -560,7 +586,7 @@ def assert_session_record(product, started_ms):
capability = product.grant('ListSessionsV2', {
'change_digest': 'sha256:' + hashlib.sha256(encoded(query)).hexdigest(),
'expected_revisions': revisions,
- }, 'native-product-sessions')
+ }, grant_key + '-sessions')
deadline = time.monotonic() + 30
while True:
sessions = product.cli('sessions list', query, capability)[1]['data']['sessions']
@@ -579,15 +605,45 @@ def assert_session_record(product, started_ms):
timeline_capability = product.grant('GetSessionTimelineV2', {
'change_digest': 'sha256:' + hashlib.sha256(encoded(timeline)).hexdigest(),
'expected_revisions': revisions,
- }, 'native-product-timeline')
+ }, grant_key + '-timeline')
while True:
requests = product.cli(
'sessions show', timeline, timeline_capability)[1]['data']['requests']
accepted = [request for request in requests
if request['attempted_model_count'] == 1
and request['final_native_model'] == MODEL
- and request['outcome'] == 'accepted']
- if accepted:
+ and request['outcome'] == 'accepted' and request['receipt_id']]
+ denied = [request for request in requests
+ if request['attempted_model_count'] == 0
+ and request['outcome'] == 'failed' and request['receipt_id']]
+ if accepted and (denied_binding is None or len(denied) == 6):
+ receipt = control(product, 'GetRoutingReceipt', {
+ 'id': accepted[0]['receipt_id'], 'content': None,
+ })['data']
+ assert receipt['facts_completeness'] == 'complete', receipt
+ leases = [event['fact'] for event in receipt['ordered_facts']
+ if event['fact']['kind'] == 'credential_lease']
+ assert len(leases) == 1 and leases[0]['outcome'] == 'leased', leases
+ # Reading current membership must not invent another successful lease.
+ if denied_binding is not None:
+ for request in denied:
+ receipt = control(product, 'GetRoutingReceipt', {
+ 'id': request['receipt_id'], 'content': None,
+ })['data']
+ assert receipt['schema'] == 'hiroute.routing-receipt/v1', receipt
+ assert receipt['outcome'] == 'failed', receipt
+ assert receipt['facts_completeness'] == 'complete', receipt
+ assert receipt.get('final_attempt_id') is None, receipt
+ assert all(event.get('attempt_id') is None for event in receipt['ordered_facts']), receipt
+ facts = [event['fact'] for event in receipt['ordered_facts']]
+ leases = [fact for fact in facts if fact['kind'] == 'credential_lease']
+ assert len(leases) == 1, leases
+ assert leases[0]['stable_binding_id'] == denied_binding, leases
+ assert leases[0]['outcome'] == 'source_disabled', leases
+ assert leases[0]['key_id'] is None and leases[0]['credential_generation'] is None, leases
+ finished = [fact for fact in facts if fact['kind'] == 'request_finished']
+ assert len(finished) == 1 and finished[0]['outcome'] == 'failed', finished
+ assert finished[0]['attempts_started'] == finished[0]['attempts_finished'] == 0, finished
return session_id, accepted[0]['final_native_model']
assert time.monotonic() < deadline, requests
time.sleep(.05)
@@ -632,6 +688,7 @@ def run(repository, expected_sha=None):
product.start()
recheck_saved_native_source(product, saved, 3, 'after-restart')
recheck_saved_native_source(product, unknown, 3, 'unknown-after', unknown=True)
+ assert_session_record(product, started_ms, saved['binding_id'])
with upstream.lock:
requests = list(upstream.requests)
assert [request['path'] for request in requests] == [
@@ -653,6 +710,7 @@ def run(repository, expected_sha=None):
'disabled_requests_without_upstream': 6,
'preparation_error_code': 'SOURCE_DISABLED',
'preparation_error_modes': ['nonstream', 'prebody_stream'],
+ 'complete_zero_attempt_denial_receipts_after_reopen': 6,
'credential_resolver_mode': 'saved_bearer',
'session_record': session_id,
'session_model': observed_model,
diff --git a/crates/domain/src/compute/credential_runtime.rs b/crates/domain/src/compute/credential_runtime.rs
index 20ed174a..c99bf0ec 100644
--- a/crates/domain/src/compute/credential_runtime.rs
+++ b/crates/domain/src/compute/credential_runtime.rs
@@ -244,6 +244,17 @@ impl NativeCredentialLeaseV1 {
/// Replaceable Product authority. Local storage, a Vault client, or a remote authority can
/// implement this same port; Gateway adapters never depend on SQLite types.
pub trait NativeCredentialAuthorityV1: Send + Sync {
+ /// Non-secret current order for an already authorized Native candidate. `None` keeps
+ /// legacy exact users unchanged; an empty list means the managed candidate is unavailable.
+ /// This reads no secret and issues no lease. Current permission denials retain their
+ /// closed cause; the frozen exact request supplies target proof.
+ fn current_native_credential_refs(
+ &self,
+ _request: &NativeCredentialLeaseRequestV1,
+ ) -> Result<Option<Vec<String>>, NativeCredentialLeaseErrorV1> {
+ Ok(None)
+ }
+
/// An empty lease means exact exhaustion. Current managed source/Key permission
/// denials retain their closed reason before any secret is decrypted.
fn lease_native_credential(
@@ -263,7 +274,7 @@ pub enum NativeCredentialAccessDeniedV1 {
CredentialDisabled,
}
-/// In-process lease failure, separate from persisted credential and request schemas.
+/// In-process Native permission failure, separate from persisted credential and request schemas.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum NativeCredentialLeaseErrorV1 {
#[error("current managed credential permission was denied: {0:?}")]
diff --git a/crates/domain/src/compute/managed_identity.rs b/crates/domain/src/compute/managed_identity.rs
new file mode 100644
index 00000000..deed0465
--- /dev/null
+++ b/crates/domain/src/compute/managed_identity.rs
@@ -0,0 +1,35 @@
+//! Stable identity shared by the management producer and protected Desktop input preparation.
+
+use crate::{CanonicalDigest, CanonicalDigestError};
+
+/// Preserve the released v2 identity: source ownership and the protected candidate reference,
+/// without its transient revision. Knowing this ID grants no credential authority.
+pub fn managed_key_id(
+ source_id: &str,
+ candidate_ref: &str,
+) -> Result<String, CanonicalDigestError> {
+ let digest = CanonicalDigest::of(&(
+ "hiroute.compute-management-key/v2",
+ source_id,
+ candidate_ref,
+ ))?;
+ Ok(format!(
+ "credential/managed-{}",
+ super::digest_suffix(&digest, 24)
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn released_key_identity_keeps_its_canonical_bytes_and_source_scope() {
+ assert_eq!(
+ super::managed_key_id("source/test", "candidate/test").unwrap(),
+ "credential/managed-7be9f916223c72e005f2f164"
+ );
+ assert_ne!(
+ super::managed_key_id("source/other", "candidate/test").unwrap(),
+ super::managed_key_id("source/test", "candidate/test").unwrap()
+ );
+ }
+}
diff --git a/crates/domain/src/compute/mod.rs b/crates/domain/src/compute/mod.rs
index c26b7c6b..d648a772 100644
--- a/crates/domain/src/compute/mod.rs
+++ b/crates/domain/src/compute/mod.rs
@@ -9,6 +9,7 @@ mod control_projection;
mod credential_runtime;
mod credential_selection;
mod inventory;
+mod managed_identity;
mod management;
mod model_data;
mod model_metadata;
@@ -26,6 +27,7 @@ pub use control_projection::*;
pub use credential_runtime::*;
pub use credential_selection::*;
pub use inventory::*;
+pub use managed_identity::*;
pub use management::*;
pub use model_data::*;
pub use model_metadata::*;
diff --git a/crates/gateway-core/src/core/execution_plan/binding.rs b/crates/gateway-core/src/core/execution_plan/binding.rs
index 55d4d1a5..963d0b0e 100644
--- a/crates/gateway-core/src/core/execution_plan/binding.rs
+++ b/crates/gateway-core/src/core/execution_plan/binding.rs
@@ -55,6 +55,34 @@ impl RequestExecutionBinding {
self.ingress_plan.take();
}
+ /// Bind current credentials to this request's candidate, after Product source/target
+ /// authorization and before execution admission. Shared publication segments stay immutable.
+ pub fn bind_candidate_credentials(
+ &mut self,
+ binding: ResolvedTargetBindingId,
+ credentials: Arc<[CredentialRef]>,
+ ) -> Result<(), PlanError> {
+ if binding.plan_revision() != self.plan_revision
+ || credentials.is_empty()
+ || credentials.len() > 64
+ || credentials
+ .iter()
+ .map(CredentialRef::as_str)
+ .collect::<std::collections::HashSet<_>>()
+ .len()
+ != credentials.len()
+ {
+ return Err(PlanError::InvalidRouteCandidateClosure);
+ }
+ let plan = self
+ .route_attempt_plans
+ .as_mut()
+ .and_then(|plans| plans.get_mut(&binding))
+ .ok_or(PlanError::BindingOutsideRouteClosure(binding))?;
+ Arc::make_mut(plan).credential_refs = credentials;
+ Ok(())
+ }
+
/// Narrow the publication segments to one matched route and atomically
/// acquire its complete RequestPinned candidate/accepted closure.
pub fn bind_route(&mut self, route: &CompiledRoute) -> Result<(), PlanError> {
diff --git a/crates/gateway-core/tests/publication_and_configuration/retention_and_binding.rs b/crates/gateway-core/tests/publication_and_configuration/retention_and_binding.rs
index fdbfc60e..3768e6ab 100644
--- a/crates/gateway-core/tests/publication_and_configuration/retention_and_binding.rs
+++ b/crates/gateway-core/tests/publication_and_configuration/retention_and_binding.rs
@@ -1,5 +1,84 @@
use crate::fixture::*;
+#[test]
+fn current_credentials_are_owned_by_one_request_and_do_not_mutate_publication() {
+ use hiroute_gateway_core::core::execution_plan::CredentialRef;
+ let installer = PublicationInstaller::new();
+ install(&installer, envelope(1, 1));
+ let mut request = installer.bind_request().unwrap();
+ let route = request.ingress_plan().unwrap().routes[0].clone();
+ request.bind_route(&route).unwrap();
+ let original = request.resolve_attempt(route.binding).unwrap();
+ let original_credentials = Arc::clone(&original.plan().credential_refs);
+ let current: Arc<[CredentialRef]> = ["credential/current-b", "credential/current-a"]
+ .into_iter()
+ .map(|id| CredentialRef::new(id).unwrap())
+ .collect::<Vec<_>>()
+ .into();
+ request
+ .bind_candidate_credentials(route.binding, Arc::clone(&current))
+ .unwrap();
+ assert_eq!(
+ request
+ .resolve_attempt(route.binding)
+ .unwrap()
+ .plan()
+ .credential_refs,
+ current
+ );
+ assert_eq!(original.plan().credential_refs, original_credentials);
+ let mut later = installer.bind_request().unwrap();
+ later.bind_route(&route).unwrap();
+ assert_eq!(
+ later
+ .resolve_attempt(route.binding)
+ .unwrap()
+ .plan()
+ .credential_refs,
+ original_credentials
+ );
+ assert!(
+ request
+ .bind_candidate_credentials(route.binding, Arc::from([]))
+ .is_err()
+ );
+ assert!(
+ request
+ .bind_candidate_credentials(
+ route.binding,
+ Arc::from([current[0].clone(), current[0].clone()])
+ )
+ .is_err()
+ );
+ assert!(
+ request
+ .bind_candidate_credentials(ResolvedTargetBindingId::new(PlanRevision(2), 7), current)
+ .is_err()
+ );
+ let maximum: Arc<[CredentialRef]> = (0..64)
+ .map(|index| CredentialRef::new(format!("credential/current-{index}")).unwrap())
+ .collect::<Vec<_>>()
+ .into();
+ request
+ .bind_candidate_credentials(route.binding, Arc::clone(&maximum))
+ .unwrap();
+ let mut too_many = maximum.to_vec();
+ too_many.push(CredentialRef::new("credential/extra").unwrap());
+ assert!(
+ request
+ .bind_candidate_credentials(route.binding, too_many.into())
+ .is_err()
+ );
+ assert_eq!(
+ request
+ .resolve_attempt(route.binding)
+ .unwrap()
+ .plan()
+ .credential_refs,
+ maximum
+ );
+}
+
#[test]
fn request_binding_does_not_keep_publication_root_alive() {
let installer = PublicationInstaller::new();
diff --git a/crates/gateway/README.md b/crates/gateway/README.md
index 9e0bc50d..10fcf486 100644
--- a/crates/gateway/README.md
+++ b/crates/gateway/README.md
@@ -99,6 +99,13 @@ uses the caller's `ExecutionScope`, keeps the existing error categories, and
does not read credentials or runtime-state stores. E2E configuration remains
captured at construction, not reloaded on each resolution.
+[core_runtime/credentials.rs](src/core_runtime/credentials.rs) binds current managed Native
+Key IDs/order once at request admission. The control authority verifies the saved source,
+model and target; exact attempt leases still enforce current generation and revocation.
+Only the request-owned attempt view changes, leaving shared publication content immutable.
+[publication/lease_target.rs](src/publication/lease_target.rs) derives the same selected
+protocol target for admission and materialization; neither caller may substitute a destination.
+
[planner.rs](src/planner.rs) validates the selected category and chooses eligible
groups/candidates under the frozen policy. Availability relay may move execution
from regular to primary within that category. History and assessment retain the
@@ -260,3 +267,23 @@ publishes that usage before request termination, so its receipt does not depend
on canonical capture scheduling. Nonstream capture still records delivered
content but leaves usage to provider completion; converted streaming capture
continues publishing accepted usage events. Missing usage remains unknown.
+
+### Current-pool admission failures
+
+Current-pool admission checks the frozen model and target before reporting a managed
+source denial. It keeps the request's members and order fixed, excludes denied sources
+and records a request-level permission fact without a leased Key or generation. A
+successful membership read does not create a lease fact.
+
+If admission excludes every candidate, HTTP 502 uses `hiroute.gateway.error/v1`:
+
+| Current-pool evidence | `code` | `phase` |
+| --- | --- | --- |
+| Every source is disabled | `SOURCE_DISABLED` | `credential_lease` |
+| Every managed pool is empty/unavailable | `CREDENTIAL_UNAVAILABLE` | `credential_lease` |
+| Mixed causes | `CANDIDATE_PREPARATION_FAILED` | `candidate_preparation` |
+
+Admission exclusions also join the existing request-local preparation summary when
+another candidate remains. Mixed permanent failures do not become a pure cooling
+response, and an actual upstream attempt retains its existing response. These errors
+contain no credentials or provider text and have no `Retry-After`.
diff --git a/crates/gateway/src/composition/ports.rs b/crates/gateway/src/composition/ports.rs
index 3c7ffcc2..17ab6610 100644
--- a/crates/gateway/src/composition/ports.rs
+++ b/crates/gateway/src/composition/ports.rs
@@ -344,6 +344,14 @@ impl RuntimePublicationFeed for GatewayPublicationInstaller {
pub trait CredentialResolver: Send + Sync {
fn acquire(&self, credential_ref: &str) -> Result<CredentialLease, PortError>;
+ /// Request admission only: current non-secret membership for this exact Native binding.
+ fn current_credential_refs(
+ &self,
+ _request: CredentialLeaseRequest<'_>,
+ ) -> Result<Option<Vec<String>>, PortError> {
+ Ok(None)
+ }
+
async fn lease_exact(
&self,
_request: CredentialLeaseRequest<'_>,
diff --git a/crates/gateway/src/core_runtime.rs b/crates/gateway/src/core_runtime.rs
index e515e581..e3c8934a 100644
--- a/crates/gateway/src/core_runtime.rs
+++ b/crates/gateway/src/core_runtime.rs
@@ -46,6 +46,8 @@ use crate::content_ref::{
};
use crate::context_hold::{ContextHoldStore, ContextRequest, HoldCompletion, begin_context};
use crate::replay::{ReplayError, ReplayManager, ReplayReader, ReplayStore};
+#[path = "core_runtime/credentials.rs"]
+mod credentials;
use crate::runtime::{
ProductionProvider, ProductionReplaySeed, ProductionReplaySeedEnvelope, ProductionRouteContext,
};
@@ -393,7 +395,7 @@ impl ProductionGatewayRuntime {
protocol: IngressProtocol,
declared_content_length: Option<usize>,
ingress_prefix: Vec<ChargedBytes>,
- authorized: Box<AuthorizedRequestPlan>,
+ mut authorized: Box<AuthorizedRequestPlan>,
budget: StreamBudget,
) -> Pin<Box<dyn Future<Output = Result<SessionReuse, TransportError>> + Send + 'a>> {
Box::pin(async move {
@@ -992,6 +994,8 @@ impl ProductionGatewayRuntime {
let mut hold_candidates =
Vec::with_capacity(planner_output.ledger.ordered_candidates.len());
let mut agent_turn_candidates = std::collections::BTreeMap::new();
+ let mut admission_preparation_failure: Option<crate::runtime::PreparationFailure> =
+ None;
for frozen in &planner_output.ledger.ordered_candidates {
let facts = fact_by_id
.get(frozen.candidate_id.as_str())
@@ -1058,7 +1062,7 @@ impl ProductionGatewayRuntime {
"sealed candidate profile mismatch".into(),
));
}
- let profile = serde_json::to_vec(&SealedCandidateExecutionV1 {
+ let execution = SealedCandidateExecutionV1 {
schema_version: SEALED_CANDIDATE_EXECUTION_SCHEMA_V1.into(),
stable_target_key: candidate.stable_target_key,
credential_destination_ref: candidate.credential_destination_ref,
@@ -1071,8 +1075,50 @@ impl ProductionGatewayRuntime {
protocol_set_digest: candidate.protocol_profile_digest,
profile_digest: facts.profile_digest.clone(),
protocol_profile: facts.protocol_profile.clone(),
+ };
+ let pool = with_active_request(request_observation.clone(), async {
+ credentials::bind_current(&self.ports, &mut authorized, binding, &execution)
})
- .map_err(|_| TransportError::Io("planner profile serialization failed".into()))?;
+ .await;
+ let excluded = match pool {
+ Ok(false) => Some(crate::runtime::PreparationFailure::CredentialUnavailable),
+ Err(crate::server::composition::PortError::CredentialDenied(reason)) => {
+ Some(match reason {
+ hiroute_domain::NativeCredentialAccessDeniedV1::SourceDisabled => {
+ crate::runtime::PreparationFailure::SourceDisabled
+ }
+ hiroute_domain::NativeCredentialAccessDeniedV1::CredentialDisabled => {
+ crate::runtime::PreparationFailure::CredentialDisabled
+ }
+ })
+ }
+ Ok(true) => None,
+ Err(_) => {
+ return write_typed_error_phase(
+ session,
+ StatusCode::BAD_GATEWAY,
+ "CREDENTIAL_AUTHORITY_FAILED",
+ "credential",
+ )
+ .await;
+ }
+ };
+ if let Some(cause) = excluded {
+ admission_preparation_failure = Some(
+ admission_preparation_failure
+ .map_or(cause, |previous| previous.merge(cause)),
+ );
+ continue;
+ }
+ let attempt = authorized
+ .core_binding()
+ .resolve_attempt(binding)
+ .map_err(|_| {
+ TransportError::Io("current candidate binding unavailable".into())
+ })?;
+ let profile = serde_json::to_vec(&execution).map_err(|_| {
+ TransportError::Io("planner profile serialization failed".into())
+ })?;
frozen_candidates.push(DecisionCandidateAuthority {
binding,
stable_target: ObservationLabel::new(frozen.stable_binding_id.clone())
@@ -1120,6 +1166,13 @@ impl ProductionGatewayRuntime {
);
}
drop(fact_by_id);
+ if frozen_candidates.is_empty() {
+ let (code, phase) = admission_preparation_failure
+ .unwrap_or(crate::runtime::PreparationFailure::Other)
+ .code_phase();
+ return write_typed_error_phase(session, StatusCode::BAD_GATEWAY, code, phase)
+ .await;
+ }
let switch_fallback = planner_input
.previous_success_candidate_id
.as_deref()
@@ -1135,7 +1188,22 @@ impl ProductionGatewayRuntime {
.get(1)
.is_some_and(|second| second.candidate_id == *id)
})
- .and_then(|_| frozen_candidates.get(1).map(|candidate| candidate.binding));
+ .and_then(|id| {
+ frozen_candidates
+ .iter()
+ .find(|candidate| {
+ candidate
+ .candidate_id
+ .as_ref()
+ .is_some_and(|candidate_id| candidate_id.as_str() == id)
+ })
+ .map(|candidate| candidate.binding)
+ })
+ .filter(|binding| {
+ frozen_candidates
+ .first()
+ .is_some_and(|first| first.binding != *binding)
+ });
let canonical_request = Box::new(planner_input.request);
let reused_cleanup = hold_ticket.as_ref().and_then(|ticket| {
let prefix = ticket.cleaned_prefix_len?;
@@ -1150,14 +1218,15 @@ impl ProductionGatewayRuntime {
.filter(|ticket| !ticket.message_history_continues)
.and(planner_input.previous_success_candidate_id.as_ref())
.and_then(|previous| {
- let first = planner_output.ledger.ordered_candidates.first()?;
- if first.candidate_id == *previous {
+ let first = frozen_candidates.first()?;
+ let first_id = first.candidate_id.as_ref()?.as_str();
+ if first_id == previous {
return None;
}
let profile = &planner_input
.candidates
.iter()
- .find(|candidate| candidate.candidate_id == first.candidate_id)?
+ .find(|candidate| candidate.candidate_id == first_id)?
.protocol_profile;
let normal =
adapters::project_candidate_request_template(&canonical_request, profile)
@@ -1168,10 +1237,8 @@ impl ProductionGatewayRuntime {
Some(canonical_request.messages.len()),
)
.ok()?;
- (normal.bytes != cleaned.bytes).then_some((
- frozen_candidates.first()?.binding,
- canonical_request.messages.len(),
- ))
+ (normal.bytes != cleaned.bytes)
+ .then_some((first.binding, canonical_request.messages.len()))
});
let reasoning_cleanup = Arc::new(crate::runtime::ReasoningCleanup::new(
cleanup_eligible,
@@ -1212,6 +1279,7 @@ impl ProductionGatewayRuntime {
context_holds: Arc::clone(&self.context_holds),
switch_fallback,
reasoning_cleanup,
+ admission_preparation_failure,
hold_completion: hold_ticket.map(|ticket| HoldCompletion {
ticket: *ticket,
candidates: hold_candidates.into(),
diff --git a/crates/gateway/src/core_runtime/credentials.rs b/crates/gateway/src/core_runtime/credentials.rs
new file mode 100644
index 00000000..b006e946
--- /dev/null
+++ b/crates/gateway/src/core_runtime/credentials.rs
@@ -0,0 +1,82 @@
+//! Request admission binds one current managed Native list; attempt leases remain exact.
+
+use hiroute_gateway_core::core::execution_plan::{CredentialRef, ResolvedTargetBindingId};
+
+use crate::ports::CredentialLeaseRequest;
+use crate::server::composition::{PortError, ProductionPorts};
+use crate::server::publication::{SealedCandidateExecutionV1, lease_target};
+use crate::server::request_plan::AuthorizedRequestPlan;
+
+pub(super) fn bind_current(
+ ports: &ProductionPorts,
+ authorized: &mut AuthorizedRequestPlan,
+ binding: ResolvedTargetBindingId,
+ execution: &SealedCandidateExecutionV1,
+) -> Result<bool, PortError> {
+ if execution.connector_runtime != hiroute_domain::ConnectorRuntimeKind::BuiltinNative {
+ return Ok(true);
+ }
+ let profile = &execution.protocol_profile;
+ let authentication = profile
+ .connector
+ .authentication
+ .exact()
+ .ok_or(PortError::Rejected)?;
+ if authentication == &super::profiles::AuthenticationSemantics::None {
+ return Ok(true);
+ }
+ let attempt = authorized
+ .core_binding()
+ .resolve_attempt(binding)
+ .map_err(|_| PortError::Rejected)?;
+ let original = attempt
+ .plan()
+ .credential_refs
+ .first()
+ .ok_or(PortError::Rejected)?;
+ let target = lease_target::for_request(execution, profile).map_err(|_| PortError::Rejected)?;
+ let digest = hiroute_domain::CanonicalDigest::of(&target).map_err(|_| PortError::Rejected)?;
+ let destination = profile
+ .native_target
+ .as_ref()
+ .map_or(execution.credential_destination_ref.as_str(), |target| {
+ target.credential_destination_ref.as_str()
+ });
+ let current = ports
+ .credentials
+ .current_credential_refs(CredentialLeaseRequest {
+ stable_binding_id: &execution.stable_target_key,
+ credential_ref: original.as_str(),
+ credential_destination_ref: destination,
+ excluded_key_ids: &[],
+ connector_runtime: execution.connector_runtime,
+ connector_id: &profile.connector.connector_id,
+ upstream_protocol: profile.capability.upstream_protocol,
+ upstream_model_id: &execution.upstream_model_id,
+ native_transport_model: &execution.native_transport_model,
+ logical_endpoint: target.uri(),
+ operational_target: target.uri(),
+ operational_target_digest: digest.as_str(),
+ runtime_epoch: target.runtime_epoch(),
+ target_epoch: target.target_epoch(),
+ protocol_profile_digest: &execution.profile_digest,
+ request_path: &profile.connector.request_path,
+ authentication,
+ })?;
+ let Some(current) = current else {
+ return Ok(true);
+ };
+ if current.is_empty() {
+ return Ok(false);
+ }
+ let credentials = current
+ .into_iter()
+ .map(CredentialRef::new)
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|_| PortError::Rejected)?;
+ authorized
+ .core_binding_mut()
+ .bind_candidate_credentials(binding, credentials.into())
+ .map_err(|_| PortError::Rejected)?;
+ Ok(true)
+}
diff --git a/crates/gateway/src/observation/ports.rs b/crates/gateway/src/observation/ports.rs
index 1d296506..7c53b499 100644
--- a/crates/gateway/src/observation/ports.rs
+++ b/crates/gateway/src/observation/ports.rs
@@ -32,6 +32,41 @@ impl CredentialResolver for ObservedCredentialResolver {
self.inner.acquire(credential_ref)
}
+ fn current_credential_refs(
+ &self,
+ request: CredentialLeaseRequest<'_>,
+ ) -> Result<Option<Vec<String>>, PortError> {
+ let stable_binding_id = request.stable_binding_id;
+ let credential_ref = request.credential_ref;
+ let excluded_key_count = request.excluded_key_ids.len();
+ let result = self.inner.current_credential_refs(request);
+ let outcome = match &result {
+ Ok(Some(refs)) if refs.is_empty() => Some("exhausted"),
+ Err(PortError::CredentialDenied(reason)) => Some(match reason {
+ hiroute_domain::NativeCredentialAccessDeniedV1::SourceDisabled => "source_disabled",
+ hiroute_domain::NativeCredentialAccessDeniedV1::CredentialDisabled => {
+ "credential_disabled"
+ }
+ }),
+ Err(_) => Some("authority_error"),
+ _ => None,
+ };
+ // A successful membership read is not a lease. Only a rejected permission
+ // check contributes a zero-Key/generation request-level preparation fact.
+ if let Some(outcome) = outcome
+ && let Some(observation) = active_request()
+ {
+ observation.credential_lease(
+ stable_binding_id,
+ credential_ref,
+ excluded_key_count,
+ None,
+ outcome,
+ );
+ }
+ result
+ }
+
async fn lease_exact(
&self,
request: CredentialLeaseRequest<'_>,
diff --git a/crates/gateway/src/runtime/driver/materialization/lease_target.rs b/crates/gateway/src/publication/lease_target.rs
similarity index 66%
rename from crates/gateway/src/runtime/driver/materialization/lease_target.rs
rename to crates/gateway/src/publication/lease_target.rs
index 4539f856..54cce70a 100644
--- a/crates/gateway/src/runtime/driver/materialization/lease_target.rs
+++ b/crates/gateway/src/publication/lease_target.rs
@@ -1,6 +1,6 @@
use std::sync::Arc;
-pub(super) fn for_request(
+pub(crate) fn for_request(
execution: &crate::server::publication::SealedCandidateExecutionV1,
profile: &crate::server::core_runtime::profiles::CandidateProtocolProfile,
) -> Result<hiroute_domain::GatewayOperationalTargetV1, Arc<str>> {
@@ -8,19 +8,18 @@ pub(super) fn for_request(
if let Some(target) = &profile.native_target {
let domain_profile: hiroute_domain::GatewayCandidateProtocolProfileV1 =
serde_json::from_value(
- serde_json::to_value(profile)
- .map_err(|_| Arc::from(super::super::MATERIALIZATION_PROTOCOL_FAILED))?,
+ serde_json::to_value(profile).map_err(|_| Arc::from("protocol_failed"))?,
)
- .map_err(|_| Arc::from(super::super::MATERIALIZATION_PROTOCOL_FAILED))?;
+ .map_err(|_| Arc::from("protocol_failed"))?;
if !target.validate_for(&domain_profile) {
- return Err(Arc::from(super::super::MATERIALIZATION_PROTOCOL_FAILED));
+ return Err(Arc::from("protocol_failed"));
}
return Ok(target.operational_target.clone());
}
execution
.operational_target
.for_protocol_path(&profile.connector.request_path)
- .ok_or_else(|| Arc::from(super::super::MATERIALIZATION_PROTOCOL_FAILED))
+ .ok_or_else(|| Arc::from("protocol_failed"))
} else {
Ok(execution.operational_target.clone())
}
diff --git a/crates/gateway/src/publication/mod.rs b/crates/gateway/src/publication/mod.rs
index 060d7c45..0ef2871f 100644
--- a/crates/gateway/src/publication/mod.rs
+++ b/crates/gateway/src/publication/mod.rs
@@ -3,6 +3,7 @@
mod catalog;
mod compiler;
mod installer;
+pub(crate) mod lease_target;
mod run;
mod schema;
mod trust;
diff --git a/crates/gateway/src/runtime/driver.rs b/crates/gateway/src/runtime/driver.rs
index 5a69e036..e275ebfa 100644
--- a/crates/gateway/src/runtime/driver.rs
+++ b/crates/gateway/src/runtime/driver.rs
@@ -44,6 +44,7 @@ pub(crate) mod response_diagnostics;
mod selection;
pub(crate) use materialization::TargetResolver;
+pub(crate) use selection::PreparationFailure;
pub use selection::{ProductionDecisionSession, ProductionSelection};
const MATERIALIZATION_BINDING_UNAVAILABLE: &str = "binding_unavailable";
@@ -88,6 +89,7 @@ pub struct ProductionRouteContext {
pub(crate) switch_fallback: Option<ResolvedTargetBindingId>,
pub(crate) hold_completion: Option<HoldCompletion>,
pub(crate) reasoning_cleanup: Arc<ReasoningCleanup>,
+ pub(crate) admission_preparation_failure: Option<PreparationFailure>,
}
/// One request's frozen cleanup opportunity, plus a previously successful
diff --git a/crates/gateway/src/runtime/driver/materialization.rs b/crates/gateway/src/runtime/driver/materialization.rs
index 4fa65951..a036583b 100644
--- a/crates/gateway/src/runtime/driver/materialization.rs
+++ b/crates/gateway/src/runtime/driver/materialization.rs
@@ -35,8 +35,7 @@ use crate::server::core_runtime::profiles::{
};
use super::response::{connector_error_profile, failure_facts};
-#[path = "materialization/lease_target.rs"]
-mod lease_target;
+use crate::server::publication::lease_target;
use super::{
MATERIALIZATION_AUTHORITY_FAILED, MATERIALIZATION_BINDING_COOLING_PREFIX,
diff --git a/crates/gateway/src/runtime/driver/selection.rs b/crates/gateway/src/runtime/driver/selection.rs
index f84f034a..b3dd3277 100644
--- a/crates/gateway/src/runtime/driver/selection.rs
+++ b/crates/gateway/src/runtime/driver/selection.rs
@@ -23,7 +23,7 @@ use crate::context_hold::{ContextHoldStore, HoldCompletion};
use super::ProductionRouteContext;
mod preparation;
-use preparation::PreparationFailure;
+pub(crate) use preparation::PreparationFailure;
#[derive(Clone, Default)]
pub struct ProductionSelection;
@@ -365,9 +365,9 @@ impl SelectionPublicationPort<ProductionRouteContext> for ProductionSelection {
temporary_block_seen: false,
probe_busy_seen: false,
earliest_retry_at: None,
- non_temporary_block_seen: false,
+ non_temporary_block_seen: route_context.admission_preparation_failure.is_some(),
upstream_attempted: false,
- preparation_failure: None,
+ preparation_failure: route_context.admission_preparation_failure,
})
}
}
diff --git a/crates/gateway/src/runtime/driver/selection/preparation.rs b/crates/gateway/src/runtime/driver/selection/preparation.rs
index d97cd4de..bd2a0643 100644
--- a/crates/gateway/src/runtime/driver/selection/preparation.rs
+++ b/crates/gateway/src/runtime/driver/selection/preparation.rs
@@ -7,7 +7,7 @@ use http::{HeaderMap, HeaderValue, StatusCode};
/// Request-local summary of the closed preparation facts. Different causes cannot
/// be projected as if every candidate was rejected for one source or Key permission.
#[derive(Clone, Copy, Eq, PartialEq)]
-pub(super) enum PreparationFailure {
+pub(crate) enum PreparationFailure {
SourceDisabled,
CredentialDisabled,
CredentialUnavailable,
@@ -24,17 +24,21 @@ impl PreparationFailure {
}
}
- pub(super) fn merge(self, next: Self) -> Self {
+ pub(crate) fn merge(self, next: Self) -> Self {
if self == next { self } else { Self::Other }
}
- pub(super) fn local_reply(self) -> LocalReply {
- let (code, phase) = match self {
+ pub(crate) fn code_phase(self) -> (&'static str, &'static str) {
+ match self {
Self::SourceDisabled => ("SOURCE_DISABLED", "credential_lease"),
Self::CredentialDisabled => ("CREDENTIAL_DISABLED", "credential_lease"),
Self::CredentialUnavailable => ("CREDENTIAL_UNAVAILABLE", "credential_lease"),
Self::Other => ("CANDIDATE_PREPARATION_FAILED", "candidate_preparation"),
- };
+ }
+ }
+
+ pub(super) fn local_reply(self) -> LocalReply {
+ let (code, phase) = self.code_phase();
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
LocalReply {
diff --git a/crates/gateway/src/runtime/driver/selection/tests.rs b/crates/gateway/src/runtime/driver/selection/tests.rs
index ffae44f3..a79851a9 100644
--- a/crates/gateway/src/runtime/driver/selection/tests.rs
+++ b/crates/gateway/src/runtime/driver/selection/tests.rs
@@ -95,6 +95,67 @@ fn materialization_failure(
}
}
+#[test]
+fn admitted_pool_denial_combines_with_later_preparation_but_preserves_real_attempts() {
+ for (class, expected_code) in [
+ ("source_disabled", "SOURCE_DISABLED"),
+ ("credential_exhausted", "CANDIDATE_PREPARATION_FAILED"),
+ ("runtime_state_cooling_down", "CANDIDATE_PREPARATION_FAILED"),
+ ] {
+ for formal_attempt in [false, true] {
+ let now = Instant::now();
+ let candidates: Arc<[DecisionCandidateAuthority]> =
+ vec![candidate(2, &["key-b"])].into();
+ let request = DecisionSessionRequest {
+ request_id: RequestId(1),
+ route_binding: candidates[0].binding,
+ candidate_bindings: vec![candidates[0].binding].into(),
+ route_context: ProductionRouteContext {
+ ingress: crate::server::request_plan::IngressProtocol::Responses,
+ context_holds: Arc::new(ContextHoldStore::default()),
+ switch_fallback: None,
+ hold_completion: None,
+ reasoning_cleanup: Arc::new(super::super::super::ReasoningCleanup::new(
+ None, None,
+ )),
+ admission_preparation_failure: Some(PreparationFailure::SourceDisabled),
+ },
+ overall_deadline: now + Duration::from_secs(10),
+ max_attempts: 3,
+ };
+ let mut session = ProductionSelection
+ .begin_authorized_session(request, candidates)
+ .unwrap();
+ let realtime = RealtimeRoutingFacts::default();
+ let mut selected = session
+ .select_next(selection_request(now, 1, 3, &realtime))
+ .unwrap()
+ .unwrap();
+ if formal_attempt {
+ selected.attempt_id = AttemptId(1);
+ }
+ session
+ .decide_failure(&selected, &materialization_failure(now, class, None))
+ .unwrap();
+ let reply = session.exhaustion_local_reply(now).unwrap();
+ if formal_attempt {
+ assert!(
+ reply.is_none(),
+ "an earlier admission denial cannot rewrite an upstream reply"
+ );
+ } else {
+ let reply = reply.unwrap();
+ assert_eq!(reply.status, StatusCode::BAD_GATEWAY);
+ assert!(!reply.headers.contains_key(RETRY_AFTER));
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&reply.body).unwrap()["code"],
+ expected_code
+ );
+ }
+ }
+ }
+}
+
#[test]
fn uniform_provisional_denials_retain_the_closed_code_without_retry_or_attempts() {
for (class, code) in [
diff --git a/crates/local-storage/src/control/compute/management.rs b/crates/local-storage/src/control/compute/management.rs
index ef206d95..00398b4a 100644
--- a/crates/local-storage/src/control/compute/management.rs
+++ b/crates/local-storage/src/control/compute/management.rs
@@ -14,6 +14,7 @@ use serde_json::Value;
mod compensation;
mod references;
+mod runtime_pool;
pub(in crate::control) use compensation::reconcile as reconcile_compensation;
diff --git a/crates/local-storage/src/control/compute/management/runtime_pool.rs b/crates/local-storage/src/control/compute/management/runtime_pool.rs
new file mode 100644
index 00000000..d9db5063
--- /dev/null
+++ b/crates/local-storage/src/control/compute/management/runtime_pool.rs
@@ -0,0 +1,117 @@
+//! Current managed Native membership. This never reads or decrypts Secret material.
+
+use hiroute_domain::{
+ ComputeManagementRepositoryPort, MaterializationState, NativeCredentialAccessDeniedV1,
+ NativeCredentialLeaseErrorV1, NativeCredentialLeaseRequestV1, PortError, PortErrorCode,
+ WorkspaceId,
+};
+
+impl crate::LocalStorageSet {
+ pub fn current_native_credential_refs(
+ &self,
+ request: &NativeCredentialLeaseRequestV1,
+ ) -> Result<Option<Vec<String>>, NativeCredentialLeaseErrorV1> {
+ request.validate().map_err(|_| rejected())?;
+ // One transaction binds source state, models, members and ordinal together.
+ let snapshot = self
+ .control()
+ .compute_management_snapshot(&WorkspaceId::default())?;
+ let mut owners = snapshot.sources.iter().filter(|source| {
+ source
+ .models
+ .iter()
+ .any(|model| model.binding_id == request.stable_binding_id)
+ });
+ let Some(source) = owners.next() else {
+ // Namespace classification only fails closed; it never grants access.
+ return Ok((request.stable_binding_id.starts_with("binding/managed-")
+ || request.credential_id.starts_with("credential/managed-"))
+ .then(Vec::new));
+ };
+ if owners.next().is_some() || !source.provenance.is_native() {
+ return Err(rejected().into());
+ }
+ let model = source
+ .models
+ .iter()
+ .find(|model| model.binding_id == request.stable_binding_id)
+ .ok_or_else(rejected)?;
+ if model.upstream_model_id != request.upstream_model_id {
+ return Err(rejected().into());
+ }
+ let target_matches = std::iter::once((&source.target, &source.authentication))
+ .chain(
+ source
+ .additional_native_endpoints
+ .iter()
+ .map(|endpoint| (&endpoint.target, &endpoint.authentication)),
+ )
+ .any(|(target, authentication)| {
+ *authentication == request.authentication
+ && target
+ .credential_destination()
+ .is_ok_and(|destination| destination == request.credential_destination_ref)
+ && request
+ .logical_endpoint
+ .strip_suffix(&request.request_path)
+ .is_some_and(|base| {
+ let host = if target.authority.contains(':')
+ && !target.authority.starts_with('[')
+ {
+ format!("[{}]", target.authority)
+ } else {
+ target.authority.clone()
+ };
+ base.eq_ignore_ascii_case(&format!(
+ "{}://{}:{}",
+ target.scheme, host, target.port
+ )) || ((target.scheme.eq_ignore_ascii_case("https")
+ && target.port == 443
+ || target.scheme.eq_ignore_ascii_case("http") && target.port == 80)
+ && base
+ .eq_ignore_ascii_case(&format!("{}://{}", target.scheme, host)))
+ })
+ });
+ if !target_matches {
+ return Err(rejected().into());
+ }
+ if source.state == MaterializationState::Disabled {
+ return Err(NativeCredentialLeaseErrorV1::Denied(
+ NativeCredentialAccessDeniedV1::SourceDisabled,
+ ));
+ }
+ if source.state != MaterializationState::Ready {
+ return Ok(Some(Vec::new()));
+ }
+ let destinations = source.native_destinations().map_err(|_| rejected())?;
+ let mut credentials: Vec<_> = source
+ .credentials
+ .iter()
+ .filter(|key| key.enabled)
+ .collect();
+ credentials.sort_by_key(|key| key.ordinal);
+ for key in &credentials {
+ let reference = &key.credential;
+ if reference.owner_scope() != format!("source/{}", source.source_id)
+ || reference.subject() != "hirouted"
+ || reference.purpose() != "provider-auth"
+ || reference.allowed_destinations() != &destinations
+ {
+ return Err(rejected().into());
+ }
+ }
+ Ok(Some(
+ credentials
+ .into_iter()
+ .map(|key| key.credential.credential_id().to_owned())
+ .collect(),
+ ))
+ }
+}
+
+fn rejected() -> PortError {
+ PortError::new(
+ PortErrorCode::PermissionDenied,
+ "compute.management.pool.binding",
+ )
+}
diff --git a/crates/local-storage/src/control/compute/management/tests/runtime_leases.rs b/crates/local-storage/src/control/compute/management/tests/runtime_leases.rs
index 6d3099be..37c806e6 100644
--- a/crates/local-storage/src/control/compute/management/tests/runtime_leases.rs
+++ b/crates/local-storage/src/control/compute/management/tests/runtime_leases.rs
@@ -247,3 +247,217 @@ fn frozen_native_requests_obey_current_source_and_key_switches_after_restart() {
assert_eq!(lease.credential_id(), request.credential_id);
}
}
+
+#[test]
+fn current_pool_uses_saved_order_without_changing_frozen_request_or_lease_identity() {
+ let root = tempdir().unwrap();
+ let registry = TrustedComputeCandidateRegistry::new();
+ let primary = candidate("candidate/pool-primary", "slot/primary");
+ let secondary = candidate("candidate/pool-secondary", "slot/secondary");
+ let replacement = candidate("candidate/pool-replacement", "slot/replacement");
+ for facts in [&primary, &secondary, &replacement] {
+ registry.register_compute_candidate(facts.clone()).unwrap();
+ }
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let source = save(
+ &stores,
+ &registry,
+ ComputeManagementSubjectV2::Candidate {
+ candidate: primary.candidate,
+ },
+ ComputeManagementIntentV2::SaveReady,
+ vec![],
+ "pool-create",
+ );
+ let request = frozen_request(&source, 0, 0);
+ let first = source.credentials[0].key_id.clone();
+ let subject = ComputeManagementSubjectV2::SavedSource {
+ source_id: source.source_id.clone(),
+ };
+ let second =
+ hiroute_domain::managed_key_id(&source.source_id, &secondary.candidate.candidate_ref)
+ .unwrap();
+ save(
+ &stores,
+ &registry,
+ subject.clone(),
+ ComputeManagementIntentV2::SaveReady,
+ vec![
+ ComputeKeyEditV2::Add {
+ input_candidate: secondary.candidate,
+ },
+ ComputeKeyEditV2::SetOrder {
+ key_ids: vec![second.clone(), first.clone()],
+ },
+ ],
+ "pool-add-and-order",
+ );
+ let bound_members = stores
+ .current_native_credential_refs(&request)
+ .unwrap()
+ .unwrap();
+ assert_eq!(bound_members, [second.clone(), first.clone()]);
+ assert_eq!(request.credential_id, first);
+ assert_eq!(
+ stores
+ .lease_native_credential_exact(&request)
+ .unwrap()
+ .unwrap()
+ .credential_id(),
+ first
+ );
+
+ save(
+ &stores,
+ &registry,
+ subject.clone(),
+ ComputeManagementIntentV2::SaveReady,
+ vec![
+ ComputeKeyEditV2::Replace {
+ key_id: second.clone(),
+ expected_generation: 1,
+ input_candidate: replacement.candidate,
+ },
+ ComputeKeyEditV2::SetOrder {
+ key_ids: vec![first.clone(), second.clone()],
+ },
+ ],
+ "pool-replace-and-order",
+ );
+ assert_eq!(
+ stores
+ .current_native_credential_refs(&request)
+ .unwrap()
+ .unwrap(),
+ [first.clone(), second.clone()]
+ );
+ assert_eq!(
+ bound_members,
+ [second.clone(), first.clone()],
+ "an admitted request's owned list stays fixed"
+ );
+ let mut bound_second = request.clone();
+ bound_second.credential_id = second.clone();
+ let lease = stores
+ .lease_native_credential_exact(&bound_second)
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ lease.generation(),
+ 2,
+ "a later exact lease sees the current generation of the same key"
+ );
+ assert_eq!(lease.credential_id(), second);
+
+ save(
+ &stores,
+ &registry,
+ subject.clone(),
+ ComputeManagementIntentV2::SaveReady,
+ vec![ComputeKeyEditV2::SetEnabled {
+ key_id: second.clone(),
+ expected_generation: 2,
+ enabled: false,
+ }],
+ "pool-disable-second",
+ );
+ assert_eq!(
+ stores
+ .current_native_credential_refs(&request)
+ .unwrap()
+ .unwrap(),
+ std::slice::from_ref(&first)
+ );
+ assert_eq!(
+ stores
+ .lease_native_credential_exact(&bound_second)
+ .err()
+ .expect("a disabled key denies an exact lease"),
+ NativeCredentialLeaseErrorV1::Denied(NativeCredentialAccessDeniedV1::CredentialDisabled)
+ );
+ save(
+ &stores,
+ &registry,
+ subject.clone(),
+ ComputeManagementIntentV2::SaveDisabled,
+ vec![],
+ "pool-disable-source",
+ );
+ assert_eq!(
+ stores.current_native_credential_refs(&request),
+ Err(NativeCredentialLeaseErrorV1::Denied(
+ NativeCredentialAccessDeniedV1::SourceDisabled
+ ))
+ );
+ drop(stores);
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ assert_eq!(
+ stores.current_native_credential_refs(&request),
+ Err(NativeCredentialLeaseErrorV1::Denied(
+ NativeCredentialAccessDeniedV1::SourceDisabled
+ ))
+ );
+ save(
+ &stores,
+ &registry,
+ subject,
+ ComputeManagementIntentV2::SaveReady,
+ vec![],
+ "pool-restore-source",
+ );
+ assert_eq!(
+ stores
+ .current_native_credential_refs(&request)
+ .unwrap()
+ .unwrap(),
+ [first]
+ );
+}
+
+#[test]
+fn current_pool_rejects_frozen_requests_for_other_models_targets_or_authentication() {
+ let root = tempdir().unwrap();
+ let registry = TrustedComputeCandidateRegistry::new();
+ let primary = candidate("candidate/pool-target", "slot/primary");
+ registry
+ .register_compute_candidate(primary.clone())
+ .unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let source = save(
+ &stores,
+ &registry,
+ ComputeManagementSubjectV2::Candidate {
+ candidate: primary.candidate,
+ },
+ ComputeManagementIntentV2::SaveReady,
+ vec![],
+ "pool-target-create",
+ );
+ let request = frozen_request(&source, 0, 0);
+ let mut other_model = request.clone();
+ other_model.upstream_model_id = "other-model".into();
+ other_model.native_transport_model = "other-model".into();
+ let mut other_destination = request.clone();
+ other_destination.credential_destination_ref = "compute-target/other".into();
+ let mut other_endpoint = request.clone();
+ other_endpoint.logical_endpoint = "https://evil.example.test/v1/responses".into();
+ other_endpoint.operational_target = GatewayOperationalTargetV1::UserConfiguredNative {
+ uri: other_endpoint.logical_endpoint.clone(),
+ };
+ other_endpoint.operational_target_digest =
+ CanonicalDigest::of(&other_endpoint.operational_target).unwrap();
+ let mut other_auth = request.clone();
+ other_auth.authentication = GatewayAuthenticationSemanticsV1::Bearer;
+ for changed in [other_model, other_destination, other_endpoint, other_auth] {
+ assert!(changed.validate().is_ok());
+ assert!(stores.current_native_credential_refs(&changed).is_err());
+ }
+ let mut deleted_source = request;
+ deleted_source.stable_binding_id = "binding/managed-deleted".into();
+ assert_eq!(
+ stores
+ .current_native_credential_refs(&deleted_source)
+ .unwrap(),
+ Some(vec![])
+ );
+}
diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.md
index e4388a31..55d50623 100644
--- a/docs/code-map/architecture.md
+++ b/docs/code-map/architecture.md
@@ -43,6 +43,7 @@ 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 |
| Rename a connection, append models or remove saved configuration | [Shared lifecycle planner](../../crates/application/src/compute_management/mutations/lifecycle.rs), [transactional reference guards](../../crates/local-storage/src/control/compute/management/references.rs), [Desktop lifecycle dialog](../../apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx) | Templates do not own credentials. Explicit append preserves saved members; enabled/disabled routes and retained recovery versions block removal. Removing the last model requires explicit connection deletion; owned secrets follow the same recoverable operation. |
+| Save Key order or use current Keys with an older plan | [Single-save edits](../../apps/desktop/src/features/models/model-draft.ts), [request admission](../../crates/gateway/src/core_runtime/credentials.rs), [current pool authority](../../crates/local-storage/src/control/compute/management/runtime_pool.rs), [safe Key masks](../../crates/daemon/src/control/runtime/model_connections/key_masks.rs) | A request owns its admitted Key IDs and order; later exact leases enforce current source/Key eligibility and generation. Admission retains closed permission denials in the existing request summary. Shared Plan content stays frozen. Masks are a separate authenticated query; saved plaintext never reaches Desktop. |
| 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) | Device scan explains native credential-refresh dependence and opens the existing independent sign-in. 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. |
diff --git a/scripts/test-build-release.py b/scripts/test-build-release.py
index 4df7e0a8..262aa19f 100644
--- a/scripts/test-build-release.py
+++ b/scripts/test-build-release.py
@@ -35,7 +35,7 @@ class CandidateTests(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
- self.root = Path(temporary.name)
+ self.root = Path(temporary.name).resolve()
self.source = self.root / "cpa-source"
self.source.mkdir()
self.addCleanup(patch.stopall)
diff --git a/scripts/test-validation-schedule.py b/scripts/test-validation-schedule.py
index e4f94119..c2cb87a4 100644
--- a/scripts/test-validation-schedule.py
+++ b/scripts/test-validation-schedule.py
@@ -45,13 +45,15 @@ sys.exit(101 if bad else 0)
class Schedule(unittest.TestCase):
- def test_current_gateway_runtime_consumers_require_product_preparation(self):
- tests = Path(__file__).resolve().parent.parent / 'tools/e2e-harness/tests'
- consumers = {source.stem for source in tests.glob('*.rs')
- if 'mod runtime_support;' in source.read_text()}
- self.assertTrue(consumers, 'Gateway runtime consumer inventory is empty')
+ def test_gateway_runtime_consumers_require_product_preparation(self):
+ tests = Path(__file__).resolve().parents[1] / 'tools/e2e-harness/tests'
+ consumers = {
+ source.stem for source in tests.glob('*.rs')
+ if 'mod runtime_support;' in source.read_text()
+ }
+ self.assertIn('p0_gateway_native_sessions', consumers)
self.assertEqual(consumers - scheduler.PRODUCT_TARGETS, set(),
- 'Gateway runtime targets must use prepared product binaries')
+ 'Gateway runtime targets must wait for prepared product binaries')
def test_exec_audit_rejects_runtime_cargo_without_storing_arguments(self):
trace = ('123 execve("/tmp/bin/test", [...], 0x1) = 0\n'