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    /// The variable name.
40    pub name: String,
41    /// The variable value.
42    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
63/// Registers the environment flags: `--env` (repeatable,
64/// one value per occurrence, kept verbatim — no comma splitting) and
65/// `--default_env` (default true; a value only as `--default_env=<v>`).
66pub fn register_environment_flags(cmd: Command) -> Command {
67    // Repeated --env flags are used rather than Python's agent_config env_vars.
68    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
81/// The pattern of an environment variable name: `^[a-zA-Z_][a-zA-Z0-9_]*$`.
82fn 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    /// Validates every `--env` entry (form `NAME=VALUE`, a name
94    /// matching `[a-zA-Z_][a-zA-Z0-9_]*`, no repeated name, a valid UTF-8 value), then returns
95    /// the defaults not overridden by an entry (when `--default_env`) followed by the entries
96    /// in flag order. Errors name the 1-based entry, never its contents.
97    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                // Do not echo malformed input: it may contain a secret, including when the
108                // user accidentally omitted NAME=.
109                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            // The name is ASCII (checked above).
114            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        // EnvVar expands references to previously defined variables. Keep custom flags in
141        // their original order, including overrides of a default.
142        vars.extend(custom);
143        Ok(vars)
144    }
145}
146
147/// The JSON form of the `ReasoningEngineSpec.DeploymentSpec` holding `vars` as `env`:
148/// an empty list is left out (`{}`) and so is an empty
149/// `value`.
150pub 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        // The value is everything after the first `=`.
209        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    /// `--env` values may be secrets: `Debug` shows the names only.
251    #[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}