//! 从真实 HTTP 调用授权原语,验证实时生效、事务回滚和 Owner 保护。 use super::*; #[test] fn generated_authorization_uses_real_roles_and_transaction_boundaries() { exercise( "authorization", serde_json::json!({"type":"sqlite","path":"data/main.db","max_connections":1}), ); } #[test] #[ignore = "requires an isolated PostgreSQL database; run test/postgres.py"] fn postgres_generated_authorization_uses_real_roles_and_transaction_boundaries() { exercise( "authorization-postgres", serde_json::json!({"type":"postgres","url":std::env::var("DEVER_TEST_POSTGRES").unwrap(),"tls":"disabled","max_connections":2}), ); } fn exercise(name: &str, database: serde_json::Value) { let root = project( name, r#" 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 | | user | data | data.user.first(name == claims.subject) | | - | check | user != null else Unauthorized | | identity | calc | Identity {id=claims.subject,user_id=user.id,tenant_id=null} | flow save(id:Text,accept:Bool) () | step | kind | do | | - | calc | dever.auth.saveRole(id,"Reader",false,["demo.service.front.read"]) | | - | calc | dever.auth.grantRole(2,id) | | - | check | accept else Conflict | flow roles() (out:List) | step | kind | do | | out | calc | dever.auth.roles() | flow role(id:Text) (out:dever.auth.Role?) | step | kind | do | | out | calc | dever.auth.role(id) | flow revoke(id:Text) () | step | kind | do | | - | calc | dever.auth.revokeRole(2,id) | flow disable(id:Text) () | step | kind | do | | - | calc | dever.auth.disableRole(id) | flow remove(id:Text) () | step | kind | do | | - | calc | dever.auth.deleteRole(id) | flow permissions() (out:List) | step | kind | do | | out | calc | dever.auth.permissions() | flow currentPermissions() (out:List) | step | kind | do | | out | calc | dever.auth.currentPermissions() | flow userRoles(user:data.user.id) (out:List) | step | kind | do | | out | calc | dever.auth.userRoles(user) | flow owner(user:Int) (out:Bool) | step | kind | do | | out | calc | dever.auth.hasProtectedRoles(user) | read() (out:Text) {out="read"} "#, "post save = app.save\nget roles = app.roles\nget role = app.role\npost revoke = app.revoke\npost disable = app.disable\ndelete remove = app.remove\nget permissions = app.permissions\nauthenticated get currentPermissions = app.currentPermissions\nget userRoles = app.userRoles\nget owner = app.owner\nget read = app.read", ); let models = root.join("module/demo/service/data"); fs::create_dir_all(&models).unwrap(); fs::write( models.join("user.dever"), "global type User {name:Text unique}\nseed {{name=\"admin\"},{name=\"reader\"}}", ) .unwrap(); fs::write( models.join("tenant.dever"), "global type Tenant {name:Text}", ) .unwrap(); fs::create_dir_all(root.join("data")).unwrap(); let (path, port, mut config) = config(&root); 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::write(&path, config.to_string()).unwrap(); let (loaded, program) = analyze(&root); let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap(); for args in [ vec!["migrate"], vec![ "dever.auth.owner", r#"{"site":"front","user_id":1,"tenant":null}"#, ], ] { success( Command::new(&artifact.binary) .arg("--config") .arg(&path) .args(args) .output() .unwrap(), ); } let provider = dever_runtime::auth::Provider::new( "users".into(), dever_runtime::value::secret::Secret::from_input( b"01234567890123456789012345678901".to_vec(), ), 3600, ) .unwrap(); let headers = |subject: &str| { let header = dever_runtime::auth::request::Cookie::new("session".into(), "http://localhost") .unwrap() .issue( &provider, &dever_runtime::auth::Claims { subject: subject.into(), session: "test-session".into(), tenant: None, site: "front".into(), }, dever_runtime::value::calendar::DateTime::now() .unwrap() .millis() / 1000, ) .unwrap(); format!( "Cookie: {}\r\nOrigin: http://localhost\r\nContent-Type: application/json\r\n", std::str::from_utf8(&header.value) .unwrap() .split(';') .next() .unwrap() ) }; let admin = headers("admin"); let reader = headers("reader"); let server = Server::start(&artifact.binary, &path, port); let call = |method: &str, action: &str, body: &str, headers: &str| { server.call( method, &format!("/demo/service/front/main/{action}"), body, headers, ) }; assert_eq!(call("GET", "read", "", &reader).0, 403); assert_eq!( call( "POST", "save", r#"{"id":"rollback","accept":false}"#, &admin ) .0, 409 ); assert!(call("GET", "role?id=rollback", "", &admin).1["data"].is_null()); assert_eq!(call("GET", "read", "", &reader).0, 403); assert_eq!( call("POST", "save", r#"{"id":"reader","accept":true}"#, &admin).0, 200 ); assert_eq!(call("GET", "read", "", &reader).0, 200); let permissions = call("GET", "currentPermissions", "", &reader); assert_eq!(permissions.0, 200); assert_eq!( permissions.1["data"], serde_json::json!([{"key":"demo.service.front.read","component":"demo","domain":"service","site":"front","action":"read","method":"GET","kind":"http"}]) ); assert_eq!( call("GET", "userRoles?user=2", "", &admin).1["data"][0]["id"], "reader" ); assert_eq!(call("GET", "owner?user=1", "", &admin).1["data"], true); assert_eq!(call("GET", "owner?user=2", "", &admin).1["data"], false); for action in ["disable", "remove", "save"] { let (method, action, body) = if action == "remove" { ("DELETE", "remove?id=owner", "") } else { ( "POST", action, if action == "save" { r#"{"id":"owner","accept":true}"# } else { r#"{"id":"owner"}"# }, ) }; assert_eq!(call(method, action, body, &admin).0, 403); } for _ in 0..2 { assert_eq!(call("POST", "revoke", r#"{"id":"reader"}"#, &admin).0, 200); } assert_eq!(call("GET", "read", "", &reader).0, 403); assert_eq!( call("POST", "save", r#"{"id":"reader","accept":true}"#, &admin).0, 200 ); assert_eq!(call("POST", "disable", r#"{"id":"reader"}"#, &admin).0, 200); assert_eq!(call("GET", "read", "", &reader).0, 403); assert_eq!(call("DELETE", "remove?id=reader", "", &admin).0, 200); assert_eq!(call("POST", "revoke", r#"{"id":"reader"}"#, &admin).0, 404); assert_eq!( call("GET", "roles", "", &admin).1["data"] .as_array() .unwrap() .len(), 1 ); assert!( !call("GET", "permissions", "", &admin).1["data"] .as_array() .unwrap() .is_empty() ); server.stop(); }