feat: goctf final
This commit is contained in:
commit
f205b802d5
128 files changed
+37794
No files matched your search
@@ -0,0 +1,3 @@
|
||||
target/
|
||||
data/
|
||||
tests/
|
||||
Whitespace-only changes.
Generated
+107
@@ -0,0 +1,107 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "orbit-ctf"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "orbit-ctf"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
@@ -0,0 +1,15 @@
|
||||
FROM rust:1.90-bookworm AS build
|
||||
WORKDIR /build
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY src/ ./src/
|
||||
RUN cargo build --release --locked
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN useradd --system --uid 10001 --create-home orbit \
|
||||
&& mkdir /data && chown orbit:orbit /data
|
||||
COPY --from=build /build/target/release/orbit-ctf /usr/local/bin/orbit-ctf
|
||||
USER orbit
|
||||
ENV LISTEN_ADDR=0.0.0.0:8080 DATA_DIR=/data
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/usr/local/bin/orbit-ctf"]
|
||||
@@ -0,0 +1,22 @@
|
||||
name: orbital_navigation
|
||||
|
||||
services:
|
||||
orbital_navigation:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
LISTEN_ADDR: 0.0.0.0:8080
|
||||
DATA_DIR: /data
|
||||
ports:
|
||||
- "8086:8080"
|
||||
volumes:
|
||||
- orbital-data:/data
|
||||
pids_limit: 256
|
||||
mem_limit: 1g
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080'"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 15
|
||||
volumes:
|
||||
orbital-data:
|
||||
@@ -0,0 +1,40 @@
|
||||
# Orbital Navigation — handoff
|
||||
|
||||
Дата анализа: 2026-10-25.
|
||||
|
||||
## Подтверждённые уязвимости до патча
|
||||
|
||||
Сервис принимает JSON-RPC через `POST /rpc`, бинарные пакеты через `PUT /packages/{id}` и отдаёт внутренние сводки через `GET /internal/summaries/{id}`. Локально на исходной версии с двумя синтетическими пользователями воспроизведены следующие пути чтения чужих данных:
|
||||
|
||||
- `bind_source` проверял только существование канонизированного `source`, но не владельца корабля. Другой пользователь мог передать регистровый алиас идентификатора чужого корабля и затем получить его сообщения через привязанный источник.
|
||||
- `edit_profile` позволял владельцу профиля заменить `ship_id` на чужой корабль. Уже созданный экспортный job сохранял ссылку на профиль, а `run_export` не перепроверял владение текущим кораблём, поэтому после подмены профиля возвращал чужие сообщения.
|
||||
- Ключ `geometry_cache` состоял только из `geometry`, `map_version` и `options`. Если другой пользователь первым создавал полёт с той же публичной тройкой параметров, отчёт по полёту мог взять его cached flight и раскрыть чужой manifest.
|
||||
- `delegate` разрешал дочернему grant запрашивать права, отсутствующие у родительского grant, и не проверял фактическое истечение срока. Публичный grant с `delegate` можно было повысить до `manifest.read`; `read_manifest` также принимал просроченный grant.
|
||||
- Внутренний маршрут `/internal/summaries/{id}` защищался только статическим importer key, который сам сервис добавлял при `import_bulletin`. Проверка URL отбрасывала лишь строковые `localhost`/`127.0.0.1`; loopback-алиас `127.1` разрешал SSRF и чтение чужой summary. После первого исправления оставался обход через IPv4-mapped IPv6: разрешённый резолвером `::ffff:127.0.0.1` не считался IPv6 loopback, но подключался к IPv4 loopback. Прямой запрос с известным ключом также не ограничивался loopback peer.
|
||||
- После `approve_package` содержимое пакета можно было заменить через повторный `PUT`, не сбрасывая approval. `generate_report` распаковывал уже заменённый TAR без повторной безопасной проверки и разрешал canonical target внутри общего `navigation`, поэтому symlink-entry мог прочитать файл навигации другого пользователя.
|
||||
|
||||
Ожидаемые источники флагов до исправления: сообщения корабля, manifest полёта, content summary и файлы `navigation/{flight_id}.txt`. Для воспроизведения нужны только публичные маршруты сервиса, обычные учётные записи и идентификаторы объектов; реальные флаги, игровые токены и чужие адреса здесь не используются.
|
||||
|
||||
## Затронутый код до патча
|
||||
|
||||
Файл `src/lib.rs`: `cache_key`, `Server::new`, RPC-ветки `bind_source`, `edit_profile`, `run_export`, `delegate`, `read_manifest`, `generate_report`, HTTP-обработка `PUT /packages/{id}` и `GET /internal/summaries/{id}`, а также `fetch_bulletin`.
|
||||
|
||||
## Исправление
|
||||
|
||||
- Проверка владельца добавлена при привязке и чтении источника, смене корабля профиля и выполнении export job. При загрузке состояния удаляются cross-owner source aliases, а результаты export jobs с нарушенной цепочкой владения очищаются.
|
||||
- В cache key добавлен владелец; при загрузке состояния кэш безопасно перестраивается для существующих полётов.
|
||||
- Делегируемые права теперь обязаны быть подмножеством родительских; оба срока должны быть действующими, а дочерний срок не может превышать родительский. `read_manifest` проверяет expiry. При загрузке удаляются просроченные и legacy grants с правами, которые нельзя получить через штатный `grant_geometry`.
|
||||
- Internal summary требует одновременно loopback peer и importer key. `fetch_bulletin` канонизирует IPv4-mapped IPv6 после DNS-разрешения и запрещает loopback или unspecified адрес перед каждым соединением, включая redirects.
|
||||
- Любая повторная загрузка package сбрасывает approval. Перед распаковкой пакет снова проходит `validate_safe_tar`, а attachment обязан оставаться внутри индивидуального work-каталога.
|
||||
|
||||
## Проверки
|
||||
|
||||
- Docker image успешно собран командой `docker compose -f compose.yml build`.
|
||||
- На исходной версии все шесть классов проблем воспроизведены с синтетическими данными; second-order export дополнительно проверен отдельной последовательностью HTTP-запросов и после перезапуска контейнера.
|
||||
- На исправленной версии прошли 12 runtime-сценариев: штатные source/export/summary/package flows, запрет cross-user source/profile/cache, запрет повышения/просрочки grant, разрешённое subset-delegation, блокировка прямого internal endpoint и loopback-alias SSRF, блокировка замены одобренного TAR.
|
||||
- Дополнительная baseline-vs-patch проверка настоящих бинарников воспроизвела на `f09895d` SSRF через `0.0.0.0`, чтение через сохранённый cross-owner alias, legacy `manifest.read` grant и poisoned export result. Исправленная версия блокирует все четыре пути, сохраняя owner reads, легитимный alias, subset-delegation и корректный завершённый export job.
|
||||
- Отдельная synthetic runtime-проверка воспроизвела обход через IPv4-mapped IPv6 на `5d2407b`. После канонизации блокируются dotted/hex mapped loopback и mapped unspecified, включая переход через разрешённый redirect; обычный import с non-loopback HTTP endpoint сохраняет исходное содержимое.
|
||||
- `cargo check --locked` и `cargo test --locked` проходят; проект не содержит встроенных unit-тестов.
|
||||
- `git diff --check` проходит.
|
||||
|
||||
Ограничения: исходный проект не содержит автоматических тестов или checker; официальный Skipper/checker и сохранность реальных данных на vulnbox не проверялись. Патч не развёртывался; ветка предназначена для проверки и слияния через Gitea.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
||||
use orbit_ctf::Server;
|
||||
use std::net::TcpListener;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
let addr = std::env::var("LISTEN_ADDR").unwrap_or_else(|_| "127.0.0.1:8080".into());
|
||||
|
||||
let root = PathBuf::from(std::env::var("DATA_DIR").unwrap_or_else(|_| "./data".into()));
|
||||
|
||||
let listener = TcpListener::bind(&addr)?;
|
||||
|
||||
eprintln!("orbit-navigation-service listening on {addr}");
|
||||
|
||||
Server::new(root)?.serve(listener)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
# Local Orbital Navigation checker
|
||||
|
||||
`checker.py` exercises the real HTTP interface with Python's standard library.
|
||||
It uses five distinct random **synthetic** values, never a game flag. Run it
|
||||
only against an isolated local container and a separate test volume. The
|
||||
private Skipper checker is unavailable, so this is a deployment regression
|
||||
test, not a replica or proof of a scored `UP` round. Public Skipper logs show
|
||||
CHECK/PUT/GET status and duration but do not expose their internal requests.
|
||||
|
||||
## Run against a disposable container
|
||||
|
||||
From the repository root, choose a free loopback port (shown here as `18086`):
|
||||
|
||||
```sh
|
||||
TEST_ID="orbital-check-$(date +%s)-$$"
|
||||
STATE_FILE="/tmp/${TEST_ID}.json"
|
||||
docker build -t "${TEST_ID}:local" orbital_navigation
|
||||
docker volume create "${TEST_ID}-data"
|
||||
docker run -d --name "$TEST_ID" -p 127.0.0.1:18086:8080 \
|
||||
-v "${TEST_ID}-data:/data" "${TEST_ID}:local"
|
||||
|
||||
python3 orbital_navigation/tests/checker.py \
|
||||
--url http://127.0.0.1:18086 --state "$STATE_FILE" put
|
||||
docker restart "$TEST_ID"
|
||||
python3 orbital_navigation/tests/checker.py \
|
||||
--url http://127.0.0.1:18086 --state "$STATE_FILE" get
|
||||
python3 orbital_navigation/tests/checker.py \
|
||||
--url http://127.0.0.1:18086 --state "$STATE_FILE" check
|
||||
```
|
||||
|
||||
`put` refuses to overwrite an existing state file. Its atomic write creates
|
||||
the file with mode `0600`; it contains the two synthetic user tokens and the
|
||||
five markers, so keep it outside Git and do not share its contents. `get`
|
||||
reads the same records after a process restart with the same `/data` volume.
|
||||
`check` verifies cross-user denials, legitimate public geometry delegation,
|
||||
the observed `register` → `create_flight` → `grant_geometry` CHECK flow,
|
||||
package upload/approval/report, approval reset after replacement, and small
|
||||
malformed requests. It also checks a valid source alias, rejects loopback
|
||||
bulletin URLs, and re-reads the summary at the end. All commands print only
|
||||
pass/fail summaries.
|
||||
|
||||
To cover the normal `import_bulletin` → `import_result` path, start a tiny
|
||||
HTTP mock in the disposable container's network at an address that is **not**
|
||||
loopback from the service container. The service intentionally rejects
|
||||
`localhost`, `127.0.0.1`, and their aliases. Then add `--import-url` and
|
||||
`--import-contains` before `put` and `check`. `put` stores the imported content
|
||||
in its private state file; `get` confirms it still exists after restart, while
|
||||
`check` verifies a fresh import and cross-user denial. Choose a free mock port:
|
||||
Docker can already be forwarding a port even when another host process appears
|
||||
to listen on it. Keep this mock local; the service sends its importer header
|
||||
to the specified server.
|
||||
|
||||
To remove **only this disposable test instance** after finishing:
|
||||
|
||||
```sh
|
||||
docker rm -f "$TEST_ID"
|
||||
docker volume rm "${TEST_ID}-data"
|
||||
rm -f "$STATE_FILE"
|
||||
```
|
||||
|
||||
`all` runs `put`, `get`, and `check` in one process, but the separate commands
|
||||
above are needed to test old data across a restart. This checker does not
|
||||
cover the private Skipper PUT/GET choice of flag slot, the normal bulletin
|
||||
import unless a local mock URL is supplied, load limits, or the actual game
|
||||
route. Confirm live status from Skipper after any deployment.
|
||||
@@ -0,0 +1,441 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Synthetic, local-only functional checker for Orbital Navigation.
|
||||
|
||||
This does not reproduce the private Skipper checker. Keep its state file outside
|
||||
Git; it contains test bearer tokens and synthetic marker values.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import stat
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
class CheckFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, base_url: str, timeout: float):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
|
||||
def request(
|
||||
self,
|
||||
path: str,
|
||||
*,
|
||||
method: str = "GET",
|
||||
body: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> tuple[int, bytes]:
|
||||
request = Request(
|
||||
self.base_url + path,
|
||||
data=body,
|
||||
headers=headers or {},
|
||||
method=method,
|
||||
)
|
||||
try:
|
||||
with urlopen(request, timeout=self.timeout) as response:
|
||||
return response.status, response.read(2_100_001)
|
||||
except HTTPError as error:
|
||||
return error.code, error.read(2_100_001)
|
||||
except (URLError, TimeoutError, OSError) as error:
|
||||
raise CheckFailure(f"HTTP {method} {path}: connection or timeout failure") from error
|
||||
|
||||
def wait_ready(self) -> None:
|
||||
deadline = time.monotonic() + 6
|
||||
while True:
|
||||
try:
|
||||
status, _ = self.request("/does-not-exist")
|
||||
if status == 404:
|
||||
return
|
||||
raise CheckFailure("service readiness probe returned an unexpected status")
|
||||
except CheckFailure as error:
|
||||
if "connection or timeout failure" not in str(error) or time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
|
||||
def rpc_response(self, action: str, token: str | None = None, **fields: object) -> tuple[int, dict]:
|
||||
payload: dict[str, object] = {"action": action, **fields}
|
||||
if token is not None:
|
||||
payload["token"] = token
|
||||
status, raw = self.request(
|
||||
"/rpc",
|
||||
method="POST",
|
||||
body=json.dumps(payload, separators=(",", ":")).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
envelope = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError) as error:
|
||||
raise CheckFailure(f"RPC {action}: response is not JSON") from error
|
||||
if not isinstance(envelope, dict) or not isinstance(envelope.get("ok"), bool):
|
||||
raise CheckFailure(f"RPC {action}: invalid response envelope")
|
||||
return status, envelope
|
||||
|
||||
def rpc(self, action: str, token: str | None = None, **fields: object) -> dict:
|
||||
status, envelope = self.rpc_response(action, token, **fields)
|
||||
result = envelope.get("result")
|
||||
if status != 200 or not envelope["ok"] or not isinstance(result, dict):
|
||||
raise CheckFailure(f"RPC {action}: expected successful result, got HTTP {status}")
|
||||
return result
|
||||
|
||||
def rejected(self, action: str, token: str | None, reason: str, **fields: object) -> None:
|
||||
status, envelope = self.rpc_response(action, token, **fields)
|
||||
if status != 400 or envelope["ok"] or reason not in str(envelope.get("error", "")):
|
||||
raise CheckFailure(f"RPC {action}: expected rejection ({reason})")
|
||||
|
||||
def upload(self, package_id: str, token: str | None, content: bytes) -> int:
|
||||
headers = {"Content-Type": "application/octet-stream"}
|
||||
if token is not None:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
status, _ = self.request(
|
||||
f"/packages/{package_id}/content", method="PUT", body=content, headers=headers
|
||||
)
|
||||
return status
|
||||
|
||||
|
||||
def marker(kind: str) -> str:
|
||||
# Intentionally not a game-flag-shaped value.
|
||||
return f"LOCAL_CHECK_{kind}_{secrets.token_hex(16)}"
|
||||
|
||||
|
||||
def value(result: dict, key: str, action: str) -> str:
|
||||
item = result.get(key)
|
||||
if not isinstance(item, str) or not item:
|
||||
raise CheckFailure(f"RPC {action}: missing {key}")
|
||||
return item
|
||||
|
||||
|
||||
def require(condition: bool, description: str) -> None:
|
||||
if not condition:
|
||||
raise CheckFailure(description)
|
||||
|
||||
|
||||
def save_state(path: Path, data: dict) -> None:
|
||||
if path.exists() or path.is_symlink():
|
||||
raise CheckFailure("state file already exists; choose a fresh path")
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
||||
try:
|
||||
os.fchmod(descriptor, 0o600)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
json.dump(data, stream, sort_keys=True)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
def load_state(path: Path) -> dict:
|
||||
try:
|
||||
mode = path.stat().st_mode
|
||||
if not stat.S_ISREG(mode) or mode & 0o077:
|
||||
raise CheckFailure("state file must be a private regular file (mode 0600)")
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as error:
|
||||
raise CheckFailure("cannot load state file") from error
|
||||
if not isinstance(data, dict) or data.get("schema") != 1:
|
||||
raise CheckFailure("unsupported state file")
|
||||
for key in (
|
||||
"owner_token", "other_token", "ship_id", "profile_id", "job_id",
|
||||
"flight_id", "summary_id", "package_id", "message", "manifest",
|
||||
"summary", "navigation", "package_report",
|
||||
):
|
||||
if not isinstance(data.get(key), str) or not data[key]:
|
||||
raise CheckFailure("incomplete state file")
|
||||
if ("import_id" in data) != ("import_content" in data):
|
||||
raise CheckFailure("incomplete imported bulletin state")
|
||||
for key in ("import_id", "import_content"):
|
||||
if key in data and (not isinstance(data[key], str) or not data[key]):
|
||||
raise CheckFailure("incomplete imported bulletin state")
|
||||
return data
|
||||
|
||||
|
||||
def put(
|
||||
client: Client,
|
||||
path: Path,
|
||||
import_url: str | None = None,
|
||||
import_contains: str | None = None,
|
||||
) -> dict:
|
||||
if path.exists() or path.is_symlink():
|
||||
raise CheckFailure("state file already exists; choose a fresh path")
|
||||
|
||||
owner = value(client.rpc("register"), "token", "register")
|
||||
other = value(client.rpc("register"), "token", "register")
|
||||
ship = value(client.rpc("create_ship", owner), "ship_id", "create_ship")
|
||||
message = marker("MESSAGE")
|
||||
manifest = marker("MANIFEST")
|
||||
summary = marker("SUMMARY")
|
||||
navigation = marker("NAVIGATION")
|
||||
package_report = marker("PACKAGE_REPORT")
|
||||
|
||||
client.rpc("post_message", owner, ship_id=ship, message=message)
|
||||
profile = value(
|
||||
client.rpc("create_profile", owner, ship_id=ship), "profile_id", "create_profile"
|
||||
)
|
||||
job = value(
|
||||
client.rpc("create_export", owner, profile_id=profile), "job_id", "create_export"
|
||||
)
|
||||
exported = client.rpc("run_export", owner, job_id=job)
|
||||
require(message in exported.get("messages", []), "run_export omitted ship message")
|
||||
|
||||
flight = value(
|
||||
client.rpc(
|
||||
"create_flight",
|
||||
owner,
|
||||
geometry="local-check-" + secrets.token_hex(8),
|
||||
map_version="1",
|
||||
options="default",
|
||||
manifest=manifest,
|
||||
navigation=navigation,
|
||||
),
|
||||
"flight_id",
|
||||
"create_flight",
|
||||
)
|
||||
summary_id = value(
|
||||
client.rpc("create_summary", owner, content=summary),
|
||||
"summary_id",
|
||||
"create_summary",
|
||||
)
|
||||
package_id = value(client.rpc("create_package", owner), "package_id", "create_package")
|
||||
require(
|
||||
client.upload(package_id, owner, regular_tar(package_report)) == 200,
|
||||
"package PUT failed",
|
||||
)
|
||||
client.rpc("approve_package", owner, package_id=package_id)
|
||||
state = {
|
||||
"schema": 1,
|
||||
"owner_token": owner,
|
||||
"other_token": other,
|
||||
"ship_id": ship,
|
||||
"profile_id": profile,
|
||||
"job_id": job,
|
||||
"flight_id": flight,
|
||||
"summary_id": summary_id,
|
||||
"package_id": package_id,
|
||||
"message": message,
|
||||
"manifest": manifest,
|
||||
"summary": summary,
|
||||
"navigation": navigation,
|
||||
"package_report": package_report,
|
||||
}
|
||||
if import_url is not None:
|
||||
imported = client.rpc("import_bulletin", owner, url=import_url)
|
||||
content = value(imported, "content", "import_bulletin")
|
||||
require(import_contains is not None and import_contains in content, "bulletin content mismatch")
|
||||
state["import_id"] = value(imported, "import_id", "import_bulletin")
|
||||
state["import_content"] = content
|
||||
save_state(path, state)
|
||||
get(client, state)
|
||||
return state
|
||||
|
||||
|
||||
def get(client: Client, state: dict) -> None:
|
||||
owner = state["owner_token"]
|
||||
source = client.rpc("read_source_messages", owner, source_id=state["ship_id"])
|
||||
require(state["message"] in source.get("messages", []), "old ship message missing")
|
||||
|
||||
exported = client.rpc("export_result", owner, job_id=state["job_id"])
|
||||
require(exported.get("state") == "DONE", "old export job is not DONE")
|
||||
require(state["message"] in exported.get("messages", []), "old export message missing")
|
||||
|
||||
report = client.rpc("report", owner, flight_id=state["flight_id"])
|
||||
require(report.get("manifest") == state["manifest"], "old flight manifest missing")
|
||||
manifest = client.rpc("read_manifest", owner, flight_id=state["flight_id"])
|
||||
require(manifest.get("manifest") == state["manifest"], "old direct manifest read failed")
|
||||
|
||||
summary = client.rpc("read_summary", owner, summary_id=state["summary_id"])
|
||||
require(summary.get("content") == state["summary"], "old summary missing")
|
||||
|
||||
navigation = client.rpc("read_navigation", owner, flight_id=state["flight_id"])
|
||||
require(navigation.get("navigation") == state["navigation"], "old navigation missing")
|
||||
|
||||
package = client.rpc(
|
||||
"generate_report", owner, package_id=state["package_id"], attachment="report.txt"
|
||||
)
|
||||
require(package.get("report") == state["package_report"], "old package report missing")
|
||||
if "import_id" in state:
|
||||
imported = client.rpc("import_result", owner, import_id=state["import_id"])
|
||||
require(imported.get("content") == state["import_content"], "old imported bulletin missing")
|
||||
|
||||
|
||||
def regular_tar(content: str) -> bytes:
|
||||
raw = content.encode()
|
||||
output = io.BytesIO()
|
||||
with tarfile.open(fileobj=output, mode="w") as archive:
|
||||
item = tarfile.TarInfo("report.txt")
|
||||
item.size = len(raw)
|
||||
item.mode = 0o600
|
||||
archive.addfile(item, io.BytesIO(raw))
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def check(client: Client, state: dict, import_url: str | None = None, import_contains: str | None = None) -> None:
|
||||
owner, other = state["owner_token"], state["other_token"]
|
||||
ship, flight = state["ship_id"], state["flight_id"]
|
||||
|
||||
# The observed Skipper CHECK sequence uses these three actions in order.
|
||||
probe_owner = value(client.rpc("register"), "token", "register")
|
||||
probe_flight = value(
|
||||
client.rpc(
|
||||
"create_flight", probe_owner, geometry="public-check",
|
||||
map_version="1", options="default", manifest="synthetic-public-check",
|
||||
navigation="synthetic-public-check",
|
||||
),
|
||||
"flight_id", "create_flight",
|
||||
)
|
||||
value(
|
||||
client.rpc("grant_geometry", probe_owner, flight_id=probe_flight),
|
||||
"grant_id", "grant_geometry",
|
||||
)
|
||||
|
||||
client.rejected("read_source_messages", other, "forbidden", source_id=ship)
|
||||
client.rejected("export_result", other, "forbidden", job_id=state["job_id"])
|
||||
client.rejected("report", other, "forbidden", flight_id=flight)
|
||||
client.rejected("read_summary", other, "forbidden", summary_id=state["summary_id"])
|
||||
client.rejected("read_navigation", other, "forbidden", flight_id=flight)
|
||||
client.rejected(
|
||||
"generate_report", other, "forbidden",
|
||||
package_id=state["package_id"], attachment="report.txt",
|
||||
)
|
||||
if "import_id" in state:
|
||||
client.rejected("import_result", other, "forbidden", import_id=state["import_id"])
|
||||
|
||||
# Former alias/profile chains must not connect another user to this ship.
|
||||
client.rejected("bind_source", other, "forbidden", source_id=ship.upper())
|
||||
own_alias = f" {ship.upper()} "
|
||||
status, envelope = client.rpc_response("bind_source", owner, source_id=own_alias)
|
||||
if status != 200 or not envelope["ok"]:
|
||||
require(
|
||||
status == 400 and envelope.get("error") == "source exists",
|
||||
"valid own source alias could not be created or reused",
|
||||
)
|
||||
aliased = client.rpc("read_source_messages", owner, source_id=own_alias)
|
||||
require(state["message"] in aliased.get("messages", []), "valid own source alias broke")
|
||||
own_ship = value(client.rpc("create_ship", other), "ship_id", "create_ship")
|
||||
own_profile = value(
|
||||
client.rpc("create_profile", other, ship_id=own_ship), "profile_id", "create_profile"
|
||||
)
|
||||
client.rejected(
|
||||
"edit_profile", other, "forbidden", profile_id=own_profile, ship_id=ship
|
||||
)
|
||||
|
||||
public = client.rpc("flight_public", other, flight_id=flight)
|
||||
require(isinstance(public.get("geometry"), str), "public flight view broke")
|
||||
parent = value(client.rpc("grant_geometry", owner, flight_id=flight), "grant_id", "grant_geometry")
|
||||
expires = int(time.time()) + 300
|
||||
client.rejected(
|
||||
"delegate", other, "invalid delegation", parent_id=parent,
|
||||
rights=["manifest.read"], expires=expires,
|
||||
)
|
||||
subset = value(
|
||||
client.rpc("delegate", other, parent_id=parent, rights=["geometry.read"], expires=expires),
|
||||
"grant_id", "delegate",
|
||||
)
|
||||
client.rejected("read_manifest", other, "forbidden", flight_id=flight, grant_id=subset)
|
||||
|
||||
client.rejected(
|
||||
"import_bulletin", other, "internal source forbidden",
|
||||
url="http://127.0.0.1:8080/internal/summaries/local-check",
|
||||
)
|
||||
if import_url is not None:
|
||||
imported = client.rpc("import_bulletin", other, url=import_url)
|
||||
import_id = value(imported, "import_id", "import_bulletin")
|
||||
content = value(imported, "content", "import_bulletin")
|
||||
require(import_contains is not None and import_contains in content, "bulletin content mismatch")
|
||||
reread = client.rpc("import_result", other, import_id=import_id)
|
||||
require(reread.get("content") == content, "stored import result mismatch")
|
||||
client.rejected("import_result", owner, "forbidden", import_id=import_id)
|
||||
|
||||
package = value(client.rpc("create_package", other), "package_id", "create_package")
|
||||
first, second = marker("REPORT1"), marker("REPORT2")
|
||||
require(client.upload(package, other, regular_tar(first)) == 200, "package PUT failed")
|
||||
require(client.upload(package, None, regular_tar(first)) == 400, "anonymous package PUT accepted")
|
||||
require(client.upload(package, owner, regular_tar(first)) == 400, "cross-user package PUT accepted")
|
||||
client.rpc("approve_package", other, package_id=package)
|
||||
result = client.rpc("generate_report", other, package_id=package, attachment="report.txt")
|
||||
require(result.get("report") == first, "approved report content mismatch")
|
||||
client.rejected(
|
||||
"generate_report", owner, "forbidden", package_id=package, attachment="report.txt"
|
||||
)
|
||||
require(client.upload(package, other, regular_tar(second)) == 200, "replacement PUT failed")
|
||||
client.rejected(
|
||||
"generate_report", other, "package not approved",
|
||||
package_id=package, attachment="report.txt",
|
||||
)
|
||||
client.rpc("approve_package", other, package_id=package)
|
||||
result = client.rpc("generate_report", other, package_id=package, attachment="report.txt")
|
||||
require(result.get("report") == second, "replacement report content mismatch")
|
||||
|
||||
invalid_package = value(
|
||||
client.rpc("create_package", other), "package_id", "create_package"
|
||||
)
|
||||
require(client.upload(invalid_package, other, b"not a tar") == 200, "invalid TAR upload failed")
|
||||
client.rejected("approve_package", other, "empty package", package_id=invalid_package)
|
||||
|
||||
status, raw = client.request(
|
||||
"/rpc", method="POST", body=b"{", headers={"Content-Type": "application/json"}
|
||||
)
|
||||
require(status == 400 and b'"ok":false' in raw, "malformed JSON was not rejected")
|
||||
client.rejected("read_summary", None, "missing token", summary_id=state["summary_id"])
|
||||
client.rejected("unknown_check_action", owner, "unknown action")
|
||||
status, _ = client.request("/does-not-exist")
|
||||
require(status == 404, "unknown route did not return 404")
|
||||
final_summary = client.rpc("read_summary", owner, summary_id=state["summary_id"])
|
||||
require(final_summary.get("content") == state["summary"], "final summary read failed")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--url", default="http://127.0.0.1:18086", help="isolated local service URL")
|
||||
parser.add_argument("--state", required=True, type=Path, help="private state file outside Git")
|
||||
parser.add_argument("--timeout", default=3.0, type=float, help="per-request timeout in seconds")
|
||||
parser.add_argument("--import-url", help="optional non-loopback local bulletin mock URL")
|
||||
parser.add_argument("--import-contains", help="expected substring from that mock bulletin")
|
||||
parser.add_argument("command", choices=("put", "get", "check", "all"))
|
||||
args = parser.parse_args()
|
||||
if args.timeout <= 0:
|
||||
parser.error("--timeout must be positive")
|
||||
if not args.url.startswith(("http://", "https://")):
|
||||
parser.error("--url must be HTTP(S)")
|
||||
if bool(args.import_url) != bool(args.import_contains):
|
||||
parser.error("--import-url and --import-contains must be supplied together")
|
||||
if args.import_url and not args.import_url.startswith("http://"):
|
||||
parser.error("--import-url must be an HTTP URL")
|
||||
client = Client(args.url, args.timeout)
|
||||
try:
|
||||
client.wait_ready()
|
||||
if args.command in ("put", "all"):
|
||||
state = put(client, args.state, args.import_url, args.import_contains)
|
||||
print("PASS put: five synthetic values stored and read")
|
||||
else:
|
||||
state = load_state(args.state)
|
||||
if args.command in ("get", "all"):
|
||||
get(client, state)
|
||||
print("PASS get: stored values, export, and package survived")
|
||||
if args.command in ("check", "all"):
|
||||
check(client, state, args.import_url, args.import_contains)
|
||||
print("PASS check: ownership, delegation, package, malformed requests")
|
||||
return 0
|
||||
except CheckFailure as error:
|
||||
print(f"FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user