Skip to main content

gadk_cli/util/
text.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//! Text helpers for the generated Dockerfile and the console banners.
17//!
18//! The checks take bytes (`&str`, `String` and `&[u8]` all qualify) because a byte string can
19//! hold invalid UTF-8, which both checks reject; gadk's flag values are `String`s (clap rejects
20//! a non-UTF-8 argument), so that branch is reached only by direct callers.
21
22use gadk_platform::go_quote_bytes;
23
24/// `s` padded with spaces to width `w`, the extra space on the right; `w`
25/// counts bytes.
26pub fn center_string(s: &str, w: usize) -> String {
27    let sw = w as isize - s.len() as isize;
28    let lw = sw / 2;
29    let rw = sw - lw;
30    // A string wider than `w` gets no padding (the count is clamped at 0). No caller passes
31    // such a string.
32    " ".repeat(lw.max(0) as usize) + s + &" ".repeat(rw.max(0) as usize)
33}
34
35/// Rejects `"`, `` ` ``, `\`, every C0 control byte and invalid
36/// UTF-8, so a value embedded in a generated Dockerfile's exec-form `CMD` keeps the line a
37/// valid JSON array and reaches the container unchanged. The weaker of the two checks; a value
38/// that reaches a `RUN` line needs [`validate_shell_arg_safe`].
39pub fn validate_dockerfile_safe(s: impl AsRef<[u8]>, label: &str) -> Result<(), String> {
40    let s = s.as_ref();
41    // A byte loop: the property is about the bytes written to the file.
42    if s.iter()
43        .any(|&c| c == b'"' || c == b'`' || c == b'\\' || c < 0x20)
44    {
45        return Err(format!(
46            "{label} {} contains a character (quote, backtick, backslash, or a control character) that is not allowed in a value embedded in generated Dockerfile content",
47            go_quote_bytes(s)
48        ));
49    }
50    if std::str::from_utf8(s).is_err() {
51        return Err(format!(
52            "{label} {} is not valid UTF-8; the invalid bytes would reach the container as U+FFFD rather than as written",
53            go_quote_bytes(s)
54        ));
55    }
56    Ok(())
57}
58
59/// Admits only letters, digits, `.`, `/`, `-`, `_` and non-ASCII
60/// runes (valid UTF-8), the check for a value reaching a shell-form `RUN` line or a `COPY`
61/// operand.
62pub fn validate_shell_arg_safe(s: impl AsRef<[u8]>, label: &str) -> Result<(), String> {
63    let s = s.as_ref();
64    // A byte loop: every byte of a multi-byte rune is >= 0x80, so the class applies
65    // per byte and the UTF-8 check below rules out a stray high byte.
66    let allowed =
67        |c: u8| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b'/' | b'-') || c >= 0x80;
68    if !s.iter().all(|&c| allowed(c)) {
69        return Err(format!(
70            "{label} {} contains a character not allowed in a value embedded in generated Dockerfile content; whitespace splits COPY operands and shell metacharacters are live in a RUN line, so only letters, digits, '.', '/', '-', '_', and non-ASCII characters are permitted",
71            go_quote_bytes(s)
72        ));
73    }
74    if std::str::from_utf8(s).is_err() {
75        return Err(format!(
76            "{label} {} is not valid UTF-8; a COPY operand containing an invalid byte does not match the file it names",
77            go_quote_bytes(s)
78        ));
79    }
80    Ok(())
81}
82
83#[cfg(test)]
84mod tests {
85    use pretty_assertions::assert_eq;
86
87    use super::*;
88
89    /// Go `CenterString` outputs (`runGcloudProxy`'s banner lines at width 80).
90    #[test]
91    fn center_string_pads_like_go() {
92        assert_eq!(center_string("", 4), "    ");
93        assert_eq!(center_string("ab", 5), " ab  ");
94        assert_eq!(center_string("abc", 6), " abc  ");
95        assert_eq!(center_string("abcd", 4), "abcd");
96        assert_eq!(center_string("Press Ctrl-C to stop", 80).len(), 80);
97        assert_eq!(
98            center_string("Press Ctrl-C to stop", 80),
99            format!("{}Press Ctrl-C to stop{}", " ".repeat(30), " ".repeat(30))
100        );
101        // Non-ASCII counts bytes, as Go's `len`.
102        assert_eq!(center_string("é", 4), " é ");
103        assert_eq!(center_string("toolong", 3), "toolong");
104    }
105
106    #[test]
107    fn rejection_texts_are_go_verbatim() {
108        assert_eq!(
109            validate_dockerfile_safe("x\"y", "--a2a_agent_url").unwrap_err(),
110            r#"--a2a_agent_url "x\"y" contains a character (quote, backtick, backslash, or a control character) that is not allowed in a value embedded in generated Dockerfile content"#
111        );
112        assert_eq!(
113            validate_dockerfile_safe(b"http://x\xffy", "--a2a_agent_url").unwrap_err(),
114            r#"--a2a_agent_url "http://x\xffy" is not valid UTF-8; the invalid bytes would reach the container as U+FFFD rather than as written"#
115        );
116        assert_eq!(
117            validate_shell_arg_safe("main go", "label:").unwrap_err(),
118            r#"label: "main go" contains a character not allowed in a value embedded in generated Dockerfile content; whitespace splits COPY operands and shell metacharacters are live in a RUN line, so only letters, digits, '.', '/', '-', '_', and non-ASCII characters are permitted"#
119        );
120        assert_eq!(
121            validate_shell_arg_safe(b"agent\xff", "--source_dir").unwrap_err(),
122            r#"--source_dir "agent\xff" is not valid UTF-8; a COPY operand containing an invalid byte does not match the file it names"#
123        );
124        assert_eq!(
125            validate_dockerfile_safe("http://127.0.0.1:8081", "x"),
126            Ok(())
127        );
128        assert_eq!(validate_shell_arg_safe("agentes/café/main", "x"), Ok(()));
129    }
130}