refactor(privacy): remove combined workspace action

Use independent workspace privacy steps and widen the processing method column.

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-11-25 22:43:44 +08:00
co-authored by Codex
parent c843a4d380
commit 9d3d7ef223
13 changed files with 53 additions and 129 deletions
@@ -49,8 +49,6 @@ pub enum PrivacyAction {
RenameKey,
RemoveField,
AnonymizeProject,
/// 已保存的组合动作继续执行,编辑器将其展开为独立步骤
AnonymizeWorkspace,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -87,8 +87,6 @@ pub enum PrivacyAction {
RenameKey,
RemoveField,
AnonymizeProject,
/// 已保存的组合动作继续执行,编辑器将其展开为独立步骤
AnonymizeWorkspace,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
@@ -16,12 +16,10 @@ pub(super) struct CompiledStep {
impl CompiledStep {
pub(super) fn compile(rule: &PrivacyStep) -> Result<Self, &'static str> {
if matches!(
rule.action,
PrivacyAction::AnonymizeProject | PrivacyAction::AnonymizeWorkspace
) && (rule.scope != PrivacyScope::TurnMetadata
|| rule.selector != "$.workspaces"
|| rule.pattern.is_some())
if rule.action == PrivacyAction::AnonymizeProject
&& (rule.scope != PrivacyScope::TurnMetadata
|| rule.selector != "$.workspaces"
|| rule.pattern.is_some())
{
return Err("工作区匿名化仅支持 turn_metadata 的 $.workspaces,且不使用匹配表达式");
}
@@ -104,9 +102,6 @@ impl CompiledStep {
PrivacyAction::AnonymizeProject => {
*count += super::workspace::anonymize_project(value, budget)?;
}
PrivacyAction::AnonymizeWorkspace => {
*count += super::workspace::anonymize(value, budget)?;
}
PrivacyAction::RemoveField => {
if let Some(regex) = &self.regex {
let text = value.as_str().ok_or("条件删除只能匹配字符串值")?;
@@ -1,4 +1,4 @@
//! 工作区路径的账号会话化名、Git 元数据裁剪与预览会话识别
//! 工作区项目名的账号会话化名与预览会话识别
use gateway_core::account::ProviderAccount;
use reqwest::header::HeaderMap;
@@ -19,39 +19,6 @@ pub(super) fn account_session_scope(session: &str, account: &ProviderAccount) ->
hex::encode(hash.finalize())
}
pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<usize, &'static str> {
let count = anonymize_project(value, budget)?;
let workspaces = value.as_object_mut().ok_or("工作区映射必须是对象")?;
let mut renamed = Map::new();
// 保留已保存组合动作的用户名替换与 Git 裁剪,独立项目动作不包含这些副作用
for (path, mut metadata) in std::mem::take(workspaces) {
let object = metadata.as_object_mut().ok_or("工作区信息必须是对象")?;
object.remove("associated_remote_urls");
object.remove("latest_git_commit_hash");
let split = path.rfind(['/', '\\']).ok_or("工作区路径缺少工程目录")?;
let mut alias = String::new();
let mut username = false;
for part in path[..=split].split_inclusive(['/', '\\']) {
let component = part.trim_end_matches(['/', '\\']);
if username && !component.is_empty() {
alias.push_str("user");
alias.push_str(&part[component.len()..]);
username = false;
} else {
alias.push_str(part);
username = component.eq_ignore_ascii_case("users")
|| component.eq_ignore_ascii_case("home");
}
}
alias.push_str(&path[split + 1..]);
if renamed.insert(alias, metadata).is_some() {
return Err("工作区匿名化产生重名");
}
}
*workspaces = renamed;
Ok(count)
}
pub(super) fn anonymize_project(
value: &mut Value,
budget: &mut Budget<'_>,
@@ -1,7 +1,7 @@
//! 隐私规则在真实 HTTP、WebSocket 和发送前拒绝边界的合同
use super::*;
use crate::transport::privacy::{policy, rule};
use crate::transport::privacy::{policy, rule, workspace_rule};
use gateway_core::settings::privacy::{CodexPrivacyPolicy, PrivacyAction, PrivacyScope};
fn privacy_context(policy: &CodexPrivacyPolicy, fallback: bool) -> AttemptContext {
@@ -96,11 +96,7 @@ fn workspace_operation(session: &str, owner: &str) -> Operation {
}
fn workspace_policy() -> CodexPrivacyPolicy {
policy(vec![rule(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeWorkspace,
)])
policy(vec![workspace_rule("user")])
}
fn assert_workspace_alias(header: &str, body: &Value) -> String {
@@ -31,6 +31,33 @@ fn step(scope: PrivacyScope, selector: &str, action: PrivacyAction) -> PrivacySt
}
}
pub(crate) fn workspace_rule(username: &str) -> PrivacyRule {
let mut configured = rule(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeProject,
);
let mut rename = step(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::RenameKey,
);
rename.pattern = Some(r"(?i)^((?:[a-z]:)?[/\\](?:home|users)[/\\])[^/\\]+([/\\])".into());
rename.replacement = format!("${{1}}{username}${{2}}");
configured.steps.push(rename);
for selector in [
"$.workspaces.*.associated_remote_urls",
"$.workspaces.*.latest_git_commit_hash",
] {
configured.steps.push(step(
PrivacyScope::TurnMetadata,
selector,
PrivacyAction::RemoveField,
));
}
configured
}
pub(crate) fn policy(rules: Vec<PrivacyRule>) -> CodexPrivacyPolicy {
CodexPrivacyPolicy {
enabled: true,
@@ -2,41 +2,6 @@
use super::*;
fn anonymous_rule() -> PrivacyRule {
rule(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeWorkspace,
)
}
fn composed_rule(username: &str) -> PrivacyRule {
let mut configured = rule(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeProject,
);
let mut rename = step(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::RenameKey,
);
rename.pattern = Some(r"(?i)^((?:[a-z]:)?[/\\](?:home|users)[/\\])[^/\\]+([/\\])".into());
rename.replacement = format!("${{1}}{username}${{2}}");
configured.steps.push(rename);
for selector in [
"$.workspaces.*.associated_remote_urls",
"$.workspaces.*.latest_git_commit_hash",
] {
configured.steps.push(step(
PrivacyScope::TurnMetadata,
selector,
PrivacyAction::RemoveField,
));
}
configured
}
#[test]
fn project_anonymization_preserves_usernames_and_git_information() {
for path in [
@@ -70,15 +35,17 @@ fn project_anonymization_preserves_usernames_and_git_information() {
}
#[test]
fn independent_steps_preserve_combined_behavior_and_allow_customization() {
fn workspace_steps_allow_customizing_username_and_retaining_remotes() {
for path in [
"/home/alex/projects/private",
"/Users/alex/private",
r"C:\Users\alex\private",
] {
let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}}});
let mut customized = workspace_rule("blg");
customized.steps.remove(2);
let mut request = sample(
vec![anonymous_rule()],
vec![customized],
json!({"client_metadata":{"x-codex-turn-metadata":metadata.to_string()}}),
);
request.turn_metadata = Some(metadata.to_string());
@@ -88,16 +55,6 @@ fn independent_steps_preserve_combined_behavior_and_allow_customization() {
request
.headers
.insert("x-codex-turn-metadata".into(), vec![metadata.to_string()]);
let combined = preview(request.clone()).unwrap();
request.policy.rules = vec![composed_rule("user")];
let composed = preview(request.clone()).unwrap();
assert_eq!(composed.body, combined.body);
assert_eq!(composed.headers, combined.headers);
assert_eq!(composed.turn_metadata, combined.turn_metadata);
let mut customized = composed_rule("blg");
customized.steps.remove(2);
request.policy.rules = vec![customized];
let output = preview(request).unwrap();
let value: Value = serde_json::from_str(output.turn_metadata.as_deref().unwrap()).unwrap();
let (alias, workspace) = value["workspaces"]
@@ -138,7 +95,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}},"request_kind":"turn"});
let original_input = json!([{"role":"user","content":format!("<cwd>{path}</cwd>")}]);
let mut request = sample(
vec![anonymous_rule()],
vec![workspace_rule("user")],
json!({
"input":original_input,
"turnMetadata":metadata,
@@ -207,7 +164,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
{
assert_eq!(serde_json::from_str::<Value>(raw).unwrap(), expected);
}
assert_eq!(result.outcomes[0].matches, 7);
assert_eq!(result.outcomes[0].matches, 28);
assert_eq!(preview(request.clone()).unwrap().body, result.body);
request
.headers
@@ -223,7 +180,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
fn long_workspace_names_produce_valid_directory_components() {
let path = format!("/workspace/{}", "工程".repeat(40));
let mut request = sample(
vec![anonymous_rule()],
vec![workspace_rule("user")],
json!({"turn_metadata":{"workspaces":{path:{}}}}),
);
request
@@ -243,7 +200,7 @@ fn long_workspace_names_produce_valid_directory_components() {
#[test]
fn multiple_workspaces_remain_stable_as_the_workspace_set_grows() {
let compiled = compile(&policy(vec![anonymous_rule()])).unwrap();
let compiled = compile(&policy(vec![workspace_rule("user")])).unwrap();
let transform = |scope, count| {
let mut entries = serde_json::Map::new();
for n in 0..count {
@@ -281,7 +238,7 @@ fn multiple_workspaces_remain_stable_as_the_workspace_set_grows() {
fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
let original = json!({"turn_metadata":{"workspaces":{"/Users/alex/projects/private":{"latest_git_commit_hash":"abc"}}}});
for (scope, invalid_header) in [(None, false), (Some("session"), true)] {
let mut config = policy(vec![anonymous_rule()]);
let mut config = policy(vec![workspace_rule("user")]);
config.on_error = PrivacyFailureMode::SkipRule;
let mut body = original.clone();
let mut headers = reqwest::header::HeaderMap::new();
@@ -308,7 +265,7 @@ fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
);
}
assert!(
preview(sample(vec![anonymous_rule()], json!({})))
preview(sample(vec![workspace_rule("user")], json!({})))
.unwrap()
.outcomes[0]
.matches
-2
View File
@@ -2459,8 +2459,6 @@ UA、平台参数及自动 Git 上下文版本由 [OpenAI 上游客户端身份]
换账号、新会话或更换工作区重新派生化名,切回原账号和原会话恢复对应化名,不保存路径映射表。正常令牌续期与代理出口变化不重置化名。
默认组合移除 Git 远端与提交信息,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
已保存的 `anonymize_workspace` 组合动作继续替换用户名、生成项目化名并删除 Git 信息。管理端编辑时将其展开为四个独立步骤,应用草稿并保存后生效;展开后的步骤仍计入总上限
工作区必须是绝对路径,映射值必须是对象。缺少稳定会话身份、路径无效或化名冲突时按策略失败模式处理,不随机补造会话。
预览从样本请求头或正文识别会话,可在样本的 `headers` 中填写 `"session-id": ["example-session"]`;预览只使用样本身份,实际出站另外按 Client Key 和选定账号隔离
+1 -1
View File
@@ -2,7 +2,7 @@ import type { RequestOptions } from '../../request'
import request from '../../request'
export type PrivacyScope = 'turn_metadata' | 'desktop_git_context' | 'environment_text' | 'request_body' | 'request_header'
export type PrivacyAction = 'regex_replace' | 'set_value' | 'rename_key' | 'remove_field' | 'anonymize_project' | 'anonymize_workspace'
export type PrivacyAction = 'regex_replace' | 'set_value' | 'rename_key' | 'remove_field' | 'anonymize_project'
export type JsonValue = unknown
export interface PrivacyRule {
@@ -6,7 +6,7 @@ import { Play } from '@lucide/vue'
import { cloneDeep } from 'es-toolkit'
import { computed, ref, shallowRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { exampleRequest, expandWorkspaceSteps, newRule, newStep } from './presets'
import { exampleRequest, newRule, newStep } from './presets'
import StepFields from './StepFields.vue'
import StepList from './StepList.vue'
import { usePrivacyPreview } from './usePrivacyPreview'
@@ -46,7 +46,6 @@ watch(open, (value) => {
if (value) {
selectedIndex.value = 0
draft.value = cloneDeep(props.rule ?? newRule())
draft.value.steps = expandWorkspaceSteps(draft.value.steps)
fixedValues.value = draft.value.steps.map(step => JSON.stringify(step.value))
sample.value = JSON.stringify(exampleRequest(), null, 2)
}
@@ -109,7 +109,7 @@ const columns = computed(() => (defineTableColumns<PrivacyRule>([
key: 'action',
label: t('settings.privacy.rules.processingMethod'),
kind: 'meta',
size: 'md',
size: '2xl',
},
{
key: 'actions',
@@ -145,7 +145,7 @@ const columns = computed(() => (defineTableColumns<PrivacyRule>([
{{ [...new Set(row.steps.map(step => scopes.find(item => item.value === step.scope)?.label))].join('、') }}
</template>
<template #action="{ row }">
{{ [...new Set(row.steps.map(step => step.action === 'anonymize_workspace' ? t('settings.privacy.presets.anonymizeWorkspace') : actions.find(item => item.value === step.action)?.label))].join('、') }}
{{ [...new Set(row.steps.map(step => actions.find(item => item.value === step.action)?.label))].join('、') }}
</template>
<template #actions="{ row }">
<div class="flex items-center justify-end gap-1">
@@ -182,24 +182,13 @@ export function createPreset(key: string): PrivacyRule {
return {
...newRule(),
name: preset.name,
steps: createSteps(preset.steps),
steps: preset.steps.map(step => ({
...newStep(),
...cloneDeep(step),
})),
}
}
function createSteps(steps: Partial<PrivacyStep>[]): PrivacyStep[] {
return steps.map(step => ({
...newStep(),
...cloneDeep(step),
}))
}
export function expandWorkspaceSteps(steps: PrivacyStep[]): PrivacyStep[] {
// 只展开编辑草稿,已保存的组合动作由后端保持原行为
return steps.flatMap(step => step.action === 'anonymize_workspace'
? createSteps(workspaceSteps)
: [step])
}
// 样本使用虚构仓库、路径与标识,字段形状对应官方 Core 和 Desktop Git 上下文
const metadata = {
workspaces: {
+1 -1
View File
@@ -3,7 +3,7 @@
## 优化改进
- 统一各页面的平台选择器,分组和密钥按平台展示专属配置,通用项保持独立
- 工作区匿名化拆分为项目名、用户名、Git 远端及提交信息四个可编辑步骤,已有组合规则继续生效
- 工作区匿名化拆分为项目名、用户名、Git 远端及提交信息四个可编辑步骤
- 更新 macOS 客户端身份预设,CLI 预设默认使用 TUI 入口和 Apple Terminal,保留已保存的入口与终端配置
## 问题修复