Skip to main content

gadk_cli/deploy/agentengine/
environment.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The Agent Engine deployment environment (`--env NAME=VALUE`, `--default_env`).
17//!
18//! `--env` values are kept as [`OsString`]s (the argument bytes) so a value that is not
19//! valid UTF-8 reaches [`AgentEngineFlags::environment_variables`] and gets ADK's error text.
20//! No error names an entry's name or value: a malformed entry may hold a secret.
21
22use std::ffi::OsString;
23
24use clap::{Arg, ArgAction, Command};
25use serde_json::{Value, json};
26
27use super::AgentEngineFlags;
28use crate::flags::bool_flag;
29
30/// The help text of `--env`.
31pub 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.";
32/// The help text of `--default_env`.
33pub 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/// One variable of the deployment environment. `Debug` shows the
36/// name only: values may be secrets.
37#[derive(Clone, Default, PartialEq, Eq)]
38pub struct EnvVar {
39    pub name: String,
40    pub value: String,
41}
42
43impl std::fmt::Debug for EnvVar {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.debug_struct("EnvVar")
46            .field("name", &self.name)
47            .field("value", &format_args!("<redacted>"))
48            .finish()
49    }
50}
51
52impl EnvVar {
53    fn new(name: &str, value: &str) -> EnvVar {
54        EnvVar {
55            name: name.to_string(),
56            value: value.to_string(),
57        }
58    }
59}
60
61/// Registers the environment flags: `--env` (repeatable,
62/// one value per occurrence, kept verbatim — no comma splitting) and
63/// `--default_env` (default true; a value only as `--default_env=<v>`).
64pub fn register_environment_flags(cmd: Command) -> Command {
65    // Repeated --env flags are used rather than Python's agent_config env_vars.
66    cmd.arg(
67        Arg::new("env")
68            .long("env")
69            .help(ENV_HELP)
70            .value_name("stringArray")
71            .action(ArgAction::Append)
72            .num_args(1)
73            .allow_hyphen_values(true)
74            .value_parser(clap::value_parser!(OsString)),
75    )
76    .arg(bool_flag("default_env", true, DEFAULT_ENV_HELP))
77}
78
79/// The pattern of an environment variable name: `^[a-zA-Z_][a-zA-Z0-9_]*$`.
80fn is_environment_name(name: &[u8]) -> bool {
81    match name.split_first() {
82        Some((first, rest)) => {
83            (first.is_ascii_alphabetic() || *first == b'_')
84                && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_')
85        }
86        None => false,
87    }
88}
89
90impl AgentEngineFlags {
91    /// Validates every `--env` entry (form `NAME=VALUE`, a name
92    /// matching `[a-zA-Z_][a-zA-Z0-9_]*`, no repeated name, a valid UTF-8 value), then returns
93    /// the defaults not overridden by an entry (when `--default_env`) followed by the entries
94    /// in flag order. Errors name the 1-based entry, never its contents.
95    pub fn environment_variables(&self) -> Result<Vec<EnvVar>, String> {
96        let mut custom: Vec<EnvVar> = Vec::with_capacity(self.agent_engine.env.len());
97        for (i, raw) in self.agent_engine.env.iter().enumerate() {
98            let n = i + 1;
99            let bytes = raw.as_encoded_bytes();
100            let split = bytes
101                .iter()
102                .position(|&b| b == b'=')
103                .map(|at| (&bytes[..at], &bytes[at + 1..]));
104            let Some((name, value)) = split.filter(|(name, _)| is_environment_name(name)) else {
105                // Do not echo malformed input: it may contain a secret, including when the
106                // user accidentally omitted NAME=.
107                return Err(format!(
108                    "--env entry {n} must have the form NAME=VALUE with a name matching [a-zA-Z_][a-zA-Z0-9_]*"
109                ));
110            };
111            // The name is ASCII (checked above).
112            let name = String::from_utf8_lossy(name);
113            if custom.iter().any(|e| e.name == name) {
114                return Err(format!(
115                    "--env entry {n} repeats an environment variable name"
116                ));
117            }
118            let Ok(value) = std::str::from_utf8(value) else {
119                return Err(format!("--env entry {n} must have a valid UTF-8 value"));
120            };
121            custom.push(EnvVar::new(&name, value));
122        }
123
124        let mut vars = Vec::new();
125        if self.agent_engine.default_env {
126            let defaults = [
127                EnvVar::new("GOOGLE_CLOUD_REGION", &self.gcloud.region),
128                EnvVar::new("NUM_WORKERS", "1"),
129                EnvVar::new("GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY", "true"),
130                EnvVar::new("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "true"),
131            ];
132            vars.extend(
133                defaults
134                    .into_iter()
135                    .filter(|d| !custom.iter().any(|e| e.name == d.name)),
136            );
137        }
138        // EnvVar expands references to previously defined variables. Keep custom flags in
139        // their original order, including overrides of a default.
140        vars.extend(custom);
141        Ok(vars)
142    }
143}
144
145/// The JSON form of the `ReasoningEngineSpec.DeploymentSpec` holding `vars` as `env`:
146/// an empty list is left out (`{}`) and so is an empty
147/// `value`.
148pub fn deployment_spec(vars: &[EnvVar]) -> Value {
149    if vars.is_empty() {
150        return json!({});
151    }
152    let env: Vec<Value> = vars
153        .iter()
154        .map(|v| {
155            if v.value.is_empty() {
156                json!({"name": v.name})
157            } else {
158                json!({"name": v.name, "value": v.value})
159            }
160        })
161        .collect();
162    json!({ "env": env })
163}
164
165#[cfg(test)]
166mod tests {
167    use pretty_assertions::assert_eq;
168
169    use super::*;
170
171    fn flags(env: &[&str], default_env: bool) -> AgentEngineFlags {
172        let mut f = AgentEngineFlags::default();
173        f.gcloud.region = "r".into();
174        f.agent_engine.env = env.iter().map(OsString::from).collect();
175        f.agent_engine.default_env = default_env;
176        f
177    }
178
179    #[test]
180    fn names_follow_go_pattern() {
181        for ok in ["A", "_", "a_1", "_9", "Z_BASE"] {
182            assert!(is_environment_name(ok.as_bytes()), "{ok}");
183        }
184        for bad in ["", "9A", "A-B", "A B", "é", "A.B"] {
185            assert!(!is_environment_name(bad.as_bytes()), "{bad}");
186        }
187    }
188
189    #[test]
190    fn defaults_first_unless_overridden_then_customs_in_flag_order() {
191        let got = flags(&["Z=5", "NUM_WORKERS=$(Z)", "E="], true)
192            .environment_variables()
193            .unwrap();
194        assert_eq!(
195            got,
196            vec![
197                EnvVar::new("GOOGLE_CLOUD_REGION", "r"),
198                EnvVar::new("GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY", "true"),
199                EnvVar::new("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "true"),
200                EnvVar::new("Z", "5"),
201                EnvVar::new("NUM_WORKERS", "$(Z)"),
202                EnvVar::new("E", ""),
203            ]
204        );
205        assert_eq!(flags(&[], false).environment_variables(), Ok(vec![]));
206        // The value is everything after the first `=`.
207        assert_eq!(
208            flags(&["A=b=c"], false).environment_variables(),
209            Ok(vec![EnvVar::new("A", "b=c")])
210        );
211    }
212
213    #[test]
214    fn errors_are_go_texts_and_never_echo_the_entry() {
215        let form = "must have the form NAME=VALUE with a name matching [a-zA-Z_][a-zA-Z0-9_]*";
216        for (env, want) in [
217            (vec!["SECRET"], format!("--env entry 1 {form}")),
218            (vec!["A=1", "=SECRET"], format!("--env entry 2 {form}")),
219            (
220                vec!["A=SECRET", "B=1", "A=SECRET"],
221                "--env entry 3 repeats an environment variable name".to_string(),
222            ),
223        ] {
224            let got = flags(&env, true).environment_variables().unwrap_err();
225            assert_eq!(got, want);
226            assert!(!got.contains("SECRET"));
227        }
228        use std::os::unix::ffi::OsStringExt;
229        let mut f = flags(&["A=1"], true);
230        f.agent_engine
231            .env
232            .push(OsString::from_vec(b"B=SECRET\xff".to_vec()));
233        assert_eq!(
234            f.environment_variables(),
235            Err("--env entry 2 must have a valid UTF-8 value".to_string())
236        );
237    }
238
239    #[test]
240    fn deployment_spec_is_protojson() {
241        assert_eq!(deployment_spec(&[]), json!({}));
242        assert_eq!(
243            deployment_spec(&[EnvVar::new("A", "1"), EnvVar::new("_empty", "")]),
244            json!({"env": [{"name": "A", "value": "1"}, {"name": "_empty"}]})
245        );
246    }
247
248    /// `--env` values may be secrets: `Debug` shows the names only.
249    #[test]
250    fn debug_redacts_env_values() {
251        let mut f = flags(&["API_KEY=s3cret-value", "bare-s3cret-value"], true);
252        f.agent_engine.env_vars = vec![EnvVar::new("API_KEY", "s3cret-value")];
253        let got = format!("{f:?}");
254        assert!(!got.contains("s3cret-value"), "{got}");
255        assert!(got.contains("API_KEY"), "{got}");
256        assert!(
257            got.contains(r#"env: ["API_KEY=<redacted>", "<redacted>"]"#),
258            "{got}"
259        );
260        let got = format!("{:?}", EnvVar::new("TOKEN", "s3cret-value"));
261        assert_eq!(got, r#"EnvVar { name: "TOKEN", value: <redacted> }"#);
262    }
263}