-
Notifications
You must be signed in to change notification settings - Fork 6.5k
execpolicy helpers #7032
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zhao-oai
wants to merge
15
commits into
main
Choose a base branch
from
pr7032
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+336
−35
Open
execpolicy helpers #7032
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
43f28cc
Add allow-prefix amendment helper to execpolicy
zhao-oai 73ecd7c
fmt
zhao-oai 154ab8b
feat: adding prefix rules to existing policy
zhao-oai b544a5b
using json-serialize
zhao-oai e896cf5
feat: advisory locks in amend
zhao-oai 71b53b2
fmt
zhao-oai ac15fcb
one write_all
zhao-oai ade87ae
using r#
zhao-oai a3c3db1
removing explicit file.unlock()
zhao-oai 22b6e38
deferring to_path_buf() construction
zhao-oai dfb4cb0
adding comment
zhao-oai 8a9a475
function rename + docstring
zhao-oai 6e4a66b
tests now output -> Result<()>
zhao-oai 96e3f80
fix test error assertion
zhao-oai 96a8e47
serializing commands nicely
zhao-oai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,226 @@ | ||
| use std::fs::OpenOptions; | ||
| use std::io::Read; | ||
| use std::io::Seek; | ||
| use std::io::SeekFrom; | ||
| use std::io::Write; | ||
| use std::path::Path; | ||
| use std::path::PathBuf; | ||
|
|
||
| use serde_json; | ||
| use thiserror::Error; | ||
|
|
||
| #[derive(Debug, Error)] | ||
| pub enum AmendError { | ||
| #[error("prefix rule requires at least one token")] | ||
| EmptyPrefix, | ||
| #[error("policy path has no parent: {path}")] | ||
| MissingParent { path: PathBuf }, | ||
| #[error("failed to create policy directory {dir}: {source}")] | ||
| CreatePolicyDir { | ||
| dir: PathBuf, | ||
| source: std::io::Error, | ||
| }, | ||
| #[error("failed to format prefix tokens: {source}")] | ||
| SerializePrefix { source: serde_json::Error }, | ||
| #[error("failed to open policy file {path}: {source}")] | ||
| OpenPolicyFile { | ||
| path: PathBuf, | ||
| source: std::io::Error, | ||
| }, | ||
| #[error("failed to write to policy file {path}: {source}")] | ||
| WritePolicyFile { | ||
| path: PathBuf, | ||
| source: std::io::Error, | ||
| }, | ||
| #[error("failed to lock policy file {path}: {source}")] | ||
| LockPolicyFile { | ||
| path: PathBuf, | ||
| source: std::io::Error, | ||
| }, | ||
| #[error("failed to seek policy file {path}: {source}")] | ||
| SeekPolicyFile { | ||
| path: PathBuf, | ||
| source: std::io::Error, | ||
| }, | ||
| #[error("failed to read policy file {path}: {source}")] | ||
| ReadPolicyFile { | ||
| path: PathBuf, | ||
| source: std::io::Error, | ||
| }, | ||
| #[error("failed to read metadata for policy file {path}: {source}")] | ||
| PolicyMetadata { | ||
| path: PathBuf, | ||
| source: std::io::Error, | ||
| }, | ||
| } | ||
|
|
||
| /// Note this thread uses advisory file locking and performs blocking I/O, so it should be used with | ||
| /// [`tokio::task::spawn_blocking`] when called from an async context. | ||
| pub fn blocking_append_allow_prefix_rule( | ||
| policy_path: &Path, | ||
| prefix: &[String], | ||
| ) -> Result<(), AmendError> { | ||
| if prefix.is_empty() { | ||
| return Err(AmendError::EmptyPrefix); | ||
| } | ||
|
|
||
| let tokens = prefix | ||
| .iter() | ||
| .map(serde_json::to_string) | ||
| .collect::<Result<Vec<_>, _>>() | ||
| .map_err(|source| AmendError::SerializePrefix { source })?; | ||
| let pattern = format!("[{}]", tokens.join(", ")); | ||
| let rule = format!(r#"prefix_rule(pattern={pattern}, decision="allow")"#); | ||
|
|
||
| let dir = policy_path | ||
| .parent() | ||
| .ok_or_else(|| AmendError::MissingParent { | ||
| path: policy_path.to_path_buf(), | ||
| })?; | ||
| match std::fs::create_dir(dir) { | ||
| Ok(()) => {} | ||
| Err(ref source) if source.kind() == std::io::ErrorKind::AlreadyExists => {} | ||
| Err(source) => { | ||
| return Err(AmendError::CreatePolicyDir { | ||
| dir: dir.to_path_buf(), | ||
| source, | ||
| }); | ||
| } | ||
| } | ||
| append_locked_line(policy_path, &rule) | ||
| } | ||
|
|
||
| fn append_locked_line(policy_path: &Path, line: &str) -> Result<(), AmendError> { | ||
| let mut file = OpenOptions::new() | ||
| .create(true) | ||
| .read(true) | ||
| .append(true) | ||
| .open(policy_path) | ||
| .map_err(|source| AmendError::OpenPolicyFile { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| })?; | ||
| file.lock().map_err(|source| AmendError::LockPolicyFile { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| })?; | ||
|
|
||
| let len = file | ||
| .metadata() | ||
| .map_err(|source| AmendError::PolicyMetadata { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| })? | ||
| .len(); | ||
|
|
||
| // Ensure file ends in a newline before appending. | ||
| if len > 0 { | ||
zhao-oai marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| file.seek(SeekFrom::End(-1)) | ||
| .map_err(|source| AmendError::SeekPolicyFile { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| })?; | ||
| let mut last = [0; 1]; | ||
| file.read_exact(&mut last) | ||
| .map_err(|source| AmendError::ReadPolicyFile { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| })?; | ||
|
|
||
| if last[0] != b'\n' { | ||
| file.write_all(b"\n") | ||
| .map_err(|source| AmendError::WritePolicyFile { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| })?; | ||
| } | ||
| } | ||
|
|
||
| file.write_all(format!("{line}\n").as_bytes()) | ||
| .map_err(|source| AmendError::WritePolicyFile { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| })?; | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use pretty_assertions::assert_eq; | ||
| use tempfile::tempdir; | ||
|
|
||
| #[test] | ||
| fn appends_rule_and_creates_directories() { | ||
| let tmp = tempdir().expect("create temp dir"); | ||
| let policy_path = tmp.path().join("policy").join("default.codexpolicy"); | ||
|
|
||
| blocking_append_allow_prefix_rule( | ||
| &policy_path, | ||
| &[String::from("echo"), String::from("Hello, world!")], | ||
| ) | ||
| .expect("append rule"); | ||
|
|
||
| let contents = | ||
| std::fs::read_to_string(&policy_path).expect("default.codexpolicy should exist"); | ||
| assert_eq!( | ||
| contents, | ||
| r#"prefix_rule(pattern=["echo", "Hello, world!"], decision="allow") | ||
| "# | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn appends_rule_without_duplicate_newline() { | ||
| let tmp = tempdir().expect("create temp dir"); | ||
| let policy_path = tmp.path().join("policy").join("default.codexpolicy"); | ||
| std::fs::create_dir_all(policy_path.parent().unwrap()).expect("create policy dir"); | ||
| std::fs::write( | ||
| &policy_path, | ||
| r#"prefix_rule(pattern=["ls"], decision="allow") | ||
| "#, | ||
| ) | ||
| .expect("write seed rule"); | ||
|
|
||
| blocking_append_allow_prefix_rule( | ||
| &policy_path, | ||
| &[String::from("echo"), String::from("Hello, world!")], | ||
| ) | ||
| .expect("append rule"); | ||
|
|
||
| let contents = std::fs::read_to_string(&policy_path).expect("read policy"); | ||
| assert_eq!( | ||
| contents, | ||
| r#"prefix_rule(pattern=["ls"], decision="allow") | ||
| prefix_rule(pattern=["echo", "Hello, world!"], decision="allow") | ||
| "# | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn inserts_newline_when_missing_before_append() { | ||
| let tmp = tempdir().expect("create temp dir"); | ||
| let policy_path = tmp.path().join("policy").join("default.codexpolicy"); | ||
| std::fs::create_dir_all(policy_path.parent().unwrap()).expect("create policy dir"); | ||
| std::fs::write( | ||
| &policy_path, | ||
| r#"prefix_rule(pattern=["ls"], decision="allow")"#, | ||
| ) | ||
| .expect("write seed rule without newline"); | ||
|
|
||
| blocking_append_allow_prefix_rule( | ||
| &policy_path, | ||
| &[String::from("echo"), String::from("Hello, world!")], | ||
| ) | ||
| .expect("append rule"); | ||
|
|
||
| let contents = std::fs::read_to_string(&policy_path).expect("read policy"); | ||
| assert_eq!( | ||
| contents, | ||
| r#"prefix_rule(pattern=["ls"], decision="allow") | ||
| prefix_rule(pattern=["echo", "Hello, world!"], decision="allow") | ||
| "# | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.