[Backport release-26.11] envoy: update to 1.40.2 and rebuild derivation (#596076)

This commit is contained in:
Luke Granger-Brown
2026-12-02 21:19:11 +00:00
committed by GitHub
32 changed files with 10987 additions and 764 deletions

View File

@@ -1,85 +0,0 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Paul Meyer <49727155+katexochen@users.noreply.github.com>
Date: Mon, 22 Apr 2024 11:52:59 +0200
Subject: [PATCH] nixpkgs: use system Python
Signed-off-by: Paul Meyer <49727155+katexochen@users.noreply.github.com>
Signed-off-by: Luke Granger-Brown <git@lukegb.com>
---
bazel/python_dependencies.bzl | 9 ++++-----
bazel/repositories_extra.bzl | 17 +----------------
2 files changed, 5 insertions(+), 21 deletions(-)
diff --git a/bazel/python_dependencies.bzl b/bazel/python_dependencies.bzl
index 9867dc3a46dbe780eb3c02bad8f6a22a2c7fd97e..ff8685e0e437aee447218e912f1cf3e494755cf4 100644
--- a/bazel/python_dependencies.bzl
+++ b/bazel/python_dependencies.bzl
@@ -3,25 +3,24 @@ load("@envoy_toolshed//:packages.bzl", "load_packages")
load("@rules_python//python:pip.bzl", "pip_parse")
def envoy_python_dependencies():
- # TODO(phlax): rename base_pip3 -> pip3 and remove this
- load_packages()
+ pip_parse(
+ name = "pip3",
+ requirements_lock = "@envoy_toolshed//:requirements.txt",
+ )
pip_parse(
name = "base_pip3",
- python_interpreter_target = "@python3_12_host//:python",
requirements_lock = "@envoy//tools/base:requirements.txt",
extra_pip_args = ["--require-hashes"],
)
pip_parse(
name = "dev_pip3",
- python_interpreter_target = "@python3_12_host//:python",
requirements_lock = "@envoy//tools/dev:requirements.txt",
extra_pip_args = ["--require-hashes"],
)
pip_parse(
name = "fuzzing_pip3",
- python_interpreter_target = "@python3_12_host//:python",
requirements_lock = "@rules_fuzzing//fuzzing:requirements.txt",
extra_pip_args = ["--require-hashes"],
)
diff --git a/bazel/repositories_extra.bzl b/bazel/repositories_extra.bzl
index 84e2a69c092fa4c824401a52b2c39a49f83d0837..e5afd5743613ad5fdbf7b28a99b6d1b5902566ac 100644
--- a/bazel/repositories_extra.bzl
+++ b/bazel/repositories_extra.bzl
@@ -4,19 +4,11 @@ load("@com_google_protobuf//bazel/private:proto_bazel_features.bzl", "proto_baze
load("@emsdk//:deps.bzl", emsdk_deps = "deps")
load("@envoy_examples//bazel:env.bzl", "envoy_examples_env")
load("@proxy_wasm_cpp_host//bazel/cargo/wasmtime/remote:crates.bzl", "crate_repositories")
-load("@rules_python//python:repositories.bzl", "py_repositories", "python_register_toolchains")
+load("@rules_python//python:repositories.bzl", "py_repositories")
load("//bazel/external/cargo:crates.bzl", "raze_fetch_remote_crates")
-def _python_minor_version(python_version):
- return "_".join(python_version.split(".")[:-1])
-
-# Python version for `rules_python`
-PYTHON_VERSION = "3.12.3"
-PYTHON_MINOR_VERSION = _python_minor_version(PYTHON_VERSION)
-
# Envoy deps that rely on a first stage of dependency loading in envoy_dependencies().
def envoy_dependencies_extra(
- python_version = PYTHON_VERSION,
ignore_root_user_error = False):
bazel_features_deps()
emsdk_deps()
@@ -24,13 +16,6 @@ def envoy_dependencies_extra(
crate_repositories()
py_repositories()
- # Registers underscored Python minor version - eg `python3_10`
- python_register_toolchains(
- name = "python%s" % _python_minor_version(python_version),
- python_version = python_version,
- ignore_root_user_error = ignore_root_user_error,
- )
-
aspect_bazel_lib_dependencies()
if not native.existing_rule("proto_bazel_features"):

View File

@@ -1,29 +0,0 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Paul Meyer <49727155+katexochen@users.noreply.github.com>
Date: Mon, 22 Apr 2024 11:59:22 +0200
Subject: [PATCH] nixpkgs: use system C/C++ toolchains
Signed-off-by: Paul Meyer <49727155+katexochen@users.noreply.github.com>
Signed-off-by: Luke Granger-Brown <git@lukegb.com>
---
bazel/dependency_imports.bzl | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/bazel/dependency_imports.bzl b/bazel/dependency_imports.bzl
index 10be4b0b3f65e486c1dc8419337a5cf823431774..b0badb3ccab3b112043bd8616770f8014238d396 100644
--- a/bazel/dependency_imports.bzl
+++ b/bazel/dependency_imports.bzl
@@ -40,7 +40,11 @@ def envoy_dependency_imports(
yq_version = YQ_VERSION,
buf_sha = BUF_SHA,
buf_version = BUF_VERSION):
compatibility_proxy_repo()
- rules_foreign_cc_dependencies()
+ rules_foreign_cc_dependencies(
+ register_default_tools=False, # no prebuilt toolchains
+ register_built_tools=False, # nor from source
+ register_preinstalled_tools=True, # use host tools (default)
+ )
go_rules_dependencies()
go_register_toolchains(go_version)
if go_version != "host":

View File

@@ -1,34 +0,0 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Luke Granger-Brown <git@lukegb.com>
Date: Thu, 17 Apr 2025 02:40:18 +0100
Subject: [PATCH] nixpkgs: bump rules_rust to 0.60.0
Signed-off-by: Luke Granger-Brown <git@lukegb.com>
---
bazel/repository_locations.bzl | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/bazel/repository_locations.bzl b/bazel/repository_locations.bzl
index 1293e432c815071ed55721760e583ac0e9f40108..664f8c8e2bf4641e7862e9321fd6f91d162c3c17 100644
--- a/bazel/repository_locations.bzl
+++ b/bazel/repository_locations.bzl
@@ -1528,8 +1528,8 @@ REPOSITORY_LOCATIONS_SPEC = dict(
project_name = "Bazel rust rules",
project_desc = "Bazel rust rules (used by Wasm)",
project_url = "https://github.com/bazelbuild/rules_rust",
- version = "0.56.0",
- sha256 = "f1306aac0b258b790df01ad9abc6abb0df0b65416c74b4ef27f4aab298780a64",
+ version = "0.60.0",
+ sha256 = "7825214ccad7c2482cb490ac91dbc1e88b30223062796ce328aca893b74ae342",
# Note: rules_rust should point to the releases, not archive to avoid the hassle of bootstrapping in crate_universe.
# This is described in https://bazelbuild.github.io/rules_rust/crate_universe.html#setup, otherwise bootstrap
# is required which in turn requires a system CC toolchains, not the bazel controlled ones.
@@ -1540,7 +1540,7 @@ REPOSITORY_LOCATIONS_SPEC = dict(
"dataplane_ext",
],
extensions = ["envoy.wasm.runtime.wasmtime"],
- release_date = "2024-12-16",
+ release_date = "2025-04-08",
cpe = "N/A",
license = "Apache-2.0",
license_url = "https://github.com/bazelbuild/rules_rust/blob/{version}/LICENSE.txt",

View File

@@ -1,79 +0,0 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Daniel Baker <dan@djacu.dev>
Date: Thu, 30 Apr 2026 08:42:44 -0700
Subject: [PATCH] nixpkgs: pin Go SDK downloads
Pin Go SDK downloads to avoid fetching the mutable version listing from
https://go.dev/dl/?mode=json&include=all. Without explicit sdks, each
go_download_sdk call downloads that listing (which changes with every Go
release) and caches it in repository_cache, causing the deps hash to
drift. See: io_bazel_rules_go/go/private/sdk.bzl lines 74-93 (rules_go
v0.50.0)
Signed-off-by: Daniel Baker <dan@djacu.dev>
---
bazel/dependency_imports.bzl | 19 ++++++++++++++++++-
1 file changed, 18 insertions(+), 1 deletion(-)
diff --git a/bazel/dependency_imports.bzl b/bazel/dependency_imports.bzl
index 90e49d5ceb0024b57481b816518990f58fc2ad5f..26091a877ea3951bfe69944ab8580857e787bb64 100644
--- a/bazel/dependency_imports.bzl
+++ b/bazel/dependency_imports.bzl
@@ -27,6 +27,18 @@ load("@rules_rust//rust:repositories.bzl", "rules_rust_dependencies", "rust_regi
# go version for rules_go
GO_VERSION = "1.24.6"
+# Pin Go SDK downloads to avoid fetching the mutable version listing from
+# https://go.dev/dl/?mode=json&include=all. Without explicit sdks, each
+# go_download_sdk call downloads that listing (which changes with every Go
+# release) and caches it in repository_cache, causing the deps hash to drift.
+# See: io_bazel_rules_go/go/private/sdk.bzl lines 74-93 (rules_go v0.50.0)
+_GO_SDKS = {
+ "linux_amd64": ["go" + GO_VERSION + ".linux-amd64.tar.gz", "bbca37cc395c974ffa4893ee35819ad23ebb27426df87af92e93a9ec66ef8712"],
+ "linux_arm64": ["go" + GO_VERSION + ".linux-arm64.tar.gz", "124ea6033a8bf98aa9fbab53e58d134905262d45a022af3a90b73320f3c3afd5"],
+ "darwin_amd64": ["go" + GO_VERSION + ".darwin-amd64.tar.gz", "4a8d7a32052f223e71faab424a69430455b27b3fff5f4e651f9d97c3e51a8746"],
+ "darwin_arm64": ["go" + GO_VERSION + ".darwin-arm64.tar.gz", "4e29202c49573b953be7cc3500e1f8d9e66ddd12faa8cf0939a4951411e09a2a"],
+}
+
JQ_VERSION = "1.7"
YQ_VERSION = "4.24.4"
@@ -46,7 +58,8 @@ def envoy_dependency_imports(
register_preinstalled_tools=True, # use host tools (default)
)
go_rules_dependencies()
- go_register_toolchains(go_version)
+ go_download_sdk(name = "go_sdk", version = go_version, sdks = _GO_SDKS)
+ go_register_toolchains()
if go_version != "host":
envoy_download_go_sdks(go_version)
gazelle_dependencies(go_sdk = "go_sdk")
@@ -218,24 +231,28 @@ def envoy_download_go_sdks(go_version):
goos = "linux",
goarch = "amd64",
version = go_version,
+ sdks = _GO_SDKS,
)
go_download_sdk(
name = "go_linux_arm64",
goos = "linux",
goarch = "arm64",
version = go_version,
+ sdks = _GO_SDKS,
)
go_download_sdk(
name = "go_darwin_amd64",
goos = "darwin",
goarch = "amd64",
version = go_version,
+ sdks = _GO_SDKS,
)
go_download_sdk(
name = "go_darwin_arm64",
goos = "darwin",
goarch = "arm64",
version = go_version,
+ sdks = _GO_SDKS,
)
def crates_repositories():

View File

@@ -0,0 +1,33 @@
load("@rules_rust//rust:toolchain.bzl", "rust_stdlib_filegroup", "rust_toolchain")
package(default_visibility = ["//visibility:public"])
rust_stdlib_filegroup(
name = "rust_stdlib",
srcs = glob(["rust_lib/**"]),
)
rust_toolchain(
name = "rust_nix_impl",
binary_ext = "",
cargo = "bin/cargo",
clippy_driver = "bin/clippy-driver",
default_edition = "2021",
dylib_ext = "@dylib_ext@",
exec_triple = "@rust_triple@",
rust_doc = "bin/rustdoc",
rust_std = ":rust_stdlib",
rustc = "bin/rustc",
staticlib_ext = ".a",
stdlib_linkflags = [
"-lpthread",
"-ldl",
],
target_triple = "@rust_triple@",
)
toolchain(
name = "rust_nix_toolchain",
toolchain = ":rust_nix_impl",
toolchain_type = "@rules_rust//rust:toolchain_type",
)

View File

@@ -0,0 +1,77 @@
load("@bazel_tools//tools/sh:sh_toolchain.bzl", "sh_toolchain")
load("@rules_python//python:defs.bzl", "py_runtime", "py_runtime_pair")
load("@rules_python//python:py_exec_tools_toolchain.bzl", "py_exec_tools_toolchain")
package(default_visibility = ["//visibility:public"])
sh_toolchain(
name = "local_sh",
path = "@bash@",
)
toolchain(
name = "local_sh_toolchain",
toolchain = ":local_sh",
toolchain_type = "@bazel_tools//tools/sh:toolchain_type",
)
py_runtime(
name = "local_py3",
interpreter_path = "@python3@",
python_version = "PY3",
stub_shebang = "#!@python3@",
)
py_runtime_pair(
name = "local_py_runtime_pair",
py3_runtime = ":local_py3",
)
toolchain(
name = "local_py_toolchain",
toolchain = ":local_py_runtime_pair",
toolchain_type = "@rules_python//python:toolchain_type",
)
py_exec_tools_toolchain(
name = "local_py_exec_tools",
precompiler = "@rules_python//tools/precompiler:precompiler",
)
toolchain(
name = "local_py_exec_tools_toolchain",
toolchain = ":local_py_exec_tools",
toolchain_type = "@rules_python//python:exec_tools_toolchain_type",
)
toolchain(
name = "local_jdk_runtime_toolchain",
toolchain = "@local_jdk//:jdk",
toolchain_type = "@bazel_tools//tools/jdk:runtime_toolchain_type",
)
toolchain(
name = "local_jdk_bootstrap_runtime_toolchain",
toolchain = "@local_jdk//:jdk",
toolchain_type = "@bazel_tools//tools/jdk:bootstrap_runtime_toolchain_type",
)
platform(
name = "darwin_arm64",
constraint_values = [
"@platforms//cpu:aarch64",
"@platforms//os:macos",
],
)
# Synthetic C++ toolchain alias for cross-platform `--nobuild` dependency
# discovery from Linux hosts; not registered during normal builds.
toolchain(
name = "darwin_arm64_cc_toolchain",
target_compatible_with = [
"@platforms//cpu:aarch64",
"@platforms//os:macos",
],
toolchain = "@local_config_cc//:@cc_compiler@",
toolchain_type = "@bazel_tools//tools/cpp:toolchain_type",
)

View File

@@ -1,68 +0,0 @@
load("@bazel_tools//tools/sh:sh_toolchain.bzl", "sh_toolchain")
load("@rules_rust//rust:toolchain.bzl", "rust_toolchain")
load("@rules_rust//rust:defs.bzl", "rust_stdlib_filegroup")
toolchains = {
"x86_64": "x86_64-unknown-linux-gnu",
"aarch64": "aarch64-unknown-linux-gnu",
}
exports_files(["cargo", "rustdoc", "rustc"])
[
rust_stdlib_filegroup(
name = "rust_nix_" + k + "_stdlib",
srcs = glob(
[
"rustcroot/lib/rustlib/" + v + "/lib/**",
],
allow_empty=True,
),
)
for k, v in toolchains.items()
]
[
rust_toolchain(
name = "rust_nix_" + k + "_impl",
binary_ext = "",
dylib_ext = ".so",
exec_triple = v,
cargo = ":cargo",
rust_doc = ":rustdoc",
rust_std = ":rust_nix_" + k + "_stdlib",
rustc = ":rustc",
stdlib_linkflags = ["-ldl", "-lpthread"],
staticlib_ext = ".a",
target_triple = v,
)
for k, v in toolchains.items()
]
[
toolchain(
name = "rust_nix_" + k,
exec_compatible_with = [
"@platforms//cpu:" + k,
"@platforms//os:linux",
],
target_compatible_with = [
"@platforms//cpu:" + k,
"@platforms//os:linux",
],
toolchain = ":rust_nix_" + k + "_impl",
toolchain_type = "@rules_rust//rust:toolchain_type",
)
for k in toolchains.keys()
]
sh_toolchain(
name = "local_sh_impl",
path = "@bash@",
)
toolchain(
name = "local_sh",
toolchain = ":local_sh_impl",
toolchain_type = "@bazel_tools//tools/sh:toolchain_type",
)

View File

@@ -0,0 +1,3 @@
{
"mirrors": []
}

View File

@@ -0,0 +1,18 @@
--- a/bazel/antlr.bzl
+++ b/bazel/antlr.bzl
@@ -99,6 +99,7 @@ def _antlr_library(ctx):
inputs = [output],
outputs = [header],
executable = executable,
+ use_default_shell_env = True,
arguments = [
"-c",
'cp "{generated}" "{out}"'.format(generated = generated + ".h", out = header.path),
@@ -109,6 +110,7 @@ def _antlr_library(ctx):
inputs = [output],
outputs = [source],
executable = executable,
+ use_default_shell_env = True,
arguments = [
"-c",
'cp "{generated}" "{out}"'.format(generated = generated + ".cpp", out = source.path),

8437
pkgs/by-name/en/envoy/deps.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,280 @@
#!/usr/bin/env python3
"""Discover Bazel repository_cache dependencies for an Envoy derivation.
Materializes the derivation's own unpackPhase + patchPhase, runs `bazel build
--nobuild` through a local HTTP proxy configured via
`--experimental_downloader_config`, and writes the exact sha256 -> URL (+
optional canonical ID markers) mapping to deps.json.
"""
import argparse
import hashlib
import http.server
import json
import os
import re
import shlex
import shutil
import socketserver
import subprocess
import sys
import tempfile
import threading
import urllib.error
import urllib.request
from pathlib import Path
BCR_MUTABLE_RE = re.compile(
r"^https://bcr\.bazel\.build/(bazel_registry\.json|modules/[^/]+/metadata\.json)$"
)
class _ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
daemon_threads = True
def start_recording_proxy() -> tuple[_ThreadedHTTPServer, int, dict[str, list[str]]]:
records: dict[str, list[str]] = {}
lock = threading.Lock()
class ProxyHandler(http.server.BaseHTTPRequestHandler):
def _handle(self, method: str) -> None:
raw = self.path.lstrip("/")
if raw.startswith("http://") or raw.startswith("https://"):
candidates = [raw]
else:
candidates = ["https://" + raw, "http://" + raw]
for url in candidates:
req = urllib.request.Request(
url,
method=method,
headers={"User-Agent": "nixpkgs-bazel-discover-deps"},
)
try:
with urllib.request.urlopen(req, timeout=120) as resp:
data = resp.read() if method == "GET" else b""
if method == "GET":
sha = hashlib.sha256(data).hexdigest()
with lock:
urls = records.setdefault(sha, [])
if url not in urls:
urls.append(url)
self.send_response(resp.status)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
if data:
self.wfile.write(data)
return
except urllib.error.HTTPError as exc:
self.send_response(exc.code)
self.send_header("Content-Length", "0")
self.end_headers()
return
except Exception as exc:
if url == candidates[-1]:
print(
f"Proxy error for {url}: {exc}",
file=sys.stderr,
flush=True,
)
self.send_response(502)
self.send_header("Content-Length", "0")
self.end_headers()
def do_GET(self) -> None:
self._handle("GET")
def do_HEAD(self) -> None:
self._handle("HEAD")
def log_message(self, fmt: str, *args: object) -> None:
pass
srv = _ThreadedHTTPServer(("127.0.0.1", 0), ProxyHandler)
port = srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv, port, records
def materialize_patched_source(attr: str) -> Path:
expr = f"""
let pkgs = import ./. {{}}; in
(pkgs.{attr}.overrideAttrs (old: {{
bazelRepoCache = null;
preBuildPhase = "true";
buildPhase = "true";
phases = [ "unpackPhase" "patchPhase" "installPhase" ];
installPhase = ''
mkdir -p $out
cp -a . $out/
'';
dontFixup = true;
}}))
"""
out = subprocess.check_output(
["nix-build", "--no-out-link", "-E", expr], text=True
).strip()
return Path(out)
def main() -> None:
parser = argparse.ArgumentParser(
description="Discover Bazel repository_cache dependencies and write deps.json."
)
parser.add_argument("--attr", required=True, help="Nixpkgs attribute path")
parser.add_argument(
"--pkg-dir", help="Package directory containing deps.json"
)
parser.add_argument(
"--deps-file",
help="Output JSON path (defaults to <pkg-dir>/deps.json)",
)
parser.add_argument(
"--bazel-target",
action="append",
dest="bazel_targets",
required=True,
help="Bazel target to analyze (repeatable)",
)
parser.add_argument(
"--bazel-flag",
action="append",
dest="bazel_flags",
default=[],
help="Extra Bazel build flag (repeatable)",
)
parser.add_argument(
"--variant-flag",
action="append",
dest="variant_flags",
default=[],
help="Per-variant Bazel flag to run discovery across (repeatable)",
)
args = parser.parse_args()
patched_store = materialize_patched_source(args.attr)
srv, port, records = start_recording_proxy()
try:
with tempfile.TemporaryDirectory(prefix="bazel-discover-deps-") as tmp:
tmp_path = Path(tmp)
src_dir = tmp_path / "src"
repo_cache = tmp_path / "repo_cache"
user_root = tmp_path / "user_root"
home_dir = tmp_path / "home"
dl_cfg = tmp_path / "downloader.cfg"
shutil.copytree(patched_store, src_dir, symlinks=True)
for root, dirs, files in os.walk(src_dir):
os.chmod(root, 0o755)
for name in files:
p = os.path.join(root, name)
if not os.path.islink(p):
os.chmod(p, os.stat(p).st_mode | 0o200)
repo_cache.mkdir()
home_dir.mkdir()
dl_cfg.write_text(f"rewrite (.*) http://127.0.0.1:{port}/$1\n")
env = os.environ.copy()
env["HOME"] = str(home_dir)
variant_runs = [shlex.split(f) for f in args.variant_flags] if args.variant_flags else [[]]
for extra in variant_runs:
cmd = [
"bazel",
"--batch",
f"--output_user_root={user_root}",
"build",
"--nobuild",
f"--repository_cache={repo_cache}",
f"--experimental_downloader_config={dl_cfg}",
*args.bazel_flags,
*extra,
*args.bazel_targets,
]
print("Running Bazel discovery:", " ".join(cmd), file=sys.stderr, flush=True)
subprocess.run(cmd, cwd=src_dir, env=env, check=True)
cas_dir = repo_cache / "content_addressable" / "sha256"
if not cas_dir.is_dir():
sys.exit(f"ERROR: expected repo_cache directory at {cas_dir}")
entries: list[dict[str, object]] = []
missing: list[str] = []
for hash_dir in sorted(cas_dir.iterdir()):
if not hash_dir.is_dir():
continue
sha256 = hash_dir.name
urls = records.get(sha256, [])
if not urls:
missing.append(sha256)
continue
# Skip mutable BCR files (metadata.json is only fetched online for
# yanked-version checks; bazel_registry.json is synthesized locally).
if all(BCR_MUTABLE_RE.match(u) for u in urls):
continue
entry: dict[str, object] = {
"sha256": sha256,
"urls": sorted(urls),
}
canonical_ids = sorted(
p.name for p in hash_dir.iterdir() if p.name.startswith("id-")
)
if canonical_ids:
entry["canonicalIds"] = canonical_ids
entries.append(entry)
if missing:
sys.exit(
f"ERROR: {len(missing)} repo_cache hashes had no recorded URL: "
+ ", ".join(missing[:10])
)
if args.deps_file:
deps_path = Path(args.deps_file)
elif args.pkg_dir:
deps_path = Path(args.pkg_dir) / "deps.json"
else:
sys.exit("ERROR: either --deps-file or --pkg-dir must be provided")
# Build the exact filtered repo_cache layout and compute its NAR hash.
out_dir = tmp_path / "fod_out"
out_cas = out_dir / "repo_cache" / "content_addressable" / "sha256"
for entry in entries:
sha256 = str(entry["sha256"])
dst_dir = out_cas / sha256
dst_dir.mkdir(parents=True, exist_ok=True)
src_file = cas_dir / sha256 / "file"
dst_file = dst_dir / "file"
shutil.copyfile(src_file, dst_file)
os.chmod(dst_file, 0o644)
for cid in entry.get("canonicalIds", []):
cid_path = dst_dir / str(cid)
cid_path.write_bytes(b"")
os.chmod(cid_path, 0o644)
nar_hash = subprocess.check_output(
["nix-hash", "--type", "sha256", "--sri", str(out_dir)],
text=True,
).strip()
deps_path.write_text(
json.dumps({"hash": nar_hash, "entries": entries}, indent=2) + "\n"
)
print(
f"Wrote {len(entries)} entries (hash {nar_hash}) to {deps_path}",
file=sys.stderr,
flush=True,
)
finally:
srv.shutdown()
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Fetch Bazel repository_cache entries from deps.json into a single FOD."""
from __future__ import annotations
import argparse
import concurrent.futures
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
CHUNK_SIZE = 1024 * 1024
MAX_RETRIES = 4
def fetch_entry(entry: dict[str, object], cas_dir: Path) -> str:
sha256 = str(entry["sha256"])
urls = [str(u) for u in entry["urls"]]
canonical_ids = [str(cid) for cid in entry.get("canonicalIds", [])]
entry_dir = cas_dir / sha256
entry_dir.mkdir(parents=True, exist_ok=True)
dest = entry_dir / "file"
last_err: Exception | None = None
for url in urls:
for attempt in range(1, MAX_RETRIES + 1):
try:
req = urllib.request.Request(
url, headers={"User-Agent": "nixpkgs-bazel-repo-cache/1.0"}
)
h = hashlib.sha256()
tmp = entry_dir / ".file.tmp"
with urllib.request.urlopen(req, timeout=60) as resp, open(
tmp, "wb"
) as out:
while True:
chunk = resp.read(CHUNK_SIZE)
if not chunk:
break
h.update(chunk)
out.write(chunk)
got = h.hexdigest()
if got != sha256:
tmp.unlink(missing_ok=True)
raise ValueError(
f"sha256 mismatch for {url}: expected {sha256}, got {got}"
)
os.chmod(tmp, 0o644)
tmp.replace(dest)
for cid in canonical_ids:
cid_path = entry_dir / cid
cid_path.write_bytes(b"")
os.chmod(cid_path, 0o644)
return sha256
except Exception as err:
last_err = err
if attempt < MAX_RETRIES:
time.sleep(min(2 ** (attempt - 1), 8))
print(
f"WARN: failed all retries for {url}: {last_err}",
file=sys.stderr,
flush=True,
)
raise RuntimeError(f"Failed to fetch {sha256} from {urls}: {last_err}")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--deps-file", required=True, help="Path to deps.json")
parser.add_argument("--out", required=True, help="Output store directory")
parser.add_argument(
"--jobs", type=int, default=8, help="Parallel download workers"
)
args = parser.parse_args()
entries = json.loads(Path(args.deps_file).read_text())["entries"]
cas_dir = Path(args.out) / "repo_cache" / "content_addressable" / "sha256"
cas_dir.mkdir(parents=True, exist_ok=True)
print(
f"Fetching {len(entries)} Bazel repo_cache entries with {args.jobs} workers...",
file=sys.stderr,
flush=True,
)
done = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as pool:
futures = [pool.submit(fetch_entry, e, cas_dir) for e in entries]
for fut in concurrent.futures.as_completed(futures):
fut.result()
done += 1
if done % 200 == 0 or done == len(entries):
print(
f"Fetched {done}/{len(entries)} entries",
file=sys.stderr,
flush=True,
)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,48 @@
single_version_override(
module_name = "cel-cpp",
patch_strip = 1,
patches = ["//bazel/nix:cel_cpp_antlr.patch"],
)
single_version_override(
module_name = "protoc-gen-validate",
patch_strip = 1,
patches = ["//bazel/nix:pgv.patch"],
)
single_version_override(
module_name = "rules_buf",
patch_strip = 1,
patches = ["//bazel/nix:rules_buf_no_download.patch"],
)
single_version_override(
module_name = "rules_cc",
patch_strip = 1,
patches = ["//bazel/nix:rules_cc_shebang.patch"],
)
single_version_override(
module_name = "rules_java",
patch_strip = 1,
patches = ["//bazel/nix:rules_java_shebang.patch"],
)
single_version_override(
module_name = "rules_rust",
patch_strip = 1,
patches = ["//bazel/nix:rules_rust_skip_repin.patch"],
)
single_version_override(
module_name = "v8",
patch_strip = 1,
patches = ["//bazel/nix:v8_no_pip.patch"],
)
single_version_override(
module_name = "wasmtime",
patch_strip = 1,
patches = ["//bazel/nix:wasmtime_conf.patch"],
)

View File

@@ -1,376 +1,483 @@
{
lib,
bazel_7,
bazel-gazelle,
buildBazelPackage,
fetchFromGitHub,
applyPatches,
stdenv,
cacert,
cargo,
rustc,
rustPlatform,
clippy,
cmake,
gn,
openjdk11_headless,
ninja,
patchelf,
python312,
linuxHeaders,
nixosTests,
runCommandLocal,
gnutar,
gnugrep,
envoy,
fetchFromGitHub,
fetchurl,
git,
gnumake,
gnugrep,
gnused,
jdk21_headless,
jq,
libiconv,
linkFarm,
linuxHeaders,
llvmPackages,
lndir,
ninja,
nix-update-script,
nixosTests,
perl,
pkg-config,
protoc-gen-validate,
python3,
runCommand,
rustPlatform,
rustc,
rustfmt,
stdenvAdapters,
which,
writeShellScript,
yq-go,
bazel_8,
# v8 (upstream default), wavm, wamr, wasmtime, disabled
# v8, wamr, wasmtime, disabled
wasmRuntime ? "wasmtime",
# Allows overriding the deps hash used for building - you will likely need to
# set this if you have changed the 'wasmRuntime' setting.
depsHash ? null,
}:
let
srcVer = {
# We need the commit hash, since Bazel stamps the build with it.
# However, the version string is more useful for end-users.
# These are contained in a attrset of their own to make it obvious that
# people should update both.
version = "1.36.10";
rev = "053a8989382dd91542ecf0cef8f379b9cb761cdd";
hash = "sha256-6bGXZfU2JutiriefwBudt46BrJRnwEqQCjYVRjUgyaY=";
};
# When GO_VERSION changes upstream, update the four sha256 hex strings in the
# _GO_SDKS dict in 0005-nixpkgs-pin-go-sdk-downloads.patch using output from
# this command (set the version literal in `select` to match GO_VERSION):
# curl -s 'https://go.dev/dl/?mode=json&include=all' | jq -r '.[] | select(.version == "go1.24.6") | .files[] | select(.kind == "archive" and (.os == "linux" or .os == "darwin") and (.arch == "amd64" or .arch == "arm64")) | "\(.os)_\(.arch): \(.sha256)"'
# these need to be updated for any changes to fetchAttrs
depsHash' =
if depsHash != null then
depsHash
version = "1.40.2";
rustTriple = stdenv.buildPlatform.rust.rustcTargetSpec;
bazelCcCompiler =
if stdenv.buildPlatform.isDarwin then
if stdenv.buildPlatform.isAarch64 then "cc-compiler-darwin_arm64" else "cc-compiler-darwin_x86_64"
else if stdenv.buildPlatform.isAarch64 then
"cc-compiler-aarch64"
else
{
x86_64-linux = "sha256-EUPWZ8N8wXtnOle8WMLfdxQEdCnTv1JJSbgG39UOoMc=";
aarch64-linux = "sha256-WltewtSjwvmYfZQwYAslCCoBdLY1MyO9jnMC/bCzVeg=";
}
.${stdenv.system} or (throw "unsupported system ${stdenv.system}");
"cc-compiler-k8";
# Include jinja2 for V8's source build (wasmRuntime = "v8"), avoiding @v8_python_deps pip fetches.
python3Env = python3.withPackages (ps: [ ps.jinja2 ]);
python3 = python312;
jdk = openjdk11_headless;
cargoBazel = rustPlatform.buildRustPackage (finalAttrs: {
pname = "cargo-bazel";
version = "0.74.0";
in
buildBazelPackage rec {
pname = "envoy";
inherit (srcVer) version;
bazel = bazel_7;
src = applyPatches {
src = fetchFromGitHub {
owner = "envoyproxy";
repo = "envoy";
inherit (srcVer) hash rev;
src = fetchurl {
url = "https://github.com/bazelbuild/rules_rust/releases/download/${finalAttrs.version}/rules_rust-${finalAttrs.version}.tar.gz";
hash = "sha256-2LzB4RHpgnDcAxcuIu96+cL5TzJpgBYYorg9IIkPjfU=";
};
# By convention, these patches are generated like:
# git format-patch --zero-commit --signoff --no-numbered --minimal --full-index --no-signature
patches = [
# use system Python, not bazel-fetched binary Python
./0001-nixpkgs-use-system-Python.patch
# use system C/C++ tools
./0003-nixpkgs-use-system-C-C-toolchains.patch
# bump rules_rust to support newer Rust
./0004-nixpkgs-bump-rules_rust-to-0.60.0.patch
# pin Go SDK downloads so the deps hash doesn't drift on every Go release
./0005-nixpkgs-pin-go-sdk-downloads.patch
];
postPatch = ''
chmod -R +w .
rm ./.bazelversion
echo ${srcVer.rev} > ./SOURCE_VERSION
unpackPhase = ''
runHook preUnpack
mkdir -p source
tar -xzf "$src" -C source
sourceRoot=source/crate_universe
runHook postUnpack
'';
};
postPatch = ''
sed -i 's,#!/usr/bin/env python3,#!${python3}/bin/python,' bazel/foreign_cc/luajit.patch
sed -i '/javabase=/d' .bazelrc
sed -i '/"-Werror"/d' bazel/envoy_internal.bzl
cargoHash = "sha256-H4u1Pm6zLYoa7ShvUA+Rk6QmfWEgRhfyflzECFQ4vTY=";
cargoBuildFlags = [
"--bin"
"cargo-bazel"
];
doCheck = false;
});
mkdir -p bazel/nix/
substitute ${./bazel_nix.BUILD.bazel} bazel/nix/BUILD.bazel \
--subst-var-by bash "$(type -p bash)"
ln -sf "${cargo}/bin/cargo" bazel/nix/cargo
ln -sf "${rustc}/bin/rustc" bazel/nix/rustc
ln -sf "${rustc}/bin/rustdoc" bazel/nix/rustdoc
ln -sf "${rustc.unwrapped}" bazel/nix/rustcroot
substituteInPlace bazel/dependency_imports.bzl \
--replace-fail 'crate_universe_dependencies()' 'crate_universe_dependencies(rust_toolchain_cargo_template="@@//bazel/nix:cargo", rust_toolchain_rustc_template="@@//bazel/nix:rustc")' \
--replace-fail 'crates_repository(' 'crates_repository(rust_toolchain_cargo_template="@@//bazel/nix:cargo", rust_toolchain_rustc_template="@@//bazel/nix:rustc",'
stdenv' =
if stdenv.hostPlatform.isLinux then
stdenvAdapters.useMoldLinker llvmPackages.libcxxStdenv
else
llvmPackages.libcxxStdenv;
# patch rules_rust for envoy specifics
cp ${./rules_rust.patch} bazel/rules_rust.patch
substituteInPlace bazel/repositories.bzl \
--replace-fail ', "@envoy//bazel:rules_rust_ppc64le.patch"' "" \
--replace-fail '"@envoy//bazel:emsdk.patch"' ""
mkRepoCache =
{
name ? "bazel-repo-cache",
depsFile,
}:
runCommand name
{
outputHashMode = "recursive";
outputHashAlgo = null;
outputHash = (lib.importJSON depsFile).hash;
nativeBuildInputs = [
cacert
python3
];
env.SSL_CERT_FILE = "${cacert}/etc/ssl/certs/ca-bundle.crt";
}
''
${python3.interpreter} ${./fetch-repo-cache.py} \
--deps-file ${depsFile} \
--out "$out"
'';
substitute ${./rules_rust_extra.patch} bazel/nix/rules_rust_extra.patch \
--subst-var-by bash "$(type -p bash)"
cat bazel/nix/rules_rust_extra.patch bazel/rules_rust.patch > bazel/nix/rules_rust.patch
mv bazel/nix/rules_rust.patch bazel/rules_rust.patch
'';
mkBazelRegistries =
repoCache:
let
entries = (lib.importJSON ./deps.json).entries;
mkRegLinks =
entry:
let
fetched = "${repoCache}/repo_cache/content_addressable/sha256/${entry.sha256}/file";
urlToLink =
url:
let
bcrPrefix = "https://bcr.bazel.build/";
envoyMatch = builtins.match "https://raw\\.githubusercontent\\.com/envoyproxy/bazel-registry/[^/]+/(.*)" url;
in
if lib.hasPrefix bcrPrefix url then
[
{
name = "bcr/${lib.removePrefix bcrPrefix url}";
path = fetched;
}
]
else if envoyMatch != null then
[
{
name = "envoy/${builtins.head envoyMatch}";
path = fetched;
}
]
else
[ ];
in
lib.concatMap urlToLink entry.urls;
in
linkFarm "envoy-bazel-registries" (
[
{
name = "bcr/bazel_registry.json";
path = ./bcr-bazel_registry.json;
}
]
++ lib.concatMap mkRegLinks entries
);
extraToolchains = [
"//bazel/nix:local_sh_toolchain"
"//bazel/nix:local_py_toolchain"
"//bazel/nix:local_py_exec_tools_toolchain"
"//bazel/nix:local_jdk_runtime_toolchain"
"//bazel/nix:local_jdk_bootstrap_runtime_toolchain"
"@local_config_cc_toolchains//:all"
"@rules_foreign_cc//toolchains:preinstalled_cmake_toolchain"
"@rules_foreign_cc//toolchains:preinstalled_ninja_toolchain"
"//bazel/nix/rust:rust_nix_toolchain"
];
commonCommandArgs = [
"--repository_disable_download"
"--repo_env=BAZEL_HTTP_RULES_URLS_AS_DEFAULT_CANONICAL_ID=0"
"--curses=no"
"-c"
"opt"
"--spawn_strategy=standalone"
"--noincompatible_strict_action_env"
"--action_env=CMAKE_POLICY_VERSION_MINIMUM=3.5"
"--cxxopt=-std=c++20"
"--host_cxxopt=-std=c++20"
"--per_file_copt=.*@-Wno-error"
"--@proxy-wasm-cpp-host//bazel:engine=${wasmRuntime}"
"--@protobuf//bazel/toolchains:prefer_prebuilt_protoc=false"
"--@rules_python//python/config_settings:bootstrap_impl=system_python"
"--extra_toolchains=${lib.concatStringsSep "," extraToolchains}"
"--java_runtime_version=local_jdk"
"--tool_java_runtime_version=local_jdk"
"--verbose_failures"
]
++ lib.optionals stdenv.hostPlatform.isLinux [
"--action_env=BAZEL_LINKLIBS=-lc++:-lc++abi"
"--action_env=BAZEL_LINKOPTS=-lm:-pthread"
"--linkopt=-Wl,-z,noexecstack"
"--linkopt=-Wl,--unresolved-symbols=ignore-in-object-files"
]
++ lib.optionals stdenv.hostPlatform.isDarwin [
"--repo_env=CC=${stdenv'.cc}/bin/clang"
"--action_env=PATH"
"--host_action_env=PATH"
"--action_env=BAZEL_LINKLIBS=-lc++"
"--action_env=BAZEL_LINKOPTS=-lm"
"--action_env=SDKROOT"
"--host_action_env=SDKROOT"
"--action_env=DEVELOPER_DIR"
"--host_action_env=DEVELOPER_DIR"
"--action_env=NIX_CFLAGS_COMPILE"
"--host_action_env=NIX_CFLAGS_COMPILE"
"--action_env=NIX_CFLAGS_COMPILE_${stdenv'.cc.suffixSalt}"
"--host_action_env=NIX_CFLAGS_COMPILE_${stdenv'.cc.suffixSalt}"
"--action_env=NIX_CXXSTDLIB_COMPILE_${stdenv'.cc.suffixSalt}"
"--host_action_env=NIX_CXXSTDLIB_COMPILE_${stdenv'.cc.suffixSalt}"
"--action_env=NIX_LDFLAGS"
"--host_action_env=NIX_LDFLAGS"
"--action_env=NIX_LDFLAGS_${stdenv'.cc.suffixSalt}"
"--host_action_env=NIX_LDFLAGS_${stdenv'.cc.suffixSalt}"
"--macos_minimum_os=14.0"
"--host_macos_minimum_os=14.0"
"--host_copt=-mmacosx-version-min=14.0"
"--features=-layering_check"
"--host_features=-layering_check"
]
++ lib.optionals stdenv.hostPlatform.isAarch64 [
"--define=tcmalloc=disabled"
];
nativeBuildInputs = [
cmake
python3
gn
jdk
ninja
patchelf
cacert
git
gnumake
gnugrep
gnused
jdk21_headless
jq
ninja
perl
pkg-config
python3Env
which
yq-go
cargo
clippy
rustc
rustfmt
];
buildInputs = [ linuxHeaders ];
discoverDeps = writeShellScript "discover-deps-envoy" ''
set -euo pipefail
export PATH="${
lib.makeBinPath (
[
bazel_8
stdenv'.cc
]
++ nativeBuildInputs
)
}:$PATH"
export SSL_CERT_FILE="${cacert}/etc/ssl/certs/ca-bundle.crt"
export JAVA_HOME="${jdk21_headless.home}"
export BZLMOD_ALLOW_YANKED_VERSIONS=all
export CC="${stdenv'.cc}/bin/cc"
export CXX="${stdenv'.cc}/bin/c++"
exec ${python3.interpreter} ${./discover-deps.py} \
--bazel-target //source/exe:envoy-static \
${
lib.escapeShellArgs (
map (f: "--bazel-flag=${f}") (
lib.filter (f: f != "--repository_disable_download") commonCommandArgs
)
++ map (r: "--variant-flag=--@proxy-wasm-cpp-host//bazel:engine=${r}") [
"wasmtime"
"wamr"
"v8"
"disabled"
]
++ [
"--variant-flag=--platforms=//bazel/nix:darwin_arm64 --extra_toolchains=//bazel/nix:darwin_arm64_cc_toolchain"
]
)
} \
"$@"
'';
in
stdenv'.mkDerivation (finalAttrs: {
pname = "envoy";
inherit version;
fetchAttrs = {
sha256 = depsHash';
env.CARGO_BAZEL_REPIN = true;
dontUseCmakeConfigure = true;
dontUseGnConfigure = true;
postPatch = ''
${postPatch}
strictDeps = true;
__structuredAttrs = true;
echo "common --repository_cache=\"$bazelOut/external/repository_cache\"" >> .bazelrc
substituteInPlace bazel/dependency_imports.bzl \
--replace-fail 'crate_universe_dependencies(' 'crate_universe_dependencies(bootstrap=True, ' \
--replace-fail 'crates_repository(' 'crates_repository(generator="@@cargo_bazel_bootstrap//:cargo-bazel", '
'';
preInstall = ''
# Envoy uses --noenable_bzlmod so BCR modules are not needed.
# Populate the repository cache with entries the build needs from the empty
# workspace. Use `bazel sync` (which fetches WORKSPACE repos) rather than
# `bazel fetch` (which requires bzlmod for its --all mode).
mkdir $NIX_BUILD_TOP/empty
pushd $NIX_BUILD_TOP/empty
touch MODULE.bazel WORKSPACE
bazel sync --noenable_bzlmod --repository_cache="$bazelOut/external/repository_cache"
popd
# Strip out the path to the build location (by deleting the comment line).
find $bazelOut/external -name requirements.bzl | while read requirements; do
sed -i '/# Generated from /d' "$requirements"
done
# Remove references to paths in the Nix store.
sed -i \
-e 's,${python3},__NIXPYTHON__,' \
-e 's,${stdenv.shellPackage},__NIXSHELL__,' \
-e 's,${builtins.storeDir}/[^/]\+/bin/bash,__NIXBASH__,' \
$bazelOut/external/com_github_luajit_luajit/build.py \
$bazelOut/external/local_config_sh/BUILD \
$bazelOut/external/*_pip3/BUILD.bazel \
$bazelOut/external/rules_rust/util/process_wrapper/private/process_wrapper.sh \
$bazelOut/external/rules_rust/crate_universe/src/metadata/cargo_tree_rustc_wrapper.sh
rm -r $bazelOut/external/local_jdk
rm -r $bazelOut/external/bazel_gazelle_go_repository_tools/bin
# Drop prebuilt JDK toolchains and non-Linux java tool bundles; we force @local_jdk anyway.
shopt -s nullglob
rm -rf $bazelOut/external/remotejdk*
for dir in $bazelOut/external/remote_java_tools*; do
base=$(basename "$dir")
if [[ "$base" != remote_java_tools_linux ]]; then
rm -rf "$dir"
fi
done
rm -rf $bazelOut/external/android_tools $bazelOut/external/android_gmaven_r8
find $bazelOut/external/repository_cache -maxdepth 1 -type f \
\( -iname '*remotejdk*' -o -iname '*remote_java_tools*' -o -iname '*android*' \) -delete
# Prune repository_cache entries for unused remote JDK/tool bundles.
keep_patterns=()
case ${stdenv.hostPlatform.system} in
x86_64-linux)
keep_patterns+=("remotejdk8_linux" "remotejdk11_linux" "remotejdk17_linux" "remotejdk21_linux" "remote_java_tools_linux")
;;
aarch64-linux)
keep_patterns+=("remotejdk8_linux_aarch64" "remotejdk11_linux_aarch64" "remotejdk17_linux_aarch64" "remotejdk21_linux_aarch64" "remote_java_tools_linux")
;;
esac
find $bazelOut/external/repository_cache -type f \( -iname '*remotejdk*' -o -iname '*remote_java_tools*' -o -iname '*android*' \) | while read f; do
keep=false
for pat in $keep_patterns; do
if [[ $(basename "$f") == *"$pat"* ]]; then
keep=true
break
fi
done
if ! $keep; then
rm -f "$f"
fi
done
shopt -u nullglob
# CMake 4.1 drops compatibility with <3.5; bump libevent's floor to avoid configure failure.
sed -i 's/cmake_minimum_required(VERSION 3\\.1.2 FATAL_ERROR)/cmake_minimum_required(VERSION 3.5 FATAL_ERROR)/' \
$bazelOut/external/com_github_libevent_libevent/CMakeLists.txt
# Remove compiled python
find $bazelOut -name '*.pyc' -delete
# Remove Unix timestamps from go cache.
rm -rf $bazelOut/external/bazel_gazelle_go_repository_cache/{gocache,pkg/mod/cache,pkg/sumdb}
# fix tcmalloc failure https://github.com/envoyproxy/envoy/issues/30838
sed -i '/TCMALLOC_GCC_FLAGS = \[/a"-Wno-changes-meaning",' $bazelOut/external/com_github_google_tcmalloc/tcmalloc/copts.bzl
# Install repinned rules_rust lockfile
cp source/extensions/dynamic_modules/sdk/rust/Cargo.Bazel.lock $bazelOut/external/Cargo.Bazel.lock
# Don't save cargo_bazel_bootstrap or the crate index cache
rm -rf $bazelOut/external/cargo_bazel_bootstrap $bazelOut/external/dynamic_modules_rust_sdk_crate_index/.cargo_home $bazelOut/external/dynamic_modules_rust_sdk_crate_index/splicing-output
'';
};
buildAttrs = {
dontUseCmakeConfigure = true;
dontUseGnConfigure = true;
dontUseNinjaInstall = true;
bazel = null;
preConfigure = ''
export CMAKE_POLICY_VERSION_MINIMUM=3.5
echo "common --repository_cache=\"$bazelOut/external/repository_cache\"" >> .bazelrc
echo "common --repository_disable_download" >> .bazelrc
# Make executables work, for the most part.
find $bazelOut/external -type f -executable | while read execbin; do
file "$execbin" | grep -q ': ELF .*, dynamically linked,' || continue
patchelf \
--set-interpreter $(cat ${stdenv.cc}/nix-support/dynamic-linker) \
"$execbin" || echo "$execbin"
done
ln -s ${bazel-gazelle}/bin $bazelOut/external/bazel_gazelle_go_repository_tools/bin
sed -i 's,#!/usr/bin/env bash,#!${stdenv.shell},' $bazelOut/external/rules_foreign_cc/foreign_cc/private/framework/toolchains/linux_commands.bzl
# Add paths to Nix store back.
sed -i \
-e 's,__NIXPYTHON__,${python3},' \
-e 's,__NIXSHELL__,${stdenv.shellPackage},' \
-e 's,__NIXBASH__,${stdenv.shell},' \
$bazelOut/external/com_github_luajit_luajit/build.py \
$bazelOut/external/local_config_sh/BUILD \
$bazelOut/external/*_pip3/BUILD.bazel \
$bazelOut/external/rules_rust/util/process_wrapper/private/process_wrapper.sh \
$bazelOut/external/rules_rust/crate_universe/src/metadata/cargo_tree_rustc_wrapper.sh
# Install repinned rules_rust lockfile
cp $bazelOut/external/Cargo.Bazel.lock source/extensions/dynamic_modules/sdk/rust/Cargo.Bazel.lock
'';
installPhase = ''
install -Dm0755 bazel-bin/source/exe/envoy-static $out/bin/envoy
'';
src = fetchFromGitHub {
owner = "envoyproxy";
repo = "envoy";
tag = "v${version}";
hash = "sha256-Ni+vX3rqo8s7000IPjzg2B7smtFm3SQF501tdRZAv4M=";
};
removeRulesCC = false;
removeLocalConfigCc = true;
removeLocal = false;
bazelTargets = [ "//source/exe:envoy-static" ];
bazelFlags = [
"--repo_env=BAZEL_HTTP_RULES_URLS_AS_DEFAULT_CANONICAL_ID=0"
];
bazelBuildFlags = [
"-c opt"
"--spawn_strategy=standalone"
"--noexperimental_strict_action_env"
"--cxxopt=-Wno-error"
"--linkopt=-Wl,-z,noexecstack"
"--config=gcc"
"--verbose_failures"
"--incompatible_enable_cc_toolchain_resolution=true"
bazelRepoCache = mkRepoCache {
name = "envoy-${version}-repo-cache";
depsFile = ./deps.json;
};
# Force use of system Java.
"--extra_toolchains=@local_jdk//:all"
"--java_runtime_version=local_jdk"
"--tool_java_runtime_version=local_jdk"
inherit nativeBuildInputs;
buildInputs =
lib.optional stdenv.hostPlatform.isLinux linuxHeaders
++ lib.optional stdenv.hostPlatform.isDarwin libiconv;
# Force use of system Rust.
"--extra_toolchains=//bazel/nix:rust_nix_aarch64,//bazel/nix:rust_nix_x86_64"
# undefined reference to 'grpc_core::*Metadata*::*Memento*
#
# During linking of the final binary, we see undefined references to grpc_core related symbols.
# The missing symbols would be instantiations of a template class from https://github.com/grpc/grpc/blob/v1.59.4/src/core/lib/transport/metadata_batch.h
# "ParseMemento" and "MementoToValue" are only implemented for some types
# and appear unused and unimplemented for the undefined cases reported by the linker.
"--linkopt=-Wl,--unresolved-symbols=ignore-in-object-files"
"--define=wasm=${wasmRuntime}"
]
++ (lib.optionals stdenv.hostPlatform.isAarch64 [
# external/com_github_google_tcmalloc/tcmalloc/internal/percpu_tcmalloc.h:611:9: error: expected ':' or '::' before '[' token
# 611 | : [end_ptr] "=&r"(end_ptr), [cpu_id] "=&r"(cpu_id),
# | ^
"--define=tcmalloc=disabled"
]);
bazelFetchFlags = [
"--define=wasm=${wasmRuntime}"
# Force use of system Rust.
"--extra_toolchains=//bazel/nix:rust_nix_aarch64,//bazel/nix:rust_nix_x86_64"
# https://github.com/bazelbuild/rules_go/issues/3844
"--repo_env=GOPROXY=https://proxy.golang.org,direct"
"--repo_env=GOSUMDB=sum.golang.org"
];
dontUseCmakeConfigure = true;
dontUseNinjaInstall = true;
requiredSystemFeatures = [ "big-parallel" ];
passthru.tests = {
envoy = nixosTests.envoy;
# tested as a core component of Pomerium
pomerium = nixosTests.pomerium;
env = {
JAVA_HOME = jdk21_headless.home;
BZLMOD_ALLOW_YANKED_VERSIONS = "all";
};
deps-store-free =
runCommandLocal "${envoy.name}-deps-store-free-test"
{
nativeBuildInputs = [
gnutar
gnugrep
];
}
''
touch $out
tar -xf ${envoy.deps}
grep -r /nix/store external && status=$? || status=$?
case $status in
1)
echo "No match found."
;;
0)
echo
echo "Error: Found references to /nix/store in envoy.deps derivation"
echo "This is a reproducibility issue, as the hash of the fixed-output derivation"
echo "will change in case the store path of the input changes."
echo
echo "Replace the store path in fetcherAttrs.preInstall."
exit 1
;;
*)
echo "An unexpected error occurred."
exit $status
;;
esac
'';
postPatch = ''
rm -f ./.bazelversion
echo "v${version}" > ./SOURCE_VERSION
# Verify cargoBazel matches the rules_rust version pinned in MODULE.bazel.
rulesRustVersion=$(sed -n 's/^bazel_dep(name = "rules_rust", version = "\([^"]*\)")/\1/p' MODULE.bazel)
if [[ "$rulesRustVersion" != "${cargoBazel.version}" && "$rulesRustVersion" != "${cargoBazel.version}."* ]]; then
echo "ERROR: MODULE.bazel uses rules_rust '$rulesRustVersion', but cargoBazel is '${cargoBazel.version}'; update cargoBazel in package.nix" >&2
exit 1
fi
# Expose @local_jdk from rules_java so //bazel/nix can register Nix's JDK,
# and drop unused prebuilt toolchain registrations (Go queries mutable go.dev/dl/?mode=json;
# LLVM and Rust prebuilt tarballs are replaced by Nix's toolchains via --extra_toolchains).
substituteInPlace MODULE.bazel \
--replace-fail '"remotejdk25_linux",' '"local_jdk", "remotejdk25_linux",' \
--replace-fail '"@go_toolchains//:all",' "" \
--replace-fail 'register_toolchains("@llvm_toolchain//:all")' "" \
--replace-fail 'register_toolchains("@rust_toolchains//:all")' ""
# Use NONPREBUILT_TOOLCHAIN_CONFIGURATION (builds ijar/singlejar from source) and Nix's local_jdk.
# Also use --build-id=sha1 instead of --build-id=0x<SOURCE_VERSION> since SOURCE_VERSION is a tag (v${version}), not hex,
# and build wee8 (V8) from source rather than fetching envoy_toolshed prebuilt binaries.
substituteInPlace bazel/BUILD \
--replace-fail 'load("@rules_java//toolchains:default_java_toolchain.bzl", "default_java_toolchain")' 'load("@rules_java//toolchains:default_java_toolchain.bzl", "NONPREBUILT_TOOLCHAIN_CONFIGURATION", "default_java_toolchain")' \
--replace-fail 'java_runtime = "@rules_java//toolchains:remotejdk_25",' 'configuration = NONPREBUILT_TOOLCHAIN_CONFIGURATION, java_runtime = "@local_jdk//:jdk",' \
--replace-fail 'javabuilder_jvm_opts = ["--sun-misc-unsafe-memory-access=allow"],' "" \
--replace-fail 'echo --build-id=0x$$(' 'echo --build-id=sha1 > $@ && exit 0; echo $$(' \
--replace-fail '"//conditions:default": "@envoy_toolshed//v8:wee8",' '"//conditions:default": "@proxy-wasm-cpp-host//bazel:wee8_no_pointer_compression",'
cat ${./module-overrides.bazel} >> MODULE.bazel
mkdir -p bazel/nix
substitute ${./bazel-nix.BUILD.bazel} bazel/nix/BUILD.bazel \
--subst-var-by bash "${stdenv'.shell}" \
--subst-var-by cc_compiler "${bazelCcCompiler}" \
--subst-var-by python3 "${python3Env.interpreter}"
substitute ${./pgv.patch} bazel/nix/pgv.patch \
--subst-var-by protoc_gen_validate "${lib.getExe' protoc-gen-validate "protoc-gen-validate"}"
substitute ${./rules_cc_shebang.patch} bazel/nix/rules_cc_shebang.patch \
--subst-var-by bash "${stdenv'.shell}"
substitute ${./rules_java_shebang.patch} bazel/nix/rules_java_shebang.patch \
--subst-var-by bash "${stdenv'.shell}"
cp ${./cel_cpp_antlr.patch} bazel/nix/cel_cpp_antlr.patch
cp ${./rules_buf_no_download.patch} bazel/nix/rules_buf_no_download.patch
substitute ${./rules_rust_skip_repin.patch} bazel/nix/rules_rust_skip_repin.patch \
--subst-var-by cargo "${cargo}/bin/cargo" \
--subst-var-by cargo_bazel "${cargoBazel}/bin/cargo-bazel" \
--subst-var-by rustc "${rustc}/bin/rustc"
cp ${./v8_no_pip.patch} bazel/nix/v8_no_pip.patch
cp ${./wasmtime_conf.patch} bazel/nix/wasmtime_conf.patch
substituteInPlace source/extensions/dynamic_modules/dynamic_modules.bzl \
--replace-fail '"$(location @llvm_toolchain_llvm//:objcopy) "' '"objcopy "' \
--replace-fail 'tools = ["@llvm_toolchain_llvm//:objcopy"],' 'tools = [],'
# Use Nix's libclang and glibc headers for bindgen instead of downloaded sysroot/LLVM tarballs.
substituteInPlace source/extensions/dynamic_modules/sdk/rust/BUILD \
--replace-fail 'load("//bazel:toolchains.bzl", "LLVM_MAJOR")' "" \
--replace-fail '"LIBCLANG_PATH": "$(location @llvm_toolchain_llvm//:lib/libclang.so)",' '"LIBCLANG_PATH": "${llvmPackages.libclang.lib}/lib",' \
--replace-fail '"ENVOY_LLVM_ANCHOR": "$(location @llvm_toolchain_llvm//:lib/libclang.so)",' "\"BINDGEN_EXTRA_CLANG_ARGS\": \"-isystem ${llvmPackages.libclang.lib}/lib/clang/${lib.versions.major llvmPackages.libclang.version}/include${lib.optionalString stdenv.hostPlatform.isLinux " -isystem ${stdenv.cc.libc_dev}/include"}${lib.optionalString stdenv.hostPlatform.isDarwin " -isysroot $SDKROOT"}\"," \
--replace-fail '"ENVOY_LLVM_MAJOR": LLVM_MAJOR,' "" \
--replace-fail '"ENVOY_SYSROOT_AMD64_ANCHOR": "$(location @sysroot_linux_amd64//:usr/include/stdio.h)",' "" \
--replace-fail '"ENVOY_SYSROOT_ARM64_ANCHOR": "$(location @sysroot_linux_arm64//:usr/include/stdio.h)",' "" \
--replace-fail '"@llvm_toolchain_llvm//:include",' "" \
--replace-fail '"@llvm_toolchain_llvm//:lib/libclang.so",' "" \
--replace-fail '"@llvm_toolchain_llvm//:lib_legacy",' "" \
--replace-fail '"@sysroot_linux_amd64//:usr/include/stdio.h",' "" \
--replace-fail '"@sysroot_linux_arm64//:usr/include/stdio.h",' "" \
--replace-fail '"@platforms//cpu:x86_64": ["@sysroot_linux_amd64//:headers"],' "" \
--replace-fail '"@platforms//cpu:aarch64": ["@sysroot_linux_arm64//:headers"],' ""
mkdir -p bazel/nix/rust/bin bazel/nix/rust/rust_lib
substitute ${./bazel-nix-rust.BUILD.bazel} bazel/nix/rust/BUILD.bazel \
--subst-var-by dylib_ext "${stdenv'.hostPlatform.extensions.sharedLibrary}" \
--subst-var-by rust_triple "${rustTriple}"
ln -s "${rustc}/bin/rustc" bazel/nix/rust/bin/rustc
ln -s "${rustc}/bin/rustdoc" bazel/nix/rust/bin/rustdoc
ln -s "${cargo}/bin/cargo" bazel/nix/rust/bin/cargo
ln -s "${clippy}/bin/clippy-driver" bazel/nix/rust/bin/clippy-driver
cp -rs "$(${rustc}/bin/rustc --print sysroot)/lib/rustlib/${rustTriple}/lib/." bazel/nix/rust/rust_lib/
'';
preBuildPhases = [ "preBuildPhase" ];
preBuildPhase =
lib.optionalString (finalAttrs.bazelRepoCache != null) ''
# repo_cache needs to be writable even in air-gapped builds
mkdir repo_cache
${lndir}/bin/lndir -silent ${finalAttrs.bazelRepoCache}/repo_cache repo_cache
''
+ ''
true
'';
buildPhase = ''
runHook preBuild
export HOME=$(mktemp -d)
export BAZEL_USE_CPP_ONLY_TOOLCHAIN=1
export USER=homeless-shelter
${lib.optionalString stdenv.hostPlatform.isDarwin ''
export NIX_CFLAGS_COMPILE_${stdenv'.cc.suffixSalt}="''${NIX_CFLAGS_COMPILE:-}"
export NIX_CXXSTDLIB_COMPILE_${stdenv'.cc.suffixSalt}="''${NIX_CXXSTDLIB_COMPILE:-}"
export NIX_LDFLAGS_${stdenv'.cc.suffixSalt}="''${NIX_LDFLAGS:-}"
''}
echo repo_cache >> .bazelignore
${lib.optionalString (finalAttrs.bazelRepoCache != null) ''
sed -i.bak "s|https://bcr.bazel.build/|file://${mkBazelRegistries finalAttrs.bazelRepoCache}/bcr|g" .bazelrc
sed -i.bak "s|https://raw.githubusercontent.com/envoyproxy/bazel-registry/[^ ]*|file://${mkBazelRegistries finalAttrs.bazelRepoCache}/envoy|g" .bazelrc
rm -f .bazelrc.bak
''}
{
echo "common --lockfile_mode=off"
echo "build --jobs=$NIX_BUILD_CORES"
${lib.optionalString stdenv.hostPlatform.isLinux ''
for flag in $NIX_CFLAGS_COMPILE $NIX_CXXSTDLIB_COMPILE; do
echo "build --copt=$flag"
echo "build --host_copt=$flag"
done
for flag in $NIX_LDFLAGS; do
echo "build --linkopt=-Wl,$flag"
echo "build --host_linkopt=-Wl,$flag"
done
''}
${lib.optionalString stdenv.hostPlatform.isDarwin ''
echo "build --linkopt=-isysroot"
echo "build --linkopt=$SDKROOT"
echo "build --linkopt=-L${lib.getLib libiconv}/lib"
echo "build --host_linkopt=-isysroot"
echo "build --host_linkopt=$SDKROOT"
echo "build --host_linkopt=-L${lib.getLib libiconv}/lib"
''}
} >> user.bazelrc
${bazel_8}/bin/bazel \
--server_javabase=${jdk21_headless.home} \
--batch \
build \
--repository_cache=repo_cache \
${lib.escapeShellArgs commonCommandArgs} \
//source/exe:envoy-static
runHook postBuild
'';
installPhase = ''
runHook preInstall
install -Dm755 bazel-bin/source/exe/envoy-static "$out/bin/envoy"
runHook postInstall
'';
passthru = {
inherit cargoBazel mkRepoCache discoverDeps;
discoverDepsScript = ./discover-deps.py;
updateScript = writeShellScript "update-envoy" ''
set -euo pipefail
${
lib.escapeShellArgs (nix-update-script {
attrPath = "envoy";
extraArgs = [ "--use-github-releases" ];
})
} "$@"
exec ${envoy.discoverDeps} --attr envoy --pkg-dir pkgs/by-name/en/envoy
'';
tests = {
envoy = nixosTests.envoy;
};
};
meta = {
@@ -385,4 +492,4 @@ buildBazelPackage rec {
"aarch64-linux"
];
};
}
})

View File

@@ -0,0 +1,39 @@
--- a/BUILD.bazel
+++ b/BUILD.bazel
@@ -1,29 +1,7 @@
-load("@bazel_gazelle//:def.bzl", "gazelle")
-load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
-
-# gazelle:prefix github.com/envoyproxy/protoc-gen-validate
-# gazelle:exclude tests
-# gazelle:exclude example-workspace
-# gazelle:exclude validate/validate.h
-# gazelle:go_naming_convention import_alias
-gazelle(name = "gazelle")
-
-go_binary(
- name = "protoc-gen-validate",
- embed = [":protoc-gen-validate_lib"],
- importpath = "github.com/envoyproxy/protoc-gen-validate",
- visibility = ["//visibility:public"],
-)
-
-go_library(
- name = "protoc-gen-validate_lib",
- srcs = ["main.go"],
- importpath = "github.com/envoyproxy/protoc-gen-validate",
- visibility = ["//visibility:private"],
- deps = [
- "//module",
- "@com_github_lyft_protoc_gen_star_v2//:protoc-gen-star",
- "@com_github_lyft_protoc_gen_star_v2//lang/go",
- "@org_golang_google_protobuf//types/pluginpb",
- ],
-)
+genrule(
+ name = "protoc-gen-validate",
+ outs = ["protoc-gen-validate-bin"],
+ cmd = "cp @protoc_gen_validate@ $@ && chmod +x $@",
+ executable = True,
+ visibility = ["//visibility:public"],
+)

View File

@@ -0,0 +1,12 @@
--- a/buf/internal/toolchain.bzl
+++ b/buf/internal/toolchain.bzl
@@ -102,6 +102,9 @@
return goos, goarch
def _buf_download_releases_impl(ctx):
+ ctx.file("BUILD", "")
+ return
+
version = ctx.attr.version
repository_url = ctx.attr.repository_url
sha256 = ctx.attr.sha256

View File

@@ -0,0 +1,8 @@
--- a/cc/private/toolchain/generate_system_module_map.sh
+++ b/cc/private/toolchain/generate_system_module_map.sh
@@ -1,4 +1,4 @@
-#!/usr/bin/env bash
+#!@bash@
# Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -0,0 +1,8 @@
--- a/java/bazel/rules/java_stub_template.txt
+++ b/java/bazel/rules/java_stub_template.txt
@@ -1,4 +1,4 @@
-#!/usr/bin/env bash
+#!@bash@
# Copyright 2014 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");

View File

@@ -1,50 +0,0 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Luke Granger-Brown <git@lukegb.com>
Date: Thu, 17 Apr 2025 02:44:24 +0100
Subject: [PATCH] rules_rust base
Signed-off-by: Luke Granger-Brown <git@lukegb.com>
---
crate_universe/src/lockfile.rs | 4 ++--
rust/private/rustc.bzl | 4 ++--
4 files changed, 13 insertions(+), 13 deletions(-)
diff --git crate_universe/src/lockfile.rs crate_universe/src/lockfile.rs
index 3e0ce6265fda6fbdd9e3e989e3e4e4443b615b8c..0fafcea8fbc7a590676d34d2c4ca8c413b953955 100644
--- crate_universe/src/lockfile.rs
+++ crate_universe/src/lockfile.rs
@@ -146,10 +146,10 @@ impl Digest {
));
hasher.update(b"\0");
- hasher.update(Digest::compute_single_hash(cargo_version, "Cargo version"));
+ hasher.update(Digest::compute_single_hash("hermetic", "Cargo version"));
hasher.update(b"\0");
- hasher.update(Digest::compute_single_hash(rustc_version, "Rustc version"));
+ hasher.update(Digest::compute_single_hash("hermetic", "Rustc version"));
hasher.update(b"\0");
let hash = hasher.finalize().encode_hex::<String>();
diff --git rust/private/rustc.bzl rust/private/rustc.bzl
index d78c28902c8f73ae655b8f6b5df3db5a1805aa19..321a24a946c33d5e3452758a72a77b52d5a3eccf 100644
--- rust/private/rustc.bzl
+++ rust/private/rustc.bzl
@@ -1059,7 +1059,7 @@ def construct_arguments(
if toolchain.llvm_cov and ctx.configuration.coverage_enabled:
# https://doc.rust-lang.org/rustc/instrument-coverage.html
- rustc_flags.add("--codegen=instrument-coverage")
+ pass
if toolchain._experimental_link_std_dylib:
rustc_flags.add("--codegen=prefer-dynamic")
@@ -1563,7 +1563,7 @@ def rustc_compile_action(
})
crate_info = rust_common.create_crate_info(**crate_info_dict)
- if crate_info.type in ["staticlib", "cdylib"]:
+ if crate_info.type in ["staticlib", "cdylib"] and not out_binary:
# These rules are not supposed to be depended on by other rust targets, and
# as such they shouldn't provide a CrateInfo. However, one may still want to
# write a rust_test for them, so we provide the CrateInfo wrapped in a provider

View File

@@ -1,18 +0,0 @@
--- crate_universe/src/metadata/cargo_tree_rustc_wrapper.sh
+++ crate_universe/src/metadata/cargo_tree_rustc_wrapper.sh
@@ -1,4 +1,4 @@
-#!/usr/bin/env bash
+#!@bash@
#
# For details, see:
# `@rules_rust//crate_universe/src/metadata/cargo_tree_resolver.rs - TreeResolver::create_rustc_wrapper`
--- util/process_wrapper/private/process_wrapper.sh
+++ util/process_wrapper/private/process_wrapper.sh
@@ -1,4 +1,4 @@
-#!/usr/bin/env bash
+#!@bash@
set -euo pipefail

View File

@@ -0,0 +1,33 @@
diff --git a/crate_universe/private/generate_utils.bzl b/crate_universe/private/generate_utils.bzl
--- a/crate_universe/private/generate_utils.bzl
+++ b/crate_universe/private/generate_utils.bzl
@@ -399,6 +399,8 @@ def determine_repin(
if not lockfile_path:
return True
+ return False
+
# Run the binary to check if a repin is needed
result = cargo_bazel_fn(
args = [
diff --git a/crate_universe/extensions.bzl b/crate_universe/extensions.bzl
--- a/crate_universe/extensions.bzl
+++ b/crate_universe/extensions.bzl
@@ -824,6 +824,8 @@ def _get_generator(module_ctx, host_triple):
tuple(path, dict) The path to a 'cargo-bazel' binary. The pairing (dict)
may be `None` if there is not need to update the attribute
"""
+ return module_ctx.path("@cargo_bazel@")
+
use_environ = False
for var in GENERATOR_ENV_VARS:
if var in module_ctx.os.environ:
@@ -873,6 +875,8 @@ def _get_host_cargo_rustc(module_ctx, host_triple, host_tools_repo):
Returns:
tuple[Path, Path]: A tuple of path to cargo, path to rustc.
"""
+ return module_ctx.path("@cargo@"), module_ctx.path("@rustc@")
+
binary_ext = system_to_binary_ext(host_triple.system)
root = module_ctx.path(host_tools_repo)

View File

@@ -0,0 +1,21 @@
--- a/BUILD.bazel
+++ b/BUILD.bazel
@@ -6,7 +6,6 @@
load("@rules_cc//cc:cc_library.bzl", "cc_library")
load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
load("@rules_python//python:defs.bzl", "py_binary", "py_test")
-load("@v8_python_deps//:requirements.bzl", "requirement")
load(
"@v8//:bazel/defs.bzl",
"v8_binary",
@@ -4395,9 +4394,7 @@
"third_party/inspector_protocol/templates/TypeBuilder_h.template",
],
imports = ["third_party/inspector_protocol/"],
- deps = [
- requirement("jinja2"),
- ],
+ deps = [],
)
genrule(

View File

@@ -0,0 +1,11 @@
--- /dev/null
+++ b/crates/c-api/include/wasmtime/conf.h
@@ -0,0 +1,8 @@
+#ifndef WASMTIME_CONF_H
+#define WASMTIME_CONF_H
+
+#define WASMTIME_FEATURE_CRANELIFT
+#define WASMTIME_FEATURE_COMPILER
+#define WASMTIME_FEATURE_GC
+
+#endif // WASMTIME_CONF_H

View File

@@ -0,0 +1,302 @@
diff --git a/BUILD b/BUILD
index 4c71dda..755d3b1 100644
--- a/BUILD
+++ b/BUILD
@@ -2,9 +2,7 @@ load(
"@envoy//bazel:envoy_build_system.bzl",
"envoy_cc_binary",
)
-load("@hedron_compile_commands//:refresh_compile_commands.bzl", "refresh_compile_commands")
load("@rules_foreign_cc//foreign_cc:configure.bzl", "configure_make")
-load("//bazel/ci/images:oci.bzl", "image")
package(default_visibility = ["//visibility:public"])
@@ -59,30 +57,6 @@ envoy_cc_binary(
],
)
-image(
- name = "envoy.image",
- srcs = [":envoy"],
- repository = "ghcr.io/pomerium/envoy-custom-debug",
-)
-
-image(
- name = "envoy.stripped.image",
- srcs = [":envoy.stripped"],
- repository = "ghcr.io/pomerium/envoy-custom",
-)
-
-image(
- name = "envoy.static.image",
- srcs = [":envoy.static"],
- repository = "ghcr.io/pomerium/envoy-custom-static-debug",
-)
-
-image(
- name = "envoy.static.stripped.image",
- srcs = [":envoy.static.stripped"],
- repository = "ghcr.io/pomerium/envoy-custom-static",
-)
-
configure_make(
name = "openssh_config_h",
autoreconf = True,
@@ -111,12 +85,3 @@ configure_make(
],
)
-refresh_compile_commands(
- name = "refresh_compile_commands",
- exclude_headers = "external",
- targets = {
- "//:envoy": "",
- "//test/...": "",
- "//tools/...": "",
- },
-)
diff --git a/WORKSPACE b/WORKSPACE
index 65931b6..6067474 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -2,31 +2,6 @@ workspace(name = "pomerium_envoy")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
-# Hedron's Compile Commands Extractor for Bazel
-# https://github.com/hedronvision/bazel-compile-commands-extractor
-http_archive(
- name = "hedron_compile_commands",
- sha256 = "e875b18876190b172ab59eaf193c2eec16fff8c46306c5eb0577ef7d1f8a65f7",
- strip_prefix = "bazel-compile-commands-extractor-9f69112e3f61b9df76a8275085dabad36ef37c96",
- url = "https://github.com/kralicky/bazel-compile-commands-extractor/archive/9f69112e3f61b9df76a8275085dabad36ef37c96.tar.gz",
-)
-
-load("@hedron_compile_commands//:workspace_setup.bzl", "hedron_compile_commands_setup")
-
-hedron_compile_commands_setup()
-
-load("@hedron_compile_commands//:workspace_setup_transitive.bzl", "hedron_compile_commands_setup_transitive")
-
-hedron_compile_commands_setup_transitive()
-
-load("@hedron_compile_commands//:workspace_setup_transitive_transitive.bzl", "hedron_compile_commands_setup_transitive_transitive")
-
-hedron_compile_commands_setup_transitive_transitive()
-
-load("@hedron_compile_commands//:workspace_setup_transitive_transitive_transitive.bzl", "hedron_compile_commands_setup_transitive_transitive_transitive")
-
-hedron_compile_commands_setup_transitive_transitive_transitive()
-
envoy_version = "4be7862a2a6d9a7867f576385d545bb0b47b9181" # v1.38.5
openssh_version = "V_10_3_P1"
@@ -70,6 +45,7 @@ http_archive(
],
sha256 = "1b1c95003a057560451c545de8fb281040fd0b0a38387f0a461f1b018df715d2",
strip_prefix = "envoy-" + envoy_version,
+ patch_cmds = ["@patch_envoy_tree@ ."],
url = "https://github.com/envoyproxy/envoy/archive/" + envoy_version + ".tar.gz",
)
@@ -98,17 +74,6 @@ envoy_api_dependencies()
load("@envoy//bazel:repositories.bzl", "envoy_dependencies", "external_http_archive")
-external_http_archive(
- name = "toolchains_llvm",
- patch_args = ["-p1"],
- patches = [
- "@envoy//bazel:toolchains_llvm.patch",
- "@envoy//bazel/foreign_cc:toolchains_llvm_stdc++.patch",
- # linux->darwin cross-compile support
- "//patches/toolchains_llvm:0002-darwin.patch",
- ],
-)
-
external_http_archive(
name = "luajit",
build_file = "//bazel/foreign_cc:luajit.BUILD",
@@ -125,21 +90,6 @@ load("//bazel:repositories.bzl", "patch_antlr4_runtimes")
patch_antlr4_runtimes()
-http_archive(
- name = "rules_oci",
- sha256 = "6d47e0bb9d3c269695cbb35abb603d1db08434376a1210867da8f6f4a9c630ba",
- strip_prefix = "rules_oci-" + rules_oci_version,
- url = "https://github.com/bazel-contrib/rules_oci/releases/download/v" + rules_oci_version + "/rules_oci-v" + rules_oci_version + ".tar.gz",
-)
-
-load("@rules_oci//oci:dependencies.bzl", "rules_oci_dependencies")
-
-rules_oci_dependencies()
-
-load("@rules_oci//oci:repositories.bzl", "oci_register_toolchains")
-
-oci_register_toolchains(name = "oci")
-
load("@envoy//bazel:bazel_deps.bzl", "envoy_bazel_dependencies")
envoy_bazel_dependencies()
@@ -160,26 +110,6 @@ load("@envoy//bazel:repo.bzl", "envoy_repo")
envoy_repo()
-load("//bazel:toolchains.bzl", "pomerium_envoy_toolchains")
-
-pomerium_envoy_toolchains()
-
-load("//bazel/sysroots:load_sysroots.bzl", "load_sysroots")
-
-load_sysroots()
-
-load("//bazel/cxx_libs:load_cxx_cross_libs.bzl", "load_cxx_cross_libs")
-
-load_cxx_cross_libs()
-
-load("//bazel/llvm_extras:load_llvm_extras.bzl", "load_llvm_extras")
-
-load_llvm_extras()
-
-load("@llvm_toolchain//:toolchains.bzl", "llvm_register_toolchains")
-
-llvm_register_toolchains()
-
envoy_http_archive(
name = "openssh_portable",
build_file = "//bazel/foreign_cc:openssh.BUILD",
diff --git a/bazel/foreign_cc/openssh/include/config_linux/config.h b/bazel/foreign_cc/openssh/include/config_linux/config.h
index a9c6142..0209f12 100644
--- a/bazel/foreign_cc/openssh/include/config_linux/config.h
+++ b/bazel/foreign_cc/openssh/include/config_linux/config.h
@@ -1157,7 +1157,6 @@
#define HAVE_RLIMIT_NPROC /**/
/* Define to 1 if you have the <rpc/types.h> header file. */
-#define HAVE_RPC_TYPES_H 1
/* Define to 1 if you have the `rresvport_af' function. */
#define HAVE_RRESVPORT_AF 1
diff --git a/envoy.bazelrc b/envoy.bazelrc
index e87a20e..45d53cb 100644
--- a/envoy.bazelrc
+++ b/envoy.bazelrc
@@ -98,8 +98,6 @@ build:macos --action_env=PATH=/opt/homebrew/bin:/opt/local/bin:/usr/local/bin:/u
build:macos --host_action_env=PATH=/opt/homebrew/bin:/opt/local/bin:/usr/local/bin:/usr/bin:/bin
build:macos --define tcmalloc=disabled
build:macos --cxxopt=-Wno-nullability-completeness
-build:macos --@toolchains_llvm//toolchain/config:compiler-rt=false
-build:macos --@toolchains_llvm//toolchain/config:libunwind=false
#############################################################################
@@ -108,16 +106,12 @@ build:macos --@toolchains_llvm//toolchain/config:libunwind=false
# Common flags for Clang (shared between all clang variants)
common:clang-common --linkopt=-fuse-ld=lld
-common:clang-common --@toolchains_llvm//toolchain/config:compiler-rt=false
-common:clang-common --@toolchains_llvm//toolchain/config:libunwind=false
# Clang with libc++ (default)
-common:clang --config=clang-common
common:clang --config=libc++
common:clang --repo_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1
# Clang installed to non-standard location (ie not /opt/llvm/)
-common:clang-local --config=clang-common
common:clang-local --config=libc++
# Use gold linker for gcc compiler.
@@ -144,7 +138,6 @@ build:gcc --action_env=BAZEL_LINKOPTS=-lm:-fuse-ld=gold
# libc++ - default for clang
common:libc++ --action_env=CXXFLAGS=-stdlib=libc++
-common:libc++ --action_env=LDFLAGS="-stdlib=libc++ -fuse-ld=lld"
common:libc++ --action_env=BAZEL_CXXOPTS=-stdlib=libc++
common:libc++ --action_env=BAZEL_LINKLIBS=-l%:libc++.a:-l%:libc++abi.a
common:libc++ --action_env=BAZEL_LINKOPTS=-lm:-pthread
@@ -270,7 +263,6 @@ build:asan-common --build_tag_filters=-no_san
build:asan-common --test_tag_filters=-no_san
build:asan-common --copt -fsanitize=address,undefined
build:asan-common --linkopt -fsanitize=address,undefined
-# vptr and function sanitizer are enabled in asan when using --config=clang.
build:asan-common --copt -fno-sanitize=vptr,function
build:asan-common --linkopt -fno-sanitize=vptr,function
build:asan-common --copt -DADDRESS_SANITIZER=1
@@ -463,21 +455,17 @@ build:docker-sandbox --experimental_docker_verbose
build:docker-sandbox --experimental_enable_docker_sandbox
build:docker-clang --config=docker-sandbox
-build:docker-clang --config=clang
build:docker-gcc --config=docker-sandbox
build:docker-gcc --config=gcc
build:docker-asan --config=docker-sandbox
-build:docker-asan --config=clang
build:docker-asan --config=asan
build:docker-msan --config=docker-sandbox
-build:docker-msan --config=clang
build:docker-msan --config=msan
build:docker-tsan --config=docker-sandbox
-build:docker-tsan --config=clang
build:docker-tsan --config=tsan
diff --git a/pomerium.bazelrc b/pomerium.bazelrc
index 1392bb8..66558e0 100644
--- a/pomerium.bazelrc
+++ b/pomerium.bazelrc
@@ -3,7 +3,6 @@ build:linux --copt="-Wno-error=unused-command-line-argument"
# The quiche library is partially annotated for nullability.
build --copt="-Wno-nullability-completeness"
build --cxxopt=-std=c++23 --host_cxxopt=-std=c++23
-build --config=clang
build:asan-common --test_env=UBSAN_SYMBOLIZER_PATH
build:tsan --test_env=TSAN_SYMBOLIZER_PATH
@@ -12,16 +11,11 @@ build:tsan --test_env=TSAN_SYMBOLIZER_PATH
# Force all cc targets built with the llvm toolchain to use compiler-rt and libunwind. This removes
# the dependency on libgcc.
-common:clang-common --@toolchains_llvm//toolchain/config:compiler-rt=true
-common:clang-common --@toolchains_llvm//toolchain/config:libunwind=true
# Same as above, but applies to foreign_cc targets using autotools/cmake, which may not inherit the
# link flags applied by the toolchain.
# FIXME: this should not be necessary, but not having it breaks c-only foreign_cc dependencies
# that use cmake. The c-only targets DO inherit flags from the toolchain's conly_flags option, but
# that also breaks other C targets when set due to unused compiler flag errors.
-common:libc++ --action_env=LDFLAGS="-stdlib=libc++ -fuse-ld=lld -rtlib=compiler-rt"
-common:sanitizer --action_env=LDFLAGS="-stdlib=libc++ -fuse-ld=lld -rtlib=compiler-rt -l:libunwind.a"
-common:coverage --action_env=LDFLAGS="-stdlib=libc++ -fuse-ld=lld -rtlib=compiler-rt -l:libunwind.a"
# Disable cgo. If cgo is enabled, some of the cc toolchain flags will propagate to the go toolchain,
# which causes fPIC mismatch errors.
diff --git a/bazel/foreign_cc/luajit.bzl b/bazel/foreign_cc/luajit.bzl
--- a/bazel/foreign_cc/luajit.bzl
+++ b/bazel/foreign_cc/luajit.bzl
@@ -73,7 +73,7 @@ def _get_host_platform():
if "@platforms//cpu:x86_64" in HOST_CONSTRAINTS:
host_arch = "x64"
- elif "@platforms//cpu:arm64" in HOST_CONSTRAINTS:
+ elif "@platforms//cpu:arm64" in HOST_CONSTRAINTS or "@platforms//cpu:aarch64" in HOST_CONSTRAINTS:
host_arch = "arm64"
else:
fail("unknown host platform: %s" % HOST_CONSTRAINTS)
diff --git a/source/common/apple.h b/source/common/apple.h
--- a/source/common/apple.h
+++ b/source/common/apple.h
@@ -1,7 +1,2 @@
+// Nix links against its own libcxx rather than Apple's system libc++.1.dylib.
#include <version>
-
-#if defined(__APPLE__)
-#if !_LIBCPP_HAS_VENDOR_AVAILABILITY_ANNOTATIONS
-#error "vendor availability annotations are not enabled"
-#endif
-#endif

View File

@@ -0,0 +1,50 @@
load("@aspect_bazel_lib//lib/private:jq_toolchain.bzl", "jq_toolchain")
load("@bazel_tools//tools/sh:sh_toolchain.bzl", "sh_toolchain")
exports_files([
"protoc-gen-validate",
"yq",
"jq",
])
sh_toolchain(
name = "local_sh_impl",
path = "@bash@",
)
toolchain(
name = "local_sh",
toolchain = ":local_sh_impl",
toolchain_type = "@bazel_tools//tools/sh:toolchain_type",
)
jq_toolchain(
name = "jq_nix_impl",
bin = ":jq",
)
toolchain(
name = "jq_nix",
toolchain = ":jq_nix_impl",
toolchain_type = "@aspect_bazel_lib//lib:jq_toolchain_type",
)
platform(
name = "darwin_arm64",
constraint_values = [
"@platforms//cpu:aarch64",
"@platforms//os:macos",
],
)
# Synthetic C++ toolchain alias for cross-platform `--nobuild` dependency
# discovery from Linux hosts; not registered during normal builds.
toolchain(
name = "darwin_arm64_cc_toolchain",
target_compatible_with = [
"@platforms//cpu:aarch64",
"@platforms//os:macos",
],
toolchain = "@local_config_cc//:@cc_compiler@",
toolchain_type = "@bazel_tools//tools/cpp:toolchain_type",
)

View File

@@ -0,0 +1,395 @@
{
"hash": "sha256-xUFjxH7Gx8odF6uKLzT8kEVDrUeAiPLwuR1R79BZbV4=",
"entries": [
{
"sha256": "0485886f4d2aa3b666540e752d7a2e8eed9b79f6840f8f1cfad3b41f135cdb76",
"urls": [
"https://github.com/envoyproxy/toolshed/releases/download/bazel-v0.4.13.post0/toolshed-bazel-v0.4.13.post0.tar.gz"
]
},
{
"sha256": "08033a0886b470d4ea836a6b785ef6ef7d638265e5523a37718cdd6d1ef6a409",
"urls": [
"https://github.com/google/quiche/archive/e68fe05e70da74a3ea282d927c76f76b4bc4e710.tar.gz"
]
},
{
"sha256": "098ba13578e796c00c853a2161f382647f32eb9a77099e1c88bc5299333d0d6e",
"urls": [
"https://github.com/bazelbuild/rules_python/archive/1.9.0.tar.gz"
]
},
{
"sha256": "0a4f9a1c0bcc83629eb30d1c278883d32dec0f701efcdabd7bebf33fef8dab71",
"urls": [
"https://github.com/google/cel-cpp/archive/v0.14.0.tar.gz"
]
},
{
"sha256": "0af37b800953130b47c075b56683ee60bdc3eda3c37fc6004193f5b569758204",
"urls": [
"https://github.com/grpc/grpc/archive/v1.76.0.tar.gz"
]
},
{
"sha256": "13583c5a312861648449845b709722676a3c9b43396b6b8e9cbe4538feb74ad2",
"urls": [
"https://github.com/google/cel-spec/archive/v0.25.1.tar.gz"
]
},
{
"sha256": "14a225870ab4e91869652cfd69ef2028277fc1dc4910d65d353b62d6e0ae21f4",
"urls": [
"https://github.com/bazelbuild/rules_proto/archive/refs/tags/7.1.0.tar.gz"
]
},
{
"sha256": "17b18cb4f92ab7b94aa343ce78531b73960b1bed2ba166e5b02c9fdf0b0ac270",
"urls": [
"https://github.com/bazelbuild/rules_java/releases/download/7.12.5/rules_java-7.12.5.tar.gz"
]
},
{
"sha256": "1b1c95003a057560451c545de8fb281040fd0b0a38387f0a461f1b018df715d2",
"urls": [
"https://github.com/envoyproxy/envoy/archive/4be7862a2a6d9a7867f576385d545bb0b47b9181.tar.gz"
]
},
{
"sha256": "1e54959a3f3cb675938d858603ad69d0f3f7c82439fc2bf86d7232daec2bd10e",
"urls": [
"https://github.com/Neargye/magic_enum/archive/v0.9.8.tar.gz"
]
},
{
"sha256": "20da84f8efe8f53c10cbde79d2cdd1e63365b0ae1ad9de22af56aa1a49d59330",
"urls": [
"https://github.com/bufbuild/protoc-gen-validate/archive/refs/tags/v1.3.3.zip"
]
},
{
"sha256": "25cb043240f828a8c51beb830569634bc7ac603978e0f69d6b63558dadefd49a",
"urls": [
"https://github.com/jbeder/yaml-cpp/archive/refs/tags/yaml-cpp-0.9.0.tar.gz"
]
},
{
"sha256": "26d4021f6898e23b82ef953078389dd49ac2b5618ac564ade4ef87cced147b38",
"urls": [
"https://github.com/bazelbuild/rules_license/releases/download/1.0.0/rules_license-1.0.0.tar.gz"
]
},
{
"sha256": "283fa1cdaaf172337898749cf4b9b1ef5ea269da59540954e51fba0e7b8f277a",
"urls": [
"https://github.com/bazelbuild/rules_cc/releases/download/0.2.17/rules_cc-0.2.17.tar.gz"
]
},
{
"sha256": "28db894977ac51c8f3ab7c6dc9d655a85510366734e900b3c5302ce1ed91256c",
"urls": [
"https://github.com/bazelbuild/rules_swift/releases/download/2.4.0/rules_swift.2.4.0.tar.gz"
]
},
{
"sha256": "2a0860a336ae836b54671cbbe0710eec17c64ef70c4c5a88ccfd47ea6e3739bd",
"urls": [
"https://github.com/rules-proto-grpc/rules_proto_grpc/releases/download/4.6.0/rules_proto_grpc-4.6.0.tar.gz"
]
},
{
"sha256": "2a6bef88f8cccda4a63a2f4bb09e655b3ee5ea0a2ce68d16e6ea2d5f5c4be9c1",
"urls": [
"https://github.com/google/tcmalloc/archive/12f255231938d30493186b0a037feedd70f5a1c1.tar.gz"
]
},
{
"sha256": "32759728913c376ba45b0116869b71b68b1c2ebf8f2bcf7b41222bc07b773d73",
"urls": [
"https://github.com/bazelbuild/rules_foreign_cc/archive/0.15.1.tar.gz"
]
},
{
"sha256": "3560f7dd3f08e16b9f84d877a5be21ec62071564783009571af5fcc6fad734d2",
"urls": [
"https://github.com/google/boringssl/archive/0.20260413.0.tar.gz"
]
},
{
"sha256": "365ff6aec0b1612fb964a763ca73748d80e0b3379cbdd9f82d86333eb8ae4638",
"urls": [
"https://github.com/antlr/antlr4/archive/refs/tags/4.13.1.zip"
]
},
{
"sha256": "3709d1745ba4be4ef054449647b62e424267066eca887bb00dd29242cb8463a0",
"urls": [
"https://github.com/bazelbuild/rules_shell/releases/download/v0.7.1/rules_shell-v0.7.1.tar.gz"
]
},
{
"sha256": "37d7284556b20954e56e1ca85b80226768902e2edabd3b649e9e72c0c9012ee3",
"urls": [
"https://github.com/facebook/zstd/archive/v1.5.7.tar.gz"
]
},
{
"sha256": "3b5b49006181f5f8ff626ef8ddceaa95e9bb8ad294f7b5d7b11ea9f7ddaf8c59",
"urls": [
"https://github.com/bazelbuild/bazel-skylib/releases/download/1.9.0/bazel-skylib-1.9.0.tar.gz"
]
},
{
"sha256": "4314e2a7cbac89cac25a2f2322870f343d81579756ceff7f431803c2c9090195",
"urls": [
"https://github.com/abseil/abseil-cpp/archive/20260107.1.tar.gz"
]
},
{
"sha256": "47c5ea7949f68e7f7b344350c59b6bd31eeb921f0eec6c3a566e27cf1951470c",
"urls": [
"https://github.com/prometheus/client_model/archive/v0.6.2.tar.gz"
]
},
{
"sha256": "4b92eb0c06d10683f7447ce9406cb97cd4b453be18d7279320f7b2f025c10187",
"urls": [
"https://github.com/nlohmann/json/archive/v3.12.0.tar.gz"
]
},
{
"sha256": "4c80e5fe044ce5f8055b20a2f141ee32ec2614000f3e95d2aa81611a4c8f5213",
"urls": [
"https://github.com/libevent/libevent/archive/62c152d9a7cd264b993dad730c4163c6ede2e0a3.tar.gz"
]
},
{
"sha256": "4ffa45a827646692e7b26e2a8c0dcbc1b1763a26def2fbbd82362970962a2fcf",
"urls": [
"https://github.com/google/gurl/archive/dd4080fec0b443296c0ed0036e1e776df8813aa7.tar.gz"
]
},
{
"sha256": "52c85df79badc45da7e6a8735e8090b05a961b0208756187e1492a40db2d1f5f",
"urls": [
"https://github.com/open-telemetry/opentelemetry-proto/archive/v1.10.0.tar.gz"
]
},
{
"sha256": "532224ed052bcd5f4c6be0ed9bb2b8c88dfe7e26e3eb4dd9335303b059df6691",
"urls": [
"https://github.com/cameron314/readerwriterqueue/archive/v1.0.7.tar.gz"
]
},
{
"sha256": "53cadea9109e646a93ed4dc90c9bbcaa8073c7c3df745b92f6a5000daf7aa3da",
"urls": [
"https://github.com/aspect-build/bazel-lib/releases/download/v2.21.2/bazel-lib-v2.21.2.tar.gz"
]
},
{
"sha256": "5f80964108981c6ad979c735f0b4877d5f49914c2a062f8e88282f26bf61de0c",
"urls": [
"https://github.com/axboe/liburing/archive/liburing-2.14.tar.gz"
]
},
{
"sha256": "695fd197fa5aff8fc67b5f2bbc110490a875cdf7a41686ac8512fb480fa8ada7",
"urls": [
"https://github.com/fmtlib/fmt/releases/download/12.1.0/fmt-12.1.0.zip"
]
},
{
"sha256": "6a0561b50b8f5f6434a6a9e667a67026f2b2064a1ffa959c6b2dae320161c2a8",
"urls": [
"https://github.com/zlib-ng/zlib-ng/archive/2.3.2.tar.gz"
]
},
{
"sha256": "6b6599b54c88d75904b7471f5ca34a725fa0af92e134dd1a32d5b395aa4b4ca8",
"urls": [
"https://github.com/protocolbuffers/protobuf/releases/download/v33.2/protobuf-33.2.tar.gz"
]
},
{
"sha256": "6dfbd649fde380f7a2256def43b9c6374c6d6fe768178b09e39eedf874b139f4",
"urls": [
"https://github.com/openhistogram/libcircllhist/archive/refs/tags/py-0.3.2.tar.gz"
]
},
{
"sha256": "73ad768dfe824c736d0a8a81521867b1fb7a822acda2ed265897c03de6ae6767",
"urls": [
"https://github.com/bazelbuild/rules_apple/releases/download/3.20.1/rules_apple.3.20.1.tar.gz"
]
},
{
"sha256": "74c978eab040ad4ec38ce0d0970ac813cc2c6f4f6f4f121c0414719487edc991",
"urls": [
"https://mirror.bazel.build/bazel_java_tools/releases/java/v13.6.1/java_tools-v13.6.1.zip"
]
},
{
"sha256": "7b63435aa19cc6a0cfd1a82fbdf2c7a2f0a94db1a79ff7a4469ffa94286261ab",
"urls": [
"https://github.com/bazel-contrib/jq.bzl/releases/download/v0.1.0/jq.bzl-v0.1.0.tar.gz"
]
},
{
"sha256": "7e87d13734076fa4f626f6144ce9a02717198b3f054341a6886e2107b048b235",
"urls": [
"https://github.com/mirror/tclap/archive/v1.2.5.tar.gz"
]
},
{
"sha256": "816c96e8e8f193b40151dad7e8ff37b1221d019dbcb9c35cd3fadbfe6477dfec",
"urls": [
"https://github.com/google/brotli/archive/v1.2.0.tar.gz"
]
},
{
"sha256": "82363065ca2c978398d2307fe960c301a0b6655d55981fac017783bba22771d9",
"urls": [
"https://github.com/cncf/xds/archive/8bfbf64dc13ee1a570be4fbdcfccbdd8532463f0.tar.gz"
]
},
{
"sha256": "852b71bfa15712cec124e4a57179b6bc95d59fdf5052945f5d550e072501a769",
"urls": [
"https://github.com/bazelbuild/platforms/archive/1.0.0.tar.gz"
]
},
{
"sha256": "85c341e957ba58482892a8088e4a34391d15bd98917f0993ecb62f008d6986d6",
"urls": [
"https://github.com/bazel-contrib/toolchains_llvm/releases/download/v1.7.0/toolchains_llvm-v1.7.0.tar.gz"
]
},
{
"sha256": "86d3dc8f59d253524f933aaf2f3c05896cb0b605fc35b460c0b4b039996124c6",
"urls": [
"https://github.com/bazelbuild/rules_go/releases/download/v0.60.0/rules_go-v0.60.0.zip"
]
},
{
"sha256": "87adb1357bb5a932fa0de6fed0fc37412490a0c96f5259855008f208cf53a74f",
"urls": [
"https://github.com/bazelbuild/rules_fuzzing/archive/v0.7.0.tar.gz"
]
},
{
"sha256": "8a878777a18a013e0ee6604629d1b5f29b162354c14489ad1dccd370f14ac372",
"urls": [
"https://github.com/open-telemetry/opentelemetry-cpp/archive/refs/tags/v1.26.0.tar.gz"
]
},
{
"sha256": "912dd7cc3b3e8a79c52fd7fb9c0f4ecf0aaa73e45efda880266a2d6e26b84ef5",
"urls": [
"https://github.com/c-ares/c-ares/releases/download/v1.34.6/c-ares-1.34.6.tar.gz"
]
},
{
"sha256": "9555d9cf7bd541ea5fdb67d7d6b72ea44da77df3e27b960b4155dc0c6b81d476",
"urls": [
"https://github.com/grpc-ecosystem/proto-converter/archive/1db76535b86b80aa97489a1edcc7009e18b67ab7.zip"
]
},
{
"sha256": "97fc354dddfd3ea03e7bf2ad74129291ed6fad7ff39d3bd8daec738a3672eb8a",
"urls": [
"https://github.com/googleapis/googleapis/archive/fd52b5754b2b268bc3a22a10f29844f206abb327.tar.gz"
]
},
{
"sha256": "a835fe55fbdcd8e80f38584ab22d0840662c67f2feb36bd679402da9641dc71e",
"urls": [
"https://github.com/google/re2/releases/download/2024-07-02/re2-2024-07-02.zip"
]
},
{
"sha256": "aae608dfe8213dfd05d909a57718ef82f30722c392344583d3f39050c7f29a80",
"urls": [
"https://github.com/Cyan4973/xxHash/archive/v0.8.3.tar.gz"
]
},
{
"sha256": "ab3f16d82df6946543565cfb0d2810d387d79a3a43e0431695b03466188e2680",
"urls": [
"https://github.com/LuaJIT/LuaJIT/archive/871db2c84ecefd70a850e03a6c340214a81739f0.tar.gz"
]
},
{
"sha256": "adfdb3cffab3a99a63363d844d559a81965d2b61a6062dd51a3d2478d416768f",
"urls": [
"https://github.com/bazel-contrib/bazel_features/releases/download/v1.45.0/bazel_features-v1.45.0.tar.gz"
]
},
{
"sha256": "b51d82b561a78ab21d265107b0edbf98d68a390b4103992d0b03258bb3819601",
"urls": [
"https://github.com/bazel-contrib/yq.bzl/releases/download/v0.1.1/yq.bzl-v0.1.1.tar.gz"
]
},
{
"sha256": "b53f6491e742549f13866628ddffcc75d1f3b2d6987dc4f14a16b242113c890b",
"urls": [
"https://github.com/bazelbuild/apple_support/releases/download/1.17.1/apple_support.1.17.1.tar.gz"
]
},
{
"sha256": "bbc764c252d061281b2359277a4d46480e2dcfaf72afc1ce6e00ada58ccbfd4c",
"urls": [
"https://github.com/bazelbuild/rules_rust/releases/download/0.69.0/rules_rust-0.69.0.tar.gz"
]
},
{
"sha256": "bc13a9c57a8dd7d5196888211e5ede657cb64a3ce968608697e4f668251a8487",
"urls": [
"https://www.antlr.org/download/antlr-4.13.1-complete.jar"
]
},
{
"sha256": "c1a4420b1a25ba7336f62afd42ed5974d93455a2ab8c769b5e8e0c8ff8eedadc",
"urls": [
"https://github.com/openssh/openssh-portable/archive/V_10_3_P1.tar.gz"
]
},
{
"sha256": "d18d919175f9e4d740ace6b52f0f4f91284160c454e91b36ffd6456282a02206",
"urls": [
"https://github.com/gperftools/gperftools/releases/download/gperftools-2.18.1/gperftools-2.18.1.tar.gz"
]
},
{
"sha256": "d8862955c6d74e5846b3f580b1605d2428b11d97a410d86e2fb13e857cd3a744",
"urls": [
"https://github.com/gabime/spdlog/archive/v1.17.0.tar.gz"
]
},
{
"sha256": "dbd2d449fca10c1cd655efe21eee34fe880f4ff5fe7f01562f7829ca8dd4b2bf",
"urls": [
"https://github.com/proxy-wasm/proxy-wasm-cpp-host/archive/beb8a4ece9eede4ab21d89d723359607600296d4.tar.gz"
]
},
{
"sha256": "de9c6411e8f1b45dd67ce2b93e9243731aec37df6d65cc20dcd574d2d0b65d0f",
"urls": [
"https://github.com/bazelbuild/rules_pkg/archive/1.2.0.tar.gz"
]
},
{
"sha256": "e178687730c207f3a659730096df192b52d3752786c068b8e5ee7aeb8edae05a",
"urls": [
"https://github.com/nghttp2/nghttp2/releases/download/v1.66.0/nghttp2-1.66.0.tar.gz"
]
},
{
"sha256": "f81c3162b1046fe8b84b9a0dbdd383e24fdbcf88583b9cb6028f90d04d90696a",
"urls": [
"https://github.com/google/flatbuffers/archive/v25.12.19.tar.gz"
]
}
]
}

View File

@@ -0,0 +1,5 @@
alias(
name = "protoc-gen-validate",
actual = "@//bazel/nix:protoc-gen-validate",
visibility = ["//visibility:public"],
)

View File

@@ -1,15 +1,13 @@
{
buildGoModule,
buildGo126Module,
buildNpmPackage,
runCommand,
runCommandCC,
callPackage,
fetchFromGitHub,
jq,
lib,
nixosTests,
pomerium-cli,
patchelf,
moreutils,
jq,
stdenv,
}:
let
@@ -20,6 +18,8 @@ let
mapAttrsToList
;
pomerium-envoy = callPackage ./pomerium-envoy.nix { };
version = "0.33.4";
src = fetchFromGitHub {
owner = "pomerium";
@@ -40,26 +40,8 @@ let
runHook postBuild
'';
};
getEnvoy = buildGoModule {
pname = "pomerium-get-envoy";
inherit
src
version
vendorHash
overrideModAttrs
;
subPackages = [
"pkg/envoy/get-envoy"
];
# get-envoy's envoy version is pinned via pkg/envoy/envoyversion, which
# relies on a specific version of github.com/pomerium/envoy-custom as a Go module,
# and then fetches that version's release binaries from GHCR.
};
in
buildGoModule (finalAttrs: {
buildGo126Module (finalAttrs: {
pname = "pomerium";
inherit
src
@@ -68,45 +50,7 @@ buildGoModule (finalAttrs: {
overrideModAttrs
;
envoyBinariesRaw =
runCommand "pomerium-envoy-binaries-raw"
{
nativeBuildInputs = [ getEnvoy ];
outputHashAlgo = "sha256";
outputHashMode = "recursive";
outputHash = "sha256-SX+LpYGwMb33eVRo6TO7rPUfSlMMfD0N4zvZZRnkG2w=";
meta = {
homepage = "https://github.com/pomerium/envoy-custom";
sourceProvenance = [ lib.sourceTypes.binaryNativeCode ];
};
}
''
mkdir $out
cd $out
get-envoy
chmod +x envoy-darwin-arm64 envoy-linux-amd64 envoy-linux-arm64
'';
envoyBinaries =
runCommandCC "pomerium-envoy-binaries"
{
nativeBuildInputs = [
patchelf
moreutils
jq
];
}
''
mkdir $out
cp ${finalAttrs.envoyBinariesRaw}/* $out
chmod -R +w $out
patchelf --set-interpreter $(cat $NIX_CC/nix-support/dynamic-linker) $out/envoy-linux-amd64
patchelf --set-interpreter $(cat $NIX_CC/nix-support/dynamic-linker) $out/envoy-linux-arm64
jq ".digest = \"sha256:$(sha256sum $out/envoy-linux-amd64 | cut -f1 -d' ')\"" $out/envoy-linux-amd64.lock | sponge $out/envoy-linux-amd64.lock
jq ".digest = \"sha256:$(sha256sum $out/envoy-linux-arm64 | cut -f1 -d' ')\"" $out/envoy-linux-arm64.lock | sponge $out/envoy-linux-arm64.lock
'';
nativeBuildInputs = [ jq ];
ui = buildNpmPackage {
pname = "pomerium-ui";
@@ -151,8 +95,32 @@ buildGoModule (finalAttrs: {
];
preBuild = ''
# Insert embedded envoy.
cp -r ${finalAttrs.envoyBinaries}/* pkg/envoy/files
# Verify pomerium-envoy.nix matches the envoy-custom revision pinned in go.mod.
goModEnvoyRev=$(sed -n 's|.*github.com/pomerium/envoy-custom .*-\([0-9a-f]\{12\}\)$|\1|p' go.mod)
if [[ -z "$goModEnvoyRev" || "${pomerium-envoy.src.rev}" != "$goModEnvoyRev"* ]]; then
echo "ERROR: go.mod references pomerium/envoy-custom rev '$goModEnvoyRev', but pomerium-envoy.nix is at '${pomerium-envoy.src.rev}'; run pomerium/updater.sh" >&2
exit 1
fi
# Insert embedded envoy built from source.
envoyFile="envoy-${stdenv.hostPlatform.go.GOOS}-${stdenv.hostPlatform.go.GOARCH}"
cp "${lib.getExe pomerium-envoy}" "pkg/envoy/files/$envoyFile"
jq -n \
--arg filename "$envoyFile" \
--argjson size "$(stat -c %s "pkg/envoy/files/$envoyFile")" \
--arg digest "sha256:$(sha256sum "pkg/envoy/files/$envoyFile" | cut -f1 -d' ')" \
--arg version "${pomerium-envoy.version}" \
--arg rev "${pomerium-envoy.src.rev}" \
'{
filename: $filename,
size: $size,
digest: $digest,
version: $version,
labels: {
BUILD_SCM_REMOTE: "https://github.com/pomerium/envoy-custom.git",
BUILD_SCM_REVISION: $rev
}
}' > "pkg/envoy/files/$envoyFile.lock"
# put the built UI files where they will be picked up as part of binary build
cp -r ${finalAttrs.ui}/* ui/dist
@@ -163,6 +131,7 @@ buildGoModule (finalAttrs: {
'';
passthru = {
envoy = pomerium-envoy;
tests = {
inherit (nixosTests) pomerium;
inherit pomerium-cli;

View File

@@ -0,0 +1,220 @@
#!/usr/bin/env python3
"""Patch an Envoy source tree for offline Bazel builds inside the Nix sandbox.
Works for both standalone Envoy workspaces (run in postPatch on `.`) and
external consumer workspaces such as pomerium/envoy-custom (run via Bazel
`patch_cmds` on the `@envoy` http_archive).
"""
import argparse
import os
import sys
def replace_if_present(root: str, rel: str, old: str, new: str) -> None:
path = os.path.join(root, rel)
if not os.path.exists(path):
return
with open(path, "r") as f:
txt = f.read()
if old in txt:
with open(path, "w") as f:
f.write(txt.replace(old, new))
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("root", nargs="?", default=".", help="Envoy source root")
parser.add_argument("--python", help="Path to Nix python3 interpreter")
parser.add_argument("--bash", help="Path to Nix bash interpreter")
parser.add_argument("--pgv-build", required=True, help="Path to replacement BUILD.bazel for protoc-gen-validate")
parser.add_argument("--use-rust", action="store_true", help="Register Rust toolchains in dependency_imports.bzl")
args = parser.parse_args()
root = args.root
# Drop -Werror and pinned javabase flags.
replace_if_present(root, "bazel/envoy_internal.bzl", '"-Werror",', "")
bazelrc = os.path.join(root, ".bazelrc")
if os.path.exists(bazelrc):
with open(bazelrc, "r") as f:
lines = [l for l in f if "javabase=" not in l]
with open(bazelrc, "w") as f:
f.writelines(lines)
# Fix python shebang in luajit.patch if present.
if args.python:
replace_if_present(
root,
"bazel/foreign_cc/luajit.patch",
"#!/usr/bin/env python3",
f"#!{args.python}",
)
# Build protoc from the vendored protobuf source instead of downloading
# dynamically-linked per-arch prebuilt binaries.
replace_if_present(
root,
"bazel/protobuf.patch",
'":linux-aarch_64": "@com_google_protobuf_protoc_linux_aarch_64//:protoc",',
'":linux-aarch_64": ":compiled_protoc",',
)
replace_if_present(
root,
"bazel/protobuf.patch",
'":linux-x86_64": "@com_google_protobuf_protoc_linux_x86_64//:protoc",',
'":linux-x86_64": ":compiled_protoc",',
)
replace_if_present(
root,
"bazel/protobuf.patch",
'":osx-aarch_64": "@com_google_protobuf_protoc_osx_aarch_64//:protoc",',
'":osx-aarch_64": ":compiled_protoc",',
)
replace_if_present(
root,
"bazel/protobuf.patch",
'":osx-x86_64": "@com_google_protobuf_protoc_osx_x86_64//:protoc",',
'":osx-x86_64": ":compiled_protoc",',
)
# Alias com_envoyproxy_protoc_gen_validate//:protoc-gen-validate to nixpkgs.
api_repos = os.path.join(root, "api/bazel/repositories.bzl")
if os.path.exists(api_repos):
with open(api_repos, "r") as f:
txt = f.read()
marker = 'name = "com_envoyproxy_protoc_gen_validate",'
if marker in txt and "patch_cmds" not in txt[txt.index(marker) : txt.index(marker) + 350]:
txt = txt.replace(
marker,
marker + f'\n patch_cmds = ["cp {args.pgv_build} BUILD.bazel"],',
1,
)
with open(api_repos, "w") as f:
f.write(txt)
# Fix bash shebang in rules_foreign_cc.
if args.bash:
repos_bzl = os.path.join(root, "bazel/repositories.bzl")
if os.path.exists(repos_bzl):
with open(repos_bzl, "r") as f:
txt = f.read()
marker = 'patches = ["@envoy//bazel:rules_foreign_cc.patch"],'
if marker in txt and "linux_commands.bzl" not in txt:
txt = txt.replace(
marker,
marker
+ f' patch_cmds = ["sed -i.bak \'s,#!/usr/bin/env bash,#!{args.bash},\' foreign_cc/private/framework/toolchains/linux_commands.bzl foreign_cc/private/framework/toolchains/macos_commands.bzl && rm -f foreign_cc/private/framework/toolchains/*.bak"],',
1,
)
with open(repos_bzl, "w") as f:
f.write(txt)
# Use nixpkgs yq in Envoy 1.38+ bazel/repo.bzl.
replace_if_present(root, "bazel/repo.bzl", 'default = "@yq"', 'default = "@//bazel/nix:yq"')
# Strip emsdk and binary python_register_toolchains from repositories_extra.bzl.
replace_if_present(root, "bazel/repositories.bzl", '"@envoy//bazel:emsdk.patch"', "")
repos_extra = os.path.join(root, "bazel/repositories_extra.bzl")
if os.path.exists(repos_extra):
with open(repos_extra, "r") as f:
txt = f.read()
txt = txt.replace('load("@emsdk//:deps.bzl", emsdk_deps = "deps")\n', "")
txt = txt.replace(" emsdk_deps()\n", "")
txt = txt.replace('"py_repositories", "python_register_toolchains"', '"py_repositories"')
idx = txt.find(" python_register_toolchains(")
if idx != -1:
end = txt.find(")\n", idx)
if end != -1:
txt = txt[:idx] + txt[end + 2 :]
with open(repos_extra, "w") as f:
f.write(txt)
# Trim python_dependencies.bzl (keep system_python if Envoy's protobuf uses it).
py_deps = os.path.join(root, "bazel/python_dependencies.bzl")
orig_py_deps = open(py_deps).read() if os.path.exists(py_deps) else ""
with open(py_deps, "w") as f:
if "//bazel:system_python.bzl" in orig_py_deps:
f.write(
'load("@com_google_protobuf//bazel:system_python.bzl", "system_python")\n\n'
"def envoy_python_dependencies():\n"
" system_python(\n"
' name = "system_python",\n'
' minimum_python_version = "3.7",\n'
" )\n"
)
else:
f.write("def envoy_python_dependencies():\n pass\n")
# Stub out dependency_imports_extra.bzl (dynamic_modules Rust SDK crate_universe).
di_extra = os.path.join(root, "bazel/dependency_imports_extra.bzl")
if os.path.exists(di_extra):
with open(di_extra, "w") as f:
f.write("def envoy_dependency_imports_extra():\n pass\n")
# Trim dependency_imports.bzl while preserving version-specific parser_deps load
# (@com_google_cel_cpp in Envoy <=1.36 vs @cel-cpp in Envoy >=1.38).
di_path = os.path.join(root, "bazel/dependency_imports.bzl")
orig_di = open(di_path).read() if os.path.exists(di_path) else ""
cel_load = next(
(l for l in orig_di.splitlines() if "parser_deps" in l and l.startswith("load(")),
'load("@com_google_cel_cpp//bazel:deps.bzl", "parser_deps")',
)
rust_loads = ""
rust_calls = " rules_rust_dependencies()\n"
if args.use_rust:
rust_loads = (
'load("@rules_rust//rust:defs.bzl", "rust_common")\n'
'load("@rules_rust//rust:repositories.bzl", "rules_rust_dependencies", "rust_register_toolchains", "rust_repository_set")\n'
)
rust_calls = (
" rust_repository_set(\n"
' name = "rust_linux_s390x",\n'
' exec_triple = "s390x-unknown-linux-gnu",\n'
' extra_target_triples = ["wasm32-unknown-unknown", "wasm32-wasi"],\n'
" versions = [rust_common.default_version],\n"
" )\n"
" rules_rust_dependencies()\n"
" rust_register_toolchains(\n"
' extra_target_triples = ["wasm32-unknown-unknown", "wasm32-wasi"],\n'
" )\n"
)
else:
rust_loads = 'load("@rules_rust//rust:repositories.bzl", "rules_rust_dependencies")\n'
with open(di_path, "w") as f:
f.write(
'load("@build_bazel_rules_apple//apple:repositories.bzl", "apple_rules_dependencies")\n'
f"{cel_load}\n"
'load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies")\n'
'load("@rules_cc//cc:extensions.bzl", "compatibility_proxy_repo")\n'
'load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies")\n'
'load("@rules_fuzzing//fuzzing:repositories.bzl", "rules_fuzzing_dependencies")\n'
'load("@rules_pkg//:deps.bzl", "rules_pkg_dependencies")\n'
'load("@rules_proto_grpc//:repositories.bzl", "rules_proto_grpc_toolchains")\n'
f"{rust_loads}\n"
"def envoy_dependency_imports(**kwargs):\n"
" compatibility_proxy_repo()\n"
" rules_foreign_cc_dependencies(\n"
" register_default_tools = False,\n"
" register_built_tools = False,\n"
" register_preinstalled_tools = True,\n"
" )\n"
" go_rules_dependencies()\n"
" rules_pkg_dependencies()\n"
f"{rust_calls}"
" rules_fuzzing_dependencies(\n"
" oss_fuzz = True,\n"
" honggfuzz = False,\n"
" )\n"
" apple_rules_dependencies()\n"
" parser_deps()\n"
" rules_proto_grpc_toolchains()\n"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,289 @@
{
lib,
bazel_7,
cacert,
cmake,
envoy,
fetchFromGitHub,
gn,
jdk21_headless,
jq,
libxcrypt,
linuxHeaders,
llvmPackages,
lndir,
ninja,
protoc-gen-validate,
python312,
stdenvAdapters,
writeShellScript,
yq-go,
}:
let
stdenv =
if llvmPackages.libcxxStdenv.hostPlatform.isLinux then
stdenvAdapters.useMoldLinker llvmPackages.libcxxStdenv
else
llvmPackages.libcxxStdenv;
version = "1.37.0-rc3-unstable-2026-10-01";
bazelCcCompiler =
if stdenv.buildPlatform.isDarwin then
if stdenv.buildPlatform.isAarch64 then "cc-compiler-darwin_arm64" else "cc-compiler-darwin_x86_64"
else if stdenv.buildPlatform.isAarch64 then
"cc-compiler-aarch64"
else
"cc-compiler-k8";
src = fetchFromGitHub {
owner = "pomerium";
repo = "envoy-custom";
rev = "8b998d0f6ff30a8243296168125a783c35772141";
hash = "sha256-xLekdqMJvveEuSil+WxFI91GAVE+NST+lFShf/ysm4U=";
};
patchEnvoyTree = writeShellScript "patch-envoy-tree" ''
exec ${python312.interpreter} ${./patch-envoy-tree.py} \
--python "${python312}/bin/python" \
--bash "${stdenv.shell}" \
--pgv-build "${./envoy-pgv.BUILD.bazel}" \
"$@"
'';
extraToolchains = [
"//bazel/nix:local_sh"
"//bazel/nix:jq_nix"
"@rules_foreign_cc//toolchains:preinstalled_cmake_toolchain"
"@rules_foreign_cc//toolchains:preinstalled_ninja_toolchain"
"@rules_foreign_cc//toolchains:preinstalled_make_toolchain"
"@rules_foreign_cc//toolchains:preinstalled_autoconf_toolchain"
"@rules_foreign_cc//toolchains:preinstalled_automake_toolchain"
"@rules_foreign_cc//toolchains:preinstalled_m4_toolchain"
"@rules_foreign_cc//toolchains:preinstalled_pkgconfig_toolchain"
"@local_config_cc_toolchains//:all"
];
commonCommandArgs = [
"--repository_disable_download"
"--repo_env=BAZEL_HTTP_RULES_URLS_AS_DEFAULT_CANONICAL_ID=0"
"--curses=no"
"-c"
"opt"
"--spawn_strategy=standalone"
"--noincompatible_strict_action_env"
"--repo_env=CC=${stdenv.cc}/bin/clang"
"--action_env=CMAKE_POLICY_VERSION_MINIMUM=3.5"
"--cxxopt=-Wno-error"
"--cxxopt=-include"
"--cxxopt=cstdint"
"--per_file_copt=external/com_github_google_tcmalloc/.*@-Wno-changes-meaning"
"--verbose_failures"
"--define=force_libcpp=enabled"
"--@envoy//bazel:libc++=true"
"--incompatible_enable_cc_toolchain_resolution=true"
"--extra_toolchains=${lib.concatStringsSep "," extraToolchains}"
"--java_runtime_version=local_jdk"
"--tool_java_runtime_version=local_jdk"
]
++ lib.optionals stdenv.hostPlatform.isLinux [
"--linkopt=-Wl,-z,noexecstack"
"--linkopt=-Wl,--build-id=sha1"
"--action_env=BAZEL_LINKLIBS=-lc++:-lc++abi"
"--action_env=BAZEL_LINKOPTS=-lm:-pthread"
]
++ lib.optionals stdenv.hostPlatform.isDarwin [
"--action_env=PATH"
"--host_action_env=PATH"
"--action_env=BAZEL_LINKLIBS=-lc++"
"--action_env=BAZEL_LINKOPTS=-lm"
"--action_env=SDKROOT"
"--host_action_env=SDKROOT"
"--action_env=DEVELOPER_DIR"
"--host_action_env=DEVELOPER_DIR"
"--action_env=NIX_CFLAGS_COMPILE"
"--host_action_env=NIX_CFLAGS_COMPILE"
"--action_env=NIX_CFLAGS_COMPILE_${stdenv.cc.suffixSalt}"
"--host_action_env=NIX_CFLAGS_COMPILE_${stdenv.cc.suffixSalt}"
"--action_env=NIX_CXXSTDLIB_COMPILE_${stdenv.cc.suffixSalt}"
"--host_action_env=NIX_CXXSTDLIB_COMPILE_${stdenv.cc.suffixSalt}"
"--action_env=NIX_LDFLAGS"
"--host_action_env=NIX_LDFLAGS"
"--action_env=NIX_LDFLAGS_${stdenv.cc.suffixSalt}"
"--host_action_env=NIX_LDFLAGS_${stdenv.cc.suffixSalt}"
"--macos_minimum_os=14.0"
"--host_macos_minimum_os=14.0"
"--host_copt=-mmacosx-version-min=14.0"
"--features=-layering_check"
"--host_features=-layering_check"
]
++ lib.optionals stdenv.hostPlatform.isAarch64 [
"--define=tcmalloc=disabled"
];
nativeBuildInputs = [
cmake
gn
jdk21_headless
ninja
python312
];
discoverDeps = writeShellScript "discover-deps-pomerium-envoy" ''
set -euo pipefail
export PATH="${
lib.makeBinPath (
[
bazel_7
stdenv.cc
]
++ nativeBuildInputs
)
}:$PATH"
export SSL_CERT_FILE="${cacert}/etc/ssl/certs/ca-bundle.crt"
export JAVA_HOME="${jdk21_headless.home}"
export CC="${stdenv.cc}/bin/cc"
export CXX="${stdenv.cc}/bin/c++"
exec ${python312.interpreter} ${envoy.discoverDepsScript} \
--bazel-target //:envoy \
${
lib.escapeShellArgs (
map (f: "--bazel-flag=${f}") (
lib.filter (f: f != "--repository_disable_download") commonCommandArgs
)
++ [
"--variant-flag="
"--variant-flag=--platforms=//bazel/nix:darwin_arm64 --extra_toolchains=//bazel/nix:darwin_arm64_cc_toolchain"
]
)
} \
"$@"
'';
in
stdenv.mkDerivation (finalAttrs: {
pname = "pomerium-envoy";
inherit version src;
strictDeps = true;
__structuredAttrs = true;
patches = [
./0001-envoy-use-system-toolchains.patch
];
bazelRepoCache = envoy.mkRepoCache {
name = "pomerium-envoy-${version}-repo-cache";
depsFile = ./envoy-deps.json;
};
inherit nativeBuildInputs;
buildInputs = [
libxcrypt
]
++ lib.optional stdenv.hostPlatform.isLinux linuxHeaders;
dontUseCmakeConfigure = true;
dontUseGnConfigure = true;
dontUseNinjaInstall = true;
requiredSystemFeatures = [ "big-parallel" ];
env = {
JAVA_HOME = jdk21_headless.home;
};
postPatch = ''
rm -f .bazelversion
echo "${src.rev}" > SOURCE_VERSION
mkdir -p bazel/nix
substitute ${./envoy-bazel-nix.BUILD.bazel} bazel/nix/BUILD.bazel \
--subst-var-by bash "${stdenv.shell}" \
--subst-var-by cc_compiler "${bazelCcCompiler}"
ln -sf "${protoc-gen-validate}/bin/protoc-gen-validate" bazel/nix/protoc-gen-validate
ln -sf "${yq-go}/bin/yq" bazel/nix/yq
ln -sf "${jq}/bin/jq" bazel/nix/jq
substituteInPlace WORKSPACE \
--subst-var-by patch_envoy_tree "${patchEnvoyTree}" \
--replace-fail '"//patches/luajit:0001-libunwind-fde-offset.patch",' ""
'';
preBuildPhases = [ "preBuildPhase" ];
preBuildPhase =
lib.optionalString (finalAttrs.bazelRepoCache != null) ''
# repo_cache needs to be writable even in air-gapped builds
mkdir repo_cache
${lndir}/bin/lndir -silent ${finalAttrs.bazelRepoCache}/repo_cache repo_cache
''
+ ''
true
'';
buildPhase = ''
runHook preBuild
export HOME=$(mktemp -d)
export BAZEL_USE_CPP_ONLY_TOOLCHAIN=1
export USER=homeless-shelter
${lib.optionalString stdenv.hostPlatform.isDarwin ''
export NIX_CFLAGS_COMPILE_${stdenv.cc.suffixSalt}="''${NIX_CFLAGS_COMPILE:-}"
export NIX_CXXSTDLIB_COMPILE_${stdenv.cc.suffixSalt}="''${NIX_CXXSTDLIB_COMPILE:-}"
export NIX_LDFLAGS_${stdenv.cc.suffixSalt}="''${NIX_LDFLAGS:-}"
''}
echo repo_cache >> .bazelignore
{
echo "build --jobs=$NIX_BUILD_CORES"
${lib.optionalString stdenv.hostPlatform.isLinux ''
for flag in $NIX_CFLAGS_COMPILE $NIX_CXXSTDLIB_COMPILE; do
echo "build --copt=$flag"
echo "build --host_copt=$flag"
done
for flag in $NIX_LDFLAGS; do
echo "build --linkopt=-Wl,$flag"
echo "build --host_linkopt=-Wl,$flag"
done
''}
} >> user.bazelrc
${bazel_7}/bin/bazel \
--server_javabase=${jdk21_headless.home} \
--batch \
build \
--repository_cache=repo_cache \
${lib.escapeShellArgs commonCommandArgs} \
//:envoy
runHook postBuild
'';
installPhase = ''
runHook preInstall
install -Dm0755 bazel-bin/envoy "$out/bin/envoy"
runHook postInstall
'';
passthru = {
inherit discoverDeps patchEnvoyTree;
updateScript = writeShellScript "update-pomerium-envoy" ''
set -euo pipefail
export SSL_CERT_FILE="${cacert}/etc/ssl/certs/ca-bundle.crt"
exec ${python312.interpreter} ${./update-envoy.py} \
--discover-deps ${discoverDeps} \
"$@"
'';
};
meta = {
homepage = "https://github.com/pomerium/envoy-custom";
description = "Custom Envoy build with Pomerium extensions";
mainProgram = "envoy";
license = lib.licenses.asl20;
maintainers = with lib.maintainers; [ lukegb ];
platforms = [
"x86_64-linux"
"aarch64-linux"
];
};
})

View File

@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""Update script for pkgs/by-name/po/pomerium-envoy.
Determines the target github.com/pomerium/envoy-custom revision from the
currently packaged `pomerium` derivation's `go.mod`, updates version/rev/hash
in package.nix, and invokes pomerium-envoy.discoverDeps to regenerate deps.json.
"""
import argparse
import json
import os
import re
import subprocess
import urllib.request
PKG_DIR = "pkgs/by-name/po/pomerium"
PKG_NIX = os.path.join(PKG_DIR, "pomerium-envoy.nix")
DEPS_JSON = os.path.join(PKG_DIR, "envoy-deps.json")
def github_get_json(url: str) -> dict:
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "nixpkgs-pomerium-envoy-updater",
}
token = os.environ.get("GITHUB_TOKEN")
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req) as resp:
return json.load(resp)
def prefetch_sri(url: str) -> str:
base32 = subprocess.check_output(
["nix-prefetch-url", "--unpack", "--type", "sha256", url], text=True
).strip().splitlines()[-1]
return subprocess.check_output(
["nix", "hash", "to-sri", "--type", "sha256", base32], text=True
).strip()
def resolve_from_pomerium_gomod() -> tuple[str, str]:
"""Return (version, rev) from pomerium.src/go.mod's envoy-custom requirement."""
pomerium_src = subprocess.check_output(
["nix-build", "--no-out-link", "-A", "pomerium.src"], text=True
).strip()
gomod = open(os.path.join(pomerium_src, "go.mod")).read()
m = re.search(r"github\.com/pomerium/envoy-custom\s+(v[^\s]+)", gomod)
if not m:
raise RuntimeError("Could not find github.com/pomerium/envoy-custom in pomerium go.mod")
mod_ver = m.group(1)
# Go pseudo-version: e.g. v1.37.0-rc3.0.20261001211751-8b998d0f6ff3
# or v0.0.0-20261001211751-8b998d0f6ff3
pseudo = re.match(
r"^v([0-9]+\.[0-9]+\.[0-9]+(?:-[^.\s]+)?)\.(?:0\.)?(\d{4})(\d{2})(\d{2})\d{6}-([0-9a-f]{12})$",
mod_ver,
) or re.match(
r"^v([0-9]+\.[0-9]+\.[0-9]+)-(\d{4})(\d{2})(\d{2})\d{6}-([0-9a-f]{12})$",
mod_ver,
)
if pseudo:
base, yyyy, mm, dd, short_sha = pseudo.groups()
commit = github_get_json(
f"https://api.github.com/repos/pomerium/envoy-custom/commits/{short_sha}"
)
return f"{base}-unstable-{yyyy}-{mm}-{dd}", commit["sha"]
# Regular release tag: e.g. v1.38.9
ref = github_get_json(
f"https://api.github.com/repos/pomerium/envoy-custom/git/ref/tags/{mod_ver}"
)
obj = ref["object"]
rev = github_get_json(obj["url"])["object"]["sha"] if obj["type"] == "tag" else obj["sha"]
return mod_ver.lstrip("v"), rev
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--discover-deps", required=True, help="Path to pomerium-envoy.discoverDeps script"
)
parser.add_argument("--skip-version-bump", action="store_true")
parser.add_argument("--force", action="store_true")
args = parser.parse_args()
if not args.skip_version_bump:
new_version, new_rev = resolve_from_pomerium_gomod()
txt = open(PKG_NIX).read()
old_rev_m = re.search(r'rev\s*=\s*"([0-9a-f]{40})";', txt)
if old_rev_m and old_rev_m.group(1) == new_rev and not args.force:
print(f"pomerium-envoy is already at {new_version} ({new_rev}).")
return 0
print(f"Updating pomerium-envoy to {new_version} ({new_rev})")
new_hash = prefetch_sri(
f"https://github.com/pomerium/envoy-custom/archive/{new_rev}.tar.gz"
)
txt = re.sub(r'(version\s*=\s*")[^"]+(";)', rf"\g<1>{new_version}\g<2>", txt, count=1)
txt = re.sub(r'(rev\s*=\s*")[0-9a-f]{40}(";)', rf"\g<1>{new_rev}\g<2>", txt, count=1)
txt = re.sub(r'(hash\s*=\s*")sha256-[^"]+(";)', rf"\g<1>{new_hash}\g<2>", txt, count=1)
with open(PKG_NIX, "w") as f:
f.write(txt)
subprocess.check_call(
[args.discover_deps, "--attr", "pomerium.envoy", "--deps-file", DEPS_JSON]
)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -17,3 +17,4 @@ fi
popd
nix-update pomerium --version $version
nix-update pomerium --version=skip --subpackage ui
"$(nix-build --no-out-link -A pomerium.envoy.updateScript)"