420 lines
15 KiB
Rust
420 lines
15 KiB
Rust
use super::*;
|
|
use dever_runtime::{
|
|
auth::{Claims, Provider},
|
|
value::{calendar::DateTime, secret::Secret},
|
|
};
|
|
|
|
#[test]
|
|
fn generated_http_revalidates_accounts_permissions_cookie_origins_and_transactions() {
|
|
exercise(
|
|
"api-auth",
|
|
serde_json::json!({"type":"sqlite","path":"data/api.db","max_connections":2}),
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
#[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"]
|
|
fn postgres_generated_http_identity_permissions_transactions_and_jobs() {
|
|
let url = std::env::var("DEVER_TEST_POSTGRES").expect("isolated PostgreSQL database");
|
|
exercise(
|
|
"api-auth-postgres",
|
|
serde_json::json!({"type":"postgres","url":url,"tls":"disabled","max_connections":3}),
|
|
);
|
|
}
|
|
fn exercise(name: &str, database: serde_json::Value) {
|
|
let root = project(
|
|
name,
|
|
r#"
|
|
type Payload {title:Text}
|
|
type Identity {id:Text,user_id:data.user.id?,tenant_id:data.tenant.id?}
|
|
flow verify(claims:dever.auth.Claims) (identity:Identity)
|
|
| step | kind | do |
|
|
| account | data | data.user.first(subject == claims.subject) |
|
|
| - | check | account != null else Unauthorized |
|
|
| - | check | account.enabled else Unauthorized |
|
|
| identity | calc | Identity {id=claims.subject,user_id=account.id,tenant_id=null} |
|
|
flow create(title:Text, accept:Bool) (out: data.Service)
|
|
| step | kind | do |
|
|
| out | data | data.create({title=title}) |
|
|
| - | check | accept else Conflict |
|
|
flow count() (out:Int)
|
|
| step | kind | do |
|
|
| out | data | data.count() |
|
|
flow submit(title:Text) (out:Id)
|
|
| step | kind | do |
|
|
| out | calc | enqueue(job.save,Payload {title=title},title) |
|
|
flow jobStates(owned:Id, scheduled:Id) (owned_state:Text?, scheduled_state:Text?)
|
|
| step | kind | do |
|
|
| states | calc | dever.job.states([owned, scheduled, null]) |
|
|
| owned_state | calc | get(states, owned) |
|
|
| scheduled_state | calc | get(states, scheduled) |
|
|
flow systemJobStates(owned:Id, scheduled:Id) (owned_state:Text?, scheduled_state:Text?)
|
|
| step | kind | do |
|
|
| states | calc | dever.job.states([owned, scheduled, null], "system") |
|
|
| owned_state | calc | get(states, owned) |
|
|
| scheduled_state | calc | get(states, scheduled) |
|
|
flow save(input:Payload) ()
|
|
| step | kind | do |
|
|
| user: data.user.id? | calc | dever.auth.userId() |
|
|
| - | check | user != null else Unauthorized |
|
|
| - | data | data.create({title=input.title}) |
|
|
flow subject() (out:Text)
|
|
| step | kind | do |
|
|
| out | calc | dever.auth.id() |
|
|
flow current() (id:Text,session:Text,user_id:data.user.id?,tenant_id:data.tenant.id?)
|
|
| step | kind | do |
|
|
| task | calc | run(app.subject()) |
|
|
| id | calc | wait(task) |
|
|
| session | calc | dever.auth.session() |
|
|
| user_id | calc | dever.auth.userId() |
|
|
| tenant_id | calc | dever.auth.tenantId() |
|
|
ready() (out:Bool) {out=true}
|
|
"#,
|
|
"job save(input:app.Payload) retry(1) timeout(1000) = app.save\npost submit = app.submit\npost create = app.create\nget count = app.count\nauthenticated get current = app.current\nauthenticated post touch = app.ready\nauthenticated post jobStates = app.jobStates\npublic get health = app.ready",
|
|
);
|
|
let domain = root.join("module/demo/service");
|
|
fs::create_dir_all(domain.join("data")).unwrap();
|
|
fs::write(
|
|
domain.join("api.dever"),
|
|
"cmd submitSystem = app.submit\ncmd systemJobStates = app.systemJobStates",
|
|
)
|
|
.unwrap();
|
|
write_source(domain.join("data/main.dever"), "type Service {title:Text}").unwrap();
|
|
fs::write(domain.join("data/user.dever"),"global type User {subject:Text unique,enabled:Bool}\nseed { {subject=\"alice\",enabled=true} }").unwrap();
|
|
fs::write(
|
|
domain.join("data/tenant.dever"),
|
|
"global type Tenant {name:Text}",
|
|
)
|
|
.unwrap();
|
|
let (path, port, mut config) = config(&root);
|
|
config["job"] =
|
|
serde_json::json!({"workers":1,"poll_ms":5,"lease_ms":10000,"shutdown_ms":5000});
|
|
config["database"] = serde_json::json!({"default":database});
|
|
config["sites"]["front"]["auth"] = serde_json::json!("users");
|
|
config["sites"]["front"]["origin"] = serde_json::json!("http://localhost");
|
|
config["auth"] = serde_json::json!({"providers":{"users":{"verify":"demo.service.verify","jwtSecret":"01234567890123456789012345678901","ttlSeconds":3600,"cookie":"session"}}});
|
|
fs::create_dir_all(root.join("data")).unwrap();
|
|
fs::write(&path, config.to_string()).unwrap();
|
|
let (loaded, program) = analyze(&root);
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
success(
|
|
Command::new(&artifact.binary)
|
|
.arg("--config")
|
|
.arg(&path)
|
|
.arg("migrate")
|
|
.output()
|
|
.unwrap(),
|
|
);
|
|
let database_config: dever_runtime::database::config::Config =
|
|
serde_json::from_value(database).unwrap();
|
|
let sql = |sql: &'static str| {
|
|
dever_runtime::task::run(true, 8, async |scope| {
|
|
let database = database_config.open(&root, false).await.unwrap();
|
|
database
|
|
.acquire()
|
|
.await
|
|
.unwrap()
|
|
.execute(
|
|
scope,
|
|
dever_runtime::database::Sql {
|
|
sqlite: sql,
|
|
postgres: sql,
|
|
},
|
|
vec![],
|
|
)
|
|
.await
|
|
.unwrap();
|
|
Ok::<_, String>(())
|
|
})
|
|
.unwrap()
|
|
.unwrap();
|
|
};
|
|
// 通过实际角色表赋权;被测入口仍必须读取实时目录和角色状态。
|
|
sql(
|
|
"INSERT INTO _dever_role(site,id,name,all_permissions,enabled,protected) VALUES ('front','writer','Writer',FALSE,TRUE,FALSE)",
|
|
);
|
|
sql("INSERT INTO _dever_user_role VALUES ('front',1,'writer')");
|
|
sql(
|
|
"INSERT INTO _dever_role_permission VALUES ('front','writer','demo.service.front.create'),('front','writer','demo.service.front.count'),('front','writer','demo.service.front.submit')",
|
|
);
|
|
let provider = Provider::new(
|
|
"users".into(),
|
|
Secret::from_input(b"01234567890123456789012345678901".to_vec()),
|
|
3600,
|
|
)
|
|
.unwrap();
|
|
let claims = Claims {
|
|
subject: "alice".into(),
|
|
session: "session-1".into(),
|
|
site: "front".into(),
|
|
tenant: None,
|
|
};
|
|
let now = DateTime::now().unwrap().millis() / 1000;
|
|
let issued = dever_runtime::auth::request::Cookie::new("session".into(), "http://localhost")
|
|
.unwrap()
|
|
.issue(&provider, &claims, now)
|
|
.unwrap();
|
|
let cookie_value = std::str::from_utf8(&issued.value)
|
|
.unwrap()
|
|
.split(';')
|
|
.next()
|
|
.unwrap();
|
|
let authorization = format!("Cookie: {cookie_value}\r\nOrigin: http://localhost\r\n");
|
|
let server = Server::start(&artifact.binary, &path, port);
|
|
let create = "/demo/service/front/main/create";
|
|
let count = "/demo/service/front/main/count";
|
|
assert_eq!(server.call("GET", count, "", "").0, 401);
|
|
let json = format!("{authorization}Content-Type: application/json\r\n");
|
|
assert_eq!(
|
|
server
|
|
.call(
|
|
"POST",
|
|
create,
|
|
r#"{"title":"rollback","accept":false}"#,
|
|
&json
|
|
)
|
|
.0,
|
|
409
|
|
);
|
|
assert_eq!(server.call("GET", count, "", &authorization).1["data"], 0);
|
|
assert_eq!(
|
|
server
|
|
.call("POST", create, r#"{"title":"saved","accept":true}"#, &json)
|
|
.0,
|
|
200
|
|
);
|
|
assert_eq!(server.call("GET", count, "", &authorization).1["data"], 1);
|
|
let current = server.call(
|
|
"GET",
|
|
"/demo/service/front/main/current",
|
|
"",
|
|
&authorization,
|
|
);
|
|
assert_eq!(current.0, 200);
|
|
assert_eq!(
|
|
current.1["data"],
|
|
serde_json::json!({"id":"alice","session":"session-1","user_id":1,"tenant_id":null})
|
|
);
|
|
assert_eq!(
|
|
server
|
|
.call(
|
|
"GET",
|
|
"/demo/service/front/main/current?user_id=99",
|
|
"",
|
|
&authorization
|
|
)
|
|
.0,
|
|
400
|
|
);
|
|
sql("DELETE FROM _dever_role_permission WHERE permission_key='demo.service.front.create'");
|
|
assert_eq!(
|
|
server
|
|
.call("POST", create, r#"{"title":"denied","accept":true}"#, &json)
|
|
.0,
|
|
403
|
|
);
|
|
assert_eq!(
|
|
server
|
|
.call(
|
|
"GET",
|
|
"/demo/service/front/main/current",
|
|
"",
|
|
&authorization
|
|
)
|
|
.0,
|
|
200
|
|
);
|
|
let cookie = dever_runtime::auth::request::Cookie::new("session".into(), "http://localhost")
|
|
.unwrap()
|
|
.issue(&provider, &claims, now)
|
|
.unwrap();
|
|
let cookie = std::str::from_utf8(&cookie.value)
|
|
.unwrap()
|
|
.split(';')
|
|
.next()
|
|
.unwrap();
|
|
let headers = format!("Cookie: {cookie}\r\nContent-Type: application/json\r\n");
|
|
assert_eq!(
|
|
server
|
|
.call("POST", "/demo/service/front/main/touch", "{}", &headers)
|
|
.0,
|
|
403
|
|
);
|
|
assert_eq!(
|
|
server
|
|
.call(
|
|
"POST",
|
|
"/demo/service/front/main/touch",
|
|
"{}",
|
|
&format!("{headers}Origin: http://localhost\r\n")
|
|
)
|
|
.0,
|
|
200
|
|
);
|
|
assert_eq!(
|
|
server
|
|
.call(
|
|
"POST",
|
|
"/demo/service/front/main/touch",
|
|
"{}",
|
|
&format!("{headers}Authorization: Bearer invalid\r\nOrigin: http://localhost\r\n")
|
|
)
|
|
.0,
|
|
401
|
|
);
|
|
let submit = "/demo/service/front/main/submit";
|
|
let (status, user_job) = server.call("POST", submit, r#"{"title":"job-ok"}"#, &json);
|
|
assert_eq!(status, 200, "{user_job}");
|
|
let user_id = user_job["data"].as_str().unwrap();
|
|
let mut worker = Server {
|
|
child: Command::new(&artifact.binary)
|
|
.arg("--config")
|
|
.arg(&path)
|
|
.arg("worker")
|
|
.stdout(std::process::Stdio::null())
|
|
.stderr(std::process::Stdio::piped())
|
|
.spawn()
|
|
.unwrap(),
|
|
port: 0,
|
|
};
|
|
let count_jobs = |state: &str| {
|
|
dever_runtime::task::run(true, 8, async |scope| {
|
|
let database = database_config.open(&root, false).await.unwrap();
|
|
let rows = database
|
|
.acquire()
|
|
.await
|
|
.unwrap()
|
|
.query(
|
|
scope,
|
|
dever_runtime::database::Sql::same(
|
|
"SELECT COUNT(*) FROM _dever_job WHERE state=$1",
|
|
),
|
|
vec![dever_runtime::database::Parameter::Text(state.into())],
|
|
|row| row.get::<i64>(0),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
Ok::<_, String>(rows[0])
|
|
})
|
|
.unwrap()
|
|
.unwrap()
|
|
};
|
|
let until = Instant::now() + Duration::from_secs(5);
|
|
while server.call("GET", count, "", &authorization).1["data"] != 2 {
|
|
assert!(
|
|
worker.child.try_wait().unwrap().is_none(),
|
|
"worker exited early"
|
|
);
|
|
assert!(Instant::now() < until, "user Job did not complete");
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
worker.stop();
|
|
assert_eq!(
|
|
server
|
|
.call("POST", submit, r#"{"title":"job-revoked"}"#, &json)
|
|
.0,
|
|
200
|
|
);
|
|
sql("UPDATE demo_service_user SET enabled=FALSE WHERE id=1");
|
|
let worker = Server {
|
|
child: Command::new(&artifact.binary)
|
|
.arg("--config")
|
|
.arg(&path)
|
|
.arg("worker")
|
|
.stdout(std::process::Stdio::null())
|
|
.stderr(std::process::Stdio::piped())
|
|
.spawn()
|
|
.unwrap(),
|
|
port: 0,
|
|
};
|
|
let until = Instant::now() + Duration::from_secs(5);
|
|
while count_jobs("blocked") != 1 {
|
|
assert!(
|
|
Instant::now() < until,
|
|
"revoked identity Job was not blocked"
|
|
);
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
worker.stop();
|
|
assert_eq!(server.call("GET", count, "", &authorization).0, 401);
|
|
assert_eq!(
|
|
server
|
|
.call("GET", "/demo/service/front/main/health", "", "")
|
|
.0,
|
|
200
|
|
);
|
|
server.stop();
|
|
sql("UPDATE demo_service_user SET enabled=TRUE WHERE id=1");
|
|
let server = Server::mode(&artifact.binary, &path, port, "all");
|
|
assert_eq!(
|
|
server
|
|
.call("POST", submit, r#"{"title":"job-all-mode"}"#, &json)
|
|
.0,
|
|
200
|
|
);
|
|
let until = Instant::now() + Duration::from_secs(5);
|
|
while server.call("GET", count, "", &authorization).1["data"] != 3 {
|
|
assert!(
|
|
Instant::now() < until,
|
|
"joint API/worker mode did not execute the Job"
|
|
);
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
server.stop();
|
|
let owner = |input: &str| {
|
|
Command::new(&artifact.binary)
|
|
.arg("--config")
|
|
.arg(&path)
|
|
.args(["dever.auth.owner", input])
|
|
.output()
|
|
.unwrap()
|
|
};
|
|
for input in [
|
|
"[]",
|
|
r#"{"site":"front","user_id":0}"#,
|
|
r#"{"site":"missing","user_id":1}"#,
|
|
r#"{"site":"front","site":"front","user_id":1}"#,
|
|
] {
|
|
assert!(!owner(input).status.success());
|
|
}
|
|
success(owner(r#"{"site":"front","user_id":1}"#));
|
|
success(owner(r#"{"site":"front","user_id":1}"#));
|
|
let server = Server::start(&artifact.binary, &path, port);
|
|
assert_eq!(
|
|
server
|
|
.call("POST", create, r#"{"title":"owner","accept":true}"#, &json)
|
|
.0,
|
|
200
|
|
);
|
|
|
|
let command = |name: &str, input: serde_json::Value| {
|
|
let output = success(
|
|
Command::new(&artifact.binary)
|
|
.arg("--config")
|
|
.arg(&path)
|
|
.args([name, &input.to_string()])
|
|
.output()
|
|
.unwrap(),
|
|
);
|
|
serde_json::from_str::<serde_json::Value>(&output).unwrap()["data"].clone()
|
|
};
|
|
let system_job = command(
|
|
"demo.service.submitSystem",
|
|
serde_json::json!({"title":"job-system"}),
|
|
);
|
|
let system_id = system_job.as_str().unwrap();
|
|
let ids = serde_json::json!({"owned":user_id,"scheduled":system_id});
|
|
let endpoint = "/demo/service/front/main/jobStates";
|
|
let (status, user_states) = server.call("POST", endpoint, &ids.to_string(), &json);
|
|
assert_eq!(status, 200, "{user_states}");
|
|
assert_eq!(
|
|
user_states["data"],
|
|
serde_json::json!({"owned_state":"completed","scheduled_state":null})
|
|
);
|
|
assert_eq!(
|
|
command("demo.service.systemJobStates", ids),
|
|
serde_json::json!({"owned_state":null,"scheduled_state":"pending"})
|
|
);
|
|
server.stop();
|
|
}
|