gadk_cli/deploy/agentengine/
environment.rs1use std::ffi::OsString;
23
24use clap::{Arg, ArgAction, Command};
25use serde_json::{Value, json};
26
27use super::AgentEngineFlags;
28use crate::flags::bool_flag;
29
30pub const ENV_HELP: &str = "Environment variable NAME=VALUE (repeat --env for each variable). Overrides a default with the same name. On update, replaces the entire environment, including the defaults unless --default_env=false is set.";
32pub const DEFAULT_ENV_HELP: &str = "Include GOOGLE_CLOUD_REGION, NUM_WORKERS=1, GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY=true and OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true. Use --default_env=false to omit them. Explicitly setting this flag replaces the environment on update; omit both environment flags to preserve it.";
34
35#[derive(Clone, Default, PartialEq, Eq)]
38pub struct EnvVar {
39 pub name: String,
41 pub value: String,
43}
44
45impl std::fmt::Debug for EnvVar {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 f.debug_struct("EnvVar")
48 .field("name", &self.name)
49 .field("value", &format_args!("<redacted>"))
50 .finish()
51 }
52}
53
54impl EnvVar {
55 fn new(name: &str, value: &str) -> EnvVar {
56 EnvVar {
57 name: name.to_string(),
58 value: value.to_string(),
59 }
60 }
61}
62
63pub fn register_environment_flags(cmd: Command) -> Command {
67 cmd.arg(
69 Arg::new("env")
70 .long("env")
71 .help(ENV_HELP)
72 .value_name("stringArray")
73 .action(ArgAction::Append)
74 .num_args(1)
75 .allow_hyphen_values(true)
76 .value_parser(clap::value_parser!(OsString)),
77 )
78 .arg(bool_flag("default_env", true, DEFAULT_ENV_HELP))
79}
80
81fn is_environment_name(name: &[u8]) -> bool {
83 match name.split_first() {
84 Some((first, rest)) => {
85 (first.is_ascii_alphabetic() || *first == b'_')
86 && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_')
87 }
88 None => false,
89 }
90}
91
92impl AgentEngineFlags {
93 pub fn environment_variables(&self) -> Result<Vec<EnvVar>, String> {
98 let mut custom: Vec<EnvVar> = Vec::with_capacity(self.agent_engine.env.len());
99 for (i, raw) in self.agent_engine.env.iter().enumerate() {
100 let n = i + 1;
101 let bytes = raw.as_encoded_bytes();
102 let split = bytes
103 .iter()
104 .position(|&b| b == b'=')
105 .map(|at| (&bytes[..at], &bytes[at + 1..]));
106 let Some((name, value)) = split.filter(|(name, _)| is_environment_name(name)) else {
107 return Err(format!(
110 "--env entry {n} must have the form NAME=VALUE with a name matching [a-zA-Z_][a-zA-Z0-9_]*"
111 ));
112 };
113 let name = String::from_utf8_lossy(name);
115 if custom.iter().any(|e| e.name == name) {
116 return Err(format!(
117 "--env entry {n} repeats an environment variable name"
118 ));
119 }
120 let Ok(value) = std::str::from_utf8(value) else {
121 return Err(format!("--env entry {n} must have a valid UTF-8 value"));
122 };
123 custom.push(EnvVar::new(&name, value));
124 }
125
126 let mut vars = Vec::new();
127 if self.agent_engine.default_env {
128 let defaults = [
129 EnvVar::new("GOOGLE_CLOUD_REGION", &self.gcloud.region),
130 EnvVar::new("NUM_WORKERS", "1"),
131 EnvVar::new("GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY", "true"),
132 EnvVar::new("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "true"),
133 ];
134 vars.extend(
135 defaults
136 .into_iter()
137 .filter(|d| !custom.iter().any(|e| e.name == d.name)),
138 );
139 }
140 vars.extend(custom);
143 Ok(vars)
144 }
145}
146
147pub fn deployment_spec(vars: &[EnvVar]) -> Value {
151 if vars.is_empty() {
152 return json!({});
153 }
154 let env: Vec<Value> = vars
155 .iter()
156 .map(|v| {
157 if v.value.is_empty() {
158 json!({"name": v.name})
159 } else {
160 json!({"name": v.name, "value": v.value})
161 }
162 })
163 .collect();
164 json!({ "env": env })
165}
166
167#[cfg(test)]
168mod tests {
169 use pretty_assertions::assert_eq;
170
171 use super::*;
172
173 fn flags(env: &[&str], default_env: bool) -> AgentEngineFlags {
174 let mut f = AgentEngineFlags::default();
175 f.gcloud.region = "r".into();
176 f.agent_engine.env = env.iter().map(OsString::from).collect();
177 f.agent_engine.default_env = default_env;
178 f
179 }
180
181 #[test]
182 fn names_follow_go_pattern() {
183 for ok in ["A", "_", "a_1", "_9", "Z_BASE"] {
184 assert!(is_environment_name(ok.as_bytes()), "{ok}");
185 }
186 for bad in ["", "9A", "A-B", "A B", "é", "A.B"] {
187 assert!(!is_environment_name(bad.as_bytes()), "{bad}");
188 }
189 }
190
191 #[test]
192 fn defaults_first_unless_overridden_then_customs_in_flag_order() {
193 let got = flags(&["Z=5", "NUM_WORKERS=$(Z)", "E="], true)
194 .environment_variables()
195 .unwrap();
196 assert_eq!(
197 got,
198 vec![
199 EnvVar::new("GOOGLE_CLOUD_REGION", "r"),
200 EnvVar::new("GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY", "true"),
201 EnvVar::new("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "true"),
202 EnvVar::new("Z", "5"),
203 EnvVar::new("NUM_WORKERS", "$(Z)"),
204 EnvVar::new("E", ""),
205 ]
206 );
207 assert_eq!(flags(&[], false).environment_variables(), Ok(vec![]));
208 assert_eq!(
210 flags(&["A=b=c"], false).environment_variables(),
211 Ok(vec![EnvVar::new("A", "b=c")])
212 );
213 }
214
215 #[test]
216 fn errors_are_go_texts_and_never_echo_the_entry() {
217 let form = "must have the form NAME=VALUE with a name matching [a-zA-Z_][a-zA-Z0-9_]*";
218 for (env, want) in [
219 (vec!["SECRET"], format!("--env entry 1 {form}")),
220 (vec!["A=1", "=SECRET"], format!("--env entry 2 {form}")),
221 (
222 vec!["A=SECRET", "B=1", "A=SECRET"],
223 "--env entry 3 repeats an environment variable name".to_string(),
224 ),
225 ] {
226 let got = flags(&env, true).environment_variables().unwrap_err();
227 assert_eq!(got, want);
228 assert!(!got.contains("SECRET"));
229 }
230 use std::os::unix::ffi::OsStringExt;
231 let mut f = flags(&["A=1"], true);
232 f.agent_engine
233 .env
234 .push(OsString::from_vec(b"B=SECRET\xff".to_vec()));
235 assert_eq!(
236 f.environment_variables(),
237 Err("--env entry 2 must have a valid UTF-8 value".to_string())
238 );
239 }
240
241 #[test]
242 fn deployment_spec_is_protojson() {
243 assert_eq!(deployment_spec(&[]), json!({}));
244 assert_eq!(
245 deployment_spec(&[EnvVar::new("A", "1"), EnvVar::new("_empty", "")]),
246 json!({"env": [{"name": "A", "value": "1"}, {"name": "_empty"}]})
247 );
248 }
249
250 #[test]
252 fn debug_redacts_env_values() {
253 let mut f = flags(&["API_KEY=s3cret-value", "bare-s3cret-value"], true);
254 f.agent_engine.env_vars = vec![EnvVar::new("API_KEY", "s3cret-value")];
255 let got = format!("{f:?}");
256 assert!(!got.contains("s3cret-value"), "{got}");
257 assert!(got.contains("API_KEY"), "{got}");
258 assert!(
259 got.contains(r#"env: ["API_KEY=<redacted>", "<redacted>"]"#),
260 "{got}"
261 );
262 let got = format!("{:?}", EnvVar::new("TOKEN", "s3cret-value"));
263 assert_eq!(got, r#"EnvVar { name: "TOKEN", value: <redacted> }"#);
264 }
265}