1+ use crate :: config:: find_config_path_with_default;
2+ use crate :: utils:: ErrorContext as EC ;
3+
4+ use anyhow:: { Context , Result } ;
15use clap:: ValueEnum ;
6+ use directories:: ProjectDirs ;
7+ use std:: collections:: BTreeSet ;
8+ use std:: fs;
9+ use std:: io:: { IsTerminal , Write } ;
10+ use std:: path:: { Path , PathBuf } ;
11+
12+ const TRUST_DIR_ENV : & str = "AST_GREP_TRUST_DIR" ;
213
3- #[ derive( Clone , Copy , Debug , Default , PartialEq , Eq , ValueEnum ) ]
14+ #[ derive( Clone , Copy , Debug , PartialEq , Eq , ValueEnum ) ]
415pub enum CustomLanguagePolicy {
516 /// Load native custom language libraries for this invocation.
617 Allow ,
718 /// Skip native custom language libraries without reporting an error.
8- #[ default]
919 Ignore ,
20+ /// Load native custom language libraries and remember this project.
21+ Trust ,
22+ /// Forget this project and ignore its native custom language libraries.
23+ Revoke ,
1024}
1125
1226#[ derive( Clone , Copy , Debug , PartialEq , Eq ) ]
@@ -15,16 +29,7 @@ pub enum CustomLanguageAction {
1529 Ignore ,
1630}
1731
18- impl From < CustomLanguagePolicy > for CustomLanguageAction {
19- fn from ( policy : CustomLanguagePolicy ) -> Self {
20- match policy {
21- CustomLanguagePolicy :: Allow => Self :: Load ,
22- CustomLanguagePolicy :: Ignore => Self :: Ignore ,
23- }
24- }
25- }
26-
27- pub fn parse_policy ( args : & [ String ] ) -> CustomLanguagePolicy {
32+ pub fn parse_policy ( args : & [ String ] ) -> Option < CustomLanguagePolicy > {
2833 let mut policy = None ;
2934 let mut i = 1 ;
3035 while i < args. len ( ) {
@@ -33,31 +38,137 @@ pub fn parse_policy(args: &[String]) -> CustomLanguagePolicy {
3338 break ;
3439 }
3540 let value = if arg == "--custom-languages" {
41+ if policy. is_some ( ) {
42+ return Some ( CustomLanguagePolicy :: Ignore ) ;
43+ }
44+ // Safe fallback while Clap handles a missing or invalid value.
45+ policy = Some ( CustomLanguagePolicy :: Ignore ) ;
3646 i += 1 ;
3747 args. get ( i) . map ( String :: as_str)
3848 } else {
39- arg. strip_prefix ( "--custom-languages=" )
49+ let value = arg. strip_prefix ( "--custom-languages=" ) ;
50+ if value. is_some ( ) {
51+ if policy. is_some ( ) {
52+ return Some ( CustomLanguagePolicy :: Ignore ) ;
53+ }
54+ policy = Some ( CustomLanguagePolicy :: Ignore ) ;
55+ }
56+ value
4057 } ;
4158 if let Some ( value) = value {
42- if policy. is_some ( ) {
43- return CustomLanguagePolicy :: Ignore ;
44- }
4559 policy = match value {
4660 "allow" => Some ( CustomLanguagePolicy :: Allow ) ,
4761 "ignore" => Some ( CustomLanguagePolicy :: Ignore ) ,
48- _ => return CustomLanguagePolicy :: Ignore ,
62+ "trust" => Some ( CustomLanguagePolicy :: Trust ) ,
63+ "revoke" => Some ( CustomLanguagePolicy :: Revoke ) ,
64+ _ => Some ( CustomLanguagePolicy :: Ignore ) ,
4965 } ;
5066 }
5167 i += 1 ;
5268 }
53- policy. unwrap_or_default ( )
69+ policy
70+ }
71+
72+ pub fn resolve (
73+ policy : Option < CustomLanguagePolicy > ,
74+ config_path : Option < & Path > ,
75+ ) -> Result < CustomLanguageAction > {
76+ match policy {
77+ Some ( CustomLanguagePolicy :: Trust ) => {
78+ eprintln ! (
79+ "WARNING: native custom languages execute code with your permissions. \
80+ ast-grep remembers the configuration path, not its contents."
81+ ) ;
82+ confirm_trust ( config_path) ?;
83+ set_trusted ( config_path, true ) ?;
84+ Ok ( CustomLanguageAction :: Load )
85+ }
86+ Some ( CustomLanguagePolicy :: Revoke ) => {
87+ set_trusted ( config_path, false ) ?;
88+ Ok ( CustomLanguageAction :: Ignore )
89+ }
90+ None if is_trusted ( config_path) => Ok ( CustomLanguageAction :: Load ) ,
91+ Some ( CustomLanguagePolicy :: Allow ) => Ok ( CustomLanguageAction :: Load ) ,
92+ Some ( CustomLanguagePolicy :: Ignore ) | None => Ok ( CustomLanguageAction :: Ignore ) ,
93+ }
94+ }
95+
96+ fn confirm_trust ( config_path : Option < & Path > ) -> Result < ( ) > {
97+ if !std:: io:: stdin ( ) . is_terminal ( ) || !std:: io:: stderr ( ) . is_terminal ( ) {
98+ return Err ( anyhow:: anyhow!( EC :: TrustRequiresInteractiveTerminal ) ) ;
99+ }
100+ let config_path = canonical_config_path ( config_path) ?;
101+ let prompt = format ! (
102+ "Trust native custom languages configured by {}?" ,
103+ config_path. display( )
104+ ) ;
105+ if !inquire:: Confirm :: new ( & prompt)
106+ . with_default ( false )
107+ . prompt ( ) ?
108+ {
109+ anyhow:: bail!( "Custom language trust was not granted" ) ;
110+ }
111+ Ok ( ( ) )
112+ }
113+
114+ fn is_trusted ( config_path : Option < & Path > ) -> bool {
115+ canonical_config_path ( config_path)
116+ . and_then ( |path| load_store ( ) . map ( |store| store. contains ( & path) ) )
117+ . unwrap_or ( false )
118+ }
119+
120+ fn set_trusted ( config_path : Option < & Path > , trusted : bool ) -> Result < ( ) > {
121+ let config_path = canonical_config_path ( config_path) ?;
122+ let mut store = load_store ( ) ?;
123+ let changed = if trusted {
124+ store. insert ( config_path)
125+ } else {
126+ store. remove ( & config_path)
127+ } ;
128+ if changed {
129+ save_store ( & store) ?;
130+ }
131+ Ok ( ( ) )
132+ }
133+
134+ fn load_store ( ) -> Result < BTreeSet < PathBuf > > {
135+ match fs:: read ( trust_store_path ( ) ?) {
136+ Ok ( json) => serde_json:: from_slice ( & json) . context ( "Cannot parse the ast-grep trust store" ) ,
137+ Err ( error) if error. kind ( ) == std:: io:: ErrorKind :: NotFound => Ok ( BTreeSet :: new ( ) ) ,
138+ Err ( error) => Err ( error) . context ( "Cannot read the ast-grep trust store" ) ,
139+ }
140+ }
141+
142+ fn save_store ( store : & BTreeSet < PathBuf > ) -> Result < ( ) > {
143+ let path = trust_store_path ( ) ?;
144+ let parent = path. parent ( ) . expect ( "trust store path has a parent" ) ;
145+ fs:: create_dir_all ( parent) . context ( "Cannot create the ast-grep configuration directory" ) ?;
146+ let mut temp = tempfile:: NamedTempFile :: new_in ( parent) ?;
147+ temp. write_all ( & serde_json:: to_vec_pretty ( store) ?) ?;
148+ temp. persist ( path) . map_err ( |error| error. error ) ?;
149+ Ok ( ( ) )
150+ }
151+
152+ fn trust_store_path ( ) -> Result < PathBuf > {
153+ if let Some ( path) = std:: env:: var_os ( TRUST_DIR_ENV ) {
154+ return Ok ( PathBuf :: from ( path) . join ( "trusted-configs.json" ) ) ;
155+ }
156+ let dirs = ProjectDirs :: from ( "" , "" , "ast-grep" )
157+ . context ( "Cannot determine the ast-grep configuration directory" ) ?;
158+ Ok ( dirs. config_dir ( ) . join ( "trusted-configs.json" ) )
159+ }
160+
161+ fn canonical_config_path ( config_path : Option < & Path > ) -> Result < PathBuf > {
162+ let config_path = find_config_path_with_default ( config_path. map ( Path :: to_path_buf) ) ?
163+ . context ( "Cannot find the ast-grep configuration file" ) ?;
164+ fs:: canonicalize ( config_path) . context ( "Cannot resolve the ast-grep configuration path" )
54165}
55166
56167#[ cfg( test) ]
57168mod test {
58169 use super :: * ;
59170
60- fn parse ( args : & [ & str ] ) -> CustomLanguagePolicy {
171+ fn parse ( args : & [ & str ] ) -> Option < CustomLanguagePolicy > {
61172 parse_policy (
62173 & args
63174 . iter ( )
@@ -68,14 +179,22 @@ mod test {
68179
69180 #[ test]
70181 fn test_parse_policy ( ) {
71- assert_eq ! ( parse( & [ "sg" , "scan" ] ) , CustomLanguagePolicy :: Ignore ) ;
182+ assert_eq ! ( parse( & [ "sg" , "scan" ] ) , None ) ;
72183 assert_eq ! (
73184 parse( & [ "sg" , "scan" , "--custom-languages=allow" ] ) ,
74- CustomLanguagePolicy :: Allow ,
185+ Some ( CustomLanguagePolicy :: Allow ) ,
75186 ) ;
76187 assert_eq ! (
77188 parse( & [ "sg" , "run" , "--" , "--custom-languages" , "allow" ] ) ,
78- CustomLanguagePolicy :: Ignore ,
189+ None ,
190+ ) ;
191+ assert_eq ! (
192+ parse( & [ "sg" , "scan" , "--custom-languages" , "trust" ] ) ,
193+ Some ( CustomLanguagePolicy :: Trust ) ,
194+ ) ;
195+ assert_eq ! (
196+ parse( & [ "sg" , "scan" , "--custom-languages=revoke" ] ) ,
197+ Some ( CustomLanguagePolicy :: Revoke ) ,
79198 ) ;
80199 }
81200}
0 commit comments