Skip to content

Commit f7fb9fa

Browse files
agorischekCopilot
andauthored
Decode the runner API's responses whole, against TypeBox schemas (#105)
* Decode the runner API's responses whole, against TypeBox schemas The Inspector's response decoders checked an outer object and array, then asserted the full type with `as unknown as`: an adopt preview with `files: [null]`, an explore candidate missing a field or a sweep cell of the wrong type reached UI code, which failed there instead of at the boundary. The local runner's API responses the Inspector decodes now have TypeBox schemas in `packages/schemas/src/runner` (exported as `@githubnext/projections-schemas/runner`; internal and unversioned), which give the Inspector's types and `decodeRunnerResponse`, whose `RunnerResponseError` names the request and the JSON pointer. The generated `internal/runner-api.json` holds the Rust service to them: the service tests check each response they receive against it, refusing undeclared fields. Saved documents and trial definitions stay opaque past their envelope. Code review, finding 11. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Document the runner API's exported types Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Runner API: declare a per-file explore candidate's basis.file Explore's per-file candidates (one per workflow) name their file in basis.file, which the schema omitted, so the strict conformance check refused them. Declare it, regenerate internal/runner-api.json, and check a workflow's candidate against the schema. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent e5df8a8 commit f7fb9fa

20 files changed

Lines changed: 1055 additions & 214 deletions

File tree

‎docs/contracts.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,42 @@ and the catalog entry for them would be:
109109
and for their tests, `comparator-tests/v0.json`, matching
110110
`*.comparator.test.yaml` and `*.comparator.test.yml`.
111111

112+
### Schema-owned contracts
113+
114+
TypeBox, in `packages/schemas`, is the one schema system for the contracts this
115+
repository owns: each schema provides the JSON Schema, the TypeScript type and
116+
the runtime validator, so a hand-written type never stands in for a checked one.
117+
118+
- **Published contracts**, `src/typebox`: the versioned documents above, with
119+
their `$id`s and reference pages.
120+
- **The local runner's API**, `src/runner`, exported as
121+
`@githubnext/projections-schemas/runner`: the responses of the Inspector
122+
service (`projections view` and [`serve --stdio`](runner/stdio-backend.md))
123+
that its clients decode. It is internal and unversioned, never published: the
124+
runner and its clients ship from the same commit. Its generated schema is
125+
`packages/schemas/internal/runner-api.json`, outside the published set.
126+
`decodeRunnerResponse(name, value)` checks a response whole, nested entries
127+
included, and returns it typed, or throws a `RunnerResponseError` that names
128+
the request and the JSON pointer of the value that doesn't match. It uses
129+
TypeBox's interpreting checker, which needs no `eval` and so runs under the
130+
Inspector's content security policy. Clients accept properties a schema
131+
doesn't declare, so a runner can add a field without breaking them.
132+
- **Documents another boundary validates** are opaque in the runner API, which
133+
checks only the envelope its clients read: a saved document's `format` and
134+
`version` (the CLI validated the document when it loaded it), and an explore
135+
candidate's trial definition.
136+
137+
**Rust conformance.** The Rust service has no generated types. Instead, its
138+
tests (`packages/cli/tests/service/conformance.rs`) check every runner API
139+
response they receive against `internal/runner-api.json`, more strictly than the
140+
clients: a property the schema doesn't declare fails. Changing a response
141+
therefore starts in the TypeBox source; regenerate the schema, and the service
142+
tests then hold the Rust side to it.
143+
144+
Host-to-renderer and renderer-to-host frame validation is asymmetric on purpose
145+
(see [renderer frames](contracts/renderer-frames.md)) and stays outside this
146+
rule.
147+
112148
## Pages
113149

114150
Each page specifies one family of documents; the rules that apply to all of them

‎docs/runner/stdio-backend.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,10 @@ and thumbnail renders.
9292

9393
## Requests
9494

95+
The responses the Inspector decodes have TypeBox schemas, and the service tests
96+
hold these responses to them
97+
([schema-owned contracts](../contracts.md#schema-owned-contracts)).
98+
9599
- `GET /api/definitions?ref=REV[&include=ID]`:
96100
`{"definitions", "policies", "ref", "commit"?, "executionAuthorized", "invalid"}`;
97101
`commit` is the full commit `ref` names when it isn't `working-tree` (a

‎packages/cli/tests/service/authoring.rs‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ use std::{fs, path::Path};
44

55
use serde_json::{Value, json};
66

7-
use crate::common::{Fixture, post};
7+
use crate::{
8+
common::{Fixture, post},
9+
conformance::conforms,
10+
};
811

912
#[tokio::test]
1013
async fn saving_parts_previews_then_writes_the_definition_with_trust() {
@@ -18,6 +21,7 @@ async fn saving_parts_previews_then_writes_the_definition_with_trust() {
1821
.await;
1922
assert_eq!(preview.status, 200);
2023
let preview = preview.json();
24+
conforms("definitionSave", &preview);
2125
assert_eq!(preview["path"], ".projections/example.json");
2226
assert_eq!(preview["written"], false);
2327
assert_eq!(preview["before"], original.as_str());
@@ -43,6 +47,7 @@ async fn saving_parts_previews_then_writes_the_definition_with_trust() {
4347
)
4448
.await;
4549
assert_eq!(saved.status, 200);
50+
conforms("definitionSave", &saved.json());
4651
assert_eq!(saved.json()["written"], true);
4752
assert_eq!(fs::read_to_string(&file).unwrap(), preview["after"].as_str().unwrap());
4853
let definitions = fixture.get("/api/definitions?ref=working-tree").await.json();
@@ -81,6 +86,23 @@ async fn saving_parts_previews_then_writes_the_definition_with_trust() {
8186
assert_eq!(refused.status, 403);
8287
}
8388

89+
#[tokio::test]
90+
async fn exploring_proposes_a_conforming_candidate_per_workflow() {
91+
let fixture = Fixture::new(true, false, false).await;
92+
let workflows = fixture.root.join("repo/.github/workflows");
93+
fs::create_dir_all(&workflows).unwrap();
94+
fs::write(workflows.join("ci.yml"), "on: push\njobs: {}\n").unwrap();
95+
let candidates = fixture.get("/api/explore").await.json();
96+
conforms("explore", &candidates);
97+
let workflow = candidates["candidates"]
98+
.as_array()
99+
.unwrap()
100+
.iter()
101+
.find(|candidate| candidate["extractor"] == "github-actions-jobs")
102+
.expect("a candidate for the workflow");
103+
assert_eq!(workflow["basis"]["file"], ".github/workflows/ci.yml");
104+
}
105+
84106
#[tokio::test]
85107
async fn adopting_previews_then_writes_with_trust() {
86108
let fixture = Fixture::new(true, false, false).await;
@@ -95,6 +117,7 @@ async fn adopting_previews_then_writes_with_trust() {
95117
};
96118
// The fixture repository's files suggest the file map, among others.
97119
let candidates = fixture.get("/api/explore").await.json();
120+
conforms("explore", &candidates);
98121
assert_eq!(candidates["session"], false);
99122
assert!(
100123
candidates["candidates"]
@@ -106,6 +129,7 @@ async fn adopting_previews_then_writes_with_trust() {
106129
let preview = write("/api/adopt", json!({"projections": ["repository-map"], "dryRun": true})).await;
107130
assert_eq!(preview.status, 200);
108131
let preview = preview.json();
132+
conforms("adopt", &preview);
109133
// The definitions directory the repository already uses.
110134
assert_eq!(preview["files"][0]["path"], ".projections/repository-map.json");
111135
assert!(!repo.join(".projections/repository-map.json").exists());
@@ -118,8 +142,10 @@ async fn adopting_previews_then_writes_with_trust() {
118142
)
119143
.await;
120144
assert_eq!(written.status, 200);
145+
conforms("adopt", &written.json());
121146
assert!(repo.join(".projections/repository-map.json").is_file());
122147
let candidates = fixture.get("/api/explore").await.json();
148+
conforms("explore", &candidates);
123149
let map = candidates["candidates"]
124150
.as_array()
125151
.unwrap()

‎packages/cli/tests/service/changes.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::fs;
44

55
use projections_cli::scaffold;
66

7-
use crate::common::Fixture;
7+
use crate::{common::Fixture, conformance::conforms};
88

99
#[tokio::test]
1010
async fn working_tree_changes_name_the_projection_parts_that_changed() {
@@ -14,6 +14,7 @@ async fn working_tree_changes_name_the_projection_parts_that_changed() {
1414
// Generations start at 1, so this answers at once with the current one.
1515
let first = fixture.request("GET", "/api/changes?since=0", fixture.auth(), b"").await;
1616
assert_eq!(first.status, 200);
17+
conforms("changes", &first.json());
1718
let start = first.json()["generation"].as_u64().unwrap();
1819
// The watcher's first state was taken when the server started, so the edit
1920
// is a change whenever the next poll runs. Long-poll until every expected
@@ -30,6 +31,7 @@ async fn working_tree_changes_name_the_projection_parts_that_changed() {
3031
.request("GET", &format!("/api/changes?since={since}"), fixture.auth(), b"")
3132
.await
3233
.json();
34+
conforms("changes", &changed);
3335
assert_eq!(changed["complete"], true);
3436
let generation = changed["generation"].as_u64().unwrap();
3537
assert!(generation >= since);
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
//! The runner API's conformance: each response the service writes for a
2+
//! request its clients decode with `@githubnext/projections-schemas/runner`
3+
//! matches that response's schema in the generated
4+
//! `packages/schemas/internal/runner-api.json`, so the Rust service and the
5+
//! TypeScript decoders can't drift apart.
6+
//!
7+
//! It is stricter than the clients: a property the schema doesn't declare
8+
//! fails it unless the schema allows `additionalProperties`, so a field the
9+
//! service adds is declared, and typed, in the TypeBox source first. It
10+
//! supports only the keywords the generator writes and refuses any other, so
11+
//! a schema can't silently go unchecked.
12+
13+
use serde_json::{Map, Value, json};
14+
15+
const SCHEMA: &str = include_str!("../../../schemas/internal/runner-api.json");
16+
17+
/// The keywords the check applies, and the annotations it ignores.
18+
const KEYWORDS: &[&str] = &[
19+
"type",
20+
"required",
21+
"properties",
22+
"additionalProperties",
23+
"items",
24+
"anyOf",
25+
"enum",
26+
"const",
27+
"minimum",
28+
"maximum",
29+
"title",
30+
"description",
31+
"x-request",
32+
];
33+
34+
/// Asserts that `value` is a valid `name` response (`adopt`, `explore`, …).
35+
pub(super) fn conforms(name: &str, value: &Value) {
36+
let problems = problems(name, value);
37+
assert!(
38+
problems.is_empty(),
39+
"the {name} response doesn't match its schema in packages/schemas/internal/runner-api.json:\n{}\n{value:#}",
40+
problems.join("\n")
41+
);
42+
}
43+
44+
/// Where and why `value` isn't a valid `name` response.
45+
fn problems(name: &str, value: &Value) -> Vec<String> {
46+
let schema: Value = serde_json::from_str(SCHEMA).unwrap();
47+
let definition = &schema["$defs"][name];
48+
assert!(definition.is_object(), "runner-api.json has no {name} response");
49+
let mut problems = Vec::new();
50+
check(definition, value, "", &mut problems);
51+
problems
52+
}
53+
54+
fn check(schema: &Value, value: &Value, pointer: &str, problems: &mut Vec<String>) {
55+
let schema = schema.as_object().expect("a schema is an object");
56+
if let Some(keyword) = schema.keys().find(|keyword| !KEYWORDS.contains(&keyword.as_str())) {
57+
panic!("the conformance check doesn't support {keyword} (at {pointer})");
58+
}
59+
assert!(
60+
schema.get("type") == Some(&json!("object"))
61+
|| !["properties", "required", "additionalProperties"]
62+
.iter()
63+
.any(|keyword| schema.contains_key(*keyword)),
64+
"the conformance check applies object keywords only with type object (at {pointer})"
65+
);
66+
let at = if pointer.is_empty() { "the root" } else { pointer };
67+
if let Some(alternatives) = schema.get("anyOf").and_then(Value::as_array)
68+
&& !alternatives.iter().any(|alternative| {
69+
let mut nested = Vec::new();
70+
check(alternative, value, pointer, &mut nested);
71+
nested.is_empty()
72+
})
73+
{
74+
problems.push(format!("{at}: matches none of {}", Value::Array(alternatives.clone())));
75+
}
76+
if let Some(kind) = schema.get("type").and_then(Value::as_str)
77+
&& !is(kind, value)
78+
{
79+
problems.push(format!("{at}: {value} is not {kind}"));
80+
return;
81+
}
82+
if let Some(constant) = schema.get("const")
83+
&& value != constant
84+
{
85+
problems.push(format!("{at}: {value} is not {constant}"));
86+
}
87+
if let Some(values) = schema.get("enum").and_then(Value::as_array)
88+
&& !values.contains(value)
89+
{
90+
problems.push(format!("{at}: {value} is not one of {}", Value::Array(values.clone())));
91+
}
92+
if let (Some(minimum), Some(number)) = (schema.get("minimum").and_then(Value::as_f64), value.as_f64())
93+
&& number < minimum
94+
{
95+
problems.push(format!("{at}: {number} is less than {minimum}"));
96+
}
97+
if let (Some(maximum), Some(number)) = (schema.get("maximum").and_then(Value::as_f64), value.as_f64())
98+
&& number > maximum
99+
{
100+
problems.push(format!("{at}: {number} is more than {maximum}"));
101+
}
102+
if let Some(object) = value.as_object()
103+
&& schema.get("type") == Some(&json!("object"))
104+
{
105+
object_problems(schema, object, pointer, problems);
106+
}
107+
if let (Some(items), Some(array)) = (schema.get("items"), value.as_array()) {
108+
for (index, item) in array.iter().enumerate() {
109+
check(items, item, &format!("{pointer}/{index}"), problems);
110+
}
111+
}
112+
}
113+
114+
fn object_problems(schema: &Map<String, Value>, object: &Map<String, Value>, pointer: &str, problems: &mut Vec<String>) {
115+
let at = if pointer.is_empty() { "the root" } else { pointer };
116+
for name in schema.get("required").and_then(Value::as_array).into_iter().flatten() {
117+
let name = name.as_str().unwrap();
118+
if !object.contains_key(name) {
119+
problems.push(format!("{at}: {name} is missing"));
120+
}
121+
}
122+
let empty = Map::new();
123+
let properties = schema.get("properties").and_then(Value::as_object).unwrap_or(&empty);
124+
for (name, item) in object {
125+
let path = format!("{pointer}/{}", name.replace('~', "~0").replace('/', "~1"));
126+
match (properties.get(name), schema.get("additionalProperties")) {
127+
(Some(property), _) => check(property, item, &path, problems),
128+
(None, Some(Value::Bool(true))) => {}
129+
(None, Some(additional @ Value::Object(_))) => check(additional, item, &path, problems),
130+
(None, _) => problems.push(format!("{path}: is not declared in the schema")),
131+
}
132+
}
133+
}
134+
135+
fn is(kind: &str, value: &Value) -> bool {
136+
match kind {
137+
"object" => value.is_object(),
138+
"array" => value.is_array(),
139+
"string" => value.is_string(),
140+
"boolean" => value.is_boolean(),
141+
"null" => value.is_null(),
142+
"number" => value.is_number(),
143+
"integer" => value.is_i64() || value.is_u64() || value.as_f64().is_some_and(|number| number.fract() == 0.0),
144+
_ => panic!("the conformance check doesn't support type {kind}"),
145+
}
146+
}
147+
148+
#[test]
149+
fn the_conformance_check_refuses_malformed_nested_entries_and_undeclared_fields() {
150+
let preview = json!({"files": [], "digest": "sha256:00", "written": false});
151+
assert_eq!(problems("adopt", &preview), Vec::<String>::new());
152+
let mut nested = preview.clone();
153+
nested["files"] = json!([null]);
154+
assert_eq!(problems("adopt", &nested), ["/files/0: null is not object"]);
155+
let mut undeclared = preview.clone();
156+
undeclared["extra"] = json!(1);
157+
assert_eq!(problems("adopt", &undeclared), ["/extra: is not declared in the schema"]);
158+
// An opaque document is checked only by its envelope.
159+
let document = json!({"document": {"format": "projections.extraction", "version": 0, "extraction": {}}});
160+
assert_eq!(problems("document", &document), Vec::<String>::new());
161+
}

‎packages/cli/tests/service/fixtures.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ use serde_json::{Value, json};
1414
use tokio::time::{sleep, timeout};
1515
use uuid::Uuid;
1616

17-
use crate::common::{Fixture, HttpResponse, assets};
17+
use crate::{
18+
common::{Fixture, HttpResponse, assets},
19+
conformance::conforms,
20+
};
1821

1922
const PROBE: &str = "globalThis.projectionsProbe = 0;";
2023

@@ -161,9 +164,12 @@ async fn fixtures_mode_serves_scenarios_and_renderers_without_a_repository() {
161164
let renderers = fixture.get("/api/renderers").await.json();
162165
assert_eq!(renderers["renderers"][0]["name"], "basic");
163166
assert_eq!(renderers["customRendererBase"], Value::Null);
164-
assert_eq!(fixture.get("/api/document").await.json()["document"], Value::Null);
167+
let document = fixture.get("/api/document").await.json();
168+
conforms("document", &document);
169+
assert_eq!(document["document"], Value::Null);
165170
let started = std::time::Instant::now();
166171
let changes = fixture.get("/api/fixtures/changes?since=0").await;
172+
conforms("fixturesChanges", &changes.json());
167173
assert_eq!(changes.json(), json!({"generation": 1}));
168174
assert!(started.elapsed() < Duration::from_secs(2));
169175
assert_eq!(fixture.get("/api/fixtures/changes").await.status, 400);

0 commit comments

Comments
 (0)