-
Notifications
You must be signed in to change notification settings - Fork 6.4k
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
6
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.
+298
−0
Open
execpolicy helpers #7032
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1273f94
Add allow-prefix amendment helper to execpolicy
zhao-oai dbdece7
fmt
zhao-oai c727ec6
feat: adding prefix rules to existing policy
zhao-oai 9bf0d69
using json-serialize
zhao-oai f574da1
feat: advisory locks in amend
zhao-oai c5f0f62
fmt
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,150 @@ | ||
| use std::fs::OpenOptions; | ||
| 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 token {token}: {source}")] | ||
| SerializeToken { | ||
| token: String, | ||
| 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 read metadata for policy file {path}: {source}")] | ||
| PolicyMetadata { | ||
| path: PathBuf, | ||
| source: std::io::Error, | ||
| }, | ||
| } | ||
|
|
||
| pub fn append_allow_prefix_rule(policy_path: &Path, prefix: &[String]) -> Result<(), AmendError> { | ||
| if prefix.is_empty() { | ||
| return Err(AmendError::EmptyPrefix); | ||
| } | ||
|
|
||
| let tokens: Vec<String> = prefix | ||
| .iter() | ||
| .map(|token| { | ||
| serde_json::to_string(token).map_err(|source| AmendError::SerializeToken { | ||
| token: token.clone(), | ||
| source, | ||
| }) | ||
| }) | ||
| .collect::<Result<_, _>>()?; | ||
| let pattern = tokens.join(", "); | ||
| let rule = format!("prefix_rule(pattern=[{pattern}], decision=\"allow\")\n"); | ||
|
|
||
| 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, | ||
| }); | ||
| } | ||
| } | ||
| let mut file = OpenOptions::new() | ||
zhao-oai marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| .create(true) | ||
| .append(true) | ||
| .open(policy_path) | ||
| .map_err(|source| AmendError::OpenPolicyFile { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| })?; | ||
| let needs_newline = file | ||
| .metadata() | ||
| .map(|metadata| metadata.len() > 0) | ||
| .map_err(|source| AmendError::PolicyMetadata { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| })?; | ||
| let final_rule = if needs_newline { | ||
| format!("\n{rule}") | ||
| } else { | ||
| rule | ||
| }; | ||
|
|
||
| file.write_all(final_rule.as_bytes()) | ||
| .map_err(|source| AmendError::WritePolicyFile { | ||
| path: policy_path.to_path_buf(), | ||
| source, | ||
| }) | ||
| } | ||
|
|
||
| #[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"); | ||
|
|
||
| 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, | ||
| "prefix_rule(pattern=[\"echo\", \"Hello, world!\"], decision=\"allow\")\n" | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn separates_rules_with_newlines_when_appending() { | ||
| 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, | ||
| "prefix_rule(pattern=[\"ls\"], decision=\"allow\")\n", | ||
| ) | ||
| .expect("write seed rule"); | ||
|
|
||
| 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, | ||
| "prefix_rule(pattern=[\"ls\"], decision=\"allow\")\n\nprefix_rule(pattern=[\"echo\", \"Hello, world!\"], decision=\"allow\")\n" | ||
| ); | ||
| } | ||
| } | ||
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.
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.