Datasets:
Tasks:
Text Generation
Formats:
parquet
Sub-tasks:
language-modeling
Languages:
English
Size:
< 1K
License:
Update dataset (part 3)
Browse files- harbor/tasks/pomerium_route_order_contract/environment/Dockerfile +24 -0
- harbor/tasks/pomerium_route_order_contract/environment/capture.py +28 -0
- harbor/tasks/pomerium_route_order_contract/environment/capture_submission.py +157 -0
- harbor/tasks/pomerium_route_order_contract/environment/docker-compose.yaml +11 -0
- harbor/tasks/pomerium_route_order_contract/environment/sanitize.py +25 -0
- harbor/tasks/pomerium_route_order_contract/instruction.md +7 -0
- harbor/tasks/pomerium_route_order_contract/solution/reference.patch +537 -0
- harbor/tasks/pomerium_route_order_contract/solution/solve.sh +543 -0
- harbor/tasks/pomerium_route_order_contract/task.toml +26 -0
- harbor/tasks/pomerium_route_order_contract/tests/Dockerfile +9 -0
- harbor/tasks/pomerium_route_order_contract/tests/config.json +112 -0
- harbor/tasks/pomerium_route_order_contract/tests/docker-compose.yaml +6 -0
- harbor/tasks/pomerium_route_order_contract/tests/evidence.py +123 -0
- harbor/tasks/pomerium_route_order_contract/tests/test.sh +4 -0
- harbor/tasks/pomerium_route_order_contract/tests/verify.py +235 -0
- harbor/tasks/shared_handle_abandoned_operations/environment/Dockerfile +20 -0
- harbor/tasks/shared_handle_abandoned_operations/environment/capture.py +28 -0
- harbor/tasks/shared_handle_abandoned_operations/environment/capture_submission.py +157 -0
- harbor/tasks/shared_handle_abandoned_operations/environment/docker-compose.yaml +11 -0
- harbor/tasks/shared_handle_abandoned_operations/environment/sanitize.py +25 -0
- harbor/tasks/shared_handle_abandoned_operations/instruction.md +9 -0
- harbor/tasks/shared_handle_abandoned_operations/solution/reference.patch +180 -0
- harbor/tasks/shared_handle_abandoned_operations/solution/solve.sh +186 -0
- harbor/tasks/shared_handle_abandoned_operations/task.toml +26 -0
- harbor/tasks/shared_handle_abandoned_operations/tests/Dockerfile +12 -0
- harbor/tasks/shared_handle_abandoned_operations/tests/config.json +234 -0
- harbor/tasks/shared_handle_abandoned_operations/tests/docker-compose.yaml +6 -0
- harbor/tasks/shared_handle_abandoned_operations/tests/evidence.py +123 -0
- harbor/tasks/shared_handle_abandoned_operations/tests/test.sh +4 -0
- harbor/tasks/shared_handle_abandoned_operations/tests/verify.py +235 -0
harbor/tasks/pomerium_route_order_contract/environment/Dockerfile
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-pomerium:source-v10 AS sanitized
|
| 2 |
+
USER root
|
| 3 |
+
COPY sanitize.py capture.py capture_submission.py /opt/task-tools/
|
| 4 |
+
RUN HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 /opt/hudvenv/bin/python /opt/task-tools/sanitize.py
|
| 5 |
+
FROM scratch
|
| 6 |
+
COPY --from=sanitized / /
|
| 7 |
+
ENV PATH="/usr/local/go/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
|
| 8 |
+
ENV LANG="C.UTF-8"
|
| 9 |
+
ENV GOTOOLCHAIN="local"
|
| 10 |
+
ENV CGO_ENABLED="1"
|
| 11 |
+
ENV GOWORK="off"
|
| 12 |
+
ENV GOFLAGS="-mod=mod"
|
| 13 |
+
ENV GOPATH="/go"
|
| 14 |
+
ENV GOMODCACHE="/go/pkg/mod"
|
| 15 |
+
ENV GOMEMLIMIT="1GiB"
|
| 16 |
+
ENV GOPROXY="off"
|
| 17 |
+
ENV GOMAXPROCS="2"
|
| 18 |
+
ENV HOME="/tmp/agent-home"
|
| 19 |
+
ENV GOCACHE="/tmp/agent-home/.cache/go-build"
|
| 20 |
+
ENV HUD_TELEMETRY_ENABLED="false"
|
| 21 |
+
ENV HUD_CLI_ANALYTICS_ENABLED="0"
|
| 22 |
+
WORKDIR /workspace/repo
|
| 23 |
+
USER 1000:1000
|
| 24 |
+
CMD ["sleep", "infinity"]
|
harbor/tasks/pomerium_route_order_contract/environment/capture.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capture a patch against protected baseline history inside the agent sandbox."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
sys.path.insert(0, "/opt/task-tools")
|
| 11 |
+
from capture_submission import capture_submission # noqa: E402
|
| 12 |
+
|
| 13 |
+
with tempfile.TemporaryDirectory(prefix="capture-") as directory:
|
| 14 |
+
git_dir = Path(directory) / "git"
|
| 15 |
+
shutil.copytree("/opt/task-tools/baseline.git", git_dir)
|
| 16 |
+
os.environ.update(
|
| 17 |
+
GIT_DIR=str(git_dir),
|
| 18 |
+
GIT_WORK_TREE="/workspace/repo",
|
| 19 |
+
GIT_CONFIG_NOSYSTEM="1",
|
| 20 |
+
GIT_CONFIG_GLOBAL="/dev/null",
|
| 21 |
+
)
|
| 22 |
+
print(
|
| 23 |
+
json.dumps(
|
| 24 |
+
capture_submission(
|
| 25 |
+
Path("/workspace/repo"), Path("/workspace/submissions/submitted.patch")
|
| 26 |
+
)
|
| 27 |
+
)
|
| 28 |
+
)
|
harbor/tasks/pomerium_route_order_contract/environment/capture_submission.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capture tracked and new SWE files without changing the agent's Git index."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import shlex
|
| 8 |
+
import subprocess
|
| 9 |
+
import tempfile
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
MAX_SUBMISSION_BYTES = 32 * 1024 * 1024
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def capture_submission(
|
| 16 |
+
repository: Path, output: Path, *, max_bytes: int = MAX_SUBMISSION_BYTES
|
| 17 |
+
) -> dict[str, object]:
|
| 18 |
+
"""Write a bounded binary patch including nonignored new files.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
repository : Path
|
| 23 |
+
Git checkout root. HEAD must remain the task's initial commit.
|
| 24 |
+
output : Path
|
| 25 |
+
Submission path outside the checkout. Replaces any prior submission.
|
| 26 |
+
max_bytes : int, default: 33554432
|
| 27 |
+
Maximum emitted patch size. Oversized submissions fail without a patch.
|
| 28 |
+
|
| 29 |
+
Returns
|
| 30 |
+
-------
|
| 31 |
+
dict
|
| 32 |
+
Patch size, SHA-256, base commit and capture format for trial evidence.
|
| 33 |
+
|
| 34 |
+
Raises
|
| 35 |
+
------
|
| 36 |
+
ValueError
|
| 37 |
+
If paths or the limit are invalid, or the patch exceeds the limit.
|
| 38 |
+
OSError, subprocess.CalledProcessError, RuntimeError
|
| 39 |
+
If capture fails. No partial patch is published.
|
| 40 |
+
|
| 41 |
+
Notes
|
| 42 |
+
-----
|
| 43 |
+
Uses a temporary index to combine staged, unstaged and untracked changes.
|
| 44 |
+
Ignored untracked files are excluded. This is a capture bound, not a total
|
| 45 |
+
sandbox disk quota or a security boundary against a malicious Git runtime.
|
| 46 |
+
"""
|
| 47 |
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
|
| 48 |
+
raise ValueError("max_bytes must be a positive integer")
|
| 49 |
+
repository = repository.resolve(strict=True)
|
| 50 |
+
if output.is_symlink():
|
| 51 |
+
raise ValueError("Submission output must not be a symlink")
|
| 52 |
+
output = output.resolve()
|
| 53 |
+
if output.is_relative_to(repository):
|
| 54 |
+
raise ValueError("Submission output must be outside the repository")
|
| 55 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
output.unlink(missing_ok=True)
|
| 57 |
+
root = subprocess.check_output(
|
| 58 |
+
["git", "rev-parse", "--show-toplevel"], cwd=repository, text=True
|
| 59 |
+
).strip()
|
| 60 |
+
if Path(root).resolve() != repository:
|
| 61 |
+
raise ValueError("repository must be the Git checkout root")
|
| 62 |
+
base = subprocess.check_output(
|
| 63 |
+
["git", "rev-parse", "--verify", "HEAD^{commit}"], cwd=repository, text=True
|
| 64 |
+
).strip()
|
| 65 |
+
with tempfile.TemporaryDirectory(prefix="submission-", dir=output.parent) as directory:
|
| 66 |
+
temporary = Path(directory)
|
| 67 |
+
env = {**os.environ, "GIT_INDEX_FILE": str(temporary / "index")}
|
| 68 |
+
for arguments in (["read-tree", base], ["add", "--all", "--", "."]):
|
| 69 |
+
subprocess.run(["git", *arguments], cwd=repository, env=env, check=True)
|
| 70 |
+
patch = temporary / "patch"
|
| 71 |
+
size = 0
|
| 72 |
+
digest = hashlib.sha256()
|
| 73 |
+
with (
|
| 74 |
+
patch.open("wb") as stream,
|
| 75 |
+
tempfile.TemporaryFile() as errors,
|
| 76 |
+
subprocess.Popen(
|
| 77 |
+
[
|
| 78 |
+
"git",
|
| 79 |
+
"diff",
|
| 80 |
+
"--cached",
|
| 81 |
+
"--binary",
|
| 82 |
+
"--full-index",
|
| 83 |
+
"--no-renames",
|
| 84 |
+
"--no-ext-diff",
|
| 85 |
+
"--no-textconv",
|
| 86 |
+
"--no-color",
|
| 87 |
+
"--src-prefix=a/",
|
| 88 |
+
"--dst-prefix=b/",
|
| 89 |
+
base,
|
| 90 |
+
],
|
| 91 |
+
cwd=repository,
|
| 92 |
+
env=env,
|
| 93 |
+
stdout=subprocess.PIPE,
|
| 94 |
+
stderr=errors,
|
| 95 |
+
) as process,
|
| 96 |
+
):
|
| 97 |
+
assert process.stdout is not None
|
| 98 |
+
try:
|
| 99 |
+
while chunk := process.stdout.read(65536):
|
| 100 |
+
size += len(chunk)
|
| 101 |
+
if size > max_bytes:
|
| 102 |
+
raise ValueError(f"Submission exceeds {max_bytes} bytes")
|
| 103 |
+
stream.write(chunk)
|
| 104 |
+
digest.update(chunk)
|
| 105 |
+
except BaseException:
|
| 106 |
+
process.kill()
|
| 107 |
+
process.wait()
|
| 108 |
+
raise
|
| 109 |
+
if process.wait():
|
| 110 |
+
errors.seek(0)
|
| 111 |
+
raise RuntimeError(
|
| 112 |
+
"Git patch capture failed: " + errors.read(4096).decode(errors="replace")
|
| 113 |
+
)
|
| 114 |
+
patch.replace(output)
|
| 115 |
+
return {
|
| 116 |
+
"bytes": size,
|
| 117 |
+
"sha256": digest.hexdigest(),
|
| 118 |
+
"base_commit": base,
|
| 119 |
+
"format": "git-binary-v1",
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def submission_command(*, max_bytes: int = MAX_SUBMISSION_BYTES) -> str:
|
| 124 |
+
"""Build the trusted command recorded before Harbor collects artifacts.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
----------
|
| 128 |
+
max_bytes : int, default: 33554432
|
| 129 |
+
Maximum emitted patch bytes.
|
| 130 |
+
|
| 131 |
+
Returns
|
| 132 |
+
-------
|
| 133 |
+
str
|
| 134 |
+
Shell command carrying this exact helper into the solver runtime.
|
| 135 |
+
|
| 136 |
+
Raises
|
| 137 |
+
------
|
| 138 |
+
ValueError
|
| 139 |
+
If the size limit is invalid.
|
| 140 |
+
"""
|
| 141 |
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
|
| 142 |
+
raise ValueError("max_bytes must be a positive integer")
|
| 143 |
+
return "python -c " + shlex.quote(Path(__file__).read_text()) + f" --max-bytes {max_bytes}"
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def main() -> None:
|
| 147 |
+
"""Capture the submission and print its identity as trial evidence."""
|
| 148 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 149 |
+
parser.add_argument("--repository", type=Path, default=Path("/testbed"))
|
| 150 |
+
parser.add_argument("--output", type=Path, default=Path("/workspace/submitted.patch"))
|
| 151 |
+
parser.add_argument("--max-bytes", type=int, default=MAX_SUBMISSION_BYTES)
|
| 152 |
+
args = parser.parse_args()
|
| 153 |
+
print(json.dumps(capture_submission(args.repository, args.output, max_bytes=args.max_bytes)))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
main()
|
harbor/tasks/pomerium_route_order_contract/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
pids_limit: 512
|
| 4 |
+
security_opt:
|
| 5 |
+
- no-new-privileges:true
|
| 6 |
+
volumes:
|
| 7 |
+
- type: tmpfs
|
| 8 |
+
target: /logs/verifier
|
| 9 |
+
tmpfs:
|
| 10 |
+
mode: 448
|
| 11 |
+
size: 1048576
|
harbor/tasks/pomerium_route_order_contract/environment/sanitize.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Remove private task assets and history when building the agent-only image."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
sys.path.insert(0, "/app")
|
| 10 |
+
from env import _setup # noqa: E402
|
| 11 |
+
|
| 12 |
+
asyncio.run(_setup())
|
| 13 |
+
# The new history contains only the public baseline. Preserve a root-owned
|
| 14 |
+
# copy so capture can ignore agent-controlled refs, hooks and Git configuration.
|
| 15 |
+
shutil.copytree("/workspace/repo/.git", "/opt/task-tools/baseline.git")
|
| 16 |
+
for path in Path("/opt/task-tools/baseline.git").rglob("*"):
|
| 17 |
+
os.chown(path, 0, 0)
|
| 18 |
+
path.chmod(0o755 if path.is_dir() else 0o644)
|
| 19 |
+
for name in ("/hud", "/app", "/root/.cache", "/root/.hud"):
|
| 20 |
+
if Path(name).exists():
|
| 21 |
+
shutil.rmtree(name)
|
| 22 |
+
# Capture runs on the base interpreter under one name, whatever the image calls it.
|
| 23 |
+
os.symlink(os.path.realpath(sys.executable), "/opt/task-tools/python")
|
| 24 |
+
Path("/workspace/submissions").mkdir()
|
| 25 |
+
os.chown("/workspace/submissions", 1000, 1000)
|
harbor/tasks/pomerium_route_order_contract/instruction.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Please make your changes directly in /workspace/repo.
|
| 2 |
+
|
| 3 |
+
# Ticket
|
| 4 |
+
|
| 5 |
+
Requests land on wrong routes and configuration order takes the blame: priority settles overlapping regex routes; a from address without a port serves every port, one naming a port only that port, spelled or implied; host names carry no case, on the address and in the request alike; wildcard routes still serve hosts that own routes, which win where they match; in-process lookups match the proxy. Keep the suite green without editing tests.
|
| 6 |
+
|
| 7 |
+
Finish with a final response when your changes are ready.
|
harbor/tasks/pomerium_route_order_contract/solution/reference.patch
ADDED
|
@@ -0,0 +1,537 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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/envoyconfig/route_configurations.go
|
| 4 |
+
+++ b/config/envoyconfig/route_configurations.go
|
| 5 |
+
@@ -85,12 +85,18 @@ func (b *Builder) buildMainRouteConfiguration(
|
| 6 |
+
return nil, err
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
+ explicitPortOnly := explicitPortOnlyHosts(cfg.Options)
|
| 10 |
+
+
|
| 11 |
+
var virtualHosts []*envoy_config_route_v3.VirtualHost
|
| 12 |
+
for _, host := range allHosts {
|
| 13 |
+
vh, err := b.buildVirtualHost(cfg.Options, host, host, mcpHosts[host])
|
| 14 |
+
if err != nil {
|
| 15 |
+
return nil, err
|
| 16 |
+
}
|
| 17 |
+
+ if explicitPortOnly[host] {
|
| 18 |
+
+ // every route of this host names its port: it is not served on any port
|
| 19 |
+
+ vh.Domains = []string{host}
|
| 20 |
+
+ }
|
| 21 |
+
|
| 22 |
+
if cfg.Options.Addr == cfg.Options.GetGRPCAddr() {
|
| 23 |
+
// if this is a gRPC service domain and we're supposed to handle that, add those routes
|
| 24 |
+
@@ -212,11 +218,15 @@ func getAllRouteableHosts(options *config.Options, addr string) ([]string, map[s
|
| 25 |
+
if err != nil {
|
| 26 |
+
return nil, nil, err
|
| 27 |
+
}
|
| 28 |
+
- allHosts.InsertSlice(hosts)
|
| 29 |
+
+ // host names carry no case: two from addresses that spell one host
|
| 30 |
+
+ // differently are one virtual host, not two envoy would reject
|
| 31 |
+
+ for _, host := range hosts {
|
| 32 |
+
+ allHosts.Insert(strings.ToLower(host))
|
| 33 |
+
+ }
|
| 34 |
+
// Merge any MCP hosts
|
| 35 |
+
for host, isMCP := range hostsMCP {
|
| 36 |
+
if isMCP {
|
| 37 |
+
- mcpHosts[host] = true
|
| 38 |
+
+ mcpHosts[strings.ToLower(host)] = true
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
@@ -226,7 +236,9 @@ func getAllRouteableHosts(options *config.Options, addr string) ([]string, map[s
|
| 43 |
+
if err != nil {
|
| 44 |
+
return nil, nil, err
|
| 45 |
+
}
|
| 46 |
+
- allHosts.InsertSlice(hosts)
|
| 47 |
+
+ for _, host := range hosts {
|
| 48 |
+
+ allHosts.Insert(strings.ToLower(host))
|
| 49 |
+
+ }
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
var filtered []string
|
| 53 |
+
@@ -256,6 +268,31 @@ func urlsMatchHost(urls []*url.URL, host string) bool {
|
| 54 |
+
return false
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
+// explicitPortOnlyHosts returns the hosts whose policy from URLs all carry a port.
|
| 58 |
+
+func explicitPortOnlyHosts(options *config.Options) map[string]bool {
|
| 59 |
+
+ withPort, withoutPort := map[string]bool{}, map[string]bool{}
|
| 60 |
+
+ for p := range options.GetAllPolicies() {
|
| 61 |
+
+ if p.IsSSH() {
|
| 62 |
+
+ continue
|
| 63 |
+
+ }
|
| 64 |
+
+ u, err := urlutil.ParseAndValidateURL(p.From)
|
| 65 |
+
+ if err != nil || strings.Contains(u.Host, "*") {
|
| 66 |
+
+ continue
|
| 67 |
+
+ }
|
| 68 |
+
+ if u.Port() != "" {
|
| 69 |
+
+ withPort[strings.ToLower(u.Hostname())] = true
|
| 70 |
+
+ } else {
|
| 71 |
+
+ withoutPort[strings.ToLower(u.Hostname())] = true
|
| 72 |
+
+ }
|
| 73 |
+
+ }
|
| 74 |
+
+ for h := range withoutPort {
|
| 75 |
+
+ delete(withPort, h)
|
| 76 |
+
+ }
|
| 77 |
+
+ return withPort
|
| 78 |
+
+}
|
| 79 |
+
+
|
| 80 |
+
func urlMatchesHost(u *url.URL, host string) bool {
|
| 81 |
+
- return slices.Contains(urlutil.GetDomainsForURL(u, true), host)
|
| 82 |
+
+ return slices.ContainsFunc(urlutil.GetDomainsForURL(u, true), func(domain string) bool {
|
| 83 |
+
+ return strings.EqualFold(domain, host)
|
| 84 |
+
+ })
|
| 85 |
+
}
|
| 86 |
+
diff --git a/config/envoyconfig/route_order_test.go b/config/envoyconfig/route_order_test.go
|
| 87 |
+
new file mode 100644
|
| 88 |
+
index 0000000..85148c2
|
| 89 |
+
--- /dev/null
|
| 90 |
+
+++ b/config/envoyconfig/route_order_test.go
|
| 91 |
+
@@ -0,0 +1,56 @@
|
| 92 |
+
+package envoyconfig
|
| 93 |
+
+
|
| 94 |
+
+import (
|
| 95 |
+
+ "testing"
|
| 96 |
+
+
|
| 97 |
+
+ envoy_config_route_v3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
|
| 98 |
+
+ "github.com/stretchr/testify/assert"
|
| 99 |
+
+ "github.com/stretchr/testify/require"
|
| 100 |
+
+
|
| 101 |
+
+ "github.com/pomerium/pomerium/config"
|
| 102 |
+
+ "github.com/pomerium/pomerium/config/envoyconfig/filemgr"
|
| 103 |
+
+)
|
| 104 |
+
+
|
| 105 |
+
+func TestBuilder_buildMainRouteConfiguration_RouteOrder(t *testing.T) {
|
| 106 |
+
+ t.Parallel()
|
| 107 |
+
+
|
| 108 |
+
+ prio := func(v int64) *int64 { return &v }
|
| 109 |
+
+ opts := config.NewDefaultOptions()
|
| 110 |
+
+ opts.Services = "proxy"
|
| 111 |
+
+ opts.Policies = []config.Policy{
|
| 112 |
+
+ {From: "https://*.example.com", To: mustParseWeightedURLs(t, "https://wild.internal")},
|
| 113 |
+
+ {From: "https://own.example.com", Path: "/own", To: mustParseWeightedURLs(t, "https://own.internal")},
|
| 114 |
+
+ {From: "https://own.example.com", Regex: "^/a/.*$", RegexPriorityOrder: prio(1), To: mustParseWeightedURLs(t, "https://low.internal")},
|
| 115 |
+
+ {From: "https://own.example.com", Regex: "^/a/b/.*$", RegexPriorityOrder: prio(2), To: mustParseWeightedURLs(t, "https://high.internal")},
|
| 116 |
+
+ {From: "https://pinned.example.com:443", To: mustParseWeightedURLs(t, "https://pinned.internal")},
|
| 117 |
+
+ }
|
| 118 |
+
+ b := New("connect", "grpc", "http", "debug", "metrics", filemgr.NewManager(), nil, true)
|
| 119 |
+
+ rc, err := b.buildMainRouteConfiguration(t.Context(), config.New(opts))
|
| 120 |
+
+ require.NoError(t, err)
|
| 121 |
+
+
|
| 122 |
+
+ vhosts := map[string]*envoy_config_route_v3.VirtualHost{}
|
| 123 |
+
+ for _, vh := range rc.GetVirtualHosts() {
|
| 124 |
+
+ vhosts[vh.GetName()] = vh
|
| 125 |
+
+ }
|
| 126 |
+
+ policyRoutes := func(vh *envoy_config_route_v3.VirtualHost) []string {
|
| 127 |
+
+ var names []string
|
| 128 |
+
+ for _, r := range vh.GetRoutes() {
|
| 129 |
+
+ if len(r.GetName()) > len("policy-") && r.GetName()[:len("policy-")] == "policy-" {
|
| 130 |
+
+ names = append(names, r.GetName())
|
| 131 |
+
+ }
|
| 132 |
+
+ }
|
| 133 |
+
+ return names
|
| 134 |
+
+ }
|
| 135 |
+
+
|
| 136 |
+
+ own := vhosts["own.example.com"]
|
| 137 |
+
+ require.NotNil(t, own)
|
| 138 |
+
+ // higher priority first, then the rest of the host's own routes, then the
|
| 139 |
+
+ // wildcard routes (one per wildcard domain)
|
| 140 |
+
+ assert.Equal(t, []string{"policy-3", "policy-2", "policy-1", "policy-0"}, policyRoutes(own))
|
| 141 |
+
+ assert.Equal(t, []string{"own.example.com", "own.example.com:*"}, own.GetDomains())
|
| 142 |
+
+
|
| 143 |
+
+ pinned := vhosts["pinned.example.com"]
|
| 144 |
+
+ require.NotNil(t, pinned)
|
| 145 |
+
+ assert.Equal(t, []string{"pinned.example.com"}, pinned.GetDomains())
|
| 146 |
+
+ assert.NotNil(t, vhosts["pinned.example.com:443"])
|
| 147 |
+
+}
|
| 148 |
+
diff --git a/config/envoyconfig/routes.go b/config/envoyconfig/routes.go
|
| 149 |
+
index f8c1d5a..5e7c3cf 100644
|
| 150 |
+
--- a/config/envoyconfig/routes.go
|
| 151 |
+
+++ b/config/envoyconfig/routes.go
|
| 152 |
+
@@ -3,7 +3,9 @@ package envoyconfig
|
| 153 |
+
import (
|
| 154 |
+
"encoding/json"
|
| 155 |
+
"fmt"
|
| 156 |
+
+ "net"
|
| 157 |
+
"net/url"
|
| 158 |
+
+ "regexp"
|
| 159 |
+
"slices"
|
| 160 |
+
"sort"
|
| 161 |
+
"strings"
|
| 162 |
+
@@ -195,32 +197,100 @@ func (b *Builder) buildRoutesForPoliciesWithHost(
|
| 163 |
+
host string,
|
| 164 |
+
) ([]*envoy_config_route_v3.Route, error) {
|
| 165 |
+
var routes []*envoy_config_route_v3.Route
|
| 166 |
+
- for i, p := range cfg.Options.GetAllPoliciesIndexed() {
|
| 167 |
+
- policy := p
|
| 168 |
+
- fromURL, err := urlutil.ParseAndValidateURL(policy.From)
|
| 169 |
+
- if err != nil {
|
| 170 |
+
- return nil, err
|
| 171 |
+
- }
|
| 172 |
+
+ // the host's own routes come first, then the wildcard routes that match the
|
| 173 |
+
+ // host: envoy never consults the catch-all virtual host for a host that has
|
| 174 |
+
+ // a virtual host of its own
|
| 175 |
+
+ for _, wildcard := range []bool{false, true} {
|
| 176 |
+
+ for i, policy := range cfg.Options.GetAllPoliciesInRouteOrder() {
|
| 177 |
+
+ fromURL, err := urlutil.ParseAndValidateURL(policy.From)
|
| 178 |
+
+ if err != nil {
|
| 179 |
+
+ return nil, err
|
| 180 |
+
+ }
|
| 181 |
+
|
| 182 |
+
- if !urlMatchesHost(fromURL, host) {
|
| 183 |
+
- continue
|
| 184 |
+
- }
|
| 185 |
+
+ if strings.Contains(fromURL.Host, "*") != wildcard {
|
| 186 |
+
+ continue
|
| 187 |
+
+ }
|
| 188 |
+
+ if wildcard && !wildcardURLMatchesHost(cfg.Options, fromURL, host) {
|
| 189 |
+
+ continue
|
| 190 |
+
+ }
|
| 191 |
+
+ // a route whose from address names a port answers only on that port,
|
| 192 |
+
+ // even on a host that other routes serve on every port
|
| 193 |
+
+ var onlyAuthority string
|
| 194 |
+
+ if !wildcard {
|
| 195 |
+
+ switch {
|
| 196 |
+
+ case urlMatchesHost(fromURL, host):
|
| 197 |
+
+ if fromURL.Port() != "" && !config.HasPort(host) {
|
| 198 |
+
+ onlyAuthority = "(?i)^" + regexp.QuoteMeta(fromURL.Hostname()) + "(:" + fromURL.Port() + ")?$"
|
| 199 |
+
+ }
|
| 200 |
+
+ case portlessURLServesHostPort(cfg.Options, fromURL, host):
|
| 201 |
+
+ // a from address without a port serves this port as well
|
| 202 |
+
+ default:
|
| 203 |
+
+ continue
|
| 204 |
+
+ }
|
| 205 |
+
+ }
|
| 206 |
+
|
| 207 |
+
- policyRoutes, err := b.buildRoutesForPolicy(cfg, policy, fmt.Sprintf("policy-%d", i))
|
| 208 |
+
- if err != nil {
|
| 209 |
+
- return nil, err
|
| 210 |
+
- }
|
| 211 |
+
+ policyRoutes, err := b.buildRoutesForPolicy(cfg, policy, fmt.Sprintf("policy-%d", i))
|
| 212 |
+
+ if err != nil {
|
| 213 |
+
+ return nil, err
|
| 214 |
+
+ }
|
| 215 |
+
+ if onlyAuthority != "" {
|
| 216 |
+
+ for _, r := range policyRoutes {
|
| 217 |
+
+ r.Match.Headers = append(r.Match.Headers, &envoy_config_route_v3.HeaderMatcher{
|
| 218 |
+
+ Name: ":authority",
|
| 219 |
+
+ HeaderMatchSpecifier: &envoy_config_route_v3.HeaderMatcher_StringMatch{
|
| 220 |
+
+ StringMatch: &envoy_type_matcher_v3.StringMatcher{
|
| 221 |
+
+ MatchPattern: &envoy_type_matcher_v3.StringMatcher_SafeRegex{
|
| 222 |
+
+ SafeRegex: &envoy_type_matcher_v3.RegexMatcher{Regex: onlyAuthority},
|
| 223 |
+
+ },
|
| 224 |
+
+ },
|
| 225 |
+
+ },
|
| 226 |
+
+ })
|
| 227 |
+
+ }
|
| 228 |
+
+ }
|
| 229 |
+
|
| 230 |
+
- routes = append(routes, policyRoutes...)
|
| 231 |
+
+ routes = append(routes, policyRoutes...)
|
| 232 |
+
+ }
|
| 233 |
+
}
|
| 234 |
+
return routes, nil
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
+// portlessURLServesHostPort reports whether a from URL without a port serves a
|
| 238 |
+
+// virtual host that names a port: such a route serves every port of its host.
|
| 239 |
+
+func portlessURLServesHostPort(options *config.Options, u *url.URL, host string) bool {
|
| 240 |
+
+ if !options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort) || u.Port() != "" ||
|
| 241 |
+
+ strings.Contains(u.Host, "*") || !config.HasPort(host) {
|
| 242 |
+
+ return false
|
| 243 |
+
+ }
|
| 244 |
+
+ hostname, _, err := net.SplitHostPort(host)
|
| 245 |
+
+ return err == nil && strings.EqualFold(u.Hostname(), hostname)
|
| 246 |
+
+}
|
| 247 |
+
+
|
| 248 |
+
+func wildcardURLMatchesHost(options *config.Options, u *url.URL, host string) bool {
|
| 249 |
+
+ stripPort := options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort)
|
| 250 |
+
+ anyPort := stripPort && u.Port() == ""
|
| 251 |
+
+ host = strings.ToLower(host)
|
| 252 |
+
+ for _, domain := range urlutil.GetDomainsForURL(u, !anyPort) {
|
| 253 |
+
+ domain = strings.ToLower(domain)
|
| 254 |
+
+ if stripPort && !config.HasPort(host) {
|
| 255 |
+
+ // this virtual host serves its host on every port: a wildcard that
|
| 256 |
+
+ // names a port belongs in it too, its :authority match keeps it to
|
| 257 |
+
+ // that port
|
| 258 |
+
+ if hostname, _, err := net.SplitHostPort(domain); err == nil {
|
| 259 |
+
+ domain = hostname
|
| 260 |
+
+ }
|
| 261 |
+
+ }
|
| 262 |
+
+ if regexp.MustCompile(config.WildcardToRegex(domain, anyPort)).MatchString(host) {
|
| 263 |
+
+ return true
|
| 264 |
+
+ }
|
| 265 |
+
+ }
|
| 266 |
+
+ return false
|
| 267 |
+
+}
|
| 268 |
+
+
|
| 269 |
+
func (b *Builder) buildRoutesForPoliciesWithCatchAll(
|
| 270 |
+
cfg *config.Config,
|
| 271 |
+
) ([]*envoy_config_route_v3.Route, error) {
|
| 272 |
+
var routes []*envoy_config_route_v3.Route
|
| 273 |
+
- for i, policy := range cfg.Options.GetAllPoliciesIndexed() {
|
| 274 |
+
+ for i, policy := range cfg.Options.GetAllPoliciesInRouteOrder() {
|
| 275 |
+
fromURL, err := urlutil.ParseAndValidateURL(policy.From)
|
| 276 |
+
if err != nil {
|
| 277 |
+
return nil, err
|
| 278 |
+
@@ -252,9 +322,12 @@ func (b *Builder) buildRoutesForPolicy(
|
| 279 |
+
|
| 280 |
+
var routes []*envoy_config_route_v3.Route
|
| 281 |
+
if strings.Contains(fromURL.Host, "*") {
|
| 282 |
+
- // we have to match '*.example.com' and '*.example.com:443', so there are two routes
|
| 283 |
+
- for _, host := range urlutil.GetDomainsForURL(fromURL, !cfg.Options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort)) {
|
| 284 |
+
- route, err := b.buildRouteForPolicyAndMatch(cfg, policy, name, mkRouteMatchForHost(cfg.Options, policy, host))
|
| 285 |
+
+ // we have to match '*.example.com' and '*.example.com:443', so there are two routes;
|
| 286 |
+
+ // a wildcard address that names its port, the default one included, keeps
|
| 287 |
+
+ // both and is served on that port only
|
| 288 |
+
+ anyPort := cfg.Options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort) && fromURL.Port() == ""
|
| 289 |
+
+ for _, host := range urlutil.GetDomainsForURL(fromURL, !anyPort) {
|
| 290 |
+
+ route, err := b.buildRouteForPolicyAndMatch(cfg, policy, name, mkRouteMatchForHost(cfg.Options, policy, host, anyPort))
|
| 291 |
+
if err != nil {
|
| 292 |
+
return nil, err
|
| 293 |
+
}
|
| 294 |
+
@@ -560,15 +633,22 @@ func mkRouteMatchForHost(
|
| 295 |
+
options *config.Options,
|
| 296 |
+
policy *config.Policy,
|
| 297 |
+
host string,
|
| 298 |
+
+ anyPort bool,
|
| 299 |
+
) *envoy_config_route_v3.RouteMatch {
|
| 300 |
+
match := mkRouteMatch(policy)
|
| 301 |
+
+ // the expression is written in lower case, the way a host name is compared
|
| 302 |
+
+ regex := config.WildcardToRegex(strings.ToLower(host), anyPort)
|
| 303 |
+
+ if options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort) {
|
| 304 |
+
+ // a host name carries no case, however the request spells it
|
| 305 |
+
+ regex = "(?i)" + regex
|
| 306 |
+
+ }
|
| 307 |
+
match.Headers = append(match.Headers, &envoy_config_route_v3.HeaderMatcher{
|
| 308 |
+
Name: ":authority",
|
| 309 |
+
HeaderMatchSpecifier: &envoy_config_route_v3.HeaderMatcher_StringMatch{
|
| 310 |
+
StringMatch: &envoy_type_matcher_v3.StringMatcher{
|
| 311 |
+
MatchPattern: &envoy_type_matcher_v3.StringMatcher_SafeRegex{
|
| 312 |
+
SafeRegex: &envoy_type_matcher_v3.RegexMatcher{
|
| 313 |
+
- Regex: config.WildcardToRegex(host, options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort)),
|
| 314 |
+
+ Regex: regex,
|
| 315 |
+
},
|
| 316 |
+
},
|
| 317 |
+
},
|
| 318 |
+
diff --git a/config/from.go b/config/from.go
|
| 319 |
+
index c5d5cd9..09944d5 100644
|
| 320 |
+
--- a/config/from.go
|
| 321 |
+
+++ b/config/from.go
|
| 322 |
+
@@ -10,8 +10,22 @@ import (
|
| 323 |
+
|
| 324 |
+
// FromURLMatchesRequestURL returns true if the from URL matches the request URL.
|
| 325 |
+
func FromURLMatchesRequestURL(fromURL, requestURL *url.URL, stripPort bool) bool {
|
| 326 |
+
+ // host names are not case sensitive: fold both sides before comparing, so
|
| 327 |
+
+ // that a from address and a request naming the same host agree however
|
| 328 |
+
+ // either of them happens to be spelled
|
| 329 |
+
+ reqHost := strings.ToLower(requestURL.Host)
|
| 330 |
+
+ reqHostname := strings.ToLower(requestURL.Hostname())
|
| 331 |
+
+
|
| 332 |
+
+ // a from URL without a port matches any port
|
| 333 |
+
+ if stripPort && fromURL.Port() == "" && !strings.Contains(fromURL.Host, "*") &&
|
| 334 |
+
+ !strings.HasPrefix(fromURL.Scheme, "tcp+") && !strings.HasPrefix(fromURL.Scheme, "udp+") &&
|
| 335 |
+
+ strings.ToLower(fromURL.Hostname()) == reqHostname {
|
| 336 |
+
+ return true
|
| 337 |
+
+ }
|
| 338 |
+
+
|
| 339 |
+
for _, domain := range urlutil.GetDomainsForURL(fromURL, true) {
|
| 340 |
+
- if domain == requestURL.Host {
|
| 341 |
+
+ domain = strings.ToLower(domain)
|
| 342 |
+
+ if domain == reqHost {
|
| 343 |
+
return true
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
@@ -19,9 +33,16 @@ func FromURLMatchesRequestURL(fromURL, requestURL *url.URL, stripPort bool) bool
|
| 347 |
+
continue
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
- reStr := WildcardToRegex(domain, stripPort)
|
| 351 |
+
+ // a wildcard address that names a port answers on that port only
|
| 352 |
+
+ reStr := WildcardToRegex(domain, stripPort && fromURL.Port() == "")
|
| 353 |
+
re := regexp.MustCompile(reStr)
|
| 354 |
+
- if re.MatchString(requestURL.Host) {
|
| 355 |
+
+ // the proxy folds the case of a request only where it serves any port:
|
| 356 |
+
+ // elsewhere the lookup reads the request the way the proxy does
|
| 357 |
+
+ host := reqHost
|
| 358 |
+
+ if !stripPort {
|
| 359 |
+
+ host = requestURL.Host
|
| 360 |
+
+ }
|
| 361 |
+
+ if re.MatchString(host) {
|
| 362 |
+
return true
|
| 363 |
+
}
|
| 364 |
+
}
|
| 365 |
+
diff --git a/config/identity.go b/config/identity.go
|
| 366 |
+
index 2117b5f..5e1c7cb 100644
|
| 367 |
+
--- a/config/identity.go
|
| 368 |
+
+++ b/config/identity.go
|
| 369 |
+
@@ -3,6 +3,7 @@ package config
|
| 370 |
+
import (
|
| 371 |
+
"context"
|
| 372 |
+
"slices"
|
| 373 |
+
+ "strings"
|
| 374 |
+
|
| 375 |
+
oteltrace "go.opentelemetry.io/otel/trace"
|
| 376 |
+
|
| 377 |
+
@@ -91,12 +92,23 @@ func (o *Options) GetIdentityProviderForRequestURL(requestURL string) (*identity
|
| 378 |
+
return nil, err
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
- for p := range o.GetAllPolicies() {
|
| 382 |
+
- if p.Matches(u, o.IsRuntimeFlagSet(RuntimeFlagMatchAnyIncomingPort)) {
|
| 383 |
+
- return o.GetIdentityProviderForPolicy(p)
|
| 384 |
+
+ // the same order the proxy matches in: route order, and a host's own
|
| 385 |
+
+ // routes before wildcard routes
|
| 386 |
+
+ stripPort := o.IsRuntimeFlagSet(RuntimeFlagMatchAnyIncomingPort)
|
| 387 |
+
+ var wildcard *Policy
|
| 388 |
+
+ for _, p := range o.GetAllPoliciesInRouteOrder() {
|
| 389 |
+
+ if !p.Matches(u, stripPort) {
|
| 390 |
+
+ continue
|
| 391 |
+
+ }
|
| 392 |
+
+ if strings.Contains(p.From, "*") {
|
| 393 |
+
+ if wildcard == nil {
|
| 394 |
+
+ wildcard = p
|
| 395 |
+
+ }
|
| 396 |
+
+ continue
|
| 397 |
+
}
|
| 398 |
+
+ return o.GetIdentityProviderForPolicy(p)
|
| 399 |
+
}
|
| 400 |
+
- return o.GetIdentityProviderForPolicy(nil)
|
| 401 |
+
+ return o.GetIdentityProviderForPolicy(wildcard)
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
// GetAuthenticator gets the authenticator for the given IDP id.
|
| 405 |
+
diff --git a/config/options.go b/config/options.go
|
| 406 |
+
index ad93c0a..74c7541 100644
|
| 407 |
+
--- a/config/options.go
|
| 408 |
+
+++ b/config/options.go
|
| 409 |
+
@@ -1075,6 +1075,40 @@ func (o *Options) GetAllPoliciesIndexed() iter.Seq2[int, *Policy] {
|
| 410 |
+
}
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
+// GetAllPoliciesInRouteOrder returns all the policies, with their configuration
|
| 414 |
+
+// index, in the order requests are matched against them: configuration order,
|
| 415 |
+
+// except that a policy with a higher regex_priority_order comes first.
|
| 416 |
+
+func (o *Options) GetAllPoliciesInRouteOrder() iter.Seq2[int, *Policy] {
|
| 417 |
+
+ type indexedPolicy struct {
|
| 418 |
+
+ index int
|
| 419 |
+
+ policy *Policy
|
| 420 |
+
+ }
|
| 421 |
+
+ var all []indexedPolicy
|
| 422 |
+
+ for i, p := range o.GetAllPoliciesIndexed() {
|
| 423 |
+
+ all = append(all, indexedPolicy{i, p})
|
| 424 |
+
+ }
|
| 425 |
+
+ slices.SortStableFunc(all, func(a, b indexedPolicy) int {
|
| 426 |
+
+ x, y := a.policy.RegexPriorityOrder, b.policy.RegexPriorityOrder
|
| 427 |
+
+ switch {
|
| 428 |
+
+ case x == nil && y == nil:
|
| 429 |
+
+ return 0
|
| 430 |
+
+ case x == nil:
|
| 431 |
+
+ return 1
|
| 432 |
+
+ case y == nil:
|
| 433 |
+
+ return -1
|
| 434 |
+
+ default:
|
| 435 |
+
+ return cmp.Compare(*y, *x)
|
| 436 |
+
+ }
|
| 437 |
+
+ })
|
| 438 |
+
+ return func(yield func(int, *Policy) bool) {
|
| 439 |
+
+ for _, e := range all {
|
| 440 |
+
+ if !yield(e.index, e.policy) {
|
| 441 |
+
+ return
|
| 442 |
+
+ }
|
| 443 |
+
+ }
|
| 444 |
+
+ }
|
| 445 |
+
+}
|
| 446 |
+
+
|
| 447 |
+
func (o *Options) NumPolicies() int {
|
| 448 |
+
return len(o.Policies) + len(o.Routes) + len(o.AdditionalPolicies)
|
| 449 |
+
}
|
| 450 |
+
@@ -1373,7 +1407,8 @@ func (o *Options) GetAllRouteableHTTPHosts() ([]string, map[string]bool, error)
|
| 451 |
+
return nil, nil, err
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
- domains := urlutil.GetDomainsForURL(fromURL, !o.IsRuntimeFlagSet(RuntimeFlagMatchAnyIncomingPort))
|
| 455 |
+
+ // a from URL with a port is served on that port, so it keeps it
|
| 456 |
+
+ domains := urlutil.GetDomainsForURL(fromURL, !o.IsRuntimeFlagSet(RuntimeFlagMatchAnyIncomingPort) || fromURL.Port() != "")
|
| 457 |
+
hosts.InsertSlice(domains)
|
| 458 |
+
|
| 459 |
+
// Track if the domains are associated with an MCP policy
|
| 460 |
+
diff --git a/config/route_order_test.go b/config/route_order_test.go
|
| 461 |
+
new file mode 100644
|
| 462 |
+
index 0000000..c2ebd62
|
| 463 |
+
--- /dev/null
|
| 464 |
+
+++ b/config/route_order_test.go
|
| 465 |
+
@@ -0,0 +1,72 @@
|
| 466 |
+
+package config
|
| 467 |
+
+
|
| 468 |
+
+import (
|
| 469 |
+
+ "testing"
|
| 470 |
+
+
|
| 471 |
+
+ "github.com/stretchr/testify/assert"
|
| 472 |
+
+)
|
| 473 |
+
+
|
| 474 |
+
+func TestGetIdentityProviderForRequestURL_RouteOrder(t *testing.T) {
|
| 475 |
+
+ t.Parallel()
|
| 476 |
+
+
|
| 477 |
+
+ prio := func(v int64) *int64 { return &v }
|
| 478 |
+
+ opts := func(policies ...Policy) *Options {
|
| 479 |
+
+ o := NewDefaultOptions()
|
| 480 |
+
+ o.AuthenticateURLString = "https://authenticate.example.com"
|
| 481 |
+
+ o.ClientID = "default"
|
| 482 |
+
+ o.ClientSecret = "secret"
|
| 483 |
+
+ o.Provider = "oidc"
|
| 484 |
+
+ o.ProviderURL = "https://idp.example.com"
|
| 485 |
+
+ o.Policies = policies
|
| 486 |
+
+ for i := range o.Policies {
|
| 487 |
+
+ assert.NoError(t, o.Policies[i].Validate())
|
| 488 |
+
+ }
|
| 489 |
+
+ return o
|
| 490 |
+
+ }
|
| 491 |
+
+ lookup := func(o *Options, u string) string {
|
| 492 |
+
+ idp, err := o.GetIdentityProviderForRequestURL(u)
|
| 493 |
+
+ if !assert.NoError(t, err) {
|
| 494 |
+
+ return ""
|
| 495 |
+
+ }
|
| 496 |
+
+ return idp.GetClientId()
|
| 497 |
+
+ }
|
| 498 |
+
+ to := mustParseWeightedURLs(t, "https://to.example.com")
|
| 499 |
+
+
|
| 500 |
+
+ t.Run("ports", func(t *testing.T) {
|
| 501 |
+
+ t.Parallel()
|
| 502 |
+
+ o := opts(
|
| 503 |
+
+ Policy{From: "https://any.example.com", To: to, IDPClientID: "any"},
|
| 504 |
+
+ Policy{From: "https://pinned.example.com:443", To: to, IDPClientID: "pinned"},
|
| 505 |
+
+ Policy{From: "https://*.wild443.example.com:443", To: to, IDPClientID: "wild443"},
|
| 506 |
+
+ Policy{From: "https://*.wild8443.example.com:8443", To: to, IDPClientID: "wild8443"},
|
| 507 |
+
+ )
|
| 508 |
+
+ assert.Equal(t, "any", lookup(o, "https://any.example.com:8443/x"))
|
| 509 |
+
+ assert.Equal(t, "any", lookup(o, "https://any.example.com/x"))
|
| 510 |
+
+ assert.Equal(t, "pinned", lookup(o, "https://pinned.example.com/x"))
|
| 511 |
+
+ assert.Equal(t, "default", lookup(o, "https://pinned.example.com:8443/x"))
|
| 512 |
+
+ assert.Equal(t, "wild443", lookup(o, "https://a.wild443.example.com/x"))
|
| 513 |
+
+ assert.Equal(t, "wild443", lookup(o, "https://a.wild443.example.com:443/x"))
|
| 514 |
+
+ assert.Equal(t, "default", lookup(o, "https://a.wild443.example.com:8443/x"))
|
| 515 |
+
+ assert.Equal(t, "wild8443", lookup(o, "https://a.wild8443.example.com:8443/x"))
|
| 516 |
+
+ assert.Equal(t, "default", lookup(o, "https://a.wild8443.example.com/x"))
|
| 517 |
+
+ })
|
| 518 |
+
+ t.Run("own route before wildcard", func(t *testing.T) {
|
| 519 |
+
+ t.Parallel()
|
| 520 |
+
+ o := opts(
|
| 521 |
+
+ Policy{From: "https://*.example.com", To: to, IDPClientID: "wild"},
|
| 522 |
+
+ Policy{From: "https://own.example.com", Path: "/own", To: to, IDPClientID: "own"},
|
| 523 |
+
+ )
|
| 524 |
+
+ assert.Equal(t, "own", lookup(o, "https://own.example.com/own"))
|
| 525 |
+
+ assert.Equal(t, "wild", lookup(o, "https://own.example.com/other"))
|
| 526 |
+
+ assert.Equal(t, "wild", lookup(o, "https://else.example.com/own"))
|
| 527 |
+
+ })
|
| 528 |
+
+ t.Run("regex priority", func(t *testing.T) {
|
| 529 |
+
+ t.Parallel()
|
| 530 |
+
+ o := opts(
|
| 531 |
+
+ Policy{From: "https://re.example.com", Regex: "^/a/.*$", RegexPriorityOrder: prio(1), To: to, IDPClientID: "low"},
|
| 532 |
+
+ Policy{From: "https://re.example.com", Regex: "^/a/b/.*$", RegexPriorityOrder: prio(2), To: to, IDPClientID: "high"},
|
| 533 |
+
+ )
|
| 534 |
+
+ assert.Equal(t, "high", lookup(o, "https://re.example.com/a/b/c"))
|
| 535 |
+
+ assert.Equal(t, "low", lookup(o, "https://re.example.com/a/c"))
|
| 536 |
+
+ })
|
| 537 |
+
+}
|
harbor/tasks/pomerium_route_order_contract/solution/solve.sh
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -eu
|
| 3 |
+
cd /workspace/repo
|
| 4 |
+
git apply <<'REFERENCE_PATCH'
|
| 5 |
+
diff --git a/config/envoyconfig/route_configurations.go b/config/envoyconfig/route_configurations.go
|
| 6 |
+
index 2aa0752..c43de28 100644
|
| 7 |
+
--- a/config/envoyconfig/route_configurations.go
|
| 8 |
+
+++ b/config/envoyconfig/route_configurations.go
|
| 9 |
+
@@ -85,12 +85,18 @@ func (b *Builder) buildMainRouteConfiguration(
|
| 10 |
+
return nil, err
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
+ explicitPortOnly := explicitPortOnlyHosts(cfg.Options)
|
| 14 |
+
+
|
| 15 |
+
var virtualHosts []*envoy_config_route_v3.VirtualHost
|
| 16 |
+
for _, host := range allHosts {
|
| 17 |
+
vh, err := b.buildVirtualHost(cfg.Options, host, host, mcpHosts[host])
|
| 18 |
+
if err != nil {
|
| 19 |
+
return nil, err
|
| 20 |
+
}
|
| 21 |
+
+ if explicitPortOnly[host] {
|
| 22 |
+
+ // every route of this host names its port: it is not served on any port
|
| 23 |
+
+ vh.Domains = []string{host}
|
| 24 |
+
+ }
|
| 25 |
+
|
| 26 |
+
if cfg.Options.Addr == cfg.Options.GetGRPCAddr() {
|
| 27 |
+
// if this is a gRPC service domain and we're supposed to handle that, add those routes
|
| 28 |
+
@@ -212,11 +218,15 @@ func getAllRouteableHosts(options *config.Options, addr string) ([]string, map[s
|
| 29 |
+
if err != nil {
|
| 30 |
+
return nil, nil, err
|
| 31 |
+
}
|
| 32 |
+
- allHosts.InsertSlice(hosts)
|
| 33 |
+
+ // host names carry no case: two from addresses that spell one host
|
| 34 |
+
+ // differently are one virtual host, not two envoy would reject
|
| 35 |
+
+ for _, host := range hosts {
|
| 36 |
+
+ allHosts.Insert(strings.ToLower(host))
|
| 37 |
+
+ }
|
| 38 |
+
// Merge any MCP hosts
|
| 39 |
+
for host, isMCP := range hostsMCP {
|
| 40 |
+
if isMCP {
|
| 41 |
+
- mcpHosts[host] = true
|
| 42 |
+
+ mcpHosts[strings.ToLower(host)] = true
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
@@ -226,7 +236,9 @@ func getAllRouteableHosts(options *config.Options, addr string) ([]string, map[s
|
| 47 |
+
if err != nil {
|
| 48 |
+
return nil, nil, err
|
| 49 |
+
}
|
| 50 |
+
- allHosts.InsertSlice(hosts)
|
| 51 |
+
+ for _, host := range hosts {
|
| 52 |
+
+ allHosts.Insert(strings.ToLower(host))
|
| 53 |
+
+ }
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
var filtered []string
|
| 57 |
+
@@ -256,6 +268,31 @@ func urlsMatchHost(urls []*url.URL, host string) bool {
|
| 58 |
+
return false
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
+// explicitPortOnlyHosts returns the hosts whose policy from URLs all carry a port.
|
| 62 |
+
+func explicitPortOnlyHosts(options *config.Options) map[string]bool {
|
| 63 |
+
+ withPort, withoutPort := map[string]bool{}, map[string]bool{}
|
| 64 |
+
+ for p := range options.GetAllPolicies() {
|
| 65 |
+
+ if p.IsSSH() {
|
| 66 |
+
+ continue
|
| 67 |
+
+ }
|
| 68 |
+
+ u, err := urlutil.ParseAndValidateURL(p.From)
|
| 69 |
+
+ if err != nil || strings.Contains(u.Host, "*") {
|
| 70 |
+
+ continue
|
| 71 |
+
+ }
|
| 72 |
+
+ if u.Port() != "" {
|
| 73 |
+
+ withPort[strings.ToLower(u.Hostname())] = true
|
| 74 |
+
+ } else {
|
| 75 |
+
+ withoutPort[strings.ToLower(u.Hostname())] = true
|
| 76 |
+
+ }
|
| 77 |
+
+ }
|
| 78 |
+
+ for h := range withoutPort {
|
| 79 |
+
+ delete(withPort, h)
|
| 80 |
+
+ }
|
| 81 |
+
+ return withPort
|
| 82 |
+
+}
|
| 83 |
+
+
|
| 84 |
+
func urlMatchesHost(u *url.URL, host string) bool {
|
| 85 |
+
- return slices.Contains(urlutil.GetDomainsForURL(u, true), host)
|
| 86 |
+
+ return slices.ContainsFunc(urlutil.GetDomainsForURL(u, true), func(domain string) bool {
|
| 87 |
+
+ return strings.EqualFold(domain, host)
|
| 88 |
+
+ })
|
| 89 |
+
}
|
| 90 |
+
diff --git a/config/envoyconfig/route_order_test.go b/config/envoyconfig/route_order_test.go
|
| 91 |
+
new file mode 100644
|
| 92 |
+
index 0000000..85148c2
|
| 93 |
+
--- /dev/null
|
| 94 |
+
+++ b/config/envoyconfig/route_order_test.go
|
| 95 |
+
@@ -0,0 +1,56 @@
|
| 96 |
+
+package envoyconfig
|
| 97 |
+
+
|
| 98 |
+
+import (
|
| 99 |
+
+ "testing"
|
| 100 |
+
+
|
| 101 |
+
+ envoy_config_route_v3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
|
| 102 |
+
+ "github.com/stretchr/testify/assert"
|
| 103 |
+
+ "github.com/stretchr/testify/require"
|
| 104 |
+
+
|
| 105 |
+
+ "github.com/pomerium/pomerium/config"
|
| 106 |
+
+ "github.com/pomerium/pomerium/config/envoyconfig/filemgr"
|
| 107 |
+
+)
|
| 108 |
+
+
|
| 109 |
+
+func TestBuilder_buildMainRouteConfiguration_RouteOrder(t *testing.T) {
|
| 110 |
+
+ t.Parallel()
|
| 111 |
+
+
|
| 112 |
+
+ prio := func(v int64) *int64 { return &v }
|
| 113 |
+
+ opts := config.NewDefaultOptions()
|
| 114 |
+
+ opts.Services = "proxy"
|
| 115 |
+
+ opts.Policies = []config.Policy{
|
| 116 |
+
+ {From: "https://*.example.com", To: mustParseWeightedURLs(t, "https://wild.internal")},
|
| 117 |
+
+ {From: "https://own.example.com", Path: "/own", To: mustParseWeightedURLs(t, "https://own.internal")},
|
| 118 |
+
+ {From: "https://own.example.com", Regex: "^/a/.*$", RegexPriorityOrder: prio(1), To: mustParseWeightedURLs(t, "https://low.internal")},
|
| 119 |
+
+ {From: "https://own.example.com", Regex: "^/a/b/.*$", RegexPriorityOrder: prio(2), To: mustParseWeightedURLs(t, "https://high.internal")},
|
| 120 |
+
+ {From: "https://pinned.example.com:443", To: mustParseWeightedURLs(t, "https://pinned.internal")},
|
| 121 |
+
+ }
|
| 122 |
+
+ b := New("connect", "grpc", "http", "debug", "metrics", filemgr.NewManager(), nil, true)
|
| 123 |
+
+ rc, err := b.buildMainRouteConfiguration(t.Context(), config.New(opts))
|
| 124 |
+
+ require.NoError(t, err)
|
| 125 |
+
+
|
| 126 |
+
+ vhosts := map[string]*envoy_config_route_v3.VirtualHost{}
|
| 127 |
+
+ for _, vh := range rc.GetVirtualHosts() {
|
| 128 |
+
+ vhosts[vh.GetName()] = vh
|
| 129 |
+
+ }
|
| 130 |
+
+ policyRoutes := func(vh *envoy_config_route_v3.VirtualHost) []string {
|
| 131 |
+
+ var names []string
|
| 132 |
+
+ for _, r := range vh.GetRoutes() {
|
| 133 |
+
+ if len(r.GetName()) > len("policy-") && r.GetName()[:len("policy-")] == "policy-" {
|
| 134 |
+
+ names = append(names, r.GetName())
|
| 135 |
+
+ }
|
| 136 |
+
+ }
|
| 137 |
+
+ return names
|
| 138 |
+
+ }
|
| 139 |
+
+
|
| 140 |
+
+ own := vhosts["own.example.com"]
|
| 141 |
+
+ require.NotNil(t, own)
|
| 142 |
+
+ // higher priority first, then the rest of the host's own routes, then the
|
| 143 |
+
+ // wildcard routes (one per wildcard domain)
|
| 144 |
+
+ assert.Equal(t, []string{"policy-3", "policy-2", "policy-1", "policy-0"}, policyRoutes(own))
|
| 145 |
+
+ assert.Equal(t, []string{"own.example.com", "own.example.com:*"}, own.GetDomains())
|
| 146 |
+
+
|
| 147 |
+
+ pinned := vhosts["pinned.example.com"]
|
| 148 |
+
+ require.NotNil(t, pinned)
|
| 149 |
+
+ assert.Equal(t, []string{"pinned.example.com"}, pinned.GetDomains())
|
| 150 |
+
+ assert.NotNil(t, vhosts["pinned.example.com:443"])
|
| 151 |
+
+}
|
| 152 |
+
diff --git a/config/envoyconfig/routes.go b/config/envoyconfig/routes.go
|
| 153 |
+
index f8c1d5a..5e7c3cf 100644
|
| 154 |
+
--- a/config/envoyconfig/routes.go
|
| 155 |
+
+++ b/config/envoyconfig/routes.go
|
| 156 |
+
@@ -3,7 +3,9 @@ package envoyconfig
|
| 157 |
+
import (
|
| 158 |
+
"encoding/json"
|
| 159 |
+
"fmt"
|
| 160 |
+
+ "net"
|
| 161 |
+
"net/url"
|
| 162 |
+
+ "regexp"
|
| 163 |
+
"slices"
|
| 164 |
+
"sort"
|
| 165 |
+
"strings"
|
| 166 |
+
@@ -195,32 +197,100 @@ func (b *Builder) buildRoutesForPoliciesWithHost(
|
| 167 |
+
host string,
|
| 168 |
+
) ([]*envoy_config_route_v3.Route, error) {
|
| 169 |
+
var routes []*envoy_config_route_v3.Route
|
| 170 |
+
- for i, p := range cfg.Options.GetAllPoliciesIndexed() {
|
| 171 |
+
- policy := p
|
| 172 |
+
- fromURL, err := urlutil.ParseAndValidateURL(policy.From)
|
| 173 |
+
- if err != nil {
|
| 174 |
+
- return nil, err
|
| 175 |
+
- }
|
| 176 |
+
+ // the host's own routes come first, then the wildcard routes that match the
|
| 177 |
+
+ // host: envoy never consults the catch-all virtual host for a host that has
|
| 178 |
+
+ // a virtual host of its own
|
| 179 |
+
+ for _, wildcard := range []bool{false, true} {
|
| 180 |
+
+ for i, policy := range cfg.Options.GetAllPoliciesInRouteOrder() {
|
| 181 |
+
+ fromURL, err := urlutil.ParseAndValidateURL(policy.From)
|
| 182 |
+
+ if err != nil {
|
| 183 |
+
+ return nil, err
|
| 184 |
+
+ }
|
| 185 |
+
|
| 186 |
+
- if !urlMatchesHost(fromURL, host) {
|
| 187 |
+
- continue
|
| 188 |
+
- }
|
| 189 |
+
+ if strings.Contains(fromURL.Host, "*") != wildcard {
|
| 190 |
+
+ continue
|
| 191 |
+
+ }
|
| 192 |
+
+ if wildcard && !wildcardURLMatchesHost(cfg.Options, fromURL, host) {
|
| 193 |
+
+ continue
|
| 194 |
+
+ }
|
| 195 |
+
+ // a route whose from address names a port answers only on that port,
|
| 196 |
+
+ // even on a host that other routes serve on every port
|
| 197 |
+
+ var onlyAuthority string
|
| 198 |
+
+ if !wildcard {
|
| 199 |
+
+ switch {
|
| 200 |
+
+ case urlMatchesHost(fromURL, host):
|
| 201 |
+
+ if fromURL.Port() != "" && !config.HasPort(host) {
|
| 202 |
+
+ onlyAuthority = "(?i)^" + regexp.QuoteMeta(fromURL.Hostname()) + "(:" + fromURL.Port() + ")?$"
|
| 203 |
+
+ }
|
| 204 |
+
+ case portlessURLServesHostPort(cfg.Options, fromURL, host):
|
| 205 |
+
+ // a from address without a port serves this port as well
|
| 206 |
+
+ default:
|
| 207 |
+
+ continue
|
| 208 |
+
+ }
|
| 209 |
+
+ }
|
| 210 |
+
|
| 211 |
+
- policyRoutes, err := b.buildRoutesForPolicy(cfg, policy, fmt.Sprintf("policy-%d", i))
|
| 212 |
+
- if err != nil {
|
| 213 |
+
- return nil, err
|
| 214 |
+
- }
|
| 215 |
+
+ policyRoutes, err := b.buildRoutesForPolicy(cfg, policy, fmt.Sprintf("policy-%d", i))
|
| 216 |
+
+ if err != nil {
|
| 217 |
+
+ return nil, err
|
| 218 |
+
+ }
|
| 219 |
+
+ if onlyAuthority != "" {
|
| 220 |
+
+ for _, r := range policyRoutes {
|
| 221 |
+
+ r.Match.Headers = append(r.Match.Headers, &envoy_config_route_v3.HeaderMatcher{
|
| 222 |
+
+ Name: ":authority",
|
| 223 |
+
+ HeaderMatchSpecifier: &envoy_config_route_v3.HeaderMatcher_StringMatch{
|
| 224 |
+
+ StringMatch: &envoy_type_matcher_v3.StringMatcher{
|
| 225 |
+
+ MatchPattern: &envoy_type_matcher_v3.StringMatcher_SafeRegex{
|
| 226 |
+
+ SafeRegex: &envoy_type_matcher_v3.RegexMatcher{Regex: onlyAuthority},
|
| 227 |
+
+ },
|
| 228 |
+
+ },
|
| 229 |
+
+ },
|
| 230 |
+
+ })
|
| 231 |
+
+ }
|
| 232 |
+
+ }
|
| 233 |
+
|
| 234 |
+
- routes = append(routes, policyRoutes...)
|
| 235 |
+
+ routes = append(routes, policyRoutes...)
|
| 236 |
+
+ }
|
| 237 |
+
}
|
| 238 |
+
return routes, nil
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
+// portlessURLServesHostPort reports whether a from URL without a port serves a
|
| 242 |
+
+// virtual host that names a port: such a route serves every port of its host.
|
| 243 |
+
+func portlessURLServesHostPort(options *config.Options, u *url.URL, host string) bool {
|
| 244 |
+
+ if !options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort) || u.Port() != "" ||
|
| 245 |
+
+ strings.Contains(u.Host, "*") || !config.HasPort(host) {
|
| 246 |
+
+ return false
|
| 247 |
+
+ }
|
| 248 |
+
+ hostname, _, err := net.SplitHostPort(host)
|
| 249 |
+
+ return err == nil && strings.EqualFold(u.Hostname(), hostname)
|
| 250 |
+
+}
|
| 251 |
+
+
|
| 252 |
+
+func wildcardURLMatchesHost(options *config.Options, u *url.URL, host string) bool {
|
| 253 |
+
+ stripPort := options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort)
|
| 254 |
+
+ anyPort := stripPort && u.Port() == ""
|
| 255 |
+
+ host = strings.ToLower(host)
|
| 256 |
+
+ for _, domain := range urlutil.GetDomainsForURL(u, !anyPort) {
|
| 257 |
+
+ domain = strings.ToLower(domain)
|
| 258 |
+
+ if stripPort && !config.HasPort(host) {
|
| 259 |
+
+ // this virtual host serves its host on every port: a wildcard that
|
| 260 |
+
+ // names a port belongs in it too, its :authority match keeps it to
|
| 261 |
+
+ // that port
|
| 262 |
+
+ if hostname, _, err := net.SplitHostPort(domain); err == nil {
|
| 263 |
+
+ domain = hostname
|
| 264 |
+
+ }
|
| 265 |
+
+ }
|
| 266 |
+
+ if regexp.MustCompile(config.WildcardToRegex(domain, anyPort)).MatchString(host) {
|
| 267 |
+
+ return true
|
| 268 |
+
+ }
|
| 269 |
+
+ }
|
| 270 |
+
+ return false
|
| 271 |
+
+}
|
| 272 |
+
+
|
| 273 |
+
func (b *Builder) buildRoutesForPoliciesWithCatchAll(
|
| 274 |
+
cfg *config.Config,
|
| 275 |
+
) ([]*envoy_config_route_v3.Route, error) {
|
| 276 |
+
var routes []*envoy_config_route_v3.Route
|
| 277 |
+
- for i, policy := range cfg.Options.GetAllPoliciesIndexed() {
|
| 278 |
+
+ for i, policy := range cfg.Options.GetAllPoliciesInRouteOrder() {
|
| 279 |
+
fromURL, err := urlutil.ParseAndValidateURL(policy.From)
|
| 280 |
+
if err != nil {
|
| 281 |
+
return nil, err
|
| 282 |
+
@@ -252,9 +322,12 @@ func (b *Builder) buildRoutesForPolicy(
|
| 283 |
+
|
| 284 |
+
var routes []*envoy_config_route_v3.Route
|
| 285 |
+
if strings.Contains(fromURL.Host, "*") {
|
| 286 |
+
- // we have to match '*.example.com' and '*.example.com:443', so there are two routes
|
| 287 |
+
- for _, host := range urlutil.GetDomainsForURL(fromURL, !cfg.Options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort)) {
|
| 288 |
+
- route, err := b.buildRouteForPolicyAndMatch(cfg, policy, name, mkRouteMatchForHost(cfg.Options, policy, host))
|
| 289 |
+
+ // we have to match '*.example.com' and '*.example.com:443', so there are two routes;
|
| 290 |
+
+ // a wildcard address that names its port, the default one included, keeps
|
| 291 |
+
+ // both and is served on that port only
|
| 292 |
+
+ anyPort := cfg.Options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort) && fromURL.Port() == ""
|
| 293 |
+
+ for _, host := range urlutil.GetDomainsForURL(fromURL, !anyPort) {
|
| 294 |
+
+ route, err := b.buildRouteForPolicyAndMatch(cfg, policy, name, mkRouteMatchForHost(cfg.Options, policy, host, anyPort))
|
| 295 |
+
if err != nil {
|
| 296 |
+
return nil, err
|
| 297 |
+
}
|
| 298 |
+
@@ -560,15 +633,22 @@ func mkRouteMatchForHost(
|
| 299 |
+
options *config.Options,
|
| 300 |
+
policy *config.Policy,
|
| 301 |
+
host string,
|
| 302 |
+
+ anyPort bool,
|
| 303 |
+
) *envoy_config_route_v3.RouteMatch {
|
| 304 |
+
match := mkRouteMatch(policy)
|
| 305 |
+
+ // the expression is written in lower case, the way a host name is compared
|
| 306 |
+
+ regex := config.WildcardToRegex(strings.ToLower(host), anyPort)
|
| 307 |
+
+ if options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort) {
|
| 308 |
+
+ // a host name carries no case, however the request spells it
|
| 309 |
+
+ regex = "(?i)" + regex
|
| 310 |
+
+ }
|
| 311 |
+
match.Headers = append(match.Headers, &envoy_config_route_v3.HeaderMatcher{
|
| 312 |
+
Name: ":authority",
|
| 313 |
+
HeaderMatchSpecifier: &envoy_config_route_v3.HeaderMatcher_StringMatch{
|
| 314 |
+
StringMatch: &envoy_type_matcher_v3.StringMatcher{
|
| 315 |
+
MatchPattern: &envoy_type_matcher_v3.StringMatcher_SafeRegex{
|
| 316 |
+
SafeRegex: &envoy_type_matcher_v3.RegexMatcher{
|
| 317 |
+
- Regex: config.WildcardToRegex(host, options.IsRuntimeFlagSet(config.RuntimeFlagMatchAnyIncomingPort)),
|
| 318 |
+
+ Regex: regex,
|
| 319 |
+
},
|
| 320 |
+
},
|
| 321 |
+
},
|
| 322 |
+
diff --git a/config/from.go b/config/from.go
|
| 323 |
+
index c5d5cd9..09944d5 100644
|
| 324 |
+
--- a/config/from.go
|
| 325 |
+
+++ b/config/from.go
|
| 326 |
+
@@ -10,8 +10,22 @@ import (
|
| 327 |
+
|
| 328 |
+
// FromURLMatchesRequestURL returns true if the from URL matches the request URL.
|
| 329 |
+
func FromURLMatchesRequestURL(fromURL, requestURL *url.URL, stripPort bool) bool {
|
| 330 |
+
+ // host names are not case sensitive: fold both sides before comparing, so
|
| 331 |
+
+ // that a from address and a request naming the same host agree however
|
| 332 |
+
+ // either of them happens to be spelled
|
| 333 |
+
+ reqHost := strings.ToLower(requestURL.Host)
|
| 334 |
+
+ reqHostname := strings.ToLower(requestURL.Hostname())
|
| 335 |
+
+
|
| 336 |
+
+ // a from URL without a port matches any port
|
| 337 |
+
+ if stripPort && fromURL.Port() == "" && !strings.Contains(fromURL.Host, "*") &&
|
| 338 |
+
+ !strings.HasPrefix(fromURL.Scheme, "tcp+") && !strings.HasPrefix(fromURL.Scheme, "udp+") &&
|
| 339 |
+
+ strings.ToLower(fromURL.Hostname()) == reqHostname {
|
| 340 |
+
+ return true
|
| 341 |
+
+ }
|
| 342 |
+
+
|
| 343 |
+
for _, domain := range urlutil.GetDomainsForURL(fromURL, true) {
|
| 344 |
+
- if domain == requestURL.Host {
|
| 345 |
+
+ domain = strings.ToLower(domain)
|
| 346 |
+
+ if domain == reqHost {
|
| 347 |
+
return true
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
@@ -19,9 +33,16 @@ func FromURLMatchesRequestURL(fromURL, requestURL *url.URL, stripPort bool) bool
|
| 351 |
+
continue
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
- reStr := WildcardToRegex(domain, stripPort)
|
| 355 |
+
+ // a wildcard address that names a port answers on that port only
|
| 356 |
+
+ reStr := WildcardToRegex(domain, stripPort && fromURL.Port() == "")
|
| 357 |
+
re := regexp.MustCompile(reStr)
|
| 358 |
+
- if re.MatchString(requestURL.Host) {
|
| 359 |
+
+ // the proxy folds the case of a request only where it serves any port:
|
| 360 |
+
+ // elsewhere the lookup reads the request the way the proxy does
|
| 361 |
+
+ host := reqHost
|
| 362 |
+
+ if !stripPort {
|
| 363 |
+
+ host = requestURL.Host
|
| 364 |
+
+ }
|
| 365 |
+
+ if re.MatchString(host) {
|
| 366 |
+
return true
|
| 367 |
+
}
|
| 368 |
+
}
|
| 369 |
+
diff --git a/config/identity.go b/config/identity.go
|
| 370 |
+
index 2117b5f..5e1c7cb 100644
|
| 371 |
+
--- a/config/identity.go
|
| 372 |
+
+++ b/config/identity.go
|
| 373 |
+
@@ -3,6 +3,7 @@ package config
|
| 374 |
+
import (
|
| 375 |
+
"context"
|
| 376 |
+
"slices"
|
| 377 |
+
+ "strings"
|
| 378 |
+
|
| 379 |
+
oteltrace "go.opentelemetry.io/otel/trace"
|
| 380 |
+
|
| 381 |
+
@@ -91,12 +92,23 @@ func (o *Options) GetIdentityProviderForRequestURL(requestURL string) (*identity
|
| 382 |
+
return nil, err
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
- for p := range o.GetAllPolicies() {
|
| 386 |
+
- if p.Matches(u, o.IsRuntimeFlagSet(RuntimeFlagMatchAnyIncomingPort)) {
|
| 387 |
+
- return o.GetIdentityProviderForPolicy(p)
|
| 388 |
+
+ // the same order the proxy matches in: route order, and a host's own
|
| 389 |
+
+ // routes before wildcard routes
|
| 390 |
+
+ stripPort := o.IsRuntimeFlagSet(RuntimeFlagMatchAnyIncomingPort)
|
| 391 |
+
+ var wildcard *Policy
|
| 392 |
+
+ for _, p := range o.GetAllPoliciesInRouteOrder() {
|
| 393 |
+
+ if !p.Matches(u, stripPort) {
|
| 394 |
+
+ continue
|
| 395 |
+
+ }
|
| 396 |
+
+ if strings.Contains(p.From, "*") {
|
| 397 |
+
+ if wildcard == nil {
|
| 398 |
+
+ wildcard = p
|
| 399 |
+
+ }
|
| 400 |
+
+ continue
|
| 401 |
+
}
|
| 402 |
+
+ return o.GetIdentityProviderForPolicy(p)
|
| 403 |
+
}
|
| 404 |
+
- return o.GetIdentityProviderForPolicy(nil)
|
| 405 |
+
+ return o.GetIdentityProviderForPolicy(wildcard)
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
// GetAuthenticator gets the authenticator for the given IDP id.
|
| 409 |
+
diff --git a/config/options.go b/config/options.go
|
| 410 |
+
index ad93c0a..74c7541 100644
|
| 411 |
+
--- a/config/options.go
|
| 412 |
+
+++ b/config/options.go
|
| 413 |
+
@@ -1075,6 +1075,40 @@ func (o *Options) GetAllPoliciesIndexed() iter.Seq2[int, *Policy] {
|
| 414 |
+
}
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
+// GetAllPoliciesInRouteOrder returns all the policies, with their configuration
|
| 418 |
+
+// index, in the order requests are matched against them: configuration order,
|
| 419 |
+
+// except that a policy with a higher regex_priority_order comes first.
|
| 420 |
+
+func (o *Options) GetAllPoliciesInRouteOrder() iter.Seq2[int, *Policy] {
|
| 421 |
+
+ type indexedPolicy struct {
|
| 422 |
+
+ index int
|
| 423 |
+
+ policy *Policy
|
| 424 |
+
+ }
|
| 425 |
+
+ var all []indexedPolicy
|
| 426 |
+
+ for i, p := range o.GetAllPoliciesIndexed() {
|
| 427 |
+
+ all = append(all, indexedPolicy{i, p})
|
| 428 |
+
+ }
|
| 429 |
+
+ slices.SortStableFunc(all, func(a, b indexedPolicy) int {
|
| 430 |
+
+ x, y := a.policy.RegexPriorityOrder, b.policy.RegexPriorityOrder
|
| 431 |
+
+ switch {
|
| 432 |
+
+ case x == nil && y == nil:
|
| 433 |
+
+ return 0
|
| 434 |
+
+ case x == nil:
|
| 435 |
+
+ return 1
|
| 436 |
+
+ case y == nil:
|
| 437 |
+
+ return -1
|
| 438 |
+
+ default:
|
| 439 |
+
+ return cmp.Compare(*y, *x)
|
| 440 |
+
+ }
|
| 441 |
+
+ })
|
| 442 |
+
+ return func(yield func(int, *Policy) bool) {
|
| 443 |
+
+ for _, e := range all {
|
| 444 |
+
+ if !yield(e.index, e.policy) {
|
| 445 |
+
+ return
|
| 446 |
+
+ }
|
| 447 |
+
+ }
|
| 448 |
+
+ }
|
| 449 |
+
+}
|
| 450 |
+
+
|
| 451 |
+
func (o *Options) NumPolicies() int {
|
| 452 |
+
return len(o.Policies) + len(o.Routes) + len(o.AdditionalPolicies)
|
| 453 |
+
}
|
| 454 |
+
@@ -1373,7 +1407,8 @@ func (o *Options) GetAllRouteableHTTPHosts() ([]string, map[string]bool, error)
|
| 455 |
+
return nil, nil, err
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
- domains := urlutil.GetDomainsForURL(fromURL, !o.IsRuntimeFlagSet(RuntimeFlagMatchAnyIncomingPort))
|
| 459 |
+
+ // a from URL with a port is served on that port, so it keeps it
|
| 460 |
+
+ domains := urlutil.GetDomainsForURL(fromURL, !o.IsRuntimeFlagSet(RuntimeFlagMatchAnyIncomingPort) || fromURL.Port() != "")
|
| 461 |
+
hosts.InsertSlice(domains)
|
| 462 |
+
|
| 463 |
+
// Track if the domains are associated with an MCP policy
|
| 464 |
+
diff --git a/config/route_order_test.go b/config/route_order_test.go
|
| 465 |
+
new file mode 100644
|
| 466 |
+
index 0000000..c2ebd62
|
| 467 |
+
--- /dev/null
|
| 468 |
+
+++ b/config/route_order_test.go
|
| 469 |
+
@@ -0,0 +1,72 @@
|
| 470 |
+
+package config
|
| 471 |
+
+
|
| 472 |
+
+import (
|
| 473 |
+
+ "testing"
|
| 474 |
+
+
|
| 475 |
+
+ "github.com/stretchr/testify/assert"
|
| 476 |
+
+)
|
| 477 |
+
+
|
| 478 |
+
+func TestGetIdentityProviderForRequestURL_RouteOrder(t *testing.T) {
|
| 479 |
+
+ t.Parallel()
|
| 480 |
+
+
|
| 481 |
+
+ prio := func(v int64) *int64 { return &v }
|
| 482 |
+
+ opts := func(policies ...Policy) *Options {
|
| 483 |
+
+ o := NewDefaultOptions()
|
| 484 |
+
+ o.AuthenticateURLString = "https://authenticate.example.com"
|
| 485 |
+
+ o.ClientID = "default"
|
| 486 |
+
+ o.ClientSecret = "secret"
|
| 487 |
+
+ o.Provider = "oidc"
|
| 488 |
+
+ o.ProviderURL = "https://idp.example.com"
|
| 489 |
+
+ o.Policies = policies
|
| 490 |
+
+ for i := range o.Policies {
|
| 491 |
+
+ assert.NoError(t, o.Policies[i].Validate())
|
| 492 |
+
+ }
|
| 493 |
+
+ return o
|
| 494 |
+
+ }
|
| 495 |
+
+ lookup := func(o *Options, u string) string {
|
| 496 |
+
+ idp, err := o.GetIdentityProviderForRequestURL(u)
|
| 497 |
+
+ if !assert.NoError(t, err) {
|
| 498 |
+
+ return ""
|
| 499 |
+
+ }
|
| 500 |
+
+ return idp.GetClientId()
|
| 501 |
+
+ }
|
| 502 |
+
+ to := mustParseWeightedURLs(t, "https://to.example.com")
|
| 503 |
+
+
|
| 504 |
+
+ t.Run("ports", func(t *testing.T) {
|
| 505 |
+
+ t.Parallel()
|
| 506 |
+
+ o := opts(
|
| 507 |
+
+ Policy{From: "https://any.example.com", To: to, IDPClientID: "any"},
|
| 508 |
+
+ Policy{From: "https://pinned.example.com:443", To: to, IDPClientID: "pinned"},
|
| 509 |
+
+ Policy{From: "https://*.wild443.example.com:443", To: to, IDPClientID: "wild443"},
|
| 510 |
+
+ Policy{From: "https://*.wild8443.example.com:8443", To: to, IDPClientID: "wild8443"},
|
| 511 |
+
+ )
|
| 512 |
+
+ assert.Equal(t, "any", lookup(o, "https://any.example.com:8443/x"))
|
| 513 |
+
+ assert.Equal(t, "any", lookup(o, "https://any.example.com/x"))
|
| 514 |
+
+ assert.Equal(t, "pinned", lookup(o, "https://pinned.example.com/x"))
|
| 515 |
+
+ assert.Equal(t, "default", lookup(o, "https://pinned.example.com:8443/x"))
|
| 516 |
+
+ assert.Equal(t, "wild443", lookup(o, "https://a.wild443.example.com/x"))
|
| 517 |
+
+ assert.Equal(t, "wild443", lookup(o, "https://a.wild443.example.com:443/x"))
|
| 518 |
+
+ assert.Equal(t, "default", lookup(o, "https://a.wild443.example.com:8443/x"))
|
| 519 |
+
+ assert.Equal(t, "wild8443", lookup(o, "https://a.wild8443.example.com:8443/x"))
|
| 520 |
+
+ assert.Equal(t, "default", lookup(o, "https://a.wild8443.example.com/x"))
|
| 521 |
+
+ })
|
| 522 |
+
+ t.Run("own route before wildcard", func(t *testing.T) {
|
| 523 |
+
+ t.Parallel()
|
| 524 |
+
+ o := opts(
|
| 525 |
+
+ Policy{From: "https://*.example.com", To: to, IDPClientID: "wild"},
|
| 526 |
+
+ Policy{From: "https://own.example.com", Path: "/own", To: to, IDPClientID: "own"},
|
| 527 |
+
+ )
|
| 528 |
+
+ assert.Equal(t, "own", lookup(o, "https://own.example.com/own"))
|
| 529 |
+
+ assert.Equal(t, "wild", lookup(o, "https://own.example.com/other"))
|
| 530 |
+
+ assert.Equal(t, "wild", lookup(o, "https://else.example.com/own"))
|
| 531 |
+
+ })
|
| 532 |
+
+ t.Run("regex priority", func(t *testing.T) {
|
| 533 |
+
+ t.Parallel()
|
| 534 |
+
+ o := opts(
|
| 535 |
+
+ Policy{From: "https://re.example.com", Regex: "^/a/.*$", RegexPriorityOrder: prio(1), To: to, IDPClientID: "low"},
|
| 536 |
+
+ Policy{From: "https://re.example.com", Regex: "^/a/b/.*$", RegexPriorityOrder: prio(2), To: to, IDPClientID: "high"},
|
| 537 |
+
+ )
|
| 538 |
+
+ assert.Equal(t, "high", lookup(o, "https://re.example.com/a/b/c"))
|
| 539 |
+
+ assert.Equal(t, "low", lookup(o, "https://re.example.com/a/c"))
|
| 540 |
+
+ })
|
| 541 |
+
+}
|
| 542 |
+
|
| 543 |
+
REFERENCE_PATCH
|
harbor/tasks/pomerium_route_order_contract/task.toml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
artifacts = ["/workspace/submissions/submitted.patch"]
|
| 3 |
+
[metadata]
|
| 4 |
+
task = "pomerium_route_order_contract"
|
| 5 |
+
validation_revision = "coding-rubric-v2"
|
| 6 |
+
[agent]
|
| 7 |
+
timeout_sec = 1800
|
| 8 |
+
user = "1000:1000"
|
| 9 |
+
[environment]
|
| 10 |
+
build_timeout_sec = 1800
|
| 11 |
+
cpus = 2
|
| 12 |
+
memory_mb = 8192
|
| 13 |
+
network_mode = "no-network"
|
| 14 |
+
[verifier]
|
| 15 |
+
timeout_sec = 7200
|
| 16 |
+
user = "0"
|
| 17 |
+
environment_mode = "separate"
|
| 18 |
+
[verifier.environment]
|
| 19 |
+
build_timeout_sec = 1800
|
| 20 |
+
cpus = 2
|
| 21 |
+
memory_mb = 8192
|
| 22 |
+
network_mode = "no-network"
|
| 23 |
+
[[verifier.collect]]
|
| 24 |
+
command = "/opt/task-tools/python -I /opt/task-tools/capture.py"
|
| 25 |
+
user = "0"
|
| 26 |
+
timeout_sec = 900
|
harbor/tasks/pomerium_route_order_contract/tests/Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-pomerium:source-v10
|
| 2 |
+
USER root
|
| 3 |
+
RUN grep -q '^[^:]*:[^:]*:1000:' /etc/passwd || echo 'grader:x:1000:1000::/tmp/agent-home:/bin/sh' >> /etc/passwd; grep -q '^[^:]*:[^:]*:1000:' /etc/group || echo 'grader:x:1000:' >> /etc/group
|
| 4 |
+
ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
|
| 5 |
+
RUN rm -f /hud/gold.diff
|
| 6 |
+
COPY verify.py evidence.py config.json test.sh /tests/
|
| 7 |
+
RUN chmod 755 /tests/test.sh
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
CMD ["sleep", "infinity"]
|
harbor/tasks/pomerium_route_order_contract/tests/config.json
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"revision": "coding-rubric-v2",
|
| 3 |
+
"task_id": "pomerium_route_order_contract",
|
| 4 |
+
"arguments": {},
|
| 5 |
+
"grader_version": "0.6.15",
|
| 6 |
+
"source_image": "ec-swe-pomerium:source-v10",
|
| 7 |
+
"source_image_id": "sha256:fd5dc4a78767a4430c8fc7c261dcecd3feb49e992bdc1d1f0c307caa7caa1193",
|
| 8 |
+
"provenance": {
|
| 9 |
+
"repository": "pomerium/pomerium",
|
| 10 |
+
"environment_id": "27189e2e-0d13-4bdf-83c7-7e5b413706f2",
|
| 11 |
+
"build": 10,
|
| 12 |
+
"build_id": "8d4d701f-12e8-44da-b079-95a78cafd767",
|
| 13 |
+
"hosted_task": "pomerium_route_order_contract",
|
| 14 |
+
"task_version": "abdcd9d0-572f-46b4-8b17-d67e4d4fa19e",
|
| 15 |
+
"source_archive_sha256": "669b8e3af43969044d3b0751e602888447e1e33bdc8649f0a9121848cecd3a84",
|
| 16 |
+
"hosted_revision_argument": "not recorded; the scenario does not read it"
|
| 17 |
+
},
|
| 18 |
+
"criteria": [
|
| 19 |
+
[
|
| 20 |
+
"explicit_port_route_serves_only_that_port",
|
| 21 |
+
0.28,
|
| 22 |
+
true,
|
| 23 |
+
"bash",
|
| 24 |
+
900
|
| 25 |
+
],
|
| 26 |
+
[
|
| 27 |
+
"regex_priority_settles_routes_that_name_the_port_in_any_case",
|
| 28 |
+
0.1,
|
| 29 |
+
true,
|
| 30 |
+
"bash",
|
| 31 |
+
900
|
| 32 |
+
],
|
| 33 |
+
[
|
| 34 |
+
"wildcard_route_serves_host_with_own_routes_in_any_case",
|
| 35 |
+
0.1525,
|
| 36 |
+
false,
|
| 37 |
+
"bash",
|
| 38 |
+
900
|
| 39 |
+
],
|
| 40 |
+
[
|
| 41 |
+
"explicit_port_from_written_in_capitals_serves_only_that_port",
|
| 42 |
+
0.1525,
|
| 43 |
+
false,
|
| 44 |
+
"bash",
|
| 45 |
+
900
|
| 46 |
+
],
|
| 47 |
+
[
|
| 48 |
+
"regex_priority_and_wildcard_fallback_in_any_case",
|
| 49 |
+
0.1525,
|
| 50 |
+
false,
|
| 51 |
+
"bash",
|
| 52 |
+
900
|
| 53 |
+
],
|
| 54 |
+
[
|
| 55 |
+
"inproc_lookup_matches_the_proxy_in_any_case",
|
| 56 |
+
0.1525,
|
| 57 |
+
false,
|
| 58 |
+
"bash",
|
| 59 |
+
900
|
| 60 |
+
],
|
| 61 |
+
[
|
| 62 |
+
"gate_repo_suite_green_and_tests_untouched",
|
| 63 |
+
0.01,
|
| 64 |
+
true,
|
| 65 |
+
"bash",
|
| 66 |
+
1800
|
| 67 |
+
]
|
| 68 |
+
],
|
| 69 |
+
"gates": [],
|
| 70 |
+
"reward_rule": "weighted_cap",
|
| 71 |
+
"local_hostname": false,
|
| 72 |
+
"fault_exit": 3,
|
| 73 |
+
"grader_readable": [],
|
| 74 |
+
"grader_writable": [],
|
| 75 |
+
"blocker_cap": 0.6,
|
| 76 |
+
"empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 77 |
+
"verifier_files": {
|
| 78 |
+
"/app/tasks.py": "a87312ea210c0d54280553db17370d4ad59f6d77d5662c8c12a947b95c3decd9",
|
| 79 |
+
"/app/env.py": "b53cd954bff21786840b391bd1dbb88b4c222accf24b33610e216f5780a3aa04",
|
| 80 |
+
"/app/task/prompt.md": "2720511effd9d9b30f1f5c560be72adf7e95199479660ea3d117d78c71393e03",
|
| 81 |
+
"/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
|
| 82 |
+
"/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
|
| 83 |
+
"/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
|
| 84 |
+
"/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
|
| 85 |
+
"/hud/grader/suite_gate.py": "b6fc04b43d5ea6b5a88dc82d6f08ef1d370b81018de5590aa48678c1d7ff7f79",
|
| 86 |
+
"/hud/grader/run_grading.sh": "0d6c87859be96d31252cec64945db1cd90066186686526a018ce0316e596a50c",
|
| 87 |
+
"/hud/grader/cells/cells_test.go": "e7eb2cf03dd31cf00088b2713612aa0ccd7da8909cedc65bf5ddd2ef4c0c0e85"
|
| 88 |
+
},
|
| 89 |
+
"preflight": [
|
| 90 |
+
[
|
| 91 |
+
"/bin/bash",
|
| 92 |
+
"--version"
|
| 93 |
+
],
|
| 94 |
+
[
|
| 95 |
+
"setpriv",
|
| 96 |
+
"--version"
|
| 97 |
+
],
|
| 98 |
+
[
|
| 99 |
+
"git",
|
| 100 |
+
"--version"
|
| 101 |
+
],
|
| 102 |
+
[
|
| 103 |
+
"bash",
|
| 104 |
+
"-c",
|
| 105 |
+
"bash -lc 'go version' || go version"
|
| 106 |
+
],
|
| 107 |
+
[
|
| 108 |
+
"/usr/local/bin/python3",
|
| 109 |
+
"--version"
|
| 110 |
+
]
|
| 111 |
+
]
|
| 112 |
+
}
|
harbor/tasks/pomerium_route_order_contract/tests/docker-compose.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
network_mode: none
|
| 4 |
+
pids_limit: 512
|
| 5 |
+
security_opt:
|
| 6 |
+
- no-new-privileges:true
|
harbor/tasks/pomerium_route_order_contract/tests/evidence.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validate complete coding-rubric evidence without importing the grader library or Harbor."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
REVISION = "coding-rubric-v2"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _number(value: Any) -> float:
|
| 12 |
+
if isinstance(value, bool) or not isinstance(value, (float, int)):
|
| 13 |
+
raise ValueError("Expected numeric rubric evidence")
|
| 14 |
+
if not math.isfinite(value) or not 0 <= value <= 1:
|
| 15 |
+
raise ValueError("Rubric values must be finite and within [0, 1]")
|
| 16 |
+
return float(value)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def validate_report(report: dict[str, Any], config: dict[str, Any], digest: str) -> None:
|
| 20 |
+
"""Check provenance, criterion coverage, weights, caps and command outcomes.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
report, config : dict
|
| 25 |
+
Fresh verifier evidence and the trusted prepared task configuration.
|
| 26 |
+
digest : str
|
| 27 |
+
SHA-256 of the submission collected by Harbor.
|
| 28 |
+
|
| 29 |
+
Raises
|
| 30 |
+
------
|
| 31 |
+
ValueError
|
| 32 |
+
If evidence is missing, inconsistent or reports infrastructure failure.
|
| 33 |
+
"""
|
| 34 |
+
if (
|
| 35 |
+
report.get("revision") != REVISION
|
| 36 |
+
or report.get("task_id") != config["task_id"]
|
| 37 |
+
or report.get("patch_sha256") != digest
|
| 38 |
+
or report.get("grader_version") != config["grader_version"]
|
| 39 |
+
):
|
| 40 |
+
raise ValueError("Verifier evidence provenance mismatch")
|
| 41 |
+
result = report.get("result", {})
|
| 42 |
+
reward = _number(result.get("reward"))
|
| 43 |
+
# A rubric may flag its own result when a grader could not judge. That is
|
| 44 |
+
# admitted only together with proof, checked below, that the same grader
|
| 45 |
+
# reaches a verdict on the untouched repository.
|
| 46 |
+
fault_exit = config.get("fault_exit")
|
| 47 |
+
faults = {
|
| 48 |
+
row["name"]
|
| 49 |
+
for row in report.get("commands", [])
|
| 50 |
+
if fault_exit is not None and (row.get("info") or {}).get("exit_code") == fault_exit
|
| 51 |
+
}
|
| 52 |
+
flagged = result.get("isError", False)
|
| 53 |
+
if (flagged and not faults) or result.get("done", True) is not True:
|
| 54 |
+
raise ValueError("Grader returned an incomplete or failed evaluation")
|
| 55 |
+
status = report.get("status")
|
| 56 |
+
if status == "rejected_patch":
|
| 57 |
+
if reward != 0 or not report.get("patch_error") or result.get("subscores"):
|
| 58 |
+
raise ValueError("Invalid rejected-patch evidence")
|
| 59 |
+
return
|
| 60 |
+
if status == "empty_patch":
|
| 61 |
+
credited = any(_number(row["value"]) for row in result.get("subscores") or [])
|
| 62 |
+
if reward != 0 or digest != config["empty_sha256"] or report.get("commands") or credited:
|
| 63 |
+
raise ValueError("Invalid empty-patch evidence")
|
| 64 |
+
return
|
| 65 |
+
if status != "graded":
|
| 66 |
+
raise ValueError("Verifier did not complete")
|
| 67 |
+
scores = result.get("subscores")
|
| 68 |
+
expected = {row[0]: row for row in config["criteria"]}
|
| 69 |
+
if not isinstance(scores, list) or len(scores) != len(expected):
|
| 70 |
+
raise ValueError("Missing rubric criteria")
|
| 71 |
+
names = [row["name"] for row in scores]
|
| 72 |
+
if len(set(names)) != len(names) or set(names) != set(expected):
|
| 73 |
+
raise ValueError("Duplicate or unexpected rubric criteria")
|
| 74 |
+
raw = 0.0
|
| 75 |
+
values = {}
|
| 76 |
+
for score in scores:
|
| 77 |
+
name = score["name"]
|
| 78 |
+
value, weight = _number(score["value"]), _number(score["weight"])
|
| 79 |
+
if not math.isclose(weight, expected[name][1], abs_tol=1e-12):
|
| 80 |
+
raise ValueError("Criterion weights changed")
|
| 81 |
+
raw += value * weight
|
| 82 |
+
values[name] = value
|
| 83 |
+
commands = report.get("commands", [])
|
| 84 |
+
command_names = [row["name"] for row in commands]
|
| 85 |
+
expected_commands = set(expected) | set(config["gates"])
|
| 86 |
+
if len(command_names) != len(set(command_names)) or set(command_names) != expected_commands:
|
| 87 |
+
raise ValueError("Missing or duplicate grader command evidence")
|
| 88 |
+
for command in commands:
|
| 89 |
+
info = command.get("info") or {}
|
| 90 |
+
code = info.get("exit_code")
|
| 91 |
+
verdict = type(code) is int and (code in (0, 1) or command["name"] in faults)
|
| 92 |
+
if not verdict or info.get("timed_out"):
|
| 93 |
+
raise ValueError("Grader command failed outside its verdict contract")
|
| 94 |
+
if _number(command["value"]) != float(code == 0):
|
| 95 |
+
raise ValueError("Command exit code disagrees with score")
|
| 96 |
+
probes = {row["name"]: row for row in report.get("fault_probes") or []}
|
| 97 |
+
if set(probes) != faults or any(
|
| 98 |
+
row.get("timed_out") or row.get("exit_code") not in (0, 1) for row in probes.values()
|
| 99 |
+
):
|
| 100 |
+
raise ValueError(
|
| 101 |
+
"A grader could not judge and the untouched repository does not explain it"
|
| 102 |
+
)
|
| 103 |
+
if any(values.get(name, 0) for name in faults):
|
| 104 |
+
raise ValueError("A criterion its grader could not judge is credited")
|
| 105 |
+
info = result.get("info") or {}
|
| 106 |
+
if info.get("aggregate_mismatch") or info.get("git_apply"):
|
| 107 |
+
raise ValueError("Grader reported inconsistent grading")
|
| 108 |
+
if config.get("reward_rule") == "authored":
|
| 109 |
+
# The task's own function decides the reward. It may take credit away
|
| 110 |
+
# (a cap, a criterion that pays only with progress) but never add any.
|
| 111 |
+
passed = {row["name"]: row["value"] for row in commands}
|
| 112 |
+
if any(values[name] > passed[name] for name in expected):
|
| 113 |
+
raise ValueError("A criterion is credited although its command failed")
|
| 114 |
+
if reward > raw + 1e-9:
|
| 115 |
+
raise ValueError("Grader reward exceeds its weighted criteria")
|
| 116 |
+
return
|
| 117 |
+
failed = {name for name, row in expected.items() if row[2] and values[name] < 1}
|
| 118 |
+
gate_failed = {
|
| 119 |
+
row["name"] for row in commands if row["name"] in config["gates"] and row["value"] < 1
|
| 120 |
+
}
|
| 121 |
+
expected_reward = min(raw, config["blocker_cap"]) if failed or gate_failed else raw
|
| 122 |
+
if not math.isclose(reward, expected_reward, abs_tol=1e-9):
|
| 123 |
+
raise ValueError("Grader reward disagrees with original weights and blocker cap")
|
harbor/tasks/pomerium_route_order_contract/tests/test.sh
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
echo '127.0.0.1 localhost.pomerium.io api.localhost.pomerium.io api-a.localhost.pomerium.io api-b.localhost.pomerium.io api-k3s.localhost.pomerium.io authenticate.localhost.pomerium.io bench-h1.localhost.pomerium.io bench-h2.localhost.pomerium.io echo.localhost.pomerium.io foo.localhost.pomerium.io grpc-h2c.localhost.pomerium.io grpc-http.localhost.pomerium.io grpc1.localhost.pomerium.io h1.localhost.pomerium.io h2.localhost.pomerium.io http.localhost.pomerium.io http1.localhost.pomerium.io mock-idp.localhost.pomerium.io sampling-50pct.localhost.pomerium.io test.localhost.pomerium.io ws-mid.localhost.pomerium.io ws-test.localhost.pomerium.io ws-test-denied.localhost.pomerium.io' >> /etc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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the original trusted coding rubric in a fresh, offline verifier container."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import hashlib
|
| 7 |
+
import importlib
|
| 8 |
+
import importlib.metadata
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import shlex
|
| 12 |
+
import shutil
|
| 13 |
+
import signal
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
from evidence import REVISION, validate_report
|
| 20 |
+
|
| 21 |
+
OUT = Path("/logs/verifier")
|
| 22 |
+
PRIVATE = Path("/var/lib/task-evidence")
|
| 23 |
+
CONFIG = Path("/tests/config.json")
|
| 24 |
+
PATCH = Path("/workspace/submissions/submitted.patch")
|
| 25 |
+
GRADER_HOME = "/tmp/agent-home"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
|
| 29 |
+
return subprocess.run(command, text=True, capture_output=True, timeout=300, **kwargs)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _preflight(config: dict[str, Any]) -> None:
|
| 33 |
+
if importlib.metadata.version("hud") != config["grader_version"]:
|
| 34 |
+
raise RuntimeError("Grader library version does not match the task")
|
| 35 |
+
for filename, expected in config["verifier_files"].items():
|
| 36 |
+
if hashlib.sha256(Path(filename).read_bytes()).hexdigest() != expected:
|
| 37 |
+
raise RuntimeError(f"Verifier source changed: {filename}")
|
| 38 |
+
for command in config["preflight"]:
|
| 39 |
+
completed = _run(command, cwd="/workspace/repo")
|
| 40 |
+
if completed.returncode:
|
| 41 |
+
raise RuntimeError(f"Prerequisite failed: {command}: {completed.stderr[-2000:]}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _readable_mode(path: Path) -> int:
|
| 45 |
+
# World-readable, keeping what is executable so: a grader may ship tools.
|
| 46 |
+
return 0o755 if path.is_dir() or path.stat().st_mode & 0o111 else 0o644
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _permissions() -> None:
|
| 50 |
+
# The orchestrator owns reports and rubric definitions. Grader commands,
|
| 51 |
+
# and so the candidate's code, run as uid 1000: the user the task installed
|
| 52 |
+
# its toolchain and caches for. They cannot read gold/vault or overwrite
|
| 53 |
+
# the rubric or the result files, which stay root's.
|
| 54 |
+
Path("/hud").chmod(0o711)
|
| 55 |
+
for root in (Path("/hud/grader"), Path("/hud/base"), Path("/hud/base-src")):
|
| 56 |
+
if root.exists():
|
| 57 |
+
root.chmod(0o755)
|
| 58 |
+
for path in root.rglob("*"):
|
| 59 |
+
if not path.is_symlink():
|
| 60 |
+
path.chmod(_readable_mode(path))
|
| 61 |
+
home = Path(GRADER_HOME)
|
| 62 |
+
home.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
os.chown(home, 1000, 1000)
|
| 64 |
+
for directory in ("/hud/logs", "/hud/gocache", "/hud/grader/runner"):
|
| 65 |
+
path = Path(directory)
|
| 66 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
for item in (path, *path.rglob("*")):
|
| 68 |
+
if not item.is_symlink():
|
| 69 |
+
os.chown(item, 1000, 1000)
|
| 70 |
+
item.chmod(_readable_mode(item))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _hand_over_checkout() -> None:
|
| 74 |
+
# The original grader runs as root and may run the candidate's own suite in
|
| 75 |
+
# place, which writes into the tree. The rubric resets and re-applies the
|
| 76 |
+
# candidate as root, so give what root touched back to the grading user.
|
| 77 |
+
# Installed dependency trees are large and already that user's.
|
| 78 |
+
subprocess.run(
|
| 79 |
+
[
|
| 80 |
+
"find",
|
| 81 |
+
"/workspace/repo",
|
| 82 |
+
"-path",
|
| 83 |
+
"*/node_modules",
|
| 84 |
+
"-prune",
|
| 85 |
+
"-o",
|
| 86 |
+
"!",
|
| 87 |
+
"-user",
|
| 88 |
+
"1000",
|
| 89 |
+
"-exec",
|
| 90 |
+
"chown",
|
| 91 |
+
"-h",
|
| 92 |
+
"1000:1000",
|
| 93 |
+
"{}",
|
| 94 |
+
"+",
|
| 95 |
+
],
|
| 96 |
+
check=True,
|
| 97 |
+
capture_output=True,
|
| 98 |
+
timeout=3600,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
async def _grade(config: dict[str, Any], record: dict[str, Any]) -> None:
|
| 103 |
+
_preflight(config)
|
| 104 |
+
sys.path.insert(0, "/app")
|
| 105 |
+
task: Any = importlib.import_module("tasks")
|
| 106 |
+
await task._setup()
|
| 107 |
+
_permissions()
|
| 108 |
+
patch = PATCH.read_bytes()
|
| 109 |
+
if patch:
|
| 110 |
+
checked = _run(["git", "apply", "--check", str(PATCH)], cwd="/workspace/repo")
|
| 111 |
+
if checked.returncode:
|
| 112 |
+
record.update(
|
| 113 |
+
status="rejected_patch",
|
| 114 |
+
patch_error=checked.stderr[-4000:],
|
| 115 |
+
result={"reward": 0.0, "subscores": None},
|
| 116 |
+
)
|
| 117 |
+
return
|
| 118 |
+
_run(["git", "apply", str(PATCH)], cwd="/workspace/repo", check=True)
|
| 119 |
+
original = task.BashGrader
|
| 120 |
+
fault_exit = config.get("fault_exit")
|
| 121 |
+
faulted: list[tuple[tuple[Any, ...], dict[str, Any], str]] = []
|
| 122 |
+
|
| 123 |
+
class ObservedGrader:
|
| 124 |
+
@classmethod
|
| 125 |
+
async def grade(cls, *args: Any, **kwargs: Any) -> Any:
|
| 126 |
+
command = kwargs["command"]
|
| 127 |
+
_hand_over_checkout()
|
| 128 |
+
kwargs["command"] = (
|
| 129 |
+
"setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs "
|
| 130 |
+
f"env HOME={GRADER_HOME} bash -lc " + shlex.quote(command)
|
| 131 |
+
)
|
| 132 |
+
score = await original.grade(*args, **kwargs)
|
| 133 |
+
snapshot = score.model_dump(mode="json")
|
| 134 |
+
record["commands"].append(snapshot)
|
| 135 |
+
(PRIVATE / "commands.json").write_text(json.dumps(record["commands"], indent=2))
|
| 136 |
+
info = snapshot.get("info") or {}
|
| 137 |
+
if info.get("timed_out") or type(info.get("exit_code")) is not int:
|
| 138 |
+
raise RuntimeError(f"Grader infrastructure failure: {snapshot['name']}")
|
| 139 |
+
if fault_exit is not None and info["exit_code"] == fault_exit:
|
| 140 |
+
# The grader says it could not judge. Whether the submission or
|
| 141 |
+
# the environment is the reason is settled after grading.
|
| 142 |
+
faulted.append((args, dict(kwargs), snapshot["name"]))
|
| 143 |
+
elif info["exit_code"] not in (0, 1):
|
| 144 |
+
raise RuntimeError(f"Grader command exit {info['exit_code']}: {snapshot['name']}")
|
| 145 |
+
return score
|
| 146 |
+
|
| 147 |
+
task.BashGrader = ObservedGrader
|
| 148 |
+
result = await task._grade(None)
|
| 149 |
+
if faulted:
|
| 150 |
+
# Ask the same commands about the untouched repository. A verdict there
|
| 151 |
+
# means the grader works here and the submission is what it could not
|
| 152 |
+
# judge, so the criterion stays unmet. No verdict there means the
|
| 153 |
+
# environment is at fault, and the attempt is invalid.
|
| 154 |
+
await task.repo_lib.git(task.REPO_DIR, "reset", "--hard", "HEAD")
|
| 155 |
+
await task.repo_lib.git(task.REPO_DIR, "clean", "-fd")
|
| 156 |
+
# Graders keep state between criteria, some of them a copy of the tree
|
| 157 |
+
# they judged. It describes the submission, so it goes too.
|
| 158 |
+
for leftover in Path(getattr(task, "LOGS_DIR", "/hud/logs")).iterdir():
|
| 159 |
+
if leftover.is_dir() and not leftover.is_symlink():
|
| 160 |
+
shutil.rmtree(leftover)
|
| 161 |
+
else:
|
| 162 |
+
leftover.unlink()
|
| 163 |
+
record["fault_probes"] = []
|
| 164 |
+
for args, kwargs, name in faulted:
|
| 165 |
+
_hand_over_checkout()
|
| 166 |
+
probe = (await original.grade(*args, **kwargs)).model_dump(mode="json")
|
| 167 |
+
info = probe.get("info") or {}
|
| 168 |
+
record["fault_probes"].append(
|
| 169 |
+
{
|
| 170 |
+
"name": name,
|
| 171 |
+
"exit_code": info.get("exit_code"),
|
| 172 |
+
"timed_out": info.get("timed_out"),
|
| 173 |
+
"stdout": (info.get("stdout") or "")[-2000:],
|
| 174 |
+
}
|
| 175 |
+
)
|
| 176 |
+
(PRIVATE / "fault_probes.json").write_text(json.dumps(record["fault_probes"], indent=2))
|
| 177 |
+
if info.get("timed_out") or info.get("exit_code") not in (0, 1):
|
| 178 |
+
raise RuntimeError(f"Grader cannot judge the untouched repository: {name}")
|
| 179 |
+
record["result"] = result.model_dump(mode="json")
|
| 180 |
+
# A rubric may answer an empty change without running any criterion.
|
| 181 |
+
record["status"] = "empty_patch" if not patch and not record["commands"] else "graded"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _stop_candidate_processes() -> None:
|
| 185 |
+
# A candidate may fork. End its UID's processes before publishing evidence
|
| 186 |
+
# to a host bind mount, whose permissions may differ on Docker Desktop.
|
| 187 |
+
for directory in Path("/proc").iterdir():
|
| 188 |
+
if not directory.name.isdecimal():
|
| 189 |
+
continue
|
| 190 |
+
try:
|
| 191 |
+
status = (directory / "status").read_text()
|
| 192 |
+
uid = next(line.split()[1] for line in status.splitlines() if line.startswith("Uid:"))
|
| 193 |
+
if uid == "1000":
|
| 194 |
+
os.kill(int(directory.name), signal.SIGKILL)
|
| 195 |
+
except (FileNotFoundError, ProcessLookupError):
|
| 196 |
+
pass
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def main() -> None:
|
| 200 |
+
"""Persist structured evidence and publish reward only after validation."""
|
| 201 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 202 |
+
PRIVATE.mkdir(parents=True, exist_ok=True, mode=0o700)
|
| 203 |
+
PRIVATE.chmod(0o700)
|
| 204 |
+
reward_path = OUT / "reward.txt"
|
| 205 |
+
reward_path.unlink(missing_ok=True)
|
| 206 |
+
config = json.loads(CONFIG.read_text())
|
| 207 |
+
shutil.copy2(CONFIG, OUT / "config.json")
|
| 208 |
+
record: dict[str, Any] = {
|
| 209 |
+
"revision": REVISION,
|
| 210 |
+
"task_id": config["task_id"],
|
| 211 |
+
"grader_version": importlib.metadata.version("hud"),
|
| 212 |
+
"commands": [],
|
| 213 |
+
"status": "error",
|
| 214 |
+
}
|
| 215 |
+
try:
|
| 216 |
+
if PATCH.is_symlink() or not PATCH.is_file() or PATCH.stat().st_size > 32 * 1024 * 1024:
|
| 217 |
+
raise ValueError("Missing, oversized or symlink submission")
|
| 218 |
+
record["patch_sha256"] = hashlib.sha256(PATCH.read_bytes()).hexdigest()
|
| 219 |
+
try:
|
| 220 |
+
asyncio.run(_grade(config, record))
|
| 221 |
+
finally:
|
| 222 |
+
_stop_candidate_processes()
|
| 223 |
+
reward_path.unlink(missing_ok=True)
|
| 224 |
+
validate_report(record, config, record["patch_sha256"])
|
| 225 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 226 |
+
reward_path.write_text(str(record["result"]["reward"]) + "\n")
|
| 227 |
+
except BaseException as error:
|
| 228 |
+
reward_path.unlink(missing_ok=True)
|
| 229 |
+
record.update(status="error", error={"type": type(error).__name__, "message": str(error)})
|
| 230 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 231 |
+
raise
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
main()
|
harbor/tasks/shared_handle_abandoned_operations/environment/Dockerfile
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-rust-postgres:source-v6 AS sanitized
|
| 2 |
+
USER root
|
| 3 |
+
COPY sanitize.py capture.py capture_submission.py /opt/task-tools/
|
| 4 |
+
RUN HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 /opt/hudvenv/bin/python /opt/task-tools/sanitize.py
|
| 5 |
+
FROM scratch
|
| 6 |
+
COPY --from=sanitized / /
|
| 7 |
+
ENV PATH="/cargo/bin:/usr/lib/postgresql/18/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
|
| 8 |
+
ENV LANG="C.UTF-8"
|
| 9 |
+
ENV CARGO_NET_OFFLINE="true"
|
| 10 |
+
ENV CARGO_TARGET_DIR="/agent-target"
|
| 11 |
+
ENV CARGO_HOME="/cargo"
|
| 12 |
+
ENV CARGO_BUILD_JOBS="2"
|
| 13 |
+
ENV RUSTUP_HOME="/usr/local/rustup"
|
| 14 |
+
ENV HOME="/tmp/agent-home"
|
| 15 |
+
ENV GOCACHE="/tmp/agent-home/.cache/go-build"
|
| 16 |
+
ENV HUD_TELEMETRY_ENABLED="false"
|
| 17 |
+
ENV HUD_CLI_ANALYTICS_ENABLED="0"
|
| 18 |
+
WORKDIR /workspace/repo
|
| 19 |
+
USER 1000:1000
|
| 20 |
+
CMD ["sleep", "infinity"]
|
harbor/tasks/shared_handle_abandoned_operations/environment/capture.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capture a patch against protected baseline history inside the agent sandbox."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
sys.path.insert(0, "/opt/task-tools")
|
| 11 |
+
from capture_submission import capture_submission # noqa: E402
|
| 12 |
+
|
| 13 |
+
with tempfile.TemporaryDirectory(prefix="capture-") as directory:
|
| 14 |
+
git_dir = Path(directory) / "git"
|
| 15 |
+
shutil.copytree("/opt/task-tools/baseline.git", git_dir)
|
| 16 |
+
os.environ.update(
|
| 17 |
+
GIT_DIR=str(git_dir),
|
| 18 |
+
GIT_WORK_TREE="/workspace/repo",
|
| 19 |
+
GIT_CONFIG_NOSYSTEM="1",
|
| 20 |
+
GIT_CONFIG_GLOBAL="/dev/null",
|
| 21 |
+
)
|
| 22 |
+
print(
|
| 23 |
+
json.dumps(
|
| 24 |
+
capture_submission(
|
| 25 |
+
Path("/workspace/repo"), Path("/workspace/submissions/submitted.patch")
|
| 26 |
+
)
|
| 27 |
+
)
|
| 28 |
+
)
|
harbor/tasks/shared_handle_abandoned_operations/environment/capture_submission.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capture tracked and new SWE files without changing the agent's Git index."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import shlex
|
| 8 |
+
import subprocess
|
| 9 |
+
import tempfile
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
MAX_SUBMISSION_BYTES = 32 * 1024 * 1024
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def capture_submission(
|
| 16 |
+
repository: Path, output: Path, *, max_bytes: int = MAX_SUBMISSION_BYTES
|
| 17 |
+
) -> dict[str, object]:
|
| 18 |
+
"""Write a bounded binary patch including nonignored new files.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
repository : Path
|
| 23 |
+
Git checkout root. HEAD must remain the task's initial commit.
|
| 24 |
+
output : Path
|
| 25 |
+
Submission path outside the checkout. Replaces any prior submission.
|
| 26 |
+
max_bytes : int, default: 33554432
|
| 27 |
+
Maximum emitted patch size. Oversized submissions fail without a patch.
|
| 28 |
+
|
| 29 |
+
Returns
|
| 30 |
+
-------
|
| 31 |
+
dict
|
| 32 |
+
Patch size, SHA-256, base commit and capture format for trial evidence.
|
| 33 |
+
|
| 34 |
+
Raises
|
| 35 |
+
------
|
| 36 |
+
ValueError
|
| 37 |
+
If paths or the limit are invalid, or the patch exceeds the limit.
|
| 38 |
+
OSError, subprocess.CalledProcessError, RuntimeError
|
| 39 |
+
If capture fails. No partial patch is published.
|
| 40 |
+
|
| 41 |
+
Notes
|
| 42 |
+
-----
|
| 43 |
+
Uses a temporary index to combine staged, unstaged and untracked changes.
|
| 44 |
+
Ignored untracked files are excluded. This is a capture bound, not a total
|
| 45 |
+
sandbox disk quota or a security boundary against a malicious Git runtime.
|
| 46 |
+
"""
|
| 47 |
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
|
| 48 |
+
raise ValueError("max_bytes must be a positive integer")
|
| 49 |
+
repository = repository.resolve(strict=True)
|
| 50 |
+
if output.is_symlink():
|
| 51 |
+
raise ValueError("Submission output must not be a symlink")
|
| 52 |
+
output = output.resolve()
|
| 53 |
+
if output.is_relative_to(repository):
|
| 54 |
+
raise ValueError("Submission output must be outside the repository")
|
| 55 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
output.unlink(missing_ok=True)
|
| 57 |
+
root = subprocess.check_output(
|
| 58 |
+
["git", "rev-parse", "--show-toplevel"], cwd=repository, text=True
|
| 59 |
+
).strip()
|
| 60 |
+
if Path(root).resolve() != repository:
|
| 61 |
+
raise ValueError("repository must be the Git checkout root")
|
| 62 |
+
base = subprocess.check_output(
|
| 63 |
+
["git", "rev-parse", "--verify", "HEAD^{commit}"], cwd=repository, text=True
|
| 64 |
+
).strip()
|
| 65 |
+
with tempfile.TemporaryDirectory(prefix="submission-", dir=output.parent) as directory:
|
| 66 |
+
temporary = Path(directory)
|
| 67 |
+
env = {**os.environ, "GIT_INDEX_FILE": str(temporary / "index")}
|
| 68 |
+
for arguments in (["read-tree", base], ["add", "--all", "--", "."]):
|
| 69 |
+
subprocess.run(["git", *arguments], cwd=repository, env=env, check=True)
|
| 70 |
+
patch = temporary / "patch"
|
| 71 |
+
size = 0
|
| 72 |
+
digest = hashlib.sha256()
|
| 73 |
+
with (
|
| 74 |
+
patch.open("wb") as stream,
|
| 75 |
+
tempfile.TemporaryFile() as errors,
|
| 76 |
+
subprocess.Popen(
|
| 77 |
+
[
|
| 78 |
+
"git",
|
| 79 |
+
"diff",
|
| 80 |
+
"--cached",
|
| 81 |
+
"--binary",
|
| 82 |
+
"--full-index",
|
| 83 |
+
"--no-renames",
|
| 84 |
+
"--no-ext-diff",
|
| 85 |
+
"--no-textconv",
|
| 86 |
+
"--no-color",
|
| 87 |
+
"--src-prefix=a/",
|
| 88 |
+
"--dst-prefix=b/",
|
| 89 |
+
base,
|
| 90 |
+
],
|
| 91 |
+
cwd=repository,
|
| 92 |
+
env=env,
|
| 93 |
+
stdout=subprocess.PIPE,
|
| 94 |
+
stderr=errors,
|
| 95 |
+
) as process,
|
| 96 |
+
):
|
| 97 |
+
assert process.stdout is not None
|
| 98 |
+
try:
|
| 99 |
+
while chunk := process.stdout.read(65536):
|
| 100 |
+
size += len(chunk)
|
| 101 |
+
if size > max_bytes:
|
| 102 |
+
raise ValueError(f"Submission exceeds {max_bytes} bytes")
|
| 103 |
+
stream.write(chunk)
|
| 104 |
+
digest.update(chunk)
|
| 105 |
+
except BaseException:
|
| 106 |
+
process.kill()
|
| 107 |
+
process.wait()
|
| 108 |
+
raise
|
| 109 |
+
if process.wait():
|
| 110 |
+
errors.seek(0)
|
| 111 |
+
raise RuntimeError(
|
| 112 |
+
"Git patch capture failed: " + errors.read(4096).decode(errors="replace")
|
| 113 |
+
)
|
| 114 |
+
patch.replace(output)
|
| 115 |
+
return {
|
| 116 |
+
"bytes": size,
|
| 117 |
+
"sha256": digest.hexdigest(),
|
| 118 |
+
"base_commit": base,
|
| 119 |
+
"format": "git-binary-v1",
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def submission_command(*, max_bytes: int = MAX_SUBMISSION_BYTES) -> str:
|
| 124 |
+
"""Build the trusted command recorded before Harbor collects artifacts.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
----------
|
| 128 |
+
max_bytes : int, default: 33554432
|
| 129 |
+
Maximum emitted patch bytes.
|
| 130 |
+
|
| 131 |
+
Returns
|
| 132 |
+
-------
|
| 133 |
+
str
|
| 134 |
+
Shell command carrying this exact helper into the solver runtime.
|
| 135 |
+
|
| 136 |
+
Raises
|
| 137 |
+
------
|
| 138 |
+
ValueError
|
| 139 |
+
If the size limit is invalid.
|
| 140 |
+
"""
|
| 141 |
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
|
| 142 |
+
raise ValueError("max_bytes must be a positive integer")
|
| 143 |
+
return "python -c " + shlex.quote(Path(__file__).read_text()) + f" --max-bytes {max_bytes}"
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def main() -> None:
|
| 147 |
+
"""Capture the submission and print its identity as trial evidence."""
|
| 148 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 149 |
+
parser.add_argument("--repository", type=Path, default=Path("/testbed"))
|
| 150 |
+
parser.add_argument("--output", type=Path, default=Path("/workspace/submitted.patch"))
|
| 151 |
+
parser.add_argument("--max-bytes", type=int, default=MAX_SUBMISSION_BYTES)
|
| 152 |
+
args = parser.parse_args()
|
| 153 |
+
print(json.dumps(capture_submission(args.repository, args.output, max_bytes=args.max_bytes)))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
main()
|
harbor/tasks/shared_handle_abandoned_operations/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
pids_limit: 512
|
| 4 |
+
security_opt:
|
| 5 |
+
- no-new-privileges:true
|
| 6 |
+
volumes:
|
| 7 |
+
- type: tmpfs
|
| 8 |
+
target: /logs/verifier
|
| 9 |
+
tmpfs:
|
| 10 |
+
mode: 448
|
| 11 |
+
size: 1048576
|
harbor/tasks/shared_handle_abandoned_operations/environment/sanitize.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Remove private task assets and history when building the agent-only image."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
sys.path.insert(0, "/app")
|
| 10 |
+
from env import _setup # noqa: E402
|
| 11 |
+
|
| 12 |
+
asyncio.run(_setup())
|
| 13 |
+
# The new history contains only the public baseline. Preserve a root-owned
|
| 14 |
+
# copy so capture can ignore agent-controlled refs, hooks and Git configuration.
|
| 15 |
+
shutil.copytree("/workspace/repo/.git", "/opt/task-tools/baseline.git")
|
| 16 |
+
for path in Path("/opt/task-tools/baseline.git").rglob("*"):
|
| 17 |
+
os.chown(path, 0, 0)
|
| 18 |
+
path.chmod(0o755 if path.is_dir() else 0o644)
|
| 19 |
+
for name in ("/hud", "/app", "/root/.cache", "/root/.hud"):
|
| 20 |
+
if Path(name).exists():
|
| 21 |
+
shutil.rmtree(name)
|
| 22 |
+
# Capture runs on the base interpreter under one name, whatever the image calls it.
|
| 23 |
+
os.symlink(os.path.realpath(sys.executable), "/opt/task-tools/python")
|
| 24 |
+
Path("/workspace/submissions").mkdir()
|
| 25 |
+
os.chown("/workspace/submissions", 1000, 1000)
|
harbor/tasks/shared_handle_abandoned_operations/instruction.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Please make your changes directly in /workspace/repo.
|
| 2 |
+
|
| 3 |
+
# Ticket
|
| 4 |
+
|
| 5 |
+
A connection handle is shared by many concurrent tasks, and any of them may give up on an operation partway through; whatever the server had already set up on that operation's behalf must then be taken back, and the tasks still using the handle must not be able to tell it ever happened.
|
| 6 |
+
|
| 7 |
+
Two things this change is held to. The crate's existing tests stay exactly as they are; anything you want to check goes into a file of your own. And keep the existing design: what a prepared query or a cursor already does today when it is dropped comes out byte for byte unchanged; add the new cleanup beside that path rather than reworking it into a shared helper.
|
| 8 |
+
|
| 9 |
+
Finish with a final response when your changes are ready.
|
harbor/tasks/shared_handle_abandoned_operations/solution/reference.patch
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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use std::sync::atomic::{AtomicUsize, Ordering};
|
| 6 |
+
|
| 7 |
+
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
|
| 8 |
+
|
| 9 |
+
+/// Closes the named portal on the server if the `bind` future is dropped before
|
| 10 |
+
+/// the `Portal` handle (whose own `Drop` performs the close) has been constructed.
|
| 11 |
+
+struct CloseOnDrop<'a> {
|
| 12 |
+
+ client: &'a Arc<InnerClient>,
|
| 13 |
+
+ name: Option<String>,
|
| 14 |
+
+}
|
| 15 |
+
+
|
| 16 |
+
+impl CloseOnDrop<'_> {
|
| 17 |
+
+ fn disarm(mut self) -> String {
|
| 18 |
+
+ self.name.take().expect("guard already disarmed")
|
| 19 |
+
+ }
|
| 20 |
+
+}
|
| 21 |
+
+
|
| 22 |
+
+impl Drop for CloseOnDrop<'_> {
|
| 23 |
+
+ fn drop(&mut self) {
|
| 24 |
+
+ if let Some(name) = self.name.take() {
|
| 25 |
+
+ let buf = self.client.with_buf(|buf| {
|
| 26 |
+
+ frontend::close(b'P', &name, buf).unwrap();
|
| 27 |
+
+ frontend::sync(buf);
|
| 28 |
+
+ buf.split().freeze()
|
| 29 |
+
+ });
|
| 30 |
+
+ let _ = self
|
| 31 |
+
+ .client
|
| 32 |
+
+ .send(RequestMessages::Single(FrontendMessage::Raw(buf)));
|
| 33 |
+
+ }
|
| 34 |
+
+ }
|
| 35 |
+
+}
|
| 36 |
+
+
|
| 37 |
+
pub async fn bind<P, I>(
|
| 38 |
+
client: &Arc<InnerClient>,
|
| 39 |
+
statement: Statement,
|
| 40 |
+
@@ -28,11 +56,15 @@ where
|
| 41 |
+
})?;
|
| 42 |
+
|
| 43 |
+
let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
|
| 44 |
+
+ let guard = CloseOnDrop {
|
| 45 |
+
+ client,
|
| 46 |
+
+ name: Some(name),
|
| 47 |
+
+ };
|
| 48 |
+
|
| 49 |
+
match responses.next().await? {
|
| 50 |
+
Message::BindComplete => {}
|
| 51 |
+
_ => return Err(Error::unexpected_message()),
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
- Ok(Portal::new(client, name, statement))
|
| 55 |
+
+ Ok(Portal::new(client, guard.disarm(), statement))
|
| 56 |
+
}
|
| 57 |
+
diff --git a/tokio-postgres/src/client.rs b/tokio-postgres/src/client.rs
|
| 58 |
+
index 6d3b03d3..e4136665 100644
|
| 59 |
+
--- a/tokio-postgres/src/client.rs
|
| 60 |
+
+++ b/tokio-postgres/src/client.rs
|
| 61 |
+
@@ -786,6 +786,17 @@ impl Client {
|
| 62 |
+
.send(RequestMessages::Single(FrontendMessage::Raw(buf)));
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
+ #[doc(hidden)]
|
| 66 |
+
+ pub fn __private_api_release_savepoint(&self, name: &str) {
|
| 67 |
+
+ let buf = self.inner().with_buf(|buf| {
|
| 68 |
+
+ frontend::query(&format!("RELEASE {name}"), buf).unwrap();
|
| 69 |
+
+ buf.split().freeze()
|
| 70 |
+
+ });
|
| 71 |
+
+ let _ = self
|
| 72 |
+
+ .inner()
|
| 73 |
+
+ .send(RequestMessages::Single(FrontendMessage::Raw(buf)));
|
| 74 |
+
+ }
|
| 75 |
+
+
|
| 76 |
+
#[doc(hidden)]
|
| 77 |
+
pub fn __private_api_close(&mut self) {
|
| 78 |
+
self.inner.sender.close_channel()
|
| 79 |
+
diff --git a/tokio-postgres/src/prepare.rs b/tokio-postgres/src/prepare.rs
|
| 80 |
+
index 8484fa33..ad673a4c 100644
|
| 81 |
+
--- a/tokio-postgres/src/prepare.rs
|
| 82 |
+
+++ b/tokio-postgres/src/prepare.rs
|
| 83 |
+
@@ -58,6 +58,35 @@ ORDER BY attnum
|
| 84 |
+
|
| 85 |
+
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
|
| 86 |
+
|
| 87 |
+
+/// Closes the named statement on the server if the `prepare` future is dropped
|
| 88 |
+
+/// before the `Statement` handle (whose own `Drop` performs the close) has been
|
| 89 |
+
+/// constructed.
|
| 90 |
+
+struct CloseOnDrop<'a> {
|
| 91 |
+
+ client: &'a Arc<InnerClient>,
|
| 92 |
+
+ name: Option<String>,
|
| 93 |
+
+}
|
| 94 |
+
+
|
| 95 |
+
+impl CloseOnDrop<'_> {
|
| 96 |
+
+ fn disarm(mut self) -> String {
|
| 97 |
+
+ self.name.take().expect("guard already disarmed")
|
| 98 |
+
+ }
|
| 99 |
+
+}
|
| 100 |
+
+
|
| 101 |
+
+impl Drop for CloseOnDrop<'_> {
|
| 102 |
+
+ fn drop(&mut self) {
|
| 103 |
+
+ if let Some(name) = self.name.take() {
|
| 104 |
+
+ let buf = self.client.with_buf(|buf| {
|
| 105 |
+
+ frontend::close(b'S', &name, buf).unwrap();
|
| 106 |
+
+ frontend::sync(buf);
|
| 107 |
+
+ buf.split().freeze()
|
| 108 |
+
+ });
|
| 109 |
+
+ let _ = self
|
| 110 |
+
+ .client
|
| 111 |
+
+ .send(RequestMessages::Single(FrontendMessage::Raw(buf)));
|
| 112 |
+
+ }
|
| 113 |
+
+ }
|
| 114 |
+
+}
|
| 115 |
+
+
|
| 116 |
+
pub async fn prepare(
|
| 117 |
+
client: &Arc<InnerClient>,
|
| 118 |
+
query: &str,
|
| 119 |
+
@@ -66,6 +95,12 @@ pub async fn prepare(
|
| 120 |
+
let name = format!("s{}", NEXT_ID.fetch_add(1, Ordering::SeqCst));
|
| 121 |
+
let buf = encode(client, &name, query, types)?;
|
| 122 |
+
let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
|
| 123 |
+
+ // From this point on the server may own a statement named `name`; make sure
|
| 124 |
+
+ // it is closed if this future is abandoned before `Statement` takes over.
|
| 125 |
+
+ let guard = CloseOnDrop {
|
| 126 |
+
+ client,
|
| 127 |
+
+ name: Some(name),
|
| 128 |
+
+ };
|
| 129 |
+
|
| 130 |
+
match responses.next().await? {
|
| 131 |
+
Message::ParseComplete => {}
|
| 132 |
+
@@ -106,7 +141,7 @@ pub async fn prepare(
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
- Ok(Statement::new(client, name, parameters, columns))
|
| 137 |
+
+ Ok(Statement::new(client, guard.disarm(), parameters, columns))
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
fn prepare_rec<'a>(
|
| 141 |
+
diff --git a/tokio-postgres/src/transaction.rs b/tokio-postgres/src/transaction.rs
|
| 142 |
+
index 81e8036b..d901764e 100644
|
| 143 |
+
--- a/tokio-postgres/src/transaction.rs
|
| 144 |
+
+++ b/tokio-postgres/src/transaction.rs
|
| 145 |
+
@@ -332,7 +332,34 @@ impl<'a> Transaction<'a> {
|
| 146 |
+
let depth = self.savepoint.as_ref().map_or(0, |sp| sp.depth) + 1;
|
| 147 |
+
let name = name.unwrap_or_else(|| format!("sp_{depth}"));
|
| 148 |
+
let query = format!("SAVEPOINT {name}");
|
| 149 |
+
- self.batch_execute(&query).await?;
|
| 150 |
+
+
|
| 151 |
+
+ struct ReleaseIfNotDone<'me> {
|
| 152 |
+
+ client: &'me Client,
|
| 153 |
+
+ name: &'me str,
|
| 154 |
+
+ done: bool,
|
| 155 |
+
+ }
|
| 156 |
+
+
|
| 157 |
+
+ impl Drop for ReleaseIfNotDone<'_> {
|
| 158 |
+
+ fn drop(&mut self) {
|
| 159 |
+
+ if self.done {
|
| 160 |
+
+ return;
|
| 161 |
+
+ }
|
| 162 |
+
+
|
| 163 |
+
+ // The future was dropped after `SAVEPOINT` was sent but before the
|
| 164 |
+
+ // nested `Transaction` (which would roll it back on drop) was created.
|
| 165 |
+
+ self.client.__private_api_release_savepoint(self.name);
|
| 166 |
+
+ }
|
| 167 |
+
+ }
|
| 168 |
+
+
|
| 169 |
+
+ {
|
| 170 |
+
+ let mut cleaner = ReleaseIfNotDone {
|
| 171 |
+
+ client: self.client,
|
| 172 |
+
+ name: &name,
|
| 173 |
+
+ done: false,
|
| 174 |
+
+ };
|
| 175 |
+
+ self.client.batch_execute(&query).await?;
|
| 176 |
+
+ cleaner.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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -eu
|
| 3 |
+
cd /workspace/repo
|
| 4 |
+
git apply <<'REFERENCE_PATCH'
|
| 5 |
+
diff --git a/tokio-postgres/src/bind.rs b/tokio-postgres/src/bind.rs
|
| 6 |
+
index 06cd14d2..ac1a4f90 100644
|
| 7 |
+
--- a/tokio-postgres/src/bind.rs
|
| 8 |
+
+++ b/tokio-postgres/src/bind.rs
|
| 9 |
+
@@ -10,6 +10,34 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
| 10 |
+
|
| 11 |
+
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
|
| 12 |
+
|
| 13 |
+
+/// Closes the named portal on the server if the `bind` future is dropped before
|
| 14 |
+
+/// the `Portal` handle (whose own `Drop` performs the close) has been constructed.
|
| 15 |
+
+struct CloseOnDrop<'a> {
|
| 16 |
+
+ client: &'a Arc<InnerClient>,
|
| 17 |
+
+ name: Option<String>,
|
| 18 |
+
+}
|
| 19 |
+
+
|
| 20 |
+
+impl CloseOnDrop<'_> {
|
| 21 |
+
+ fn disarm(mut self) -> String {
|
| 22 |
+
+ self.name.take().expect("guard already disarmed")
|
| 23 |
+
+ }
|
| 24 |
+
+}
|
| 25 |
+
+
|
| 26 |
+
+impl Drop for CloseOnDrop<'_> {
|
| 27 |
+
+ fn drop(&mut self) {
|
| 28 |
+
+ if let Some(name) = self.name.take() {
|
| 29 |
+
+ let buf = self.client.with_buf(|buf| {
|
| 30 |
+
+ frontend::close(b'P', &name, buf).unwrap();
|
| 31 |
+
+ frontend::sync(buf);
|
| 32 |
+
+ buf.split().freeze()
|
| 33 |
+
+ });
|
| 34 |
+
+ let _ = self
|
| 35 |
+
+ .client
|
| 36 |
+
+ .send(RequestMessages::Single(FrontendMessage::Raw(buf)));
|
| 37 |
+
+ }
|
| 38 |
+
+ }
|
| 39 |
+
+}
|
| 40 |
+
+
|
| 41 |
+
pub async fn bind<P, I>(
|
| 42 |
+
client: &Arc<InnerClient>,
|
| 43 |
+
statement: Statement,
|
| 44 |
+
@@ -28,11 +56,15 @@ where
|
| 45 |
+
})?;
|
| 46 |
+
|
| 47 |
+
let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
|
| 48 |
+
+ let guard = CloseOnDrop {
|
| 49 |
+
+ client,
|
| 50 |
+
+ name: Some(name),
|
| 51 |
+
+ };
|
| 52 |
+
|
| 53 |
+
match responses.next().await? {
|
| 54 |
+
Message::BindComplete => {}
|
| 55 |
+
_ => return Err(Error::unexpected_message()),
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
- Ok(Portal::new(client, name, statement))
|
| 59 |
+
+ Ok(Portal::new(client, guard.disarm(), statement))
|
| 60 |
+
}
|
| 61 |
+
diff --git a/tokio-postgres/src/client.rs b/tokio-postgres/src/client.rs
|
| 62 |
+
index 6d3b03d3..e4136665 100644
|
| 63 |
+
--- a/tokio-postgres/src/client.rs
|
| 64 |
+
+++ b/tokio-postgres/src/client.rs
|
| 65 |
+
@@ -786,6 +786,17 @@ impl Client {
|
| 66 |
+
.send(RequestMessages::Single(FrontendMessage::Raw(buf)));
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
+ #[doc(hidden)]
|
| 70 |
+
+ pub fn __private_api_release_savepoint(&self, name: &str) {
|
| 71 |
+
+ let buf = self.inner().with_buf(|buf| {
|
| 72 |
+
+ frontend::query(&format!("RELEASE {name}"), buf).unwrap();
|
| 73 |
+
+ buf.split().freeze()
|
| 74 |
+
+ });
|
| 75 |
+
+ let _ = self
|
| 76 |
+
+ .inner()
|
| 77 |
+
+ .send(RequestMessages::Single(FrontendMessage::Raw(buf)));
|
| 78 |
+
+ }
|
| 79 |
+
+
|
| 80 |
+
#[doc(hidden)]
|
| 81 |
+
pub fn __private_api_close(&mut self) {
|
| 82 |
+
self.inner.sender.close_channel()
|
| 83 |
+
diff --git a/tokio-postgres/src/prepare.rs b/tokio-postgres/src/prepare.rs
|
| 84 |
+
index 8484fa33..ad673a4c 100644
|
| 85 |
+
--- a/tokio-postgres/src/prepare.rs
|
| 86 |
+
+++ b/tokio-postgres/src/prepare.rs
|
| 87 |
+
@@ -58,6 +58,35 @@ ORDER BY attnum
|
| 88 |
+
|
| 89 |
+
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
|
| 90 |
+
|
| 91 |
+
+/// Closes the named statement on the server if the `prepare` future is dropped
|
| 92 |
+
+/// before the `Statement` handle (whose own `Drop` performs the close) has been
|
| 93 |
+
+/// constructed.
|
| 94 |
+
+struct CloseOnDrop<'a> {
|
| 95 |
+
+ client: &'a Arc<InnerClient>,
|
| 96 |
+
+ name: Option<String>,
|
| 97 |
+
+}
|
| 98 |
+
+
|
| 99 |
+
+impl CloseOnDrop<'_> {
|
| 100 |
+
+ fn disarm(mut self) -> String {
|
| 101 |
+
+ self.name.take().expect("guard already disarmed")
|
| 102 |
+
+ }
|
| 103 |
+
+}
|
| 104 |
+
+
|
| 105 |
+
+impl Drop for CloseOnDrop<'_> {
|
| 106 |
+
+ fn drop(&mut self) {
|
| 107 |
+
+ if let Some(name) = self.name.take() {
|
| 108 |
+
+ let buf = self.client.with_buf(|buf| {
|
| 109 |
+
+ frontend::close(b'S', &name, buf).unwrap();
|
| 110 |
+
+ frontend::sync(buf);
|
| 111 |
+
+ buf.split().freeze()
|
| 112 |
+
+ });
|
| 113 |
+
+ let _ = self
|
| 114 |
+
+ .client
|
| 115 |
+
+ .send(RequestMessages::Single(FrontendMessage::Raw(buf)));
|
| 116 |
+
+ }
|
| 117 |
+
+ }
|
| 118 |
+
+}
|
| 119 |
+
+
|
| 120 |
+
pub async fn prepare(
|
| 121 |
+
client: &Arc<InnerClient>,
|
| 122 |
+
query: &str,
|
| 123 |
+
@@ -66,6 +95,12 @@ pub async fn prepare(
|
| 124 |
+
let name = format!("s{}", NEXT_ID.fetch_add(1, Ordering::SeqCst));
|
| 125 |
+
let buf = encode(client, &name, query, types)?;
|
| 126 |
+
let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
|
| 127 |
+
+ // From this point on the server may own a statement named `name`; make sure
|
| 128 |
+
+ // it is closed if this future is abandoned before `Statement` takes over.
|
| 129 |
+
+ let guard = CloseOnDrop {
|
| 130 |
+
+ client,
|
| 131 |
+
+ name: Some(name),
|
| 132 |
+
+ };
|
| 133 |
+
|
| 134 |
+
match responses.next().await? {
|
| 135 |
+
Message::ParseComplete => {}
|
| 136 |
+
@@ -106,7 +141,7 @@ pub async fn prepare(
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
- Ok(Statement::new(client, name, parameters, columns))
|
| 141 |
+
+ Ok(Statement::new(client, guard.disarm(), parameters, columns))
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
fn prepare_rec<'a>(
|
| 145 |
+
diff --git a/tokio-postgres/src/transaction.rs b/tokio-postgres/src/transaction.rs
|
| 146 |
+
index 81e8036b..d901764e 100644
|
| 147 |
+
--- a/tokio-postgres/src/transaction.rs
|
| 148 |
+
+++ b/tokio-postgres/src/transaction.rs
|
| 149 |
+
@@ -332,7 +332,34 @@ impl<'a> Transaction<'a> {
|
| 150 |
+
let depth = self.savepoint.as_ref().map_or(0, |sp| sp.depth) + 1;
|
| 151 |
+
let name = name.unwrap_or_else(|| format!("sp_{depth}"));
|
| 152 |
+
let query = format!("SAVEPOINT {name}");
|
| 153 |
+
- self.batch_execute(&query).await?;
|
| 154 |
+
+
|
| 155 |
+
+ struct ReleaseIfNotDone<'me> {
|
| 156 |
+
+ client: &'me Client,
|
| 157 |
+
+ name: &'me str,
|
| 158 |
+
+ done: bool,
|
| 159 |
+
+ }
|
| 160 |
+
+
|
| 161 |
+
+ impl Drop for ReleaseIfNotDone<'_> {
|
| 162 |
+
+ fn drop(&mut self) {
|
| 163 |
+
+ if self.done {
|
| 164 |
+
+ return;
|
| 165 |
+
+ }
|
| 166 |
+
+
|
| 167 |
+
+ // The future was dropped after `SAVEPOINT` was sent but before the
|
| 168 |
+
+ // nested `Transaction` (which would roll it back on drop) was created.
|
| 169 |
+
+ self.client.__private_api_release_savepoint(self.name);
|
| 170 |
+
+ }
|
| 171 |
+
+ }
|
| 172 |
+
+
|
| 173 |
+
+ {
|
| 174 |
+
+ let mut cleaner = ReleaseIfNotDone {
|
| 175 |
+
+ client: self.client,
|
| 176 |
+
+ name: &name,
|
| 177 |
+
+ done: false,
|
| 178 |
+
+ };
|
| 179 |
+
+ self.client.batch_execute(&query).await?;
|
| 180 |
+
+ cleaner.done = true;
|
| 181 |
+
+ }
|
| 182 |
+
|
| 183 |
+
Ok(Transaction {
|
| 184 |
+
client: self.client,
|
| 185 |
+
|
| 186 |
+
REFERENCE_PATCH
|
harbor/tasks/shared_handle_abandoned_operations/task.toml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
artifacts = ["/workspace/submissions/submitted.patch"]
|
| 3 |
+
[metadata]
|
| 4 |
+
task = "shared_handle_abandoned_operations"
|
| 5 |
+
validation_revision = "coding-rubric-v2"
|
| 6 |
+
[agent]
|
| 7 |
+
timeout_sec = 1800
|
| 8 |
+
user = "1000:1000"
|
| 9 |
+
[environment]
|
| 10 |
+
build_timeout_sec = 1800
|
| 11 |
+
cpus = 2
|
| 12 |
+
memory_mb = 8192
|
| 13 |
+
network_mode = "no-network"
|
| 14 |
+
[verifier]
|
| 15 |
+
timeout_sec = 7200
|
| 16 |
+
user = "0"
|
| 17 |
+
environment_mode = "separate"
|
| 18 |
+
[verifier.environment]
|
| 19 |
+
build_timeout_sec = 1800
|
| 20 |
+
cpus = 2
|
| 21 |
+
memory_mb = 8192
|
| 22 |
+
network_mode = "no-network"
|
| 23 |
+
[[verifier.collect]]
|
| 24 |
+
command = "/opt/task-tools/python -I /opt/task-tools/capture.py"
|
| 25 |
+
user = "0"
|
| 26 |
+
timeout_sec = 900
|
harbor/tasks/shared_handle_abandoned_operations/tests/Dockerfile
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-rust-postgres:source-v6
|
| 2 |
+
USER root
|
| 3 |
+
RUN grep -q '^[^:]*:[^:]*:1000:' /etc/passwd || echo 'grader:x:1000:1000::/tmp/agent-home:/bin/sh' >> /etc/passwd; grep -q '^[^:]*:[^:]*:1000:' /etc/group || echo 'grader:x:1000:' >> /etc/group
|
| 4 |
+
RUN chmod -R a+rX /hud/cells.lock
|
| 5 |
+
RUN chown -R 1000:1000 /hud/cellstarget
|
| 6 |
+
RUN chown -R 1000:1000 /hud/repotarget
|
| 7 |
+
ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
|
| 8 |
+
RUN rm -f /hud/gold.diff
|
| 9 |
+
COPY verify.py evidence.py config.json test.sh /tests/
|
| 10 |
+
RUN chmod 755 /tests/test.sh
|
| 11 |
+
WORKDIR /app
|
| 12 |
+
CMD ["sleep", "infinity"]
|
harbor/tasks/shared_handle_abandoned_operations/tests/config.json
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"revision": "coding-rubric-v2",
|
| 3 |
+
"task_id": "shared_handle_abandoned_operations",
|
| 4 |
+
"arguments": {},
|
| 5 |
+
"grader_version": "0.6.15",
|
| 6 |
+
"source_image": "ec-swe-rust-postgres:source-v6",
|
| 7 |
+
"source_image_id": "sha256:6e0d4eab87a320005c9028f5675dcd876909c4d8cd02a9297293704c0575cd41",
|
| 8 |
+
"provenance": {
|
| 9 |
+
"repository": "sfackler/rust-postgres",
|
| 10 |
+
"environment_id": "ce1cbe36-00e5-4fde-a2bf-6137d3414ec4",
|
| 11 |
+
"build": 6,
|
| 12 |
+
"build_id": "0b011ade-1ef8-4251-baa2-17dfb2c7c7b1",
|
| 13 |
+
"hosted_task": "shared_handle_abandoned_operations",
|
| 14 |
+
"task_version": "56f75a82-9a24-4f78-afef-d9c65188b941",
|
| 15 |
+
"source_archive_sha256": "6499ba0fcd581626bc1052f09d38ac28476ab1a033d2c14da820087b02b3a36f",
|
| 16 |
+
"hosted_revision_argument": "not recorded; the scenario does not read it"
|
| 17 |
+
},
|
| 18 |
+
"criteria": [
|
| 19 |
+
[
|
| 20 |
+
"abandoned_rollback_point_not_left_set",
|
| 21 |
+
0.1342,
|
| 22 |
+
true,
|
| 23 |
+
"bash",
|
| 24 |
+
900
|
| 25 |
+
],
|
| 26 |
+
[
|
| 27 |
+
"rule_existing_teardown_kept",
|
| 28 |
+
0.25,
|
| 29 |
+
true,
|
| 30 |
+
"bash",
|
| 31 |
+
120
|
| 32 |
+
],
|
| 33 |
+
[
|
| 34 |
+
"same_with_the_outer_transaction_intact",
|
| 35 |
+
0.067,
|
| 36 |
+
false,
|
| 37 |
+
"bash",
|
| 38 |
+
600
|
| 39 |
+
],
|
| 40 |
+
[
|
| 41 |
+
"same_one_level_down",
|
| 42 |
+
0.0596,
|
| 43 |
+
false,
|
| 44 |
+
"bash",
|
| 45 |
+
600
|
| 46 |
+
],
|
| 47 |
+
[
|
| 48 |
+
"automatic_name_at_depth_not_left_set",
|
| 49 |
+
0.067,
|
| 50 |
+
false,
|
| 51 |
+
"bash",
|
| 52 |
+
600
|
| 53 |
+
],
|
| 54 |
+
[
|
| 55 |
+
"inner_point_gone_with_the_enclosing_one_kept",
|
| 56 |
+
0.0819,
|
| 57 |
+
false,
|
| 58 |
+
"bash",
|
| 59 |
+
600
|
| 60 |
+
],
|
| 61 |
+
[
|
| 62 |
+
"the_name_is_free_for_the_next_nested_transaction",
|
| 63 |
+
0.0745,
|
| 64 |
+
false,
|
| 65 |
+
"bash",
|
| 66 |
+
600
|
| 67 |
+
],
|
| 68 |
+
[
|
| 69 |
+
"a_neighbours_work_survives_the_cleanup",
|
| 70 |
+
0.067,
|
| 71 |
+
false,
|
| 72 |
+
"bash",
|
| 73 |
+
600
|
| 74 |
+
],
|
| 75 |
+
[
|
| 76 |
+
"same_when_the_point_carried_a_name",
|
| 77 |
+
0.0313,
|
| 78 |
+
false,
|
| 79 |
+
"bash",
|
| 80 |
+
600
|
| 81 |
+
],
|
| 82 |
+
[
|
| 83 |
+
"abandoned_prepare_leaves_no_server_object",
|
| 84 |
+
0.0223,
|
| 85 |
+
false,
|
| 86 |
+
"bash",
|
| 87 |
+
600
|
| 88 |
+
],
|
| 89 |
+
[
|
| 90 |
+
"same_under_implicit_preparation",
|
| 91 |
+
0.0164,
|
| 92 |
+
false,
|
| 93 |
+
"bash",
|
| 94 |
+
600
|
| 95 |
+
],
|
| 96 |
+
[
|
| 97 |
+
"same_under_typed_preparation",
|
| 98 |
+
0.0112,
|
| 99 |
+
false,
|
| 100 |
+
"bash",
|
| 101 |
+
600
|
| 102 |
+
],
|
| 103 |
+
[
|
| 104 |
+
"same_under_direct_execution",
|
| 105 |
+
0.0089,
|
| 106 |
+
false,
|
| 107 |
+
"bash",
|
| 108 |
+
600
|
| 109 |
+
],
|
| 110 |
+
[
|
| 111 |
+
"abandonment_at_the_first_suspension_point",
|
| 112 |
+
0.0127,
|
| 113 |
+
false,
|
| 114 |
+
"bash",
|
| 115 |
+
600
|
| 116 |
+
],
|
| 117 |
+
[
|
| 118 |
+
"eight_tasks_on_one_handle",
|
| 119 |
+
0.0127,
|
| 120 |
+
false,
|
| 121 |
+
"bash",
|
| 122 |
+
600
|
| 123 |
+
],
|
| 124 |
+
[
|
| 125 |
+
"nothing_left_and_concurrent_readers_correct",
|
| 126 |
+
0.0164,
|
| 127 |
+
false,
|
| 128 |
+
"bash",
|
| 129 |
+
600
|
| 130 |
+
],
|
| 131 |
+
[
|
| 132 |
+
"four_abandoning_tasks_and_two_hundred_controls",
|
| 133 |
+
0.0112,
|
| 134 |
+
false,
|
| 135 |
+
"bash",
|
| 136 |
+
600
|
| 137 |
+
],
|
| 138 |
+
[
|
| 139 |
+
"same_text_prepared_again_afterwards",
|
| 140 |
+
0.006,
|
| 141 |
+
false,
|
| 142 |
+
"bash",
|
| 143 |
+
600
|
| 144 |
+
],
|
| 145 |
+
[
|
| 146 |
+
"micro_timeout_boundary",
|
| 147 |
+
0.006,
|
| 148 |
+
false,
|
| 149 |
+
"bash",
|
| 150 |
+
600
|
| 151 |
+
],
|
| 152 |
+
[
|
| 153 |
+
"streaming_upload_path",
|
| 154 |
+
0.0074,
|
| 155 |
+
false,
|
| 156 |
+
"bash",
|
| 157 |
+
600
|
| 158 |
+
],
|
| 159 |
+
[
|
| 160 |
+
"streaming_download_path",
|
| 161 |
+
0.0074,
|
| 162 |
+
false,
|
| 163 |
+
"bash",
|
| 164 |
+
600
|
| 165 |
+
],
|
| 166 |
+
[
|
| 167 |
+
"abandoned_binding_leaves_no_portal",
|
| 168 |
+
0.0089,
|
| 169 |
+
false,
|
| 170 |
+
"bash",
|
| 171 |
+
600
|
| 172 |
+
],
|
| 173 |
+
[
|
| 174 |
+
"gate_repo_suite_green_and_tests_untouched",
|
| 175 |
+
0.02,
|
| 176 |
+
true,
|
| 177 |
+
"bash",
|
| 178 |
+
900
|
| 179 |
+
]
|
| 180 |
+
],
|
| 181 |
+
"gates": [
|
| 182 |
+
"gate_repo_suite_green_and_tests_untouched"
|
| 183 |
+
],
|
| 184 |
+
"reward_rule": "weighted_cap",
|
| 185 |
+
"local_hostname": false,
|
| 186 |
+
"fault_exit": 3,
|
| 187 |
+
"grader_readable": [
|
| 188 |
+
"/hud/cells.lock"
|
| 189 |
+
],
|
| 190 |
+
"grader_writable": [
|
| 191 |
+
"/hud/cellstarget",
|
| 192 |
+
"/hud/repotarget"
|
| 193 |
+
],
|
| 194 |
+
"blocker_cap": 0.6,
|
| 195 |
+
"empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 196 |
+
"verifier_files": {
|
| 197 |
+
"/app/tasks.py": "838544623b6da7045315c41477f67c3ae57caf9d9fcef5264f18a08af7b0f8a4",
|
| 198 |
+
"/app/env.py": "e79c321d2b08a004f496ad793c37c7e8bbf7d5bfb1f4ca1ea4def83fb46f7271",
|
| 199 |
+
"/app/task/prompt.md": "e672293afc73702ab05be8b72bcc2f17ca5e3ff4d8a4fea2ec887e11343856fd",
|
| 200 |
+
"/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
|
| 201 |
+
"/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
|
| 202 |
+
"/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
|
| 203 |
+
"/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
|
| 204 |
+
"/hud/grader/calibrate_host.sh": "934b41dad85689de0ba025554156de437b22d33913dc9d8600b1717570050054",
|
| 205 |
+
"/hud/grader/board.json": "a23fbce57b1533a55075004fb0117ae6a9c6380ce6d249aa5db5d9a260bf02f5",
|
| 206 |
+
"/hud/grader/run_grading.sh": "e4a65c915709d5032115fda9f4551dba9cacb8d4827e5261ae892d7b77b798c9",
|
| 207 |
+
"/hud/grader/score_board.py": "8162554f843ee7500ad0157e823bb5637fafb7eaca21074816a929ac25d096a3",
|
| 208 |
+
"/hud/grader/cells/Cargo.toml.tmpl": "87e7c6a1e48a963d2097bb05be32e351db106298f16f20175c3cf7bdb76d285a",
|
| 209 |
+
"/hud/grader/cells/src/main.rs": "b1ad195a3e2411e640e69a819c90edb1cd39b4b10d613f96f7a5b3db24a9531a"
|
| 210 |
+
},
|
| 211 |
+
"preflight": [
|
| 212 |
+
[
|
| 213 |
+
"/bin/bash",
|
| 214 |
+
"--version"
|
| 215 |
+
],
|
| 216 |
+
[
|
| 217 |
+
"setpriv",
|
| 218 |
+
"--version"
|
| 219 |
+
],
|
| 220 |
+
[
|
| 221 |
+
"git",
|
| 222 |
+
"--version"
|
| 223 |
+
],
|
| 224 |
+
[
|
| 225 |
+
"bash",
|
| 226 |
+
"-c",
|
| 227 |
+
"bash -lc 'cargo --version' || cargo --version"
|
| 228 |
+
],
|
| 229 |
+
[
|
| 230 |
+
"/usr/local/bin/python3",
|
| 231 |
+
"--version"
|
| 232 |
+
]
|
| 233 |
+
]
|
| 234 |
+
}
|
harbor/tasks/shared_handle_abandoned_operations/tests/docker-compose.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
network_mode: none
|
| 4 |
+
pids_limit: 512
|
| 5 |
+
security_opt:
|
| 6 |
+
- no-new-privileges:true
|
harbor/tasks/shared_handle_abandoned_operations/tests/evidence.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validate complete coding-rubric evidence without importing the grader library or Harbor."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
REVISION = "coding-rubric-v2"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _number(value: Any) -> float:
|
| 12 |
+
if isinstance(value, bool) or not isinstance(value, (float, int)):
|
| 13 |
+
raise ValueError("Expected numeric rubric evidence")
|
| 14 |
+
if not math.isfinite(value) or not 0 <= value <= 1:
|
| 15 |
+
raise ValueError("Rubric values must be finite and within [0, 1]")
|
| 16 |
+
return float(value)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def validate_report(report: dict[str, Any], config: dict[str, Any], digest: str) -> None:
|
| 20 |
+
"""Check provenance, criterion coverage, weights, caps and command outcomes.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
report, config : dict
|
| 25 |
+
Fresh verifier evidence and the trusted prepared task configuration.
|
| 26 |
+
digest : str
|
| 27 |
+
SHA-256 of the submission collected by Harbor.
|
| 28 |
+
|
| 29 |
+
Raises
|
| 30 |
+
------
|
| 31 |
+
ValueError
|
| 32 |
+
If evidence is missing, inconsistent or reports infrastructure failure.
|
| 33 |
+
"""
|
| 34 |
+
if (
|
| 35 |
+
report.get("revision") != REVISION
|
| 36 |
+
or report.get("task_id") != config["task_id"]
|
| 37 |
+
or report.get("patch_sha256") != digest
|
| 38 |
+
or report.get("grader_version") != config["grader_version"]
|
| 39 |
+
):
|
| 40 |
+
raise ValueError("Verifier evidence provenance mismatch")
|
| 41 |
+
result = report.get("result", {})
|
| 42 |
+
reward = _number(result.get("reward"))
|
| 43 |
+
# A rubric may flag its own result when a grader could not judge. That is
|
| 44 |
+
# admitted only together with proof, checked below, that the same grader
|
| 45 |
+
# reaches a verdict on the untouched repository.
|
| 46 |
+
fault_exit = config.get("fault_exit")
|
| 47 |
+
faults = {
|
| 48 |
+
row["name"]
|
| 49 |
+
for row in report.get("commands", [])
|
| 50 |
+
if fault_exit is not None and (row.get("info") or {}).get("exit_code") == fault_exit
|
| 51 |
+
}
|
| 52 |
+
flagged = result.get("isError", False)
|
| 53 |
+
if (flagged and not faults) or result.get("done", True) is not True:
|
| 54 |
+
raise ValueError("Grader returned an incomplete or failed evaluation")
|
| 55 |
+
status = report.get("status")
|
| 56 |
+
if status == "rejected_patch":
|
| 57 |
+
if reward != 0 or not report.get("patch_error") or result.get("subscores"):
|
| 58 |
+
raise ValueError("Invalid rejected-patch evidence")
|
| 59 |
+
return
|
| 60 |
+
if status == "empty_patch":
|
| 61 |
+
credited = any(_number(row["value"]) for row in result.get("subscores") or [])
|
| 62 |
+
if reward != 0 or digest != config["empty_sha256"] or report.get("commands") or credited:
|
| 63 |
+
raise ValueError("Invalid empty-patch evidence")
|
| 64 |
+
return
|
| 65 |
+
if status != "graded":
|
| 66 |
+
raise ValueError("Verifier did not complete")
|
| 67 |
+
scores = result.get("subscores")
|
| 68 |
+
expected = {row[0]: row for row in config["criteria"]}
|
| 69 |
+
if not isinstance(scores, list) or len(scores) != len(expected):
|
| 70 |
+
raise ValueError("Missing rubric criteria")
|
| 71 |
+
names = [row["name"] for row in scores]
|
| 72 |
+
if len(set(names)) != len(names) or set(names) != set(expected):
|
| 73 |
+
raise ValueError("Duplicate or unexpected rubric criteria")
|
| 74 |
+
raw = 0.0
|
| 75 |
+
values = {}
|
| 76 |
+
for score in scores:
|
| 77 |
+
name = score["name"]
|
| 78 |
+
value, weight = _number(score["value"]), _number(score["weight"])
|
| 79 |
+
if not math.isclose(weight, expected[name][1], abs_tol=1e-12):
|
| 80 |
+
raise ValueError("Criterion weights changed")
|
| 81 |
+
raw += value * weight
|
| 82 |
+
values[name] = value
|
| 83 |
+
commands = report.get("commands", [])
|
| 84 |
+
command_names = [row["name"] for row in commands]
|
| 85 |
+
expected_commands = set(expected) | set(config["gates"])
|
| 86 |
+
if len(command_names) != len(set(command_names)) or set(command_names) != expected_commands:
|
| 87 |
+
raise ValueError("Missing or duplicate grader command evidence")
|
| 88 |
+
for command in commands:
|
| 89 |
+
info = command.get("info") or {}
|
| 90 |
+
code = info.get("exit_code")
|
| 91 |
+
verdict = type(code) is int and (code in (0, 1) or command["name"] in faults)
|
| 92 |
+
if not verdict or info.get("timed_out"):
|
| 93 |
+
raise ValueError("Grader command failed outside its verdict contract")
|
| 94 |
+
if _number(command["value"]) != float(code == 0):
|
| 95 |
+
raise ValueError("Command exit code disagrees with score")
|
| 96 |
+
probes = {row["name"]: row for row in report.get("fault_probes") or []}
|
| 97 |
+
if set(probes) != faults or any(
|
| 98 |
+
row.get("timed_out") or row.get("exit_code") not in (0, 1) for row in probes.values()
|
| 99 |
+
):
|
| 100 |
+
raise ValueError(
|
| 101 |
+
"A grader could not judge and the untouched repository does not explain it"
|
| 102 |
+
)
|
| 103 |
+
if any(values.get(name, 0) for name in faults):
|
| 104 |
+
raise ValueError("A criterion its grader could not judge is credited")
|
| 105 |
+
info = result.get("info") or {}
|
| 106 |
+
if info.get("aggregate_mismatch") or info.get("git_apply"):
|
| 107 |
+
raise ValueError("Grader reported inconsistent grading")
|
| 108 |
+
if config.get("reward_rule") == "authored":
|
| 109 |
+
# The task's own function decides the reward. It may take credit away
|
| 110 |
+
# (a cap, a criterion that pays only with progress) but never add any.
|
| 111 |
+
passed = {row["name"]: row["value"] for row in commands}
|
| 112 |
+
if any(values[name] > passed[name] for name in expected):
|
| 113 |
+
raise ValueError("A criterion is credited although its command failed")
|
| 114 |
+
if reward > raw + 1e-9:
|
| 115 |
+
raise ValueError("Grader reward exceeds its weighted criteria")
|
| 116 |
+
return
|
| 117 |
+
failed = {name for name, row in expected.items() if row[2] and values[name] < 1}
|
| 118 |
+
gate_failed = {
|
| 119 |
+
row["name"] for row in commands if row["name"] in config["gates"] and row["value"] < 1
|
| 120 |
+
}
|
| 121 |
+
expected_reward = min(raw, config["blocker_cap"]) if failed or gate_failed else raw
|
| 122 |
+
if not math.isclose(reward, expected_reward, abs_tol=1e-9):
|
| 123 |
+
raise ValueError("Grader reward disagrees with original weights and blocker cap")
|
harbor/tasks/shared_handle_abandoned_operations/tests/test.sh
ADDED
|
@@ -0,0 +1,4 @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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the original trusted coding rubric in a fresh, offline verifier container."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import hashlib
|
| 7 |
+
import importlib
|
| 8 |
+
import importlib.metadata
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import shlex
|
| 12 |
+
import shutil
|
| 13 |
+
import signal
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
from evidence import REVISION, validate_report
|
| 20 |
+
|
| 21 |
+
OUT = Path("/logs/verifier")
|
| 22 |
+
PRIVATE = Path("/var/lib/task-evidence")
|
| 23 |
+
CONFIG = Path("/tests/config.json")
|
| 24 |
+
PATCH = Path("/workspace/submissions/submitted.patch")
|
| 25 |
+
GRADER_HOME = "/tmp/agent-home"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
|
| 29 |
+
return subprocess.run(command, text=True, capture_output=True, timeout=300, **kwargs)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _preflight(config: dict[str, Any]) -> None:
|
| 33 |
+
if importlib.metadata.version("hud") != config["grader_version"]:
|
| 34 |
+
raise RuntimeError("Grader library version does not match the task")
|
| 35 |
+
for filename, expected in config["verifier_files"].items():
|
| 36 |
+
if hashlib.sha256(Path(filename).read_bytes()).hexdigest() != expected:
|
| 37 |
+
raise RuntimeError(f"Verifier source changed: {filename}")
|
| 38 |
+
for command in config["preflight"]:
|
| 39 |
+
completed = _run(command, cwd="/workspace/repo")
|
| 40 |
+
if completed.returncode:
|
| 41 |
+
raise RuntimeError(f"Prerequisite failed: {command}: {completed.stderr[-2000:]}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _readable_mode(path: Path) -> int:
|
| 45 |
+
# World-readable, keeping what is executable so: a grader may ship tools.
|
| 46 |
+
return 0o755 if path.is_dir() or path.stat().st_mode & 0o111 else 0o644
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _permissions() -> None:
|
| 50 |
+
# The orchestrator owns reports and rubric definitions. Grader commands,
|
| 51 |
+
# and so the candidate's code, run as uid 1000: the user the task installed
|
| 52 |
+
# its toolchain and caches for. They cannot read gold/vault or overwrite
|
| 53 |
+
# the rubric or the result files, which stay root's.
|
| 54 |
+
Path("/hud").chmod(0o711)
|
| 55 |
+
for root in (Path("/hud/grader"), Path("/hud/base"), Path("/hud/base-src")):
|
| 56 |
+
if root.exists():
|
| 57 |
+
root.chmod(0o755)
|
| 58 |
+
for path in root.rglob("*"):
|
| 59 |
+
if not path.is_symlink():
|
| 60 |
+
path.chmod(_readable_mode(path))
|
| 61 |
+
home = Path(GRADER_HOME)
|
| 62 |
+
home.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
os.chown(home, 1000, 1000)
|
| 64 |
+
for directory in ("/hud/logs", "/hud/gocache", "/hud/grader/runner"):
|
| 65 |
+
path = Path(directory)
|
| 66 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
for item in (path, *path.rglob("*")):
|
| 68 |
+
if not item.is_symlink():
|
| 69 |
+
os.chown(item, 1000, 1000)
|
| 70 |
+
item.chmod(_readable_mode(item))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _hand_over_checkout() -> None:
|
| 74 |
+
# The original grader runs as root and may run the candidate's own suite in
|
| 75 |
+
# place, which writes into the tree. The rubric resets and re-applies the
|
| 76 |
+
# candidate as root, so give what root touched back to the grading user.
|
| 77 |
+
# Installed dependency trees are large and already that user's.
|
| 78 |
+
subprocess.run(
|
| 79 |
+
[
|
| 80 |
+
"find",
|
| 81 |
+
"/workspace/repo",
|
| 82 |
+
"-path",
|
| 83 |
+
"*/node_modules",
|
| 84 |
+
"-prune",
|
| 85 |
+
"-o",
|
| 86 |
+
"!",
|
| 87 |
+
"-user",
|
| 88 |
+
"1000",
|
| 89 |
+
"-exec",
|
| 90 |
+
"chown",
|
| 91 |
+
"-h",
|
| 92 |
+
"1000:1000",
|
| 93 |
+
"{}",
|
| 94 |
+
"+",
|
| 95 |
+
],
|
| 96 |
+
check=True,
|
| 97 |
+
capture_output=True,
|
| 98 |
+
timeout=3600,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
async def _grade(config: dict[str, Any], record: dict[str, Any]) -> None:
|
| 103 |
+
_preflight(config)
|
| 104 |
+
sys.path.insert(0, "/app")
|
| 105 |
+
task: Any = importlib.import_module("tasks")
|
| 106 |
+
await task._setup()
|
| 107 |
+
_permissions()
|
| 108 |
+
patch = PATCH.read_bytes()
|
| 109 |
+
if patch:
|
| 110 |
+
checked = _run(["git", "apply", "--check", str(PATCH)], cwd="/workspace/repo")
|
| 111 |
+
if checked.returncode:
|
| 112 |
+
record.update(
|
| 113 |
+
status="rejected_patch",
|
| 114 |
+
patch_error=checked.stderr[-4000:],
|
| 115 |
+
result={"reward": 0.0, "subscores": None},
|
| 116 |
+
)
|
| 117 |
+
return
|
| 118 |
+
_run(["git", "apply", str(PATCH)], cwd="/workspace/repo", check=True)
|
| 119 |
+
original = task.BashGrader
|
| 120 |
+
fault_exit = config.get("fault_exit")
|
| 121 |
+
faulted: list[tuple[tuple[Any, ...], dict[str, Any], str]] = []
|
| 122 |
+
|
| 123 |
+
class ObservedGrader:
|
| 124 |
+
@classmethod
|
| 125 |
+
async def grade(cls, *args: Any, **kwargs: Any) -> Any:
|
| 126 |
+
command = kwargs["command"]
|
| 127 |
+
_hand_over_checkout()
|
| 128 |
+
kwargs["command"] = (
|
| 129 |
+
"setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs "
|
| 130 |
+
f"env HOME={GRADER_HOME} bash -lc " + shlex.quote(command)
|
| 131 |
+
)
|
| 132 |
+
score = await original.grade(*args, **kwargs)
|
| 133 |
+
snapshot = score.model_dump(mode="json")
|
| 134 |
+
record["commands"].append(snapshot)
|
| 135 |
+
(PRIVATE / "commands.json").write_text(json.dumps(record["commands"], indent=2))
|
| 136 |
+
info = snapshot.get("info") or {}
|
| 137 |
+
if info.get("timed_out") or type(info.get("exit_code")) is not int:
|
| 138 |
+
raise RuntimeError(f"Grader infrastructure failure: {snapshot['name']}")
|
| 139 |
+
if fault_exit is not None and info["exit_code"] == fault_exit:
|
| 140 |
+
# The grader says it could not judge. Whether the submission or
|
| 141 |
+
# the environment is the reason is settled after grading.
|
| 142 |
+
faulted.append((args, dict(kwargs), snapshot["name"]))
|
| 143 |
+
elif info["exit_code"] not in (0, 1):
|
| 144 |
+
raise RuntimeError(f"Grader command exit {info['exit_code']}: {snapshot['name']}")
|
| 145 |
+
return score
|
| 146 |
+
|
| 147 |
+
task.BashGrader = ObservedGrader
|
| 148 |
+
result = await task._grade(None)
|
| 149 |
+
if faulted:
|
| 150 |
+
# Ask the same commands about the untouched repository. A verdict there
|
| 151 |
+
# means the grader works here and the submission is what it could not
|
| 152 |
+
# judge, so the criterion stays unmet. No verdict there means the
|
| 153 |
+
# environment is at fault, and the attempt is invalid.
|
| 154 |
+
await task.repo_lib.git(task.REPO_DIR, "reset", "--hard", "HEAD")
|
| 155 |
+
await task.repo_lib.git(task.REPO_DIR, "clean", "-fd")
|
| 156 |
+
# Graders keep state between criteria, some of them a copy of the tree
|
| 157 |
+
# they judged. It describes the submission, so it goes too.
|
| 158 |
+
for leftover in Path(getattr(task, "LOGS_DIR", "/hud/logs")).iterdir():
|
| 159 |
+
if leftover.is_dir() and not leftover.is_symlink():
|
| 160 |
+
shutil.rmtree(leftover)
|
| 161 |
+
else:
|
| 162 |
+
leftover.unlink()
|
| 163 |
+
record["fault_probes"] = []
|
| 164 |
+
for args, kwargs, name in faulted:
|
| 165 |
+
_hand_over_checkout()
|
| 166 |
+
probe = (await original.grade(*args, **kwargs)).model_dump(mode="json")
|
| 167 |
+
info = probe.get("info") or {}
|
| 168 |
+
record["fault_probes"].append(
|
| 169 |
+
{
|
| 170 |
+
"name": name,
|
| 171 |
+
"exit_code": info.get("exit_code"),
|
| 172 |
+
"timed_out": info.get("timed_out"),
|
| 173 |
+
"stdout": (info.get("stdout") or "")[-2000:],
|
| 174 |
+
}
|
| 175 |
+
)
|
| 176 |
+
(PRIVATE / "fault_probes.json").write_text(json.dumps(record["fault_probes"], indent=2))
|
| 177 |
+
if info.get("timed_out") or info.get("exit_code") not in (0, 1):
|
| 178 |
+
raise RuntimeError(f"Grader cannot judge the untouched repository: {name}")
|
| 179 |
+
record["result"] = result.model_dump(mode="json")
|
| 180 |
+
# A rubric may answer an empty change without running any criterion.
|
| 181 |
+
record["status"] = "empty_patch" if not patch and not record["commands"] else "graded"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _stop_candidate_processes() -> None:
|
| 185 |
+
# A candidate may fork. End its UID's processes before publishing evidence
|
| 186 |
+
# to a host bind mount, whose permissions may differ on Docker Desktop.
|
| 187 |
+
for directory in Path("/proc").iterdir():
|
| 188 |
+
if not directory.name.isdecimal():
|
| 189 |
+
continue
|
| 190 |
+
try:
|
| 191 |
+
status = (directory / "status").read_text()
|
| 192 |
+
uid = next(line.split()[1] for line in status.splitlines() if line.startswith("Uid:"))
|
| 193 |
+
if uid == "1000":
|
| 194 |
+
os.kill(int(directory.name), signal.SIGKILL)
|
| 195 |
+
except (FileNotFoundError, ProcessLookupError):
|
| 196 |
+
pass
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def main() -> None:
|
| 200 |
+
"""Persist structured evidence and publish reward only after validation."""
|
| 201 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 202 |
+
PRIVATE.mkdir(parents=True, exist_ok=True, mode=0o700)
|
| 203 |
+
PRIVATE.chmod(0o700)
|
| 204 |
+
reward_path = OUT / "reward.txt"
|
| 205 |
+
reward_path.unlink(missing_ok=True)
|
| 206 |
+
config = json.loads(CONFIG.read_text())
|
| 207 |
+
shutil.copy2(CONFIG, OUT / "config.json")
|
| 208 |
+
record: dict[str, Any] = {
|
| 209 |
+
"revision": REVISION,
|
| 210 |
+
"task_id": config["task_id"],
|
| 211 |
+
"grader_version": importlib.metadata.version("hud"),
|
| 212 |
+
"commands": [],
|
| 213 |
+
"status": "error",
|
| 214 |
+
}
|
| 215 |
+
try:
|
| 216 |
+
if PATCH.is_symlink() or not PATCH.is_file() or PATCH.stat().st_size > 32 * 1024 * 1024:
|
| 217 |
+
raise ValueError("Missing, oversized or symlink submission")
|
| 218 |
+
record["patch_sha256"] = hashlib.sha256(PATCH.read_bytes()).hexdigest()
|
| 219 |
+
try:
|
| 220 |
+
asyncio.run(_grade(config, record))
|
| 221 |
+
finally:
|
| 222 |
+
_stop_candidate_processes()
|
| 223 |
+
reward_path.unlink(missing_ok=True)
|
| 224 |
+
validate_report(record, config, record["patch_sha256"])
|
| 225 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 226 |
+
reward_path.write_text(str(record["result"]["reward"]) + "\n")
|
| 227 |
+
except BaseException as error:
|
| 228 |
+
reward_path.unlink(missing_ok=True)
|
| 229 |
+
record.update(status="error", error={"type": type(error).__name__, "message": str(error)})
|
| 230 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 231 |
+
raise
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
main()
|