mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-10-27 16:02:43 +00:00
* feat: run a workspace handler when a secret variable expires Secret variables gain an optional `value_expires_at`, and a workspace can point at a script or flow to run once that date passes, so a rotation is driven by the platform instead of tracked out of band. The secret never leaves the database. The sweep selects the path, description and expiry and nothing else, so the handler is given a reference to rotate rather than a value to handle. Job results are stored in cleartext and shown in Runs, which is what makes that a boundary rather than a preference; a test asserts the job's args never contain the value. Each row is claimed by writing `expiration_dispatched_for` in the same transaction as the push, so a failed push un-claims it and a lost race claims nothing. Moving the date re-arms the row; re-saving the same date does not. A pass takes at most 100 rows under a transaction-scoped advisory lock, and orders so that one broken workspace cannot starve the rest. Dispatch runs as `g/variable_expiration_handler`, exempt from the CE group limit and from non-premium exec metering the way the error and schedule handlers already are. A handler that keeps failing backs off and raises a critical alert instead of retrying every pass, and the back-off ends when the handler is repointed. The expiry travels with the variable through workspace clone, tarball export and workspace comparison. The dispatch marker deliberately does not, so a fork re-arms on its own copy. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(frontend): expose variable value expiration in the UI The variable drawer takes an optional expiry on a secret value, and the variables list badges it, turning red once the date has passed. A workspace settings tab picks the handler, its extra args, and whether variables under `u/` are skipped. That mute flag is stored inside the handler setting, so the toggle stays disabled until a handler is picked: saving it on its own would clear the setting it lives in and still report success. The expiry is carried as a tri-state through the draft deploy and copilot paths — absent leaves the remote value alone, an explicit null clears it — so deploying a draft cannot silently drop a date someone set elsewhere. The settings tab names the one case where the configured identity does not apply: a handler script carrying `on_behalf_of` runs as that user rather than as `g/variable_expiration_handler`, which matters because the same tab asks the admin to grant that group write access to the variables it rotates. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(cli): sync variable expiry and the workspace expiration handler `wmill sync` carries `value_expires_at` on variables in both directions, and pushes the workspace handler alongside the error and success handlers in the grouped settings format. Dropping the key from a variable's yaml clears the remote expiry, so the file stays canonical rather than accumulating fields that can only ever be added. The handler follows the same rule, with the caveat recorded where the type is declared: an omitted handler only reaches the clear when some other setting differs, because the push short-circuits on a comparison that walks the local object's keys and so never sees a missing one. That gate is shared with the two existing handlers and is left as it is here. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(frontend): open the variable expiration handler template in a new tab The "Create a handler" button hands its script template to /scripts/add through the URL hash, which `load` reads from `window.location`. A client-side navigation leaves the previous page's hash in place, so the payload was dropped and the editor opened on the default template at a `u/` path. `target="_blank"` forces a full page load, matching the success handler's "Create from template" button. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(frontend): make the variable expiry field state its own status The expiry field rendered a DateTimeInput whose time defaults to 12:00 when it holds no value, so a variable with no expiry looked like one already configured, and "cleared" looked identical to "never set". Setting an expiry is optional, so the field has to say which it is. Rebuild it on the shape ScriptAdvancedSettings already uses for Timeout, Cache and Concurrency limits: a toggle whose checked state is the stored value being present, seeding a date on enable rather than revealing an empty picker, with the input under its own label. Drop `clearable` with it, so the toggle is the single way to mean "no expiry" instead of competing with an X. Stop the surrounding copy promising a run that may not happen. A handler is only dispatched if the workspace has one configured and does not skip u/ paths, so the list tooltip now states the date alone, and the form hedges both conditions, naming the u/ mute only on personal paths where it can apply. Also anchor the mute toggle's tooltip: Popover's trigger is a span around a block-level label, which stretched to the full width of its SettingCard and left the popup floating beside the card rather than under the control. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(rust-client): initialize value_expires_at in the variable models The generated `CreateVariable` / `EditVariable` structs gain the field from openapi.yaml, and client.rs builds both with exhaustive literals. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(frontend): drop extra_args when the variable expiration handler is cleared Clearing the handler nulls the whole setting server-side, extra_args included, but the tab kept its loaded copy. A handler picked afterwards without reloading was persisted with the cleared one's arguments, which the tab does not display. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat: back the variable expiration handler's built-in Slack and Teams destinations Backfills the Slack bot token grant for g/variable_expiration_handler, mirroring 20231016142659 for g/error_handler: the slack_bot folder's extra_perms is written once at Slack connect and never refreshed, and disconnecting leaves the folder behind, so workspaces that already connected Slack cannot pick the grant up from the creation-time list alone. Adds run_variable_expiration_test_job so an admin can exercise the handler on demand rather than waiting for a real expiry, which may be months away. It goes through push_variable_expiration_handler so the test run proves what matters: the handler resolves, and the group can read what it needs, under the same identity and argument shape the sweep uses. Also covers extra_args on the edit endpoint, which the settings tab now writes for the built-ins' channel. The endpoint rebuilds the setting from the request, so an omitted extra_args erases it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * feat(frontend): offer Slack and Teams as variable expiration handlers Gives the variable expiration tab the same no-code destinations the workspace error handler has, so "tell #ops before this credential expires" no longer requires writing a script. A sibling component rather than a fourth mode of ErrorOrRecoveryHandler: that one is shared with the workspace error handler and the three schedule handlers, and its stripped-args list, hub path suffixes and Email tab are all error-shaped. This reuses the pieces that are already generic (SlackConnectionStatus, TeamsConnectionStatus, ChannelSelector, ScriptPicker, SchemaForm) and leaves those five call sites untouched. extra_args stops being an API/CLI-only escape hatch now that the built-ins write their channel into it, so it joins the unsaved-changes comparison and the discard path, normalised through the existing helper that drops the two auto-managed keys. The two hub ids are placeholders until the scripts are pushed to the hub. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * fix(frontend): scope the handler identity notice to the chosen destination The notice told every admin to grant g/variable_expiration_handler write access to the variables it rotates. That is right for a custom handler and wrong for the built-ins, which only post a message and are granted the Slack bot token by migration. Following it for a Slack handler would hand a group write access to the workspace's secrets for no reason. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * feat(frontend): flag the Slack and Teams handlers as EE Connecting a workspace to Slack or Teams is EE-only (oauth2_oss.rs returns "Slack only available on enterprise"), so on CE those two tabs can never be completed. Says so up front, the way the error/success handler tab does, instead of leaving the user at a "not connected" badge with no working path. Only on those two tabs: a custom script or flow handler is CE. Drops the "Connect Slack first" alert, now that the banner and the connection badge above it already say it twice. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * chore(backend): regenerate the sqlx cache after the merge The merged workspace_settings column list in change_workspace_id is a new query text, so it needs a new cached entry. Drops the two pre-merge entries it supersedes; both had been left with conflict markers by the merge, since rename/rename markers are eight characters and escape the usual scan. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * fix(cli): narrow the expiry-clear check to a variable that exists remotely Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Do7wJTnL6MG6ngFpCGW4DG * feat(frontend): point the built-in handlers at their published hub scripts Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(backend): regenerate the sqlx cache after the merge Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(frontend): disable the Slack and Teams handler controls without a license Matches the workspace error handler, which greys out its built-in destinations and hides the test button on an unlicensed instance. The custom destination stays editable: unlike the error handler, the variable expiration handler itself is not an EE feature. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat: record which destination a variable expiration handler uses handler_configured now counts slack, teams, custom or cleared instead of set or cleared, so usage shows whether the built-in destinations are picked. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(frontend): let the variable expiration handler template run on any worker Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix: guard the variable expiration test endpoint and correct its help text * fix: reuse the error handler's slack arg and built-in path helpers * docs: trim variable expiration sweep and backfill comments * feat: put the variable value expiration under an advanced section * fix: restrict the expiration test job to built-ins and keep expiry on conflict reload * fix: link the expiry hint to the variable's workspace and document built-in test paths * fix: give the expiration sweep its own lock id and reuse double_option * fix: pin the variable expiration presets so the hub-paths test accepts them * feat: let the variable expiration handler set how far ahead it runs * fix: give the notify before expiry setting its own card * feat: remind the variable expiration handler at a set interval * fix: tighten the gap between the Slack channel field and its test button * feat: refuse a value expiry on variables linked to an OAuth account * refactor: reuse the shared handler form for variable expiration * refactor: sweep expiring variables round-robin and check the handler exists * chore: trim comments to the constraints they record * fix: compare expiry dates by moment when deploying a variable draft * refactor: rename value_expires_at to value_valid_until * fix: neutralize variable fields in expiration handler args * fix: reserve the variable_expiration_handler group name for admins * fix: send first expiry notices before reminders * test: pin that a handler failing to start leaves its rows unclaimed * chore: say any hub handler path skips the existence check * fix: empty a pre-existing handler group before granting it the Slack token * docs: correct the registered feature usage counts * fix: let a workspace whose handler failed to start sit out for an hour * fix: send first notices before reminders across workspaces * fix: end a failed handler's wait as soon as it is redeployed * fix: show an expiry-only variable change in the AI fork diff * chore: regenerate workspace tool schemas * test: keep one variable expiration guard per behavior * fix: use the renamed hub expiration handlers and template * feat: carry the variable expiry in windmill-utils-internal 1.8.4 * fix: keep the variable expiry through MCP drafts * chore: bump windmill-utils-internal to 1.8.4 * fix: keep the variable expiry through mcp deploys * fix: disable saving a slack or teams expiry handler without ee * fix: skip the failure mark when the expiry handler was saved mid-sweep * fix: count expiry telemetry only where the expiry changed * test: assert the exact variable expiry in export and cli push tests * fix: stamp an expiry handler failure with the pass's read time * fix: wait for a pending handler lock instead of marking it failed * test: isolate expiry handler tests from the deployed-script cache * fix: retry a failing expiry handler every pass instead of waiting an hour * chore: update ee-repo-ref to b6e23d229966cf0019c0a1926a254fda658d8def This commit updates the EE repository reference after PR #744 was merged in windmill-ee-private. Previous ee-repo-ref: c52c06d145b13a6fb04459e85ca5818bf3c1bff4 New ee-repo-ref: b6e23d229966cf0019c0a1926a254fda658d8def Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> Co-authored-by: hugocasa <hugo@casademont.ch>
471 lines
17 KiB
Rust
471 lines
17 KiB
Rust
use serde_json::json;
|
|
use sqlx::{Pool, Postgres};
|
|
|
|
use windmill_test_utils::*;
|
|
|
|
fn variable_url(port: u16, endpoint: &str, path: &str) -> String {
|
|
format!("http://localhost:{port}/api/w/test-workspace/variables/{endpoint}/{path}")
|
|
}
|
|
|
|
fn client() -> reqwest::Client {
|
|
reqwest::Client::new()
|
|
}
|
|
|
|
fn authed(builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
|
builder.header("Authorization", "Bearer SECRET_TOKEN")
|
|
}
|
|
|
|
async fn authed_get(port: u16, endpoint: &str, path: &str) -> reqwest::Response {
|
|
authed(client().get(variable_url(port, endpoint, path)))
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
#[sqlx::test(migrations = "../migrations", fixtures("base", "variables_test"))]
|
|
async fn test_variable_endpoints(db: Pool<Postgres>) -> anyhow::Result<()> {
|
|
initialize_tracing().await;
|
|
let server = ApiServer::start(db.clone()).await?;
|
|
let port = server.addr.port();
|
|
let base = format!("http://localhost:{port}/api/w/test-workspace/variables");
|
|
|
|
// --- exists ---
|
|
let resp = authed_get(port, "exists", "u/test-user/plain_var").await;
|
|
assert_eq!(resp.status(), 200);
|
|
assert_eq!(resp.json::<bool>().await?, true);
|
|
|
|
let resp = authed_get(port, "exists", "u/test-user/nonexistent").await;
|
|
assert_eq!(resp.status(), 200);
|
|
assert_eq!(resp.json::<bool>().await?, false);
|
|
|
|
// --- get (plain) ---
|
|
let resp = authed_get(port, "get", "u/test-user/plain_var").await;
|
|
assert_eq!(resp.status(), 200);
|
|
let body = resp.json::<serde_json::Value>().await?;
|
|
assert_eq!(body["path"], "u/test-user/plain_var");
|
|
assert_eq!(body["value"], "hello world");
|
|
assert_eq!(body["is_secret"], false);
|
|
assert_eq!(body["description"], "A plain variable");
|
|
|
|
// --- get (secret, decrypt_secret=false) ---
|
|
// fixture secrets are stored as plaintext, so skip decryption
|
|
let resp = authed(client().get(format!(
|
|
"{}/get/u/test-user/secret_var?decrypt_secret=false",
|
|
base
|
|
)))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
let body = resp.json::<serde_json::Value>().await?;
|
|
assert_eq!(body["path"], "u/test-user/secret_var");
|
|
assert_eq!(body["is_secret"], true);
|
|
assert_eq!(body["value"], serde_json::Value::Null);
|
|
|
|
// get (secret, include_encrypted=true returns raw stored value)
|
|
let resp = authed(client().get(format!(
|
|
"{}/get/u/test-user/secret_var?decrypt_secret=false&include_encrypted=true",
|
|
base
|
|
)))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
let body = resp.json::<serde_json::Value>().await?;
|
|
assert_eq!(body["is_secret"], true);
|
|
assert!(body["value"].is_string(), "expected encrypted value string");
|
|
|
|
// --- get not found ---
|
|
let resp = authed_get(port, "get", "u/test-user/nonexistent").await;
|
|
assert_eq!(resp.status(), 404);
|
|
|
|
// --- get_value (plain) ---
|
|
let resp = authed_get(port, "get_value", "u/test-user/plain_var").await;
|
|
assert_eq!(resp.status(), 200);
|
|
assert_eq!(resp.json::<String>().await?, "hello world");
|
|
|
|
let resp = authed_get(port, "get_value", "u/test-user/nonexistent").await;
|
|
assert_eq!(resp.status(), 404);
|
|
|
|
// --- list ---
|
|
let resp = authed(client().get(format!("{base}/list")))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
let list = resp.json::<Vec<serde_json::Value>>().await?;
|
|
assert!(
|
|
list.len() >= 3,
|
|
"expected at least 3 variables from fixture, got {}",
|
|
list.len()
|
|
);
|
|
assert!(list.iter().any(|v| v["path"] == "u/test-user/plain_var"));
|
|
// secrets should have null value in list
|
|
let secret = list
|
|
.iter()
|
|
.find(|v| v["path"] == "u/test-user/secret_var")
|
|
.expect("secret_var missing from list");
|
|
assert_eq!(secret["value"], serde_json::Value::Null);
|
|
|
|
// list with path_start filter
|
|
let resp = authed(client().get(format!("{base}/list?path_start=u/test-user/plain")))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
let list = resp.json::<Vec<serde_json::Value>>().await?;
|
|
assert_eq!(list.len(), 1);
|
|
assert_eq!(list[0]["path"], "u/test-user/plain_var");
|
|
|
|
// --- list_contextual ---
|
|
let resp = authed(client().get(format!("{base}/list_contextual")))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
let list = resp.json::<Vec<serde_json::Value>>().await?;
|
|
assert!(!list.is_empty());
|
|
// should contain reserved variable names like WM_TOKEN, WM_WORKSPACE
|
|
assert!(
|
|
list.iter().any(|v| v["name"] == "WM_WORKSPACE"),
|
|
"expected WM_WORKSPACE in contextual variables"
|
|
);
|
|
|
|
// --- create (plain) ---
|
|
let resp = authed(client().post(format!("{base}/create")))
|
|
.json(&json!({
|
|
"path": "u/test-user/new_var",
|
|
"value": "new_value",
|
|
"is_secret": false,
|
|
"description": "Created in test"
|
|
}))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 201);
|
|
|
|
let resp = authed_get(port, "exists", "u/test-user/new_var").await;
|
|
assert_eq!(resp.json::<bool>().await?, true);
|
|
|
|
let resp = authed_get(port, "get_value", "u/test-user/new_var").await;
|
|
assert_eq!(resp.json::<String>().await?, "new_value");
|
|
|
|
// create duplicate -> 400
|
|
let resp = authed(client().post(format!("{base}/create")))
|
|
.json(&json!({
|
|
"path": "u/test-user/new_var",
|
|
"value": "dup",
|
|
"is_secret": false,
|
|
"description": "Duplicate"
|
|
}))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 400);
|
|
|
|
// --- create (secret) ---
|
|
let resp = authed(client().post(format!("{base}/create")))
|
|
.json(&json!({
|
|
"path": "u/test-user/new_secret",
|
|
"value": "my_secret_val",
|
|
"is_secret": true,
|
|
"description": "A new secret"
|
|
}))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 201);
|
|
|
|
// secret is stored encrypted, get_value should decrypt it
|
|
let resp = authed_get(port, "get_value", "u/test-user/new_secret").await;
|
|
assert_eq!(resp.status(), 200);
|
|
assert_eq!(resp.json::<String>().await?, "my_secret_val");
|
|
|
|
// --- update (value) ---
|
|
let resp = authed(client().post(variable_url(port, "update", "u/test-user/new_var")))
|
|
.json(&json!({"value": "updated_value"}))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
|
|
let resp = authed_get(port, "get_value", "u/test-user/new_var").await;
|
|
assert_eq!(resp.json::<String>().await?, "updated_value");
|
|
|
|
// --- update (description) ---
|
|
let resp = authed(client().post(variable_url(port, "update", "u/test-user/new_var")))
|
|
.json(&json!({"description": "Updated desc"}))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
|
|
let resp = authed_get(port, "get", "u/test-user/new_var").await;
|
|
let body = resp.json::<serde_json::Value>().await?;
|
|
assert_eq!(body["description"], "Updated desc");
|
|
|
|
// --- delete ---
|
|
let resp = authed(client().delete(variable_url(port, "delete", "u/test-user/new_var")))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
|
|
let resp = authed_get(port, "exists", "u/test-user/new_var").await;
|
|
assert_eq!(resp.json::<bool>().await?, false);
|
|
|
|
// delete nonexistent -> 200 (no-op, doesn't error)
|
|
let resp = authed(client().delete(variable_url(port, "delete", "u/test-user/new_var")))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
|
|
// --- delete_bulk ---
|
|
let resp = authed(client().delete(format!("{base}/delete_bulk")))
|
|
.json(&json!({"paths": ["u/test-user/new_secret", "u/test-user/another_var"]}))
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
let deleted = resp.json::<Vec<String>>().await?;
|
|
assert_eq!(deleted.len(), 2);
|
|
|
|
let resp = authed_get(port, "exists", "u/test-user/new_secret").await;
|
|
assert_eq!(resp.json::<bool>().await?, false);
|
|
|
|
let resp = authed_get(port, "exists", "u/test-user/another_var").await;
|
|
assert_eq!(resp.json::<bool>().await?, false);
|
|
|
|
// --- encrypt ---
|
|
let resp = authed(client().post(format!("{base}/encrypt")))
|
|
.json(&"test_plaintext".to_string())
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(resp.status(), 200);
|
|
let encrypted = resp.text().await?;
|
|
assert!(!encrypted.is_empty());
|
|
assert_ne!(encrypted, "test_plaintext");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Regression test: the variable-value cache (`get_value?allow_cache=true`) must be
|
|
/// identity-scoped. test-user-2 (folder access) warms the cache; test-user-3 (no access)
|
|
/// must then be denied rather than served the cached value.
|
|
#[sqlx::test(migrations = "../migrations", fixtures("base", "variable_cache_rls"))]
|
|
async fn test_variable_value_cache_is_identity_scoped(db: Pool<Postgres>) -> anyhow::Result<()> {
|
|
initialize_tracing().await;
|
|
let server = ApiServer::start(db.clone()).await?;
|
|
let port = server.addr.port();
|
|
let url = format!(
|
|
"{}?allow_cache=true",
|
|
variable_url(port, "get_value", "f/secret/cache_target_var")
|
|
);
|
|
let get = |token: &str| {
|
|
client()
|
|
.get(url.as_str())
|
|
.header("Authorization", format!("Bearer {token}"))
|
|
};
|
|
|
|
// test-user-2 has folder access and WARMS the cache.
|
|
let resp = get("SECRET_TOKEN_2").send().await?;
|
|
assert_eq!(resp.status(), 200);
|
|
assert!(resp.text().await?.contains("LEAKED_VAR_SECRET"));
|
|
|
|
// test-user-3 has no folder access: must miss the cache and be denied (401), not leak.
|
|
let resp = get("SECRET_TOKEN_3").send().await?;
|
|
assert_eq!(resp.status(), 401);
|
|
assert!(!resp.text().await?.contains("LEAKED_VAR_SECRET"));
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Secret variables ARE cached (with their per-read side effects — the EE
|
|
/// `variables.decrypt_secret` audit and running-job secret registration — re-run on every
|
|
/// hit; that re-emission is not observable in the OSS build since `audit_log` is a no-op).
|
|
/// We assert the caching itself: warm the cache, delete the row directly (no API/NOTIFY, so
|
|
/// the in-memory cache survives), and re-read with `allow_cache=true` — the value is still
|
|
/// returned from cache. A non-secret variable behaves identically (control).
|
|
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
|
|
async fn test_variables_are_cached(db: Pool<Postgres>) -> anyhow::Result<()> {
|
|
initialize_tracing().await;
|
|
let server = ApiServer::start(db.clone()).await?;
|
|
let port = server.addr.port();
|
|
let base = format!("http://localhost:{port}/api/w/test-workspace/variables");
|
|
|
|
let plain = "u/test-user/cache_plain_probe";
|
|
let secret = "u/test-user/cache_secret_probe";
|
|
|
|
// Create one non-secret and one secret variable (the secret is stored encrypted).
|
|
for (path, value, is_secret) in [
|
|
(plain, "PLAIN_PROBE", false),
|
|
(secret, "SECRET_PROBE", true),
|
|
] {
|
|
let resp = authed(client().post(format!("{base}/create")))
|
|
.json(
|
|
&json!({ "path": path, "value": value, "is_secret": is_secret, "description": "" }),
|
|
)
|
|
.send()
|
|
.await?;
|
|
assert_eq!(resp.status(), 201);
|
|
}
|
|
|
|
let read = |path: &str| {
|
|
let url = format!("{base}/get_value/{path}?allow_cache=true");
|
|
async move { authed(client().get(url)).send().await.unwrap() }
|
|
};
|
|
|
|
// Warm the cache for both.
|
|
assert_eq!(read(plain).await.json::<String>().await?, "PLAIN_PROBE");
|
|
assert_eq!(read(secret).await.json::<String>().await?, "SECRET_PROBE");
|
|
|
|
// Delete both rows directly — bypasses the API and its NOTIFY-based invalidation, so
|
|
// the in-memory cache survives. A subsequent read can only succeed from cache.
|
|
for path in [plain, secret] {
|
|
sqlx::query("DELETE FROM variable WHERE workspace_id = 'test-workspace' AND path = $1")
|
|
.bind(path)
|
|
.execute(&db)
|
|
.await?;
|
|
}
|
|
|
|
// Both (secret included) are still served from the cache.
|
|
assert_eq!(read(plain).await.json::<String>().await?, "PLAIN_PROBE");
|
|
let resp = read(secret).await;
|
|
assert_eq!(resp.status(), 200, "secret must still be served from cache");
|
|
assert_eq!(resp.json::<String>().await?, "SECRET_PROBE");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// A draft-only row is built field by field, so a forgotten field is dropped silently.
|
|
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
|
|
async fn test_draft_only_row_carries_value_valid_until(db: Pool<Postgres>) -> anyhow::Result<()> {
|
|
initialize_tracing().await;
|
|
let server = ApiServer::start(db.clone()).await?;
|
|
let port = server.addr.port();
|
|
|
|
authed(client().post(format!(
|
|
"http://localhost:{port}/api/w/test-workspace/drafts/update/variable/u/test-user/draft_var"
|
|
)))
|
|
.json(&json!({
|
|
"value": {
|
|
"path": "u/test-user/draft_var",
|
|
"variable": { "value": "x", "is_secret": true, "description": "" },
|
|
"wsSpecific": false,
|
|
"value_valid_until": "2027-03-15T08:00:00Z"
|
|
}
|
|
}))
|
|
.send()
|
|
.await?;
|
|
|
|
let resp = authed(client().get(format!(
|
|
"http://localhost:{port}/api/w/test-workspace/variables/list?include_draft_only=true"
|
|
)))
|
|
.send()
|
|
.await?;
|
|
assert_eq!(resp.status(), 200);
|
|
let rows = resp.json::<Vec<serde_json::Value>>().await?;
|
|
|
|
let row = rows
|
|
.iter()
|
|
.find(|v| v["path"] == "u/test-user/draft_var")
|
|
.expect("draft-only row is listed");
|
|
assert_eq!(row["draft_only"], true);
|
|
assert_eq!(row["value_valid_until"], "2027-03-15T08:00:00Z");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// An expiry on an OAuth-linked variable is refused with a readable error, not a raw
|
|
/// constraint violation.
|
|
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
|
|
async fn test_oauth_variable_refuses_value_expiry(db: Pool<Postgres>) -> anyhow::Result<()> {
|
|
initialize_tracing().await;
|
|
let server = ApiServer::start(db.clone()).await?;
|
|
let port = server.addr.port();
|
|
|
|
sqlx::query(
|
|
"WITH a AS (INSERT INTO account (workspace_id, expires_at, refresh_token, client)
|
|
VALUES ('test-workspace', now() + interval '1 hour', 'r', 'github') RETURNING id)
|
|
INSERT INTO variable (workspace_id, path, value, is_secret, description, account, is_oauth)
|
|
SELECT 'test-workspace', 'u/test-user/oauth_var', 't', false, '', id, true FROM a",
|
|
)
|
|
.execute(&db)
|
|
.await?;
|
|
|
|
let resp = authed(client().post(format!(
|
|
"http://localhost:{port}/api/w/test-workspace/variables/update/u/test-user/oauth_var"
|
|
)))
|
|
.json(&json!({ "value_valid_until": "2027-03-15T08:00:00Z" }))
|
|
.send()
|
|
.await?;
|
|
assert_eq!(resp.status(), 400);
|
|
assert!(resp.text().await?.contains("OAuth"));
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Reading a variable linked to an OAuth account refreshes through it and returns the fresh token,
|
|
/// so the variable endpoints must not let a caller choose the link.
|
|
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
|
|
async fn test_variable_endpoints_ignore_account_link(db: Pool<Postgres>) -> anyhow::Result<()> {
|
|
initialize_tracing().await;
|
|
let server = ApiServer::start(db.clone()).await?;
|
|
let port = server.addr.port();
|
|
let base = format!("http://localhost:{port}/api/w/test-workspace/variables");
|
|
|
|
let account: i32 = sqlx::query_scalar(
|
|
"INSERT INTO account (workspace_id, client, expires_at, refresh_token)
|
|
VALUES ('test-workspace', 'github', now(), 'r') RETURNING id",
|
|
)
|
|
.fetch_one(&db)
|
|
.await?;
|
|
let link = |path: &'static str| {
|
|
let db = db.clone();
|
|
async move {
|
|
sqlx::query_scalar::<_, Option<i32>>(
|
|
"SELECT account FROM variable WHERE workspace_id = 'test-workspace' AND path = $1",
|
|
)
|
|
.bind(path)
|
|
.fetch_one(&db)
|
|
.await
|
|
.unwrap()
|
|
}
|
|
};
|
|
|
|
let path = "u/test-user/oauth_probe";
|
|
let resp = authed(client().post(format!("{base}/create")))
|
|
.json(
|
|
&json!({ "path": path, "value": "t", "is_secret": true, "description": "",
|
|
"is_oauth": true, "account": account }),
|
|
)
|
|
.send()
|
|
.await?;
|
|
assert_eq!(resp.status(), 201);
|
|
assert_eq!(link(path).await, None);
|
|
|
|
let other: i32 = sqlx::query_scalar(
|
|
"INSERT INTO account (workspace_id, client, expires_at, refresh_token)
|
|
VALUES ('test-workspace', 'github', now(), 'r') RETURNING id",
|
|
)
|
|
.fetch_one(&db)
|
|
.await?;
|
|
sqlx::query(
|
|
"UPDATE variable SET account = $1 WHERE workspace_id = 'test-workspace' AND path = $2",
|
|
)
|
|
.bind(account)
|
|
.bind(path)
|
|
.execute(&db)
|
|
.await?;
|
|
let resp = authed(client().post(variable_url(port, "update", path)))
|
|
.json(&json!({ "description": "d", "account": other }))
|
|
.send()
|
|
.await?;
|
|
assert_eq!(resp.status(), 200);
|
|
assert_eq!(link(path).await, Some(account));
|
|
|
|
Ok(())
|
|
}
|