Match bazel's filename requirements

Bazel has several requirements on filenames
* No absolute paths
* No up-references (../blah)
* No references to subpackages (foo/bar.cc, where foo/BUILD.gn exists).

The first two make perfect sense and should just be implemented.
The third rule isn't particularly useful, but not having it would make
any potential future migration to bazel much harder.

This is not a particularly hard requirement to meet in bazel due since
you can just pass targets exporting files instead of the files
themselves.

Bug: 528225104
Change-Id: I34e257c6e497be89c7d95e20e5c5e0046a6a6964
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/29300
Commit-Queue: Matt Stark <msta@google.com>
Reviewed-by: Takuto Ikuta <tikuta@google.com>
diff --git a/src/gn/starlark/Cargo.lock b/src/gn/starlark/Cargo.lock
index c9708b0..f77e822 100644
--- a/src/gn/starlark/Cargo.lock
+++ b/src/gn/starlark/Cargo.lock
@@ -2394,6 +2394,7 @@
  "starlark",
  "starlark_derive",
  "strum",
+ "tempfile",
  "thiserror",
 ]
 
diff --git a/src/gn/starlark/crates/attr/src/allow_files.rs b/src/gn/starlark/crates/attr/src/allow_files.rs
index 6b6fedf..70fb046 100644
--- a/src/gn/starlark/crates/attr/src/allow_files.rs
+++ b/src/gn/starlark/crates/attr/src/allow_files.rs
@@ -144,4 +144,33 @@
             assert!(!check_match("foo.cc", "bar.cc"));
         });
     }
+
+    #[test]
+    fn test_allow_files_rejects_up_references() {
+        let path_resolver = types::PathResolver::new_for_testing();
+        let pkg = PackageRef::new("//foo").unwrap();
+        let schema = AttrSchema {
+            kind: AttrKind::Label,
+            default: None,
+            disallow_empty: false,
+            allow_files: AllowFilesSchema::Many(AllowFiles::All),
+            cfg: AttrCfg::CurrentToolchain,
+            doc: String::new(),
+        };
+
+        starlark::values::Heap::temp(|heap| {
+            let err = Attr::create(
+                &schema,
+                Some(heap.alloc("../allow_files/file.cc")),
+                pkg,
+                &path_resolver,
+            )
+            .unwrap_err()
+            .to_string();
+            assert!(
+                err.contains("Invalid source file path"),
+                "unexpected error: {err}"
+            );
+        });
+    }
 }
diff --git a/src/gn/starlark/crates/types/Cargo.toml b/src/gn/starlark/crates/types/Cargo.toml
index ffb6514..bdddcf3 100644
--- a/src/gn/starlark/crates/types/Cargo.toml
+++ b/src/gn/starlark/crates/types/Cargo.toml
@@ -17,3 +17,6 @@
 starlark_derive = { workspace = true }
 strum = { workspace = true }
 thiserror = { workspace = true }
+
+[dev-dependencies]
+tempfile = { workspace = true }
diff --git a/src/gn/starlark/crates/types/src/ctx_state.rs b/src/gn/starlark/crates/types/src/ctx_state.rs
index 3e4a220..4ed9ce6 100644
--- a/src/gn/starlark/crates/types/src/ctx_state.rs
+++ b/src/gn/starlark/crates/types/src/ctx_state.rs
@@ -2,8 +2,6 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-use std::path::{Component, Path};
-
 use allocative::Allocative;
 use starlark::collections::SmallSet;
 use starlark_derive::Freeze;
@@ -69,12 +67,7 @@
 
     /// Declares a new output file relative to the target's output directory.
     pub fn declare_file(&mut self, name: &str) -> starlark::Result<File> {
-        if name.is_empty()
-            // Even on windows, for declare_file, we require using / for a path separator.
-            || name.contains('\\')
-            // Validate that the path is both relative and normalized.
-            || !Path::new(name).components().all(|c| matches!(c, Component::Normal(_)))
-        {
+        if !crate::util::is_normalized_relative_path(name) {
             return Err(crate::errors::Error::UnsupportedFilename(name.to_owned()).into());
         }
         let mut path = String::new();
diff --git a/src/gn/starlark/crates/types/src/errors.rs b/src/gn/starlark/crates/types/src/errors.rs
index 646d13c..9686481 100644
--- a/src/gn/starlark/crates/types/src/errors.rs
+++ b/src/gn/starlark/crates/types/src/errors.rs
@@ -22,6 +22,24 @@
     /// The referenced file does not exist on disk.
     #[error("File {1} does not exist in {0}")]
     FileNotFound(Package, String),
+    /// The referenced source file path is invalid (e.g. contains `..`, `.`,
+    /// backslashes, or is absolute).
+    #[error(
+        "Invalid source file path {1:?} in {0}: source paths must be normalized relative paths \
+         within the package"
+    )]
+    InvalidSourcePath(Package, String),
+    /// The referenced source file is inside a subdirectory containing a
+    /// `BUILD.gn` file.
+    #[error(
+        "Source file {path:?} in {package} is inside subpackage {subpackage} (directory contains \
+         a BUILD.gn)"
+    )]
+    SourceInSubpackage {
+        package: Package,
+        path: String,
+        subpackage: String,
+    },
     #[error("Invalid package, must start with \"//\": \"{0}\"")]
     NotAPackage(String),
     /// The output file was not declared by this target.
diff --git a/src/gn/starlark/crates/types/src/path_resolver.rs b/src/gn/starlark/crates/types/src/path_resolver.rs
index 6acbd9f..19ce280 100644
--- a/src/gn/starlark/crates/types/src/path_resolver.rs
+++ b/src/gn/starlark/crates/types/src/path_resolver.rs
@@ -2,14 +2,14 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-use std::path::PathBuf;
+use std::{collections::HashMap, path::PathBuf, sync::RwLock};
 
 use normalize_path::NormalizePath as _;
 
-use crate::{File, PackageRef};
+use crate::{File, Package, PackageRef};
 
 /// Resolves paths to Files relative to the root_build_dir.
-#[derive(Clone, Debug)]
+#[derive(Debug)]
 pub struct PathResolver {
     /// Absolute path to the root source dir on disk.
     source_root: PathBuf,
@@ -18,6 +18,8 @@
     /// Path to the root source dir relative to the root_build_dir.
     /// *Must* end with a trailing slash.
     source_root_rel: String,
+    /// Cache mapping packages to whether their `BUILD.gn` exists on disk.
+    package_exists_cache: RwLock<HashMap<Package, bool>>,
 }
 
 impl PathResolver {
@@ -29,6 +31,7 @@
             source_root: source_root.normalize(),
             build_root: build_root.normalize(),
             source_root_rel,
+            package_exists_cache: Default::default(),
         }
     }
 
@@ -43,6 +46,26 @@
         )
     }
 
+    /// Returns `true` if `package` contains a `BUILD.gn` file on disk, caching
+    /// the result for future lookups.
+    fn package_exists(&self, package: &PackageRef) -> bool {
+        if let Some(exists) = self
+            .package_exists_cache
+            .read()
+            .unwrap()
+            .get(package)
+            .copied()
+        {
+            return exists;
+        }
+        let exists = self.absolute_path(package, "BUILD.gn").is_file();
+        self.package_exists_cache
+            .write()
+            .unwrap()
+            .insert(package.to_owned(), exists);
+        exists
+    }
+
     /// Resolves an output file to its absolute on-disk path.
     /// The caller is responsible for ensuring that file is in the output
     /// directory.
@@ -69,17 +92,155 @@
     }
 
     /// Creates a `File` object for a file path relative to a package.
-    /// Validates that the file exists on disk.
+    /// Validates that the file is a normalized path within the package and
+    /// exists on disk.
     pub fn existing_source_file(&self, pkg: &PackageRef, s: &str) -> starlark::Result<File> {
+        if !crate::util::is_normalized_relative_path(s) {
+            return Err(crate::Error::InvalidSourcePath(pkg.to_owned(), s.to_owned()).into());
+        }
+        // Match Bazel's package boundary rule: files inside any subdirectory
+        // containing a BUILD.gn belong to that subpackage instead of `pkg`.
+        for (slash_idx, _) in s.match_indices('/') {
+            let subdir = &s[..slash_idx];
+            let subpackage = if pkg.is_root() {
+                format!("//{subdir}")
+            } else {
+                format!("{pkg}/{subdir}")
+            };
+            if self.package_exists(PackageRef::new(&subpackage).unwrap()) {
+                return Err(crate::Error::SourceInSubpackage {
+                    package: pkg.to_owned(),
+                    path: s.to_owned(),
+                    subpackage,
+                }
+                .into());
+            }
+        }
         // Gn *does not* check that the files you refer to exist on disk.
         // This is because native GN allows referencing generated files that do
         // not yet exist at `gn gen` time.
         // We explicitly disallow referencing generated files in starlark, so
         // we should validate that the files exist on disk for correctness.
-        if self.absolute_path(pkg, s).exists() {
+        if self.absolute_path(pkg, s).is_file() {
             Ok(self.source_file(pkg, s))
         } else {
             Err(crate::Error::FileNotFound(pkg.to_owned(), s.to_owned()).into())
         }
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_existing_source_file() {
+        let root = tempfile::tempdir().unwrap();
+        for rel in [
+            "BUILD.gn",
+            "other/file.cc",
+            "pkg/BUILD.gn",
+            "pkg/file.cc",
+            "pkg/plain/file.cc",
+            "pkg/plain/nested/ok.txt",
+            "pkg/subpkg/BUILD.gn",
+            "pkg/subpkg/direct.txt",
+            "pkg/subpkg/nested/deep.txt",
+            "root_subpkg/BUILD.gn",
+            "root_subpkg/in_root_sub.txt",
+        ] {
+            let p = root.path().join(rel);
+            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
+            std::fs::write(p, "").unwrap();
+        }
+
+        let resolver = PathResolver::new(
+            root.path().to_path_buf(),
+            root.path().join("out"),
+            "../".to_string(),
+        );
+        let pkg = PackageRef::new("//pkg").unwrap();
+        let subpkg = PackageRef::new("//pkg/subpkg").unwrap();
+
+        // Files in the package itself and non-subpackage directories are allowed.
+        assert_eq!(
+            resolver
+                .existing_source_file(PackageRef::root(), "other/file.cc")
+                .unwrap()
+                .as_str(),
+            "../other/file.cc"
+        );
+        assert_eq!(
+            resolver
+                .existing_source_file(pkg, "file.cc")
+                .unwrap()
+                .as_str(),
+            "../pkg/file.cc"
+        );
+        assert_eq!(
+            resolver
+                .existing_source_file(pkg, "plain/file.cc")
+                .unwrap()
+                .as_str(),
+            "../pkg/plain/file.cc"
+        );
+        assert_eq!(
+            resolver
+                .existing_source_file(pkg, "plain/nested/ok.txt")
+                .unwrap()
+                .as_str(),
+            "../pkg/plain/nested/ok.txt"
+        );
+
+        // Files inside a subpackage are allowed only when resolved from that subpackage.
+        assert_eq!(
+            resolver
+                .existing_source_file(subpkg, "direct.txt")
+                .unwrap()
+                .as_str(),
+            "../pkg/subpkg/direct.txt"
+        );
+        resolver
+            .existing_source_file(PackageRef::root(), "root_subpkg/in_root_sub.txt")
+            .unwrap_err();
+        resolver
+            .existing_source_file(pkg, "subpkg/direct.txt")
+            .unwrap_err();
+        resolver
+            .existing_source_file(pkg, "subpkg/nested/deep.txt")
+            .unwrap_err();
+
+        // Reject unnormalized, absolute, directory, missing, and cross-subpackage paths.
+        resolver
+            .existing_source_file(pkg, "../other/file.cc")
+            .unwrap_err();
+        resolver
+            .existing_source_file(pkg, "plain/../file.cc")
+            .unwrap_err();
+        resolver.existing_source_file(pkg, "./file.cc").unwrap_err();
+        resolver
+            .existing_source_file(pkg, "plain/./file.cc")
+            .unwrap_err();
+        resolver.existing_source_file(pkg, "/file.cc").unwrap_err();
+        resolver
+            .existing_source_file(pkg, "//pkg/file.cc")
+            .unwrap_err();
+        resolver
+            .existing_source_file(pkg, "plain\\file.cc")
+            .unwrap_err();
+        resolver.existing_source_file(pkg, "file.cc/").unwrap_err();
+        resolver.existing_source_file(pkg, "plain/").unwrap_err();
+        resolver.existing_source_file(pkg, "plain").unwrap_err();
+        resolver.existing_source_file(pkg, "subpkg").unwrap_err();
+        resolver
+            .existing_source_file(PackageRef::root(), "root_subpkg")
+            .unwrap_err();
+        resolver
+            .existing_source_file(pkg, "plain//file.cc")
+            .unwrap_err();
+        resolver
+            .existing_source_file(pkg, "nonexistent.cc")
+            .unwrap_err();
+        resolver.existing_source_file(pkg, "").unwrap_err();
+    }
+}
diff --git a/src/gn/starlark/crates/types/src/util.rs b/src/gn/starlark/crates/types/src/util.rs
index dedeeb4..3f7a158 100644
--- a/src/gn/starlark/crates/types/src/util.rs
+++ b/src/gn/starlark/crates/types/src/util.rs
@@ -14,6 +14,20 @@
     unsafe { std::mem::transmute(val) }
 }
 
+/// Returns `true` if `path` is a non-empty relative path normalized without `.`
+/// or `..` components and using `/` as the path separator.
+pub(crate) fn is_normalized_relative_path(path: &str) -> bool {
+    !path.is_empty()
+        // Even on windows, we require using / for a path separator.
+        && !path.contains('\\')
+        // Don't support drive letters. This is also ambiguous WRT labels.
+        // If this is too broad, we can specifically choose to allow labels
+        // and reject drive letters later.
+        && !path.contains(':')
+        // Also reject trailing slashes, empty segments, and internal `.` components.
+        && path.split('/').all(|s| !matches!(s, "" | "." | ".."))
+}
+
 /// De-duplicates elements in a small vector in-place while preserving relative order.
 ///
 /// This performs an O(N^2) linear scan, which is faster than allocating a