462 lines
17 KiB
Rust
462 lines
17 KiB
Rust
use super::*;
|
|
|
|
#[test]
|
|
fn unused_model_sources_are_checked_without_generating_rest_routes() {
|
|
let root = project(
|
|
"unused-rest-bindings",
|
|
"text() (out:Text) {out=\"value\"}",
|
|
"",
|
|
);
|
|
let model = root.join("module/demo/service/data/main.dever");
|
|
for source in [
|
|
"title:Text create = missing",
|
|
"title:Text replace = 1",
|
|
"title:Text create = app.text()",
|
|
"title:Text index search = input + 1",
|
|
"private title:Text create = input",
|
|
] {
|
|
write_source(&model, format!("type Service {{{source}}}")).unwrap();
|
|
let loaded = Project::load(&root).unwrap();
|
|
assert!(loaded.diagnostics.is_empty());
|
|
assert!(
|
|
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
|
"{source}"
|
|
);
|
|
}
|
|
write_source(&model, "type Service {private internal:Text,title:Text create = text.trim(input) replace = text.lower(input)}").unwrap();
|
|
let (_, program) = analyze(&root);
|
|
assert!(program.http.is_empty());
|
|
assert!(
|
|
!program
|
|
.functions
|
|
.iter()
|
|
.any(|f| f.signature.name.contains("Rest"))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn rest_rejects_unsafe_sources_and_ambiguous_routes() {
|
|
for (model, api) in [
|
|
("private title:Text", "rest data.article"),
|
|
("private title:Text create = input", "rest data.article"),
|
|
("uid:Uuid generated create = input", "rest data.article"),
|
|
(
|
|
"owner user_id:data.user.id? = dever.auth.userId()",
|
|
"rest data.article",
|
|
),
|
|
(
|
|
"owner first_id:data.user.id = dever.auth.userId()\nowner second_id:data.tenant.id = dever.auth.tenantId()",
|
|
"rest data.article",
|
|
),
|
|
("title:Text search = input", "rest data.article"),
|
|
("title:Text index search = \"fixed\"", "rest data.article"),
|
|
(
|
|
"title:Text index search = input\nother_title:Text index search = input",
|
|
"rest data.article",
|
|
),
|
|
("page:Int index search = input", "rest data.article"),
|
|
("title:Text create = app.text()", "rest data.article"),
|
|
("title:Text create = missing", "rest data.article"),
|
|
("title:Text create = 1", "rest data.article"),
|
|
("title:Text", "rest data.article\nget read = app.text"),
|
|
] {
|
|
let root = project(
|
|
"rest-invalid",
|
|
"type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}\nverify(claims:dever.auth.Claims) (out:Identity) {out=Identity{id=claims.subject,user_id=null,tenant_id=null}}\ntext() (out:Text) {out=\"value\"}",
|
|
api,
|
|
);
|
|
let directory = root.join("module/demo/service/data");
|
|
fs::create_dir_all(&directory).unwrap();
|
|
fs::write(directory.join("user.dever"), "global type User {name:Text}").unwrap();
|
|
fs::write(
|
|
directory.join("tenant.dever"),
|
|
"global type Tenant {name:Text}",
|
|
)
|
|
.unwrap();
|
|
fs::write(
|
|
directory.join("article.dever"),
|
|
format!("type Article {{{model}}}"),
|
|
)
|
|
.unwrap();
|
|
let loaded = Project::load(&root).unwrap();
|
|
assert!(
|
|
loaded.diagnostics.is_empty(),
|
|
"{model}: {:?}",
|
|
loaded.diagnostics
|
|
);
|
|
assert!(
|
|
program::check(&loaded.declarations, &loaded.modules).is_err(),
|
|
"accepted {model} / {api}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn session_operations_require_http_write_context() {
|
|
for api in [
|
|
"public get clear = app.clear",
|
|
"cmd clear = app.clear",
|
|
"job clear() retry(1) timeout(1000) = app.clear",
|
|
] {
|
|
let root = project(
|
|
"session-contracts",
|
|
"flow clear() ()\n| step | kind | do |\n| - | calc | dever.auth.clearCookie() |",
|
|
api,
|
|
);
|
|
let loaded = Project::load(&root).unwrap();
|
|
assert!(loaded.diagnostics.is_empty());
|
|
let error = program::check(&loaded.declarations, &loaded.modules)
|
|
.err()
|
|
.expect("session context required");
|
|
assert!(
|
|
error.message.contains("HTTP write entry")
|
|
|| error.message.contains("CMD cannot")
|
|
|| error.message.contains("Job cannot"),
|
|
"{api}: {error:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn authorization_changes_cannot_escape_protected_write_entries() {
|
|
for api in [
|
|
"public post change = app.change",
|
|
"authenticated post change = app.change",
|
|
"get change = app.change",
|
|
"long post change = app.change",
|
|
"job change() retry(1) timeout(1000) = app.change",
|
|
"cmd change = app.change",
|
|
] {
|
|
let root = project(
|
|
"authorization-contracts",
|
|
"flow change() ()\n| step | kind | do |\n| - | flow | app.save() |\nflow save() ()\n| step | kind | do |\n| - | calc | dever.auth.saveRole(\"reader\",\"Reader\",false,[]) |",
|
|
api,
|
|
);
|
|
let project = Project::load(&root).unwrap();
|
|
assert!(project.diagnostics.is_empty());
|
|
let error = program::check(&project.declarations, &project.modules)
|
|
.err()
|
|
.expect("invalid authorization entry");
|
|
assert!(
|
|
error.message.contains("protected HTTP write entry")
|
|
|| error.message.contains("CMD cannot"),
|
|
"{api}: {error:?}"
|
|
);
|
|
}
|
|
}
|
|
#[test]
|
|
fn http_bindings_share_wire_and_transaction_contracts_and_keep_source_navigation() {
|
|
let root = project(
|
|
"api-contracts",
|
|
r#"
|
|
type Payload {value:Text}
|
|
flow write(value:Text) ()
|
|
| step | kind | do |
|
|
| - | data | data.create({value=value}) |
|
|
flow queue(value:Text) ()
|
|
| step | kind | do |
|
|
| - | calc | enqueue(job.save,Payload {value=value},value) |
|
|
flow save(input:Payload) ()
|
|
| step | kind | do |
|
|
| - | data | data.create({value=input.value}) |
|
|
record(value:Payload) (out:Payload) {out=value}
|
|
flow print(value:Text) ()
|
|
| step | kind | do |
|
|
| - | flow | dever.io.println(value) |
|
|
scalar(value:Text) (out:Text) {out=value}
|
|
"#,
|
|
"public get scalar = app.scalar",
|
|
);
|
|
let domain = root.join("module/demo/service");
|
|
write_source(domain.join("data/main.dever"), "type Service {value:Text}").unwrap();
|
|
let path = domain.join("api/front/main.dever");
|
|
for (api, message) in [
|
|
("get bad = app.write", "GET cannot"),
|
|
("public post bad = app.print", "cannot block"),
|
|
("long get bad = app.scalar", "GET cannot"),
|
|
("public get bad = app.record", "must be scalar"),
|
|
("public delete bad = app.record", "must be scalar"),
|
|
(
|
|
"public post bad = app.queue",
|
|
"cannot access this Job queue with its declared identity",
|
|
),
|
|
(
|
|
"authenticated post bad = app.queue",
|
|
"cannot access this Job queue with its declared identity",
|
|
),
|
|
(
|
|
"public get same = app.scalar\npublic get same = app.scalar",
|
|
"duplicate HTTP",
|
|
),
|
|
] {
|
|
fs::write(
|
|
&path,
|
|
format!("job save(input:app.Payload) retry(1) timeout(1000) = app.save\n{api}"),
|
|
)
|
|
.unwrap();
|
|
let project = Project::load(&root).unwrap();
|
|
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
|
let error = program::check(&project.declarations, &project.modules)
|
|
.err()
|
|
.expect("invalid API rejected");
|
|
assert!(error.message.contains(message), "{api}: {error:?}");
|
|
}
|
|
fs::write(&path,"job save(input:app.Payload) retry(1) timeout(1000) = app.save\npublic get scalar = app.scalar").unwrap();
|
|
let (project, program) = analyze(&root);
|
|
let formatted = dever::compiler::format::format(&project.declarations);
|
|
assert!(formatted.contains("public get scalar = app.scalar"));
|
|
assert_eq!(program.http.len(), 1);
|
|
let index = dever::compiler::inspect::analyze(&project, None, 1, true).unwrap();
|
|
let http = index.symbols.iter().find(|s| s.kind == "http").unwrap();
|
|
let graph = index.flows.iter().find(|f| f.symbol == http.id).unwrap();
|
|
assert!(
|
|
graph
|
|
.nodes
|
|
.iter()
|
|
.any(|n| n.target.as_deref() == Some("demo.service.app.scalar"))
|
|
);
|
|
assert!(!graph.nodes.iter().any(|n| n.label.contains("verify")));
|
|
assert!(graph.edges.iter().any(|e| e.label == "失败"));
|
|
assert!(
|
|
index
|
|
.calls
|
|
.iter()
|
|
.any(|c| c.caller == http.id && c.kind == "entry")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn tenant_http_rejects_indirect_public_reads_before_listening() {
|
|
use serde_json::json;
|
|
let root = project(
|
|
"tenant-public-contract",
|
|
r#"
|
|
flow localCount() (out: Int)
|
|
| step | kind | do |
|
|
| out | data | data.count() |
|
|
flow indirect() (out: Int)
|
|
| step | kind | do |
|
|
| out | flow | localCount() |
|
|
flow globalCount() (out: Int)
|
|
| step | kind | do |
|
|
| out | data | data.banner.count() |
|
|
"#,
|
|
"public get local = app.indirect\npublic get summary = app.globalCount",
|
|
);
|
|
let domain = root.join("module/demo/service");
|
|
fs::create_dir(domain.join("data")).unwrap();
|
|
write_source(domain.join("data/main.dever"), "type Service {title: Text}").unwrap();
|
|
fs::write(
|
|
domain.join("data/banner.dever"),
|
|
"global type Banner {title: Text}",
|
|
)
|
|
.unwrap();
|
|
fs::create_dir(root.join("data")).unwrap();
|
|
success(cli(&["fmt", root.to_str().unwrap()]));
|
|
let (path, port, mut settings) = config(&root);
|
|
settings["database"] = json!({"create":true,"default":{"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants"}});
|
|
let (loaded, program) = analyze(&root);
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
fs::write(&path, settings.to_string()).unwrap();
|
|
success(cli(&["check", root.to_str().unwrap()]));
|
|
let server = Server::start(&artifact.binary, &path, port);
|
|
assert_eq!(
|
|
server
|
|
.call("GET", "/demo/service/front/main/local", "", "")
|
|
.1["data"],
|
|
0
|
|
);
|
|
server.stop();
|
|
|
|
settings["tenant"] = json!({"database":"default"});
|
|
fs::write(&path, settings.to_string()).unwrap();
|
|
let error = cli(&["check", root.to_str().unwrap()]);
|
|
let reason = String::from_utf8_lossy(&error.stderr);
|
|
assert!(!error.status.success());
|
|
assert!(reason.contains("app/main.dever:"), "{reason}");
|
|
assert!(
|
|
reason.contains("GET /demo/service/front/main/local requires authentication"),
|
|
"{reason}"
|
|
);
|
|
let child = Command::new(&artifact.binary)
|
|
.arg("--config")
|
|
.arg(&path)
|
|
.arg("api")
|
|
.stderr(std::process::Stdio::piped())
|
|
.spawn()
|
|
.unwrap();
|
|
let mut server = Server { child, port };
|
|
assert!(!server.wait_for_exit().success());
|
|
let mut reason = String::new();
|
|
server
|
|
.child
|
|
.stderr
|
|
.take()
|
|
.unwrap()
|
|
.read_to_string(&mut reason)
|
|
.unwrap();
|
|
assert!(
|
|
reason.contains("GET /demo/service/front/main/local requires authentication"),
|
|
"{reason}"
|
|
);
|
|
assert!(TcpStream::connect(("127.0.0.1", port)).is_err());
|
|
drop(artifact);
|
|
|
|
fs::write(
|
|
domain.join("api/front/main.dever"),
|
|
"public get summary = app.globalCount",
|
|
)
|
|
.unwrap();
|
|
success(cli(&["fmt", root.to_str().unwrap()]));
|
|
success(cli(&["check", root.to_str().unwrap()]));
|
|
let (loaded, program) = analyze(&root);
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
let server = Server::start(&artifact.binary, &path, port);
|
|
assert_eq!(
|
|
server
|
|
.call("GET", "/demo/service/front/main/summary", "", "")
|
|
.1["data"],
|
|
0
|
|
);
|
|
server.stop();
|
|
}
|
|
|
|
#[test]
|
|
fn http_shutdown_drains_or_cancels_an_accepted_request() {
|
|
let root = project(
|
|
"http-drain-deadline",
|
|
"echo(value: Text) (out: Text) {out = value}",
|
|
"public post echo = app.echo",
|
|
);
|
|
let (loaded, program) = analyze(&root);
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
for (deadline, finish) in [(1500, true), (200, false)] {
|
|
let (path, port, mut settings) = config(&root);
|
|
settings["http"]["shutdown_ms"] = deadline.into();
|
|
fs::write(&path, settings.to_string()).unwrap();
|
|
let mut server = Server::start(&artifact.binary, &path, port);
|
|
let body = r#"{"value":"drained"}"#;
|
|
let mut stream = pending_echo(port, body.len());
|
|
server.terminate();
|
|
let mut output = String::new();
|
|
if finish {
|
|
let until = Instant::now() + Duration::from_secs(1);
|
|
while TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
|
assert!(
|
|
Instant::now() < until,
|
|
"listener still accepting after SIGTERM"
|
|
);
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
stream.get_mut().write_all(body.as_bytes()).unwrap();
|
|
stream.read_to_string(&mut output).unwrap();
|
|
assert!(output.starts_with("HTTP/1.1 200 "), "{output}");
|
|
assert!(output.contains("\"data\":\"drained\""), "{output}");
|
|
} else {
|
|
stream.read_to_string(&mut output).unwrap();
|
|
assert!(output.is_empty(), "{output}");
|
|
}
|
|
assert_eq!(server.wait_for_exit().success(), finish);
|
|
if !finish {
|
|
assert!(
|
|
fs::read_to_string(path.with_extension("server.log"))
|
|
.unwrap()
|
|
.contains("HTTP shutdown deadline expired")
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn pending_echo(port: u16, bytes: usize) -> std::io::BufReader<TcpStream> {
|
|
use std::io::{BufRead, BufReader};
|
|
let stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
|
stream
|
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
|
.unwrap();
|
|
let mut stream = BufReader::new(stream);
|
|
write!(stream.get_mut(), "POST /demo/service/front/main/echo HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/json\r\nExpect: 100-continue\r\nContent-Length: {bytes}\r\n\r\n").unwrap();
|
|
let mut line = String::new();
|
|
stream.read_line(&mut line).unwrap();
|
|
assert!(line.starts_with("HTTP/1.1 100 "), "{line}");
|
|
line.clear();
|
|
stream.read_line(&mut line).unwrap();
|
|
assert_eq!(line, "\r\n");
|
|
stream
|
|
}
|
|
|
|
#[test]
|
|
fn http_shutdown_in_all_mode_leaves_the_worker_its_own_deadline() {
|
|
use serde_json::json;
|
|
let root = project(
|
|
"drain-api-and-job",
|
|
r#"
|
|
type Input { label: Text }
|
|
echo(value: Text) (out: Text) {out = value}
|
|
flow submit(input: Input) (out: Id)
|
|
| step | kind | do |
|
|
| out | calc | enqueue(job.record, input, input.label) |
|
|
transaction flow stage(label: Text) ()
|
|
| step | kind | do |
|
|
| - | data | data.create({title = label}) |
|
|
flow handle(input: Input) ()
|
|
| step | kind | do |
|
|
| - | flow | stage(input.label) |
|
|
| - | flow | dever.time.sleep(900) |
|
|
| - | flow | stage("finished") |
|
|
flow count() (out: Int)
|
|
| step | kind | do |
|
|
| out | data | data.count() |
|
|
"#,
|
|
"public post echo = app.echo\npublic get count = app.count",
|
|
);
|
|
let domain = root.join("module/demo/service");
|
|
write_source(domain.join("data/main.dever"), "type Service {title: Text}").unwrap();
|
|
fs::write(domain.join("api.dever"), "long job record(input: app.Input) retry(1) timeout(4000) = app.handle\ncmd submit = app.submit\ncmd count = app.count").unwrap();
|
|
fs::create_dir(root.join("data")).unwrap();
|
|
let (path, port, mut settings) = config(&root);
|
|
settings["http"]["shutdown_ms"] = json!(150);
|
|
settings["job"] = json!({"workers":1,"poll_ms":10,"shutdown_ms":2500});
|
|
settings["database"] = json!({"create":true,"default":{"type":"sqlite","path":"data/jobs.db","max_connections":4}});
|
|
fs::write(&path, settings.to_string()).unwrap();
|
|
let (loaded, program) = analyze(&root);
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
let mut server = Server::mode(&artifact.binary, &path, port, "all");
|
|
let mut request = pending_echo(port, 16);
|
|
let call = |name: &str, input: &str| {
|
|
success(
|
|
Command::new(&artifact.binary)
|
|
.arg("--config")
|
|
.arg(&path)
|
|
.args([name, input])
|
|
.output()
|
|
.unwrap(),
|
|
)
|
|
};
|
|
call("demo.service.submit", r#"{"input":{"label":"started"}}"#);
|
|
let until = Instant::now() + Duration::from_secs(3);
|
|
loop {
|
|
let (status, body) = server.call("GET", "/demo/service/front/main/count", "", "");
|
|
assert_eq!(status, 200, "{body}");
|
|
match body["data"].as_i64().unwrap() {
|
|
0 => {
|
|
assert!(Instant::now() < until, "Job did not start");
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
1 => break,
|
|
_ => panic!("Job finished before the stop signal"),
|
|
}
|
|
}
|
|
server.terminate();
|
|
let mut response = String::new();
|
|
request.read_to_string(&mut response).unwrap();
|
|
assert!(response.is_empty(), "{response}");
|
|
assert!(!server.wait_for_exit().success());
|
|
let error = fs::read_to_string(path.with_extension("server.log")).unwrap();
|
|
assert!(error.contains("HTTP shutdown deadline expired"), "{error}");
|
|
let done: serde_json::Value = serde_json::from_str(&call("demo.service.count", "{}")).unwrap();
|
|
assert_eq!(
|
|
done["data"], 2,
|
|
"the worker must finish after HTTP is cancelled"
|
|
);
|
|
}
|