diff --git a/CHANGELOG.md b/CHANGELOG.md index 0971c9a9..3c99636a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -387,6 +387,42 @@ Changes are recorded here before a release version is assigned. ### Added +- Version 0.95.0 lets a workspace give its `gh` profile a GitHub review host's + token (ADR-0147). `omgcode workspace gh-token-bind + `, `gh-token-unbind`, and `gh-token-list`, or the **GitHub token** + select beside each assigned profile on a workspace's page of the `settings` + window (a native confirmation binds; unbinding needs none), bind a profile + to a review host of kind `github`. A model command whose program is that + profile's `gh` then gets the token as `GH_TOKEN` and network access. The + workspace's `task_network` preference must permit it, and the call runs + without an approval only when the command state and `task_network` are both + `allow`; the approval shows **Network** on and the host's name, and the + digest includes the host. Commands are limited to `pr`, `issue`, `repo`, + `api`, `run`, `workflow`, `release`, `search`, `label`, and `status` + (without `repo clone` and `pr checkout`, and with the subcommand directly + after the command); a URL, `--hostname`, a `ghe.com` + or `github.localhost` name, a repository qualified by any host other than + `github.com` (a `--repo` value such as `intranet/owner/repo` too), the + Git-starting flags `--clone`, `--remote`, and `--checkout`, `--web` or + `-w`, a jq filter (`--jq` or `-q`), which could read the token from the + environment, and editor mode (`--editor`, or `-e` + where it means that) are refused before an + approval (`gh_arguments_refused`), as is a call while `task_network` is off + (`github_network_disabled`). The run gets an empty, read-only `gh` + configuration folder, the profile cannot override the `GH_*` variables or + proxies, a profile whose `PATH` holds `git` is refused, the token's bytes + are replaced in the output (with any trailing prefix when it was + truncated), the run journal records the host's name and identifier only, + and the run stops when the binding ends or names another host, even one + added again under the same name; the runner also refuses a run whose bound + host identifier changed after the turn admitted it. Each binding keeps room + for its unbind in the settings journal. A file argument such as + `--body-file` can name any file the run can read; Linux Landlock grants no + `/proc`, so `/proc/self/environ` stays out of reach, which a new + confinement probe checks directly and through a link. GitHub Enterprise + hosts are refused. The security rules record this as the one credential allowed in a + task environment. **No `gh` run with a token was made against GitHub**, and + `gh` has passed no confined acceptance run. - Version 0.93.0 implements increment 4b of the pull request review contract, the GitLab, Azure DevOps, and Bitbucket fetch adapters (ADR-0145). Every host kind now has an adapter. **No adapter has run against a real host**: each was diff --git a/Cargo.lock b/Cargo.lock index 736cc175..4e5180b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3666,7 +3666,7 @@ dependencies = [ [[package]] name = "omgcode-app" -version = "0.93.0" +version = "0.95.0" dependencies = [ "base64 0.23.1", "directories", @@ -3685,7 +3685,7 @@ dependencies = [ [[package]] name = "omgcode-cli" -version = "0.93.0" +version = "0.95.0" dependencies = [ "clap", "gix", @@ -3699,7 +3699,7 @@ dependencies = [ [[package]] name = "omgcode-core" -version = "0.93.0" +version = "0.95.0" dependencies = [ "base64 0.23.1", "bytes", @@ -3723,7 +3723,7 @@ dependencies = [ [[package]] name = "omgcode-desktop" -version = "0.93.0" +version = "0.95.0" dependencies = [ "omgcode-app", "omgcode-platform", @@ -3737,7 +3737,7 @@ dependencies = [ [[package]] name = "omgcode-platform" -version = "0.93.0" +version = "0.95.0" dependencies = [ "libc", "rustix", diff --git a/Cargo.toml b/Cargo.toml index 883e51c8..23c8b006 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/omgcode-core", "crates/omgcode-cli", "crates/omgcode-platform", "crates/omgcode-app", "crates/omgcode-desktop"] [workspace.package] -version = "0.93.0" +version = "0.95.0" edition = "2024" rust-version = "1.99.1" license = "Apache-2.0" diff --git a/crates/omgcode-app/src/desktop.rs b/crates/omgcode-app/src/desktop.rs index 5321deca..22d78453 100644 --- a/crates/omgcode-app/src/desktop.rs +++ b/crates/omgcode-app/src/desktop.rs @@ -152,8 +152,8 @@ pub use self::settings_discovery::{ }; pub use self::settings_execution::{ ContainerAccessChoice, ContainerGrantRequest, ContainerRevokeRequest, EnvironmentEntry, - GitWorkerGrantRequest, PackageProfileAddRequest, ProfileAssignmentRequest, - ProfileRemoveRequest, ToolchainProfileAddRequest, + GhTokenBindRequest, GhTokenUnbindRequest, GitWorkerGrantRequest, PackageProfileAddRequest, + ProfileAssignmentRequest, ProfileRemoveRequest, ToolchainProfileAddRequest, }; pub use self::settings_folders::{FolderAddRequest, FolderRemoveRequest, FolderSetRequest}; pub use self::settings_skills::{SkillChoice, SkillRemoveRequest, SkillStateRequest}; @@ -184,19 +184,19 @@ pub use self::wire::{ ConnectionOrigin, ConnectionRemoveRequest, ConnectionSelectRequest, ConnectionSourceView, ConnectionStatus, ConnectionStatusRequest, ConnectionView, ContainerGrantView, ContextBreakdown, ContextMeterDto, ContextPartDto, ContextPartId, Decision, EntryKind, - GitIdentityRequest, GitIdentityView, GitIndexState, GitPathView, GitStatusState, GitStatusView, - GitWorkerState, GitWorkerView, GitWorktreeState, GrantedFolderView, MessageRoleDto, - ModelChoice, NewConnectionKind, PackageProfileView, PermissionFlags, PermissionsChangeRequest, - PreferencesSource, ProviderProfileView, ReviewHostAddRequest, ReviewHostRemoveRequest, - ReviewHostTokenRequest, ReviewHostView, ReviewInfoView, ReviewMark, ReviewOperation, - ReviewOperationError, ReviewOperationRequest, ReviewOperationState, ReviewProgressView, - ReviewRemoveResult, ReviewSkillList, ReviewSkillView, ReviewStartRequest, SearchHit, - SearchRequest, SearchResult, SearchRoleDto, SessionContext, SessionCreateRequest, - SessionEffortSelectRequest, SessionModelSelectRequest, SessionRequest, SessionSetup, - SessionSetupChoice, SessionSetupProvider, SessionSkills, SessionStatus, SessionSummary, - SessionTree, SettingsOverview, SettingsRevisionRequest, SettingsScope, SkillOverrideView, - SkillSettingView, SnippetPart, ToolOutcomeDto, ToolchainProfileView, ToolsMode, - TranscriptEntry, TranscriptPage, TranscriptRequest, TreeRequest, TreeSort, TreeView, + GhTokenBindingView, GitIdentityRequest, GitIdentityView, GitIndexState, GitPathView, + GitStatusState, GitStatusView, GitWorkerState, GitWorkerView, GitWorktreeState, + GrantedFolderView, MessageRoleDto, ModelChoice, NewConnectionKind, PackageProfileView, + PermissionFlags, PermissionsChangeRequest, PreferencesSource, ProviderProfileView, + ReviewHostAddRequest, ReviewHostRemoveRequest, ReviewHostTokenRequest, ReviewHostView, + ReviewInfoView, ReviewMark, ReviewOperation, ReviewOperationError, ReviewOperationRequest, + ReviewOperationState, ReviewProgressView, ReviewRemoveResult, ReviewSkillList, ReviewSkillView, + ReviewStartRequest, SearchHit, SearchRequest, SearchResult, SearchRoleDto, SessionContext, + SessionCreateRequest, SessionEffortSelectRequest, SessionModelSelectRequest, SessionRequest, + SessionSetup, SessionSetupChoice, SessionSetupProvider, SessionSkills, SessionStatus, + SessionSummary, SessionTree, SettingsOverview, SettingsRevisionRequest, SettingsScope, + SkillOverrideView, SkillSettingView, SnippetPart, ToolOutcomeDto, ToolchainProfileView, + ToolsMode, TranscriptEntry, TranscriptPage, TranscriptRequest, TreeRequest, TreeSort, TreeView, WorkspaceChoice, WorkspaceGroup, WorkspaceInstructionsRequest, WorkspaceList, WorkspaceRevisionRequest, WorkspaceSettingsView, }; diff --git a/crates/omgcode-app/src/desktop/settings.rs b/crates/omgcode-app/src/desktop/settings.rs index 4451a1a1..18fc8615 100644 --- a/crates/omgcode-app/src/desktop/settings.rs +++ b/crates/omgcode-app/src/desktop/settings.rs @@ -46,8 +46,8 @@ use super::state::folder_of_directory; use super::wire::{ BranchState, BranchView, ClaudeCodeGrantView, ClaudeCodeView, ConnectionChoice, ConnectionOrigin, ConnectionSourceView, ConnectionStatus, ConnectionStatusRequest, - ConnectionView, ContainerGrantView, GitIdentityView, GitIndexState, GitPathView, - GitStatusState, GitStatusView, GitWorkerState, GitWorkerView, GitWorktreeState, + ConnectionView, ContainerGrantView, GhTokenBindingView, GitIdentityView, GitIndexState, + GitPathView, GitStatusState, GitStatusView, GitWorkerState, GitWorkerView, GitWorktreeState, GrantedFolderView, PackageProfileView, ProviderProfileView, ReviewHostView, SessionContext, SessionRequest, SessionSkills, SettingsOverview, SkillOverrideView, SkillSettingView, ToolchainProfileView, WorkspaceSettingsView, @@ -95,6 +95,31 @@ fn git_worker_view(store: &ControlStore, workspace: WorkspaceId, inner: &Inner) } } +/// The workspace's GitHub token bindings by profile and host name +/// (ADR-0147). A binding whose profile or host is no longer recorded is +/// left out; core ends such a binding itself. +fn gh_token_binding_views( + store: &ControlStore, + workspace_id: omgcode_core::policy::WorkspaceId, +) -> Vec { + store + .gh_token_bindings() + .iter() + .filter(|binding| binding.workspace_id() == workspace_id) + .filter_map(|binding| { + let profile = store + .profiles() + .iter() + .find(|status| status.profile().id() == binding.profile_id())?; + let host = store.gh_token_host(workspace_id, binding.profile_id())?; + Some(GhTokenBindingView { + profile: profile.profile().name().to_owned(), + host: display_safe_line(host.name()), + }) + }) + .collect() +} + /// The recorded review hosts for display (ADR-0143). Whether a token is /// readable is decided by core's checked load, which reads it and drops it at /// once: nothing of it is kept, shown, or sent to the window. A native store @@ -187,6 +212,7 @@ pub(super) fn overview_of(inner: &Inner, store: ControlStore) -> SettingsOvervie .map(|status| status.profile().name().to_owned()) }) .collect(), + gh_token_bindings: gh_token_binding_views(&store, workspace.id()), package_cache_root: store.package_cache_root_display(workspace.id()), instructions: workspace_instructions_view( &inner.data_root, diff --git a/crates/omgcode-app/src/desktop/settings_changes.rs b/crates/omgcode-app/src/desktop/settings_changes.rs index 1314d5ea..87eca266 100644 --- a/crates/omgcode-app/src/desktop/settings_changes.rs +++ b/crates/omgcode-app/src/desktop/settings_changes.rs @@ -1382,7 +1382,7 @@ impl DesktopService { /// As [`apply_checked`](Self::apply_checked) for a change that fails only /// with a core settings error. - fn apply( + pub(super) fn apply( &self, change: impl FnOnce(&mut ControlStore) -> Result<(), ControlError>, ) -> Result { diff --git a/crates/omgcode-app/src/desktop/settings_execution.rs b/crates/omgcode-app/src/desktop/settings_execution.rs index 600d811c..1f2c3353 100644 --- a/crates/omgcode-app/src/desktop/settings_execution.rs +++ b/crates/omgcode-app/src/desktop/settings_execution.rs @@ -130,6 +130,33 @@ pub struct ProfileAssignmentRequest { pub name: String, } +/// Arguments of `settings_bind_gh_token` (ADR-0147). Names only: the token +/// stays in protected storage and is read by the runner. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GhTokenBindRequest { + /// The settings revision the window last read. + pub revision: u64, + /// A registered workspace. + pub workspace_id: Uuid, + /// The recorded name of a toolchain profile assigned to the workspace. + pub profile: String, + /// The recorded name of a review host of kind `github`. + pub host: String, +} + +/// Arguments of `settings_unbind_gh_token` (ADR-0147). +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GhTokenUnbindRequest { + /// The settings revision the window last read. + pub revision: u64, + /// A registered workspace. + pub workspace_id: Uuid, + /// The recorded name of the toolchain profile whose binding ends. + pub profile: String, +} + /// Arguments of `settings_add_package_profile`. #[derive(Clone, Debug, Deserialize, Eq, PartialEq)] #[serde(deny_unknown_fields)] @@ -483,6 +510,19 @@ fn unassign_confirmation(workspace_folder: &str, name: &str, revoked: &[String]) } } +/// The native confirmation for giving a workspace profile's `gh` a review +/// host's token (ADR-0147). Fixed text apart from the three names. +fn bind_gh_token_confirmation(workspace_folder: &str, profile: &str, host: &str) -> Confirmation { + Confirmation { + title: "Give gh a GitHub token", + message: format!( + "Give the toolchain profile {} the token of the review host {} in the workspace\n{workspace_folder}?\n\nA model command in this workspace that starts this profile's gh gets the host's token as GH_TOKEN and network access. It still needs the workspace's command and task networking preferences; under Allow for both it runs without asking. gh sends the token to github.com only.", + named(profile), + named(host), + ), + } +} + /// The native confirmation for removing a toolchain profile. `workspaces` /// holds, for each workspace it is assigned to, the workspace folder and the /// display-safe folders of the grants the removal releases there. @@ -822,6 +862,88 @@ impl DesktopService { }) } + /// `settings` only. After a native confirmation that names the workspace, + /// the profile, and the review host, bind the profile's `gh` to the host's + /// token (ADR-0147). The binding is configuration: a model command of the + /// profile still needs the workspace's command and task-network + /// preferences and its approval. No token is read or shown here. + /// + /// # Errors + /// + /// `unknown_workspace`; `control` for an unknown profile or host, a + /// profile not assigned to the workspace, or a host whose kind is not + /// `github`; `cancelled`; `stale_revision`; `settings_change_running`; + /// `busy`. + pub fn settings_bind_gh_token( + &self, + request: GhTokenBindRequest, + prompt: &dyn SettingsPrompt, + ) -> Result { + let _guard = ChangeGuard::take(&self.inner.settings_change)?; + check_name(&request.profile)?; + check_name(&request.host)?; + let (workspace_id, confirmation) = { + let store = self.inner.open_or_create_control()?; + check_revision(&store, request.revision)?; + let workspace = store + .registered_workspace(request.workspace_id) + .ok_or_else(DesktopError::unknown_workspace)?; + let profile = store + .profile(&request.profile) + .ok_or_else(|| DesktopError::from_control(&ControlError::UnknownProfile))? + .profile() + .name() + .to_owned(); + let host = store + .review_host(&request.host) + .ok_or_else(|| DesktopError::from_control(&ControlError::UnknownReviewHost))? + .name() + .to_owned(); + let confirmation = bind_gh_token_confirmation( + &folder_of_directory(workspace.directory_path()), + &profile, + &host, + ); + (workspace.id(), confirmation) + }; + confirm(prompt, &confirmation)?; + self.apply(|store| { + store + .bind_gh_token( + workspace_id, + &request.profile, + &request.host, + request.revision, + ) + .map(|_| ()) + }) + } + + /// `settings` only. End a profile's GitHub token binding (ADR-0147). + /// Unbinding narrows access, so no dialog opens (ADR-0115). The runs that + /// used the binding are stopped, and the call waits for them as other + /// settings changes do. + /// + /// # Errors + /// + /// `unknown_workspace`; `control` for an unknown profile or one with no + /// binding; `stale_revision`; `settings_change_running`; `busy`; + /// `runs_not_stopped`; `runs_unchecked`. + pub fn settings_unbind_gh_token( + &self, + request: GhTokenUnbindRequest, + ) -> Result { + let _guard = ChangeGuard::take(&self.inner.settings_change)?; + check_name(&request.profile)?; + self.apply(|store| { + let workspace_id = store + .registered_workspace(request.workspace_id) + .map(|workspace| workspace.id()) + .ok_or(ControlError::UnknownWorkspace)?; + store.unbind_gh_token(workspace_id, &request.profile, request.revision) + }) + } + /// `settings` only. After a native confirmation that lists the origins /// core parsed, record a package-network profile as `omgcode workspace /// package-profile-add` does. The profile is configuration only: no run diff --git a/crates/omgcode-app/src/desktop/wire.rs b/crates/omgcode-app/src/desktop/wire.rs index 8e78c2c2..2c10fbd1 100644 --- a/crates/omgcode-app/src/desktop/wire.rs +++ b/crates/omgcode-app/src/desktop/wire.rs @@ -1203,6 +1203,9 @@ pub struct WorkspaceSettingsView { /// The names of the toolchain profiles assigned to the workspace, in the /// order assigned (ADR-0107). Only these can run in it. pub profiles: Vec, + /// The workspace's GitHub token bindings (ADR-0147), in the order made. + /// Names only. + pub gh_token_bindings: Vec, /// Display-safe text of the selected package cache root, if any. pub package_cache_root: Option, /// The workspace's custom instructions (ADR-0080), empty when none are @@ -1216,6 +1219,16 @@ pub struct WorkspaceSettingsView { pub instructions_max_bytes: Option, } +/// One toolchain profile of a workspace bound to a review host's token +/// (ADR-0147). Names only: never a token or a credential identifier. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct GhTokenBindingView { + /// The toolchain profile's name. + pub profile: String, + /// The review host's name. + pub host: String, +} + /// Whether the Git tools are offered for a workspace, as the `settings` window /// shows it (ADR-0139). Read from recorded grants and the program's file; it /// says nothing about the workspace's preferences, and starts nothing. diff --git a/crates/omgcode-app/tests/desktop_settings_execution.rs b/crates/omgcode-app/tests/desktop_settings_execution.rs index 0bcadcd9..a518fc59 100644 --- a/crates/omgcode-app/tests/desktop_settings_execution.rs +++ b/crates/omgcode-app/tests/desktop_settings_execution.rs @@ -19,18 +19,21 @@ use std::path::{Path, PathBuf}; use omgcode_app::TokenSource; use omgcode_app::desktop::{ Confirmation, ContainerGrantRequest, DesktopConfig, DesktopError, DesktopService, - FolderPurpose, GitWorkerGrantRequest, GitWorkerState, GitWorkerView, PackageProfileAddRequest, + FolderPurpose, GhTokenBindRequest, GhTokenBindingView, GhTokenUnbindRequest, + GitWorkerGrantRequest, GitWorkerState, GitWorkerView, PackageProfileAddRequest, ProfileAssignmentRequest, ProfileRemoveRequest, SettingsOverview, SettingsPrompt, ToolchainProfileAddRequest, WebHostChangeRequest, }; use omgcode_core::control::{ - ContainerGrantAccess, ContainerGrantState, ControlStore, PackageProfileDeclaration, + ContainerGrantAccess, ContainerGrantState, ControlStore, CredentialId, CredentialStore, + NewReviewHost, PackageProfileDeclaration, Secret, }; +use omgcode_core::review_host::ReviewHostKind; use omgcode_core::turn::display_safe_line; use serde_json::json; use uuid::Uuid; -use common::{Fixture, wire}; +use common::{Fixture, text_of, wire}; #[derive(Debug, PartialEq)] enum Asked { @@ -1623,3 +1626,248 @@ mod windows { assert!(silent.asked().is_empty()); } } + +/// A made-up token. It never reaches a host. +const HOST_TOKEN: &str = "gh_tok_0123456789abcdefABCDEF"; + +/// Deletes the native credential items of the review hosts a test added, also +/// after a failed assertion, and nothing else: another test or a real profile +/// may hold items in the same native store. +struct HostCredentials { + data: PathBuf, + ids: Vec, +} + +impl Drop for HostCredentials { + fn drop(&mut self) { + let Ok(credentials) = CredentialStore::open(&self.data) else { + return; + }; + for id in &self.ids { + // The item may already be gone. + let _ = credentials.delete(id); + } + } +} + +/// Record a review host directly through core, with a real native item that +/// the returned guard deletes. +fn review_host_added(fixture: &Fixture, name: &str, kind: ReviewHostKind) -> HostCredentials { + let mut store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + let revision = store.revision(); + let credentials = CredentialStore::open(&fixture.data).expect("credential store"); + let secret = Secret::new(HOST_TOKEN.as_bytes().to_vec()).expect("a secret"); + let base_url = (kind == ReviewHostKind::GitLabSelfManaged).then_some("https://git.example.com"); + let added = store + .add_review_host( + &credentials, + &NewReviewHost { + name, + kind, + base_url, + organization: None, + }, + &secret, + revision, + ) + .expect("a review host"); + HostCredentials { + data: fixture.data.clone(), + ids: vec![added.binding.id().clone()], + } +} + +fn gh_bind(revision: u64, workspace: Uuid, profile: &str, host: &str) -> GhTokenBindRequest { + wire(json!({ + "revision": revision, + "workspace_id": workspace, + "profile": profile, + "host": host, + })) +} + +fn gh_unbind(revision: u64, workspace: Uuid, profile: &str) -> GhTokenUnbindRequest { + wire(json!({ "revision": revision, "workspace_id": workspace, "profile": profile })) +} + +fn binding(profile: &str, host: &str) -> GhTokenBindingView { + GhTokenBindingView { + profile: profile.to_owned(), + host: host.to_owned(), + } +} + +/// Binding needs a native confirmation that names the workspace, the profile, +/// and the host; a declined one records nothing; core refuses a profile that +/// is not assigned and a host that is not github.com; unbinding needs no +/// dialog; and the overview lists the binding by names only (ADR-0147). +#[test] +fn binding_a_gh_token_is_confirmed_and_listed_by_names_and_unbinding_is_not() { + let fixture = Fixture::new(); + let workspace = with_workspace(&fixture); + profile_added(&fixture, "rust"); + let _credentials = [ + review_host_added(&fixture, "work", ReviewHostKind::GitHub), + review_host_added(&fixture, "lab", ReviewHostKind::GitLabSelfManaged), + ]; + let desktop = service(&fixture.data); + let silent = ScriptedPrompt::new(); + + // An unassigned profile is refused by core after the confirmation. + let before = current_revision(&fixture.data); + let accepted = ScriptedPrompt::new().answer(true); + let error = error_of( + desktop.settings_bind_gh_token(gh_bind(before, workspace, "rust", "work"), &accepted), + ); + assert_eq!(error.code(), "control", "{error}"); + assert!( + error.message().contains("not assigned"), + "{}", + error.message() + ); + assert_eq!(current_revision(&fixture.data), before); + + let assigned = desktop + .settings_assign_toolchain_profile( + assignment(before, workspace, "rust"), + &ScriptedPrompt::new().answer(true), + ) + .expect("assigned"); + + // A declined confirmation records nothing. + let declined = ScriptedPrompt::new().answer(false); + let error = error_of(desktop.settings_bind_gh_token( + gh_bind(assigned.revision, workspace, "rust", "work"), + &declined, + )); + assert_eq!(error.code(), "cancelled"); + let confirmation = declined.confirmations().remove(0); + assert_eq!(confirmation.title, "Give gh a GitHub token"); + for part in [ + "project", + "rust", + "work", + "GH_TOKEN", + "network access", + "github.com only", + ] { + assert!( + confirmation.message.contains(part), + "{part}: {}", + confirmation.message + ); + } + assert!(!confirmation.message.contains(HOST_TOKEN)); + assert_eq!(current_revision(&fixture.data), assigned.revision); + + // A host of another kind is refused by core after the confirmation. + let accepted = ScriptedPrompt::new().answer(true); + let error = error_of(desktop.settings_bind_gh_token( + gh_bind(assigned.revision, workspace, "rust", "lab"), + &accepted, + )); + assert_eq!(error.code(), "control", "{error}"); + assert_eq!(current_revision(&fixture.data), assigned.revision); + + // A stale revision, an unknown workspace, profile, or host are refused + // before any dialog. + for (request, code) in [ + ( + gh_bind(assigned.revision + 1, workspace, "rust", "work"), + "stale_revision", + ), + ( + gh_bind(assigned.revision, Uuid::new_v4(), "rust", "work"), + "unknown_workspace", + ), + ( + gh_bind(assigned.revision, workspace, "missing", "work"), + "control", + ), + ( + gh_bind(assigned.revision, workspace, "rust", "missing"), + "control", + ), + ] { + let error = error_of(desktop.settings_bind_gh_token(request, &silent)); + assert_eq!(error.code(), code, "{error}"); + } + assert!(silent.asked().is_empty()); + + // An accepted confirmation records the binding, and the overview lists it + // by names and shows no token. + let accepted = ScriptedPrompt::new().answer(true); + let bound = desktop + .settings_bind_gh_token( + gh_bind(assigned.revision, workspace, "rust", "work"), + &accepted, + ) + .expect("bound"); + assert_eq!(accepted.confirmations().len(), 1); + assert_eq!(bound.revision, assigned.revision + 1); + assert_eq!( + bound.workspaces[0].gh_token_bindings, + [binding("rust", "work")] + ); + assert!( + !text_of(&bound).contains(HOST_TOKEN), + "no token reaches the overview" + ); + + // Binding again replaces the profile's binding, never adds a second. + let rebound = desktop + .settings_bind_gh_token( + gh_bind(bound.revision, workspace, "rust", "work"), + &ScriptedPrompt::new().answer(true), + ) + .expect("rebound"); + assert_eq!( + rebound.workspaces[0].gh_token_bindings, + [binding("rust", "work")] + ); + + // Unbinding opens no dialog (the method takes no prompt) and records. + let unbound = desktop + .settings_unbind_gh_token(gh_unbind(rebound.revision, workspace, "rust")) + .expect("unbound"); + assert_eq!(unbound.revision, rebound.revision + 1); + assert!(unbound.workspaces[0].gh_token_bindings.is_empty()); + // A profile with no binding, a stale revision, and an unknown workspace + // are refused. + for (request, code) in [ + (gh_unbind(unbound.revision, workspace, "rust"), "control"), + ( + gh_unbind(unbound.revision + 1, workspace, "rust"), + "stale_revision", + ), + ( + gh_unbind(unbound.revision, Uuid::new_v4(), "rust"), + "unknown_workspace", + ), + ] { + let error = error_of(desktop.settings_unbind_gh_token(request)); + assert_eq!(error.code(), code, "{error}"); + } + + // Unassigning the profile ends a binding with no event of its own. + let bound = desktop + .settings_bind_gh_token( + gh_bind(unbound.revision, workspace, "rust", "work"), + &ScriptedPrompt::new().answer(true), + ) + .expect("bound again"); + assert_eq!(bound.workspaces[0].gh_token_bindings.len(), 1); + let unassigned = desktop + .settings_unassign_toolchain_profile( + assignment(bound.revision, workspace, "rust"), + &ScriptedPrompt::new().answer(true), + ) + .expect("unassigned"); + assert!(unassigned.workspaces[0].gh_token_bindings.is_empty()); + + fixture + .revoke_grants() + .expect("every container grant is revoked"); +} diff --git a/crates/omgcode-cli/src/control_cli.rs b/crates/omgcode-cli/src/control_cli.rs index a746a4b7..f4d30542 100644 --- a/crates/omgcode-cli/src/control_cli.rs +++ b/crates/omgcode-cli/src/control_cli.rs @@ -13,7 +13,7 @@ use omgcode_core::policy::{ Access, Operation, PermissionSet, PolicyRequest, WorkspaceId, WriteTool, }; use omgcode_core::run; -use serde_json::json; +use serde_json::{Value, json}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::thread; @@ -194,6 +194,35 @@ pub(crate) enum WorkspaceCommand { #[arg(long)] revision: u64, }, + /// Give a workspace's toolchain profile the token of a review host of + /// kind `github` (ADR-0147). A model command in the workspace whose + /// program is that profile's `gh` then gets the token as `GH_TOKEN` and + /// network access. It still needs the command preferences and + /// `task_network`; under `allow` for both it runs without an approval. + /// `gh` sends the token to github.com only, and the runner refuses + /// arguments that could name another host. Binding again replaces the + /// profile's binding, and runs that use the replaced one are withdrawn. + /// Running this command is the consent. + GhTokenBind { + workspace: String, + /// The toolchain profile name, assigned to the workspace. + profile: String, + /// The review host name, of kind `github`. + host: String, + #[arg(long)] + revision: u64, + }, + /// End a workspace profile's GitHub token binding. Runs that use it are + /// withdrawn. + GhTokenUnbind { + workspace: String, + /// The toolchain profile name. + profile: String, + #[arg(long)] + revision: u64, + }, + /// List a workspace's GitHub token bindings by profile and host name. + GhTokenList { workspace: String }, /// Record a package-network profile. Configuration only: no run accepts it. PackageProfileAdd(PackageProfileAddArgs), /// Show one recorded package-network profile. @@ -947,6 +976,64 @@ pub(crate) fn run(action: WorkspaceCommand, data_root: &Path) -> Result<(), CliE )?; print_json(&output) } + WorkspaceCommand::GhTokenBind { + workspace, + profile, + host, + revision, + } => { + let workspace_id = parse_workspace_id(&workspace)?; + let mut store = open_existing(data_root)? + .ok_or_else(|| CliError::new("control", "Workspace control is not initialized"))?; + store + .bind_gh_token(workspace_id, &profile, &host, revision) + .map_err(control_error)?; + let output = json!({ + "gh_tokens": gh_token_bindings(&store, workspace_id), + "revision": store.revision(), + }); + // A rebind to another host withdraws the runs that hold the old + // host's token; wait for them as the unbind does. + let listed = withdrawn_runs(&store); + drop(store); + stop_withdrawn_runs(data_root, listed.as_deref().unwrap_or(&[]))?; + listed?; + print_json(&output) + } + WorkspaceCommand::GhTokenUnbind { + workspace, + profile, + revision, + } => { + let workspace_id = parse_workspace_id(&workspace)?; + let mut store = open_existing(data_root)? + .ok_or_else(|| CliError::new("control", "Workspace control is not initialized"))?; + store + .unbind_gh_token(workspace_id, &profile, revision) + .map_err(control_error)?; + let output = json!({ + "gh_tokens": gh_token_bindings(&store, workspace_id), + "revision": store.revision(), + }); + let listed = withdrawn_runs(&store); + drop(store); + stop_withdrawn_runs(data_root, listed.as_deref().unwrap_or(&[]))?; + listed?; + print_json(&output) + } + WorkspaceCommand::GhTokenList { workspace } => { + let workspace_id = parse_workspace_id(&workspace)?; + let store = open_existing(data_root)? + .ok_or_else(|| CliError::new("control", "Workspace control is not initialized"))?; + if store.workspace(workspace_id).is_none() { + return Err(CliError::new("control", "Workspace is not registered")); + } + print_json(&json!({ + "workspace_id": workspace_id, + "gh_tokens": gh_token_bindings(&store, workspace_id), + "revision": store.revision(), + })) + } WorkspaceCommand::PackageProfileAdd(args) => package_profile_add(args, data_root), WorkspaceCommand::PackageProfileShow { name } => { let store = open_existing(data_root)? @@ -1784,6 +1871,24 @@ fn waiting(mut open: impl FnMut() -> Result) -> Result Vec { + store + .gh_token_bindings() + .iter() + .filter(|binding| binding.workspace_id() == workspace_id) + .filter_map(|binding| { + let profile = store + .profiles() + .iter() + .find(|status| status.profile().id() == binding.profile_id())?; + let host = store.gh_token_host(workspace_id, binding.profile_id())?; + Some(json!({"profile": profile.profile().name(), "host": host.name()})) + }) + .collect() +} + fn parse_workspace_id(value: &str) -> Result { WorkspaceId::from_str(value) .map_err(|_| CliError::new("configuration", "Invalid workspace identifier")) diff --git a/crates/omgcode-cli/src/run_cli.rs b/crates/omgcode-cli/src/run_cli.rs index fc129025..70ac13bb 100644 --- a/crates/omgcode-cli/src/run_cli.rs +++ b/crates/omgcode-cli/src/run_cli.rs @@ -162,6 +162,8 @@ pub(crate) fn run(args: RunArgs, data_root: &Path) -> Result<(), CliError> { network: args.network, model_tools: false, standing_allow: false, + github_host: None, + github_host_id: None, limits: ProcessLimits { deadline, max_stdout_bytes: args.max_output_bytes, diff --git a/crates/omgcode-cli/tests/run_workflow.rs b/crates/omgcode-cli/tests/run_workflow.rs index 73c7b59a..86107fba 100644 --- a/crates/omgcode-cli/tests/run_workflow.rs +++ b/crates/omgcode-cli/tests/run_workflow.rs @@ -1458,3 +1458,151 @@ fn a_linux_runs_change_to_the_checkpoint_folder_is_detected() { assert!(error_message(&checkpoints).contains("replaced")); scene.close(); } + +/// A workspace's `gh` profile is bound to a `github` review host's token, +/// listed by names only, refused for an unknown host or a profile the +/// workspace does not run, and unbound (ADR-0147). No token appears in any +/// output. +#[test] +fn gh_tokens_are_bound_listed_and_unbound() { + const TOKEN: &str = "github_pat_omgcode_cli_test_0147"; + let scene = Scene::new(); + // Dropped before the scene, so a failed assertion still deletes the token. + let mut cleanup = HostTokenCleanup { + data: scene.data.clone(), + id: None, + }; + assert_success(&scene.add_profile("gh", &[])); + assert_success(&scene.record_profile("other", &[])); + // A stored credential needs a private data root (ADR-0073). + #[cfg(windows)] + support::workspace_fixture::restrict_existing_to_current_user(&scene.data); + + let input = scene.temporary.path().join("token-input"); + fs::write(&input, format!("{TOKEN}\n")).expect("token input"); + let revision = scene.revision().to_string(); + let mut command = cli_command( + &scene.data, + &[ + "review-host", + "add", + "work", + "--kind", + "github", + "--revision", + &revision, + ], + ); + command.stdin(std::process::Stdio::from( + fs::File::open(&input).expect("open token input"), + )); + let added = run_with_deadline(command, CLI_DEADLINE).expect("run CLI"); + // Record the token's identifier before any assertion, so the guard can + // delete it even after the host is gone. + cleanup.record(&scene.data, "work"); + assert!(!added.timed_out, "CLI timed out"); + assert_success(&added.output); + fs::remove_file(&input).expect("remove token input"); + + let bind = |profile: &str, host: &str| { + let revision = scene.revision().to_string(); + scene.cli(&[ + "workspace", + "gh-token-bind", + &scene.id, + profile, + host, + "--revision", + &revision, + ]) + }; + assert_control_error(&bind("gh", "absent")); + assert_control_error(&bind("other", "work")); + let bound = bind("gh", "work"); + assert_success(&bound); + let expected = serde_json::json!([{"profile": "gh", "host": "work"}]); + assert_eq!(json_output(&bound)["gh_tokens"], expected); + let listed = scene.cli(&["workspace", "gh-token-list", &scene.id]); + assert_success(&listed); + assert_eq!(json_output(&listed)["gh_tokens"], expected); + for output in [&bound, &listed] { + assert!(!String::from_utf8_lossy(&output.stdout).contains(TOKEN)); + } + + let revision = scene.revision().to_string(); + let unbound = scene.settings_cli(&[ + "workspace", + "gh-token-unbind", + &scene.id, + "gh", + "--revision", + &revision, + ]); + assert_success(&unbound); + assert_eq!(json_output(&unbound)["gh_tokens"], serde_json::json!([])); + + // Removing the host deletes its stored token, with no orphan warning. + let revision = scene.revision().to_string(); + let removed = scene.cli(&["review-host", "remove", "work", "--revision", &revision]); + assert_success(&removed); + assert!( + json_output(&removed).get("warning").is_none(), + "the token was not deleted: {}", + String::from_utf8_lossy(&removed.stdout) + ); + scene.close(); +} + +/// Deletes a review host's stored token when a test ends, by the identifier +/// recorded right after the host was added, so it also covers a removal +/// that left the token behind. A token the CLI already deleted is fine. +struct HostTokenCleanup { + data: std::path::PathBuf, + id: Option, +} + +impl HostTokenCleanup { + /// Record the token identifier of review host `host`, if one is bound. + fn record(&mut self, data: &std::path::Path, host: &str) { + // The control store holds a lock a child could inherit, so it is + // opened and dropped while no test thread can start one. + let found = spawn_gate::without_child_spawns(|| { + ControlStore::open_existing(data).map(|control| { + control.and_then(|control| { + control + .review_host(host) + .map(|host| host.binding().id().clone()) + }) + }) + }); + match found { + Ok(id) => self.id = id, + Err(error) => report(format_args!( + "could not read the settings to record a test token: {error}" + )), + } + } +} + +impl Drop for HostTokenCleanup { + fn drop(&mut self) { + let Some(id) = self.id.take() else { + return; + }; + let deleted = omgcode_core::control::CredentialStore::open(&self.data) + .and_then(|credentials| credentials.delete(&id)); + match deleted { + Ok(()) | Err(omgcode_core::control::CredentialError::NotFound) => {} + Err(error) => report(format_args!( + "could not delete a test review host token: {error}" + )), + } + } +} + +/// Write a cleanup failure to standard error without panicking, which +/// `eprintln!` would do if the stream fails. +fn report(message: std::fmt::Arguments<'_>) { + use std::io::Write as _; + let _ = writeln!(std::io::stderr(), "{message}"); +} diff --git a/crates/omgcode-core/src/control.rs b/crates/omgcode-core/src/control.rs index 0aac39fb..60df7309 100644 --- a/crates/omgcode-core/src/control.rs +++ b/crates/omgcode-core/src/control.rs @@ -28,6 +28,7 @@ mod claude_code; mod container; mod credential; mod folders; +mod gh_token; mod git_identity; mod package; mod profile; @@ -70,6 +71,7 @@ pub use credential::{ }; pub(crate) use folders::broad_folder; pub use folders::{FolderAccess, GrantedFolder, MAX_FOLDER_NAME_BYTES, MAX_GRANTED_FOLDERS}; +pub use gh_token::GhTokenBinding; /// Whether this platform can record and apply container grants. pub use git_identity::{ GitIdentity, MAX_GIT_IDENTITY_EMAIL_CHARS, MAX_GIT_IDENTITY_NAME_CHARS, @@ -407,6 +409,10 @@ pub struct ControlSnapshot { /// configuration, never authority. #[serde(skip_serializing_if = "Vec::is_empty")] review_workspaces: Vec, + /// Workspace `gh` profiles bound to a `github` review host's token + /// (ADR-0147). Configuration, never authority and never a token. + #[serde(skip_serializing_if = "Vec::is_empty")] + gh_token_bindings: Vec, /// The recorded local provider profile a desktop process started without /// a connection argument uses (ADR-0064). `None` means the default /// endpoint. It always names a profile in `provider_profiles`. @@ -743,6 +749,17 @@ enum Action { #[serde(default, skip_serializing_if = "Vec::is_empty")] closed_reviews: Vec, }, + /// A workspace's toolchain profile was bound to a `github` review host's + /// token (ADR-0147), replacing any binding the profile had there. + GhTokenBound { + binding: GhTokenBinding, + }, + /// A workspace profile's token binding ended. + GhTokenUnbound { + #[serde(deserialize_with = "deserialize_workspace_id")] + workspace_id: WorkspaceId, + profile_id: Uuid, + }, /// A review workspace was created for a fetched review folder /// (ADR-0144). It changes no setting, so the revision stays. ReviewWorkspaceCreated { @@ -1100,6 +1117,7 @@ impl ControlStore { provider_profiles: Vec::new(), review_hosts: Vec::new(), review_workspaces: Vec::new(), + gh_token_bindings: Vec::new(), active_provider: None, subscription_host: None, git_identity: None, @@ -1646,6 +1664,7 @@ impl ControlStore { let skill_bytes = skill_events.saturating_mul(SKILL_REMOVAL_RESERVE_BYTES); let (host_events, host_bytes) = review_host::removal_reserve(&self.snapshot); let (review_events, review_bytes) = review_workspace::closing_reserve(&self.snapshot); + let (binding_events, binding_bytes) = gh_token::unbind_reserve(&self.snapshot); let events = self .entries .len() @@ -1653,14 +1672,16 @@ impl ControlStore { .and_then(|count| count.checked_add(grant_events)) .and_then(|count| count.checked_add(skill_events)) .and_then(|count| count.checked_add(host_events)) - .and_then(|count| count.checked_add(review_events)); + .and_then(|count| count.checked_add(review_events)) + .and_then(|count| count.checked_add(binding_events)); let bytes = self .bytes .checked_add(PERMISSION_EVENT_RESERVE_BYTES) .and_then(|size| size.checked_add(grant_bytes)) .and_then(|size| size.checked_add(skill_bytes)) .and_then(|size| size.checked_add(host_bytes)) - .and_then(|size| size.checked_add(review_bytes)); + .and_then(|size| size.checked_add(review_bytes)) + .and_then(|size| size.checked_add(binding_bytes)); events.is_some_and(|count| count <= MAX_EVENTS) && bytes.is_some_and(|size| size <= MAX_BYTES) } @@ -1806,6 +1827,9 @@ impl ControlStore { // And for open reviews: a closing drops its own review from the open // count, so it uses the slot that review reserved. let (review_events, review_bytes) = review_workspace::closing_reserve(&next); + // And for `gh` token bindings: an unbind drops its own binding from + // `next`, so it uses the slot that binding reserved (ADR-0147). + let (binding_events, binding_bytes) = gh_token::unbind_reserve(&next); let events_after = self .entries .len() @@ -1813,12 +1837,14 @@ impl ControlStore { .and_then(|count| count.checked_add(grant_events)) .and_then(|count| count.checked_add(skill_events)) .and_then(|count| count.checked_add(host_events)) - .and_then(|count| count.checked_add(review_events)); + .and_then(|count| count.checked_add(review_events)) + .and_then(|count| count.checked_add(binding_events)); let bytes_after = bytes .checked_add(grant_bytes) .and_then(|size| size.checked_add(skill_bytes)) .and_then(|size| size.checked_add(host_bytes)) - .and_then(|size| size.checked_add(review_bytes)); + .and_then(|size| size.checked_add(review_bytes)) + .and_then(|size| size.checked_add(binding_bytes)); if events_after.is_none_or(|count| count > MAX_EVENTS) || bytes_after.is_none_or(|size| size > MAX_BYTES) { @@ -2139,6 +2165,9 @@ impl ControlStore { Action::ReviewWorkspaceCreated { .. } | Action::ReviewWorkspaceClosed { .. } => { review_workspace::apply(state, &entry.action)?; } + Action::GhTokenBound { .. } | Action::GhTokenUnbound { .. } => { + gh_token::apply(state, &entry.action)?; + } Action::SkillAdded(_) | Action::SkillRemoved { .. } => { skill::apply(state, &entry.action)?; } @@ -2153,6 +2182,9 @@ impl ControlStore { approval::apply_legacy(state, &entry.action, revision)?; } } + // A binding ends with its workspace, profile assignment, or host + // (ADR-0147), whichever event ended it. + gh_token::prune(state); state.revision = revision; Ok(()) } diff --git a/crates/omgcode-core/src/control/gh_token.rs b/crates/omgcode-core/src/control/gh_token.rs new file mode 100644 index 00000000..56bf3cd5 --- /dev/null +++ b/crates/omgcode-core/src/control/gh_token.rs @@ -0,0 +1,249 @@ +//! Workspace `gh` profiles bound to a GitHub review host's token (ADR-0147). +//! +//! A binding names one workspace, one toolchain profile assigned to it, and +//! one `github` review host. A model command run of that profile whose +//! program is the profile's `gh` then gets the host's token as `GH_TOKEN`, +//! with network access (see [`crate::run`]). The binding is configuration, +//! never authority: the run still needs the command preferences and +//! `task_network`, and the host's token is read only by the runner. +//! +//! Two events exist. `gh_token_bound` records or replaces the binding of one +//! workspace and profile; `gh_token_unbound` ends it. A binding also ends, +//! without an event of its own, when its workspace is unregistered, its +//! profile is removed or unassigned from the workspace, or its host is +//! removed: [`prune`] runs after every replayed event, so replay and the live +//! state agree. + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use super::{Action, ControlError, ControlSnapshot, ControlStore, deserialize_workspace_id}; +use crate::policy::WorkspaceId; +use crate::review_host::ReviewHostKind; + +use super::ReviewHostStatus; + +/// One workspace profile bound to a review host's token. Configuration only. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct GhTokenBinding { + #[serde(deserialize_with = "deserialize_workspace_id")] + workspace_id: WorkspaceId, + profile_id: Uuid, + host_id: Uuid, +} + +impl GhTokenBinding { + /// The workspace whose runs get the token. + pub const fn workspace_id(&self) -> WorkspaceId { + self.workspace_id + } + + /// The toolchain profile whose `gh` gets the token. + pub const fn profile_id(&self) -> Uuid { + self.profile_id + } + + /// The review host whose token is passed. + pub const fn host_id(&self) -> Uuid { + self.host_id + } +} + +/// A `gh_token_unbound` event is about 330 bytes. Each binding keeps one such +/// event free, so a full journal can always end it +/// (`the_largest_unbind_event_fits_its_reserve` checks the bound). +pub(super) const UNBIND_RESERVE_BYTES: usize = 512; + +/// The events and bytes the recorded bindings keep free so each can end. +pub(super) fn unbind_reserve(snapshot: &ControlSnapshot) -> (usize, usize) { + let events = snapshot.gh_token_bindings.len(); + (events, events.saturating_mul(UNBIND_RESERVE_BYTES)) +} + +/// Why a binding was refused. The texts name no path, host address, or token. +const NOT_GITHUB: &str = "only a review host of kind github (github.com) can give gh a token; \ + GitHub Enterprise is refused because gh sends GH_ENTERPRISE_TOKEN to any host a command names"; +const NOT_ASSIGNED: &str = "the toolchain profile is not assigned to this workspace"; +const NOT_BOUND: &str = "this workspace profile has no GitHub token binding"; + +impl ControlSnapshot { + /// Every recorded binding, in the order it was made. + pub fn gh_token_bindings(&self) -> &[GhTokenBinding] { + &self.gh_token_bindings + } +} + +impl ControlStore { + /// Every recorded binding, in the order it was made. + pub fn gh_token_bindings(&self) -> &[GhTokenBinding] { + &self.snapshot.gh_token_bindings + } + + /// The review host whose token runs of `profile_id` in `workspace_id` + /// get, if the profile is bound. + pub fn gh_token_host( + &self, + workspace_id: WorkspaceId, + profile_id: Uuid, + ) -> Option<&ReviewHostStatus> { + let binding = self.snapshot.gh_token_bindings.iter().find(|binding| { + binding.workspace_id == workspace_id && binding.profile_id == profile_id + })?; + self.snapshot + .review_hosts + .iter() + .find(|host| host.id() == binding.host_id) + } + + /// Bind the profile `profile` of `workspace_id` to the review host + /// `host`, replacing any binding the profile has in that workspace. This + /// advances the settings revision, so pending approvals of the + /// workspace's commands go stale. + /// + /// # Errors + /// + /// Refuses a stale revision, an unknown workspace, profile, or host, a + /// profile not assigned to the workspace, and a host whose kind is not + /// `github`. + pub fn bind_gh_token( + &mut self, + workspace_id: WorkspaceId, + profile: &str, + host: &str, + expected_revision: u64, + ) -> Result { + self.check_revision(expected_revision)?; + if self.workspace(workspace_id).is_none() { + return Err(ControlError::UnknownWorkspace); + } + let profile_id = self + .profile(profile) + .ok_or(ControlError::UnknownProfile)? + .profile() + .id(); + let host = self + .review_host(host) + .ok_or(ControlError::UnknownReviewHost)?; + let binding = GhTokenBinding { + workspace_id, + profile_id, + host_id: host.id(), + }; + check(&self.snapshot, &binding)?; + self.append( + Action::GhTokenBound { + binding: binding.clone(), + }, + self.next_revision()?, + )?; + Ok(binding) + } + + /// End the binding of the profile `profile` in `workspace_id`. This + /// advances the settings revision and withdraws the runs that use it. + /// + /// # Errors + /// + /// Refuses a stale revision, an unknown workspace or profile, and a + /// profile with no binding in the workspace. + pub fn unbind_gh_token( + &mut self, + workspace_id: WorkspaceId, + profile: &str, + expected_revision: u64, + ) -> Result<(), ControlError> { + self.check_revision(expected_revision)?; + if self.workspace(workspace_id).is_none() { + return Err(ControlError::UnknownWorkspace); + } + let profile_id = self + .profile(profile) + .ok_or(ControlError::UnknownProfile)? + .profile() + .id(); + self.append( + Action::GhTokenUnbound { + workspace_id, + profile_id, + }, + self.next_revision()?, + ) + } +} + +/// Whether `binding` may be recorded against `state`. +fn check(state: &ControlSnapshot, binding: &GhTokenBinding) -> Result<(), ControlError> { + let workspace = state + .workspaces + .iter() + .find(|workspace| workspace.id == binding.workspace_id) + .ok_or(ControlError::UnknownWorkspace)?; + if !state + .profiles + .iter() + .any(|status| status.profile().id() == binding.profile_id) + { + return Err(ControlError::UnknownProfile); + } + if !workspace.profiles.contains(&binding.profile_id) { + return Err(ControlError::ProfileRefused(NOT_ASSIGNED)); + } + let host = state + .review_hosts + .iter() + .find(|host| host.id() == binding.host_id) + .ok_or(ControlError::UnknownReviewHost)?; + if host.kind() != ReviewHostKind::GitHub { + return Err(ControlError::ReviewHostRefused(NOT_GITHUB)); + } + Ok(()) +} + +/// Validate and apply one binding action during replay or append preflight. +pub(super) fn apply(state: &mut ControlSnapshot, action: &Action) -> Result<(), ControlError> { + match action { + Action::GhTokenBound { binding } => { + check(state, binding)?; + state.gh_token_bindings.retain(|existing| { + existing.workspace_id != binding.workspace_id + || existing.profile_id != binding.profile_id + }); + state.gh_token_bindings.push(binding.clone()); + } + Action::GhTokenUnbound { + workspace_id, + profile_id, + } => { + let index = state + .gh_token_bindings + .iter() + .position(|binding| { + binding.workspace_id == *workspace_id && binding.profile_id == *profile_id + }) + .ok_or(ControlError::ProfileRefused(NOT_BOUND))?; + state.gh_token_bindings.remove(index); + } + _ => return Err(ControlError::Invalid("not a gh token action")), + } + Ok(()) +} + +/// Drop every binding whose workspace, profile assignment, or host no longer +/// exists. Runs after every applied event, so the events that end those +/// records end their bindings too. +pub(super) fn prune(state: &mut ControlSnapshot) { + if state.gh_token_bindings.is_empty() { + return; + } + let workspaces = &state.workspaces; + let hosts = &state.review_hosts; + state.gh_token_bindings.retain(|binding| { + workspaces.iter().any(|workspace| { + workspace.id == binding.workspace_id && workspace.profiles.contains(&binding.profile_id) + }) && hosts.iter().any(|host| host.id() == binding.host_id) + }); +} + +#[cfg(test)] +mod tests; diff --git a/crates/omgcode-core/src/control/gh_token/tests.rs b/crates/omgcode-core/src/control/gh_token/tests.rs new file mode 100644 index 00000000..78416861 --- /dev/null +++ b/crates/omgcode-core/src/control/gh_token/tests.rs @@ -0,0 +1,426 @@ +//! Token bindings of workspace `gh` profiles against the real control journal. +//! Review hosts are recorded as raw events with an unused credential +//! identifier, so no native credential store is needed. + +use super::*; +use std::fs; +use std::path::PathBuf; + +use super::super::{AuditEntry, MAX_BYTES}; +use crate::control::{ + CredentialBackend, CredentialBinding, CredentialId, ProfileDeclaration, ReviewHostRecord, +}; + +struct Scene { + store: ControlStore, + data: PathBuf, + root: PathBuf, + tools: PathBuf, + _directory: tempfile::TempDir, +} + +fn scene() -> Scene { + let directory = tempfile::tempdir().expect("temporary directory"); + let data = directory.path().join("data"); + let root = directory.path().join("projects"); + let tools = directory.path().join("tools"); + fs::create_dir_all(&root).expect("development root"); + fs::create_dir_all(&tools).expect("toolchain folder"); + let mut store = ControlStore::open(&data).expect("store"); + store.set_development_root(&root, 0).expect("root"); + Scene { + store, + data, + root, + tools, + _directory: directory, + } +} + +impl Scene { + fn register(&mut self, name: &str) -> WorkspaceId { + let path = self.root.join(name); + fs::create_dir(&path).expect("workspace directory"); + let revision = self.store.revision(); + self.store + .register_workspace(&path, revision) + .expect("workspace") + .id() + } + + /// A profile named `name`, assigned to `workspace`. + fn assigned_profile(&mut self, workspace: WorkspaceId, name: &str) -> Uuid { + let root = self.tools.join(name); + fs::create_dir_all(&root).expect("profile root"); + let revision = self.store.revision(); + let id = self + .store + .add_profile( + &ProfileDeclaration { + name: name.into(), + read_only_roots: vec![root], + ..ProfileDeclaration::default() + }, + revision, + ) + .expect("profile") + .id(); + let revision = self.store.revision(); + self.store + .assign_profile(workspace, name, revision) + .expect("assign"); + id + } + + /// Record a review host of `kind` with an unused credential identifier. + fn host(&mut self, name: &str, kind: ReviewHostKind, base_url: Option<&str>) -> Uuid { + let id = Uuid::new_v4(); + let revision = self.store.next_revision().expect("revision"); + self.store + .append( + Action::ReviewHostAdded { + host: ReviewHostRecord { + id, + name: name.to_owned(), + kind, + base_url: base_url.map(str::to_owned), + organization: None, + }, + binding: binding(), + }, + revision, + ) + .expect("host"); + id + } + + fn bind( + &mut self, + workspace: WorkspaceId, + profile: &str, + host: &str, + ) -> Result { + let revision = self.store.revision(); + self.store.bind_gh_token(workspace, profile, host, revision) + } + + /// Drop the store and replay the journal. + fn reopened(self) -> Self { + let Self { + store, + data, + root, + tools, + _directory, + } = self; + drop(store); + Self { + store: ControlStore::open(&data).expect("replay"), + data, + root, + tools, + _directory, + } + } +} + +fn binding() -> CredentialBinding { + let id = CredentialId::parse(&Uuid::new_v4().simple().to_string()).expect("id"); + CredentialBinding::new(id, CredentialBackend::WindowsDpapi) +} + +/// A binding is recorded, advances the revision, names the host, replaces an +/// earlier binding of the same profile, survives replay, and is removed. +#[test] +fn a_binding_is_recorded_replaced_replayed_and_removed() { + let mut scene = scene(); + let app = scene.register("app"); + let other = scene.register("other"); + let gh = scene.assigned_profile(app, "gh"); + let work = scene.host("work", ReviewHostKind::GitHub, None); + let revision = scene.store.revision(); + + let binding = scene.bind(app, "gh", "work").expect("bind"); + assert_eq!(binding.workspace_id(), app); + assert_eq!(binding.profile_id(), gh); + assert_eq!(binding.host_id(), work); + assert_eq!(scene.store.revision(), revision + 1); + assert_eq!( + scene.store.gh_token_host(app, gh).map(ReviewHostStatus::id), + Some(work) + ); + assert!(scene.store.gh_token_host(other, gh).is_none()); + + let encoded = serde_json::to_value(scene.store.snapshot()).expect("snapshot JSON"); + assert_eq!(encoded["gh_token_bindings"][0]["host_id"], json(work)); + + // Binding again replaces, so the profile has one binding. Only one + // `github` host can be recorded, since its endpoint is fixed. + scene.bind(app, "gh", "work").expect("bind again"); + assert_eq!(scene.store.gh_token_bindings().len(), 1); + + scene = scene.reopened(); + assert_eq!( + scene.store.gh_token_host(app, gh).map(ReviewHostStatus::id), + Some(work) + ); + let revision = scene.store.revision(); + scene + .store + .unbind_gh_token(app, "gh", revision) + .expect("unbind"); + assert_eq!(scene.store.revision(), revision + 1); + assert!(scene.store.gh_token_host(app, gh).is_none()); + scene = scene.reopened(); + assert!(scene.store.gh_token_bindings().is_empty()); +} + +/// The largest unbind event fits the reserve each binding keeps free. +#[test] +fn the_largest_unbind_event_fits_its_reserve() { + let entry = AuditEntry { + schema_version: u32::MAX, + store_id: Uuid::new_v4(), + event_id: Uuid::new_v4(), + sequence: u64::MAX, + timestamp: "2026-11-18T19:15:40.641064900+14:00".into(), + revision: u64::MAX, + action: Action::GhTokenUnbound { + workspace_id: WorkspaceId::from_uuid(Uuid::new_v4()).expect("workspace id"), + profile_id: Uuid::new_v4(), + }, + }; + let encoded = serde_json::to_vec(&entry).expect("event JSON"); + assert!( + encoded.len() < UNBIND_RESERVE_BYTES, + "{} bytes", + encoded.len() + ); +} + +/// A journal filled to the reserve still ends a binding, and refuses a +/// binding that would take the last free room. +#[test] +fn a_full_journal_still_ends_a_binding() { + let mut scene = scene(); + let app = scene.register("app"); + let gh = scene.assigned_profile(app, "gh"); + scene.host("work", ReviewHostKind::GitHub, None); + scene.bind(app, "gh", "work").expect("bind"); + let (_, reserved) = super::super::review_host::removal_reserve(&scene.store.snapshot()); + // Leave the unbind and host-removal reserves plus a little. + scene.store.bytes = MAX_BYTES - UNBIND_RESERVE_BYTES - reserved - 64; + + assert!(matches!( + scene.bind(app, "gh", "work"), + Err(ControlError::LimitReached) + )); + let revision = scene.store.revision(); + scene + .store + .unbind_gh_token(app, "gh", revision) + .expect("the reserved unbind fits"); + assert!(scene.store.gh_token_host(app, gh).is_none()); +} + +/// The runner matches a binding by the host's name and identifier, so a host +/// removed and added again under the same name does not lend its token to a +/// run admitted with the old one. +#[test] +fn the_runner_matches_the_admitted_host_identifier() { + let mut scene = scene(); + let app = scene.register("app"); + let gh = scene.assigned_profile(app, "gh"); + let old = scene.host("work", ReviewHostKind::GitHub, None); + scene.bind(app, "gh", "work").expect("bind"); + let matched = |scene: &Scene, name: &str, id: Uuid| { + crate::run::bound_github_host(&scene.store, app, gh, name, id).map(ReviewHostStatus::id) + }; + assert_eq!(matched(&scene, "work", old), Some(old)); + assert_eq!(matched(&scene, "other", old), None); + + let credential = scene + .store + .review_host("work") + .map(|status| status.binding().id().clone()) + .expect("host"); + let revision = scene.store.next_revision().expect("revision"); + scene + .store + .append( + Action::ReviewHostRemoved { + host_id: old, + credential_id: credential, + closed_reviews: Vec::new(), + }, + revision, + ) + .expect("remove host"); + let new = scene.host("work", ReviewHostKind::GitHub, None); + scene.bind(app, "gh", "work").expect("bind the replacement"); + + assert_eq!(matched(&scene, "work", old), None); + assert_eq!(matched(&scene, "work", new), Some(new)); +} + +fn json(id: Uuid) -> serde_json::Value { + serde_json::to_value(id).expect("id JSON") +} + +/// Only a `github` host, a known workspace, profile, and host, a profile +/// assigned to the workspace, and the current revision are accepted. A +/// refusal records nothing. +#[test] +fn refused_bindings_change_nothing() { + let mut scene = scene(); + let app = scene.register("app"); + let other = scene.register("other"); + scene.assigned_profile(app, "gh"); + scene.assigned_profile(other, "gh-2"); + scene.host("work", ReviewHostKind::GitHub, None); + scene.host( + "corp", + ReviewHostKind::GitHubEnterprise, + Some("https://github.corp.example"), + ); + scene.host("lab", ReviewHostKind::GitLab, None); + let revision = scene.store.revision(); + + for host in ["corp", "lab"] { + assert!( + matches!( + scene.bind(app, "gh", host), + Err(ControlError::ReviewHostRefused(reason)) if reason == NOT_GITHUB + ), + "{host}" + ); + } + assert!(matches!( + scene.bind(app, "gh-2", "work"), + Err(ControlError::ProfileRefused(reason)) if reason == NOT_ASSIGNED + )); + assert!(matches!( + scene.bind(app, "none", "work"), + Err(ControlError::UnknownProfile) + )); + assert!(matches!( + scene.bind(app, "gh", "none"), + Err(ControlError::UnknownReviewHost) + )); + let unknown = WorkspaceId::from_uuid(Uuid::new_v4()).expect("workspace id"); + assert!(matches!( + scene.bind(unknown, "gh", "work"), + Err(ControlError::UnknownWorkspace) + )); + assert!(matches!( + scene.store.bind_gh_token(app, "gh", "work", revision + 1), + Err(ControlError::Conflict { .. }) + )); + assert!(matches!( + scene.store.unbind_gh_token(app, "gh", revision), + Err(ControlError::ProfileRefused(reason)) if reason == NOT_BOUND + )); + assert_eq!(scene.store.revision(), revision); + assert!(scene.store.gh_token_bindings().is_empty()); +} + +/// Unassigning the profile, removing it, removing the host, or unregistering +/// the workspace ends the binding, live and after replay. +#[test] +fn a_binding_ends_with_its_assignment_profile_host_or_workspace() { + let mut scene = scene(); + let app = scene.register("app"); + let gh = scene.assigned_profile(app, "gh"); + scene.host("work", ReviewHostKind::GitHub, None); + + scene.bind(app, "gh", "work").expect("bind"); + let revision = scene.store.revision(); + scene + .store + .unassign_profile(app, "gh", revision) + .expect("unassign"); + assert!(scene.store.gh_token_host(app, gh).is_none()); + scene = scene.reopened(); + assert!(scene.store.gh_token_bindings().is_empty()); + + let revision = scene.store.revision(); + scene + .store + .assign_profile(app, "gh", revision) + .expect("assign again"); + scene.bind(app, "gh", "work").expect("bind again"); + let revision = scene.store.revision(); + scene + .store + .remove_profile("gh", revision) + .expect("remove profile"); + assert!(scene.store.gh_token_bindings().is_empty()); + + let gh = scene.assigned_profile(app, "gh"); + let host = scene + .store + .review_host("work") + .map(|status| (status.id(), status.binding().id().clone())) + .expect("host"); + scene.bind(app, "gh", "work").expect("bind third"); + let revision = scene.store.next_revision().expect("revision"); + scene + .store + .append( + Action::ReviewHostRemoved { + host_id: host.0, + credential_id: host.1, + closed_reviews: Vec::new(), + }, + revision, + ) + .expect("remove host"); + assert!(scene.store.gh_token_host(app, gh).is_none()); + scene = scene.reopened(); + assert!(scene.store.gh_token_bindings().is_empty()); + + scene.host("work", ReviewHostKind::GitHub, None); + scene.bind(app, "gh", "work").expect("bind fourth"); + let revision = scene.store.revision(); + scene + .store + .unregister_workspace(app, revision) + .expect("unregister"); + assert!(scene.store.gh_token_bindings().is_empty()); + scene = scene.reopened(); + assert!(scene.store.gh_token_bindings().is_empty()); +} + +/// Replay refuses a binding event that names a host of another kind or a +/// profile the workspace does not run, so a hand-edited journal cannot add +/// one. +#[test] +fn replay_refuses_an_invalid_binding() { + let mut scene = scene(); + let app = scene.register("app"); + let other = scene.register("other"); + let gh = scene.assigned_profile(app, "gh"); + let lab = scene.host("lab", ReviewHostKind::GitLab, None); + let work = scene.host("work", ReviewHostKind::GitHub, None); + for binding in [ + GhTokenBinding { + workspace_id: app, + profile_id: gh, + host_id: lab, + }, + GhTokenBinding { + workspace_id: other, + profile_id: gh, + host_id: work, + }, + ] { + let revision = scene.store.next_revision().expect("revision"); + assert!( + scene + .store + .append(Action::GhTokenBound { binding }, revision) + .is_err() + ); + } + assert!(scene.store.gh_token_bindings().is_empty()); +} diff --git a/crates/omgcode-core/src/control/review_host.rs b/crates/omgcode-core/src/control/review_host.rs index 46c9322f..5fb89de1 100644 --- a/crates/omgcode-core/src/control/review_host.rs +++ b/crates/omgcode-core/src/control/review_host.rs @@ -29,7 +29,7 @@ use uuid::Uuid; use super::credential::{ CredentialBackend, CredentialBinding, CredentialError, CredentialId, CredentialStore, - OrphanedCredential, ProviderCredentialError, Secret, binding_write_uncertain, + OrphanedCredential, ProviderCredentialError, Secret, Zeroizing, binding_write_uncertain, delete_unbound_credential, store_failure, }; use super::{Action, ControlError, ControlSnapshot, ControlStore, valid_uuid}; @@ -416,6 +416,18 @@ impl LoadedReviewHost { pub fn client(&self) -> Result { ReviewHostClient::new(&self.endpoint, &self.secret) } + + /// The token as text for a bound `gh` run's `GH_TOKEN` (ADR-0147), and + /// only for a `github` host, whose token `gh` sends to `github.com`. + /// `None` for another kind or a token that is not UTF-8 text. + pub(crate) fn gh_token(&self) -> Option> { + if self.endpoint.kind() != ReviewHostKind::GitHub { + return None; + } + std::str::from_utf8(self.secret.expose()) + .ok() + .map(|token| Zeroizing::new(token.to_owned())) + } } impl std::fmt::Debug for LoadedReviewHost { diff --git a/crates/omgcode-core/src/run.rs b/crates/omgcode-core/src/run.rs index a197028e..d5be8813 100644 --- a/crates/omgcode-core/src/run.rs +++ b/crates/omgcode-core/src/run.rs @@ -37,9 +37,13 @@ use crate::session::{NativePath, SessionError}; use crate::storage::{self, StorageError}; use crate::workspace::DirectoryRecord; +mod gh_token; mod git_reads; mod refusal; +#[cfg(test)] +pub(crate) use gh_token::bound_github_host; +pub(crate) use gh_token::{argument_refusal as gh_argument_refusal, is_gh_program}; pub(crate) use git_reads::{GitReadLease, watch_git_read}; use refusal::ListedPaths; @@ -105,6 +109,18 @@ pub struct RunRequest { /// whole life, so narrowing it to `prompt` or `deny` refuses or withdraws /// the run. Requires `model_tools`. pub standing_allow: bool, + /// The `github` review host whose token this run of a bound `gh` gets as + /// `GH_TOKEN` (ADR-0147). The runner requires the workspace to bind the + /// profile to this host, the program to be the profile's `gh`, the + /// arguments to pass the `gh` rules, and `network`. `None` passes no + /// token. + pub github_host: Option, + /// That host's immutable identifier, read under the settings lock that + /// admitted the call. The runner refuses the run unless the live binding + /// names this identifier, so a host replaced under the same name between + /// admission and the run never lends its token. Required with + /// `github_host`. + pub github_host_id: Option, /// Deadline, output, cleanup, and tree bounds. Tree limits are required; /// a request without them is refused before anything is recorded. pub limits: ProcessLimits, @@ -291,6 +307,9 @@ struct Prepared { scratch: Option, /// What each path core listed is for, to name a refused one. listed: ListedPaths, + /// The GitHub token a bound `gh` run got, kept to replace it in the + /// run's output (ADR-0147). + gh_token: Option>, } /// The Linux per-run scratch directory, removed after the run. @@ -421,7 +440,7 @@ pub fn run( ) = { let control = open_control(data_root)?; let (journal_root, store_id) = control.file_audit_context()?; - let prepared = prepare(&control, request, platform, &journal_root)?; + let prepared = prepare(&control, request, platform, &journal_root, data_root)?; // Taken under the control lock, so every later change is seen. let baseline = stamp(&control_path)?; let events = control.event_count(); @@ -474,17 +493,13 @@ pub fn run( let report = RunReport { start: prepared.start, finish, - stdout: CapturedText::from_output( - &outcome - .as_ref() - .map(|o| o.stdout.clone()) - .unwrap_or_default(), + stdout: captured( + outcome.as_ref().map(|o| &o.stdout), + prepared.gh_token.as_deref(), ), - stderr: CapturedText::from_output( - &outcome - .as_ref() - .map(|o| o.stderr.clone()) - .unwrap_or_default(), + stderr: captured( + outcome.as_ref().map(|o| &o.stderr), + prepared.gh_token.as_deref(), ), granted_folder_ids: prepared.granted_folder_ids, scratch_removed, @@ -507,6 +522,22 @@ pub fn run( } } +/// The text of one captured stream, with a bound `gh` run's token replaced +/// (ADR-0147). The byte count and whether bytes were discarded are those of +/// what the run wrote, not of the replaced text. +fn captured(output: Option<&CapturedOutput>, token: Option<&String>) -> CapturedText { + let Some(output) = output else { + return CapturedText::from_output(&CapturedOutput::default()); + }; + let mut captured = CapturedText::from_output(output); + if let Some(token) = token { + let redacted = gh_token::redact(&output.bytes, token.as_bytes(), output.truncated()); + captured.utf8 = std::str::from_utf8(&redacted).is_ok(); + captured.text = String::from_utf8_lossy(&redacted).into_owned(); + } + captured +} + /// The size and modification time of the control journal. type Stamp = (u64, Option); @@ -623,9 +654,22 @@ fn withdrawn(control: &ControlStore, start: &RunStart) -> Option<&'static str> { if start.model_origin && !registration.permissions().model_tools { return Some("the workspace model_tools preference is disabled"); } - if start.standing_allow && !allows_unattended(registration.permissions()) { + if start.standing_allow + && !allows_unattended(registration.permissions(), start.network.is_some()) + { return Some(STANDING_ALLOW_WITHDRAWN); } + // The binding is compared by the host's immutable identifier, so a host + // removed and added again under the same name never keeps an old run. + if start.github_host.is_some() + && start.github_host_id.is_none_or(|host_id| { + control + .gh_token_host(start.workspace_id, start.profile_id) + .is_none_or(|bound| bound.id() != host_id) + }) + { + return Some("the workspace no longer binds this profile to that GitHub review host"); + } match ( start.package_cache_root.as_ref(), control.package_cache_root(start.workspace_id), @@ -654,8 +698,11 @@ const PROFILE_NOT_ASSIGNED: &str = "the toolchain profile is not assigned to thi /// Whether the settings still let a model command run without an approval. /// A standing-allow run is checked against this under the runner's settings /// lock, because the turn released its own lock before the run (ADR-0063). -const fn allows_unattended(permissions: PermissionSet) -> bool { +/// A networked model run, which only a bound `gh` is, also needs +/// `task_network` at `allow`, as the turn required (ADR-0147). +const fn allows_unattended(permissions: PermissionSet, network: bool) -> bool { matches!(permissions.model_command(), Access::Allow) + && (!network || matches!(permissions.task_network, Access::Allow)) } /// The preferences a run needs for its whole life. A run writes inside the @@ -988,6 +1035,7 @@ fn prepare( request: &RunRequest, platform: ProfilePlatform, data_root: &Path, + credential_root: &Path, ) -> Result { // The platform runner checks these again, but only after the intent is // recorded; check them here so an out-of-range value records nothing. @@ -1016,7 +1064,9 @@ fn prepare( // The turn chose a standing allow under a settings lock it released // before calling the runner. Recheck it under this lock so a change to // `prompt` or `deny` in between cannot start an unapproved run. - if request.standing_allow && !(request.model_tools && allows_unattended(permissions)) { + if request.standing_allow + && !(request.model_tools && allows_unattended(permissions, request.network)) + { return Err(RunError::Refused(STANDING_ALLOW_WITHDRAWN)); } permitted(permissions, request.host_services, request.network).map_err(RunError::Refused)?; @@ -1059,6 +1109,28 @@ fn prepare( &scope.workspace, &workspace, )?; + // A bound `gh` run is checked and its token read under this settings + // lock, before anything is recorded (ADR-0147). + let github = request + .github_host + .as_deref() + .map(|host| { + gh_token::prepare(&gh_token::GhTokenRequest { + control, + data_root: credential_root, + workspace_id: request.workspace_id, + workspace: &scope.workspace, + profile, + path_entries: &path_entries, + requested_program: &request.program, + program: &program, + arguments: &request.arguments, + network: request.network, + host, + host_id: request.github_host_id, + }) + }) + .transpose()?; let run_id = Uuid::new_v4(); let search_path = std::env::join_paths(&path_entries) .map_err(|_| RunError::Refused("a PATH entry contains the platform's list separator"))?; @@ -1086,8 +1158,20 @@ fn prepare( if crate::control::is_reserved_variable(variable.name()) { continue; } + // A bound `gh` run's own variables replace any the profile sets + // that could redirect the token or its configuration (ADR-0147). + if github.is_some() && gh_token::replaced_variable(variable.name()) { + continue; + } environment.push((variable.name().into(), variable.value().into())); } + let (github_host, github_host_id, gh_token) = match github { + Some(github) => { + environment.extend(github.environment); + (Some(github.host), Some(github.host_id), Some(github.token)) + } + None => (None, None, None), + }; // Folders granted to the workspace with `execute` join the sandbox after // every other entry, so the profile roots keep their positions (ADR-0118). let granted = granted_folder_roots(control, request.workspace_id)?; @@ -1141,6 +1225,8 @@ fn prepare( package_cache_root, model_origin: request.model_tools, standing_allow: request.standing_allow, + github_host, + github_host_id, }; let listed = ListedPaths { profile: profile.name().to_owned(), @@ -1161,6 +1247,7 @@ fn prepare( granted_folder_ids: granted.ids, scratch, listed, + gh_token, }) } @@ -1758,6 +1845,8 @@ mod tests { package_cache_root: None, model_origin: false, standing_allow: false, + github_host: None, + github_host_id: None, } } @@ -1918,6 +2007,8 @@ mod tests { network: false, model_tools: false, standing_allow: false, + github_host: None, + github_host_id: None, limits: ProcessLimits { tree: Some(tree), ..ProcessLimits::default() @@ -2297,6 +2388,8 @@ mod tests { network: false, model_tools, standing_allow: true, + github_host: None, + github_host_id: None, limits: ProcessLimits { tree: Some(process::TreeLimits { max_memory_bytes: 1024 * 1024 * 1024, @@ -2346,6 +2439,8 @@ mod tests { network: false, model_tools: false, standing_allow: false, + github_host: None, + github_host_id: None, limits: ProcessLimits { tree: Some(process::TreeLimits { max_memory_bytes: 1024 * 1024 * 1024, @@ -2364,6 +2459,36 @@ mod tests { assert!(!journal_root.join("runs-v1.jsonl").exists()); } + /// A bound `gh` run's token is replaced in its captured text, while the + /// byte count and the truncation flag stay those of what it wrote + /// (ADR-0147). Without a token the text is unchanged. + #[test] + fn captured_text_replaces_the_token_and_keeps_the_counts() { + let token = String::from("github_pat_0123456789abcdefghij"); + let output = CapturedOutput { + bytes: format!("user: {token}\n").into_bytes(), + total_bytes: 38, + }; + let replaced = captured(Some(&output), Some(&token)); + assert!(!replaced.text.contains(&token)); + assert!(replaced.text.contains("[redacted GitHub token]")); + assert!(replaced.utf8); + assert_eq!(replaced.total_bytes, 38); + assert!(!replaced.truncated); + let plain = captured(Some(&output), None); + assert!(plain.text.contains(&token)); + assert_eq!(captured(None, Some(&token)).text, ""); + + let cut = CapturedOutput { + bytes: b"user: gith".to_vec(), + total_bytes: 38, + }; + let replaced = captured(Some(&cut), Some(&token)); + assert_eq!(replaced.text, "user: [redacted GitHub token]"); + assert!(replaced.truncated); + assert_eq!(replaced.total_bytes, 38); + } + /// Only an effective `allow` lets a model command run unattended. #[test] fn unattended_runs_need_every_command_preference_at_allow() { @@ -2374,7 +2499,7 @@ mod tests { write: Access::Allow, ..PermissionSet::default() }; - assert!(allows_unattended(all)); + assert!(allows_unattended(all, false)); for narrowed in [ PermissionSet { model_tools: false, @@ -2393,8 +2518,24 @@ mod tests { ..all }, ] { - assert!(!allows_unattended(narrowed), "{narrowed:?}"); + assert!(!allows_unattended(narrowed, false), "{narrowed:?}"); + } + // A networked run, a bound `gh` (ADR-0147), also needs `task_network` + // at `allow`; `prompt` still permits an approved one. + assert!(!allows_unattended(all, true)); + for task_network in [Access::Deny, Access::Prompt] { + let networked = PermissionSet { + task_network, + ..all + }; + assert!(!allows_unattended(networked, true), "{task_network:?}"); } + let networked = PermissionSet { + task_network: Access::Allow, + ..all + }; + assert!(allows_unattended(networked, true)); + assert!(allows_unattended(networked, false)); } /// A standing-allow run is withdrawn once its preferences leave `allow`, @@ -2534,6 +2675,25 @@ mod tests { ); } + /// A run that got a review host's token is withdrawn once the workspace + /// no longer binds its profile to that host (ADR-0147); the same start + /// without a token is not. + #[cfg(target_os = "linux")] + #[test] + fn a_token_run_without_its_binding_is_withdrawn() { + let directory = tempfile::tempdir().expect("temporary directory"); + let (data, workspace_id, _journal_root, _store_id) = store(directory.path()); + let mut start = allowed_start(&data, directory.path(), workspace_id); + let control = open_control(&data).expect("control"); + assert_eq!(withdrawn(&control, &start), None); + start.github_host = Some("work".into()); + start.github_host_id = Some(Uuid::new_v4()); + assert_eq!( + withdrawn(&control, &start), + Some("the workspace no longer binds this profile to that GitHub review host") + ); + } + /// A configured cache-root change withdraws a run that holds the old /// exposure. #[cfg(target_os = "linux")] diff --git a/crates/omgcode-core/src/run/gh_token.rs b/crates/omgcode-core/src/run/gh_token.rs new file mode 100644 index 00000000..dc5ccca0 --- /dev/null +++ b/crates/omgcode-core/src/run/gh_token.rs @@ -0,0 +1,500 @@ +//! The GitHub token a bound `gh` run gets (ADR-0147). +//! +//! A workspace profile bound to a `github` review host +//! ([`crate::control::GhTokenBinding`]) gives a model command whose program +//! is that profile's `gh` the host's token as `GH_TOKEN`, with network +//! access. `gh` sends `GH_TOKEN` only to `github.com`, `*.ghe.com`, and +//! `github.localhost`, so every argument that could name another GitHub host +//! is refused, as are the commands that start other programs, change `gh`'s +//! own setup, or print a credential. The run gets an empty, read-only `gh` +//! configuration folder, and the token's bytes are replaced in what the run +//! prints. + +use std::ffi::{OsStr, OsString}; +use std::fs; +use std::path::{Path, PathBuf}; + +use crate::control::{ + ControlStore, CredentialStore, ReviewHostStatus, ToolchainProfile, Zeroizing, +}; +use crate::policy::WorkspaceId; +use crate::review_host::ReviewHostKind; +use crate::workspace::DirectoryRecord; + +use super::{RunError, native_form}; + +/// The `gh` commands a bound run may start. Each reads or changes pull +/// requests, issues, repositories, Actions runs, releases, or labels through +/// GitHub's API and starts no other program. +const ALLOWED_COMMANDS: [&str; 10] = [ + "pr", "issue", "repo", "api", "run", "workflow", "release", "search", "label", "status", +]; + +/// The allowed commands without subcommands. Every other allowed command +/// must name its subcommand directly after it, so the rules below always see +/// the subcommand `gh` runs: `gh` also accepts flags such as `--repo` before +/// the subcommand. +const LEAF_COMMANDS: [&str; 2] = ["api", "status"]; + +/// Subcommands of an allowed command that start Git. +const REFUSED_SUBCOMMANDS: [(&str, &str); 2] = [("repo", "clone"), ("pr", "checkout")]; + +/// Long flags that ask `gh` to start Git: `repo fork --clone` and `--remote`, +/// `repo create --clone`, and `issue develop --checkout`. +const GIT_FLAGS: [&str; 3] = ["--clone", "--remote", "--checkout"]; + +/// Subcommands whose `-c` short flag is `--clone` or `--checkout`. +const GIT_SHORT_SUBCOMMANDS: [(&str, &str); 2] = [("repo", "create"), ("issue", "develop")]; + +/// Flags whose value `gh` reads as a repository, `[HOST/]OWNER/REPO`, with +/// `-R` as the short form of `--repo`. +const REPOSITORY_FLAGS: [&str; 4] = ["--repo", "--source", "--template", "--branch-repo"]; + +/// Subcommands whose `-e` short flag is `--editor`, which starts a text +/// editor that would inherit the run's environment and so the token. +const EDITOR_SUBCOMMANDS: [(&str, &str); 4] = [ + ("issue", "create"), + ("issue", "comment"), + ("pr", "create"), + ("pr", "comment"), +]; + +/// Text that names a host `gh` would send `GH_TOKEN` to other than +/// `github.com`, compared without regard to case. +const OTHER_TOKEN_HOSTS: [&str; 2] = ["ghe.com", "github.localhost"]; + +/// The files `gh` reads from its configuration folder. +const CONFIG_FILES: [&str; 3] = ["config.yml", "hosts.yml", "state.yml"]; + +/// The marker that replaces the token's bytes in a run's output. +pub(crate) const REDACTED: &[u8] = b"[redacted GitHub token]"; + +/// Refusals. The command tool sends these to a model, so none names a path, +/// host address, or token. +pub(crate) const NOT_GH: &str = "a GitHub token run must start the profile's gh by its bare name"; +const NO_COMMAND: &str = "gh with a GitHub token must name one of the commands pr, issue, repo, \ + api, run, workflow, release, search, label, or status first"; +const FLAG_BEFORE_SUBCOMMAND: &str = "gh with a GitHub token needs a subcommand directly after \ + the command, before any flag"; +const STARTS_GIT: &str = "gh repo clone, gh pr checkout, and the --clone, --remote, and \ + --checkout flags start Git, which a GitHub token run does not offer"; +const OTHER_HOST: &str = "a GitHub token run reaches github.com only; an argument may not name \ + another host, a URL, or --hostname"; +const OPENS_BROWSER: &str = "the --web and -w flags open a browser, which a confined run cannot; \ + use the long form of another flag that -w abbreviates"; +const READS_ENVIRONMENT: &str = "the --jq and -q flags run a jq filter that can read the run's \ + environment, which holds the token; print JSON with --json and no filter, and use the long \ + form of another flag that -q abbreviates"; +const OPENS_EDITOR: &str = "the --editor and -e flags open a text editor, which a GitHub token \ + run does not offer; pass the text with --body or --body-file"; +const NOT_BOUND: &str = "the workspace no longer binds this profile to that GitHub review host"; +const OUTSIDE_ROOTS: &str = "the profile's gh must lie in a read-only profile root, outside the workspace and every \ + writable granted folder"; +const HOLDS_CONFIG: &str = "the folder that holds the profile's gh contains a gh configuration \ + file, so a GitHub token run cannot use it as an empty configuration"; +const HOLDS_GIT: &str = "the profile's PATH holds git, which would let gh choose a host from a \ + repository's remotes"; +const TOKEN_UNUSABLE: &str = "the review host's token cannot be passed to gh"; +const NEEDS_NETWORK: &str = "a GitHub token run needs network access"; + +/// Whether `program` is `gh` by its bare name: `gh`, or on Windows also +/// `gh.exe` in any case. +pub(crate) fn is_gh_program(program: &Path) -> bool { + let Some(name) = program.to_str() else { + return false; + }; + if cfg!(windows) { + name.eq_ignore_ascii_case("gh") || name.eq_ignore_ascii_case("gh.exe") + } else { + name == "gh" + } +} + +/// Why a bound `gh` run may not take these arguments, or `None`. +pub(crate) fn argument_refusal>(arguments: &[S]) -> Option<&'static str> { + let text: Vec<&str> = match arguments + .iter() + .map(|argument| argument.as_ref().to_str()) + .collect::>>() + { + Some(text) => text, + None => return Some(OTHER_HOST), + }; + let Some(command) = text.first() else { + return Some(NO_COMMAND); + }; + if !ALLOWED_COMMANDS.contains(command) { + return Some(NO_COMMAND); + } + // A missing subcommand is refused too: what `gh` then runs is left to + // its version's defaults. + if !LEAF_COMMANDS.contains(command) + && !text + .get(1) + .is_some_and(|subcommand| !subcommand.starts_with('-')) + { + return Some(FLAG_BEFORE_SUBCOMMAND); + } + if let Some(subcommand) = text.get(1) + && REFUSED_SUBCOMMANDS.contains(&(command, subcommand)) + { + return Some(STARTS_GIT); + } + let pair = text.get(1).map(|subcommand| (*command, *subcommand)); + let editor_short = pair.is_some_and(|pair| EDITOR_SUBCOMMANDS.contains(&pair)); + let git_short = pair.is_some_and(|pair| GIT_SHORT_SUBCOMMANDS.contains(&pair)); + let repository_positionals = + *command == "repo" || matches!(pair, Some(("label", "clone") | ("issue", "transfer"))); + for (index, argument) in text.iter().enumerate() { + let lower = argument.to_ascii_lowercase(); + let previous = index.checked_sub(1).and_then(|before| text.get(before)); + let operand = repository_operand( + previous.copied(), + argument, + repository_positionals && index >= 2, + ); + // A file flag's value is read from disk, so the host-name checks do + // not apply to it; a URL and a repository operand are still refused. + let file_value = is_file_value(previous.copied(), argument); + if lower.contains("://") + || (!file_value && OTHER_TOKEN_HOSTS.iter().any(|host| lower.contains(host))) + || flag_named(argument, "--hostname") + || operand.is_some_and(names_another_repository_host) + || (!file_value && names_another_host(argument)) + { + return Some(OTHER_HOST); + } + if GIT_FLAGS.iter().any(|flag| flag_named(argument, flag)) + || (git_short && short_flags_include(argument, 'c')) + { + return Some(STARTS_GIT); + } + // go-gh compiles a jq filter with the process environment, so + // `env.GH_TOKEN | explode` would print the token in a form the + // redaction does not match. + if flag_named(argument, "--jq") || short_flags_include(argument, 'q') { + return Some(READS_ENVIRONMENT); + } + if flag_named(argument, "--editor") || (editor_short && short_flags_include(argument, 'e')) + { + return Some(OPENS_EDITOR); + } + if flag_named(argument, "--web") || short_flags_include(argument, 'w') { + return Some(OPENS_BROWSER); + } + } + None +} + +/// The repository `argument` names, if `gh` reads it as one: the value after +/// a repository flag, joined with `=`, attached to `-R`, or as the next +/// argument; or, where the command takes repository operands, any argument +/// that is not a flag and holds no white space. +fn repository_operand<'a>( + previous: Option<&str>, + argument: &'a str, + positional: bool, +) -> Option<&'a str> { + if previous.is_some_and(|flag| flag == "-R" || REPOSITORY_FLAGS.contains(&flag)) { + return Some(argument); + } + if let Some(value) = argument.strip_prefix("-R") + && !value.is_empty() + && !value.starts_with('-') + { + return Some(value); + } + for flag in REPOSITORY_FLAGS { + if let Some(value) = argument + .strip_prefix(flag) + .and_then(|rest| rest.strip_prefix('=')) + { + return Some(value); + } + } + (positional && !argument.starts_with('-') && !argument.contains(char::is_whitespace)) + .then_some(argument) +} + +/// Whether `argument` is the value of a flag that names a local file, which +/// `gh` reads from disk and never takes as a host: `--body-file`, +/// `--notes-file`, `--input`, and `-F`, whose value is a file in `issue` and +/// `pr` and a `key=value` field in `api`. +fn is_file_value(previous: Option<&str>, argument: &str) -> bool { + previous.is_some_and(|flag| FILE_FLAGS.contains(&flag)) + || FILE_FLAGS.iter().any(|flag| { + flag.starts_with("--") + && argument + .strip_prefix(flag) + .is_some_and(|rest| rest.starts_with('=')) + }) +} + +/// Flags whose value is a local file (or, for `api -F`, a field). +const FILE_FLAGS: [&str; 4] = ["--body-file", "--notes-file", "--input", "-F"]; + +/// Whether a repository operand names a host other than `github.com`. `gh` +/// reads three `/` segments as `HOST/OWNER/REPO`, whatever the host looks +/// like, so any first segment of three or more is a host. +fn names_another_repository_host(operand: &str) -> bool { + let mut segments = operand.split('/'); + let first = segments.next().unwrap_or_default(); + segments.count() >= 2 && !first.eq_ignore_ascii_case("github.com") +} + +/// Whether any other argument, or a flag's `=value`, looks like a +/// host-qualified repository such as `example.com/owner/repo` whose host is +/// not `github.com`. This catches repository operands of commands not listed +/// above; it leaves `owner/repo`, API paths, and paths that start with `.`. +fn names_another_host(argument: &str) -> bool { + let mut candidates = vec![argument]; + if argument.starts_with('-') + && let Some((_, value)) = argument.split_once('=') + { + candidates.push(value); + } + candidates.into_iter().any(|candidate| { + let mut segments = candidate.split('/'); + let first = segments.next().unwrap_or_default(); + segments.count() >= 2 && looks_like_host(first) && !first.eq_ignore_ascii_case("github.com") + }) +} + +/// Whether `segment` could be a host name: only host characters, not +/// starting with a dot (which a file path such as `.github` does), and with a +/// dot or a port, or `localhost`. +fn looks_like_host(segment: &str) -> bool { + !segment.is_empty() + && !segment.starts_with('.') + && segment + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b':')) + && (segment.contains(['.', ':']) || segment.eq_ignore_ascii_case("localhost")) +} + +/// Whether `argument` is the long flag `name`, alone or with `=value`. +fn flag_named(argument: &str, name: &str) -> bool { + argument + .strip_prefix(name) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('=')) +} + +/// Whether `argument` is a group of short flags that includes `flag`. A value +/// attached to a short flag is counted too, which can refuse an argument that +/// only looks like one; the long form avoids that. +fn short_flags_include(argument: &str, flag: char) -> bool { + argument + .strip_prefix('-') + .is_some_and(|rest| !rest.starts_with('-') && rest.contains(flag)) +} + +/// What a bound run adds to the runner's preparation. +pub(super) struct GhTokenRun { + /// The host's name, recorded with the run. + pub(super) host: String, + /// The host's immutable identifier, recorded with the run. + pub(super) host_id: uuid::Uuid, + /// The token, kept to replace it in the run's output. + pub(super) token: Zeroizing, + /// The variables the run gets, after the profile's own. + pub(super) environment: Vec<(OsString, OsString)>, +} + +/// The inputs of [`prepare`], all read under the runner's settings lock. +pub(super) struct GhTokenRequest<'a> { + pub(super) control: &'a ControlStore, + pub(super) data_root: &'a Path, + pub(super) workspace_id: WorkspaceId, + pub(super) workspace: &'a DirectoryRecord, + pub(super) profile: &'a ToolchainProfile, + pub(super) path_entries: &'a [PathBuf], + pub(super) requested_program: &'a Path, + pub(super) program: &'a Path, + pub(super) arguments: &'a [OsString], + pub(super) network: bool, + pub(super) host: &'a str, + pub(super) host_id: Option, +} + +/// Check a bound run and read the host's token. Nothing is recorded. +/// +/// The control store must stay open across the call, as +/// [`ControlStore::load_review_host`] requires. +pub(super) fn prepare(request: &GhTokenRequest<'_>) -> Result { + if !request.network { + return Err(RunError::Refused(NEEDS_NETWORK)); + } + if !is_gh_program(request.requested_program) { + return Err(RunError::Program(NOT_GH)); + } + if let Some(reason) = argument_refusal(request.arguments) { + return Err(RunError::Refused(reason)); + } + let host = bound_host(request)?; + if request + .path_entries + .iter() + .any(|entry| super::search(Path::new("git"), std::slice::from_ref(entry)).is_some()) + { + return Err(RunError::Refused(HOLDS_GIT)); + } + let config = config_folder(request)?; + let credentials = + CredentialStore::open(request.data_root).map_err(|_| RunError::Refused(TOKEN_UNUSABLE))?; + let loaded = request + .control + .load_review_host(&credentials, host.id(), host.rest_origin()) + .map_err(|_| RunError::Refused(TOKEN_UNUSABLE))?; + let token = loaded.gh_token().ok_or(RunError::Refused(TOKEN_UNUSABLE))?; + let mut environment: Vec<(OsString, OsString)> = vec![ + ("GH_TOKEN".into(), token.as_str().into()), + ("GH_HOST".into(), "github.com".into()), + ("GH_CONFIG_DIR".into(), config.into_os_string()), + ]; + for (name, value) in [ + ("GH_PROMPT_DISABLED", "1"), + ("GH_NO_UPDATE_NOTIFIER", "1"), + ("GH_NO_EXTENSION_UPDATE_NOTIFIER", "1"), + ("GH_SPINNER_DISABLED", "1"), + ("GH_TELEMETRY", "false"), + ("DO_NOT_TRACK", "1"), + ("GH_PAGER", "cat"), + ("NO_COLOR", "1"), + ] { + environment.push((name.into(), value.into())); + } + Ok(GhTokenRun { + host: host.name().to_owned(), + host_id: host.id(), + token, + environment, + }) +} + +/// The `github` host the workspace binds this profile to, which must be the +/// one the request names, by name and by the identifier read at admission. +fn bound_host<'a>(request: &GhTokenRequest<'a>) -> Result<&'a ReviewHostStatus, RunError> { + request + .host_id + .and_then(|host_id| { + bound_github_host( + request.control, + request.workspace_id, + request.profile.id(), + request.host, + host_id, + ) + }) + .ok_or(RunError::Refused(NOT_BOUND)) +} + +/// The `github` host the workspace binds this profile to, when it has both +/// this name and this identifier. A host removed and added again under the +/// same name has another identifier, so it does not match. +pub(crate) fn bound_github_host<'a>( + control: &'a ControlStore, + workspace_id: WorkspaceId, + profile_id: uuid::Uuid, + name: &str, + host_id: uuid::Uuid, +) -> Option<&'a ReviewHostStatus> { + control + .gh_token_host(workspace_id, profile_id) + .filter(|host| { + host.name() == name && host.id() == host_id && host.kind() == ReviewHostKind::GitHub + }) +} + +/// The folder that holds the resolved `gh`, used as its configuration folder. +/// +/// It must lie in a read-only profile root and outside the workspace and +/// every granted folder the run may write, so the run cannot put a +/// configuration file there, and it must hold none now. +fn config_folder(request: &GhTokenRequest<'_>) -> Result { + let resolved = + fs::canonicalize(request.program).map_err(|_| RunError::Program(OUTSIDE_ROOTS))?; + let parent = resolved.parent().ok_or(RunError::Program(OUTSIDE_ROOTS))?; + let directory = DirectoryRecord::capture(parent)?; + let mut in_root = false; + for root in request.profile.read_only_roots() { + in_root = in_root || root.contains(&directory)?; + } + let mut writable = request.workspace.contains(&directory)?; + for folder in request.control.granted_folders(request.workspace_id) { + if folder.access().write { + writable = writable || folder.directory().contains(&directory)?; + } + } + if !in_root || writable { + return Err(RunError::Program(OUTSIDE_ROOTS)); + } + let folder = native_form(directory.live_path()?)?; + if CONFIG_FILES + .iter() + .any(|name| fs::symlink_metadata(folder.join(name)).is_ok()) + { + return Err(RunError::Refused(HOLDS_CONFIG)); + } + Ok(folder) +} + +/// Whether the runner must leave a profile variable out of a bound run, so +/// the profile cannot redirect the token, its host, or its configuration. +/// Names are compared without regard to case, as Windows compares them. +pub(super) fn replaced_variable(name: &str) -> bool { + let upper = name.to_ascii_uppercase(); + upper.starts_with("GH_") + || upper.starts_with("GITHUB_") + || upper.ends_with("_PROXY") + || matches!( + upper.as_str(), + "PAGER" + | "BROWSER" + | "EDITOR" + | "VISUAL" + | "DEBUG" + | "DO_NOT_TRACK" + | "NO_COLOR" + | "SSL_CERT_FILE" + | "SSL_CERT_DIR" + ) +} + +/// Replace every occurrence of `token` in `bytes` with [`REDACTED`], and, +/// when the output was truncated, any prefix of it that ends `bytes`, which +/// truncation inside the token leaves. +pub(super) fn redact(bytes: &[u8], token: &[u8], truncated: bool) -> Vec { + if token.is_empty() { + return bytes.to_vec(); + } + let mut output = Vec::with_capacity(bytes.len()); + let mut rest = bytes; + while let Some(index) = rest.windows(token.len()).position(|window| window == token) { + let (before, after) = rest.split_at(index); + output.extend_from_slice(before); + output.extend_from_slice(REDACTED); + rest = after.get(token.len()..).unwrap_or_default(); + } + // Only a truncated output can end inside the token, so only then is a + // trailing prefix of any length replaced. + if !truncated { + output.extend_from_slice(rest); + return output; + } + let longest = token.len().saturating_sub(1).min(rest.len()); + let tail = (1..=longest) + .rev() + .find(|length| rest.ends_with(token.get(..*length).unwrap_or_default())); + match tail { + Some(length) => { + let keep = rest.len().saturating_sub(length); + output.extend_from_slice(rest.get(..keep).unwrap_or_default()); + output.extend_from_slice(REDACTED); + } + None => output.extend_from_slice(rest), + } + output +} + +#[cfg(test)] +mod tests; diff --git a/crates/omgcode-core/src/run/gh_token/tests.rs b/crates/omgcode-core/src/run/gh_token/tests.rs new file mode 100644 index 00000000..a0420a92 --- /dev/null +++ b/crates/omgcode-core/src/run/gh_token/tests.rs @@ -0,0 +1,353 @@ +use super::*; + +fn refusal(arguments: &[&str]) -> Option<&'static str> { + argument_refusal(arguments) +} + +/// The allowed commands pass with ordinary arguments. +#[test] +fn allowed_commands_with_ordinary_arguments_pass() { + for arguments in [ + &[ + "pr", + "view", + "109", + "--repo", + "OMG-Software/OMGCode", + "--comments", + ][..], + &["pr", "diff", "109", "-R", "OMG-Software/OMGCode"], + &["issue", "list", "--state", "open", "--limit", "20"], + &["api", "repos/OMG-Software/OMGCode/pulls/109/comments"], + &["api", "graphql", "-f", "query=query { viewer { login } }"], + &["run", "list", "--workflow", "ci.yml"], + &["repo", "view", "github.com/OMG-Software/OMGCode"], + &["release", "list"], + &["search", "prs", "--author", "@me"], + &["label", "list"], + &["status"], + &["workflow", "list"], + ] { + assert_eq!(refusal(arguments), None, "{arguments:?}"); + } +} + +/// No command, another command, a global flag first, and the commands that +/// start Git are refused. +#[test] +fn other_commands_are_refused() { + for arguments in [ + &[][..], + &["auth", "token"], + &["auth", "status"], + &["alias", "set", "x", "!cmd"], + &["extension", "install", "owner/gh-x"], + &["config", "set", "pager", "more"], + &["codespace", "ssh"], + &["browse"], + &["gist", "create", "secret.txt"], + &["copilot", "suggest"], + &["--version"], + &["help"], + &["PR", "list"], + &["x-extension"], + ] { + assert_eq!(refusal(arguments), Some(NO_COMMAND), "{arguments:?}"); + } + assert_eq!(refusal(&["repo", "clone", "a/b"]), Some(STARTS_GIT)); + // A flag before the subcommand would hide it from the rules, so it is + // refused; the commands without subcommands take flags anywhere. + for arguments in [ + &["issue", "--repo=octo/example", "comment", "12", "-e"][..], + &["pr", "-R", "a/b", "checkout", "1"], + &["repo", "--help", "clone", "a/b"], + &["pr", "--", "list"], + &["pr"], + &["issue"], + ] { + assert_eq!( + refusal(arguments), + Some(FLAG_BEFORE_SUBCOMMAND), + "{arguments:?}" + ); + } + assert_eq!(refusal(&["api", "--method", "GET", "user"]), None); + assert_eq!(refusal(&["status", "--org", "octo"]), None); + assert_eq!(refusal(&["pr", "checkout", "1"]), Some(STARTS_GIT)); + // Flags that ask gh to start Git are refused too; `-c` only where it + // means `--clone` or `--checkout`. + for arguments in [ + &["repo", "fork", "owner/repo", "--clone"][..], + &["repo", "fork", "owner/repo", "--clone=true"], + &["repo", "fork", "owner/repo", "--remote"], + &["repo", "create", "name", "--public", "-c"], + &["issue", "develop", "12", "--checkout"], + &["issue", "develop", "12", "-c"], + ] { + assert_eq!(refusal(arguments), Some(STARTS_GIT), "{arguments:?}"); + } + assert_eq!( + refusal(&["repo", "fork", "owner/repo", "--remote-name", "upstream"]), + None + ); + assert_eq!(refusal(&["pr", "list", "-c"]), None); +} + +/// An argument that could send the token to another host is refused: a URL, +/// `--hostname`, and a `*.ghe.com` or `github.localhost` name in any case. +#[test] +fn another_token_host_is_refused() { + for arguments in [ + &["pr", "view", "https://github.com/a/b/pull/1"][..], + &["api", "https://example.com/x"], + &["api", "--hostname", "example.com", "user"], + &["api", "--hostname=example.com", "user"], + &["pr", "list", "--repo", "tenant.ghe.com/a/b"], + &["pr", "list", "-Rtenant.GHE.COM/a/b"], + &["repo", "view", "GitHub.localhost/a/b"], + &["api", "repos/a/b", "-H", "Host: x.ghe.com"], + &["pr", "list", "--repo", "evil.example/owner/repo"], + &["pr", "list", "--repo=evil.example/owner/repo"], + &["pr", "list", "-Revil.example/owner/repo"], + &["repo", "view", "localhost/owner/repo"], + &["repo", "view", "10.0.0.1:8443/owner/repo"], + &["issue", "list", "-R", "WWW.GITHUB.COM/owner/repo"], + // gh reads any first of three segments of a repository operand as + // its host, so a bare name such as `intranet` is a host too. + &["pr", "list", "--repo", "intranet/owner/repo"], + &["pr", "list", "--repo=intranet/owner/repo"], + &["pr", "list", "-R", "intranet/owner/repo"], + &["pr", "list", "-Rintranet/owner/repo"], + &["repo", "view", "intranet/owner/repo"], + &["repo", "delete", "--yes", "intranet/owner/repo"], + &["repo", "sync", "--source", "intranet/owner/repo"], + &["repo", "create", "name", "--template=intranet/owner/repo"], + &[ + "issue", + "develop", + "1", + "--branch-repo", + "intranet/owner/repo", + ], + &["issue", "transfer", "1", "intranet/owner/repo"], + &["label", "clone", "intranet/owner/repo"], + // A `.` path is spared only the look-alike host check: outside a + // file flag, the `ghe.com` and `github.localhost` name checks hold. + &["api", ".github.localhost/bug.md"], + &["api", ".tenant.ghe.com/a/b"], + ] { + assert_eq!(refusal(arguments), Some(OTHER_HOST), "{arguments:?}"); + } + // `github.com`, an API path, a relative file, a dot-folder file, a + // branch name, white-space text, and a field are not hosts. + for arguments in [ + &["pr", "list", "--repo", "GitHub.com/owner/repo"][..], + &["repo", "view", "github.com/owner/repo"], + &["api", "repos/owner/repo/contents/a.txt"], + &["pr", "create", "--body-file", "./notes/pr/body.md"], + &[ + "issue", + "create", + "--repo", + "owner/repo", + "--title", + "Bug", + "--body-file", + ".github/ISSUE_TEMPLATE/bug_report.md", + ], + // A file flag's value is a local path, even when its first folder + // looks like a host. + &[ + "issue", + "create", + "--repo", + "owner/repo", + "--title", + "Bug", + "--body-file", + "docs.example/templates/bug.md", + ], + &["pr", "create", "--body-file=docs.example/templates/bug.md"], + &[ + "issue", + "create", + "--repo", + "owner/repo", + "--title", + "Bug", + "--body-file", + "docs.ghe.com/templates/bug.md", + ], + &["pr", "create", "--body-file=github.localhost/bug.md"], + &[ + "release", + "create", + "v1", + "--notes-file", + "docs.example/a/notes.md", + ], + &[ + "api", + "repos/a/b/issues", + "--input", + "docs.example/a/body.json", + ], + &["pr", "view", "feature/a/b"], + &["repo", "edit", "owner/repo", "--description", "a b/c/d"], + &["api", "repos/a/b/issues", "-F", "body=@./notes/a/b.md"], + &["pr", "list", "--repo", "owner/repo"], + &["issue", "transfer", "1", "owner/repo"], + ] { + assert_eq!(refusal(arguments), None, "{arguments:?}"); + } + // `--hostnames` is not `--hostname`. + assert_eq!(refusal(&["api", "--hostnames"]), None); +} + +/// `--web`, `-w`, and a short-flag group that holds `w` are refused. +#[test] +fn browser_flags_are_refused() { + for arguments in [ + &["pr", "view", "1", "--web"][..], + &["pr", "view", "1", "--web=true"], + &["pr", "create", "-w"], + &["pr", "create", "-dw"], + ] { + assert_eq!(refusal(arguments), Some(OPENS_BROWSER), "{arguments:?}"); + } + assert_eq!(refusal(&["pr", "list", "--workflow-free"]), None); +} + +/// A jq filter, which can read the token from the environment, is refused in +/// every command. +#[test] +fn jq_filters_are_refused() { + for arguments in [ + &["api", "user", "--jq", "env.GH_TOKEN | explode"][..], + &["api", "user", "--jq=.login"], + &["pr", "list", "--json", "number", "-q", ".[]"], + &["run", "list", "-q.[]"], + &["issue", "list", "-Lq", "5"], + ] { + assert_eq!(refusal(arguments), Some(READS_ENVIRONMENT), "{arguments:?}"); + } + assert_eq!(refusal(&["pr", "list", "--json", "number"]), None); + assert_eq!(refusal(&["api", "--jqx"]), None); +} + +/// Editor mode, which starts a child that would inherit the token, is refused; +/// `-e` only where it means `--editor`. +#[test] +fn editor_flags_are_refused() { + for arguments in [ + &["issue", "comment", "12", "--editor"][..], + &["issue", "comment", "12", "-e"], + &["pr", "comment", "12", "--editor=true"], + &["pr", "create", "-de"], + &["issue", "create", "-e"], + &["api", "user", "--editor"], + ] { + assert_eq!(refusal(arguments), Some(OPENS_EDITOR), "{arguments:?}"); + } + assert_eq!(refusal(&["pr", "comment", "12", "--body", "text"]), None); + // `-e` in another command is not `--editor`. + assert_eq!(refusal(&["release", "list", "-e"]), None); +} + +/// Every refusal reads as one sentence: a line continuation lost in an edit +/// would leave a run of spaces in the text a model sees. +#[test] +fn refusal_texts_have_no_runs_of_spaces() { + for text in [ + NOT_GH, + NO_COMMAND, + FLAG_BEFORE_SUBCOMMAND, + STARTS_GIT, + OTHER_HOST, + OPENS_BROWSER, + READS_ENVIRONMENT, + OPENS_EDITOR, + NOT_BOUND, + OUTSIDE_ROOTS, + HOLDS_CONFIG, + HOLDS_GIT, + TOKEN_UNUSABLE, + NEEDS_NETWORK, + ] { + assert!(!text.contains(" "), "{text}"); + } +} + +/// Only `gh` by its bare name is the profile's `gh`. +#[test] +fn only_the_bare_name_is_gh() { + assert!(is_gh_program(Path::new("gh"))); + assert_eq!(is_gh_program(Path::new("gh.exe")), cfg!(windows)); + assert_eq!(is_gh_program(Path::new("GH")), cfg!(windows)); + for program in ["ghx", "./gh", "bin/gh", "cmd", "git"] { + assert!(!is_gh_program(Path::new(program)), "{program}"); + } +} + +/// Every whole occurrence is replaced, and, only in truncated output, a +/// prefix of any length that ends it; other text is kept. +#[test] +fn redaction_replaces_the_token_and_a_truncated_prefix() { + let token = b"ghp_0123456789abcdef"; + let marker = String::from_utf8_lossy(REDACTED).into_owned(); + let redact_text = |text: &[u8], truncated: bool| { + String::from_utf8(redact(text, token, truncated)).expect("UTF-8") + }; + + for truncated in [false, true] { + assert_eq!( + redact_text(b"a ghp_0123456789abcdef b ghp_0123456789abcdef", truncated), + format!("a {marker} b {marker}") + ); + assert_eq!(redact_text(b"nothing here", truncated), "nothing here"); + assert_eq!(redact_text(b"", truncated), ""); + assert_eq!(redact(b"abc", b"", truncated), b"abc"); + } + assert_eq!( + redact_text(b"head ghp_01234", true), + format!("head {marker}") + ); + assert_eq!(redact_text(b"head ghp_012", true), format!("head {marker}")); + assert_eq!(redact_text(b"head g", true), format!("head {marker}")); + assert_eq!(redact_text(b"head ghp_01234", false), "head ghp_01234"); +} + +/// A token shorter than eight bytes cut by truncation is still replaced. +#[test] +fn a_short_token_cut_by_truncation_is_replaced() { + let marker = String::from_utf8_lossy(REDACTED).into_owned(); + let redacted = redact(b"out abcd", b"abcdef", true); + assert_eq!( + String::from_utf8(redacted).expect("UTF-8"), + format!("out {marker}") + ); +} + +/// The variables that could redirect the token or its configuration are +/// left out of a bound run, in any case. +#[test] +fn redirecting_variables_are_replaced() { + for name in [ + "GH_TOKEN", + "gh_host", + "GH_CONFIG_DIR", + "GITHUB_TOKEN", + "GH_ENTERPRISE_TOKEN", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "PAGER", + "BROWSER", + "SSL_CERT_FILE", + ] { + assert!(replaced_variable(name), "{name}"); + } + for name in ["PATH", "LANG", "TZ", "RUSTUP_HOME"] { + assert!(!replaced_variable(name), "{name}"); + } +} diff --git a/crates/omgcode-core/src/run_journal.rs b/crates/omgcode-core/src/run_journal.rs index 886c060b..5b2cc9a7 100644 --- a/crates/omgcode-core/src/run_journal.rs +++ b/crates/omgcode-core/src/run_journal.rs @@ -200,6 +200,14 @@ pub struct RunStart { /// leaves `allow`. Approved and trusted CLI runs omit it. #[serde(default, skip_serializing_if = "is_false")] pub standing_allow: bool, + /// The `github` review host whose token a bound `gh` run got + /// (ADR-0147), by name only. Absent for every other run. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub github_host: Option, + /// That host's immutable identifier, which the watcher compares with the + /// live binding (ADR-0147). Present exactly when `github_host` is. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub github_host_id: Option, } fn is_false(value: &bool) -> bool { @@ -756,6 +764,11 @@ impl RunJournal { || start.network.as_ref().is_some_and(|network| { network.support_paths.len() > MAX_NETWORK_SUPPORT_PATHS }) + || start.github_host.as_deref().is_some_and(|host| { + start.network.is_none() || !crate::review_host::valid_review_host_name(host) + }) + || start.github_host.is_some() != start.github_host_id.is_some() + || start.github_host_id.is_some_and(|id| !valid_uuid(id)) { return Err(RunJournalError::Invalid("invalid or duplicate run start")); } diff --git a/crates/omgcode-core/src/run_journal/tests.rs b/crates/omgcode-core/src/run_journal/tests.rs index b8f9793e..9f8d7924 100644 --- a/crates/omgcode-core/src/run_journal/tests.rs +++ b/crates/omgcode-core/src/run_journal/tests.rs @@ -29,6 +29,8 @@ fn start(run_id: Uuid) -> RunStart { package_cache_root: None, model_origin: false, standing_allow: false, + github_host: None, + github_host_id: None, } } @@ -182,6 +184,45 @@ fn network_access_is_recorded_and_bounded_on_replay() { )); } +/// A bound `gh` start records its host's name and identifier together, with +/// network access; a start with one and not the other is refused on replay. +#[test] +fn a_github_host_is_recorded_with_its_identifier() { + let store = store_id(); + let support = NativePath::from_path(&std::env::temp_dir().join("hosts")).expect("native path"); + let github = |name: Option<&str>, id: Option| { + let mut start = start(Uuid::new_v4()); + start.network = Some(NetworkRecord { + support_paths: vec![support.clone()], + }); + start.github_host = name.map(str::to_owned); + start.github_host_id = id; + start + }; + let replay = |start: RunStart| { + RunJournal::apply( + &mut ReplayState::default(), + &entry( + store, + 1, + RunAction::RunStarted { + start: Box::new(start), + }, + ), + 1, + store, + ) + }; + assert!(replay(github(Some("work"), Some(Uuid::new_v4()))).is_ok()); + for refused in [ + github(Some("work"), None), + github(None, Some(Uuid::new_v4())), + github(Some("work"), Some(Uuid::nil())), + ] { + assert!(matches!(replay(refused), Err(RunJournalError::Invalid(_)))); + } +} + /// Intent and outcome pairs replay; several runs can be in flight at once. #[test] fn runs_are_recorded_and_replayed_with_several_in_flight() { diff --git a/crates/omgcode-core/src/toolchain_discovery.rs b/crates/omgcode-core/src/toolchain_discovery.rs index 2ee8d3f3..50f0fe4a 100644 --- a/crates/omgcode-core/src/toolchain_discovery.rs +++ b/crates/omgcode-core/src/toolchain_discovery.rs @@ -155,7 +155,8 @@ pub enum ProposalNote { /// Git without a network: commands that reach a remote fail. GitRemotes, /// The GitHub CLI without a network or a token: commands that call GitHub - /// fail. + /// fail unless the workspace binds the profile to a GitHub review host + /// (ADR-0147). GithubOffline, } @@ -184,7 +185,7 @@ impl ProposalNote { "Runs are offline unless the trusted CLI passes --network, and model runs never are. Commands that reach a remote, such as clone, fetch, pull, and push, fail. Git is told not to ask for a credential on a terminal; a credential helper or askpass program it is configured with can still run." } Self::GithubOffline => { - "Runs are offline unless the trusted CLI passes --network, and model runs never are, so gh commands that call GitHub, such as gh pr view, fail. The profile records no GitHub token." + "Runs are offline unless the trusted CLI passes --network. Model runs are offline too, so gh commands that call GitHub, such as gh pr view, fail, unless the workspace binds this profile to a GitHub review host, which gives its gh that host's token and network access. The profile itself records no GitHub token." } } } diff --git a/crates/omgcode-core/src/turn.rs b/crates/omgcode-core/src/turn.rs index 92f3ffb6..4482fac3 100644 --- a/crates/omgcode-core/src/turn.rs +++ b/crates/omgcode-core/src/turn.rs @@ -4841,8 +4841,58 @@ impl WorkspaceToolDispatcher<'_> { max_result_bytes, ); } - let request = - command_run_request(self.workspace_id, profile, program, arguments, cwd.as_ref()); + // A bound `gh` gets the review host's token and the network + // (ADR-0147). Its arguments and `task_network` are checked under this + // lock, before any approval is requested or consumed; the runner + // checks both again under its own. + let github_host = command_github_host(&control, self.workspace_id, profile, program); + let mut access = access; + if github_host.is_some() { + if let Some(reason) = crate::run::gh_argument_refusal(arguments) { + drop(control); + return status_result( + call, + ToolOutcome::Failed, + "gh_arguments_refused", + json!({ + "message": format!( + "{reason}. Nothing ran and no approval was requested." + ), + }), + max_result_bytes, + ); + } + let network = control + .workspace(self.workspace_id) + .map_or(Access::Deny, |workspace| { + workspace.permissions().task_network + }); + if !network.permits() { + drop(control); + return status_result( + call, + ToolOutcome::Failed, + "github_network_disabled", + json!({ + "message": "This profile's gh is bound to a GitHub token, but the \ + workspace task_network preference is off, so gh cannot reach \ + GitHub. Nothing ran and no approval was requested. Do not retry; \ + tell the user that the operator must enable task networking for \ + this workspace.", + }), + max_result_bytes, + ); + } + access = access.most_restrictive(network); + } + let request = command_run_request( + self.workspace_id, + profile, + program, + arguments, + cwd.as_ref(), + github_host.as_ref().map(|(name, id)| (name.as_str(), *id)), + ); let digest = command_digest(self.session_id, &request); if access == Access::Allow { // The live preference, read under the settings lock that admitted @@ -5084,13 +5134,15 @@ fn platform_profile_names(control: &ControlStore, workspace_id: WorkspaceId) -> /// This is the only place that turns parsed command arguments into a /// [`crate::run::RunRequest`]. Dispatch runs and digests the result, and /// approval review recomputes the same digest from it, so the two cannot -/// diverge. Network and host services are always off and the limits are fixed. +/// diverge. Host services are always off and the limits are fixed. Network is +/// on only for a bound `gh`, which gets `github_host`'s token (ADR-0147). fn command_run_request( workspace_id: WorkspaceId, profile: &str, program: &str, arguments: &[String], cwd: Option<&String>, + github_host: Option<(&str, Uuid)>, ) -> crate::run::RunRequest { crate::run::RunRequest { workspace_id, @@ -5099,9 +5151,11 @@ fn command_run_request( arguments: arguments.iter().map(OsString::from).collect(), working_directory: cwd.map(PathBuf::from), host_services: false, - network: false, + network: github_host.is_some(), model_tools: true, standing_allow: false, + github_host: github_host.map(|(name, _)| name.to_owned()), + github_host_id: github_host.map(|(_, id)| id), limits: command_limits(), } } @@ -5162,9 +5216,37 @@ fn command_digest(session_id: Uuid, request: &crate::run::RunRequest) -> String for number in numbers { push_field(&mut bytes, &number.to_le_bytes()); } + // Appended only for a bound `gh` (ADR-0147), so every other command's + // digest is unchanged. + if let Some(host) = &request.github_host { + push_field(&mut bytes, b"github-token"); + push_field(&mut bytes, host.as_bytes()); + if let Some(id) = request.github_host_id { + push_field(&mut bytes, id.as_bytes()); + } + } sha256_hex(&bytes) } +/// The `github` review host whose token a model command gets (ADR-0147), by +/// name and identifier: the program is `gh` by its bare name and the +/// workspace binds the named profile to the host. `None` otherwise, and the +/// command runs as before. +pub(crate) fn command_github_host( + control: &ControlStore, + workspace_id: WorkspaceId, + profile: &str, + program: &str, +) -> Option<(String, Uuid)> { + if !crate::run::is_gh_program(Path::new(program)) { + return None; + } + let profile_id = control.profile(profile)?.profile().id(); + control + .gh_token_host(workspace_id, profile_id) + .map(|host| (host.name().to_owned(), host.id())) +} + fn push_field(bytes: &mut Vec, value: &[u8]) { bytes.extend(u64::try_from(value.len()).unwrap_or(u64::MAX).to_le_bytes()); bytes.extend(value); diff --git a/crates/omgcode-core/src/turn/review.rs b/crates/omgcode-core/src/turn/review.rs index 6c7e3076..257c6de9 100644 --- a/crates/omgcode-core/src/turn/review.rs +++ b/crates/omgcode-core/src/turn/review.rs @@ -21,9 +21,10 @@ use super::git_write_tool; use super::granted_folder; use super::{ PreparedEdit, ReadRequest, TextEdit, ToolArguments, ToolCall, ToolName, artifact, - command_digest, command_run_request, create_digest, create_directory_digest, delete_digest, - edit_digest, edit_target, is_hidden_format, list_parent, multi_edit_digest, normalized_path, - prepare_edit, prepare_multi_edit, read_edit_source, rename_digest, web_fetch_digest, + command_digest, command_github_host, command_run_request, create_digest, + create_directory_digest, delete_digest, edit_digest, edit_target, is_hidden_format, + list_parent, multi_edit_digest, normalized_path, prepare_edit, prepare_multi_edit, + read_edit_source, rename_digest, web_fetch_digest, }; use crate::control::{ ApprovalOperation, ApprovalStatus, ControlError, ControlStore, ReviewedHost, WebHostRefusal, @@ -245,8 +246,9 @@ pub fn review_approval( } let found = match approval.operation { ApprovalOperation::Command => { + let found = review_command(&control, approval, relevant); drop(control); - review_command(approval, relevant) + found } ApprovalOperation::FileRead => { let found = review_file_read(&control, approval, relevant); @@ -286,6 +288,7 @@ fn parse_candidate(candidate: &ReviewCandidate<'_>, tool: ToolName) -> Option( + control: &ControlStore, approval: &ApprovalStatus, candidates: impl Iterator>, ) -> Option { @@ -302,12 +305,17 @@ fn review_command<'a>( else { continue; }; + // The binding is read from the settings the approval was requested + // under (the revision is checked above), so a bound `gh` reproduces + // its digest with the host's name in it (ADR-0147). + let github_host = command_github_host(control, approval.workspace_id, profile, program); let request = command_run_request( approval.workspace_id, profile, program, arguments, cwd.as_ref(), + github_host.as_ref().map(|(name, id)| (name.as_str(), *id)), ); if command_digest(approval.session_id, &request) == approval.request_sha256 { return Some(ReviewedRequest { @@ -869,7 +877,7 @@ fn command_fields(request: &crate::run::RunRequest) -> Vec { limits.max_stdout_bytes, limits.max_stderr_bytes ) }; - vec![ + let mut fields = vec![ single("Profile", display_safe_line(&request.profile)), single( "Program", @@ -888,7 +896,22 @@ fn command_fields(request: &crate::run::RunRequest) -> Vec { format!("{} seconds", limits.deadline.as_secs()), ), single("Output limit", output), - ] + ]; + // A bound `gh` gets a review host's token (ADR-0147). The field sits + // beside Network so the reviewer sees both. + if let Some(host) = &request.github_host { + fields.insert( + 5, + single( + "GitHub token", + format!( + "review host {}, sent by gh to github.com", + display_safe_line(host) + ), + ), + ); + } + fields } /// Edit fields. The path, sizes, and digests come from the prepared edit and diff --git a/crates/omgcode-core/tests/approval_review.rs b/crates/omgcode-core/tests/approval_review.rs index d2a6754b..6c13dadd 100644 --- a/crates/omgcode-core/tests/approval_review.rs +++ b/crates/omgcode-core/tests/approval_review.rs @@ -1763,3 +1763,203 @@ fn a_network_approval_needs_no_writers_stopped_acknowledgement() { drop(control); assert_eq!(fixture.state(approval.id), ApprovalState::Approved); } + +/// A `github` review host recorded with a token, and the workspace's `gh` +/// profile bound to it (ADR-0147). The token's native item is deleted when +/// this is dropped, also after a failed assertion. +struct BoundGh { + data: PathBuf, +} + +impl BoundGh { + /// Record a `gh` profile, a `github` host named `work`, and the binding, + /// with the workspace's `task_network` preference set to `task_network`. + fn new(fixture: &Fixture, task_network: Access) -> Self { + let tools = fixture.data.with_file_name("gh-tools"); + fs::create_dir_all(&tools).expect("create the gh root"); + let credentials = + omgcode_core::control::CredentialStore::open(&fixture.data).expect("credential store"); + let mut control = ControlStore::open_existing(&fixture.data) + .expect("open control") + .expect("control store"); + let permissions = control + .workspace(fixture.workspace_id) + .expect("workspace") + .permissions(); + control + .set_permissions( + fixture.workspace_id, + PermissionSet { + task_network, + ..permissions + }, + control.revision(), + ) + .expect("set task_network"); + control + .add_profile( + &ProfileDeclaration { + name: "gh".into(), + read_only_roots: vec![tools], + path_entries: Vec::new(), + environment: Vec::new(), + }, + control.revision(), + ) + .expect("declare the gh profile"); + control + .assign_profile(fixture.workspace_id, "gh", control.revision()) + .expect("assign the gh profile"); + let token = omgcode_core::control::Secret::new(b"github_pat_omgcode_test_0147".to_vec()) + .expect("token"); + let guard = Self { + data: fixture.data.clone(), + }; + let _added = control + .add_review_host( + &credentials, + &omgcode_core::control::NewReviewHost { + name: "work", + kind: omgcode_core::review_host::ReviewHostKind::GitHub, + base_url: None, + organization: None, + }, + &token, + control.revision(), + ) + .expect("record the review host"); + control + .bind_gh_token(fixture.workspace_id, "gh", "work", control.revision()) + .expect("bind the gh profile"); + guard + } + + /// End the binding, which changes the settings revision. + fn unbind(&self, workspace_id: WorkspaceId) { + let mut control = ControlStore::open_existing(&self.data) + .expect("open control") + .expect("control store"); + control + .unbind_gh_token(workspace_id, "gh", control.revision()) + .expect("unbind"); + } +} + +impl Drop for BoundGh { + fn drop(&mut self) { + let Ok(credentials) = omgcode_core::control::CredentialStore::open(&self.data) else { + return; + }; + let Ok(Some(mut control)) = ControlStore::open_existing(&self.data) else { + return; + }; + let revision = control.revision(); + if let Ok(unbinding) = control.unbind_review_host("work", revision) { + drop(control); + let _ = unbinding.finish(&credentials); + } + } +} + +/// A command whose program is the bound profile's `gh` is reviewed with +/// network on and the host whose token it gets; an unbound `gh` keeps the +/// offline fields. Ending the binding makes the approval stale. +#[test] +fn a_bound_gh_command_reviews_its_network_and_token_host() { + let mut fixture = Fixture::new(); + let bound = BoundGh::new(&fixture, Access::Prompt); + fixture.turn(vec![command_call( + "gh-1", + json!({"profile": "gh", "program": "gh", "arguments": ["pr", "list"]}), + )]); + let approval = fixture.pending(ApprovalOperation::Command); + let recorded = fixture.recorded(); + + let request = exact(fixture.review(&approval, &recorded)); + let labels: Vec<&str> = request.fields.iter().map(|field| field.label).collect(); + assert_eq!( + labels, + [ + "Profile", + "Program", + "Arguments", + "Working directory", + "Network", + "GitHub token", + "Host services", + "Time limit", + "Output limit", + ] + ); + assert_eq!(field(&request, "Network").value, "on"); + assert_eq!( + field(&request, "GitHub token").value, + "review host work, sent by gh to github.com" + ); + // The token itself is in no field. + assert!( + request + .fields + .iter() + .all(|field| !field.value.contains("github_pat_omgcode_test_0147")) + ); + + bound.unbind(fixture.workspace_id); + assert!(!matches!( + fixture.review(&approval, &recorded), + Ok(ApprovalReview::Exact(_)) + )); +} + +/// With `task_network` off, or with arguments the `gh` rules refuse, a bound +/// `gh` is answered before any approval is requested. +#[test] +fn a_bound_gh_is_refused_before_an_approval() { + let mut fixture = Fixture::new(); + let _bound = BoundGh::new(&fixture, Access::Deny); + fixture.turn(vec![command_call( + "gh-1", + json!({"profile": "gh", "program": "gh", "arguments": ["pr", "list"]}), + )]); + assert!(fixture.approvals().is_empty()); + assert!( + fixture + .journal + .snapshot() + .messages + .iter() + .any(|message| message.text.contains("github_network_disabled")) + ); + + let mut control = ControlStore::open_existing(&fixture.data) + .expect("open control") + .expect("control store"); + let permissions = control + .workspace(fixture.workspace_id) + .expect("workspace") + .permissions(); + control + .set_permissions( + fixture.workspace_id, + PermissionSet { + task_network: Access::Prompt, + ..permissions + }, + control.revision(), + ) + .expect("set task_network"); + drop(control); + fixture.turn(vec![command_call( + "gh-2", + json!({"profile": "gh", "program": "gh", "arguments": ["auth", "token"]}), + )]); + assert!(fixture.approvals().is_empty()); + assert!( + fixture + .journal + .snapshot() + .messages + .iter() + .any(|message| message.text.contains("gh_arguments_refused")) + ); +} diff --git a/crates/omgcode-desktop/capabilities/settings.json b/crates/omgcode-desktop/capabilities/settings.json index c4c97cc7..bde01288 100644 --- a/crates/omgcode-desktop/capabilities/settings.json +++ b/crates/omgcode-desktop/capabilities/settings.json @@ -16,6 +16,7 @@ "allow-settings-add-toolchain-profile", "allow-settings-add-web-fetch-host", "allow-settings-assign-toolchain-profile", + "allow-settings-bind-gh-token", "allow-settings-cancel-chatgpt-sign-in", "allow-settings-chatgpt-sign-in-address", "allow-settings-choose-package-cache", @@ -53,6 +54,7 @@ "allow-settings-sign-in-chatgpt", "allow-settings-sign-out-chatgpt", "allow-settings-unassign-toolchain-profile", + "allow-settings-unbind-gh-token", "allow-settings-unregister-workspace" ] } diff --git a/crates/omgcode-desktop/src/command_names.rs b/crates/omgcode-desktop/src/command_names.rs index 7cdd5305..5de33718 100644 --- a/crates/omgcode-desktop/src/command_names.rs +++ b/crates/omgcode-desktop/src/command_names.rs @@ -77,6 +77,8 @@ pub const COMMAND_NAMES: &[&str] = &[ "settings_add_discovered_profiles", "settings_assign_toolchain_profile", "settings_unassign_toolchain_profile", + "settings_bind_gh_token", + "settings_unbind_gh_token", "settings_add_claude_code", "settings_grant_claude_code", "settings_revoke_claude_code", diff --git a/crates/omgcode-desktop/src/commands/settings.rs b/crates/omgcode-desktop/src/commands/settings.rs index 555d949c..480ecb1e 100644 --- a/crates/omgcode-desktop/src/commands/settings.rs +++ b/crates/omgcode-desktop/src/commands/settings.rs @@ -14,13 +14,14 @@ use omgcode_app::desktop::{ ChatGptSignInAddress, ChatGptSignOutResult, ClaudeCodeAddRequest, ClaudeCodeConnectionRequest, ConnectionAddRequest, ConnectionRemoveRequest, ConnectionSelectRequest, ContainerAccessChoice, ContainerGrantRequest, ContainerRevokeRequest, DiscoveredProfilesRequest, EnvironmentEntry, - FolderAddRequest, FolderRemoveRequest, FolderSetRequest, GitIdentityRequest, - GitWorkerGrantRequest, NewConnectionKind, PackageProfileAddRequest, PermissionFlags, - PermissionsChangeRequest, ProfileAssignmentRequest, ProfileRemoveRequest, ReviewHostAddRequest, - ReviewHostKind, ReviewHostRemoveRequest, ReviewHostTokenRequest, SettingsOverview, - SettingsRevisionRequest, SkillChoice, SkillRemoveRequest, SkillStateRequest, - ToolchainDiscovery, ToolchainDiscoveryRequest, ToolchainProfileAddRequest, - WebHostChangeRequest, WorkspaceInstructionsRequest, WorkspaceRevisionRequest, discovery_host, + FolderAddRequest, FolderRemoveRequest, FolderSetRequest, GhTokenBindRequest, + GhTokenUnbindRequest, GitIdentityRequest, GitWorkerGrantRequest, NewConnectionKind, + PackageProfileAddRequest, PermissionFlags, PermissionsChangeRequest, ProfileAssignmentRequest, + ProfileRemoveRequest, ReviewHostAddRequest, ReviewHostKind, ReviewHostRemoveRequest, + ReviewHostTokenRequest, SettingsOverview, SettingsRevisionRequest, SkillChoice, + SkillRemoveRequest, SkillStateRequest, ToolchainDiscovery, ToolchainDiscoveryRequest, + ToolchainProfileAddRequest, WebHostChangeRequest, WorkspaceInstructionsRequest, + WorkspaceRevisionRequest, discovery_host, }; use tauri::Webview; use uuid::Uuid; @@ -812,6 +813,65 @@ pub async fn settings_unassign_toolchain_profile( .await } +/// `settings` only. After a native confirmation that names the workspace, +/// the profile, and the review host, binds the profile's `gh` to the host's +/// token (ADR-0147). The token never reaches the window. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error (`unknown_workspace`, +/// `cancelled`, `stale_revision`, or `control` with core's reason). +#[tauri::command(rename_all = "snake_case")] +pub async fn settings_bind_gh_token( + webview: Webview, + state: Service<'_>, + revision: u64, + workspace_id: Uuid, + profile: String, + host: String, +) -> Result { + authorize(Command::SettingsBindGhToken, webview.label())?; + let prompt = NativePrompt::new(webview.window()); + let request = GhTokenBindRequest { + revision, + workspace_id, + profile, + host, + }; + blocking(&state, move |service| { + service.settings_bind_gh_token(request, &prompt) + }) + .await +} + +/// `settings` only. Ends a profile's GitHub token binding without a dialog, +/// because it narrows access, and stops the runs that used it (ADR-0147). +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error (`unknown_workspace`, +/// `stale_revision`, `runs_not_stopped`, `runs_unchecked`, or `control` with +/// core's reason). +#[tauri::command(rename_all = "snake_case")] +pub async fn settings_unbind_gh_token( + webview: Webview, + state: Service<'_>, + revision: u64, + workspace_id: Uuid, + profile: String, +) -> Result { + authorize(Command::SettingsUnbindGhToken, webview.label())?; + let request = GhTokenUnbindRequest { + revision, + workspace_id, + profile, + }; + blocking(&state, move |service| { + service.settings_unbind_gh_token(request) + }) + .await +} + /// `settings` only. After a native confirmation that lists the origins core /// parsed, records a package-network profile (configuration only) as `omgcode /// workspace package-profile-add` does (ADR-0088). diff --git a/crates/omgcode-desktop/src/lib.rs b/crates/omgcode-desktop/src/lib.rs index 12fa43c4..f6adc5f7 100644 --- a/crates/omgcode-desktop/src/lib.rs +++ b/crates/omgcode-desktop/src/lib.rs @@ -261,6 +261,8 @@ fn run_app(service: Arc) -> ExitCode { commands::settings::settings_add_discovered_profiles, commands::settings::settings_assign_toolchain_profile, commands::settings::settings_unassign_toolchain_profile, + commands::settings::settings_bind_gh_token, + commands::settings::settings_unbind_gh_token, commands::settings::settings_add_review_host, commands::settings::settings_set_review_host_token, commands::settings::settings_remove_review_host, diff --git a/crates/omgcode-desktop/src/policy.rs b/crates/omgcode-desktop/src/policy.rs index e4fce4f8..76923f3b 100644 --- a/crates/omgcode-desktop/src/policy.rs +++ b/crates/omgcode-desktop/src/policy.rs @@ -112,6 +112,8 @@ pub enum Command { SettingsAddDiscoveredProfiles, SettingsAssignToolchainProfile, SettingsUnassignToolchainProfile, + SettingsBindGhToken, + SettingsUnbindGhToken, SettingsAddClaudeCode, SettingsGrantClaudeCode, SettingsRevokeClaudeCode, @@ -136,7 +138,7 @@ pub enum Command { impl Command { /// All commands, in the order of `command_names.rs`. - pub const ALL: [Self; 93] = [ + pub const ALL: [Self; 95] = [ Self::AppInfo, Self::SessionTree, Self::SessionSearch, @@ -210,6 +212,8 @@ impl Command { Self::SettingsAddDiscoveredProfiles, Self::SettingsAssignToolchainProfile, Self::SettingsUnassignToolchainProfile, + Self::SettingsBindGhToken, + Self::SettingsUnbindGhToken, Self::SettingsAddClaudeCode, Self::SettingsGrantClaudeCode, Self::SettingsRevokeClaudeCode, @@ -309,6 +313,8 @@ impl Command { Self::SettingsAddDiscoveredProfiles => "settings_add_discovered_profiles", Self::SettingsAssignToolchainProfile => "settings_assign_toolchain_profile", Self::SettingsUnassignToolchainProfile => "settings_unassign_toolchain_profile", + Self::SettingsBindGhToken => "settings_bind_gh_token", + Self::SettingsUnbindGhToken => "settings_unbind_gh_token", Self::SettingsAddClaudeCode => "settings_add_claude_code", Self::SettingsGrantClaudeCode => "settings_grant_claude_code", Self::SettingsRevokeClaudeCode => "settings_revoke_claude_code", @@ -377,6 +383,8 @@ impl Command { | Self::SettingsAddDiscoveredProfiles | Self::SettingsAssignToolchainProfile | Self::SettingsUnassignToolchainProfile + | Self::SettingsBindGhToken + | Self::SettingsUnbindGhToken | Self::SettingsAddClaudeCode | Self::SettingsGrantClaudeCode | Self::SettingsRevokeClaudeCode @@ -466,10 +474,10 @@ mod tests { #[test] fn every_command_has_exactly_one_window_and_the_counts_match() { - assert_eq!(Command::ALL.len(), 93); + assert_eq!(Command::ALL.len(), 95); assert_eq!(with_window(WindowLabel::Main).len(), 43); assert_eq!(with_window(WindowLabel::Approvals).len(), 3); - assert_eq!(with_window(WindowLabel::Settings).len(), 47); + assert_eq!(with_window(WindowLabel::Settings).len(), 49); } #[test] @@ -615,8 +623,8 @@ mod tests { #[test] fn shared_name_list_has_unique_names_matching_the_enum() { let shared: BTreeSet<&str> = COMMAND_NAMES.iter().copied().collect(); - assert_eq!(COMMAND_NAMES.len(), 93); - assert_eq!(shared.len(), 93); + assert_eq!(COMMAND_NAMES.len(), 95); + assert_eq!(shared.len(), 95); let from_enum: Vec<&str> = Command::ALL.iter().map(|c| c.name()).collect(); assert_eq!(from_enum, COMMAND_NAMES); } diff --git a/crates/omgcode-desktop/tests/layers.rs b/crates/omgcode-desktop/tests/layers.rs index 4cada4b0..b9920f7a 100644 --- a/crates/omgcode-desktop/tests/layers.rs +++ b/crates/omgcode-desktop/tests/layers.rs @@ -170,6 +170,7 @@ fn settings_window_is_granted_only_its_own_commands() { "allow-settings-add-toolchain-profile", "allow-settings-add-web-fetch-host", "allow-settings-assign-toolchain-profile", + "allow-settings-bind-gh-token", "allow-settings-cancel-chatgpt-sign-in", "allow-settings-chatgpt-sign-in-address", "allow-settings-choose-package-cache", @@ -207,6 +208,7 @@ fn settings_window_is_granted_only_its_own_commands() { "allow-settings-sign-in-chatgpt", "allow-settings-sign-out-chatgpt", "allow-settings-unassign-toolchain-profile", + "allow-settings-unbind-gh-token", "allow-settings-unregister-workspace", ] ); @@ -278,15 +280,15 @@ fn build_script_declares_the_shared_command_list() { assert!(build.contains("include!(\"src/command_names.rs\")")); assert!(build.contains(".commands(COMMAND_NAMES)")); - // And the shared list holds the 93 unique policy names. + // And the shared list holds the 95 unique policy names. let listed: Vec<&str> = COMMAND_NAMES_SOURCE .lines() .filter_map(|line| line.trim().strip_prefix('"')) .filter_map(|rest| rest.strip_suffix("\",")) .collect(); let unique: BTreeSet<&str> = listed.iter().copied().collect(); - assert_eq!(listed.len(), 93); - assert_eq!(unique.len(), 93); + assert_eq!(listed.len(), 95); + assert_eq!(unique.len(), 95); let policy: Vec<&str> = Command::ALL.into_iter().map(Command::name).collect(); assert_eq!(listed, policy); } @@ -397,7 +399,7 @@ fn frontend_clients_call_only_commands_the_policy_gives_their_window() { .collect(); assert_eq!(settings_calls, settings_commands); - // Together they cover all 93 policy commands. + // Together they cover all 95 policy commands. let union: BTreeSet = main_calls .union(&approval_calls) .cloned() @@ -655,10 +657,10 @@ fn generate_handler_registers_exactly_the_policy_commands() { .map(|entry| entry.rsplit("::").next().expect("segment")) .collect(); - // Then they are the 93 shared names, once each. + // Then they are the 95 shared names, once each. let unique: BTreeSet<&str> = registered.iter().copied().collect(); - assert_eq!(registered.len(), 93); - assert_eq!(unique.len(), 93); + assert_eq!(registered.len(), 95); + assert_eq!(unique.len(), 95); let shared: BTreeSet<&str> = COMMAND_NAMES_SOURCE .lines() .filter_map(|line| line.trim().strip_prefix('"')) @@ -675,7 +677,7 @@ fn generate_handler_registers_exactly_the_policy_commands() { #[test] fn every_handler_authorizes_its_own_command_before_touching_the_service() { let handlers = all_handlers(); - assert_eq!(handlers.len(), 93); + assert_eq!(handlers.len(), 95); for handler in handlers { // Given the command the function name denotes. let command = Command::ALL @@ -809,7 +811,7 @@ fn handler_parameters_match_the_keys_the_frontend_passes() { } assert_eq!( expected.len(), - 93, + 95, "all commands are called by the frontend" ); diff --git a/crates/omgcode-desktop/ui/src/ipc/settings_client.ts b/crates/omgcode-desktop/ui/src/ipc/settings_client.ts index a5ca6117..857341db 100644 --- a/crates/omgcode-desktop/ui/src/ipc/settings_client.ts +++ b/crates/omgcode-desktop/ui/src/ipc/settings_client.ts @@ -341,4 +341,23 @@ export const settingsApi = { workspace_id: workspaceId, name, }), + /** + * Binds a toolchain profile's `gh` to a `github` review host's token (ADR-0147) after a system + * confirmation that names the workspace, the profile, and the host. Sends names only; the token + * never reaches the window. + */ + bindGhToken: (revision: number, workspaceId: string, profile: string, host: string) => + invokeCommand("settings_bind_gh_token", { + revision, + workspace_id: workspaceId, + profile, + host, + }), + /** Ends a profile's token binding. It narrows access, so no dialog opens; Rust stops its runs. */ + unbindGhToken: (revision: number, workspaceId: string, profile: string) => + invokeCommand("settings_unbind_gh_token", { + revision, + workspace_id: workspaceId, + profile, + }), }; diff --git a/crates/omgcode-desktop/ui/src/ipc/types.ts b/crates/omgcode-desktop/ui/src/ipc/types.ts index 5b88b8ad..88af8883 100644 --- a/crates/omgcode-desktop/ui/src/ipc/types.ts +++ b/crates/omgcode-desktop/ui/src/ipc/types.ts @@ -493,6 +493,12 @@ export interface FolderFlags { execute: boolean; } +/** One toolchain profile of a workspace bound to a review host's token (ADR-0147). */ +export interface GhTokenBindingView { + profile: string; + host: string; +} + export interface WorkspaceSettingsView { workspace_id: string; folder_display: string; @@ -522,6 +528,11 @@ export interface WorkspaceSettingsView { * (ADR-0107). Its commands can use only these. */ profiles: string[]; + /** + * The workspace's GitHub token bindings (ADR-0147): a toolchain profile whose `gh` gets the + * token of a `github` review host. Names only; the token stays in Rust. + */ + gh_token_bindings: GhTokenBindingView[]; package_cache_root: string | null; /** The workspace's custom instructions (ADR-0080); `null` when the saved file is unreadable. */ instructions: string | null; diff --git a/crates/omgcode-desktop/ui/src/mock/backend.ts b/crates/omgcode-desktop/ui/src/mock/backend.ts index 61a2bb8e..43e8038a 100644 --- a/crates/omgcode-desktop/ui/src/mock/backend.ts +++ b/crates/omgcode-desktop/ui/src/mock/backend.ts @@ -1354,6 +1354,7 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok create_directory: "allow", }, profiles: [], + gh_token_bindings: [], package_cache_root: null, instructions: "", instructions_max_bytes: 0, @@ -1895,7 +1896,13 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok if (index < 0) { fail("control", "review host is not recorded"); } - settings.review_hosts.splice(index, 1); + const [removed] = settings.review_hosts.splice(index, 1); + // Like core (ADR-0147): a binding to the removed host ends with it. + for (const workspace of settings.workspaces) { + workspace.gh_token_bindings = workspace.gh_token_bindings.filter( + (binding) => binding.host !== removed?.name, + ); + } }); // The mock stands in for the native folder dialogs and confirmations (ADR-0088): each // root, PATH entry, or granted folder "chosen" is the next sample folder, and every @@ -1978,6 +1985,34 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok } mockUnassign(workspace, profile); }); + // Like core (ADR-0147): the profile must be assigned and the host of kind `github`; the + // system confirmation that names them is accepted here. + case "settings_bind_gh_token": + return changeSettings(args, () => { + const workspace = mockWorkspace(args); + const profile = mockProfile(str(args, "profile")); + if (!mockAssigned(workspace, profile.name)) { + fail("control", "the toolchain profile is not assigned to this workspace"); + } + const host = settings.review_hosts.find((entry) => entry.name === str(args, "host")); + if (host === undefined) { + fail("control", "review host is not recorded"); + } + if (host.kind !== "github") { + fail("control", "only a review host of kind github (github.com) can give gh a token"); + } + mockUnbind(workspace, profile.name); + workspace.gh_token_bindings.push({ profile: profile.name, host: host.name }); + }); + case "settings_unbind_gh_token": + return changeSettings(args, () => { + const workspace = mockWorkspace(args); + const profile = mockProfile(str(args, "profile")); + if (!workspace.gh_token_bindings.some((b) => mockSameName(b.profile, profile.name))) { + fail("control", "this workspace profile has no GitHub token binding"); + } + mockUnbind(workspace, profile.name); + }); case "settings_add_package_profile": return changeSettings(args, () => { const name = str(args, "name"); @@ -2577,6 +2612,17 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok return workspace.profiles.some((p) => p.toLowerCase() === name.toLowerCase()); } + function mockSameName(left: string, right: string): boolean { + return left.toLowerCase() === right.toLowerCase(); + } + + /** Ends the GitHub token binding of `name` in `workspace`, if any (ADR-0147). */ + function mockUnbind(workspace: WorkspaceSettingsView, name: string): void { + workspace.gh_token_bindings = workspace.gh_token_bindings.filter( + (binding) => !mockSameName(binding.profile, name), + ); + } + function mockGrantId(): string { grantsMade += 1; return `00000000-0000-4000-8001-${String(grantsMade).padStart(12, "0")}`; @@ -2601,6 +2647,8 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok workspace.profiles = workspace.profiles.filter( (name) => name.toLowerCase() !== profile.name.toLowerCase(), ); + // Like core (ADR-0147): the binding of an unassigned profile ends with the assignment. + mockUnbind(workspace, profile.name); const needs = settings.toolchain_profiles .filter((other) => mockAssigned(workspace, other.name)) .flatMap((other) => other.read_only_roots); @@ -2799,6 +2847,7 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok create_directory: "allow", }, profiles: [], + gh_token_bindings: [], package_cache_root: null, instructions: "Run the tests before answering.", instructions_max_bytes: 0, @@ -2826,6 +2875,7 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok create_directory: "allow", }, profiles: [], + gh_token_bindings: [], package_cache_root: null, instructions: "", instructions_max_bytes: 0, diff --git a/crates/omgcode-desktop/ui/src/settings/app.ts b/crates/omgcode-desktop/ui/src/settings/app.ts index 98554c4d..1eb071d8 100644 --- a/crates/omgcode-desktop/ui/src/settings/app.ts +++ b/crates/omgcode-desktop/ui/src/settings/app.ts @@ -190,6 +190,10 @@ const ACTIONS: Omit = { settingsApi.assignToolchainProfile(revision, workspaceId, name), unassignToolchainProfile: (workspaceId, name) => (revision) => settingsApi.unassignToolchainProfile(revision, workspaceId, name), + bindGhToken: (workspaceId, profile, host) => (revision) => + settingsApi.bindGhToken(revision, workspaceId, profile, host), + unbindGhToken: (workspaceId, profile) => (revision) => + settingsApi.unbindGhToken(revision, workspaceId, profile), }; /** diff --git a/crates/omgcode-desktop/ui/src/settings/context.ts b/crates/omgcode-desktop/ui/src/settings/context.ts index 13ce336b..f4fa9486 100644 --- a/crates/omgcode-desktop/ui/src/settings/context.ts +++ b/crates/omgcode-desktop/ui/src/settings/context.ts @@ -148,6 +148,13 @@ export interface Actions { assignToolchainProfile(workspaceId: string, name: string): Change; /** Unassigns a toolchain profile and revokes the grants it alone needed; Rust confirms natively. */ unassignToolchainProfile(workspaceId: string, name: string): Change; + /** + * Gives a workspace profile's `gh` the token of a `github` review host (ADR-0147). Rust names + * the workspace, profile, and host in a system confirmation; the confirmation is the consent. + */ + bindGhToken(workspaceId: string, profile: string, host: string): Change; + /** Ends the binding. It narrows access, so Rust asks nothing and stops the runs that used it. */ + unbindGhToken(workspaceId: string, profile: string): Change; } /** diff --git a/crates/omgcode-desktop/ui/src/settings/workspace_profiles.ts b/crates/omgcode-desktop/ui/src/settings/workspace_profiles.ts index 509142f2..25b0bd94 100644 --- a/crates/omgcode-desktop/ui/src/settings/workspace_profiles.ts +++ b/crates/omgcode-desktop/ui/src/settings/workspace_profiles.ts @@ -24,11 +24,71 @@ function assigned(workspace: WorkspaceSettingsView, name: string): boolean { return workspace.profiles.some((profile) => profile.toLowerCase() === wanted); } -function profileSwitch( +/** What the token select shows for no binding. */ +export const GH_TOKEN_NONE = "None"; + +/** Shown instead of the select when no `github` review host is recorded. */ +export const GH_TOKEN_NOTE = "To give gh a GitHub token, add a GitHub review host under Reviews."; + +/** The accessible name of one profile's GitHub token select. */ +export function ghTokenLabel(name: string): string { + return `GitHub token for ${name}`; +} + +/** + * One assigned profile's GitHub token control (ADR-0147): a select of "None" and each recorded + * `github` review host by name, showing the recorded binding. Choosing a host asks Rust to bind + * it, after a system confirmation; choosing "None" asks Rust to unbind it. The window sends names + * only, and the select shows the recorded state again after every change. + */ +function ghTokenRow( workspace: WorkspaceSettingsView, profile: ToolchainProfileView, - { submit, actions }: SectionContext, + { overview, submit, actions }: SectionContext, ): HTMLElement { + const hosts = overview.review_hosts.filter((host) => host.kind === "github"); + if (hosts.length === 0) { + return el("p", { class: "muted workspace-profile-token", text: GH_TOKEN_NOTE }); + } + const wanted = profile.name.toLowerCase(); + const bound = + workspace.gh_token_bindings.find((binding) => binding.profile.toLowerCase() === wanted)?.host ?? + ""; + const select = el("select", { + attrs: { id: `workspace-gh-token-${profile.name}`, "aria-label": ghTokenLabel(profile.name) }, + }); + select.append(el("option", { text: GH_TOKEN_NONE, attrs: { value: "" } })); + const names = hosts.map((host) => host.name); + if (bound !== "" && !names.includes(bound)) { + // Show the recorded binding even if the list does not name its host. + names.push(bound); + } + for (const name of names) { + select.append(el("option", { text: name, attrs: { value: name } })); + } + select.value = bound; + select.addEventListener("change", () => { + const id = workspace.workspace_id; + submit( + select.value === "" + ? actions.unbindGhToken(id, profile.name) + : actions.bindGhToken(id, profile.name, select.value), + ); + }); + return el( + "div", + { class: "workspace-profile-token" }, + el("label", { class: "muted", text: "GitHub token", attrs: { for: select.id } }), + select, + ); +} + +function profileSwitch( + workspace: WorkspaceSettingsView, + profile: ToolchainProfileView, + ctx: SectionContext, +): HTMLElement[] { + const { submit, actions } = ctx; const box = el("input", { class: "switch", attrs: { @@ -46,7 +106,7 @@ function profileSwitch( : actions.unassignToolchainProfile(id, profile.name), ); }); - return el( + const toggle = el( "div", { class: "toggle workspace-profile" }, box, @@ -59,6 +119,7 @@ function profileSwitch( el("label", { class: "perm-label", text: profile.name, attrs: { for: box.id } }), ), ); + return box.checked ? [toggle, ghTokenRow(workspace, profile, ctx)] : [toggle]; } /** @@ -85,7 +146,7 @@ export function workspaceProfilesBlock( : el( "div", { class: "workspace-profile-list" }, - ...profiles.map((profile) => profileSwitch(workspace, profile, ctx)), + ...profiles.flatMap((profile) => profileSwitch(workspace, profile, ctx)), ), ); } diff --git a/crates/omgcode-desktop/ui/src/styles/settings.css b/crates/omgcode-desktop/ui/src/styles/settings.css index d1273989..eab16ddc 100644 --- a/crates/omgcode-desktop/ui/src/styles/settings.css +++ b/crates/omgcode-desktop/ui/src/styles/settings.css @@ -616,6 +616,16 @@ align-items: center; } +/* The GitHub token choice (ADR-0147), indented under its profile's switch. */ +.workspace-profile-token { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin: 0 0 6px 50px; + font-size: var(--settings-secondary-size); +} + .granted-folders, .package-cache, .workspace-instructions { diff --git a/crates/omgcode-desktop/ui/tests/dist.test.ts b/crates/omgcode-desktop/ui/tests/dist.test.ts index 8e7e2e41..80ca0f99 100644 --- a/crates/omgcode-desktop/ui/tests/dist.test.ts +++ b/crates/omgcode-desktop/ui/tests/dist.test.ts @@ -110,8 +110,8 @@ suite( }); it("reads every settings-window command from the settings client", () => { - // 47 in `settings`, as `policy.rs` and the guide count them. - expect(SETTINGS_WINDOW_COMMANDS).toHaveLength(47); + // 49 in `settings`, as `policy.rs` and the guide count them. + expect(SETTINGS_WINDOW_COMMANDS).toHaveLength(49); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_overview"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_import_review_skill"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_add_review_host"); @@ -122,6 +122,8 @@ suite( expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_add_discovered_profiles"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_assign_toolchain_profile"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_unassign_toolchain_profile"); + expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_bind_gh_token"); + expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_unbind_gh_token"); expect(SETTINGS_WINDOW_COMMANDS).not.toContain("settings_grant_discovered_roots"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_add_web_fetch_host"); expect(SETTINGS_WINDOW_COMMANDS).toContain("settings_remove_web_fetch_host"); diff --git a/crates/omgcode-desktop/ui/tests/settings_discovery.test.ts b/crates/omgcode-desktop/ui/tests/settings_discovery.test.ts index c139daac..513fc42a 100644 --- a/crates/omgcode-desktop/ui/tests/settings_discovery.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_discovery.test.ts @@ -48,6 +48,7 @@ function overview(overrides: Partial = {}): SettingsOverview { git_worker: { state: "ready", folder_display: null }, granted_folders: [], profiles: [], + gh_token_bindings: [], write_tools: { edit: "allow", multi_edit: "allow", diff --git a/crates/omgcode-desktop/ui/tests/settings_execution.test.ts b/crates/omgcode-desktop/ui/tests/settings_execution.test.ts index 6e1f04a3..a908ee1c 100644 --- a/crates/omgcode-desktop/ui/tests/settings_execution.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_execution.test.ts @@ -50,6 +50,7 @@ function overview(overrides: Partial = {}): SettingsOverview { git_worker: { state: "ready", folder_display: null }, granted_folders: [], profiles: [], + gh_token_bindings: [], write_tools: { edit: "allow", multi_edit: "allow", @@ -484,6 +485,56 @@ describe("mock execution commands", () => { ).rejects.toMatchObject({ code: "control" }); }); + it("binds an assigned profile to a github host and ends the binding with its assignment (ADR-0147)", async () => { + const { invoke } = createMockBackend(); + const start0 = await overviewOf(invoke); + const workspace = start0.workspaces[0]?.workspace_id ?? ""; + const change = async (command: string, extra: Record) => { + const { revision } = await overviewOf(invoke); + return (await invoke(command, { + revision, + workspace_id: workspace, + ...extra, + })) as SettingsOverview; + }; + const addHost = async (name: string, kind: string) => { + const { revision } = await overviewOf(invoke); + return (await invoke("settings_add_review_host", { + revision, + name, + kind, + base_url: kind === "github" ? null : "https://git.example.com", + organization: null, + token: "token", + })) as SettingsOverview; + }; + await addHost("work", "github"); + await addHost("corp", "github_enterprise"); + + // An unassigned profile is refused. + await expect( + change("settings_bind_gh_token", { profile: "rust", host: "work" }), + ).rejects.toMatchObject({ code: "control" }); + await change("settings_assign_toolchain_profile", { name: "rust" }); + // A host that is not github.com is refused. + await expect( + change("settings_bind_gh_token", { profile: "rust", host: "corp" }), + ).rejects.toMatchObject({ code: "control" }); + + const bound = await change("settings_bind_gh_token", { profile: "rust", host: "work" }); + expect(bound.workspaces[0]?.gh_token_bindings).toEqual([{ profile: "rust", host: "work" }]); + const unbound = await change("settings_unbind_gh_token", { profile: "rust" }); + expect(unbound.workspaces[0]?.gh_token_bindings).toEqual([]); + await expect(change("settings_unbind_gh_token", { profile: "rust" })).rejects.toMatchObject({ + code: "control", + }); + + // Unassigning ends a binding without an event of its own. + await change("settings_bind_gh_token", { profile: "rust", host: "work" }); + const unassigned = await change("settings_unassign_toolchain_profile", { name: "rust" }); + expect(unassigned.workspaces[0]?.gh_token_bindings).toEqual([]); + }); + it("grants a registered workspace its folder and never reuses a revoked grant's identifier", async () => { const { invoke } = createMockBackend(); const before = await overviewOf(invoke); diff --git a/crates/omgcode-desktop/ui/tests/settings_folders.test.ts b/crates/omgcode-desktop/ui/tests/settings_folders.test.ts index cfca237c..633d8eed 100644 --- a/crates/omgcode-desktop/ui/tests/settings_folders.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_folders.test.ts @@ -67,6 +67,7 @@ function workspace(folders: GrantedFolderView[]) { git_worker: { state: "ready", folder_display: null }, granted_folders: folders, profiles: [], + gh_token_bindings: [], write_tools: { ...ALL_TOOLS }, package_cache_root: null, instructions: "", diff --git a/crates/omgcode-desktop/ui/tests/settings_git_worker.test.ts b/crates/omgcode-desktop/ui/tests/settings_git_worker.test.ts index 5c932cdc..ce1ac595 100644 --- a/crates/omgcode-desktop/ui/tests/settings_git_worker.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_git_worker.test.ts @@ -42,6 +42,7 @@ function workspace(worker: GitWorkerView) { web_fetch_hosts: [], granted_folders: [], profiles: [], + gh_token_bindings: [], write_tools: { edit: "allow", multi_edit: "allow", diff --git a/crates/omgcode-desktop/ui/tests/settings_sections.test.ts b/crates/omgcode-desktop/ui/tests/settings_sections.test.ts index 65d14323..776f20c2 100644 --- a/crates/omgcode-desktop/ui/tests/settings_sections.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_sections.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { setInvoker } from "../src/ipc/client"; import type { ProviderProfileView, + ReviewHostView, SettingsOverview, ToolchainProfileView, WorkspaceSettingsView, @@ -25,7 +26,14 @@ import { WEB_HOSTS_HELP, webHostMessage, } from "../src/settings/web_hosts"; -import { PROFILES_EMPTY, PROFILES_HELP, useProfileLabel } from "../src/settings/workspace_profiles"; +import { + GH_TOKEN_NONE, + GH_TOKEN_NOTE, + ghTokenLabel, + PROFILES_EMPTY, + PROFILES_HELP, + useProfileLabel, +} from "../src/settings/workspace_profiles"; import { ALL_TOOLS_LABEL, PACKAGE_CACHE_HELP, @@ -71,6 +79,7 @@ function workspace(id: string, folder: string, extra: Partial { expect(root.textContent).toContain(PROFILES_EMPTY); expect(root.querySelector(".workspace-profile")).toBeNull(); }); + + describe("GitHub token binding (ADR-0147)", () => { + const host = (name: string, kind: ReviewHostView["kind"]): ReviewHostView => ({ + name, + kind, + kind_label: kind, + base_url: null, + organization: null, + rest_origin: "https://api.github.com", + token_readable: true, + }); + const HOSTS = [ + host("work", "github"), + host("corp", "github_enterprise"), + host("lab", "gitlab"), + host("home", "github"), + ]; + + function tokenSelect(name: string): HTMLSelectElement | null { + return root.querySelector(`select[aria-label="${ghTokenLabel(name)}"]`); + } + + it("offers None and each github host by name, for an assigned profile only", async () => { + await start(() => + overview({ + toolchain_profiles: RECORDED, + review_hosts: HOSTS, + workspaces: [workspace(A, "/home/dev/a", { profiles: ["rust"] })], + }), + ); + const select = tokenSelect("rust"); + expect(Array.from(select?.options ?? [], (option) => option.text)).toEqual([ + GH_TOKEN_NONE, + "work", + "home", + ]); + expect(select?.value).toBe(""); + // The profile that is not assigned has no control. + expect(tokenSelect("go")).toBeNull(); + expect(root.textContent).not.toContain(GH_TOKEN_NOTE); + }); + + it("shows the recorded binding as the selected value", async () => { + await start(() => + overview({ + toolchain_profiles: RECORDED, + review_hosts: HOSTS, + workspaces: [ + workspace(A, "/home/dev/a", { + profiles: ["rust"], + gh_token_bindings: [{ profile: "rust", host: "home" }], + }), + ], + }), + ); + expect(tokenSelect("rust")?.value).toBe("home"); + }); + + it("binds a chosen host with names only, and unbinds on None", async () => { + await start( + () => + overview({ + toolchain_profiles: RECORDED, + review_hosts: HOSTS, + workspaces: [workspace(A, "/home/dev/a", { profiles: ["rust"] })], + }), + { + settings_bind_gh_token: () => + overview({ + revision: 4, + toolchain_profiles: RECORDED, + review_hosts: HOSTS, + workspaces: [ + workspace(A, "/home/dev/a", { + profiles: ["rust"], + gh_token_bindings: [{ profile: "rust", host: "work" }], + }), + ], + }), + settings_unbind_gh_token: () => + overview({ + revision: 5, + toolchain_profiles: RECORDED, + review_hosts: HOSTS, + workspaces: [workspace(A, "/home/dev/a", { profiles: ["rust"] })], + }), + }, + ); + const choose = (value: string) => { + const select = tokenSelect("rust"); + if (select === null) { + throw new Error("No token select"); + } + select.value = value; + select.dispatchEvent(new Event("change")); + }; + choose("work"); + await settle(); + expect(ipc.callsTo("settings_bind_gh_token")[0]?.args).toEqual({ + revision: 3, + workspace_id: A, + profile: "rust", + host: "work", + }); + expect(ipc.callsTo("settings_unbind_gh_token")).toHaveLength(0); + expect(tokenSelect("rust")?.value).toBe("work"); + + choose(""); + await settle(); + expect(ipc.callsTo("settings_unbind_gh_token")[0]?.args).toEqual({ + revision: 4, + workspace_id: A, + profile: "rust", + }); + expect(tokenSelect("rust")?.value).toBe(""); + }); + + it("shows the recorded state again when the operator declines", async () => { + await start( + () => + overview({ + toolchain_profiles: RECORDED, + review_hosts: HOSTS, + workspaces: [workspace(A, "/home/dev/a", { profiles: ["rust"] })], + }), + { settings_bind_gh_token: () => rejection("cancelled", "No change was made.") }, + ); + const select = tokenSelect("rust"); + if (select === null) { + throw new Error("No token select"); + } + select.value = "work"; + select.dispatchEvent(new Event("change")); + await settle(); + expect(ipc.callsTo("settings_bind_gh_token")).toHaveLength(1); + expect(tokenSelect("rust")?.value).toBe(""); + }); + + it("says where to add a host when no github host is recorded", async () => { + await start(() => + overview({ + toolchain_profiles: RECORDED, + review_hosts: [host("corp", "github_enterprise"), host("lab", "gitlab")], + workspaces: [workspace(A, "/home/dev/a", { profiles: ["rust"] })], + }), + ); + expect(tokenSelect("rust")).toBeNull(); + expect(root.textContent).toContain(GH_TOKEN_NOTE); + expect(GH_TOKEN_NOTE).toBe( + "To give gh a GitHub token, add a GitHub review host under Reviews.", + ); + expect(root.querySelector(".workspace-profile-token a")).toBeNull(); + }); + }); }); diff --git a/crates/omgcode-desktop/ui/tests/settings_skills.test.ts b/crates/omgcode-desktop/ui/tests/settings_skills.test.ts index 4e32ce83..050799ff 100644 --- a/crates/omgcode-desktop/ui/tests/settings_skills.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_skills.test.ts @@ -36,6 +36,7 @@ function workspace(id: string, folder: string): SettingsOverview["workspaces"][n git_worker: { state: "ready", folder_display: null }, granted_folders: [], profiles: [], + gh_token_bindings: [], write_tools: { edit: "allow", multi_edit: "allow", diff --git a/crates/omgcode-desktop/ui/tests/settings_window.test.ts b/crates/omgcode-desktop/ui/tests/settings_window.test.ts index 0e924a1a..4fc96efb 100644 --- a/crates/omgcode-desktop/ui/tests/settings_window.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_window.test.ts @@ -84,6 +84,7 @@ function workspace(overrides: Partial = {}): WorkspaceSet git_worker: { state: "ready", folder_display: null }, granted_folders: [], profiles: [], + gh_token_bindings: [], write_tools: { ...ALL_TOOLS }, package_cache_root: null, instructions: "", diff --git a/crates/omgcode-platform/src/process/tests/confinement.rs b/crates/omgcode-platform/src/process/tests/confinement.rs index 04cd05b9..e48209cb 100644 --- a/crates/omgcode-platform/src/process/tests/confinement.rs +++ b/crates/omgcode-platform/src/process/tests/confinement.rs @@ -67,6 +67,10 @@ pub(super) fn probes() -> i32 { ); report("read-secret", fs::read(&secret).map(drop)); report("list-secret-dir", fs::read_dir(secret_directory).map(drop)); + // A run's environment can hold a credential (ADR-0147), so the run must + // not read it back as a file, directly or through a link it made. + report("read-own-environ", fs::read("/proc/self/environ").map(drop)); + report("read-environ-link", read_through_link(&workspace)); report("write-secret", open_for_write(&secret)); report("workspace-round-trip", workspace_round_trip(&workspace)); report("tcp-connect-host", TcpStream::connect(&host_tcp).map(drop)); @@ -177,6 +181,15 @@ fn workspace_round_trip(workspace: &Path) -> io::Result<()> { /// Connect to the host listener. The listener's backlog completes the /// connection, so `ok` means a socket outside the tree was reached. +/// Link a workspace name to `/proc/self/environ` and read through it. +fn read_through_link(workspace: &Path) -> io::Result<()> { + let link = workspace.join("environ-link"); + std::os::unix::fs::symlink("/proc/self/environ", &link)?; + let result = fs::read(&link).map(drop); + let _ = fs::remove_file(&link); + result +} + fn unix_connect(path: &Path) -> io::Result<()> { UnixStream::connect(path).map(drop) } @@ -360,7 +373,7 @@ fn assert_results(results: &BTreeMap, expected: &[(&str, &str)]) } /// Results that must hold in every Unix-socket and network mode. -const COMMON: [(&str, &str); 11] = [ +const COMMON: [(&str, &str); 13] = [ ("read-allowed", "ok"), ("list-allowed", "ok"), ("write-read-only", "EACCES"), @@ -368,6 +381,8 @@ const COMMON: [(&str, &str); 11] = [ ("create-in-read-only", "EACCES"), ("read-secret", "EACCES"), ("list-secret-dir", "EACCES"), + ("read-own-environ", "EACCES"), + ("read-environ-link", "EACCES"), ("write-secret", "EACCES"), ("workspace-round-trip", "ok"), ("unix-stream-pair", "ok"), diff --git a/docs/adr/0147-give-a-bound-gh-profile-a-github-review-hosts-token.md b/docs/adr/0147-give-a-bound-gh-profile-a-github-review-hosts-token.md new file mode 100644 index 00000000..388344c5 --- /dev/null +++ b/docs/adr/0147-give-a-bound-gh-profile-a-github-review-hosts-token.md @@ -0,0 +1,176 @@ +# 0147: Give a bound gh profile a GitHub review host's token + +- Status: Accepted +- Date: 2026-12-05 + +## Context + +The operator asked that, when a session works with GitHub, OMGCode use their +authenticated account: the built-in tools first, then `gh`, then Git. `gh` +and Git are signed in outside the sandbox but not inside it. ADR-0138 added +`gh` as a generated toolchain profile with no token, and model runs never had +a network, so every `gh` command that calls GitHub failed. ADR-0143 records +review hosts with one token each in protected OS storage. The operator chose +to reuse a `github` review host's token for `gh` inside the sandbox rather +than store a second one. + +The security rules kept every credential out of task environments. `gh` has +features that make a token in its environment more than a header: it sends +`GH_TOKEN` to `github.com`, `*.ghe.com`, and `github.localhost`, and +`GH_ENTERPRISE_TOKEN` to any other host a command names; extensions, `!` +aliases, the pager, the editor, and the browser start other programs; and its +configuration folder can redirect requests. A model command under `allow` +runs without the operator seeing it. + +## Decision + +1. **A binding names a workspace, one of its profiles, and a `github` host.** + Two control events: `gh_token_bound` records or replaces the binding of one + workspace and profile, and `gh_token_unbound` ends it. A binding needs a + registered workspace, a profile assigned to it, and a host of kind + `github`. It ends without an event of its own when its workspace is + unregistered, its profile is unassigned or removed, or its host is removed: + every replayed event is followed by a prune. Each event advances the + settings revision, so pending command approvals go stale. The trusted CLI + has `workspace gh-token-bind`, `gh-token-unbind`, and `gh-token-list`; the + `settings` window has a **GitHub token** select beside each assigned profile, + which needs a native confirmation to bind and none to unbind. Each binding + keeps room for its `gh_token_unbound` event in the settings journal, so a + full journal can still end it. +2. **github.com only.** A GitHub Enterprise host is refused, because + `GH_ENTERPRISE_TOKEN` goes to whatever host a command names and cannot be + pinned. Every argument containing `://`, `ghe.com`, or `github.localhost`, + in any case, and `--hostname` are refused, and so is a host-qualified + repository unless its host is `github.com`. A repository operand, the + value of `--repo`, `-R`, `--source`, `--template`, or `--branch-repo` or + an operand of `repo`, `label clone`, or `issue transfer`, is checked by + `gh`'s own grammar, where any first of three segments is the host + (`intranet/owner/repo` too); any other argument is refused when it looks + like `example.com/owner/repo`, unless it starts with `.`. The value of + `--body-file`, `--notes-file`, `--input`, or `-F`, which `gh` reads as a + local file or field, is not a host: it skips that check and the `ghe.com` + and `github.localhost` name checks, but a URL is refused in it. Every other + argument, a `.` path included, still gets the name checks. + `gh` already sends `GH_TOKEN` to its own hosts only; these rules keep it on + `github.com`. The runner sets `GH_HOST=github.com`. +3. **Only the profile's own `gh`, only from a model command.** The program must + be `gh` by its bare name (`gh.exe` too on Windows), found on the profile's + `PATH`. Any other program of the profile runs as before, without a token + or a network. The trusted CLI `run` passes no token. +4. **Allowed commands.** The first argument must be `pr`, `issue`, `repo`, + `api`, `run`, `workflow`, `release`, `search`, `label`, or `status`, and + every one but `api` and `status` must name its subcommand next, so a flag + placed before it cannot hide it from these rules; `repo + clone` and `pr checkout`, and the flags `--clone`, `--remote`, and + `--checkout`, and `-c` in `repo create` and `issue develop`, which start + Git, are refused, and so are `--web` + and a short-flag group that contains `w`, which open a browser; `--jq` + and a short-flag group that contains `q`, because `gh` runs a jq filter + with the process environment and so could print the token in a form the + redaction does not match; and `--editor`, and in `issue create`, `issue + comment`, `pr create`, and `pr comment` a short-flag group that contains + `e`, which start a text editor that would inherit the token. Everything + else, including `auth`, `alias`, `extension`, `config`, `codespace`, + `browse`, `gist`, and `copilot`, is refused. The turn checks this before + any approval and answers `gh_arguments_refused`; the runner checks it again. +5. **An empty, read-only configuration folder.** `GH_CONFIG_DIR` is the folder + that holds the resolved `gh`. The runner requires it to lie in a read-only + profile root, outside the workspace and every granted folder the run may + write, and to hold no `config.yml`, `hosts.yml`, or `state.yml`, so no run + can place an alias, extension setting, or Unix-socket redirect there. It + also refuses a profile whose `PATH` holds `git`, which would let `gh` + choose a host from a repository's remotes. +6. **The environment.** After the profile's variables the runner adds + `GH_TOKEN`, `GH_HOST`, `GH_CONFIG_DIR`, `GH_PROMPT_DISABLED`, + `GH_NO_UPDATE_NOTIFIER`, `GH_NO_EXTENSION_UPDATE_NOTIFIER`, + `GH_SPINNER_DISABLED`, `GH_TELEMETRY=false`, `DO_NOT_TRACK`, `GH_PAGER=cat`, + and `NO_COLOR`, and leaves out every profile variable named `GH_*`, + `GITHUB_*`, `*_PROXY`, `PAGER`, `BROWSER`, `EDITOR`, `VISUAL`, `DEBUG`, + `DO_NOT_TRACK`, `NO_COLOR`, `SSL_CERT_FILE`, or `SSL_CERT_DIR`. +7. **Network and approval.** A bound `gh` selects network access. The + workspace's `task_network` preference must permit it, or the call is + answered `github_network_disabled` before any approval. The call's + effective state is the most restrictive of the model command state and + `task_network`, so it runs without an approval only when both are `allow`; + the runner refuses such a run, and its watcher withdraws it, once either + leaves `allow`. + The command digest appends the host's name and identifier, and only for a + bound `gh`, so every other digest is unchanged. The turn passes the + identifier it read under the lock that admitted the call to the runner, + which refuses the run unless the live binding names that identifier, so a + host replaced under the same name between admission and the run lends no + token. The approval review shows **Network** on + and a **GitHub token** field that names the host, never the token. +8. **The token.** The runner reads it under its settings lock through + `load_review_host`, the review host's checked load, and only a `github` + host's token converts to text for `GH_TOKEN`. A token that cannot be read + refuses the run; there is no fallback to no token. +9. **Output and records.** Every occurrence of the token's bytes in the + retained output is replaced with `[redacted GitHub token]`, and, when the + output was truncated, any prefix of the token that ends it, whatever its + length. The run journal records the host's name as `github_host` and its + identifier as `github_host_id`, never the token, and the run's watcher + withdraws the run when the workspace no longer binds its profile to that + host identifier, so a host removed and added again under the same name + does not keep the run. A rebind waits for the runs it withdraws. +10. **The security rules name this as the one exception** to keeping + credentials out of task environments. + +## Alternatives considered + +- **Use the operator's own `gh` sign-in.** It needs no setup, but core would + read a credential it did not store, from `gh`'s files or the OS keyring, and + that sign-in usually has full `repo` scope. Rejected. +- **A separate token for `gh`.** A second store and a second set of steps for + the same host. The operator chose to reuse the review host's token. +- **GitHub Enterprise through `GH_ENTERPRISE_TOKEN`.** It goes to any host a + command names, so a model could send it anywhere `--repo` reaches. Rejected + until `gh` can pin it. +- **No argument rules, relying on the approval.** Under `allow` for both + preferences nothing is shown before the run. The rules keep the token on + `github.com` and stop `gh` starting other programs in either case. +- **A per-run configuration folder in the container's home.** Every run of the + workspace shares that container and can write there, so another run could + place a configuration file between creation and start. The folder that + holds `gh` is read-only to every run. +- **A built-in GitHub model tool.** It would keep the token out of any + process, but it is a new network tool with its own shapes and rules. It + needs its own decision. + +## Consequences + +- With a binding and `task_network`, a model can read pull requests, issues, + Actions runs, and releases on `github.com` with `gh`, as far as the token + allows. The review host token the steps recommend reads pull requests and + contents only, so a write such as `gh pr comment` fails at GitHub unless the + operator gives the token more. +- The token is in the run's environment block and in the runner's memory for + the run's life. A process `gh` started could read it. The argument rules + refuse every command and flag known to ask for the browser, the editor, or + Git. `gh` can also look for Git on its own, for example to find the + current branch, and that is stopped only by the runner's refusal of a + profile whose `PATH` holds `git`: nothing else is on the run's `PATH` but + the profile's entries. +- A file argument such as `--body-file`, `--input`, or `-F @path` uploads + any file the run can read; the argument rules do not limit the path. The + sandbox keeps the token out of reach: Linux Landlock grants no `/proc`, + so `/proc/self/environ` is refused directly and through a link, which a + confinement test checks, and on Windows no file exposes a process's + environment. +- Redaction matches the token's exact bytes. An encoded form, such as base64 + or a jq `explode`, is not replaced; with jq filters refused, no allowed + command is known to print one. +- A profile whose `gh` sits beside other tools in a writable folder, or whose + `PATH` holds Git, cannot be bound usefully: the runner refuses it. +- No `gh` run with a token was made against GitHub, and no confined + acceptance run was made with `gh` on either platform. The rules are tested + with fixtures, the binding against the real control journal, the approval + review through real turns with a scripted model, and the CLI through the + real process. + +## References + +- [Execution contract](../execution.md#github-token-for-gh) +- [Pull request reviews](../reviews.md) +- [Security coding rules](../security-coding-rules.md) +- ADR-0032, ADR-0063, ADR-0107, ADR-0138, ADR-0143 diff --git a/docs/adr/index.md b/docs/adr/index.md index 6fdc9d16..866e6166 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -160,3 +160,4 @@ meaningful alternative does not need an ADR. | [0143: Record review hosts with a token each and an HTTPS client for their REST origin](0143-record-review-hosts-with-a-token-each-and-an-https-client-for-their-rest-origin.md) | Accepted | 2026-12-03 | | [0144: Fetch reviews from GitHub into isolated review folders and run review sessions](0144-fetch-reviews-from-github-into-isolated-review-folders-and-run-review-sessions.md) | Accepted | 2026-12-04 | | [0145: Fetch reviews from GitLab, Azure DevOps, and Bitbucket](0145-fetch-reviews-from-gitlab-azure-devops-and-bitbucket.md) | Accepted | 2026-12-04 | +| [0147: Give a bound gh profile a GitHub review host's token](0147-give-a-bound-gh-profile-a-github-review-hosts-token.md) | Accepted | 2026-12-05 | diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index b797fa34..c5bc76b5 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -334,7 +334,7 @@ has not been run, so how it behaves in a delegated cgroup is unverified. ## Windows and commands -The shell has three webview windows and 93 commands (43 in `main`, 3 in `approvals`, and 47 in `settings`). No other command exists. +The shell has three webview windows and 95 commands (43 in `main`, 3 in `approvals`, and 49 in `settings`). No other command exists. No command accepts a host path. Sessions are addressed by UUID, workspaces by their registered identifier, and approvals by identifier. @@ -426,6 +426,8 @@ their registered identifier, and approvals by identifier. | `settings_remove_toolchain_profile` | settings | Remove a toolchain profile after a native confirmation that names each workspace it is assigned to and the grants revoked there; the runs the settings then withdraw are stopped (ADR-0088, ADR-0107) | | `settings_assign_toolchain_profile` | settings | Assign a toolchain profile to one workspace after a native confirmation that names the workspace, the profile, each folder the workspace's container is granted read and execute, and the folders it cannot grant (ADR-0107) | | `settings_unassign_toolchain_profile` | settings | End one assignment after a native confirmation that names the grants it revokes and says the workspace's runs stop (ADR-0107) | +| `settings_bind_gh_token` | settings | Bind an assigned toolchain profile's `gh` to a recorded `github` review host's token after a native confirmation that names the workspace folder, the profile, and the host; names only, no token reaches the window (ADR-0147) | +| `settings_unbind_gh_token` | settings | End that binding with no dialog, because it narrows access; the runs that used it are stopped (ADR-0147) | | `settings_add_package_profile` | settings | Record a package-network profile (configuration only) after a native confirmation that lists the origins core parsed (ADR-0088) | | `settings_remove_package_profile` | settings | Remove a package-network profile, which also unbinds and deletes the credentials bound to its origins, after a native confirmation (ADR-0088) | | `settings_grant_container_folder` | settings | Windows only. Open a native folder dialog and, after a native confirmation that names the workspace, folder, and access and says the folder's access-control list changes, grant it to the workspace's container (ADR-0088) | @@ -1747,7 +1749,16 @@ waits. The window shows: when only the AppContainer profile could not be deleted. Turning one off calls `settings_unassign_toolchain_profile`, whose confirmation names the grants it revokes and says the workspace's running commands stop. A declined - confirmation or a refusal shows the recorded state again. Then **Granted + confirmation or a refusal shows the recorded state again. Under each + assigned profile a **GitHub token** select offers **None** and each recorded + review host of kind `github` by name (ADR-0147). Choosing a host calls + `settings_bind_gh_token`, whose confirmation names the workspace folder, the + profile, and the host and says that a model command starting the profile's + `gh` then gets the host's token as `GH_TOKEN` and network access; choosing + **None** calls `settings_unbind_gh_token`, which opens no dialog. The + overview lists each binding by profile and host name only. With no `github` + host recorded, the select is replaced by a note that points to **Reviews**. + Then **Granted folders** (since 0.80.0, [ADR-0118](adr/0118-grant-a-workspace-access-to-folders-outside-it.md)) lists the folders outside the workspace that the operator granted to it, up to 16, as `n of 16`. Each row shows the @@ -2947,7 +2958,7 @@ What it does not do: | Item | Value | | --- | --- | -| Commands | 93 | +| Commands | 95 | | Git status changed paths | 1,000, and a 10-second deadline | | Sessions per listing | 5,000 | | Search terms and length | 16 terms, 256 characters | diff --git a/docs/development.md b/docs/development.md index 3cbc2460..82cf517f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -289,6 +289,11 @@ than `deny` the `web_fetch` tool. `web-host-add`, `web-host-remove`, and which lets `--web-fetch allow` skip the approval for those hosts ([ADR-0098](adr/0098-add-a-model-web-fetch-tool-behind-a-host-allowlist.md), [ADR-0110](adr/0110-allow-a-web-host-from-a-fetch-approval-and-list-100-hosts.md)). +`gh-token-bind `, `gh-token-unbind`, and +`gh-token-list` bind an assigned profile to a review host of kind `github`, so +a model command that starts that profile's `gh` gets the host's token and, +under `task_network`, the network +([GitHub token for gh](execution.md#github-token-for-gh), ADR-0147). See [model tools](workspace-permissions.md#model-readlist-and-command-tools). See the [workspace contract](workspace-permissions.md) for limits and failures. `container-grant` and `container-revoke` work on Windows only. They change ACLs diff --git a/docs/execution.md b/docs/execution.md index 70cb6910..b12a4268 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -841,7 +841,8 @@ program the approved profile exposes, including an interpreter such as `sh` or `cmd`; that program's own parsing is part of the exact request the operator approves. The tool fixes its limits: a 20-second deadline, 4 KiB retained from each output stream, 1 GiB memory, 64 processes, 20 seconds of CPU, and 256 MiB of -disk growth. It selects no network or host services. +disk growth. It selects no host services, and no network except for a bound +`gh` ([GitHub token for gh](#github-token-for-gh)). Since 0.65.0 (tool schema 0.9.0) the `profile` parameter lists, as an `enum`, the names of the profiles recorded for the running platform, in the order @@ -881,6 +882,106 @@ trusted runner on both Linux and Windows, and asserts a successful exit, the bounded output, and the consumed approval. On Linux the chat process starts in a delegated cgroup; on Windows the test scene grants the workspace. +#### GitHub token for gh + +Since 0.95.0 a workspace can bind one of its assigned toolchain profiles to a +recorded review host of kind `github` ([ADR-0147](adr/0147-give-a-bound-gh-profile-a-github-review-hosts-token.md)): +`omgcode workspace gh-token-bind --revision `, +`gh-token-unbind`, and `gh-token-list`, or the **GitHub token** select beside +each assigned profile on the workspace's page of the `settings` window, which +asks for a native confirmation before it binds. A binding is configuration: +it advances the settings revision, so pending command approvals of the +workspace go stale, and it ends when the workspace is unregistered, the +profile is unassigned or removed, or the host is removed. A GitHub Enterprise +host is refused, because `gh` sends `GH_ENTERPRISE_TOKEN` to any host a +command names. + +A model command gets the token only when its `program` is `gh` by its bare +name (also `gh.exe` on Windows) and the workspace binds the named profile. +Under the lock that admits the call, before any approval is requested: + +- the arguments must start with `pr`, `issue`, `repo`, `api`, `run`, + `workflow`, `release`, `search`, `label`, or `status`, and must not be + `repo clone` or `pr checkout`, or hold `--clone`, `--remote`, or + `--checkout`, or `-c` in `repo create` or `issue develop`, which start Git. + Every allowed command but + `api` and `status` must name its subcommand directly after it, so a flag + such as `--repo` before the subcommand cannot hide it from these rules. No + argument may contain + `://`, `ghe.com`, or `github.localhost` in any case, or be `--hostname`, + `--web`, or a short-flag group that contains `w` (a browser), `--jq` or a + short-flag group that contains `q` (a jq filter, which `gh` runs with the + process environment, so it could read the token), or `--editor`, or in + `issue create`, `issue comment`, `pr create`, and `pr comment` a short-flag + group that contains `e` (a text editor, which would inherit the token). A + repository operand (the value of `--repo`, `-R`, `--source`, `--template`, + or `--branch-repo`, and a white-space-free argument that is not a flag of + `repo`, `label clone`, or `issue transfer`) with three or more `/` + segments must start with `github.com` in any case, because `gh` reads any + first segment there as the host, `intranet/owner/repo` included. Any + other argument or flag value after `=` with three or more `/` segments + whose first is a host name with a dot or a port, or `localhost`, is + refused too, unless it starts with `.`. The value of `--body-file`, + `--notes-file`, `--input`, or `-F`, which `gh` reads as a local file or + field, is not a host: it skips that check and the `ghe.com` and + `github.localhost` name checks, but a URL is refused in it. Every other + argument, a `.` path included, still gets the name checks. A refusal is + answered with `gh_arguments_refused`; +- the workspace's `task_network` preference must permit network access, or the + call is answered with `github_network_disabled`. + +The run then selects network access, and its effective state is the most +restrictive of the model command state and `task_network`: it runs without an +approval only when both are `allow`. The runner refuses such a standing-allow +run under its own lock, and its watcher withdraws it, once either leaves +`allow`. The approval's digest appends the host's +name and identifier to the command digest (every other command's digest is +unchanged), and its review shows **Network** on and a **GitHub token** field +that names the host, never the token. The turn passes the identifier it read +under the lock that admitted the call, and the runner refuses the run unless +the live binding names it. The trusted CLI `run` passes no token. Each binding +keeps room for its unbind event in the settings journal, so a full journal can +still end it. + +Under its own settings lock the runner checks the binding, the program, and the +arguments again, and refuses the run unless the resolved `gh` lies in a +read-only profile root outside the workspace and every granted folder the run +may write, that folder holds no `config.yml`, `hosts.yml`, or `state.yml`, and +no `PATH` entry of the profile holds `git`, which would let `gh` choose a host +from a repository's remotes. It reads the token through the review host's +credential binding and adds `GH_TOKEN`, `GH_HOST=github.com`, `GH_CONFIG_DIR` +set to the folder that holds `gh`, `GH_PROMPT_DISABLED`, +`GH_NO_UPDATE_NOTIFIER`, `GH_NO_EXTENSION_UPDATE_NOTIFIER`, +`GH_SPINNER_DISABLED`, `GH_TELEMETRY=false`, `DO_NOT_TRACK`, `GH_PAGER=cat`, +and `NO_COLOR` after the profile's variables, leaving out any profile variable +named `GH_*`, `GITHUB_*`, `*_PROXY`, `PAGER`, `BROWSER`, `EDITOR`, `VISUAL`, +`DEBUG`, `DO_NOT_TRACK`, `NO_COLOR`, `SSL_CERT_FILE`, or `SSL_CERT_DIR`. Every +occurrence of the token's bytes in the retained output, and, when the output +was truncated, any prefix of the token that ends it, is replaced with +`[redacted GitHub token]`; the byte counts are those the run wrote. The run +journal records the host's name in `github_host` and its identifier in +`github_host_id`, and the watcher withdraws the run when the workspace no +longer binds its profile to that host identifier, so a host removed and added +again under the same name does not keep the run. Binding the profile again, +from the trusted CLI or the `settings` window, waits for the runs it +withdraws. + +The argument rules do not limit which file a file argument names, so +`--body-file`, `--input`, or `-F @path` can upload any file the run can read. +The sandbox keeps the token out of those files. On Linux, Landlock grants +reads only under the profile roots, the workspace, the run's scratch folder, +the listed resolver and certificate files under `/etc`, and `/dev/null`, +`/dev/zero`, `/dev/random`, and `/dev/urandom`: no `/proc`, so +`/proc/self/environ` is refused, directly or through a link the run makes, +and a confinement test checks both. On Windows no file exposes a process's +environment. + +`gh` can do with the token what the token's own scopes allow. The token the +review host steps recommend reads pull requests and contents only, so a +command that writes, such as `gh pr comment`, is refused by GitHub unless the +operator gives the token more. No `gh` run with a token was made against +GitHub, and no confined acceptance run was made with `gh`. + The approval-gated `workspace_edit_file` tool (0.28.0, ADR-0043) uses the same approval records with the `file_write` operation, but never starts a process: it writes only through the checkpointed apply in the @@ -1386,7 +1487,8 @@ nothing. Adding proposals with a workspace chosen also assigns them to it and a link to a file of another name, compares Windows folders ignoring case, sets `GH_PROMPT_DISABLED=1` and `GH_NO_UPDATE_NOTIFIER=1`, records no token, and is not qualified. Model runs have no network, so its commands that call GitHub, - such as `gh pr view`, fail. + such as `gh pr view`, fail, unless the workspace binds the profile to a + GitHub review host ([GitHub token for gh](#github-token-for-gh), ADR-0147). - **Inputs:** the standard install folders, the operator's `PATH`, `JAVA_HOME`, `GOROOT`, and `RUSTUP_HOME`, and small files the installers wrote (rustup's `settings.toml`, a JDK's `release`, Go's `VERSION`), each @@ -1439,7 +1541,8 @@ nothing. Adding proposals with a workspace chosen also assigns them to it when it is a runtime without a compiler, and that offline runs cannot download dependencies. -Known limits: a model command runs with no network, a 20-second deadline, and +Known limits: a model command runs with no network (apart from a bound `gh`, +ADR-0147), a 20-second deadline, and 1 GiB of memory, so a `cargo` build that needs crates.io dependencies fails unless they are already present. Only a trusted CLI `run --network` under the workspace's `task_network` preference can fetch them. Toolchains installed in diff --git a/docs/reviews.md b/docs/reviews.md index a7e5f0d1..f4e70648 100644 --- a/docs/reviews.md +++ b/docs/reviews.md @@ -102,7 +102,12 @@ A token that can read but not post still reviews; **Post** then fails with checked load, as the [security rules](security-coding-rules.md#git-and-credentials) require for every stored credential. - The token is sent only to the host's REST origin. A request to any other - origin never carries it. + origin never carries it. The one exception is a `github` host that a + workspace binds to its `gh` profile (ADR-0147): a model command that starts + that `gh` gets the token as `GH_TOKEN` in its environment, and `gh` sends it + to `github.com` and GitHub's API hosts only. The run's output has the + token's bytes replaced, and the run journal names the host, never the token. + See [GitHub token for gh](execution.md#github-token-for-gh). - A token that cannot be read stops the operation. There is no fallback to another token or to no token, and a host without a token cannot be used. diff --git a/docs/security-coding-rules.md b/docs/security-coding-rules.md index c26bbe6b..a6553e00 100644 --- a/docs/security-coding-rules.md +++ b/docs/security-coding-rules.md @@ -451,6 +451,15 @@ crate. - Keep model/API keys and Git credentials out of frontend state, model context, task environments, process arguments, logs, and error reports. Use narrow host-side credential services and redact before recording diagnostics. + One reviewed exception exists ([ADR-0147](adr/0147-give-a-bound-gh-profile-a-github-review-hosts-token.md)): + a `github` review host's token may be `GH_TOKEN` in the environment of a + model command whose program is the `gh` of a workspace profile the operator + bound to that host, under that decision's argument, configuration, network, + and output-redaction rules. Those rules must refuse every feature of `gh` + that can read its environment into output, such as a jq filter, or start a + child that inherits it, such as the editor or browser, because redaction + matches only the token's exact bytes. No other task environment may hold a + credential, and the trusted CLI `run` passes none. - Apply the same protections to subscription access/refresh tokens, login codes, and verifier values. Do not import unrelated client login caches or silently switch subscription requests to separately billed API usage. diff --git a/docs/workspace-permissions.md b/docs/workspace-permissions.md index bc853c15..65e575f5 100644 --- a/docs/workspace-permissions.md +++ b/docs/workspace-permissions.md @@ -824,7 +824,8 @@ with `profile_not_recorded` before any approval is requested Its first call records a pending approval and does not run; after `approvals approve `, a second identical call consumes the approval and starts the trusted run. The model cannot approve. -The tool uses fixed limits and no network or host services. See +The tool uses fixed limits and no network or host services, except that a +bound `gh` selects the network (ADR-0147). See [model command tool](execution.md#model-command-tool) and [ADR-0040](adr/0040-gate-the-model-command-tool-with-approvals-and-the-trusted-runner.md). The tool schema version is 0.12.0, which adds `workspace_git_write` (ADR-0134,