mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-28 08:06:16 +00:00
fixup! feat: let a service account name who can deploy as it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
9ad95a2b09
commit
dcbf751c21
-24
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE usr SET deployers = $3 WHERE workspace_id = $1 AND username = $2\n AND is_service_account RETURNING username",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "username",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Text",
|
||||
"TextArray"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "11e62160257578bef0453f3576caced2325a4944777ded79c4521edbf3998c0c"
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT deployers FROM usr WHERE workspace_id = $1 AND username = $2 AND is_service_account",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "deployers",
|
||||
"type_info": "TextArray"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "1dbcf0682fff21c16aef4c6af3eeded1f0e8c94187bad8669b765b499a63376a"
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT on_behalf_of FROM script WHERE path = $1 AND workspace_id = 'test-workspace'",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "on_behalf_of",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "5be521faefa6193e16a7e3b1d7cd769877b63f2c3c98bc3e15853ca9d0d48d16"
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT username, email, deployers FROM usr\n WHERE workspace_id = $1 AND is_service_account AND NOT disabled ORDER BY username",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "username",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "email",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "deployers",
|
||||
"type_info": "TextArray"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "93aab806f5de68494b38c567bf26ed952ed6af182026ae48ca164b0351c50ad6"
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT deployers FROM usr WHERE workspace_id = 'test-workspace' AND username = 'sa-bot'",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "deployers",
|
||||
"type_info": "TextArray"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": []
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "dc8268dfa71d6ac0fd2dc9feeb22168451835d9c75eff6fa825db4254ba1bbe7"
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
DROP TRIGGER usr_deployers_rename_user ON usr;
|
||||
DROP FUNCTION usr_deployers_rename();
|
||||
DROP TRIGGER usr_deployers_forget_folder ON folder;
|
||||
DROP TRIGGER usr_deployers_forget_group ON group_;
|
||||
DROP TRIGGER usr_deployers_forget_user ON usr;
|
||||
DROP FUNCTION usr_deployers_forget();
|
||||
ALTER TABLE usr DROP COLUMN deployers;
|
||||
@@ -1,43 +0,0 @@
|
||||
-- Who may deploy items that run as this service account: u/<user>, g/<group>, or f/<folder>
|
||||
-- (whoever can write in that folder at deploy time). Admins and wm_deployers need no entry.
|
||||
ALTER TABLE usr ADD COLUMN deployers TEXT[] NOT NULL DEFAULT '{}';
|
||||
|
||||
-- An entry hands over a whole account, so a user, group or folder created later under a freed
|
||||
-- name must not inherit it. Triggers keep the lists in step on every path that deletes or
|
||||
-- renames one, inside that path's own transaction.
|
||||
CREATE FUNCTION usr_deployers_forget() RETURNS trigger AS $$
|
||||
DECLARE
|
||||
entry TEXT;
|
||||
BEGIN
|
||||
-- IF, not CASE: a CASE resolves every branch's field, and a usr row has no `name`.
|
||||
IF TG_TABLE_NAME = 'usr' THEN
|
||||
entry := 'u/' || OLD.username;
|
||||
ELSIF TG_TABLE_NAME = 'group_' THEN
|
||||
entry := 'g/' || OLD.name;
|
||||
ELSE
|
||||
entry := 'f/' || OLD.name;
|
||||
END IF;
|
||||
UPDATE usr SET deployers = array_remove(deployers, entry)
|
||||
WHERE workspace_id = OLD.workspace_id AND entry = ANY(deployers);
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TRIGGER usr_deployers_forget_user AFTER DELETE ON usr
|
||||
FOR EACH ROW EXECUTE FUNCTION usr_deployers_forget();
|
||||
CREATE TRIGGER usr_deployers_forget_group AFTER DELETE ON group_
|
||||
FOR EACH ROW EXECUTE FUNCTION usr_deployers_forget();
|
||||
CREATE TRIGGER usr_deployers_forget_folder AFTER DELETE ON folder
|
||||
FOR EACH ROW EXECUTE FUNCTION usr_deployers_forget();
|
||||
|
||||
CREATE FUNCTION usr_deployers_rename() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
UPDATE usr SET deployers = array_replace(deployers, 'u/' || OLD.username, 'u/' || NEW.username)
|
||||
WHERE workspace_id = NEW.workspace_id AND ('u/' || OLD.username) = ANY(deployers);
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TRIGGER usr_deployers_rename_user AFTER UPDATE OF username ON usr
|
||||
FOR EACH ROW WHEN (OLD.username IS DISTINCT FROM NEW.username)
|
||||
EXECUTE FUNCTION usr_deployers_rename();
|
||||
@@ -3043,97 +3043,3 @@ async fn test_reject_reserved_sentinel_on_behalf_of(db: Pool<Postgres>) -> anyho
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(fixtures("preserve_on_behalf_of"))]
|
||||
async fn test_service_account_deployers(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
// test-user-2 is a plain member: in group `devs`, a writer of f/team.
|
||||
sqlx::raw_sql(
|
||||
"INSERT INTO usr (workspace_id, email, username, is_service_account)
|
||||
VALUES ('test-workspace', 'sa-bot@test.sa.wm.dev', 'sa-bot', true);
|
||||
INSERT INTO group_ (workspace_id, name, summary, extra_perms)
|
||||
VALUES ('test-workspace', 'devs', '', '{}');
|
||||
INSERT INTO usr_to_group (workspace_id, group_, usr)
|
||||
VALUES ('test-workspace', 'devs', 'test-user-2');
|
||||
INSERT INTO folder (workspace_id, name, display_name, owners, extra_perms)
|
||||
VALUES ('test-workspace', 'team', 'team', '{}', '{\"u/test-user-2\": true}');
|
||||
-- Its own token: the auth cache is process-wide and keyed by token, so a parallel
|
||||
-- test caching SECRET_TOKEN_2 would hide the group and folder above.
|
||||
INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin)
|
||||
VALUES (encode(sha256('SA_DEPLOYERS_TOKEN'::bytea), 'hex'), 'SA_DEPLOYE',
|
||||
'SA_DEPLOYERS_TOKEN', 'test2@windmill.dev', 'deployers test', false);",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let base = format!(
|
||||
"http://localhost:{}/api/w/test-workspace",
|
||||
server.addr.port()
|
||||
);
|
||||
|
||||
// Each deploy asks to keep sa-bot; the list decides whether it is kept.
|
||||
let cases = [
|
||||
("empty", json!([]), "u/test-user-2"),
|
||||
("user", json!(["u/test-user-2"]), "u/sa-bot"),
|
||||
("group", json!(["g/devs"]), "u/sa-bot"),
|
||||
("folder", json!(["f/team"]), "u/sa-bot"),
|
||||
];
|
||||
for (name, deployers, expected) in cases {
|
||||
let resp = authed(
|
||||
client().post(format!("{base}/access/set_deployers")),
|
||||
"SECRET_TOKEN",
|
||||
)
|
||||
.json(&json!({ "principal": "u/sa-bot", "deployers": deployers }))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
|
||||
let path = format!("u/test-user-2/sa_{name}");
|
||||
let mut script = new_script_with_on_behalf_of(&path, None, true);
|
||||
script["on_behalf_of"] = json!("u/sa-bot");
|
||||
let resp = authed(
|
||||
client().post(format!("{base}/scripts/create")),
|
||||
"SA_DEPLOYERS_TOKEN",
|
||||
)
|
||||
.json(&script)
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 201, "{}", resp.text().await?);
|
||||
|
||||
let stored = sqlx::query_scalar!(
|
||||
"SELECT on_behalf_of FROM script WHERE path = $1 AND workspace_id = 'test-workspace'",
|
||||
path
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
assert_eq!(stored.as_deref(), Some(expected), "{name} entry");
|
||||
}
|
||||
|
||||
// A listed deployer must not be able to widen the list themselves.
|
||||
let resp = authed(
|
||||
client().post(format!("{base}/access/set_deployers")),
|
||||
"SA_DEPLOYERS_TOKEN",
|
||||
)
|
||||
.json(&json!({ "principal": "u/sa-bot", "deployers": ["g/all"] }))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 403, "{}", resp.text().await?);
|
||||
|
||||
// A folder re-created under the same name must not inherit the entry.
|
||||
let resp = authed(
|
||||
client().delete(format!("{base}/folders/delete/team")),
|
||||
"SECRET_TOKEN",
|
||||
)
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
let deployers = sqlx::query_scalar!(
|
||||
"SELECT deployers FROM usr WHERE workspace_id = 'test-workspace' AND username = 'sa-bot'"
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
assert!(deployers.is_empty(), "{deployers:?}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -720,15 +720,14 @@ async fn create_flow(
|
||||
let authed = maybe_refresh_folders(&nf.path, &w_id, authed, &db).await;
|
||||
|
||||
// Apply folder default_permissioned_as on create when the caller did not
|
||||
// explicitly preserve a value and may deploy as the default.
|
||||
// explicitly preserve a value and the user can preserve.
|
||||
let explicit_preserve = (nf.on_behalf_of_email.is_some() || nf.on_behalf_of.is_some())
|
||||
&& nf.preserve_on_behalf_of.unwrap_or(false);
|
||||
if !explicit_preserve {
|
||||
&& nf.preserve_on_behalf_of.unwrap_or(false)
|
||||
&& windmill_common::can_preserve_on_behalf_of(&authed);
|
||||
if !explicit_preserve && windmill_common::can_preserve_on_behalf_of(&authed) {
|
||||
if let Some((default_email, default_permissioned_as)) =
|
||||
windmill_common::folders::resolve_folder_default_on_behalf_of(
|
||||
&authed, &db, &w_id, &nf.path,
|
||||
)
|
||||
.await?
|
||||
windmill_common::folders::resolve_folder_default_on_behalf_of(&db, &w_id, &nf.path)
|
||||
.await?
|
||||
{
|
||||
nf.on_behalf_of_email = Some(default_email);
|
||||
nf.on_behalf_of = Some(default_permissioned_as);
|
||||
@@ -872,6 +871,7 @@ async fn create_flow(
|
||||
if let Some(on_behalf_of) = windmill_common::check_on_behalf_of_preservation(
|
||||
resolved_on_behalf_of.as_deref(),
|
||||
nf.preserve_on_behalf_of.unwrap_or(false),
|
||||
&authed,
|
||||
&windmill_common::users::username_to_permissioned_as(&authed.username),
|
||||
) {
|
||||
audit_log(
|
||||
@@ -1613,6 +1613,7 @@ async fn update_flow(
|
||||
if let Some(on_behalf_of) = windmill_common::check_on_behalf_of_preservation(
|
||||
resolved_on_behalf_of.as_deref(),
|
||||
nf.preserve_on_behalf_of.unwrap_or(false),
|
||||
&authed,
|
||||
&windmill_common::users::username_to_permissioned_as(&authed.username),
|
||||
) {
|
||||
audit_log(
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
use axum::{
|
||||
extract::{Extension, Path, Query},
|
||||
routing::{get, post},
|
||||
routing::get,
|
||||
Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -28,9 +28,6 @@ pub fn workspaced_service() -> Router {
|
||||
.route("/get", get(get_access))
|
||||
.route("/browse_folders", get(browse_folders))
|
||||
.route("/browse_items", get(browse_items))
|
||||
.route("/deployers", get(get_deployers))
|
||||
.route("/set_deployers", post(set_deployers))
|
||||
.route("/deploy_as", get(deploy_as))
|
||||
}
|
||||
|
||||
const BROWSE_PAGE: i64 = 100;
|
||||
@@ -517,162 +514,3 @@ fn item_blocked(
|
||||
.and_then(|mk| denied.iter().find(|(k, _)| *k == mk).map(|(_, e)| e.clone()))
|
||||
.or_else(|| grant_blocked(authed, path))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Deployers {
|
||||
deployers: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct SetDeployers {
|
||||
principal: String,
|
||||
deployers: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct DeployAsAccount {
|
||||
username: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct DeployAs {
|
||||
/// Admins and `wm_deployers` may deploy as anyone, not only the accounts listed.
|
||||
anyone: bool,
|
||||
service_accounts: Vec<DeployAsAccount>,
|
||||
}
|
||||
|
||||
fn service_account_name(principal: &str) -> Result<&str> {
|
||||
principal
|
||||
.strip_prefix("u/")
|
||||
.filter(|name| !name.is_empty())
|
||||
.ok_or_else(|| Error::BadRequest("principal must be u/<service account>".into()))
|
||||
}
|
||||
|
||||
async fn get_deployers(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
Query(AccessQuery { principal }): Query<AccessQuery>,
|
||||
) -> JsonResult<Deployers> {
|
||||
check_principal(&authed, &principal)?;
|
||||
let username = service_account_name(&principal)?;
|
||||
let deployers = sqlx::query_scalar!(
|
||||
"SELECT deployers FROM usr WHERE workspace_id = $1 AND username = $2 AND is_service_account",
|
||||
&w_id,
|
||||
username
|
||||
)
|
||||
.fetch_optional(&db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound(format!("no service account {principal}")))?;
|
||||
Ok(Json(Deployers { deployers }))
|
||||
}
|
||||
|
||||
/// Admins only: an entry hands its holders everything the account can reach.
|
||||
async fn set_deployers(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
Json(body): Json<SetDeployers>,
|
||||
) -> Result<String> {
|
||||
if !authed.is_admin {
|
||||
return Err(Error::PermissionDenied(
|
||||
"only workspace admins can choose who deploys as a service account".into(),
|
||||
));
|
||||
}
|
||||
let username = service_account_name(&body.principal)?;
|
||||
let mut deployers = body.deployers;
|
||||
deployers.sort();
|
||||
deployers.dedup();
|
||||
for entry in &deployers {
|
||||
let exists = match entry.split_once('/') {
|
||||
Some(("u", name)) => {
|
||||
sqlx::query_scalar!(
|
||||
"SELECT EXISTS(SELECT 1 FROM usr WHERE workspace_id = $1 AND username = $2)",
|
||||
&w_id,
|
||||
name
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?
|
||||
}
|
||||
Some(("g", name)) => {
|
||||
sqlx::query_scalar!(
|
||||
"SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2)",
|
||||
&w_id,
|
||||
name
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?
|
||||
}
|
||||
Some(("f", name)) => {
|
||||
sqlx::query_scalar!(
|
||||
"SELECT EXISTS(SELECT 1 FROM folder WHERE workspace_id = $1 AND name = $2)",
|
||||
&w_id,
|
||||
name
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"{entry}: entries must be u/<user>, g/<group> or f/<folder>"
|
||||
)))
|
||||
}
|
||||
};
|
||||
if exists != Some(true) {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"{entry} does not exist in {w_id}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut tx = db.begin().await?;
|
||||
let updated = sqlx::query_scalar!(
|
||||
"UPDATE usr SET deployers = $3 WHERE workspace_id = $1 AND username = $2
|
||||
AND is_service_account RETURNING username",
|
||||
&w_id,
|
||||
username,
|
||||
&deployers
|
||||
)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if updated.is_none() {
|
||||
return Err(Error::NotFound(format!(
|
||||
"no service account {}",
|
||||
body.principal
|
||||
)));
|
||||
}
|
||||
windmill_audit::audit_oss::audit_log(
|
||||
&mut *tx,
|
||||
&authed,
|
||||
"users.set_deployers",
|
||||
windmill_audit::ActionKind::Update,
|
||||
&w_id,
|
||||
Some(&body.principal),
|
||||
Some([("deployers", deployers.join(",").as_str())].into()),
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(format!("deployers of {} updated", body.principal))
|
||||
}
|
||||
|
||||
/// The service accounts the caller may deploy as, for the run-as pickers.
|
||||
async fn deploy_as(
|
||||
authed: ApiAuthed,
|
||||
Extension(db): Extension<DB>,
|
||||
Path(w_id): Path<String>,
|
||||
) -> JsonResult<DeployAs> {
|
||||
let anyone = windmill_common::can_preserve_on_behalf_of(&authed);
|
||||
let rows = sqlx::query!(
|
||||
"SELECT username, email, deployers FROM usr
|
||||
WHERE workspace_id = $1 AND is_service_account AND NOT disabled ORDER BY username",
|
||||
&w_id
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await?;
|
||||
let service_accounts = rows
|
||||
.into_iter()
|
||||
.filter(|r| anyone || windmill_common::deployers_admit(&r.deployers, &authed))
|
||||
.map(|r| DeployAsAccount { username: r.username, email: r.email })
|
||||
.collect();
|
||||
Ok(Json(DeployAs { anyone, service_accounts }))
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ use windmill_audit::audit_oss::audit_log;
|
||||
use windmill_audit::ActionKind;
|
||||
use windmill_common::DB;
|
||||
use windmill_common::{
|
||||
can_deploy_as,
|
||||
can_preserve_on_behalf_of,
|
||||
db::UserDB,
|
||||
error::{Error, JsonResult, Result},
|
||||
schedule::Schedule,
|
||||
@@ -44,27 +44,21 @@ use windmill_queue::schedule::push_scheduled_job;
|
||||
|
||||
/// Resolves the permissioned_as value for a schedule.
|
||||
/// When preserving, uses the provided permissioned_as value directly.
|
||||
async fn resolve_permissioned_as(
|
||||
fn resolve_permissioned_as(
|
||||
permissioned_as: Option<&String>,
|
||||
preserve_permissioned_as: Option<bool>,
|
||||
authed: &ApiAuthed,
|
||||
db: &DB,
|
||||
w_id: &str,
|
||||
) -> Result<String> {
|
||||
) -> String {
|
||||
if let Some(permissioned_as) = permissioned_as {
|
||||
if preserve_permissioned_as.unwrap_or(false)
|
||||
&& can_deploy_as(authed, permissioned_as, w_id, db).await?
|
||||
{
|
||||
return Ok(permissioned_as.clone());
|
||||
if preserve_permissioned_as.unwrap_or(false) && can_preserve_on_behalf_of(authed) {
|
||||
return permissioned_as.clone();
|
||||
}
|
||||
}
|
||||
Ok(windmill_common::users::username_to_permissioned_as(
|
||||
&authed.username,
|
||||
))
|
||||
windmill_common::users::username_to_permissioned_as(&authed.username)
|
||||
}
|
||||
|
||||
/// Create-time variant: applies the folder's `default_permissioned_as` rule when no
|
||||
/// explicit preserved value is provided and the caller may deploy as the default.
|
||||
/// explicit preserved value is provided and the caller can preserve (admin / wm_deployers).
|
||||
async fn resolve_permissioned_as_for_create(
|
||||
permissioned_as: Option<&String>,
|
||||
preserve_permissioned_as: Option<bool>,
|
||||
@@ -74,14 +68,16 @@ async fn resolve_permissioned_as_for_create(
|
||||
w_id: &str,
|
||||
) -> Result<String> {
|
||||
if let Some(pa) = permissioned_as {
|
||||
if preserve_permissioned_as.unwrap_or(false) && can_deploy_as(authed, pa, w_id, db).await? {
|
||||
if preserve_permissioned_as.unwrap_or(false) && can_preserve_on_behalf_of(authed) {
|
||||
return Ok(pa.clone());
|
||||
}
|
||||
}
|
||||
if let Some(default) =
|
||||
windmill_common::folders::folder_default_for_deploy(authed, db, w_id, path).await?
|
||||
{
|
||||
return Ok(default);
|
||||
if can_preserve_on_behalf_of(authed) {
|
||||
if let Some(default) =
|
||||
windmill_common::folders::resolve_folder_default_permissioned_as(db, w_id, path).await?
|
||||
{
|
||||
return Ok(default);
|
||||
}
|
||||
}
|
||||
Ok(windmill_common::users::username_to_permissioned_as(
|
||||
&authed.username,
|
||||
@@ -335,7 +331,6 @@ async fn create_schedule(
|
||||
&w_id,
|
||||
)
|
||||
.await?;
|
||||
let audited_permissioned_as = resolved_permissioned_as.clone();
|
||||
// email is still written for backwards compat with old workers that don't know about permissioned_as
|
||||
let resolved_email = windmill_common::users::get_email_from_permissioned_as_uncached(
|
||||
&resolved_permissioned_as,
|
||||
@@ -496,9 +491,10 @@ async fn create_schedule(
|
||||
)
|
||||
.await?;
|
||||
if let Some(on_behalf_of) = windmill_common::check_on_behalf_of_preservation(
|
||||
Some(&audited_permissioned_as),
|
||||
ns.permissioned_as.as_deref(),
|
||||
ns.preserve_permissioned_as.unwrap_or(false),
|
||||
&windmill_common::users::username_to_permissioned_as(&authed.username),
|
||||
&authed,
|
||||
&authed.username,
|
||||
) {
|
||||
audit_log(
|
||||
&mut *tx,
|
||||
@@ -562,11 +558,7 @@ async fn edit_schedule(
|
||||
es.permissioned_as.as_ref(),
|
||||
es.preserve_permissioned_as,
|
||||
&authed,
|
||||
&db,
|
||||
&w_id,
|
||||
)
|
||||
.await?;
|
||||
let audited_permissioned_as = resolved_permissioned_as.clone();
|
||||
);
|
||||
|
||||
// email is still written for backwards compat with old workers that don't know about permissioned_as.
|
||||
// When permissioned_as is preserved to a different user, derive email from it.
|
||||
@@ -739,9 +731,10 @@ async fn edit_schedule(
|
||||
.await?;
|
||||
|
||||
if let Some(on_behalf_of) = windmill_common::check_on_behalf_of_preservation(
|
||||
Some(&audited_permissioned_as),
|
||||
es.permissioned_as.as_deref(),
|
||||
es.preserve_permissioned_as.unwrap_or(false),
|
||||
&windmill_common::users::username_to_permissioned_as(&authed.username),
|
||||
&authed,
|
||||
&authed.username,
|
||||
) {
|
||||
audit_log(
|
||||
&mut *tx,
|
||||
|
||||
@@ -1188,8 +1188,7 @@ async fn resolve_folder_default_identity(
|
||||
db: &DB,
|
||||
) -> Result<Option<(String, String, (Option<String>, Option<String>))>> {
|
||||
let Some((email, permissioned_as)) =
|
||||
windmill_common::folders::resolve_folder_default_on_behalf_of(authed, db, w_id, path)
|
||||
.await?
|
||||
windmill_common::folders::resolve_folder_default_on_behalf_of(db, w_id, path).await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -1410,14 +1409,16 @@ async fn create_script_internal<'c>(
|
||||
// deploy taking a second connection while holding `tx` lets N concurrent deploys hold the
|
||||
// whole pool between them and each wait out the acquire timeout for one more.
|
||||
let explicit_preserve = (ns.on_behalf_of_email.is_some() || ns.on_behalf_of.is_some())
|
||||
&& ns.preserve_on_behalf_of.unwrap_or(false);
|
||||
&& ns.preserve_on_behalf_of.unwrap_or(false)
|
||||
&& windmill_common::can_preserve_on_behalf_of(&authed);
|
||||
// Held rather than raised: a rule naming a principal that no longer exists fails here, and
|
||||
// must fail only a first deploy, which is all the default applies to.
|
||||
let folder_default = if !explicit_preserve {
|
||||
resolve_folder_default_identity(&authed, &w_id, &ns.path, &db).await
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
let folder_default =
|
||||
if !explicit_preserve && windmill_common::can_preserve_on_behalf_of(&authed) {
|
||||
resolve_folder_default_identity(&authed, &w_id, &ns.path, &db).await
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
// Resolved here rather than at the INSERT so the no-op check below compares the identity
|
||||
// that would actually be stored: the parent row holds only the principal, while a
|
||||
// preserving push may name that same principal by address alone.
|
||||
@@ -2739,6 +2740,7 @@ async fn create_script_internal<'c>(
|
||||
if let Some(on_behalf_of) = windmill_common::check_on_behalf_of_preservation(
|
||||
resolved_on_behalf_of.as_deref(),
|
||||
ns.preserve_on_behalf_of.unwrap_or(false),
|
||||
&authed,
|
||||
&authed_principal,
|
||||
) {
|
||||
audit_log(
|
||||
@@ -2786,6 +2788,7 @@ async fn create_script_internal<'c>(
|
||||
if let Some(on_behalf_of) = windmill_common::check_on_behalf_of_preservation(
|
||||
resolved_on_behalf_of.as_deref(),
|
||||
ns.preserve_on_behalf_of.unwrap_or(false),
|
||||
&authed,
|
||||
&authed_principal,
|
||||
) {
|
||||
audit_log(
|
||||
|
||||
@@ -25094,96 +25094,6 @@ paths:
|
||||
type: boolean
|
||||
required: [items, has_more]
|
||||
|
||||
/w/{workspace}/access/deployers:
|
||||
get:
|
||||
summary: who may deploy items that run as a service account
|
||||
operationId: getServiceAccountDeployers
|
||||
tags:
|
||||
- granular_acl
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: principal
|
||||
description: "`u/<service account>`"
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: entries are `u/<user>`, `g/<group>` or `f/<folder>` (its writers)
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
deployers:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
required: [deployers]
|
||||
|
||||
/w/{workspace}/access/set_deployers:
|
||||
post:
|
||||
summary: set who may deploy items that run as a service account (admins only)
|
||||
operationId: setServiceAccountDeployers
|
||||
tags:
|
||||
- granular_acl
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
principal:
|
||||
description: "`u/<service account>`"
|
||||
type: string
|
||||
deployers:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
required: [principal, deployers]
|
||||
responses:
|
||||
"200":
|
||||
description: deployers updated
|
||||
content:
|
||||
text/plain:
|
||||
schema:
|
||||
type: string
|
||||
|
||||
/w/{workspace}/access/deploy_as:
|
||||
get:
|
||||
summary: the service accounts the caller may deploy as
|
||||
operationId: listDeployAs
|
||||
tags:
|
||||
- granular_acl
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
responses:
|
||||
"200":
|
||||
description: service accounts, and whether the caller may deploy as anyone
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
anyone:
|
||||
description: admins and wm_deployers may deploy as any member
|
||||
type: boolean
|
||||
service_accounts:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
username:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
required: [username, email]
|
||||
required: [anyone, service_accounts]
|
||||
|
||||
/w/{workspace}/acls/get/{kind}/{path}:
|
||||
get:
|
||||
summary: get granular acls
|
||||
|
||||
@@ -2851,6 +2851,7 @@ async fn create_app_internal<'a>(
|
||||
// leaves with a concurrent rename or removal, including a freed username later
|
||||
// rebinding the stored principal, is known and accepted: see `resolve_on_behalf_of`.
|
||||
let should_preserve = app.preserve_on_behalf_of.unwrap_or(false)
|
||||
&& windmill_common::can_preserve_on_behalf_of(&authed)
|
||||
&& (app.policy.on_behalf_of.is_some() || app.policy.on_behalf_of_email.is_some());
|
||||
|
||||
let mut preserved_on_behalf_of: Option<String> = None;
|
||||
@@ -2865,9 +2866,12 @@ async fn create_app_internal<'a>(
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
let folder_default =
|
||||
windmill_common::folders::folder_default_for_deploy(&authed, &db, w_id, &app.path)
|
||||
.await?;
|
||||
let folder_default = if windmill_common::can_preserve_on_behalf_of(&authed) {
|
||||
windmill_common::folders::resolve_folder_default_permissioned_as(&db, w_id, &app.path)
|
||||
.await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
app.policy.on_behalf_of =
|
||||
Some(folder_default.unwrap_or_else(|| username_to_permissioned_as(&authed.username)));
|
||||
}
|
||||
@@ -3843,6 +3847,7 @@ async fn update_app_internal<'a>(
|
||||
let mut preserved_on_behalf_of: Option<String> = None;
|
||||
if let Some(npolicy) = ns.policy.as_mut() {
|
||||
let should_preserve = ns.preserve_on_behalf_of.unwrap_or(false)
|
||||
&& windmill_common::can_preserve_on_behalf_of(&authed)
|
||||
&& (npolicy.on_behalf_of.is_some() || npolicy.on_behalf_of_email.is_some());
|
||||
|
||||
if should_preserve {
|
||||
@@ -4049,9 +4054,17 @@ async fn update_app_internal<'a>(
|
||||
.as_deref()
|
||||
.or(npolicy.on_behalf_of.as_deref())
|
||||
.unwrap_or("another user");
|
||||
return Err(Error::PermissionDenied(format!(
|
||||
"app {path} runs as {runs_as}: change who can open it by deploying it"
|
||||
)));
|
||||
return Err(Error::PermissionDenied(if composes_only {
|
||||
format!(
|
||||
"app {path} runs as {runs_as}: change who can open it by deploying it"
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"app {path} runs as {runs_as}: only admins and members of \
|
||||
wm_deployers can change who can open it without deploying it, and a \
|
||||
deploy from you makes it run as you"
|
||||
)
|
||||
}));
|
||||
}
|
||||
npolicy.set_execution_mode(mode);
|
||||
if composes_only {
|
||||
|
||||
@@ -9033,8 +9033,8 @@ fn operator_preview_refusal(job_id: Option<Uuid>) -> error::Error {
|
||||
/// The identity a preview asks to run as, or `None` when it runs as the caller.
|
||||
///
|
||||
/// A preview is request-supplied code, so running it as someone else is impersonation, not
|
||||
/// "running their runnable": only those who may set a runnable's `on_behalf_of` to that identity
|
||||
/// on deploy (`can_deploy_as`) may ask for it. Naming oneself is always allowed. Operators are
|
||||
/// "running their runnable": only those who may set a runnable's `on_behalf_of` on deploy
|
||||
/// (admins and `wm_deployers`) may ask for it. Naming oneself is always allowed. Operators are
|
||||
/// refused even in `wm_deployers`: the datatable-query exemption lets them reach this route
|
||||
/// without being able to deploy anything.
|
||||
pub(crate) async fn preview_on_behalf_of(
|
||||
@@ -9050,27 +9050,20 @@ pub(crate) async fn preview_on_behalf_of(
|
||||
if requested == own || requested == authed.email {
|
||||
return Ok(None);
|
||||
}
|
||||
let refused = || {
|
||||
Error::PermissionDenied(
|
||||
"Only admins, members of wm_deployers and those a service account's deployers list \
|
||||
names can run a preview on behalf of another user"
|
||||
if !role_can_code(db, w_id, authed).await?
|
||||
|| !windmill_common::can_preserve_on_behalf_of(authed)
|
||||
{
|
||||
return Err(Error::PermissionDenied(
|
||||
"Only admins and members of wm_deployers can run a preview on behalf of another user"
|
||||
.to_string(),
|
||||
)
|
||||
};
|
||||
if !role_can_code(db, w_id, authed).await? {
|
||||
return Err(refused());
|
||||
));
|
||||
}
|
||||
let permissioned_as =
|
||||
windmill_common::resolve_on_behalf_of(None, Some(requested), true, authed, w_id, db)
|
||||
.await?
|
||||
.unwrap_or(own.clone());
|
||||
if permissioned_as == own {
|
||||
// `resolve_on_behalf_of` falls back to the caller when the target's list refuses them.
|
||||
return if windmill_common::can_preserve_on_behalf_of(authed) {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(refused())
|
||||
};
|
||||
return Ok(None);
|
||||
}
|
||||
let email =
|
||||
windmill_common::users::get_email_from_permissioned_as_uncached(&permissioned_as, w_id, db)
|
||||
|
||||
@@ -64,42 +64,18 @@ pub async fn resolve_folder_default_permissioned_as(
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// [`resolve_folder_default_permissioned_as`] for a first deploy by `authed`: the default applies
|
||||
/// only when they may deploy as it ([`crate::can_deploy_as`]). Someone outside the admins and
|
||||
/// `wm_deployers` is not failed by a broken rule, since no rule could apply to them anyway.
|
||||
pub async fn folder_default_for_deploy(
|
||||
authed: &impl crate::db::Authable,
|
||||
db: &Pool<Postgres>,
|
||||
w_id: &str,
|
||||
path: &str,
|
||||
) -> Result<Option<String>> {
|
||||
let default = if crate::can_preserve_on_behalf_of(authed) {
|
||||
resolve_folder_default_permissioned_as(db, w_id, path).await?
|
||||
} else {
|
||||
resolve_folder_default_permissioned_as(db, w_id, path)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
};
|
||||
let Some(default) = default else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(crate::can_deploy_as(authed, &default, w_id, db)
|
||||
.await?
|
||||
.then_some(default))
|
||||
}
|
||||
|
||||
/// On-behalf-of variant of [`folder_default_for_deploy`], for flows and
|
||||
/// On-behalf-of variant of [`resolve_folder_default_permissioned_as`], for flows and
|
||||
/// scripts which store the identity as an `(email, permissioned_as)` pair.
|
||||
///
|
||||
/// Reads folder rules through the non-RLS pool: callers must already be authorized for `w_id`.
|
||||
/// Reads folder rules through the non-RLS pool and authorizes nothing: callers must already
|
||||
/// be authorized for `w_id`.
|
||||
pub async fn resolve_folder_default_on_behalf_of(
|
||||
authed: &impl crate::db::Authable,
|
||||
db: &Pool<Postgres>,
|
||||
w_id: &str,
|
||||
path: &str,
|
||||
) -> Result<Option<(String, String)>> {
|
||||
let Some(permissioned_as) = folder_default_for_deploy(authed, db, w_id, path).await? else {
|
||||
let Some(permissioned_as) = resolve_folder_default_permissioned_as(db, w_id, path).await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let email =
|
||||
|
||||
@@ -301,58 +301,15 @@ pub fn can_preserve_on_behalf_of(authed: &impl db::Authable) -> bool {
|
||||
authed.is_admin() || authed.groups().iter().any(|g| g == &WM_DEPLOYERS_GROUP)
|
||||
}
|
||||
|
||||
/// Whether `authed` may deploy an item that runs as `target`. Admins and `wm_deployers` may name
|
||||
/// anyone. Anyone else may name a service account whose `deployers` list admits them: being on
|
||||
/// that list hands over everything the account can reach, so it is the only other way in.
|
||||
pub async fn can_deploy_as(
|
||||
authed: &impl db::Authable,
|
||||
target: &str,
|
||||
w_id: &str,
|
||||
db: &sqlx::Pool<Postgres>,
|
||||
) -> error::Result<bool> {
|
||||
if can_preserve_on_behalf_of(authed)
|
||||
|| target == users::username_to_permissioned_as(authed.username())
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(username) = target.strip_prefix(users::PERMISSIONED_AS_USER_PREFIX) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let deployers = sqlx::query_scalar!(
|
||||
"SELECT deployers FROM usr WHERE workspace_id = $1 AND username = $2 AND is_service_account",
|
||||
w_id,
|
||||
username
|
||||
)
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
Ok(deployers.is_some_and(|d| deployers_admit(&d, authed)))
|
||||
}
|
||||
|
||||
/// A `deployers` entry names a user (`u/`), a group (`g/`), or a folder (`f/`), the last meaning
|
||||
/// whoever can write in it when they deploy.
|
||||
pub fn deployers_admit(deployers: &[String], authed: &impl db::Authable) -> bool {
|
||||
deployers.iter().any(|entry| match entry.split_once('/') {
|
||||
Some(("u", user)) => user == authed.username(),
|
||||
Some(("g", group)) => authed.groups().iter().any(|g| g == group),
|
||||
Some(("f", folder)) => authed
|
||||
.folders()
|
||||
.iter()
|
||||
.any(|(name, write, _)| name == folder && *write),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks if on-behalf-of preservation actually happened (the target user differs from the acting user).
|
||||
/// Returns Some(target_identifier) if preservation occurred, None otherwise.
|
||||
///
|
||||
/// `on_behalf_of_identifier` must be the identity being stored, already resolved through
|
||||
/// [`can_deploy_as`]: a requested one the caller may not keep would be audited as kept.
|
||||
pub fn check_on_behalf_of_preservation(
|
||||
on_behalf_of_identifier: Option<&str>,
|
||||
preserve: bool,
|
||||
authed: &impl db::Authable,
|
||||
authed_identifier: &str,
|
||||
) -> Option<String> {
|
||||
if preserve {
|
||||
if preserve && can_preserve_on_behalf_of(authed) {
|
||||
if let Some(id) = on_behalf_of_identifier {
|
||||
if id != authed_identifier {
|
||||
return Some(id.to_string());
|
||||
@@ -405,35 +362,9 @@ pub async fn resolve_on_behalf_of(
|
||||
// Through the same width check as every other branch: the caller's own identity is
|
||||
// address-shaped when they act without a `usr` row, and one too wide for a job row is no
|
||||
// more enqueueable for naming themselves.
|
||||
let own = || reject_unenqueueable(users::username_to_permissioned_as(authed.username()));
|
||||
if !preserve {
|
||||
return own();
|
||||
if !(preserve && can_preserve_on_behalf_of(authed)) {
|
||||
return reject_unenqueueable(users::username_to_permissioned_as(authed.username()));
|
||||
}
|
||||
if !can_preserve_on_behalf_of(authed) {
|
||||
// Only a service account whose `deployers` list admits the caller is kept. Any other
|
||||
// request, an unresolvable one included, falls back to the caller.
|
||||
let Ok(target) =
|
||||
resolve_requested_identity(on_behalf_of_email, on_behalf_of, w_id, db).await
|
||||
else {
|
||||
return own();
|
||||
};
|
||||
return if can_deploy_as(authed, &target, w_id, db).await? {
|
||||
reject_unenqueueable(target)
|
||||
} else {
|
||||
own()
|
||||
};
|
||||
}
|
||||
reject_unenqueueable(
|
||||
resolve_requested_identity(on_behalf_of_email, on_behalf_of, w_id, db).await?,
|
||||
)
|
||||
}
|
||||
|
||||
async fn resolve_requested_identity(
|
||||
on_behalf_of_email: Option<&str>,
|
||||
on_behalf_of: Option<&str>,
|
||||
w_id: &str,
|
||||
db: &sqlx::Pool<Postgres>,
|
||||
) -> error::Result<String> {
|
||||
// Reserved superadmin sentinels are rejected by name, before resolution: the lookups
|
||||
// below only reject them while no account holds their address, and the runtime grants
|
||||
// superadmin on these emails by string comparison alone.
|
||||
@@ -497,7 +428,7 @@ async fn resolve_requested_identity(
|
||||
})?
|
||||
}
|
||||
};
|
||||
Ok(permissioned_as)
|
||||
reject_unenqueueable(permissioned_as)
|
||||
}
|
||||
|
||||
/// Every principal ends up on `v2_job.permissioned_as`, which is narrower than the columns it is
|
||||
|
||||
@@ -2519,10 +2519,11 @@ async fn resolve_agent_on_behalf_of(
|
||||
return Ok(());
|
||||
}
|
||||
let mut preserve = preserve;
|
||||
let explicit = requested.is_some() && preserve;
|
||||
if created && !explicit {
|
||||
if let Some(folder_default) =
|
||||
windmill_common::folders::folder_default_for_deploy(authed, db, w_id, path).await?
|
||||
let explicit =
|
||||
requested.is_some() && preserve && windmill_common::can_preserve_on_behalf_of(authed);
|
||||
if created && !explicit && windmill_common::can_preserve_on_behalf_of(authed) {
|
||||
if let Some((_, folder_default)) =
|
||||
windmill_common::folders::resolve_folder_default_on_behalf_of(db, w_id, path).await?
|
||||
{
|
||||
requested = Some(folder_default);
|
||||
preserve = true;
|
||||
@@ -2542,9 +2543,12 @@ async fn resolve_agent_on_behalf_of(
|
||||
if let Some(resolved) = resolved.as_ref() {
|
||||
obj.insert("on_behalf_of".to_string(), resolved.clone().into());
|
||||
}
|
||||
if let Some(kept) =
|
||||
windmill_common::check_on_behalf_of_preservation(resolved.as_deref(), preserve, &own)
|
||||
{
|
||||
if let Some(kept) = windmill_common::check_on_behalf_of_preservation(
|
||||
resolved.as_deref(),
|
||||
preserve,
|
||||
authed,
|
||||
&own,
|
||||
) {
|
||||
audit_log(
|
||||
&mut **tx,
|
||||
authed,
|
||||
|
||||
@@ -574,13 +574,13 @@ async fn create_trigger<T: TriggerCrud>(
|
||||
let new_path = new_trigger.base.path.clone();
|
||||
let labels = new_trigger.base.labels.clone();
|
||||
|
||||
// If the caller did not preserve a value, fall back to the folder's
|
||||
// default_permissioned_as rule (create-time only) when they may deploy as it.
|
||||
// If the caller did not preserve a value but the user can preserve, fall back
|
||||
// to the folder's default_permissioned_as rule (create-time only).
|
||||
let explicit_preserve = new_trigger.base.permissioned_as.is_some()
|
||||
&& new_trigger.base.preserve_permissioned_as.unwrap_or(false);
|
||||
if !explicit_preserve {
|
||||
if let Some(default) = windmill_common::folders::folder_default_for_deploy(
|
||||
&authed,
|
||||
&& new_trigger.base.preserve_permissioned_as.unwrap_or(false)
|
||||
&& windmill_common::can_preserve_on_behalf_of(&authed);
|
||||
if !explicit_preserve && windmill_common::can_preserve_on_behalf_of(&authed) {
|
||||
if let Some(default) = windmill_common::folders::resolve_folder_default_permissioned_as(
|
||||
&db,
|
||||
&workspace_id,
|
||||
&new_trigger.base.path,
|
||||
@@ -591,10 +591,6 @@ async fn create_trigger<T: TriggerCrud>(
|
||||
new_trigger.base.preserve_permissioned_as = Some(true);
|
||||
}
|
||||
}
|
||||
new_trigger
|
||||
.base
|
||||
.check_deploy_as(&authed, &workspace_id, &db)
|
||||
.await?;
|
||||
|
||||
// Reject a forged superadmin run identity in a preserved permissioned_as
|
||||
// (the sentinel guard; a trigger's email is derived from it at execution).
|
||||
@@ -602,9 +598,10 @@ async fn create_trigger<T: TriggerCrud>(
|
||||
windmill_common::auth::validate_on_behalf_of(Some(&resolved_permissioned_as), None)?;
|
||||
|
||||
let on_behalf_of_info = windmill_common::check_on_behalf_of_preservation(
|
||||
Some(&resolved_permissioned_as),
|
||||
new_trigger.base.permissioned_as.as_deref(),
|
||||
new_trigger.base.preserve_permissioned_as.unwrap_or(false),
|
||||
&windmill_common::users::username_to_permissioned_as(&authed.username),
|
||||
&authed,
|
||||
&authed.username,
|
||||
);
|
||||
|
||||
handler
|
||||
@@ -865,19 +862,16 @@ async fn update_trigger<T: TriggerCrud>(
|
||||
let new_path = edit_trigger.base.path.to_string();
|
||||
let labels = edit_trigger.base.labels.clone();
|
||||
|
||||
edit_trigger
|
||||
.base
|
||||
.check_deploy_as(&authed, &workspace_id, &db)
|
||||
.await?;
|
||||
// Reject a forged superadmin run identity in a preserved permissioned_as
|
||||
// (the sentinel guard; a trigger's email is derived from it at execution).
|
||||
let resolved_permissioned_as = edit_trigger.base.resolve_permissioned_as(&authed);
|
||||
windmill_common::auth::validate_on_behalf_of(Some(&resolved_permissioned_as), None)?;
|
||||
|
||||
let on_behalf_of_info = windmill_common::check_on_behalf_of_preservation(
|
||||
Some(&resolved_permissioned_as),
|
||||
edit_trigger.base.permissioned_as.as_deref(),
|
||||
edit_trigger.base.preserve_permissioned_as.unwrap_or(false),
|
||||
&windmill_common::users::username_to_permissioned_as(&authed.username),
|
||||
&authed,
|
||||
&authed.username,
|
||||
);
|
||||
|
||||
let before =
|
||||
|
||||
@@ -181,31 +181,9 @@ pub struct BaseTriggerData {
|
||||
pub preserve_permissioned_as: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub labels: Option<Vec<String>>,
|
||||
/// Set by [`Self::check_deploy_as`]: the caller is on the deployers list of the service
|
||||
/// account `permissioned_as` names.
|
||||
#[serde(skip)]
|
||||
deploy_as_admitted: bool,
|
||||
}
|
||||
|
||||
impl BaseTriggerData {
|
||||
/// Lets [`Self::resolve_permissioned_as`], which every trigger kind calls synchronously, keep
|
||||
/// a service account for someone its deployers list names. Without it only admins and
|
||||
/// `wm_deployers` keep the requested identity.
|
||||
pub async fn check_deploy_as(
|
||||
&mut self,
|
||||
authed: &impl Authable,
|
||||
w_id: &str,
|
||||
db: &sqlx::Pool<sqlx::Postgres>,
|
||||
) -> windmill_common::error::Result<()> {
|
||||
self.deploy_as_admitted = match (&self.permissioned_as, self.preserve_permissioned_as) {
|
||||
(Some(target), Some(true)) => {
|
||||
windmill_common::can_deploy_as(authed, target, w_id, db).await?
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> &TriggerMode {
|
||||
self.mode.as_ref().unwrap_or(
|
||||
#[allow(deprecated)]
|
||||
@@ -235,7 +213,7 @@ impl BaseTriggerData {
|
||||
pub fn resolve_permissioned_as(&self, authed: &impl Authable) -> String {
|
||||
if let Some(ref permissioned_as) = self.permissioned_as {
|
||||
if self.preserve_permissioned_as.unwrap_or(false)
|
||||
&& (self.deploy_as_admitted || windmill_common::can_preserve_on_behalf_of(authed))
|
||||
&& windmill_common::can_preserve_on_behalf_of(authed)
|
||||
{
|
||||
return permissioned_as.clone();
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import Cell from './table/Cell.svelte'
|
||||
import RowIcon from './common/table/RowIcon.svelte'
|
||||
import { GranularAclService, type AccessReason, type PrincipalAccess } from '$lib/gen'
|
||||
import { userStore, workspaceStore } from '$lib/stores'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import type { Item } from '$lib/utils'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
@@ -19,7 +19,6 @@
|
||||
import GrantNavigator, { navigatorMaxHeight } from './access/GrantNavigator.svelte'
|
||||
import { KIND_LABELS, setGrant, type GrantLevel } from './access/access'
|
||||
import type { RunnableKind } from './access/detectNeeds'
|
||||
import DeployersField from './access/DeployersField.svelte'
|
||||
|
||||
type Target = 'self' | 'user' | 'service_account' | 'group'
|
||||
|
||||
@@ -27,7 +26,6 @@
|
||||
|
||||
let drawer: Drawer | undefined = $state()
|
||||
let principal = $state('')
|
||||
let target: Target = $state('user')
|
||||
let access: PrincipalAccess | undefined = $state()
|
||||
let error: string | undefined = $state()
|
||||
let search = $state('')
|
||||
@@ -40,9 +38,8 @@
|
||||
// Responses are not ordered: a slow answer for the previous principal must not land on this one.
|
||||
let requestId = 0
|
||||
|
||||
export async function open(nextPrincipal: string, nextTarget: Target): Promise<void> {
|
||||
export async function open(nextPrincipal: string, target: Target): Promise<void> {
|
||||
principal = nextPrincipal
|
||||
target = nextTarget
|
||||
access = undefined
|
||||
error = undefined
|
||||
search = ''
|
||||
@@ -51,7 +48,7 @@
|
||||
grantOpen = false
|
||||
needsOf = undefined
|
||||
drawer?.openDrawer()
|
||||
logFeatureUsage('access_view', 'opened', { key: nextTarget })
|
||||
logFeatureUsage('access_view', 'opened', { key: target })
|
||||
await reload()
|
||||
}
|
||||
|
||||
@@ -214,13 +211,6 @@
|
||||
{principal} is an admin of this workspace and can read and write every item in it.
|
||||
</Alert>
|
||||
{:else}
|
||||
{#if target === 'service_account' && $userStore?.is_admin}
|
||||
<Section label="Who can deploy as it" small>
|
||||
{#key principal}
|
||||
<DeployersField {principal} {access} />
|
||||
{/key}
|
||||
</Section>
|
||||
{/if}
|
||||
<Section label="Groups" small>
|
||||
{#if access.groups.length}
|
||||
<div class="flex flex-wrap gap-1">
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<script lang="ts">
|
||||
import DeployOnBehalfOfDialog from '$lib/components/itemSettings/DeployOnBehalfOfDialog.svelte'
|
||||
import { useDeployAs } from '$lib/components/access/deployAs.svelte'
|
||||
import { dropStalePending } from '$lib/components/access/serviceAccounts.svelte'
|
||||
import { deployAsksOnBehalfOf } from '$lib/components/itemSettings/onBehalfOf'
|
||||
import { useFolderDefaultPermissionedAs } from '$lib/components/useFolderDefaultPermissionedAs.svelte'
|
||||
@@ -143,7 +142,6 @@
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
const operatingUser = useOperatingUser()
|
||||
const actingUser = $derived(operatingUser.current)
|
||||
const deployAs = useDeployAs(() => $operatingWorkspace)
|
||||
|
||||
let {
|
||||
initialPath = $bindable(''),
|
||||
@@ -511,8 +509,7 @@
|
||||
permissionedAs: flowStore.val.on_behalf_of,
|
||||
savedEmail: deployed?.on_behalf_of_email,
|
||||
savedPermissionedAs: deployed?.on_behalf_of,
|
||||
folderDefault: folderDefault.value,
|
||||
deployAs: deployAs.current
|
||||
folderDefault: folderDefault.value
|
||||
})
|
||||
) {
|
||||
deployDialogMsg = deploymentMsg ?? ''
|
||||
|
||||
@@ -33,7 +33,6 @@
|
||||
import { Drawer, DrawerContent } from './common'
|
||||
import { enterpriseLicense, userStore } from '$lib/stores'
|
||||
import { UserService, type User } from '$lib/gen'
|
||||
import { useDeployAs } from './access/deployAs.svelte'
|
||||
import {
|
||||
getPendingServiceAccount,
|
||||
PENDING_EMAIL_DOMAIN,
|
||||
@@ -148,15 +147,6 @@
|
||||
myPermissionedAs ?? ($userStore?.username ? `u/${$userStore.username}` : undefined)
|
||||
)
|
||||
|
||||
// Without `canPreserve`, the service accounts whose deployers list admits the user are still
|
||||
// theirs to pick or keep.
|
||||
const deployAs = useDeployAs(() => targetWorkspace)
|
||||
const canPick = $derived(canPreserve || deployAs.current.length > 0)
|
||||
function allowed(value: string | undefined): boolean {
|
||||
const name = resolveDisplayName(value)
|
||||
return canPreserve || (!!name && deployAs.current.includes(name))
|
||||
}
|
||||
|
||||
const serviceAccounts = useServiceAccounts(() => targetWorkspace)
|
||||
|
||||
type Row = {
|
||||
@@ -188,7 +178,7 @@
|
||||
|
||||
const listed: Omit<Row, 'label'>[] = [
|
||||
...serviceAccounts.current
|
||||
.filter((a) => a.pending || canPreserve || deployAs.current.includes(`u/${a.username}`))
|
||||
.filter((a) => a.pending || canPreserve)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Number(!!b.pending) - Number(!!a.pending) || a.username.localeCompare(b.username)
|
||||
@@ -226,7 +216,7 @@
|
||||
value: name,
|
||||
group: GROUP_OF[rowKind],
|
||||
kind: rowKind,
|
||||
disabled: name !== myDisplayName && !allowed(targetValue)
|
||||
disabled: name !== myDisplayName && !canPreserve
|
||||
}
|
||||
})
|
||||
// Select draws a header wherever the group changes, so each group's rows must be contiguous.
|
||||
@@ -241,7 +231,7 @@
|
||||
|
||||
function pick(value: string | undefined) {
|
||||
if (!value) return
|
||||
if (targetValue && value === targetDisplayName && allowed(targetValue)) {
|
||||
if (targetValue && value === targetDisplayName && canPreserve) {
|
||||
onSelect('target')
|
||||
} else if (value === myDisplayName) {
|
||||
onSelect('me')
|
||||
@@ -300,9 +290,9 @@
|
||||
// We track `users.length` so the effect re-runs once the async user list loads.
|
||||
$effect(() => {
|
||||
if (selected !== undefined) return
|
||||
if (targetValue && allowed(targetValue)) {
|
||||
if (targetValue && canPreserve) {
|
||||
onSelect('target')
|
||||
} else if (folderDefault && allowed(folderDefault) && users.length > 0) {
|
||||
} else if (folderDefault && canPreserve && users.length > 0) {
|
||||
const username = folderDefault.startsWith('u/') ? folderDefault.slice(2) : folderDefault
|
||||
const email = users.find((u) => u.username === username)?.email ?? folderDefault
|
||||
onSelect('custom', { email, permissionedAs: folderDefault })
|
||||
@@ -325,7 +315,7 @@
|
||||
<UserCog size={14} class={selected ? 'text-green-500' : 'text-yellow-500'} />
|
||||
{/snippet}
|
||||
|
||||
{#if readOnlyWithoutPreserve && !canPick}
|
||||
{#if readOnlyWithoutPreserve && !canPreserve}
|
||||
<span class="inline-flex items-center gap-1 text-xs text-secondary">
|
||||
<UserIcon class="w-4 h-4" />
|
||||
{myDisplayName}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<script lang="ts">
|
||||
import DeployOnBehalfOfDialog from '$lib/components/itemSettings/DeployOnBehalfOfDialog.svelte'
|
||||
import { useDeployAs } from '$lib/components/access/deployAs.svelte'
|
||||
import { dropStalePending } from '$lib/components/access/serviceAccounts.svelte'
|
||||
import { deployAsksOnBehalfOf } from '$lib/components/itemSettings/onBehalfOf'
|
||||
import { useFolderDefaultPermissionedAs } from '$lib/components/useFolderDefaultPermissionedAs.svelte'
|
||||
@@ -238,7 +237,6 @@
|
||||
const operatingUser = useOperatingUser()
|
||||
const actingUser = $derived(operatingUser.current)
|
||||
const opWorkspace = $derived(autosaveWorkspace ?? $operatingWorkspace)
|
||||
const deployAs = useDeployAs(() => $operatingWorkspace)
|
||||
const indicatorPath = $derived(autosavePath ?? userDraftPath)
|
||||
dropStalePending(
|
||||
untrack(() => opWorkspace),
|
||||
@@ -682,8 +680,7 @@
|
||||
permissionedAs: script.on_behalf_of,
|
||||
savedEmail: deployed?.on_behalf_of_email,
|
||||
savedPermissionedAs: deployed?.on_behalf_of,
|
||||
folderDefault: folderDefault.value,
|
||||
deployAs: deployAs.current
|
||||
folderDefault: folderDefault.value
|
||||
})
|
||||
) {
|
||||
deployDialogStay = stay
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/common'
|
||||
import { GranularAclService, type PrincipalAccess } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import DeployersPicker from './DeployersPicker.svelte'
|
||||
|
||||
let {
|
||||
principal,
|
||||
access
|
||||
}: {
|
||||
/** `u/<service account>` */
|
||||
principal: string
|
||||
access: PrincipalAccess
|
||||
} = $props()
|
||||
|
||||
let saved: string[] = $state([])
|
||||
let deployers: string[] = $state([])
|
||||
let saving = $state(false)
|
||||
let loaded = $state(false)
|
||||
|
||||
async function load(): Promise<void> {
|
||||
const list = await GranularAclService.getServiceAccountDeployers({
|
||||
workspace: $workspaceStore!,
|
||||
principal
|
||||
})
|
||||
saved = list.deployers
|
||||
deployers = [...list.deployers]
|
||||
loaded = true
|
||||
}
|
||||
load().catch((e) => sendUserToast(`Could not load deployers: ${e?.body ?? e}`, true))
|
||||
|
||||
const dirty = $derived(
|
||||
deployers.length !== saved.length || deployers.some((d) => !saved.includes(d))
|
||||
)
|
||||
const reads = $derived(access.items.map((i) => i.path))
|
||||
|
||||
async function save(): Promise<void> {
|
||||
saving = true
|
||||
try {
|
||||
await GranularAclService.setServiceAccountDeployers({
|
||||
workspace: $workspaceStore!,
|
||||
requestBody: { principal, deployers }
|
||||
})
|
||||
saved = [...deployers]
|
||||
sendUserToast(`Saved who can deploy as ${principal}`)
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not save: ${e?.body ?? e}`, true)
|
||||
} finally {
|
||||
saving = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<p class="text-2xs text-secondary">
|
||||
These people can deploy scripts, flows, apps, schedules and triggers that run as {principal}.
|
||||
Workspace admins and members of wm_deployers always can. Anyone else who deploys an item set to
|
||||
run as {principal} makes it run as themselves.
|
||||
</p>
|
||||
{#if loaded}
|
||||
<DeployersPicker {principal} bind:deployers {reads} />
|
||||
<div>
|
||||
<Button variant="accent" unifiedSize="sm" disabled={!dirty} loading={saving} onClick={save}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,96 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Button } from '$lib/components/common'
|
||||
import Select from '$lib/components/select/Select.svelte'
|
||||
import { FolderService, GroupService, UserService } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { Folder, User, Users, X } from 'lucide-svelte'
|
||||
|
||||
let {
|
||||
principal,
|
||||
deployers = $bindable(),
|
||||
reads
|
||||
}: {
|
||||
/** `u/<service account>` */
|
||||
principal: string
|
||||
deployers: string[]
|
||||
/** Paths of the items and folders (`f/<name>`) the account reads. */
|
||||
reads: string[]
|
||||
} = $props()
|
||||
|
||||
let options: { value: string; label: string }[] = $state([])
|
||||
|
||||
async function loadOptions(): Promise<void> {
|
||||
const workspace = $workspaceStore!
|
||||
const [users, groups, folders] = await Promise.all([
|
||||
UserService.listUsernames({ workspace }),
|
||||
GroupService.listGroupNames({ workspace }),
|
||||
FolderService.listFolderNames({ workspace })
|
||||
])
|
||||
options = [
|
||||
...users.filter((u) => `u/${u}` !== principal).map((u) => `u/${u}`),
|
||||
...groups.map((g) => `g/${g}`),
|
||||
...folders.map((f) => `f/${f}`)
|
||||
].map((value) => ({
|
||||
value,
|
||||
label: value.startsWith('f/') ? `${value} (whoever can write in it)` : value
|
||||
}))
|
||||
}
|
||||
loadOptions().catch(() => (options = []))
|
||||
|
||||
const available = $derived(options.filter((o) => !deployers.includes(o.value)))
|
||||
|
||||
// Folders on the list are reachable by their writers already: what the list hands over beyond
|
||||
// that is everything else the account reads.
|
||||
const listedFolders = $derived(deployers.filter((d) => d.startsWith('f/')))
|
||||
const beyond = $derived(
|
||||
reads.filter((p) => !listedFolders.some((f) => p === f || p.startsWith(`${f}/`)))
|
||||
)
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex flex-wrap items-center gap-1">
|
||||
{#each deployers as entry (entry)}
|
||||
<span
|
||||
class="inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-2xs text-primary"
|
||||
>
|
||||
{#if entry.startsWith('f/')}
|
||||
<Folder size={12} />
|
||||
Writers of {entry}
|
||||
{:else if entry.startsWith('g/')}
|
||||
<Users size={12} />
|
||||
{entry}
|
||||
{:else}
|
||||
<User size={12} />
|
||||
{entry}
|
||||
{/if}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="2xs"
|
||||
iconOnly
|
||||
startIcon={{ icon: X }}
|
||||
title={`Remove ${entry}`}
|
||||
onClick={() => (deployers = deployers.filter((d) => d !== entry))}
|
||||
/>
|
||||
</span>
|
||||
{/each}
|
||||
<span class="text-2xs text-secondary">
|
||||
{deployers.length ? '+ admins and wm_deployers' : 'Only admins and wm_deployers.'}
|
||||
</span>
|
||||
</div>
|
||||
<div class="w-72">
|
||||
<Select
|
||||
items={available}
|
||||
bind:value={() => undefined, (v) => v && (deployers = [...deployers, v])}
|
||||
placeholder="Add a user, group or folder"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
{#if deployers.length && beyond.length}
|
||||
<Alert type="warning" size="xs" title={`They can read what ${principal} reads`}>
|
||||
Through {principal}, people on this list can read {beyond.length}
|
||||
{beyond.length === 1 ? 'item' : 'items'} outside the folders it names: {beyond
|
||||
.slice(0, 5)
|
||||
.join(', ')}{beyond.length > 5 ? ', …' : ''}.
|
||||
</Alert>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,33 +0,0 @@
|
||||
import { resource } from 'runed'
|
||||
import { GranularAclService } from '$lib/gen'
|
||||
|
||||
// Every run-as control on a page asks, so one request per workspace serves them for a minute.
|
||||
const TTL_MS = 60_000
|
||||
const asked = new Map<string, { at: number; accounts: Promise<string[]> }>()
|
||||
|
||||
function fetchDeployAs(workspace: string): Promise<string[]> {
|
||||
const hit = asked.get(workspace)
|
||||
if (hit && Date.now() - hit.at < TTL_MS) return hit.accounts
|
||||
const accounts = GranularAclService.listDeployAs({ workspace }).then(
|
||||
(res) => res.service_accounts.map((a) => `u/${a.username}`),
|
||||
() => []
|
||||
)
|
||||
asked.set(workspace, { at: Date.now(), accounts })
|
||||
return accounts
|
||||
}
|
||||
|
||||
export function forgetDeployAs(workspace: string): void {
|
||||
asked.delete(workspace)
|
||||
}
|
||||
|
||||
/** The service accounts the current user may deploy as in `workspace`, as `u/<username>`: those
|
||||
* whose deployers list names them, one of their groups, or a folder they write in. Admins and
|
||||
* `wm_deployers` get every account, and may deploy as anyone besides. */
|
||||
export function useDeployAs(workspace: () => string | undefined) {
|
||||
const accounts = resource(workspace, (ws) => (ws ? fetchDeployAs(ws) : Promise.resolve([])))
|
||||
return {
|
||||
get current(): string[] {
|
||||
return accounts.current ?? []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,6 @@
|
||||
import OnBehalfOfSelector, {
|
||||
type OnBehalfOfChoice
|
||||
} from '$lib/components/OnBehalfOfSelector.svelte'
|
||||
import { useDeployAs } from '$lib/components/access/deployAs.svelte'
|
||||
import { canDeployAs } from '$lib/components/itemSettings/onBehalfOf'
|
||||
import RunAsNotes from '$lib/components/access/RunAsNotes.svelte'
|
||||
import { dropStalePending } from '$lib/components/access/serviceAccounts.svelte'
|
||||
import type { NeedsSource } from '$lib/components/access/detectNeeds'
|
||||
@@ -174,13 +172,12 @@
|
||||
let onBehalfOfChoice: OnBehalfOfChoice = $state(undefined)
|
||||
let customOnBehalfOfEmail: string = $state('')
|
||||
let myOnBehalfOf = $derived(actingUser?.username ? `u/${actingUser.username}` : undefined)
|
||||
const deployAs = useDeployAs(() => opWs)
|
||||
// The backend runs the redeployed app as the deployer whatever the policy says when they may
|
||||
// not deploy as its user, as it does for "me".
|
||||
// Without the right to preserve, the backend runs the redeployed app as the deployer whatever
|
||||
// the policy says, as it does for "me".
|
||||
let deployOnBehalfOf = $derived.by(() => {
|
||||
if (onBehalfOfChoice === 'me') return myOnBehalfOf
|
||||
const kept = onBehalfOfChoice === 'custom' ? policy.on_behalf_of : savedOnBehalfOf
|
||||
return canDeployAs(actingUser, kept, deployAs.current) ? kept : myOnBehalfOf
|
||||
if (!canPreserve || onBehalfOfChoice === 'me') return myOnBehalfOf
|
||||
if (onBehalfOfChoice === 'custom') return policy.on_behalf_of
|
||||
return savedOnBehalfOf
|
||||
})
|
||||
let onBehalfOfWillChange = $derived(
|
||||
!newApp && !!savedOnBehalfOf && !!deployOnBehalfOf && deployOnBehalfOf !== savedOnBehalfOf
|
||||
@@ -388,10 +385,6 @@
|
||||
<div class="text-2xs text-secondary">
|
||||
{#if canPreserve}
|
||||
Viewers run the app's runnables as this user.
|
||||
{:else if deployAs.current.length}
|
||||
Viewers run the app's runnables as this user. You can pick the service accounts that list
|
||||
you as a deployer; only workspace admins and members of {WM_DEPLOYERS_GROUP} can pick anyone
|
||||
else.
|
||||
{:else}
|
||||
Only workspace admins and members of {WM_DEPLOYERS_GROUP} can pick another user.
|
||||
{/if}
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
import RunOnBehalfOfSetting from './RunOnBehalfOfSetting.svelte'
|
||||
import { appOnBehalfOfTooltip, deployedPermissionedAs } from './onBehalfOf'
|
||||
import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte'
|
||||
import { useDeployAs } from '$lib/components/access/deployAs.svelte'
|
||||
import {
|
||||
createPendingServiceAccount,
|
||||
getPendingServiceAccount
|
||||
@@ -70,9 +69,8 @@
|
||||
const on = $derived(required || !!email)
|
||||
// A flow or script whose deployed version ran on behalf of someone, turned off by this deploy.
|
||||
const stops = $derived(!on && !!savedUser)
|
||||
const deployAs = useDeployAs(() => targetWorkspace)
|
||||
const runsAs = $derived(
|
||||
deployedPermissionedAs(operatingUser.current, permissionedAs, folderDefault, deployAs.current)
|
||||
deployedPermissionedAs(operatingUser.current, permissionedAs, folderDefault)
|
||||
)
|
||||
const who = $derived(!runsAs ? 'you' : runsAs === me ? `${runsAs} (you)` : runsAs)
|
||||
const unchanged = $derived(!isNew && !!savedPermissionedAs && runsAs === savedPermissionedAs)
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
import { AlertTriangle } from 'lucide-svelte'
|
||||
import SettingToggle from './SettingToggle.svelte'
|
||||
import { canPreserveOnBehalfOf, deployedPermissionedAs, WM_DEPLOYERS_GROUP } from './onBehalfOf'
|
||||
import { useDeployAs } from '$lib/components/access/deployAs.svelte'
|
||||
import { useServiceAccounts } from '$lib/components/access/serviceAccounts.svelte'
|
||||
import type { NeedsSource } from '$lib/components/access/detectNeeds'
|
||||
const DOCS_LINK =
|
||||
@@ -69,7 +68,6 @@
|
||||
const operatingUser = useOperatingUser()
|
||||
const actingUser = $derived(operatingUser.current)
|
||||
let canPreserve = $derived(canPreserveOnBehalfOf(actingUser))
|
||||
const deployAs = useDeployAs(() => targetWorkspace)
|
||||
// "Me" is the acting user in the target workspace, its username and its email alike: usernames
|
||||
// are per-workspace, and the backend rejects a pair that names two accounts.
|
||||
let myPermissionedAs = $derived(actingUser?.username ? `u/${actingUser.username}` : undefined)
|
||||
@@ -93,9 +91,7 @@
|
||||
|
||||
let enabled = $derived(required || !!email)
|
||||
let deployPermissionedAs = $derived(
|
||||
enabled
|
||||
? deployedPermissionedAs(actingUser, permissionedAs, folderDefault, deployAs.current)
|
||||
: undefined
|
||||
enabled ? deployedPermissionedAs(actingUser, permissionedAs, folderDefault) : undefined
|
||||
)
|
||||
// Whoever cannot keep another user's identity deploys the item as themselves.
|
||||
let chosenUser = $derived(
|
||||
@@ -179,12 +175,7 @@
|
||||
{/if}
|
||||
{#if !canPreserve}
|
||||
<div class="text-2xs text-secondary">
|
||||
{#if deployAs.current.length}
|
||||
You can pick the service accounts that list you as a deployer. Only workspace admins and
|
||||
members of {WM_DEPLOYERS_GROUP} can pick anyone else.
|
||||
{:else}
|
||||
Only workspace admins and members of {WM_DEPLOYERS_GROUP} can pick another user.
|
||||
{/if}
|
||||
Only workspace admins and members of {WM_DEPLOYERS_GROUP} can pick another user.
|
||||
</div>
|
||||
{/if}
|
||||
{#if !hideDescription}
|
||||
|
||||
@@ -20,28 +20,17 @@ export function canPreserveOnBehalfOf(user: DeployingUser): boolean {
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether `user` may deploy an item running as `target`: anyone for admins and deployers, and
|
||||
* for everyone the service accounts in `deployAs` (see `useDeployAs`). */
|
||||
export function canDeployAs(
|
||||
user: DeployingUser,
|
||||
target: string | undefined,
|
||||
deployAs: string[] = []
|
||||
): boolean {
|
||||
return canPreserveOnBehalfOf(user) || (!!target && deployAs.includes(target))
|
||||
}
|
||||
|
||||
/** The `u/username` a deploy leaves the item running on behalf of. The editors send the user their
|
||||
* deploy dialog confirmed, which the backend keeps for a deployer who may deploy as it and
|
||||
* replaces with the deployer otherwise. With no user held, a create takes the folder's default
|
||||
* for the path. */
|
||||
* deploy dialog confirmed, which the backend keeps for a deployer who may preserve and replaces
|
||||
* with the deployer for anyone else. With no user held, a create takes the folder's default for
|
||||
* the path. */
|
||||
export function deployedPermissionedAs(
|
||||
user: DeployingUser,
|
||||
permissionedAs: string | undefined,
|
||||
folderDefault?: string,
|
||||
deployAs: string[] = []
|
||||
folderDefault?: string
|
||||
): string | undefined {
|
||||
const kept = permissionedAs ?? folderDefault
|
||||
if (kept && canDeployAs(user, kept, deployAs)) return kept
|
||||
if (kept && canPreserveOnBehalfOf(user)) return kept
|
||||
return user?.username ? `u/${user.username}` : undefined
|
||||
}
|
||||
|
||||
@@ -58,7 +47,6 @@ export function deployAsksOnBehalfOf(
|
||||
savedEmail: string | undefined
|
||||
savedPermissionedAs: string | undefined
|
||||
folderDefault?: string
|
||||
deployAs?: string[]
|
||||
}
|
||||
): boolean {
|
||||
if (kind === 'app') return true
|
||||
@@ -66,12 +54,8 @@ export function deployAsksOnBehalfOf(
|
||||
if (!deploy.email && !deploy.folderDefault) return deployedHoldsUser
|
||||
if (!deployedHoldsUser) return true
|
||||
return (
|
||||
deployedPermissionedAs(
|
||||
deploy.user,
|
||||
deploy.permissionedAs,
|
||||
deploy.folderDefault,
|
||||
deploy.deployAs
|
||||
) !== deploy.savedPermissionedAs
|
||||
deployedPermissionedAs(deploy.user, deploy.permissionedAs, deploy.folderDefault) !==
|
||||
deploy.savedPermissionedAs
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
import { useFolderDefaultPermissionedAs } from '$lib/components/useFolderDefaultPermissionedAs.svelte'
|
||||
import { userStore } from '$lib/stores'
|
||||
import { AlertTriangle } from 'lucide-svelte'
|
||||
import { useDeployAs } from '$lib/components/access/deployAs.svelte'
|
||||
import {
|
||||
useOperatingUser,
|
||||
useOperatingWorkspace
|
||||
@@ -41,12 +40,6 @@
|
||||
const canPreserve = $derived(
|
||||
actingUser?.is_admin || (actingUser?.groups ?? []).includes('wm_deployers')
|
||||
)
|
||||
const deployAs = useDeployAs(() => wsId)
|
||||
// Someone a service account's deployers list names may pick it, and keep it on save.
|
||||
const canPick = $derived(canPreserve || deployAs.current.length > 0)
|
||||
const keepsCurrent = $derived(
|
||||
canPreserve || (!!permissionedAs && deployAs.current.includes(permissionedAs))
|
||||
)
|
||||
|
||||
const myPermissionedAs = $derived($userStore?.username ? `u/${$userStore.username}` : undefined)
|
||||
|
||||
@@ -91,7 +84,9 @@
|
||||
permissionedAs !== effectivePermissionedAs
|
||||
)
|
||||
|
||||
const shouldRender = $derived(!!wsId && (permissionedAs !== undefined || (canPick && !disabled)))
|
||||
const shouldRender = $derived(
|
||||
!!wsId && (permissionedAs !== undefined || (canPreserve && !disabled))
|
||||
)
|
||||
|
||||
// For non-admin users editing a trigger owned by someone else: signal that
|
||||
// permissioned_as will change to the current user (backend ignores preserve for non-admins).
|
||||
@@ -99,8 +94,7 @@
|
||||
$effect(() => {
|
||||
if (
|
||||
!disabled &&
|
||||
!canPick &&
|
||||
!keepsCurrent &&
|
||||
!canPreserve &&
|
||||
permissionedAs !== undefined &&
|
||||
permissionedAs !== myPermissionedAs
|
||||
) {
|
||||
@@ -127,7 +121,7 @@
|
||||
{#if shouldRender && wsId}
|
||||
<div class="flex items-center gap-1.5 text-2xs text-tertiary mb-4">
|
||||
<span>Permissioned as</span>
|
||||
{#if canPick && !disabled}
|
||||
{#if canPreserve && !disabled}
|
||||
<OnBehalfOfSelector
|
||||
targetWorkspace={wsId}
|
||||
targetValue={permissionedAs}
|
||||
|
||||
@@ -4,12 +4,11 @@ import { resource } from 'runed'
|
||||
import { fromStore } from 'svelte/store'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { useActingUser } from '$lib/actingUser.svelte'
|
||||
import { canDeployAs, canPreserveOnBehalfOf } from './itemSettings/onBehalfOf'
|
||||
import { useDeployAs } from './access/deployAs.svelte'
|
||||
import { canPreserveOnBehalfOf } from './itemSettings/onBehalfOf'
|
||||
|
||||
/**
|
||||
* Resolves the folder's `default_permissioned_as` rule that matches a given item path.
|
||||
* Returns `undefined` when the user may not deploy as that default, the path is not under a
|
||||
* Returns `undefined` when the user is not admin/wm_deployer, the path is not under a
|
||||
* folder, the folder has no matching rules, or the fetch fails.
|
||||
*
|
||||
* The rights are the acting user's in the resolved workspace, as the backend checks them there:
|
||||
@@ -25,21 +24,11 @@ export function useFolderDefaultPermissionedAs(
|
||||
const navWorkspace = fromStore(workspaceStore)
|
||||
const workspace = () => wsGetter?.() ?? navWorkspace.current
|
||||
const acting = useActingUser(workspace)
|
||||
const deployAs = useDeployAs(workspace)
|
||||
|
||||
const folderResource = resource(
|
||||
() => ({
|
||||
path: pathGetter(),
|
||||
workspace: workspace(),
|
||||
user: acting.current,
|
||||
deployAs: deployAs.current
|
||||
}),
|
||||
async ({ path, workspace, user, deployAs }) => {
|
||||
if (
|
||||
!(canPreserveOnBehalfOf(user) || deployAs.length > 0) ||
|
||||
!workspace ||
|
||||
!path?.startsWith('f/')
|
||||
) {
|
||||
() => ({ path: pathGetter(), workspace: workspace(), user: acting.current }),
|
||||
async ({ path, workspace, user }) => {
|
||||
if (!canPreserveOnBehalfOf(user) || !workspace || !path?.startsWith('f/')) {
|
||||
return undefined
|
||||
}
|
||||
const parts = path.split('/')
|
||||
@@ -58,10 +47,7 @@ export function useFolderDefaultPermissionedAs(
|
||||
return false
|
||||
}
|
||||
})
|
||||
// The backend applies the default only for someone who may deploy as it.
|
||||
return canDeployAs(user, match?.permissioned_as, deployAs)
|
||||
? match?.permissioned_as
|
||||
: undefined
|
||||
return match?.permissioned_as
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
@@ -75,7 +61,8 @@ export function useFolderDefaultPermissionedAs(
|
||||
get loading() {
|
||||
const ws = workspace()
|
||||
return (
|
||||
folderResource.loading || (!!ws && !!pathGetter()?.startsWith('f/') && !acting.resolved(ws))
|
||||
folderResource.loading ||
|
||||
(!!ws && !!pathGetter()?.startsWith('f/') && !acting.resolved(ws))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user