Merge remote-tracking branch 'origin/main' into ruben/win-2838-widen-workspaceowner-and-captureowner-to

# Conflicts:
#	backend/ee-repo-ref.txt
This commit is contained in:
Ruben Fiszel
2026-11-26 17:58:26 +01:00
222 changed files with 7854 additions and 2095 deletions
+6 -1
View File
@@ -135,7 +135,7 @@ sufficient — see "Flip, or ask first" below. The one standing exception is an
leave that PR in draft (usually so it can be tested first) — honour it for that PR, and don't
carry it over to the next one.
1. **Trigger a round and wait for it**: launch the waiter as a background Bash task (a round takes 10–30 min; you are woken when it exits — do not stop the session or poll in the foreground while it runs):
1. **Trigger a round and wait for it**: launch the waiter as a background Bash task (a round takes about 10 min, 20 at most; you are woken when it exits — do not stop the session or poll in the foreground while it runs):
```bash
bash .agents/skills/pr/review-round.sh <PR_NUMBER>
@@ -143,6 +143,11 @@ carry it over to the next one.
It comments `/review` on the PR — which runs the Codex, Claude and Pi CI reviewers even on a draft — waits for the spawned `PR Review Commands` workflow run(s) to complete, then prints one verdict line per reviewer and saves the full review comments to files.
Waiting rules — a session that breaks one sits idle on results the user can already see:
- **Use the waiter, not a loop of your own.** It always exits: as soon as the Codex, Claude and Pi verdicts are posted, once the round's run completes (failed jobs included), at a 20-minute deadline with whatever was posted, or non-zero when no run appeared or GitHub kept erroring — treat a non-zero exit as "look yourself", not "no reviews". A hand-written loop waiting for "a comment from each reviewer" never ends when one reviewer dies (capacity errors, cancelled jobs), since a dead job posts nothing.
- **If your harness does not wake you when a background command exits, run the waiter in the foreground** with a timeout of at least 25 minutes. Backgrounding it and ending your turn then means nobody ever reads the result.
- **Act on a missing reviewer immediately.** Reviewers that never start or hang are common. The waiter names each reviewer with no review and the jobs that did not finish cleanly; re-trigger each missing one at once with a `/codex`, `/claude` or `/pi` PR comment and run the waiter again, rather than waiting longer.
`/review` (and `/codex`) are **idempotent per head SHA**: if a running or successful review already covers the current head, they skip that agent and post nothing new — the waiter reads the existing verdict for that head, so a skipped agent is *not* a missing one. A cancelled/failed head run is re-run in place; a fresh run is launched only when nothing covers the head. So an unchanged-head re-review is a near no-op, not a new round — push a commit to get genuinely fresh reviews.
2. **Judge the round.** Codex is mandatory; Claude, Pi and cubic count whenever they posted. Every review starts with one of the three `REVIEW.md` verdicts:
+56 -17
View File
@@ -7,19 +7,20 @@
# Comments `/review` on the PR (works on drafts), waits for the spawned
# "PR Review Commands" workflow run(s) to complete, then prints one verdict
# line per reviewer and saves each full review comment to a file. A round
# takes 10-30 minutes: run this in the background and act on its output when
# takes about 10 minutes, 20 at most: run this in the background and act on its output when
# it exits, per the pr skill ("Review rounds").
set -euo pipefail
REPO=${REPO:-$(gh repo view --json nameWithOwner --jq .nameWithOwner)}
PR=${1:-$(gh pr view --json number --jq .number)}
PR_TITLE=$(gh pr view "$PR" --repo "$REPO" --json title --jq .title)
# Timestamp of the trigger comment, straight from GitHub, so local clock skew
# can't make the run/comment filters below miss part of the round.
TRIGGER_TIME=$(gh api "repos/$REPO/issues/$PR/comments" -f body='/review' --jq .created_at)
echo "Review round triggered on $REPO#$PR at $TRIGGER_TIME"
# Retry wrapper for one-off gh/API hiccups: a 45-minute wait must not die on
# Retry wrapper for one-off gh/API hiccups: a 20-minute wait must not die on
# a single transient failure.
retry() {
local attempt
@@ -31,21 +32,39 @@ retry() {
}
# The /review comment spawns one "PR Review Commands" run holding the
# claude/codex/pi jobs. Runs aren't linked to a PR, so wait on every run of
# that workflow created after the trigger: a concurrent round on another PR
# can only delay the answer, never truncate it. Every issue comment on any PR
# spawns a fast-completing parse run of the same workflow, so the round's own
# run may briefly lag the listing while unrelated runs already show completed:
# require the all-completed state to hold past a floor and across two
# consecutive polls before trusting it.
DEADLINE=$(( $(date +%s) + 45 * 60 ))
# claude/codex/pi jobs. Runs aren't linked to a PR, but an issue_comment run's
# display title is the PR's title: match on it, since waiting on every run
# after the trigger means a stuck reviewer on any other PR holds this round
# to the deadline. Every comment on this PR (the reviewers' own
# included) spawns a fast-completing parse run, so the round's own run may
# briefly lag the listing while those already show completed: require the
# all-completed state to hold past a floor and across two consecutive polls.
#
# Reviews land 6-10 minutes in. A reviewer that never starts or hangs is common
# and only a human re-trigger fixes it, so stop early: as soon as all three
# verdicts are posted, else at 20 minutes, naming the jobs still unfinished.
VERDICT_RE='(Good to merge|Mergeable, but should ideally address nits|Should address issues before merging)'
# Claude edits a placeholder comment in place, hence updated_at.
all_verdicts_in() {
gh api "repos/$REPO/issues/$PR/comments?per_page=100" --paginate 2>/dev/null \
| jq -s -e --arg t "$TRIGGER_TIME" --arg re "$VERDICT_RE" '
[.[][] | select(.updated_at > $t) | select(.body // "" | test($re))] as $c
| ($c | any(.user.login == "github-actions[bot]" and (.body | startswith("## Codex Review"))))
and ($c | any(.user.login == "github-actions[bot]" and (.body | startswith("## Pi Review"))))
and ($c | any(.user.login == "claude[bot]"))' >/dev/null
}
DEADLINE=$(( $(date +%s) + 20 * 60 ))
NO_RUN_DEADLINE=$(( $(date +%s) + 5 * 60 ))
MIN_WAIT_UNTIL=$(( $(date +%s) + 3 * 60 ))
STABLE=0
SEEN=0
ALL_IN=0
ROUND_RUNS='[]'
FAILURES=0
while :; do
if RUNS=$(gh run list --repo "$REPO" --workflow=pr-review-commands.yml \
--created ">=$TRIGGER_TIME" --limit 100 --json status); then
--created ">=$TRIGGER_TIME" --limit 500 --json databaseId,status,displayTitle \
--jq "[.[] | select(.displayTitle == $(jq -Rn --arg t "$PR_TITLE" '$t'))]"); then
FAILURES=0
else
FAILURES=$(( FAILURES + 1 ))
@@ -58,6 +77,13 @@ while :; do
continue
fi
TOTAL=$(jq length <<<"$RUNS")
# The limit applies before the title filter, so on a busy repo this PR's run
# can age out of the listing: once seen, never report it as missing.
if [ "$TOTAL" -gt 0 ]; then SEEN=1; ROUND_RUNS=$RUNS; fi
if all_verdicts_in; then
ALL_IN=1
break
fi
PENDING=$(jq '[.[] | select(.status != "completed")] | length' <<<"$RUNS")
NOW=$(date +%s)
if [ "$TOTAL" -gt 0 ] && [ "$PENDING" -eq 0 ] && [ "$NOW" -gt "$MIN_WAIT_UNTIL" ]; then
@@ -68,12 +94,12 @@ while :; do
else
STABLE=0
fi
if [ "$TOTAL" -eq 0 ] && [ "$NOW" -gt "$NO_RUN_DEADLINE" ]; then
if [ "$SEEN" -eq 0 ] && [ "$NOW" -gt "$NO_RUN_DEADLINE" ]; then
echo "ERROR: no 'PR Review Commands' run appeared within 5 minutes of the /review comment; check that the comment author has write access and the workflow is enabled." >&2
exit 1
fi
if [ "$NOW" -gt "$DEADLINE" ]; then
echo "WARNING: review round still pending after 45 minutes; reporting whatever has been posted so far." >&2
echo "WARNING: review round still pending after 20 minutes; reporting whatever has been posted so far." >&2
break
fi
sleep 60
@@ -100,7 +126,7 @@ head_run_state() {
# A re-run-in-place review lands on a head-tied run that finishes after the fast
# pr-review-commands run, so let those settle before reading verdicts.
for wf in codex-pr-review.yml pi-pr-review.yml pr-ready-review.yml; do
while :; do
while [ "$ALL_IN" -eq 0 ]; do
case "$(head_run_state "$wf")" in
""|"completed "*) break ;;
*) if [ "$(date +%s)" -gt "$DEADLINE" ]; then break; fi; sleep 30 ;;
@@ -121,8 +147,6 @@ REVIEWS_RAW=$(retry gh api "repos/$REPO/pulls/$PR/reviews?per_page=100" --pagina
jq -s --arg t "$TRIGGER_TIME" '[.[][] | select((.submitted_at // "") > $t)]' \
<<<"$REVIEWS_RAW" > "$OUT_DIR/pr-reviews.json"
VERDICT_RE='(Good to merge|Mergeable, but should ideally address nits|Should address issues before merging)'
body_by_header() { # <file> <header-substring>
jq -r --arg h "$2" '[.[] | select(.body // "" | contains($h))] | last | .body // empty' "$1"
}
@@ -144,7 +168,11 @@ verdict_body() { # <header|login> <value> <workflow>
report() { # <reviewer-name> <comment-body>
local name=$1 body=$2 verdict
if [ -z "$body" ]; then
echo "$name: (no review posted for this head)"
if [ "$name" = cubic ]; then
echo "$name: (no review posted for this head)"
else
echo "$name: (no review posted for this head; re-trigger now with a '/$name' PR comment)"
fi
return
fi
printf '%s\n' "$body" > "$OUT_DIR/$name.md"
@@ -167,6 +195,17 @@ fi
report cubic "$CUBIC_BODY"
echo
echo "Full round output: $OUT_DIR (comments.json, pr-reviews.json, one .md per reviewer)"
if [ "$ALL_IN" -eq 0 ]; then
UNFINISHED=$(for id in $(jq -r '.[].databaseId' <<<"$ROUND_RUNS"); do
gh run view "$id" --repo "$REPO" --json jobs --jq '.jobs[]
| select(.status != "completed" or (.conclusion | IN("success", "skipped") | not))
| " \(.name): \(.status) \(.conclusion // "") since \(.startedAt // "-")"' 2>/dev/null || true
done)
if [ -n "$UNFINISHED" ]; then
echo "Review jobs that did not finish cleanly:"
printf '%s\n' "$UNFINISHED"
fi
fi
if [ -z "$CODEX_BODY" ]; then
echo "WARNING: no Codex verdict for $HEAD_SHA - its head run is not green (cancelled/failed/absent, not merely skipped-because-already-reviewed). Re-trigger with a '/codex' PR comment (re-runs the interrupted run in place, or launches one) and wait again." >&2
fi
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "1.884.1"
".": "1.885.0"
}
+26
View File
@@ -1,5 +1,31 @@
# Changelog
## [1.885.0](https://github.com/windmill-labs/windmill/compare/v1.884.1...v1.885.0) (2026-11-25)
### Features
* hand the code selected with ⌘K and Ctrl+L to an AI session ([#12661](https://github.com/windmill-labs/windmill/issues/12661)) ([5d4820d](https://github.com/windmill-labs/windmill/commit/5d4820d3736fa6f307fb4838e525e32c4dc24838))
* pass MCP image results to the AI chat model as images ([#12660](https://github.com/windmill-labs/windmill/issues/12660)) ([772c0c3](https://github.com/windmill-labs/windmill/commit/772c0c30f1f47a84b2fd7ec6456882482c0759c5))
* show who approved a flow run, and list opted-in approvals on home ([#12604](https://github.com/windmill-labs/windmill/issues/12604)) ([3efe1e9](https://github.com/windmill-labs/windmill/commit/3efe1e97a7d54be674b78dbfdb48e6f8f8591527))
* show why a step waits: sleep, concurrency limit, approval ([#12607](https://github.com/windmill-labs/windmill/issues/12607)) ([182356e](https://github.com/windmill-labs/windmill/commit/182356ec358cf9fa759983d39ffff128468c85cb))
### Bug Fixes
* bound sqlx's return-to-pool step so a failover can't wedge the pool ([#12655](https://github.com/windmill-labs/windmill/issues/12655)) ([8e3f117](https://github.com/windmill-labs/windmill/commit/8e3f11705f8705e2c1adb50a139b4a501795e5ec))
* check run scope on what a schedule or trigger save names ([#12618](https://github.com/windmill-labs/windmill/issues/12618)) ([4b715c4](https://github.com/windmill-labs/windmill/commit/4b715c422a75e93ac9a6aa9b9c74a31ba786734c))
* **cli:** keep generate-metadata inside the named folder ([#12668](https://github.com/windmill-labs/windmill/issues/12668)) ([2c2273c](https://github.com/windmill-labs/windmill/commit/2c2273cffb26c55e883bad6ee96653935e0412ab))
* hold a volume's lease through sync-back and pull it in parallel ([#12667](https://github.com/windmill-labs/windmill/issues/12667)) ([5953595](https://github.com/windmill-labs/windmill/commit/5953595d50a20fc08449bf1d0c7aa6b0c0a12b81))
* let the attached flow step panel scroll ([#12652](https://github.com/windmill-labs/windmill/issues/12652)) ([29383dd](https://github.com/windmill-labs/windmill/commit/29383dd814677465f98a02038b2fd2d83e117edd))
* log in on the live session when the browser sends two token cookies ([#12663](https://github.com/windmill-labs/windmill/issues/12663)) ([8f637d5](https://github.com/windmill-labs/windmill/commit/8f637d58d6654740bca41f32a3462e5951ff8f4c))
* match flow step pickers to the role and keep picked settings ([#12654](https://github.com/windmill-labs/windmill/issues/12654)) ([00e354d](https://github.com/windmill-labs/windmill/commit/00e354dade598ed9f434576ef616b53e0cf6b543))
* **mcp:** require a session on the MCP OAuth client routes and audit registrations ([#12647](https://github.com/windmill-labs/windmill/issues/12647)) ([2b7c7e9](https://github.com/windmill-labs/windmill/commit/2b7c7e98acfc96dc10931948252a02d39325e798))
* **python:** treat tomllib and newer stdlib modules as stdlib in import inference ([#12670](https://github.com/windmill-labs/windmill/issues/12670)) ([655562e](https://github.com/windmill-labs/windmill/commit/655562e805a9b74adbb1e3faa85d97bc567dd99a))
* show minutes instead of seconds after the first minute in relative times ([#12631](https://github.com/windmill-labs/windmill/issues/12631)) ([b59d27b](https://github.com/windmill-labs/windmill/commit/b59d27bdb1daaa0e3fbacc3cfb692b01fe7254d3))
* skip the session backup in preview frames and keep draft handles stable ([#12598](https://github.com/windmill-labs/windmill/issues/12598)) ([53ebb94](https://github.com/windmill-labs/windmill/commit/53ebb94ddb167ae4bebd06fcdbed77df1391bc68))
* stop state_snapshot_uncloneable warnings from chart options ([#12653](https://github.com/windmill-labs/windmill/issues/12653)) ([2bdad42](https://github.com/windmill-labs/windmill/commit/2bdad42ad060e5678df22e5df3d90d598c2586c5))
## [1.884.1](https://github.com/windmill-labs/windmill/compare/v1.884.0...v1.884.1) (2026-11-25)
+16
View File
@@ -254,6 +254,22 @@ secretRequests:
and the resource are created in the workspace, deployed, and the model reads the result the
chat would give it. `check` is reported as is; no connection test runs.
`runtime.codeSelections` attaches code to the prompt of a global case, as the chips of code
selected in an editor do. `source` names the item (`script`, `flow`, `raw_app` or `agent`) and
optionally its `part` (a flow step, app runnable, agent tool or script module file), and
`content` is the code from `startLine` to `endLine`:
```yaml
codeSelections:
- source: { kind: flow, path: f/evals/global/process_refund, part: calculate_total }
lang: bun
startLine: 1
endLine: 2
content: |-
export async function main(subtotal: number) {
return { subtotal, total: subtotal }
```
`runtime.profile` runs a session-chat case (`sessionChat: true`) as a non-admin role
instead of full access: the prompt, toolset and tool schemas are cut as production's
`capabilitiesForRole` cuts them, and the workspace's `operator_settings` are seeded for the
@@ -4,6 +4,7 @@ import {
globalToolsFor,
prepareGlobalUserMessage,
} from "../../../../../frontend/src/lib/components/copilot/chat/global/core";
import { createCodeSelection } from "../../../../../frontend/src/lib/components/copilot/chat/context";
import { assembleGlobalSystemMessage } from "../../../../../frontend/src/lib/components/copilot/chat/global/globalAssembly";
import {
canBuild,
@@ -46,6 +47,7 @@ import {
type EvalPreviewTabFixture,
} from "./evalPreviewTabs";
import type {
EvalCaseCodeSelection,
EvalCaseProfile,
EvalSecretRequestAnswer,
ModeRunContext,
@@ -145,6 +147,7 @@ export interface GlobalEvalOptions {
// Start in plan mode: the gate refuses every tool without `planModeSafe`, and the two plan
// tools are offered. Needs sessionChat, which is what plan mode is gated on in production.
planMode?: boolean;
codeSelections?: EvalCaseCodeSelection[];
// The user's rights, resolved as a session resolves them; unset keeps full access.
profile?: EvalCaseProfile;
// Run the pipeline the chat drafted once it is over (`validate.pipelineRun`).
@@ -286,6 +289,9 @@ export async function runGlobalEval(
pipelineFolders: pipelineEditors?.folders(),
});
const baseSystemMessage = assembleSystemMessage();
const codeSelections = (options.codeSelections ?? []).map(({ source, ...selection }) =>
createCodeSelection(source, selection),
);
const helpers = {
...evalArtifacts.helpers,
// A standalone chat has no session: the tools that behave differently in one (a pipeline
@@ -317,7 +323,7 @@ export async function runGlobalEval(
isToolAvailable: (name) =>
(!pipelineToolNames.has(name) || (pipelineEditors?.folders().length ?? 0) > 0) &&
(planMode?.isToolAvailable?.(name) ?? true),
userMessage: prepareGlobalUserMessage(userPrompt, [], {
userMessage: prepareGlobalUserMessage(userPrompt, codeSelections, {
...(injectActiveEditorContext ? { workspace: workspaceRoot } : {}),
activePreview: panel?.activePreview(),
resourceTypeSync: await resolveResourceTypeSync(workspaceRoot, []),
+39
View File
@@ -519,6 +519,45 @@
- returns subtotal, tax, and total from the updated flow logic
- leaves the result as a draft only
- id: global-code-selection-names-its-item
prompt: |-
Throw an error here when the subtotal is negative.
Keep the change as a draft.
initial: ai_evals/fixtures/frontend/global/initial/current_invoice_live_flow.json
runtime:
maxTurns: 10
codeSelections:
- source:
kind: flow
path: f/evals/global/process_refund
part: calculate_total
lang: bun
startLine: 1
endLine: 2
content: |-
export async function main(subtotal: number) {
return { subtotal, total: subtotal }
validate:
# The open flow's own draft, which must stay as it was, and the edited one.
draftCountExactly: 2
requiredDrafts:
- type: flow
path: f/evals/global/process_refund
valueIncludes:
- calculate_total
- throw
forbiddenDrafts:
- type: flow
path: f/evals/global/process_invoice
toolExpect:
forbiddenToolsUsed:
- deploy_workspace_item
- delete_workspace_item
judgeChecklist:
- edits the calculate_total step of the process_refund flow, which the selected code belongs to, not the flow open in the editor
- throws when the subtotal is negative and keeps the rest of the step as it was
- leaves the result as a draft only
- id: global-test14-current-without-live-editor-asks-question
prompt: |-
Please update this script so it returns `ok`.
+10
View File
@@ -38,6 +38,8 @@ export interface EvalCaseRuntimeSpec {
secretRequests?: EvalSecretRequestAnswer[];
backendPreview?: EvalCaseRuntimeBackendPreview;
appContext?: EvalCaseRuntimeAppContextSpec;
// Global mode: code the user selected in an editor and attached to the prompt.
codeSelections?: EvalCaseCodeSelection[];
// Global mode: run as a session chat (preview tools + session prompt) vs the standalone chat.
sessionChat?: boolean;
// Global session chats: start the case in plan mode, so the workspace-changing tools are
@@ -60,6 +62,14 @@ export interface EvalSecretRequestAnswer {
check?: { ok: true } | { ok: false; error: string };
}
export interface EvalCaseCodeSelection {
source: { kind: "script" | "flow" | "raw_app" | "agent"; path: string; part?: string };
lang: "bun" | "python3" | "bash" | "postgresql";
startLine: number;
endLine: number;
content: string;
}
export interface EvalCaseProfile {
operator: boolean;
operatorSettings?: {
+1
View File
@@ -55,6 +55,7 @@ export function createGlobalModeRunner(
previewTabs: initial?.previewTabs,
sessionChat: context.evalCase?.runtime?.sessionChat,
planMode: context.evalCase?.runtime?.planMode,
codeSelections: context.evalCase?.runtime?.codeSelections,
profile: context.evalCase?.runtime?.profile,
pipelineRun: context.executionOnly
? undefined
@@ -0,0 +1,28 @@
{
"db_name": "PostgreSQL",
"query": "SELECT key, original_scheduled_for IS NOT NULL AND released_at IS NULL AS \"held!\"\n FROM concurrency_key WHERE job_id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "key",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "held!",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
null
]
},
"hash": "0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), last_used_at = now(),\n lease_until = NULL, leased_by = NULL,\n generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5",
"query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), last_used_at = now(),\n generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5",
"describe": {
"columns": [],
"parameters": {
@@ -14,5 +14,5 @@
},
"nullable": []
},
"hash": "f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea"
"hash": "123015f4012169763ac8b16c2e4e0775b6da84dd53aeca8fb9b556f969aee29a"
}
@@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "SELECT u.username, u.email,\n COALESCE(array_agg(g.group_) FILTER (WHERE g.group_ IS NOT NULL), '{}') AS \"groups!\"\n FROM usr u\n JOIN password p ON p.email = u.email AND p.login_type = 'password'\n LEFT JOIN usr_to_group g ON g.workspace_id = u.workspace_id AND g.usr = u.username\n WHERE u.workspace_id = $1 AND NOT u.is_service_account\n GROUP BY u.username, u.email\n ORDER BY u.username",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "username",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "email",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "groups!",
"type_info": "VarcharArray"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
null
]
},
"hash": "1816ab8f23338f3e01d01bf4e1ba67e1c180bd4c81b17db1ae2619e2e73fef28"
}
@@ -0,0 +1,44 @@
{
"db_name": "PostgreSQL",
"query": "SELECT to_char(timestamp AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS \"day!\",\n id AS \"id!\",\n timestamp AS \"ts!\",\n row_to_json(r)::text AS \"line!\"\n FROM (\n SELECT workspace_id, id, timestamp, username, operation,\n action_kind::text AS action_kind, resource, parameters, email, span,\n client_ip, user_agent\n FROM audit_partitioned\n WHERE timestamp >= $1 AND timestamp < $2\n AND (timestamp, id) > ($3, $4)\n ORDER BY timestamp, id\n LIMIT $5\n ) r\n ORDER BY timestamp, id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "day!",
"type_info": "Text"
},
{
"ordinal": 1,
"name": "id!",
"type_info": "Int8"
},
{
"ordinal": 2,
"name": "ts!",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "line!",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Timestamptz",
"Timestamptz",
"Timestamptz",
"Int8",
"Int8"
]
},
"nullable": [
null,
false,
false,
null
]
},
"hash": "18d01ba5fb5a25984ae1291b7c20820613f4dd8cd03186b17e595f538a4d4397"
}
@@ -0,0 +1,28 @@
{
"db_name": "PostgreSQL",
"query": "SELECT login_type, username FROM password WHERE email = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "login_type",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "username",
"type_info": "Varchar"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
true
]
},
"hash": "22b6a5e8d05d47c86713ff804857e037112aac008865934fa3419581034e69d3"
}
@@ -0,0 +1,97 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT j.id AS \"id!\",\n COALESCE(j.root_job, j.parent_job, j.id) AS \"root_job_id!\",\n j.runnable_path,\n j.permissioned_as_email AS \"email!\",\n j.created_by AS \"created_by!\",\n j.created_at AS \"created_at!\",\n COALESCE(rj.runnable_path, j.runnable_path) AS flow_path,\n NULLIF(f.summary, '') AS flow_summary,\n s.flow_status->'approval_conditions' AS approval_conditions,\n NULLIF(w.m->'home'->>'step_summary', '') AS step_summary,\n COALESCE((w.m->>'count')::bigint, 1) AS \"required_approvals!\",\n -- Counted as the worker counts them: those sent to the approval step's job,\n -- plus those sent to the flow itself.\n (SELECT count(*) FROM resume_job r WHERE r.job IN (j.id, (w.m->>'job')::uuid))\n AS \"approvals!\",\n EXISTS(SELECT 1 FROM resume_job r\n WHERE r.job IN (j.id, (w.m->>'job')::uuid) AND r.approver = $2)\n AS \"approved_by_me!\"\n FROM v2_job_queue q\n JOIN v2_job j ON j.id = q.id\n JOIN v2_job_status s ON s.id = q.id\n LEFT JOIN v2_job rj ON rj.id = COALESCE(j.root_job, j.parent_job)\n LEFT JOIN flow f\n ON f.workspace_id = j.workspace_id\n AND f.path = COALESCE(rj.runnable_path, j.runnable_path)\n -- The step waiting on the approval, which the worker marks `home` when the approval\n -- step has `show_on_home`: only those are listed, since many approvals are announced\n -- elsewhere (a resume link sent to a chat) and every admin and owner could give them.\n CROSS JOIN LATERAL (\n SELECT s.flow_status->'modules'->((s.flow_status->>'step')::int) AS m\n ) w\n WHERE q.workspace_id = $1\n AND q.suspend > 0\n AND w.m->>'type' = 'WaitingForEvents'\n AND w.m->'home' IS NOT NULL\n AND ($4::text[] IS NULL OR j.tag = ANY($4))\n ORDER BY j.created_at DESC\n LIMIT $3\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id!",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "root_job_id!",
"type_info": "Uuid"
},
{
"ordinal": 2,
"name": "runnable_path",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "email!",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "created_by!",
"type_info": "Varchar"
},
{
"ordinal": 5,
"name": "created_at!",
"type_info": "Timestamptz"
},
{
"ordinal": 6,
"name": "flow_path",
"type_info": "Varchar"
},
{
"ordinal": 7,
"name": "flow_summary",
"type_info": "Text"
},
{
"ordinal": 8,
"name": "approval_conditions",
"type_info": "Jsonb"
},
{
"ordinal": 9,
"name": "step_summary",
"type_info": "Text"
},
{
"ordinal": 10,
"name": "required_approvals!",
"type_info": "Int8"
},
{
"ordinal": 11,
"name": "approvals!",
"type_info": "Int8"
},
{
"ordinal": 12,
"name": "approved_by_me!",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Text",
"Text",
"Int8",
"TextArray"
]
},
"nullable": [
false,
null,
true,
false,
false,
false,
null,
null,
null,
null,
null,
null,
null
]
},
"hash": "25a603879c2324cf4390a4d8ff3ce820f1f96d2c22e645a17b1125a949f8dd88"
}
@@ -0,0 +1,42 @@
{
"db_name": "PostgreSQL",
"query": "WITH bounds AS (\n SELECT ($2::bigint % 4294967296)::text::xid AS prev_xid,\n ($3::bigint % 4294967296)::text::xid AS cur_xid,\n $1::timestamptz AS ts_floor\n ),\n batch AS (\n SELECT workspace_id, id, timestamp, username, operation,\n action_kind::text AS action_kind, resource, parameters, email, span,\n client_ip, user_agent\n FROM audit_partitioned, bounds b\n WHERE timestamp >= b.ts_floor\n AND age(xmin) > age(b.cur_xid)\n AND age(xmin) <= age(b.prev_xid)\n ORDER BY id\n )\n SELECT to_char(timestamp AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS \"day!\",\n string_agg(row_to_json(batch)::text, E'\\n' ORDER BY id) AS \"ndjson!\",\n max(id) AS \"max_id!\",\n max(timestamp) AS \"max_ts!\"\n FROM batch\n GROUP BY 1\n ORDER BY 1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "day!",
"type_info": "Text"
},
{
"ordinal": 1,
"name": "ndjson!",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "max_id!",
"type_info": "Int8"
},
{
"ordinal": 3,
"name": "max_ts!",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Timestamptz",
"Int8",
"Int8"
]
},
"nullable": [
null,
null,
null,
null
]
},
"hash": "26f1b3af9057517b82a3c263e0396ee2747445e2a66381ed1b9fd96e0d9909bb"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), updated_by = $5, last_used_at = now(),\n lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2",
"query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), updated_by = $5, last_used_at = now(),\n lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5",
"describe": {
"columns": [],
"parameters": {
@@ -14,5 +14,5 @@
},
"nullable": []
},
"hash": "19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66"
"hash": "3339c1d01792ff181f9506b57c7e6771c3a1a2a5a67dd467ed263b3501c5d279"
}
@@ -0,0 +1,35 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO audit_partitioned\n (workspace_id, username, operation, action_kind, resource, parameters, email, span,\n client_ip, user_agent)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
{
"Custom": {
"name": "action_kind",
"kind": {
"Enum": [
"create",
"update",
"delete",
"execute"
]
}
}
},
"Varchar",
"Jsonb",
"Varchar",
"Varchar",
"Text",
"Text"
]
},
"nullable": []
},
"hash": "44ad516d89eeb5411cbd34a839c4c6eab6782b23eb8d7f8831b2f0e9f9c17055"
}
@@ -0,0 +1,41 @@
{
"db_name": "PostgreSQL",
"query": "SELECT resume_id, approver, created_at, approved FROM resume_job\n WHERE flow = $1 AND ($2::uuid IS NULL OR job IN ($1, $2))",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "resume_id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "approver",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "approved",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
"nullable": [
false,
true,
false,
false
]
},
"hash": "456f07b39a39791ea4c0764adc235374571db2fa45b6e97db42e8309ecb02c05"
}
@@ -0,0 +1,47 @@
{
"db_name": "PostgreSQL",
"query": "SELECT j.id, j.tag, j.kind = 'flownode' AS \"is_node!\",\n COALESCE(s.flow_status, c.flow_status) AS flow_status,\n COALESCE(j.raw_flow, fv.value, fn.flow) AS flow\n FROM v2_job j\n LEFT JOIN v2_job_status s ON s.id = j.id\n LEFT JOIN v2_job_completed c ON c.id = j.id\n LEFT JOIN flow_version fv\n ON j.raw_flow IS NULL AND j.kind = 'flow' AND fv.id = j.runnable_id\n LEFT JOIN flow_node fn\n ON j.raw_flow IS NULL AND j.kind = 'flownode' AND fn.id = j.runnable_id\n WHERE j.id = ANY($1) AND j.workspace_id = $2",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "tag",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "is_node!",
"type_info": "Bool"
},
{
"ordinal": 3,
"name": "flow_status",
"type_info": "Jsonb"
},
{
"ordinal": 4,
"name": "flow",
"type_info": "Jsonb"
}
],
"parameters": {
"Left": [
"UuidArray",
"Text"
]
},
"nullable": [
false,
false,
null,
null,
null
]
},
"hash": "6f9c95e209ad7161ec02b70c156a31e640ed9e8c7fcdc5bd2da94bc5728f0455"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE concurrency_key SET released_at = $2 WHERE job_id = $1 AND released_at IS NULL",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Timestamptz"
]
},
"nullable": []
},
"hash": "79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c"
}
@@ -0,0 +1,35 @@
{
"db_name": "PostgreSQL",
"query": "SELECT name, bypass_users, bypass_groups FROM workspace_protection_rule\n WHERE workspace_id = $1 AND (rules & $2) <> 0 ORDER BY name",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "name",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "bypass_users",
"type_info": "TextArray"
},
{
"ordinal": 2,
"name": "bypass_groups",
"type_info": "TextArray"
}
],
"parameters": {
"Left": [
"Text",
"Int4"
]
},
"nullable": [
false,
false,
false
]
},
"hash": "8c8ab1f498ca1460d2b58d95c09af1e3230e8f7cfd7a49b4fec87110e31470fa"
}
@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT i.email FROM workspace_invite i\n JOIN password p ON p.email = i.email AND p.login_type = 'password'\n WHERE i.workspace_id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "email",
"type_info": "Varchar"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false
]
},
"hash": "a5ddda3592c30ad7ccb1bf4215bb5271e1563ce19cb252837f9e26d5b8502667"
}
@@ -0,0 +1,35 @@
{
"db_name": "PostgreSQL",
"query": "SELECT u.workspace_id, u.username,\n COALESCE(array_agg(g.group_) FILTER (WHERE g.group_ IS NOT NULL), '{}') AS \"groups!\"\n FROM usr u\n LEFT JOIN usr_to_group g ON g.workspace_id = u.workspace_id AND g.usr = u.username\n WHERE u.email = $1 AND NOT u.is_service_account\n AND EXISTS (SELECT 1 FROM workspace_protection_rule r\n WHERE r.workspace_id = u.workspace_id AND (r.rules & $2) <> 0)\n GROUP BY u.workspace_id, u.username",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "workspace_id",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "username",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "groups!",
"type_info": "VarcharArray"
}
],
"parameters": {
"Left": [
"Text",
"Int4"
]
},
"nullable": [
false,
false,
null
]
},
"hash": "c901b1954818bfa402d2ded9f020c0862421001e10a5ac8cb3d1c1791b6ca597"
}
@@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "SELECT key, original_scheduled_for AS deferred_from, released_at FROM concurrency_key WHERE job_id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "key",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "deferred_from",
"type_info": "Timestamptz"
},
{
"ordinal": 2,
"name": "released_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
true,
true
]
},
"hash": "eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3"
}
+119 -117
View File
@@ -77,9 +77,9 @@ dependencies = [
[[package]]
name = "ahash"
version = "0.8.13"
version = "0.8.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fca89247609239eeb6915e6991111866b92d7b31025e69302bbf430cc4d2c38"
checksum = "54dae3d1d7b8956f3506c4e999a74e77f932a59153ccf38ab8cf96db74bb9dc0"
dependencies = [
"cfg-if",
"const-random",
@@ -325,7 +325,7 @@ version = "55.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70732f04d285d49054a48b72c54f791bb3424abae92d27aafdf776c98af161c8"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"arrow-buffer",
"arrow-data",
"arrow-schema",
@@ -469,7 +469,7 @@ version = "55.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd2b45757d6a2373faa3352d02ff5b54b098f5e21dccebc45a21806bc34501e5"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"arrow-array",
"arrow-buffer",
"arrow-data",
@@ -2646,12 +2646,12 @@ dependencies = [
[[package]]
name = "const-hex"
version = "1.19.3"
version = "1.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e59eef12462b0f9b0a3620219be5d639afd79fe39dff0a42c3997061f9298b4"
checksum = "dec64a10a1f3012c9950a1759c99e09444a61087441a9b1ced0039c21365f859"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"cpufeatures 0.3.1",
"proptest",
"serde_core",
]
@@ -3430,7 +3430,7 @@ version = "47.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0734015d81c8375eb5d4869b7f7ecccc2ee8d6cb81948ef737cd0e7b743bd69c"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"arrow",
"arrow-ipc",
"base64 0.22.1",
@@ -3670,7 +3670,7 @@ version = "47.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "408a05dafdc70d05a38a29005b8b15e21b0238734dab1e98483fcb58038c5aba"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"arrow",
"datafusion-common",
"datafusion-doc",
@@ -3691,7 +3691,7 @@ version = "47.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "756d21da2dd6c9bef97af1504970ff56cbf35d03fbd4ffd62827f02f4d2279d4"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"arrow",
"datafusion-common",
"datafusion-expr-common",
@@ -3798,7 +3798,7 @@ version = "47.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64c536062b0076f4e30084065d805f389f9fe38af0ca75bcbac86bc5e9fbab65"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"arrow",
"datafusion-common",
"datafusion-expr",
@@ -3820,7 +3820,7 @@ version = "47.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8a92b53b3193fac1916a1c5b8e3f4347c526f6822e56b71faa5fb372327a863"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"arrow",
"datafusion-common",
"datafusion-expr-common",
@@ -3853,7 +3853,7 @@ version = "47.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "690c615db468c2e5fe5085b232d8b1c088299a6c63d87fd960a354a71f7acb55"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"arrow",
"arrow-ord",
"arrow-schema",
@@ -5073,7 +5073,7 @@ dependencies = [
"curve25519-dalek 5.0.0",
"ed25519 3.0.0",
"serde",
"sha2 0.11.1",
"sha2 0.11.2",
"signature 3.0.0",
"subtle",
"zeroize",
@@ -6292,7 +6292,7 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"allocator-api2",
]
@@ -7659,7 +7659,7 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f1326e946fadf6248febdf8a1c001809c3899ccf48cb9768cbc536b741040dc"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"async-broadcast",
"async-stream",
"backon",
@@ -9465,7 +9465,7 @@ dependencies = [
"elliptic-curve 0.14.3",
"primefield",
"primeorder 0.14.0",
"sha2 0.11.1",
"sha2 0.11.2",
]
[[package]]
@@ -9491,7 +9491,7 @@ dependencies = [
"fiat-crypto 0.3.0",
"primefield",
"primeorder 0.14.0",
"sha2 0.11.1",
"sha2 0.11.2",
]
[[package]]
@@ -9552,7 +9552,7 @@ version = "55.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b17da4150748086bd43352bc77372efa9b6e3dbd06a04831d2a98c041c225cfa"
dependencies = [
"ahash 0.8.13",
"ahash 0.8.14",
"arrow-array",
"arrow-buffer",
"arrow-cast",
@@ -10101,7 +10101,7 @@ dependencies = [
"md-5 0.11.0",
"memchr",
"rand 0.10.4",
"sha2 0.11.1",
"sha2 0.11.2",
"stringprep",
]
@@ -10215,7 +10215,7 @@ version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit 0.25.20+spec-1.1.0",
"toml_edit 0.25.21+spec-1.1.0",
]
[[package]]
@@ -12392,9 +12392,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.1"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -12771,7 +12771,7 @@ dependencies = [
[[package]]
name = "sqlx"
version = "0.8.6"
source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b"
source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459"
dependencies = [
"sqlx-core",
"sqlx-macros",
@@ -12783,7 +12783,7 @@ dependencies = [
[[package]]
name = "sqlx-core"
version = "0.8.6"
source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b"
source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459"
dependencies = [
"base64 0.22.1",
"bigdecimal",
@@ -12821,7 +12821,7 @@ dependencies = [
[[package]]
name = "sqlx-macros"
version = "0.8.6"
source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b"
source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459"
dependencies = [
"proc-macro2",
"quote",
@@ -12833,7 +12833,7 @@ dependencies = [
[[package]]
name = "sqlx-macros-core"
version = "0.8.6"
source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b"
source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459"
dependencies = [
"dotenvy",
"either",
@@ -12857,7 +12857,7 @@ dependencies = [
[[package]]
name = "sqlx-mysql"
version = "0.8.6"
source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b"
source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459"
dependencies = [
"atoi",
"base64 0.22.1",
@@ -12901,7 +12901,7 @@ dependencies = [
[[package]]
name = "sqlx-postgres"
version = "0.8.6"
source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b"
source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459"
dependencies = [
"atoi",
"base64 0.22.1",
@@ -12941,7 +12941,7 @@ dependencies = [
[[package]]
name = "sqlx-sqlite"
version = "0.8.6"
source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b"
source = "git+https://github.com/windmill-labs/sqlx?rev=ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459#ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459"
dependencies = [
"atoi",
"chrono",
@@ -14482,9 +14482,9 @@ dependencies = [
[[package]]
name = "toml_edit"
version = "0.25.20+spec-1.1.0"
version = "0.25.21+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73"
checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4"
dependencies = [
"indexmap 2.14.2",
"toml_datetime 1.1.3+spec-1.1.0",
@@ -14494,9 +14494,9 @@ dependencies = [
[[package]]
name = "toml_parser"
version = "1.1.6+spec-1.1.0"
version = "1.1.7+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31"
checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a"
dependencies = [
"winnow 1.0.5",
]
@@ -15654,7 +15654,7 @@ dependencies = [
[[package]]
name = "windmill"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-nats",
@@ -15744,7 +15744,7 @@ dependencies = [
[[package]]
name = "windmill-ai"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"async-stream",
"async-trait",
@@ -15779,7 +15779,7 @@ dependencies = [
[[package]]
name = "windmill-alerting"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -15792,7 +15792,7 @@ dependencies = [
[[package]]
name = "windmill-api"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"argon2",
@@ -15934,7 +15934,7 @@ dependencies = [
[[package]]
name = "windmill-api-agent-workers"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -15958,7 +15958,7 @@ dependencies = [
[[package]]
name = "windmill-api-assets"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -15975,7 +15975,7 @@ dependencies = [
[[package]]
name = "windmill-api-auth"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"axum",
@@ -16002,7 +16002,7 @@ dependencies = [
[[package]]
name = "windmill-api-client"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"reqwest 0.12.28",
"serde",
@@ -16012,7 +16012,7 @@ dependencies = [
[[package]]
name = "windmill-api-configs"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -16029,7 +16029,7 @@ dependencies = [
[[package]]
name = "windmill-api-debug"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"base64 0.22.1",
@@ -16051,7 +16051,7 @@ dependencies = [
[[package]]
name = "windmill-api-embeddings"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"axum",
@@ -16074,7 +16074,7 @@ dependencies = [
[[package]]
name = "windmill-api-flow-conversations"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -16090,7 +16090,7 @@ dependencies = [
[[package]]
name = "windmill-api-flows"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -16112,7 +16112,7 @@ dependencies = [
[[package]]
name = "windmill-api-groups"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -16134,7 +16134,7 @@ dependencies = [
[[package]]
name = "windmill-api-inputs"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -16148,7 +16148,7 @@ dependencies = [
[[package]]
name = "windmill-api-integration-tests"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-nats",
@@ -16184,7 +16184,7 @@ dependencies = [
[[package]]
name = "windmill-api-jobs"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"axum",
@@ -16210,7 +16210,7 @@ dependencies = [
[[package]]
name = "windmill-api-npm-proxy"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -16238,7 +16238,7 @@ dependencies = [
[[package]]
name = "windmill-api-openapi"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"axum",
@@ -16260,7 +16260,7 @@ dependencies = [
[[package]]
name = "windmill-api-schedule"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -16279,7 +16279,7 @@ dependencies = [
[[package]]
name = "windmill-api-scripts"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"axum",
@@ -16321,7 +16321,7 @@ dependencies = [
[[package]]
name = "windmill-api-settings"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"axum",
@@ -16352,7 +16352,7 @@ dependencies = [
[[package]]
name = "windmill-api-sse"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"lazy_static",
"serde",
@@ -16364,7 +16364,7 @@ dependencies = [
[[package]]
name = "windmill-api-users"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"argon2",
"axum",
@@ -16388,7 +16388,7 @@ dependencies = [
[[package]]
name = "windmill-api-workers"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -16403,7 +16403,7 @@ dependencies = [
[[package]]
name = "windmill-api-workspaces"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"axum",
"chrono",
@@ -16442,7 +16442,7 @@ dependencies = [
[[package]]
name = "windmill-audit"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"chrono",
"lazy_static",
@@ -16457,7 +16457,7 @@ dependencies = [
[[package]]
name = "windmill-autoscaling"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"axum",
@@ -16476,7 +16476,7 @@ dependencies = [
[[package]]
name = "windmill-common"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"aes-gcm",
"aho-corasick",
@@ -16530,6 +16530,7 @@ dependencies = [
"openidconnect",
"opentelemetry 0.30.0",
"opentelemetry-appender-tracing",
"opentelemetry-http 0.30.0",
"opentelemetry-otlp 0.30.0",
"opentelemetry-semantic-conventions 0.30.0",
"opentelemetry_sdk 0.30.0",
@@ -16545,6 +16546,7 @@ dependencies = [
"rand 0.9.5",
"rcgen",
"regex",
"reqwest 0.12.28",
"reqwest 0.13.5",
"reqwest-middleware",
"reqwest-retry",
@@ -16595,7 +16597,7 @@ dependencies = [
[[package]]
name = "windmill-dep-map"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"chrono",
"futures",
@@ -16615,7 +16617,7 @@ dependencies = [
[[package]]
name = "windmill-git-sync"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"regex",
"serde",
@@ -16632,7 +16634,7 @@ dependencies = [
[[package]]
name = "windmill-indexer"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"astral-tokio-tar",
@@ -16659,7 +16661,7 @@ dependencies = [
[[package]]
name = "windmill-jseval"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"futures",
@@ -16676,7 +16678,7 @@ dependencies = [
[[package]]
name = "windmill-macros"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"itertools 0.14.0",
"lazy_static",
@@ -16692,7 +16694,7 @@ dependencies = [
[[package]]
name = "windmill-mcp"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -16714,7 +16716,7 @@ dependencies = [
[[package]]
name = "windmill-native-triggers"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -16746,7 +16748,7 @@ dependencies = [
[[package]]
name = "windmill-oauth"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"arc-swap",
@@ -16771,7 +16773,7 @@ dependencies = [
[[package]]
name = "windmill-object-store"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-stream",
@@ -16807,7 +16809,7 @@ dependencies = [
[[package]]
name = "windmill-operator"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"futures",
@@ -16826,7 +16828,7 @@ dependencies = [
[[package]]
name = "windmill-parser"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"convert_case 0.6.0",
"serde",
@@ -16835,7 +16837,7 @@ dependencies = [
[[package]]
name = "windmill-parser-bash"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -16847,7 +16849,7 @@ dependencies = [
[[package]]
name = "windmill-parser-csharp"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde_json",
@@ -16859,7 +16861,7 @@ dependencies = [
[[package]]
name = "windmill-parser-go"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"gosyn",
@@ -16871,7 +16873,7 @@ dependencies = [
[[package]]
name = "windmill-parser-graphql"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -16883,7 +16885,7 @@ dependencies = [
[[package]]
name = "windmill-parser-java"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde_json",
@@ -16895,7 +16897,7 @@ dependencies = [
[[package]]
name = "windmill-parser-nu"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"nu-parser",
@@ -16906,7 +16908,7 @@ dependencies = [
[[package]]
name = "windmill-parser-php"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -16917,7 +16919,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -16929,7 +16931,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-asset"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -16940,7 +16942,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-imports"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-recursion",
@@ -16963,7 +16965,7 @@ dependencies = [
[[package]]
name = "windmill-parser-r"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde_json",
@@ -16975,7 +16977,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ruby"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -16989,7 +16991,7 @@ dependencies = [
[[package]]
name = "windmill-parser-rust"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"convert_case 0.6.0",
@@ -17006,7 +17008,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -17019,7 +17021,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql-asset"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde",
@@ -17031,7 +17033,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -17049,7 +17051,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts-asset"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde-wasm-bindgen",
@@ -17065,7 +17067,7 @@ dependencies = [
[[package]]
name = "windmill-parser-wac"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -17082,7 +17084,7 @@ dependencies = [
[[package]]
name = "windmill-parser-yaml"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -17096,7 +17098,7 @@ dependencies = [
[[package]]
name = "windmill-queue"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-recursion",
@@ -17134,7 +17136,7 @@ dependencies = [
[[package]]
name = "windmill-runtime-nativets"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"const_format",
@@ -17172,7 +17174,7 @@ dependencies = [
[[package]]
name = "windmill-sql-datatype-parser-wasm"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"getrandom 0.3.4",
"wasm-bindgen",
@@ -17183,7 +17185,7 @@ dependencies = [
[[package]]
name = "windmill-store"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-recursion",
@@ -17218,7 +17220,7 @@ dependencies = [
[[package]]
name = "windmill-test-utils"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17242,7 +17244,7 @@ dependencies = [
[[package]]
name = "windmill-trigger"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17275,7 +17277,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-amqp"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17302,7 +17304,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-azure"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17335,7 +17337,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-email"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17355,7 +17357,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-gcp"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17389,7 +17391,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-http"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17426,7 +17428,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-kafka"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17449,7 +17451,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-mqtt"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17473,7 +17475,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-nats"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-nats",
@@ -17497,7 +17499,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-postgres"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17532,7 +17534,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-sqs"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17560,7 +17562,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-websocket"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-trait",
@@ -17586,7 +17588,7 @@ dependencies = [
[[package]]
name = "windmill-types"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"bitflags 2.13.2",
@@ -17606,7 +17608,7 @@ dependencies = [
[[package]]
name = "windmill-worker"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-once-cell",
@@ -17724,7 +17726,7 @@ dependencies = [
[[package]]
name = "windmill-worker-volumes"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"bytes",
"fs4",
@@ -18522,18 +18524,18 @@ dependencies = [
[[package]]
name = "zerocopy"
version = "0.8.65"
version = "0.8.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32bc8a75f879cd6fe53a6bedf3c28f0e1b914c77424fc2be9e2ec85d7d25aff5"
checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.65"
version = "0.8.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8bfd2644ea1681f60cf95029ff18aa8ad1cc3f7b8fe37286f8e473bb29f816b"
checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"
dependencies = [
"proc-macro2",
"quote",
+21 -14
View File
@@ -1,6 +1,6 @@
[package]
name = "windmill"
version = "1.884.1"
version = "1.885.0"
authors.workspace = true
edition.workspace = true
@@ -88,7 +88,7 @@ members = [
exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"]
[workspace.package]
version = "1.884.1"
version = "1.885.0"
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
edition = "2021"
@@ -226,12 +226,16 @@ all_sqlx_features = ["all_languages", "enterprise", "enterprise_saml", "embeddin
"windmill-git-sync/all_sqlx_features"]
[patch.crates-io]
# v0.8.6 plus the fix below and two `#[sqlx::test]`-only changes, both set in .cargo/config.toml:
# v0.8.6 plus the two fixes below and two `#[sqlx::test]`-only changes, both set in .cargo/config.toml:
# `SQLX_TEST_TEMPLATE` clones each test database from a template migrated once per migration
# set instead of migrating it per test, and `SQLX_TEST_MAX_CONNECTIONS` lifts the cap on the
# connections all test pools share. The rev is tagged `windmill-0.8.6-test-template-c1c5f1f` in
# the fork so it stays fetchable.
# The fix: `Pool::begin` is not cancel-safe on Postgres. sqlx raises the
# connections all test pools share. The rev is tagged `windmill-0.8.6-return-to-pool-timeout-ac66fd0`
# in the fork so it stays fetchable.
# The return-to-pool fix (launchbadge/sqlx#4349): a dropped connection's permit is held while
# sqlx pings it, with no time limit, so a peer that went silent (a Postgres primary after a
# failover) leaks permits until every `acquire()` fails with PoolTimedOut. It bounds that step to
# 5s. Drop it once a release we take carries transact-rs/sqlx#4350.
# The `Pool::begin` fix: `Pool::begin` is not cancel-safe on Postgres. sqlx raises the
# transaction depth its rollback-on-drop guard keys on only *after* the BEGIN round trip, so
# a cancelled caller (a disconnecting API client, a `timeout`, an aborted task) leaves the
# session in a transaction nothing will end, and the pool hands that connection out again —
@@ -242,15 +246,17 @@ all_sqlx_features = ["all_languages", "enterprise", "enterprise_saml", "embeddin
# inside the sqlx workspace, so patching it alone leaves two incompatible `sqlx-core`s and
# `Postgres` stops implementing the `Database` the macros expect.
# Changing any of this — a bump, a rebase of the fork, dropping these lines — still compiles
# clean, so run the guard that actually checks the behaviour is still there:
# clean, so run the guards that actually check the behaviour is still there, the first here and
# the second in the fork:
# cargo test -p windmill-common --test sqlx_begin_cancel_safe -- --ignored
sqlx = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" }
sqlx-core = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" }
sqlx-macros = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" }
sqlx-macros-core = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" }
sqlx-postgres = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" }
sqlx-mysql = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" }
sqlx-sqlite = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" }
# cargo test --test postgres-pool --no-default-features --features postgres,runtime-tokio,macros,migrate
sqlx = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" }
sqlx-core = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" }
sqlx-macros = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" }
sqlx-macros-core = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" }
sqlx-postgres = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" }
sqlx-mysql = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" }
sqlx-sqlite = { git = "https://github.com/windmill-labs/sqlx", rev = "ac66fd0c03daf6a0c0e307a1a86d2a7c6cafa459" }
object_store = { git = "https://github.com/apache/arrow-rs-object-store", rev = "36752c975d4f29e20b57c91f81a10872dcd48ae7" }
# Use tiberius main branch for libgssapi 0.8.1 fix (https://github.com/prisma/tiberius/issues/343)
tiberius = { git = "https://github.com/prisma/tiberius", rev = "59db57960a14b422fb3a1309aa4aa47880896ff8" }
@@ -706,6 +712,7 @@ tracing-opentelemetry = "0.31.0"
opentelemetry_sdk = { version = "0.30.0", features = ["rt-tokio", "testing"] }
opentelemetry-otlp = { version = "0.30.0", features = ["grpc-tonic", "tls", "http-proto", "gzip-tonic", "zstd-tonic"] }
opentelemetry-appender-tracing = "0.30.0"
opentelemetry-http = "0.30.0"
opentelemetry-semantic-conventions = { version = "0.30.0", features = ["semconv_experimental"] }
opentelemetry-proto = { version = "0.30.0", features = ["with-serde", "gen-tonic"] }
prost = "0.13"
@@ -0,0 +1 @@
ALTER TABLE concurrency_key DROP COLUMN IF EXISTS released_at;
@@ -0,0 +1,2 @@
-- When the concurrency limit let in a job it had held back: the time the job was last due.
ALTER TABLE concurrency_key ADD COLUMN IF NOT EXISTS released_at TIMESTAMPTZ;
@@ -0,0 +1,15 @@
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'r') THEN
ALTER TABLE audit DROP COLUMN IF EXISTS client_ip, DROP COLUMN IF EXISTS user_agent;
ELSIF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'v') THEN
DROP VIEW audit;
CREATE VIEW audit AS
SELECT workspace_id, id, timestamp, username, operation, action_kind, resource,
parameters, email, span
FROM audit_partitioned WHERE false;
GRANT ALL ON audit TO windmill_user, windmill_admin;
END IF;
END $$;
ALTER TABLE audit_partitioned DROP COLUMN IF EXISTS client_ip, DROP COLUMN IF EXISTS user_agent;
@@ -0,0 +1,15 @@
ALTER TABLE audit_partitioned ADD COLUMN IF NOT EXISTS client_ip TEXT, ADD COLUMN IF NOT EXISTS user_agent TEXT;
-- Older servers read `SELECT * FROM audit_partitioned UNION ALL SELECT * FROM audit`, so the
-- legacy table, or the empty view that replaces it, carries the same columns in the same order.
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'r') THEN
ALTER TABLE audit ADD COLUMN IF NOT EXISTS client_ip TEXT, ADD COLUMN IF NOT EXISTS user_agent TEXT;
ELSIF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'v') THEN
CREATE OR REPLACE VIEW audit AS
SELECT workspace_id, id, timestamp, username, operation, action_kind, resource,
parameters, email, span, client_ip, user_agent
FROM audit_partitioned WHERE false;
END IF;
END $$;
@@ -749,11 +749,17 @@ fn extract_nimports_from_content(
locked_version
}
const STDIMPORTS: [&str; 303] = [
// Union of `sys.stdlib_module_names` over every `PyVAlias` version (3.10 to 3.15), `_`
// written as `-` like the inferred package names. Regenerate when a version is added;
// modules a later version removed stay, since older workers still ship them.
const STDIMPORTS: [&str; 332] = [
"--future--",
"-abc",
"-aix-support",
"-android-support",
"-apple-support",
"-ast",
"-ast-unparse",
"-asyncio",
"-bisect",
"-blake2",
@@ -768,6 +774,7 @@ const STDIMPORTS: [&str; 303] = [
"-codecs-tw",
"-collections",
"-collections-abc",
"-colorize",
"-compat-pickle",
"-compression",
"-contextvars",
@@ -786,18 +793,25 @@ const STDIMPORTS: [&str; 303] = [
"-gdbm",
"-hashlib",
"-heapq",
"-hmac",
"-imp",
"-interpchannels",
"-interpqueues",
"-interpreters",
"-io",
"-ios-support",
"-json",
"-locale",
"-lsprof",
"-lzma",
"-markupbase",
"-math-integer",
"-md5",
"-msi",
"-multibytecodec",
"-multiprocessing",
"-opcode",
"-opcode-metadata",
"-operator",
"-osx-support",
"-overlapped",
@@ -805,11 +819,18 @@ const STDIMPORTS: [&str; 303] = [
"-posixshmem",
"-posixsubprocess",
"-py-abc",
"-py-warnings",
"-pydatetime",
"-pydecimal",
"-pyio",
"-pylong",
"-pyrepl",
"-queue",
"-random",
"-remote-debugging",
"-scproxy",
"-sha1",
"-sha2",
"-sha256",
"-sha3",
"-sha512",
@@ -824,20 +845,27 @@ const STDIMPORTS: [&str; 303] = [
"-string",
"-strptime",
"-struct",
"-suggestions",
"-symtable",
"-sysconfig",
"-thread",
"-threading-local",
"-tkinter",
"-tokenize",
"-tracemalloc",
"-types",
"-typing",
"-uuid",
"-warnings",
"-weakref",
"-weakrefset",
"-winapi",
"-wmi",
"-zoneinfo",
"zoneinfo",
"-zstd",
"abc",
"aifc",
"annotationlib",
"antigravity",
"argparse",
"array",
@@ -867,6 +895,7 @@ const STDIMPORTS: [&str; 303] = [
"collections",
"colorsys",
"compileall",
"compression",
"concurrent",
"configparser",
"contextlib",
@@ -963,6 +992,7 @@ const STDIMPORTS: [&str; 303] = [
"posixpath",
"pprint",
"profile",
"profiling",
"pstats",
"pty",
"pwd",
@@ -1024,6 +1054,7 @@ const STDIMPORTS: [&str; 303] = [
"tkinter",
"token",
"tokenize",
"tomllib",
"trace",
"traceback",
"tracemalloc",
@@ -1052,5 +1083,6 @@ const STDIMPORTS: [&str; 303] = [
"zipfile",
"zipimport",
"zlib",
"zoneinfo",
"",
];
@@ -157,6 +157,24 @@ def main():
Ok(())
}
#[test]
fn test_recent_stdlib_modules_not_inferred() -> anyhow::Result<()> {
let code = "
import tomllib
import annotationlib
from compression import zstd
import requests
def main():
return tomllib.loads(\"a = 1\")
";
assert_eq!(
parse_code_for_imports(code, "f/foo/bar")?,
vec![auto("requests")]
);
Ok(())
}
#[test]
fn test_parse_imports_recent_syntax_before_main() -> anyhow::Result<()> {
let code = r#"
+24 -24
View File
@@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windmill-common"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"aes-gcm",
"aho-corasick",
@@ -6430,7 +6430,7 @@ dependencies = [
[[package]]
name = "windmill-macros"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"proc-macro2",
"quote",
@@ -6442,7 +6442,7 @@ dependencies = [
[[package]]
name = "windmill-parser"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"convert_case",
"serde",
@@ -6451,7 +6451,7 @@ dependencies = [
[[package]]
name = "windmill-parser-bash"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6463,7 +6463,7 @@ dependencies = [
[[package]]
name = "windmill-parser-csharp"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde_json",
@@ -6475,7 +6475,7 @@ dependencies = [
[[package]]
name = "windmill-parser-go"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"gosyn",
@@ -6487,7 +6487,7 @@ dependencies = [
[[package]]
name = "windmill-parser-graphql"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6499,7 +6499,7 @@ dependencies = [
[[package]]
name = "windmill-parser-java"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde_json",
@@ -6511,7 +6511,7 @@ dependencies = [
[[package]]
name = "windmill-parser-nu"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"nu-parser",
@@ -6522,7 +6522,7 @@ dependencies = [
[[package]]
name = "windmill-parser-php"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -6533,7 +6533,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -6545,7 +6545,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-asset"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -6556,7 +6556,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-imports"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"async-recursion",
@@ -6579,7 +6579,7 @@ dependencies = [
[[package]]
name = "windmill-parser-r"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde_json",
@@ -6591,7 +6591,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ruby"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6605,7 +6605,7 @@ dependencies = [
[[package]]
name = "windmill-parser-rust"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"convert_case",
@@ -6622,7 +6622,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6635,7 +6635,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql-asset"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde",
@@ -6647,7 +6647,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6665,7 +6665,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts-asset"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"serde-wasm-bindgen",
@@ -6681,7 +6681,7 @@ dependencies = [
[[package]]
name = "windmill-parser-wac"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -6698,7 +6698,7 @@ dependencies = [
[[package]]
name = "windmill-parser-wasm"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"getrandom 0.2.17",
@@ -6730,7 +6730,7 @@ dependencies = [
[[package]]
name = "windmill-parser-yaml"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"lazy_static",
@@ -6744,7 +6744,7 @@ dependencies = [
[[package]]
name = "windmill-types"
version = "1.884.1"
version = "1.885.0"
dependencies = [
"anyhow",
"bitflags",
@@ -12,7 +12,7 @@ resolver = "2"
members = ["."]
[workspace.package]
version = "1.884.1"
version = "1.885.0"
edition = "2021"
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
+42 -2
View File
@@ -111,7 +111,7 @@ use windmill_common::{
CRITICAL_ALERT_MUTE_ZOMBIE_JOB_RESTART, CRITICAL_ERROR_CHANNELS, DB, DEFAULT_HUB_BASE_URL,
DEFAULT_OTEL_TRACES_RETENTION_SECS, DEFAULT_SERVICE_LOG_RETENTION_SECS, HUB_BASE_URL,
JOB_RETENTION_SECS, JOB_RETENTION_SECS_OVERRIDES, JOB_RETENTION_SECS_OVERRIDES_LOADED,
METRICS_DEBUG_ENABLED, METRICS_ENABLED, MONITOR_LOGS_ON_OBJECT_STORE, OTEL_LOGS_ENABLED,
METRICS_DEBUG_ENABLED, METRICS_ENABLED, MONITOR_LOGS_ON_OBJECT_STORE, OtelAuditLogsExport, OTEL_AUDIT_LOGS_EXPORT, OTEL_LOGS_ENABLED, OTEL_LOGS_EXCLUDE_AUDIT,
OTEL_METRICS_ENABLED, OTEL_TRACING_ENABLED, STORE_AUDIT_LOGS_S3,
};
use windmill_common::{
@@ -802,6 +802,15 @@ pub fn apply_metrics_enabled(value: Option<serde_json::Value>) {
struct OtelSetting {
metrics_enabled: Option<bool>,
logs_enabled: Option<bool>,
logs_exclude_audit: Option<bool>,
audit_logs_enabled: Option<bool>,
#[serde(default, deserialize_with = "empty_as_none")]
audit_logs_endpoint: Option<String>,
#[serde(default, deserialize_with = "empty_as_none")]
audit_logs_headers: Option<String>,
#[serde(default, deserialize_with = "empty_as_none")]
audit_logs_protocol: Option<String>,
audit_logs_workspaces: Option<Vec<String>>,
tracing_enabled: Option<bool>,
#[serde(default, deserialize_with = "empty_as_none")]
otel_exporter_otlp_endpoint: Option<String>,
@@ -837,6 +846,37 @@ pub async fn load_otel(db: &DB) {
OTEL_METRICS_ENABLED.store(metrics_enabled, Ordering::Relaxed);
OTEL_LOGS_ENABLED.store(logs_enabled, Ordering::Relaxed);
let env_bool = |var: &str| {
std::env::var(var)
.map(|x| x.parse::<bool>().unwrap_or(false))
.unwrap_or(false)
};
let logs_exclude_audit = o
.logs_exclude_audit
.unwrap_or_else(|| env_bool("OTEL_LOGS_EXCLUDE_AUDIT"));
OTEL_LOGS_EXCLUDE_AUDIT.store(logs_exclude_audit, Ordering::Relaxed);
let audit_logs = OtelAuditLogsExport::new(
o.audit_logs_enabled
.unwrap_or_else(|| env_bool("OTEL_AUDIT_LOGS_ENABLED")),
o.audit_logs_endpoint
.or_else(|| std::env::var("OTEL_AUDIT_LOGS_ENDPOINT").ok()),
o.audit_logs_headers
.or_else(|| std::env::var("OTEL_AUDIT_LOGS_HEADERS").ok()),
o.audit_logs_protocol
.or_else(|| std::env::var("OTEL_AUDIT_LOGS_PROTOCOL").ok()),
// A saved empty list means every workspace and does not fall back to the
// environment, so clearing the list in the UI cannot bring an env list back.
o.audit_logs_workspaces.or_else(|| {
std::env::var("OTEL_AUDIT_LOGS_WORKSPACES")
.ok()
.map(|v| v.split(',').map(str::to_string).collect())
}),
);
let audit_logs_endpoint = audit_logs.as_ref().map(|a| a.endpoint.clone());
if let Ok(mut export) = OTEL_AUDIT_LOGS_EXPORT.write() {
*export = audit_logs;
}
OTEL_TRACING_ENABLED.store(tracing_enabled, Ordering::Relaxed);
let endpoint = if let Some(endpoint) = o.otel_exporter_otlp_endpoint {
@@ -867,7 +907,7 @@ pub async fn load_otel(db: &DB) {
std::env::set_var("OTEL_EXPORTER_OTLP_COMPRESSION", compression);
}
}
println!("OTEL settings loaded: tracing ({tracing_enabled}), logs ({logs_enabled}), metrics ({metrics_enabled}), endpoint ({:?}), headers defined: ({})",
println!("OTEL settings loaded: tracing ({tracing_enabled}), logs ({logs_enabled}, without audit: {logs_exclude_audit}), audit logs endpoint ({audit_logs_endpoint:?}), metrics ({metrics_enabled}), endpoint ({:?}), headers defined: ({})",
endpoint, headers.is_some());
} else {
tracing::error!("Error deserializing otel settings");
+38
View File
@@ -0,0 +1,38 @@
//! A browser can send two `token` cookies: this instance's, and one a parent-domain instance set
//! with `Domain=` (app.windmill.dev on `.windmill.dev`, seen from a tenant subdomain). Safari
//! sends the host's cookie first and Chrome last, so the request must authenticate on whichever
//! is a live session here, in either order.
use reqwest::StatusCode;
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
#[sqlx::test(fixtures("base"))]
async fn test_duplicate_session_cookie_uses_the_live_one(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let client = reqwest::Client::new();
let url = format!(
"http://localhost:{}/api/workspaces/users",
server.addr.port()
);
let status = |cookie: &'static str| {
let req = client.get(&url).header("Cookie", cookie);
async move { anyhow::Ok(req.send().await?.status()) }
};
assert_eq!(
status("token=FOREIGN_INSTANCE_TOKEN; token=SECRET_TOKEN").await?,
StatusCode::OK
);
assert_eq!(
status("token=SECRET_TOKEN; token=FOREIGN_INSTANCE_TOKEN").await?,
StatusCode::OK
);
assert_eq!(
status("token=FOREIGN_INSTANCE_TOKEN; token=OTHER_FOREIGN_TOKEN").await?,
StatusCode::UNAUTHORIZED
);
Ok(())
}
+80
View File
@@ -801,3 +801,83 @@ async fn test_require_isolated_forks(db: Pool<Postgres>) -> anyhow::Result<()> {
Ok(())
}
#[sqlx::test(fixtures("base"))]
async fn test_require_sso(db: Pool<Postgres>) -> anyhow::Result<()> {
sqlx::raw_sql(
"INSERT INTO workspace (id, name, owner) VALUES ('sso-ws', 'sso-ws', 'test-user');
INSERT INTO workspace_settings (workspace_id) VALUES ('sso-ws');
INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES
('sso-ws', 'all', 'All users', '{}');
INSERT INTO usr (workspace_id, email, username, is_admin, role) VALUES
('sso-ws', 'test@windmill.dev', 'test-user', true, 'Admin');
INSERT INTO password (email, login_type, verified, username) VALUES
('sso@windmill.dev', 'google', true, 'sso-user'),
('pw@windmill.dev', 'password', true, 'pw-user'),
('pw-bypass@windmill.dev', 'password', true, 'pw-bypass')",
)
.execute(&db)
.await?;
let server = ApiServer::start(db.clone()).await?;
let api = format!("http://localhost:{}/api", server.addr.port());
let post = |path: String, body: serde_json::Value| {
authed(client().post(format!("{api}{path}")), "SECRET_TOKEN").json(&body)
};
let add = |email: &str| {
post(
"/w/sso-ws/workspaces/add_user".to_string(),
json!({"email": email, "is_admin": false, "operator": false}),
)
};
let resp = post(
"/w/sso-ws/workspaces/protection_rules".to_string(),
json!({"name": "sso", "rules": ["RequireSso"], "bypass_groups": [], "bypass_users": ["pw-bypass"]}),
)
.send()
.await?;
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
let resp = add("pw@windmill.dev").send().await?;
let status = resp.status();
let text = resp.text().await?;
assert_eq!(status, 400, "a password account must not join: {text}");
assert!(text.contains("requires SSO"), "{text}");
for email in ["sso@windmill.dev", "pw-bypass@windmill.dev"] {
let resp = add(email).send().await?;
assert_eq!(resp.status(), 201, "{email}: {}", resp.text().await?);
}
let to_password = |email: &str| {
post(
format!("/users/set_login_type/{email}"),
json!({"login_type": "password"}),
)
};
let resp = to_password("sso@windmill.dev").send().await?;
assert_eq!(resp.status(), 400, "{}", resp.text().await?);
let login_type: String =
sqlx::query_scalar("SELECT login_type FROM password WHERE email = 'sso@windmill.dev'")
.fetch_one(&db)
.await?;
assert_eq!(login_type, "google");
// A bypasser is not held by the rule.
let resp = to_password("pw-bypass@windmill.dev").send().await?;
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
// Every new member is in `all`, so bypassing it admits anyone.
let resp = post(
"/w/sso-ws/workspaces/protection_rules/sso".to_string(),
json!({"name": "sso", "rules": ["RequireSso"], "bypass_groups": ["all"], "bypass_users": []}),
)
.send()
.await?;
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
let resp = add("pw@windmill.dev").send().await?;
assert_eq!(resp.status(), 201, "{}", resp.text().await?);
Ok(())
}
+83
View File
@@ -0,0 +1,83 @@
//! A token scoped to one folder's schedules or triggers may bind them only to runnables it could
//! run itself: what they name later runs as the owner, with no token scopes left to check.
use serde_json::{json, Value};
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
#[sqlx::test(fixtures("base"))]
async fn a_save_needs_run_scope_on_what_it_names(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
sqlx::raw_sql(
r#"INSERT INTO folder(workspace_id, name, display_name, owners, extra_perms)
VALUES ('test-workspace', 'a', 'a', '{}', '{}'), ('test-workspace', 'b', 'b', '{}', '{}');
INSERT INTO token(token_hash, token_prefix, token, email, label, scopes) VALUES
(encode(sha256('WRITE_ONLY'::bytea), 'hex'), 'WRITE_ONLY', 'WRITE_ONLY',
'test@windmill.dev', 'w', '{schedules:write:f/a/*,http_triggers:write:f/a/*}'),
(encode(sha256('WRITE_RUN'::bytea), 'hex'), 'WRITE_RUN_', 'WRITE_RUN',
'test@windmill.dev', 'wr',
'{schedules:write:f/a/*,http_triggers:write:f/a/*,jobs:run:scripts:f/b/*}');"#,
)
.execute(&db)
.await?;
let server = ApiServer::start(db.clone()).await?;
let ws = format!(
"http://localhost:{}/api/w/test-workspace",
server.addr.port()
);
let client = reqwest::Client::new();
let send = async |token: &str, route: &str, body: Value| {
let resp = client
.post(format!("{ws}/{route}"))
.bearer_auth(token)
.json(&body)
.send()
.await
.unwrap();
(resp.status().as_u16(), resp.text().await.unwrap())
};
// (route, body, the path the write-only token is refused on)
#[allow(unused_mut)]
let mut saves: Vec<(&str, Value, &str)> = vec![
(
"schedules/create",
json!({"path": "f/a/sched", "schedule": "0 0 0 * * *", "timezone": "UTC",
"script_path": "f/b/x", "is_flow": false, "enabled": false}),
"f/b/x",
),
(
"schedules/create",
json!({"path": "f/a/sched_handler", "schedule": "0 0 0 * * *", "timezone": "UTC",
"script_path": "f/b/x", "is_flow": false, "enabled": false,
"on_failure": "script/f/b/y"}),
"f/b/y",
),
];
#[cfg(feature = "http_trigger")]
saves.push((
"http_triggers/create",
json!({"path": "f/a/route", "script_path": "f/b/x", "is_flow": false,
"mode": "disabled", "route_path": "a_route", "request_type": "async",
"authentication_method": "none", "http_method": "post",
"is_static_website": false, "workspaced_route": true, "wrap_body": false,
"raw_string": false}),
"f/b/x",
));
for (route, body, refused) in saves {
let (s, b) = send("WRITE_ONLY", route, body.clone()).await;
assert_eq!(s, 403, "{route} {body}: {b}");
assert!(b.contains(&format!("jobs:run:scripts:{refused}")), "{b}");
let (s, b) = send("WRITE_RUN", route, body.clone()).await;
assert!(s < 300, "{route} {body}: {b}");
}
// An edit sets the stored target's args, so it is held to the same scope.
let edit = json!({"schedule": "0 0 1 * * *", "timezone": "UTC", "args": {"x": 1}});
let (s, b) = send("WRITE_ONLY", "schedules/update/f/a/sched", edit.clone()).await;
assert_eq!(s, 403, "{b}");
let (s, b) = send("WRITE_RUN", "schedules/update/f/a/sched", edit).await;
assert!(s < 300, "{b}");
Ok(())
}
+2 -1
View File
@@ -518,11 +518,12 @@ fn test_volume_nsjail_mount() {
fn test_sync_stats_default() {
use windmill_worker_volumes::SyncStats;
let stats = SyncStats { new_size_bytes: 0, file_count: 0, uploaded: 0, skipped: 0 };
let stats = SyncStats { new_size_bytes: 0, file_count: 0, uploaded: 0, skipped: 0, deleted: 0 };
assert_eq!(stats.new_size_bytes, 0);
assert_eq!(stats.file_count, 0);
assert_eq!(stats.uploaded, 0);
assert_eq!(stats.skipped, 0);
assert_eq!(stats.deleted, 0);
}
#[test]
+80 -8
View File
@@ -41,6 +41,8 @@ lazy_static::lazy_static! {
pub static ref AUTH_CACHE: Cache<(String, String), ExpiringAuthCache> = Cache::new(300);
// Cache for token -> email lookups (for non-workspace-member authenticated users)
static ref TOKEN_EMAIL_CACHE: Cache<String, (Option<String>, std::time::Instant)> = Cache::new(500);
// Joined hashes of a request's duplicate `token` cookies -> index of the live one.
static ref PICKED_SESSION_CACHE: Cache<String, (Option<usize>, std::time::Instant)> = Cache::new(500);
}
/// A token keeps its identity when a superadmin moves the account to another address, so entries
@@ -956,6 +958,69 @@ async fn admit_and_record_guest_jwt(db: &DB, w_id: &str, email: &str, app_path:
true
}
/// Browsers send one or two; checking more would let one request try many guessed tokens
/// while `BRUTE_FORCE_COUNTER` counts a single failure.
const MAX_SESSION_COOKIES: usize = 4;
/// The first `token` cookie values, parsed the way `Cookies` parses them, in the order sent.
fn session_cookie_values(parts: &Parts) -> Vec<String> {
parts
.headers
.get_all(http::header::COOKIE)
.iter()
.filter_map(|h| h.to_str().ok())
.flat_map(|h| h.split(';'))
.filter_map(|c| tower_cookies::Cookie::parse_encoded(c).ok())
.filter(|c| c.name() == COOKIE_NAME)
.map(|c| c.value_trimmed().to_owned())
.take(MAX_SESSION_COOKIES)
.collect()
}
/// A browser can hold two `token` cookies for one host: this instance's, and one a parent-domain
/// instance set with `Domain=` (app.windmill.dev on `.windmill.dev`), which JS cannot clear since
/// it is HttpOnly. Browsers disagree on their order (Safari sends the host's first, Chrome last),
/// so neither position can be trusted: keep the first one that is a live session here.
async fn pick_live_session_token<S: Send + Sync>(
parts: &mut Parts,
state: &S,
candidates: Vec<String>,
) -> Option<String> {
// `Cookies::get` keeps the last duplicate: the pick when nothing can be checked.
let fallback = candidates.last().cloned();
let Ok(Extension(cache)) = Extension::<Arc<AuthCache>>::from_request_parts(parts, state).await
else {
return fallback;
};
let hashes: Vec<String> = candidates.iter().map(|t| hash_token(t)).collect();
// A browser keeps sending the same pair on every request, so the pick is cached. A token
// revoked within the TTL can still be picked, and then fails authentication as revoked.
let key = hashes.join(",");
if let Some((picked, at)) = PICKED_SESSION_CACHE.get(&key) {
if at.elapsed().as_secs() < TOKEN_EMAIL_CACHE_TTL_SECS {
return picked.map(|i| candidates[i].clone()).or(fallback);
}
}
let live: Vec<String> = match sqlx::query_scalar(
"SELECT h FROM unnest($1::text[]) AS h \
WHERE EXISTS (SELECT 1 FROM token WHERE token_hash = h \
AND (expiration > NOW() OR expiration IS NULL))",
)
.bind(&hashes)
.fetch_all(&cache.db)
.await
{
Ok(live) => live,
Err(e) => {
tracing::error!("checking duplicate session cookies: {e:#}");
return fallback;
}
};
let picked = hashes.iter().position(|h| live.contains(h));
PICKED_SESSION_CACHE.insert(key, (picked, std::time::Instant::now()));
picked.map(|i| candidates[i].clone()).or(fallback)
}
pub(crate) async fn extract_token<S: Send + Sync>(parts: &mut Parts, state: &S) -> Option<String> {
let auth_header = parts
.headers
@@ -965,14 +1030,21 @@ pub(crate) async fn extract_token<S: Send + Sync>(parts: &mut Parts, state: &S)
let from_cookie = match auth_header {
Some(x) => Some(x.to_owned()),
None => Extension::<Cookies>::from_request_parts(parts, state)
.await
.ok()
.and_then(|cookies| {
cookies
.get(COOKIE_NAME)
.map(|c| c.value_trimmed().to_owned())
}),
None => {
let candidates = session_cookie_values(parts);
if candidates.len() > 1 {
pick_live_session_token(parts, state, candidates).await
} else {
Extension::<Cookies>::from_request_parts(parts, state)
.await
.ok()
.and_then(|cookies| {
cookies
.get(COOKIE_NAME)
.map(|c| c.value_trimmed().to_owned())
})
}
}
};
#[derive(Deserialize)]
+18
View File
@@ -462,6 +462,24 @@ where
Ok(())
}
/// A trigger or schedule runs what it names as its owner, in a background job that carries no
/// token scopes, so the `jobs:run` scope a direct run would need is checked at save time against
/// the caller's token.
pub fn check_run_scopes<'a>(
authed: &ApiAuthed,
runnables: impl IntoIterator<Item = &'a windmill_common::runnable_ref::RunnableRef>,
) -> error::Result<()> {
for runnable in runnables {
let kind = if runnable.is_flow() {
"flows"
} else {
"scripts"
};
check_scopes(authed, || format!("jobs:run:{kind}:{}", runnable.path()))?;
}
Ok(())
}
/// Returns the caller's "real" scope restrictions: every scope other than
/// `if_jobs:filter_tags:` tag filters. `None` means the token is unscoped and
/// has the full privileges of its user; `Some` means it is restricted to the
+4 -2
View File
@@ -348,7 +348,7 @@ fn extract_domain_from_route(
/// exports) and credential minting (`job_view_token`) are deliberately absent — those are
/// `jobs:read`. Keep by-id read routes here in sync as they are added, or a run token
/// loses the ability to follow its own run through them.
const RUN_WHITELISTED_GET_PATHS: [&'static str; 33] = [
const RUN_WHITELISTED_GET_PATHS: [&'static str; 34] = [
"jobs_u/get_flow/",
"jobs_u/get_root_job_id/",
"jobs_u/get/",
@@ -377,6 +377,7 @@ const RUN_WHITELISTED_GET_PATHS: [&'static str; 33] = [
"jobs/job_signature/",
"jobs/wac_approval_urls/",
"jobs/flow/approval_step_detail/",
"jobs/flow/nested_approvals/",
"jobs/completed/get/",
"jobs/completed/get_result/",
"jobs/completed/get_result_maybe/",
@@ -575,7 +576,7 @@ fn resource_metadata_route_allowed(suffix: &str) -> bool {
/// a direct `require_job_within_read_scope`. `jobs/result_by_id/` is absent because it
/// resolves a node up through the enclosing flows, past the job the check admitted.
/// A route added here without that check serves a path-scoped token every job.
const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 26] = [
const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 27] = [
"jobs_u/get/",
"jobs_u/get_logs/",
"jobs_u/get_completed_logs_tail/",
@@ -595,6 +596,7 @@ const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 26] = [
"jobs_u/get_flow/",
"jobs_u/flow/approval_info/",
"jobs/flow/approval_step_detail/",
"jobs/flow/nested_approvals/",
"jobs/run_progress/",
"jobs/flow/user_states/",
"jobs/completed/get/",
@@ -482,12 +482,130 @@ async fn test_offboard_conflicts(db: Pool<Postgres>) -> anyhow::Result<()> {
.any(|c| c.as_str().unwrap().contains("conflict_script")),
"conflict should mention conflict_script"
);
// The UI resolves each conflict by deleting one side, so both paths must be reported.
let items = body["conflict_items"]
.as_array()
.expect("conflict_items should be array");
assert_eq!(items.len(), conflicts.len());
let item = items
.iter()
.find(|c| c["source_path"] == "u/test-user-2/conflict_script")
.expect("conflict_items should include conflict_script");
assert_eq!(item["kind"], "script");
assert_eq!(item["target_path"], "u/test-user/conflict_script");
assert_eq!(item["workspace_id"], "test-workspace");
// No summary when conflicts exist
assert!(body["summary"].is_null());
Ok(())
}
/// Usernames may hold `_`, a LIKE wildcard: another user's item matched by it maps to itself, so
/// it must be neither reported as a conflict (which offers to delete it) nor cleaned up as stale.
#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))]
async fn test_offboard_conflicts_underscore_username(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
sqlx::query(
"INSERT INTO usr (workspace_id, email, username, is_admin, role)
VALUES ('test-workspace', 'underscore@windmill.dev', 'test_user', false, 'User')",
)
.execute(&db)
.await?;
sqlx::query(
"INSERT INTO variable (workspace_id, path, value, is_secret, description)
VALUES ('test-workspace', 'u/testxuser/var', 'v', false, '')",
)
.execute(&db)
.await?;
sqlx::query(
"INSERT INTO asset (workspace_id, path, kind, usage_path, usage_kind)
VALUES ('test-workspace', 'main', 'datatable', 'u/testxuser/s', 'script')",
)
.execute(&db)
.await?;
sqlx::query(
"INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path)
VALUES ('test-workspace', 'u/testxuser/s', 'script', 'f/shared/lib')",
)
.execute(&db)
.await?;
let resp = authed(client().post(ws_url(port, "offboard/test_user")))
.json(&json!({ "reassign_to": "u/test-user", "delete_user": false }))
.send()
.await?;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await?;
assert!(body["conflict_items"].is_null(), "{body}");
let untouched: i64 = sqlx::query_scalar(
"SELECT (SELECT COUNT(*) FROM asset WHERE usage_path = 'u/testxuser/s')
+ (SELECT COUNT(*) FROM dependency_map WHERE importer_path = 'u/testxuser/s')
+ (SELECT COUNT(*) FROM variable WHERE path = 'u/testxuser/var')",
)
.fetch_one(&db)
.await?;
assert_eq!(untouched, 3, "another user's rows must survive the reassignment");
Ok(())
}
/// Resolving a conflict by deleting the target leaves that script's `dependency_map` and `asset`
/// rows behind, on the keys the departing user's rows are renamed onto.
#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))]
async fn test_offboard_over_deleted_target(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
sqlx::query(
"INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path)
VALUES ('test-workspace', 'u/test-user/conflict_script', 'script', 'f/shared/lib'),
('test-workspace', 'u/test-user-2/conflict_script', 'script', 'f/shared/lib')",
)
.execute(&db)
.await?;
sqlx::query(
"INSERT INTO asset (workspace_id, path, kind, usage_path, usage_kind)
VALUES ('test-workspace', 'main', 'datatable', 'u/test-user/conflict_script', 'script'),
('test-workspace', 'main', 'datatable', 'u/test-user-2/conflict_script', 'script')",
)
.execute(&db)
.await?;
let resp = authed(client().post(format!(
"http://localhost:{port}/api/w/test-workspace/scripts/delete/p/u/test-user/conflict_script"
)))
.send()
.await?;
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
let resp = authed(client().post(ws_url(port, "offboard/test-user-2")))
.json(&json!({ "reassign_to": "u/test-user", "delete_user": false }))
.send()
.await?;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await?;
assert!(body["summary"].is_object(), "{body}");
let importers: Vec<String> = sqlx::query_scalar(
"SELECT importer_path FROM dependency_map
WHERE workspace_id = 'test-workspace' AND imported_path = 'f/shared/lib'",
)
.fetch_all(&db)
.await?;
assert_eq!(importers, vec!["u/test-user/conflict_script".to_string()]);
let users: Vec<String> = sqlx::query_scalar(
"SELECT usage_path FROM asset WHERE workspace_id = 'test-workspace' AND path = 'main'",
)
.fetch_all(&db)
.await?;
assert_eq!(users, vec!["u/test-user/conflict_script".to_string()]);
Ok(())
}
#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))]
async fn test_offboard_tokens_deleted(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
@@ -1,7 +1,10 @@
use serde_json::json;
use serial_test::serial;
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
/// Every test here must be `#[serial]`: the rights cache is process-global and keyed by workspace id
/// alone, so parallel tests under this same id read each other's rights.
const WS: &str = "test-workspace";
fn operator_client() -> reqwest::Client {
@@ -82,6 +85,7 @@ fn inline_code_flow(path: &str) -> serde_json::Value {
/// already deployed and nothing more, and the endpoints that author code stay shut whether or not
/// it is granted.
#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))]
#[serial]
async fn test_operator_builder_flows_boundary(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
@@ -477,3 +481,49 @@ async fn check_builder_agents(
Ok(())
}
/// Each slot of a flow picks scripts of its own kind. A role without `code` gets the kind it asks
/// for, preprocessors without a main included, and still no library.
#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))]
#[serial]
async fn test_operator_lists_scripts_of_the_requested_kind(
db: Pool<Postgres>,
) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let api = format!("http://localhost:{port}/api/w/{WS}");
let c = operator_client();
add_script(&db, 5001, "u/operator/action", "operator").await?;
add_script(&db, 5002, "u/operator/library", "operator").await?;
add_script(&db, 5003, "u/operator/prep", "operator").await?;
sqlx::query(
"UPDATE script SET auto_kind = 'lib',
kind = CASE WHEN hash = 5003 THEN 'preprocessor' ELSE kind END
WHERE hash IN (5002, 5003)",
)
.execute(&db)
.await?;
for (query, expected) in [
("", vec!["u/operator/action"]),
("&kinds=preprocessor", vec!["u/operator/prep"]),
(
"&kinds=script,preprocessor",
vec!["u/operator/action", "u/operator/prep"],
),
] {
let scripts: Vec<serde_json::Value> = c
.get(format!("{api}/scripts/list?path_start=u/operator/{query}"))
.send()
.await?
.error_for_status()?
.json()
.await?;
let mut paths: Vec<&str> = scripts.iter().filter_map(|s| s["path"].as_str()).collect();
paths.sort();
assert_eq!(paths, expected, "scripts listed for `{query}`");
}
Ok(())
}
@@ -204,6 +204,7 @@ async fn test_alert_job_queue_waiting_in_global_settings(db: Pool<Postgres>) ->
async fn read_secret_surfaces(
base: &str,
names: &[&str],
reveal: bool,
) -> anyhow::Result<Vec<(String, u16, String)>> {
let mut paths = vec![
"instance_config".to_string(),
@@ -214,9 +215,13 @@ async fn read_secret_surfaces(
paths.extend(names.iter().map(|n| format!("global/{n}")));
let mut out = vec![];
for path in paths {
let resp = authed(client().get(format!("{base}/{path}")))
.send()
.await?;
let resp = authed(
client()
.get(format!("{base}/{path}"))
.query(&[("dangerously_reveal_secrets", reveal)]),
)
.send()
.await?;
let status = resp.status().as_u16();
out.push((path, status, resp.text().await?));
}
@@ -252,9 +257,17 @@ async fn test_server_secrets_follow_export_flag(db: Pool<Postgres>) -> anyhow::R
let server = ApiServer::start(db.clone()).await?;
let base = format!("http://localhost:{}/api/settings", server.addr.port());
// Default: a full export, so `get-config` and `pull` can migrate an instance.
std::env::remove_var("EXPORT_SERVER_SECRETS");
for (path, status, body) in read_secret_surfaces(&base, &names).await? {
// A read that does not ask for secrets gets them redacted.
for (path, status, body) in read_secret_surfaces(&base, &names, false).await? {
assert_2xx(status, &body, &path);
assert!(
!body.contains("planted-"),
"{path} returned a secret without dangerously_reveal_secrets: {body}"
);
}
// Asked for, a full export, so `get-config` and `pull` can migrate an instance.
for (path, status, body) in read_secret_surfaces(&base, &names, true).await? {
assert_2xx(status, &body, &path);
assert!(
body.contains("planted-"),
@@ -263,7 +276,7 @@ async fn test_server_secrets_follow_export_flag(db: Pool<Postgres>) -> anyhow::R
}
std::env::set_var("EXPORT_SERVER_SECRETS", "0");
let withheld = read_secret_surfaces(&base, &names).await;
let withheld = read_secret_surfaces(&base, &names, true).await;
std::env::remove_var("EXPORT_SERVER_SECRETS");
for (path, status, body) in withheld? {
if path.starts_with("global/") {
+27 -2
View File
@@ -17,8 +17,8 @@ use sql_builder::{prelude::Bind, SqlBuilder};
use sqlx::{Postgres, Transaction};
use std::str::FromStr;
use windmill_api_auth::{
build_scope_path_predicate, check_scopes, composed::check_new_hub_paths, maybe_refresh_folders,
require_super_admin, ApiAuthed,
build_scope_path_predicate, check_run_scopes, check_scopes, composed::check_new_hub_paths,
maybe_refresh_folders, require_super_admin, ApiAuthed,
};
use windmill_audit::audit_oss::audit_log;
use windmill_audit::ActionKind;
@@ -274,6 +274,10 @@ async fn validate_dynamic_skip<'c>(
}
}
fn dynamic_skip_runnable(path: Option<&str>) -> Option<RunnableRef> {
RunnableRef::from_path(path?, false).ok()
}
/// A handler that does not parse is left out: it never runs, as a fire parses it the same way.
fn handler_runnables(handlers: [Option<&str>; 3]) -> Vec<RunnableRef> {
handlers
@@ -381,6 +385,12 @@ async fn create_schedule(
]);
new_runnables.extend(target);
check_new_hub_paths(&new_runnables, &[], &authed, &db, &w_id).await?;
check_run_scopes(
&authed,
new_runnables
.iter()
.chain(&dynamic_skip_runnable(ns.dynamic_skip.as_deref())),
)?;
let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?;
@@ -646,6 +656,21 @@ async fn edit_schedule(
&w_id,
)
.await?;
// The edit sets the stored target's args, so its run scope is checked as on create.
let target = before.as_ref().and_then(|b| {
RunnableRef::from_path(
b.get("script_path")?.as_str()?,
b.get("is_flow")?.as_bool()?,
)
.ok()
});
check_run_scopes(
&authed,
new_handlers
.iter()
.chain(&target)
.chain(&dynamic_skip_runnable(es.dynamic_skip.as_deref())),
)?;
let schedule = sqlx::query_as!(
Schedule,
+9 -8
View File
@@ -194,7 +194,7 @@ async fn list_scripts(
Query(pagination): Query<Pagination>,
Query(lq): Query<ListScriptQuery>,
) -> JsonResult<Vec<ListableScript>> {
// A role that cannot write code lists only what it can run: no libraries, no drafts.
// A role that cannot write code lists only what it can run or compose: no libraries, no drafts.
let cannot_code = !windmill_common::roles::caller_capabilities(&db, &w_id, &authed)
.await?
.code;
@@ -259,16 +259,19 @@ async fn list_scripts(
.limit(per_page)
.clone();
let lowercased_kinds: Option<Vec<String>> = lq
let mut lowercased_kinds: Option<Vec<String>> = lq
.kinds
.map(|x| x.split(",").map(&str::to_lowercase).collect());
if (!lq.include_without_main.unwrap_or(false)
if cannot_code {
lowercased_kinds.get_or_insert_with(|| vec!["script".to_string()]);
// A preprocessor has no main, so it is a 'lib' that a composed flow can still use.
sqlb.and_where("(o.auto_kind IS NULL OR o.auto_kind <> 'lib' OR o.kind = 'preprocessor')");
} else if !lq.include_without_main.unwrap_or(false)
&& lowercased_kinds
.as_ref()
.map(|x| !x.contains(&"preprocessor".to_string()))
.unwrap_or(true))
|| cannot_code
.unwrap_or(true)
{
// only include scripts that have a runnable entrypoint. Use a
// deny-list: anything that isn't a 'lib' (library script without
@@ -325,9 +328,7 @@ async fn list_scripts(
);
}
}
if cannot_code {
sqlb.and_where_eq("kind", quote("script"));
} else if let Some(lowercased_kinds) = lowercased_kinds {
if let Some(lowercased_kinds) = lowercased_kinds {
let safe_kinds = lowercased_kinds
.into_iter()
.map(sql_builder::quote)
@@ -344,7 +344,8 @@ async fn run_backfill(
row_to_json(r)::text AS "line!"
FROM (
SELECT workspace_id, id, timestamp, username, operation,
action_kind::text AS action_kind, resource, parameters, email, span
action_kind::text AS action_kind, resource, parameters, email, span,
client_ip, user_agent
FROM audit_partitioned
WHERE timestamp >= $1 AND timestamp < $2
AND (timestamp, id) > ($3, $4)
+42 -5
View File
@@ -878,8 +878,18 @@ async fn audit_instance_action(
pub async fn set_global_setting_internal(
db: &DB,
key: String,
value: serde_json::Value,
mut value: serde_json::Value,
) -> error::Result<()> {
if instance_config::contains_redacted_secret(&value) {
let current = sqlx::query_scalar::<_, serde_json::Value>(
"SELECT value FROM global_settings WHERE name = $1",
)
.bind(&key)
.fetch_optional(db)
.await?;
instance_config::restore_redacted_secrets(&key, &mut value, current.as_ref())
.map_err(error::Error::BadRequest)?;
}
let should_bump_instance_ai_revision = key == AI_CONFIG_SETTING;
let value = if key == "retention_period_secs" {
instance_config::clamp_retention_period(value)
@@ -1348,12 +1358,22 @@ async fn run_setting_pre_write_hook(
// Bulk instance config endpoints
// ---------------------------------------------------------------------------
/// Secrets are redacted on every settings read unless asked for by name, so that a superadmin
/// token used to inspect the configuration (by a script, a CLI run or an AI assistant) does not
/// copy every instance credential into its output.
#[derive(Deserialize)]
pub struct RevealSecrets {
#[serde(default)]
pub dangerously_reveal_secrets: bool,
}
async fn get_instance_config(
Extension(db): Extension<DB>,
authed: ApiAuthed,
Query(reveal): Query<RevealSecrets>,
) -> JsonResult<InstanceConfig> {
require_super_admin(&db, &authed).await?;
let config = InstanceConfig::from_db_for_api(&db)
let config = InstanceConfig::from_db_for_api(&db, reveal.dangerously_reveal_secrets)
.await
.map_err(|e| error::Error::internal_err(e.to_string()))?;
Ok(Json(config))
@@ -1362,9 +1382,10 @@ async fn get_instance_config(
async fn get_instance_config_yaml(
Extension(db): Extension<DB>,
authed: ApiAuthed,
Query(reveal): Query<RevealSecrets>,
) -> error::Result<Response> {
require_super_admin(&db, &authed).await?;
let config = InstanceConfig::from_db_for_api(&db)
let config = InstanceConfig::from_db_for_api(&db, reveal.dangerously_reveal_secrets)
.await
.map_err(|e| error::Error::internal_err(e.to_string()))?;
let yaml = config
@@ -1387,9 +1408,13 @@ async fn set_instance_config(
.await
.map_err(|e| error::Error::internal_err(e.to_string()))?;
let desired_map = desired.global_settings.to_settings_map();
let mut desired_map = desired.global_settings.to_settings_map();
if !desired_map.is_empty() {
let current_map = current.global_settings.to_settings_map();
for (key, value) in desired_map.iter_mut() {
instance_config::restore_redacted_secrets(key, value, current_map.get(key))
.map_err(error::Error::BadRequest)?;
}
let mut settings_diff =
instance_config::diff_global_settings(&current_map, &desired_map, ApplyMode::Merge);
let ai_config_changed = settings_diff
@@ -1495,6 +1520,7 @@ pub async fn get_global_setting(
Extension(db): Extension<DB>,
authed: ApiAuthed,
Path(key): Path<String>,
Query(reveal): Query<RevealSecrets>,
) -> JsonResult<serde_json::Value> {
if !key.starts_with("default_error_handler_")
&& !key.starts_with("default_recovery_handler_")
@@ -1539,7 +1565,11 @@ pub async fn get_global_setting(
.await?
.map(|x| x.value);
Ok(Json(value.unwrap_or_else(|| serde_json::Value::Null)))
let mut value = value.unwrap_or(serde_json::Value::Null);
if !reveal.dangerously_reveal_secrets {
instance_config::redact_setting_secrets(&key, &mut value);
}
Ok(Json(value))
}
#[cfg(feature = "enterprise")]
@@ -1572,6 +1602,7 @@ async fn github_app_stale_webhooks(
async fn list_global_settings(
Extension(db): Extension<DB>,
authed: ApiAuthed,
Query(reveal): Query<RevealSecrets>,
) -> JsonResult<Vec<GlobalSetting>> {
require_super_admin(&db, &authed).await?;
let settings = sqlx::query_as!(GlobalSetting, "SELECT name, value FROM global_settings")
@@ -1579,6 +1610,12 @@ async fn list_global_settings(
.await?
.into_iter()
.filter(|s| !instance_config::is_withheld_server_secret(&s.name))
.map(|mut s| {
if !reveal.dangerously_reveal_secrets {
instance_config::redact_setting_secrets(&s.name, &mut s.value);
}
s
})
.collect();
Ok(Json(settings))
+17 -4
View File
@@ -14,6 +14,7 @@ use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::sync::LazyLock;
use std::time::Duration;
use windmill_common::client_ip::ClientIp;
use windmill_api_auth::ApiAuthed;
@@ -1278,6 +1279,14 @@ async fn join_workspace<'c>(
)));
}
windmill_common::workspaces::check_new_member_sso(
&mut *tx,
&w_id,
&authed.email,
Some(&username),
)
.await?;
sqlx::query!(
"INSERT INTO usr
(workspace_id, email, username, is_admin, operator)
@@ -2846,6 +2855,10 @@ async fn set_login_type(
.execute(&mut *tx)
.await?;
if et.login_type == "password" {
windmill_common::workspaces::check_password_login_allowed(&mut *tx, &email).await?;
}
audit_log(
&mut *tx,
&authed,
@@ -2866,7 +2879,7 @@ async fn set_login_type(
#[allow(unreachable_code, unused_variables)]
async fn login(
headers: axum::http::HeaderMap,
ClientIp(client_ip): ClientIp,
cookies: Cookies,
Extension(db): Extension<DB>,
Extension(argon2): Extension<Arc<Argon2<'_>>>,
@@ -2889,7 +2902,7 @@ async fn login(
));
}
windmill_common::login_rate_limit::check_and_increment_login_attempt(&headers, &email)?;
windmill_common::login_rate_limit::check_and_increment_login_attempt(client_ip, &email)?;
let mut tx = db.begin().await?;
let audit_author = AuditAuthor {
@@ -3861,7 +3874,7 @@ struct LoginLinkQuery {
}
async fn consume_login_link(
headers: axum::http::HeaderMap,
ClientIp(client_ip): ClientIp,
cookies: Cookies,
Extension(db): Extension<DB>,
Path(token): Path<String>,
@@ -3879,7 +3892,7 @@ async fn consume_login_link(
// The account is unknown until the row is read, so only the global and per-IP tiers
// apply here; a 32-char random token leaves nothing for the per-account tier to guard.
windmill_common::login_rate_limit::check_and_increment_login_attempt(
&headers,
client_ip,
&t_hash[..TOKEN_PREFIX_LEN],
)?;
@@ -239,6 +239,7 @@ pub fn workspaced_service() -> Router {
"/protection_rules/{rule_name}",
post(update_protection_rule).delete(delete_protection_rule),
)
.route("/password_login_members", get(list_password_login_members))
.route("/log_feature_usage", post(log_feature_usage))
.route("/cloud_quotas", get(get_cloud_quotas))
.route("/prune_versions", post(prune_versions))
@@ -12055,6 +12056,8 @@ async fn invite_user(
)));
}
windmill_common::workspaces::check_new_member_sso(&mut *tx, &w_id, &nu.email, None).await?;
sqlx::query!(
"INSERT INTO workspace_invite
(workspace_id, email, is_admin, operator, workspace_role)
@@ -12266,6 +12269,9 @@ async fn add_user(
username
};
windmill_common::workspaces::check_new_member_sso(&mut *tx, &w_id, &nu.email, Some(&username))
.await?;
sqlx::query!(
"INSERT INTO usr
(workspace_id, email, username, is_admin, operator, workspace_role)
@@ -12852,6 +12858,38 @@ async fn list_protection_rules(
))
}
#[derive(Serialize)]
struct PasswordLoginMember {
username: String,
email: String,
groups: Vec<String>,
}
/// Members other than service accounts whose account signs in with a password, with their groups
/// so the caller can leave out a rule's bypassers. A `RequireSso` rule does not remove them.
async fn list_password_login_members(
authed: ApiAuthed,
Extension(db): Extension<DB>,
Path(w_id): Path<String>,
) -> JsonResult<Vec<PasswordLoginMember>> {
require_admin(authed.is_admin, &authed.username)?;
let members = sqlx::query_as!(
PasswordLoginMember,
r#"SELECT u.username, u.email,
COALESCE(array_agg(g.group_) FILTER (WHERE g.group_ IS NOT NULL), '{}') AS "groups!"
FROM usr u
JOIN password p ON p.email = u.email AND p.login_type = 'password'
LEFT JOIN usr_to_group g ON g.workspace_id = u.workspace_id AND g.usr = u.username
WHERE u.workspace_id = $1 AND NOT u.is_service_account
GROUP BY u.username, u.email
ORDER BY u.username"#,
&w_id,
)
.fetch_all(&db)
.await?;
Ok(Json(members))
}
/// Insert or replace a protection ruleset within an existing transaction. Unlike the
/// `create_protection_rule` handler (which rejects an existing name), this upserts, so it is safe to
/// call programmatically when designating a dev/prod pair. Callers MUST invalidate the
+277 -5
View File
@@ -1,7 +1,7 @@
openapi: "3.0.3"
info:
version: 1.884.1
version: 1.885.0
title: Windmill API
contact:
@@ -1903,6 +1903,7 @@ paths:
- setting
parameters:
- $ref: "#/components/parameters/Key"
- $ref: "#/components/parameters/DangerouslyRevealSecrets"
responses:
"200":
description: status
@@ -2717,6 +2718,8 @@ paths:
operationId: listGlobalSettings
tags:
- setting
parameters:
- $ref: "#/components/parameters/DangerouslyRevealSecrets"
responses:
"200":
description: list of settings
@@ -2760,6 +2763,8 @@ paths:
operationId: getInstanceConfig
tags:
- setting
parameters:
- $ref: "#/components/parameters/DangerouslyRevealSecrets"
responses:
"200":
description: full instance configuration
@@ -8312,6 +8317,37 @@ paths:
"400":
description: rule with this name already exists
/w/{workspace}/workspaces/password_login_members:
get:
summary: list the members other than service accounts that sign in with a password
operationId: listPasswordLoginMembers
tags:
- workspace
parameters:
- $ref: "#/components/parameters/WorkspaceId"
responses:
"200":
description: members signing in with a password, with their groups
content:
application/json:
schema:
type: array
items:
type: object
required:
- username
- email
- groups
properties:
username:
type: string
email:
type: string
groups:
type: array
items:
type: string
/w/{workspace}/workspaces/protection_rules/{rule_name}:
post:
summary: update an existing protection rule
@@ -13174,6 +13210,94 @@ paths:
application/json:
schema: {}
/w/{workspace}/jobs/flow/nested_approvals/{job_id}:
get:
summary: list the approvals given in runs nested under a flow run
description: >
List the approval steps that runs nested under a flow run (subflows, branch and
loop runs, at any depth) went past, with who approved or rejected each and when.
The flow run's own approval steps are not listed: they are in its flow status.
Only the runs started by a step that can hold an approval step are read: a
subflow, or a loop or branch whose steps hold one.
operationId: listNestedApprovals
tags:
- job
parameters:
- $ref: "#/components/parameters/WorkspaceId"
- name: job_id
in: path
required: true
description: id of the flow run
schema:
type: string
format: uuid
responses:
"200":
description: the nested approval steps, oldest first
content:
application/json:
schema:
type: object
required:
- approvals
- more
properties:
approvals:
type: array
items:
type: object
required:
- job_id
- subflows
- step_id
- required_events
- approvers
properties:
job_id:
type: string
format: uuid
description: the nested run the step belongs to
subflows:
type: array
items:
type: string
description: >
ids of the subflow steps leading to the nested run, outermost
first. Step ids are unique across a flow, loop and branch steps
included, so the first one (or the step itself) is a step of
the flow run's own graph
step_id:
type: string
step_summary:
type: string
required_events:
type: integer
description: >
approvals the step required; fewer approvers means it timed out
and the flow continued
approvers:
type: array
items:
type: object
required:
- resume_id
- approver
properties:
resume_id:
type: integer
approver:
type: string
approved_at:
type: string
format: date-time
approved:
type: boolean
more:
type: boolean
description: >
more nested runs than are read, typically a loop with an approval in
every iteration: their approvals are on those runs' own pages
/w/{workspace}/jobs/flow/approval_step_detail/{job_id}/{step_id}:
get:
summary: get the approval detail of one step of a flow run
@@ -13284,8 +13408,9 @@ paths:
approvals:
type: array
description: >
approvals received. approved, value and created_at are known only
while the run is live; a finished run keeps approver names alone.
approvals received. approved and value are known only while the run is
live; a finished run keeps approver names and, for approvals recorded
since it was kept, created_at.
items:
type: object
required:
@@ -13305,6 +13430,65 @@ paths:
error:
description: the run's error, when status is not_resumed
/w/{workspace}/jobs/approvals/waiting:
get:
summary: list the runs waiting for an approval the caller can give
description: >
Runs suspended on an approval step the caller can approve, by the same check the
approval itself runs, newest first, excluding steps the caller already approved. A
step that does not require login is listed only to callers who can read its run.
operationId: listWaitingApprovals
tags:
- job
parameters:
- $ref: "#/components/parameters/WorkspaceId"
responses:
"200":
description: runs waiting for the caller's approval
content:
application/json:
schema:
type: object
required: [approvals, total]
properties:
approvals:
type: array
description: the most recent of the listed runs, at most 100
items:
type: object
required:
- job_id
- started_by
- created_at
- approvals
- required_approvals
properties:
job_id:
type: string
format: uuid
description: >
the suspended flow run, the one its approval page takes: the root
run, or the branch, loop or subflow run holding the approval step
flow_path:
type: string
flow_summary:
type: string
step_summary:
type: string
started_by:
type: string
created_at:
type: string
format: date-time
approvals:
type: integer
description: approvals received so far
required_approvals:
type: integer
total:
type: integer
description: how many runs are listed in all
/w/{workspace}/jobs/job_view_token/{id}:
get:
summary: mint a read-only share token for a job
@@ -20297,6 +20481,9 @@ paths:
flow_summary:
type: string
description: summary of the flow or workflow the approval belongs to
required_events:
type: integer
description: approvals the step requires; absent for a workflow as code
approvers:
type: array
items:
@@ -20309,6 +20496,11 @@ paths:
type: integer
approver:
type: string
approved_at:
type: string
format: date-time
approved:
type: boolean
view_token:
type: string
description: >-
@@ -20563,6 +20755,11 @@ paths:
type: integer
approver:
type: string
approved_at:
type: string
format: date-time
approved:
type: boolean
required:
- resume_id
- approver
@@ -27816,6 +28013,38 @@ paths:
application/json:
schema:
type: string
/concurrency_groups/{id}/key_status:
get:
summary: Get a job's concurrency key and whether its limit held it back
description: Requires read access to the job, the same as reading the run itself. Returns null when the job has no concurrency key.
operationId: getConcurrencyKeyStatus
tags:
- concurrencyGroups
parameters:
- $ref: "#/components/parameters/JobId"
responses:
"200":
description: concurrency key and deferral of the given job
content:
application/json:
schema:
type: object
nullable: true
properties:
key:
type: string
deferred_from:
type: string
format: date-time
nullable: true
description: When the job was first due. Set the first time its concurrency limit held it back, and kept after it ran.
released_at:
type: string
format: date-time
nullable: true
description: When the concurrency limit let in a job it had held back, as the time the job was last due. The rest until it started is queue time.
required:
- key
/w/{workspace}/concurrency_groups/list_jobs:
get:
summary: Get intervals of job runtime concurrency
@@ -29718,6 +29947,15 @@ components:
required: true
schema:
type: string
DangerouslyRevealSecrets:
name: dangerously_reveal_secrets
description: >
Return stored secrets in clear. Without it, every secret is replaced by a
placeholder, which a write sending it back unchanged keeps as the stored value.
in: query
required: false
schema:
type: boolean
WorkspaceId:
name: workspace
in: path
@@ -33709,9 +33947,34 @@ components:
items:
type: string
description: "List of path conflicts that block the offboarding. Empty on success."
conflict_items:
type: array
items:
$ref: "#/components/schemas/OffboardPathConflict"
description: "The same conflicts as `conflicts`, structured. Empty on success."
summary:
$ref: "#/components/schemas/OffboardSummary"
OffboardPathConflict:
type: object
properties:
workspace_id:
type: string
kind:
type: string
description: "Item kind, as its table name (script, flow, app, resource, variable, schedule, eval_dataset, http_trigger, ...)"
source_path:
type: string
description: "The offboarded user's item, under u/{username}/"
target_path:
type: string
description: "The existing item at the reassignment target"
required:
- workspace_id
- kind
- source_path
- target_path
OffboardSummary:
type: object
properties:
@@ -34256,6 +34519,12 @@ components:
type: object
span:
type: string
client_ip:
type: string
description: Address of the client that made the request. Forwarding headers are believed only from the proxies listed in the TRUSTED_PROXIES environment variable (loopback by default, plus the private ranges on Windmill Cloud), so behind a reverse proxy this is the proxy's address until it is listed. Absent on entries no request stands behind.
user_agent:
type: string
description: User-Agent header of the request.
required:
- workspace_id
- id
@@ -34443,9 +34712,11 @@ components:
- has_preprocessor
RecentRunStatus:
description: a failure someone or something marked as handled is `resolved`, not `failure`
description: >
a failure someone or something marked as handled is `resolved`, not `failure`; a run
waiting for an approval is `suspended`, not `running`
type: string
enum: [success, failure, resolved, canceled, running]
enum: [success, failure, resolved, canceled, running, suspended]
RecentRunHiddenItem:
type: object
@@ -41465,6 +41736,7 @@ components:
- RestrictPublicRunSharing
- RestrictGuestAppDeployment
- RequireIsolatedForks
- RequireSso
RuleBypasserGroups:
type: array
description: Groups that can bypass this ruleset
File diff suppressed because one or more lines are too long
+1
View File
@@ -578,6 +578,7 @@ async fn set_config(
let config = serde_json::to_value(&nc.trigger_config)?;
let new = windmill_trigger_websocket::WebsocketTrigger::config_runnables(&config);
check_new_hub_paths(&new, &[], &authed, &db, &w_id).await?;
windmill_api_auth::check_run_scopes(&authed, &new)?;
}
let mut tx = user_db.begin(&authed).await?;
+75 -29
View File
@@ -1,6 +1,8 @@
use std::sync::Arc;
use axum::{extract::Path, routing::get, Extension, Json, Router};
use chrono::{DateTime, Utc};
use serde::Serialize;
use uuid::Uuid;
use windmill_common::{
db::UserDB,
@@ -18,6 +20,7 @@ use crate::{
pub fn global_service() -> Router {
windmill_api_jobs::concurrency_groups::global_service()
.route("/{job_id}/key", get(get_concurrency_key))
.route("/{job_id}/key_status", get(get_concurrency_key_status))
}
/// A concurrency key embeds the job's workspace, its runnable path and any
@@ -31,6 +34,44 @@ pub fn global_service() -> Router {
/// job's own workspace before evaluating access — that also rejects non-members, for whom
/// the job does not exist. Members reaching [`require_job_read_access`] get its 403, which
/// discloses existence only inside a workspace they belong to.
async fn require_concurrency_key_read(
token: &str,
cache: &AuthCache,
db: &DB,
user_db: &UserDB,
view_token: Option<&str>,
job_id: Uuid,
) -> Result<(), Error> {
let not_found = || Error::NotFound(format!("Job {job_id} not found"));
// A caller who cannot reach the job must not be able to tell it apart from a job
// that does not exist, so both answer with the same 404.
let job = sqlx::query!(
"SELECT workspace_id, created_by FROM v2_job WHERE id = $1",
job_id
)
.fetch_optional(db)
.await?
.ok_or_else(not_found)?;
let authed_in_workspace = cache
.get_authed(Some(job.workspace_id.clone()), token)
.await
.ok_or_else(not_found)?;
windmill_api_auth::check_job_token_scope(&authed_in_workspace, || "jobs:read".to_string())?;
require_job_read_access(
db,
user_db,
&authed_in_workspace,
&job.workspace_id,
&job_id,
&job.created_by,
view_token,
)
.await
}
async fn get_concurrency_key(
_authed: ApiAuthed,
Tokened { token }: Tokened,
@@ -40,37 +81,42 @@ async fn get_concurrency_key(
OptViewToken(view_token): OptViewToken,
Path(job_id): Path<Uuid>,
) -> JsonResult<Option<String>> {
let not_found = || Error::NotFound(format!("Job {job_id} not found"));
// A caller who cannot reach the job must not be able to tell it apart from a job
// that does not exist, so both answer with the same 404.
let job = sqlx::query!(
"SELECT workspace_id, created_by FROM v2_job WHERE id = $1",
job_id
)
.fetch_optional(&db)
.await?
.ok_or_else(not_found)?;
let authed_in_workspace = cache
.get_authed(Some(job.workspace_id.clone()), &token)
.await
.ok_or_else(not_found)?;
windmill_api_auth::check_job_token_scope(&authed_in_workspace, || "jobs:read".to_string())?;
require_job_read_access(
&db,
&user_db,
&authed_in_workspace,
&job.workspace_id,
&job_id,
&job.created_by,
view_token.as_deref(),
)
.await?;
require_concurrency_key_read(&token, &cache, &db, &user_db, view_token.as_deref(), job_id)
.await?;
let key = sqlx::query_scalar!("SELECT key FROM concurrency_key WHERE job_id = $1", job_id)
.fetch_optional(&db)
.await?;
Ok(Json(key))
}
#[derive(Serialize)]
struct ConcurrencyKeyStatus {
key: String,
/// When the job was first due. Set the first time its limit held it back, and kept
/// after it ran.
deferred_from: Option<DateTime<Utc>>,
/// When the limit let the job in: the time it was last due. The rest until it started
/// is queue time.
released_at: Option<DateTime<Utc>>,
}
async fn get_concurrency_key_status(
_authed: ApiAuthed,
Tokened { token }: Tokened,
Extension(cache): Extension<Arc<AuthCache>>,
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
OptViewToken(view_token): OptViewToken,
Path(job_id): Path<Uuid>,
) -> JsonResult<Option<ConcurrencyKeyStatus>> {
require_concurrency_key_read(&token, &cache, &db, &user_db, view_token.as_deref(), job_id)
.await?;
let status = sqlx::query_as!(
ConcurrencyKeyStatus,
"SELECT key, original_scheduled_for AS deferred_from, released_at FROM concurrency_key WHERE job_id = $1",
job_id
)
.fetch_optional(&db)
.await?;
Ok(Json(status))
}
+489 -22
View File
@@ -409,6 +409,11 @@ pub fn workspaced_service() -> Router {
"/flow/approval_step_detail/{job_id}/{step_id}",
get(get_approval_step_detail),
)
.route(
"/flow/nested_approvals/{job_id}",
get(list_nested_approvals),
)
.route("/approvals/waiting", get(list_waiting_approvals))
.route(
"/job_view_token/{id}",
get(get_job_view_token).layer(cors.clone()),
@@ -5348,6 +5353,8 @@ struct ApprovalInfo {
step_summary: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
flow_summary: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
required_events: Option<u32>,
approvers: Vec<Approval>,
/// Share-read-link token for the flow, minted only for callers allowed to view this
/// approval. Lets an authenticated workspace-member approver open the run details of
@@ -5441,6 +5448,10 @@ fn approval_conditions_from_settings(suspend: &Suspend) -> Option<ApprovalCondit
struct ApprovalStepView {
skin: ApprovalSkin,
summary: Option<String>,
required_events: Option<u32>,
/// The approval step's job: approvals sent to it count for this step, with those sent to
/// the flow itself. Rows for the flow's earlier steps stay until the run finishes.
job: Option<Uuid>,
}
async fn get_approval_info(
@@ -5529,7 +5540,8 @@ async fn get_approval_info(
.and_then(|m| m.get("skin"))
.and_then(|v| serde_json::from_value::<ApprovalSkin>(v.clone()).ok())
.unwrap_or_default();
let step = Some(ApprovalStepView { skin, summary: None });
let step =
Some(ApprovalStepView { skin, summary: None, required_events: None, job: None });
(form, description, default_args, enums, run_ac, None, step)
} else {
let fs = row
@@ -5609,6 +5621,10 @@ async fn get_approval_info(
.and_then(|module| module.suspend.as_ref())
.and_then(approval_conditions_from_settings)
});
let step_job_id = fs
.as_ref()
.and_then(|s| approval_step.and_then(|step| s.modules.get(step)))
.and_then(|m| m.job());
let step = approval_module.map(|module| ApprovalStepView {
skin: module
.suspend
@@ -5616,13 +5632,11 @@ async fn get_approval_info(
.and_then(|s| s.skin)
.unwrap_or_default(),
summary: module.summary.clone().filter(|s| !s.trim().is_empty()),
required_events: module.suspend.as_ref().and_then(|s| s.required_events),
job: step_job_id,
});
// Fetch description, default_args, and enums from the step's completed job result
let step_job_id = fs
.as_ref()
.and_then(|s| approval_step.and_then(|step| s.modules.get(step)))
.and_then(|m| m.job());
let (desc, default_args, enums) = if let Some(sjid) = step_job_id {
let result: Option<serde_json::Value> = sqlx::query_scalar(
"SELECT result FROM v2_job_completed WHERE id = $1 AND workspace_id = $2",
@@ -5644,6 +5658,8 @@ async fn get_approval_info(
};
let skin = step.as_ref().map(|s| s.skin).unwrap_or_default();
let required_events = step.as_ref().and_then(|s| s.required_events);
let step_job = step.as_ref().and_then(|s| s.job);
let step_summary = step.and_then(|s| s.summary);
let user_auth_required = approval_conditions
@@ -5678,22 +5694,27 @@ async fn get_approval_info(
skin,
step_summary: None,
flow_summary: None,
required_events: None,
approvers: vec![],
view_token: None,
}));
}
// Get existing approvers
let approvers: Vec<Approval> = sqlx::query_as::<_, (i32, Option<String>)>(
"SELECT resume_id, approver FROM resume_job WHERE flow = $1",
let approvers: Vec<Approval> = sqlx::query!(
"SELECT resume_id, approver, created_at, approved FROM resume_job
WHERE flow = $1 AND ($2::uuid IS NULL OR job IN ($1, $2))",
job_id,
step_job
)
.bind(&job_id)
.fetch_all(&db)
.await?
.into_iter()
.map(|(rid, approver)| Approval {
resume_id: rid as u16,
approver: approver.unwrap_or_else(|| "anonymous".to_string()),
.map(|r| Approval {
resume_id: r.resume_id as u16,
approver: r.approver.unwrap_or_else(|| "anonymous".to_string()),
approved_at: Some(r.created_at),
approved: Some(r.approved),
})
.collect();
@@ -5725,6 +5746,7 @@ async fn get_approval_info(
skin,
step_summary,
flow_summary: row.flow_summary,
required_events,
approvers,
view_token,
}))
@@ -5744,11 +5766,377 @@ enum ApprovalStepStatus {
NotResumed,
}
#[derive(Serialize)]
struct WaitingApproval {
/// The suspended flow, the one its approval page takes: the root run, or the branch, loop or
/// subflow run holding the step.
job_id: Uuid,
#[serde(skip_serializing_if = "Option::is_none")]
flow_path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
flow_summary: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
step_summary: Option<String>,
started_by: String,
created_at: chrono::DateTime<chrono::Utc>,
approvals: i64,
required_approvals: i64,
}
#[derive(Serialize)]
struct WaitingApprovals {
approvals: Vec<WaitingApproval>,
/// Every listed run, of which `approvals` holds the most recent.
total: usize,
}
// ponytail: scans the most recent suspended runs only; a workspace past this many waiting
// approvals needs the approver check in SQL rather than in `can_approve_step`.
const WAITING_APPROVALS_SCAN: i64 = 1000;
const WAITING_APPROVALS_RETURNED: usize = 100;
#[derive(Serialize)]
struct NestedApproval {
job_id: Uuid,
subflows: Vec<String>,
step_id: String,
step_summary: Option<String>,
/// Fewer approvers than this on a step that went past: it timed out and continued.
required_events: u64,
approvers: Vec<Approval>,
}
#[derive(Serialize)]
struct NestedApprovals {
approvals: Vec<NestedApproval>,
more: bool,
}
/// Whether a step can start a run holding an approval step: a subflow, whose steps its caller
/// does not carry, or a loop or branch whose own steps hold one.
fn may_hold_approval(step: &serde_json::Value) -> bool {
let holds = |modules: &serde_json::Value| {
modules
.as_array()
.into_iter()
.flatten()
.any(|m| m.get("suspend").is_some_and(|s| !s.is_null()) || may_hold_approval(m))
};
let branches = |v: &serde_json::Value| {
v["branches"]
.as_array()
.into_iter()
.flatten()
.any(|b| holds(&b["modules"]))
};
let v = &step["value"];
match v["type"].as_str() {
Some("flow") => true,
Some("forloopflow" | "whileloopflow") => holds(&v["modules"]),
Some("branchone") => holds(&v["default"]) || branches(v),
Some("branchall") => branches(v),
_ => false,
}
}
/// The ids of the steps under `modules`, at any depth, that may hold an approval. Read from a
/// flow's full definition: a loop or branch run's own (`flow_node`) keeps nested loop and branch
/// bodies as `modules_node` references, so its inline steps are not all of them. Step ids are
/// unique across a flow, so its loop and branch runs look their steps up here.
fn approval_holders(modules: &[serde_json::Value], out: &mut HashSet<String>) {
for m in modules {
if may_hold_approval(m) {
if let Some(id) = m["id"].as_str() {
out.insert(id.to_string());
}
}
let v = &m["value"];
let nested = std::iter::once(&v["modules"])
.chain(std::iter::once(&v["default"]))
.chain(v["branches"].as_array().into_iter().flatten().map(|b| &b["modules"]));
for body in nested {
approval_holders(body.as_array().map(Vec::as_slice).unwrap_or_default(), out);
}
}
}
// ponytail: a loop whose steps hold an approval has one per iteration; past this many nested
// runs read, the rest stay on their own runs' pages.
const NESTED_RUNS_READ: usize = 200;
/// The approval steps that runs nested under a flow run (subflows, branch and loop runs, at any
/// depth) went past. Who approved them is kept on those runs, not on the flow run. Only the
/// runs started by a step that can hold an approval step are read, one level at a time.
async fn list_nested_approvals(
OptViewToken(view_token): OptViewToken,
authed: ApiAuthed,
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
Path((w_id, flow_id)): Path<(String, Uuid)>,
) -> error::Result<Json<NestedApprovals>> {
let created_by = sqlx::query_scalar!(
"SELECT created_by FROM v2_job WHERE id = $1 AND workspace_id = $2",
flow_id,
w_id
)
.fetch_optional(&db)
.await?
.ok_or_else(|| Error::NotFound(format!("Job {flow_id} not found")))?;
require_job_read_access(
&db,
&user_db,
&authed,
&w_id,
&flow_id,
&created_by,
view_token.as_deref(),
)
.await?;
let modules = |v: &Option<serde_json::Value>| -> Vec<serde_json::Value> {
v.as_ref()
.and_then(|v| v.get("modules"))
.and_then(|m| m.as_array())
.cloned()
.unwrap_or_default()
};
let scope_tags = get_scope_tags(&authed);
// Each run to read, with the subflow steps leading to it (none for the flow run itself) and,
// for a loop or branch run, the steps of its flow that may hold an approval.
type Holders = std::sync::Arc<HashSet<String>>;
let mut level: HashMap<Uuid, (Option<Vec<String>>, Option<Holders>)> =
HashMap::from([(flow_id, (None, None))]);
let mut seen: HashSet<Uuid> = HashSet::from([flow_id]);
let mut approvals = vec![];
let mut more = false;
while !level.is_empty() {
let ids: Vec<Uuid> = level.keys().copied().collect();
let rows = sqlx::query!(
r#"SELECT j.id, j.tag, j.kind = 'flownode' AS "is_node!",
COALESCE(s.flow_status, c.flow_status) AS flow_status,
COALESCE(j.raw_flow, fv.value, fn.flow) AS flow
FROM v2_job j
LEFT JOIN v2_job_status s ON s.id = j.id
LEFT JOIN v2_job_completed c ON c.id = j.id
LEFT JOIN flow_version fv
ON j.raw_flow IS NULL AND j.kind = 'flow' AND fv.id = j.runnable_id
LEFT JOIN flow_node fn
ON j.raw_flow IS NULL AND j.kind = 'flownode' AND fn.id = j.runnable_id
WHERE j.id = ANY($1) AND j.workspace_id = $2"#,
&ids,
w_id
)
.fetch_all(&db)
.await?;
let mut next = HashMap::new();
for r in rows {
let (at, inherited) = level.get(&r.id).cloned().unwrap_or_default();
let defs = modules(&r.flow);
let holders = match inherited {
Some(h) if r.is_node => h,
_ => {
let mut h = HashSet::new();
approval_holders(&defs, &mut h);
std::sync::Arc::new(h)
}
};
let statuses = modules(&r.flow_status);
// The read check admitted the flow run on its own tag only. A nested run outside
// the caller's tag scope is still walked through, so it cannot hide a descendant
// the caller could read directly, but its approvals are not returned.
let in_scope = scope_tags.as_ref().map_or(true, |t| t.contains(&r.tag.as_str()));
if let (Some(subflows), true) = (&at, in_scope) {
let flow_step = r.flow_status.as_ref().and_then(|f| f["step"].as_u64());
for (i, m) in statuses.iter().enumerate() {
// A step `skip_if` skipped never asked for approval.
if m["type"] != "Success" || m["skipped"].as_bool() == Some(true) {
continue;
}
let step_id = m["id"].as_str().unwrap_or_default();
let def = defs.iter().find(|d| d["id"] == step_id);
if !def.is_some_and(|d| !d["suspend"].is_null()) {
continue;
}
let approvers: Vec<Approval> =
serde_json::from_value(m["approvers"].clone()).unwrap_or_default();
// No response and the flow moved past the step after it: it timed out and
// continued. While it waits, `step` is that next step's index.
if approvers.is_empty() && !flow_step.is_some_and(|s| s > i as u64 + 1) {
continue;
}
let step_summary = def
.and_then(|d| d["summary"].as_str())
.filter(|s| !s.is_empty())
.map(str::to_string);
let required_events = def
.and_then(|d| d["suspend"]["required_events"].as_u64())
.unwrap_or(1);
approvals.push(NestedApproval {
job_id: r.id,
subflows: subflows.clone(),
step_id: step_id.to_string(),
step_summary,
required_events,
approvers,
});
}
}
for d in &defs {
let Some(step) = d["id"].as_str().filter(|s| holders.contains(*s)) else {
continue;
};
let Some(status) = statuses.iter().find(|s| s["id"] == step) else {
continue;
};
let mut subflows = at.clone().unwrap_or_default();
if d["value"]["type"] == "flow" {
subflows.push(step.to_string());
}
// A subflow or branch run is the step's `job`, a loop's or a branch's runs its
// `flow_jobs`.
let started = std::iter::once(&status["job"])
.chain(status["flow_jobs"].as_array().into_iter().flatten())
.filter_map(|v| v.as_str()?.parse::<Uuid>().ok());
for child in started {
if seen.len() > NESTED_RUNS_READ {
more = true;
break;
}
if seen.insert(child) {
next.insert(child, (Some(subflows.clone()), Some(holders.clone())));
}
}
}
}
level = next;
}
approvals.sort_by_key(|a| a.approvers.first().and_then(|a| a.approved_at));
Ok(Json(NestedApprovals { approvals, more }))
}
/// The runs waiting on an approval step set to show on Home that the caller can approve, by the
/// same check the resume boundary runs. A step anyone holding its link can approve is listed
/// only to those who can read its run, or every member would learn the names of flows they
/// have no access to.
async fn list_waiting_approvals(
authed: ApiAuthed,
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
Path(w_id): Path<String>,
) -> error::Result<Json<WaitingApprovals>> {
// A token confined to some tags reads no job outside them, here as in every job read.
let scope_tags =
get_scope_tags(&authed).map(|v| v.into_iter().map(str::to_string).collect::<Vec<_>>());
let rows = sqlx::query!(
r#"
SELECT j.id AS "id!",
COALESCE(j.root_job, j.parent_job, j.id) AS "root_job_id!",
j.runnable_path,
j.permissioned_as_email AS "email!",
j.created_by AS "created_by!",
j.created_at AS "created_at!",
COALESCE(rj.runnable_path, j.runnable_path) AS flow_path,
NULLIF(f.summary, '') AS flow_summary,
s.flow_status->'approval_conditions' AS approval_conditions,
NULLIF(w.m->'home'->>'step_summary', '') AS step_summary,
COALESCE((w.m->>'count')::bigint, 1) AS "required_approvals!",
-- Counted as the worker counts them: those sent to the approval step's job,
-- plus those sent to the flow itself.
(SELECT count(*) FROM resume_job r WHERE r.job IN (j.id, (w.m->>'job')::uuid))
AS "approvals!",
EXISTS(SELECT 1 FROM resume_job r
WHERE r.job IN (j.id, (w.m->>'job')::uuid) AND r.approver = $2)
AS "approved_by_me!"
FROM v2_job_queue q
JOIN v2_job j ON j.id = q.id
JOIN v2_job_status s ON s.id = q.id
LEFT JOIN v2_job rj ON rj.id = COALESCE(j.root_job, j.parent_job)
LEFT JOIN flow f
ON f.workspace_id = j.workspace_id
AND f.path = COALESCE(rj.runnable_path, j.runnable_path)
-- The step waiting on the approval, which the worker marks `home` when the approval
-- step has `show_on_home`: only those are listed, since many approvals are announced
-- elsewhere (a resume link sent to a chat) and every admin and owner could give them.
CROSS JOIN LATERAL (
SELECT s.flow_status->'modules'->((s.flow_status->>'step')::int) AS m
) w
WHERE q.workspace_id = $1
AND q.suspend > 0
AND w.m->>'type' = 'WaitingForEvents'
AND w.m->'home' IS NOT NULL
AND ($4::text[] IS NULL OR j.tag = ANY($4))
ORDER BY j.created_at DESC
LIMIT $3
"#,
&w_id,
&authed.username,
WAITING_APPROVALS_SCAN,
scope_tags.as_deref(),
)
.fetch_all(&db)
.await?;
let candidates: Vec<_> = rows
.into_iter()
.filter(|r| !r.approved_by_me)
.filter_map(|r| {
let ac = r
.approval_conditions
.as_ref()
.and_then(|v| serde_json::from_value::<ApprovalConditions>(v.clone()).ok());
let opt_authed = Some(authed.clone());
can_approve_step(&opt_authed, &ac, r.runnable_path.as_deref(), &r.email).then(|| {
let auth_required = ac.as_ref().is_some_and(|ac| ac.user_auth_required);
(r, auth_required)
})
})
.collect();
let root_ids: Vec<Uuid> = candidates
.iter()
.filter(|(_, auth_required)| !auth_required)
.map(|(r, _)| r.root_job_id)
.collect();
let readable: std::collections::HashSet<Uuid> = if root_ids.is_empty() {
Default::default()
} else {
let mut tx = user_db.begin(&authed).await?;
let ids = sqlx::query_scalar!("SELECT id FROM v2_job WHERE id = ANY($1)", &root_ids)
.fetch_all(&mut *tx)
.await?;
tx.commit().await?;
ids.into_iter().collect()
};
let listed: Vec<WaitingApproval> = candidates
.into_iter()
.filter_map(|(r, auth_required)| {
(auth_required || readable.contains(&r.root_job_id)).then(|| WaitingApproval {
job_id: r.id,
flow_path: r.flow_path,
flow_summary: r.flow_summary,
step_summary: r.step_summary,
started_by: r.created_by,
created_at: r.created_at,
approvals: r.approvals,
required_approvals: r.required_approvals,
})
})
.collect();
let total = listed.len();
let approvals = listed
.into_iter()
.take(WAITING_APPROVALS_RETURNED)
.collect();
Ok(Json(WaitingApprovals { approvals, total }))
}
#[derive(Serialize)]
struct StepApproval {
resume_id: u16,
approver: String,
/// Known only while the run is live: a finished run keeps approver names alone.
/// Known only while the run is live, as is `value`: a finished run keeps approver names and
/// times alone.
#[serde(skip_serializing_if = "Option::is_none")]
approved: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -5861,7 +6249,6 @@ async fn get_approval_step_detail(
module: Option<serde_json::Value>,
next_module: Option<serde_json::Value>,
module_def: Option<serde_json::Value>,
is_last_module: bool,
run_approval_conditions: Option<serde_json::Value>,
suspend_until: Option<chrono::DateTime<chrono::Utc>>,
flow_error: Option<serde_json::Value>,
@@ -5880,10 +6267,6 @@ async fn get_approval_step_detail(
'$.modules[*] ? (@.id == $id)',
jsonb_build_object('id', $3::text)
) AS module_def,
COALESCE(
COALESCE(j.raw_flow, fv.value, fn.flow)->'modules'->-1->>'id' = $3,
false
) AS is_last_module,
s.flow_status->'approval_conditions' AS run_approval_conditions,
q.suspend_until,
c.result->'error' AS flow_error,
@@ -5947,12 +6330,13 @@ async fn get_approval_step_detail(
.module_def
.and_then(|v| serde_json::from_value(v).ok())
.ok_or_else(not_found)?;
// The worker holds a run only after a step with a positive `required_events` that has a
// step after it (`needs_resume`); the last step's suspend settings never stop the run.
// The worker holds a run only after a step with a positive `required_events`. A last step
// holds it too: the worker appends a virtual step after it (`add_virtual_items_if_necessary`),
// which the stored flow does not carry.
let suspend = module_def
.suspend
.as_ref()
.filter(|s| s.required_events.unwrap_or(0) > 0 && !row.is_last_module)
.filter(|s| s.required_events.unwrap_or(0) > 0)
.ok_or_else(|| {
Error::BadRequest(format!("Step {step_id} is not an approval (suspend) step"))
})?;
@@ -5999,9 +6383,9 @@ async fn get_approval_step_detail(
.map(|a| StepApproval {
resume_id: a.resume_id,
approver: a.approver.clone(),
approved: None,
approved: a.approved,
value: None,
created_at: None,
created_at: a.approved_at,
})
.collect()
} else {
@@ -6594,6 +6978,8 @@ pub async fn get_suspended_job_flow(
.map(|x| Approval {
resume_id: x.resume_id as u16,
approver: x.approver.unwrap_or_else(|| "anonymous".to_string()),
approved_at: None,
approved: None,
})
.collect()
} else {
@@ -13625,3 +14011,84 @@ mod approval_view_gate_tests {
assert!(from_settings(serde_json::json!({})).is_none());
}
}
#[cfg(test)]
mod nested_approvals_tests {
use super::{approval_holders, may_hold_approval};
use serde_json::json;
fn script(id: &str) -> serde_json::Value {
json!({"id": id, "value": {"type": "rawscript", "content": "", "language": "bun"}})
}
fn approval(id: &str) -> serde_json::Value {
let mut s = script(id);
s["suspend"] = json!({"required_events": 1});
s
}
#[test]
fn reads_only_steps_that_can_hold_an_approval() {
// A subflow's steps are not in its caller's definition: always followed.
assert!(may_hold_approval(
&json!({"id": "sub", "value": {"type": "flow", "path": "f/a/b"}})
));
let lp = |modules| json!({"id": "l", "value": {"type": "forloopflow", "modules": modules}});
assert!(!may_hold_approval(&lp(json!([script("a")]))));
assert!(may_hold_approval(&lp(json!([script("a"), approval("b")]))));
// At any depth of inline loops.
assert!(may_hold_approval(&lp(json!([lp(json!([approval("b")]))]))));
assert!(may_hold_approval(
&json!({"id": "w", "value": {"type": "whileloopflow",
"modules": [{"id": "sub", "value": {"type": "flow", "path": "f/a/b"}}]}})
));
let branches = |kind, default, branch| {
json!({"id": "br", "value": {"type": kind, "default": default,
"branches": [{"modules": branch}]}})
};
assert!(!may_hold_approval(&branches(
"branchone",
json!([script("a")]),
json!([script("b")])
)));
assert!(may_hold_approval(&branches(
"branchone",
json!([approval("a")]),
json!([])
)));
assert!(may_hold_approval(&branches(
"branchone",
json!([]),
json!([approval("b")])
)));
assert!(may_hold_approval(&branches(
"branchall",
json!(null),
json!([approval("b")])
)));
assert!(!may_hold_approval(&branches(
"branchall",
json!(null),
json!([script("b")])
)));
// A step's own suspend is the caller's own approval, not a nested one.
assert!(!may_hold_approval(&approval("a")));
// `"suspend": null` is not an approval step.
let mut nulled = script("a");
nulled["suspend"] = serde_json::Value::Null;
assert!(!may_hold_approval(&lp(json!([nulled]))));
}
#[test]
fn holders_reach_into_nested_loop_bodies() {
// A loop run's own definition keeps the inner loop as a `modules_node` reference, so
// the inner loop is found only from the flow's full definition.
let inner = json!({"id": "inner", "value": {"type": "forloopflow",
"modules": [approval("s")]}});
let outer = json!({"id": "outer", "value": {"type": "forloopflow",
"modules": [script("a"), inner]}});
let mut holders = std::collections::HashSet::new();
approval_holders(&[outer, script("z")], &mut holders);
assert_eq!(holders, ["outer", "inner"].map(String::from).into());
}
}
+12 -1
View File
@@ -159,9 +159,19 @@ pub(crate) async fn list_recent_runs(
ORDER BY c.completed_at DESC
LIMIT $4)
UNION ALL
(SELECT q.id, NULL, q.started_at, NULL, NULL
(SELECT q.id,
-- `suspend` also parks a workflow as code on its children or a sleep: only
-- a wait on an approval is one.
CASE WHEN q.suspend > 0 AND (
s.flow_status->'modules'->((s.flow_status->>'step')::int)->>'type'
= 'WaitingForEvents'
OR s.workflow_as_code_status->'_checkpoint'->'pending_steps'->>'mode'
= 'approval'
) THEN 'suspended' END,
q.started_at, NULL, NULL
FROM v2_job_queue q
JOIN v2_job j ON j.id = q.id
LEFT JOIN v2_job_status s ON s.id = q.id
WHERE q.workspace_id = $1 AND q.running AND {LISTED_ROOT_RUN}
AND NOT EXISTS (SELECT 1 FROM v2_job_completed c WHERE c.id = q.id))
)
@@ -176,6 +186,7 @@ pub(crate) async fn list_recent_runs(
'script') = 'flow' THEN 'flow'
ELSE 'script' END AS kind,
CASE WHEN r.status IS NULL THEN 'running'
WHEN r.status = 'suspended' THEN 'suspended'
WHEN r.status IN ('success', 'skipped') THEN 'success'
WHEN r.status = 'canceled' THEN 'canceled'
WHEN EXISTS (SELECT 1 FROM job_resolution jr WHERE jr.job_id = r.id) THEN 'resolved'
+25 -1
View File
@@ -323,6 +323,25 @@ async fn set_request_client(
windmill_common::trigger_history::scope_client(client, next.run(req)).await
}
/// Scope the request in its origin (client address and user agent), recorded on the audit
/// entries it writes. A request routed in-process has no connect info and keeps the origin
/// of the request that routed it.
async fn set_request_origin(
req: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
use windmill_common::request_origin::{current, scope, RequestOrigin};
let peer = req
.extensions()
.get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
.map(|c| c.0.ip());
let origin = match (peer, current()) {
(None, Some(outer)) => (*outer).clone(),
(peer, _) => RequestOrigin::from_request(peer, req.headers()),
};
scope(origin, next.run(req)).await
}
#[cfg(not(feature = "tantivy"))]
type IndexReader = ();
@@ -1292,6 +1311,8 @@ pub async fn run_server(
let app = app.layer(axum::middleware::from_fn(set_request_client));
let app = app.layer(axum::middleware::from_fn(set_request_origin));
let app = app.layer(CatchPanicLayer::custom(|err| {
tracing::error!("panic in handler, returning 500: {:?}", err);
Response::builder()
@@ -1308,7 +1329,10 @@ pub async fn run_server(
let listener = listener.tap_io(move |tcp_stream| {
let _ = tcp_stream.set_nodelay(!server_mode);
});
let server = axum::serve(listener, app.into_make_service());
let server = axum::serve(
listener,
app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
);
tracing::info!(
instance = %*INSTANCE_NAME,
+5 -2
View File
@@ -367,8 +367,11 @@ async fn retire_legacy_audit_table(conn: &mut PgConnection) -> Result<(), Error>
.await?;
tx.execute("DROP TABLE audit").await?;
tx.execute(
format!("CREATE VIEW audit AS SELECT {AUDIT_COLUMNS} FROM audit_partitioned WHERE false")
.as_str(),
format!(
"CREATE VIEW audit AS SELECT {AUDIT_COLUMNS}, client_ip, user_agent \
FROM audit_partitioned WHERE false"
)
.as_str(),
)
.await?;
tx.execute("GRANT ALL ON audit TO windmill_user, windmill_admin")
+88 -22
View File
@@ -85,10 +85,44 @@ fn default_true() -> bool {
pub(crate) struct OffboardResponse {
#[serde(skip_serializing_if = "Vec::is_empty")]
conflicts: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
conflict_items: Vec<PathConflict>,
#[serde(skip_serializing_if = "Option::is_none")]
summary: Option<OffboardSummary>,
}
impl OffboardResponse {
fn conflicts(conflict_items: Vec<PathConflict>, global: bool) -> Self {
let conflicts = conflict_items
.iter()
.map(|c| {
if global {
format!("[{}] {}: {}", c.workspace_id, c.kind, c.target_path)
} else {
format!("{}: {}", c.kind, c.target_path)
}
})
.collect();
Self { conflicts, conflict_items, summary: None }
}
fn done(summary: OffboardSummary) -> Self {
Self { conflicts: vec![], conflict_items: vec![], summary: Some(summary) }
}
}
/// An item of the departing user whose reassigned path is already taken.
#[derive(Serialize)]
struct PathConflict {
workspace_id: String,
/// The table the item lives in (`script`, `flow`, `http_trigger`, ...).
kind: String,
/// The departing user's item, under `u/{username}/`.
source_path: String,
/// The existing item the reassignment would collide with.
target_path: String,
}
#[derive(Serialize)]
struct OffboardSummary {
scripts_reassigned: i64,
@@ -415,7 +449,7 @@ pub(crate) async fn offboard_workspace_user(
let conflicts = check_path_conflicts(&db, &w_id, &username, &req.reassign_to).await?;
if !conflicts.is_empty() {
return Ok(Json(OffboardResponse { conflicts, summary: None }));
return Ok(Json(OffboardResponse::conflicts(conflicts, false)));
}
let email = sqlx::query_scalar!(
@@ -478,10 +512,7 @@ pub(crate) async fn offboard_workspace_user(
.await?;
}
Ok(Json(OffboardResponse {
conflicts: vec![],
summary: Some(summary),
}))
Ok(Json(OffboardResponse::done(summary)))
}
// ---- Instance-level endpoints ----
@@ -557,16 +588,11 @@ pub(crate) async fn offboard_global_user(
&reassignment.reassign_to,
)
.await?;
for c in conflicts {
all_conflicts.push(format!("[{}] {}", &ws.workspace_id, c));
}
all_conflicts.extend(conflicts);
}
}
if !all_conflicts.is_empty() {
return Ok(Json(OffboardResponse {
conflicts: all_conflicts,
summary: None,
}));
return Ok(Json(OffboardResponse::conflicts(all_conflicts, true)));
}
let mut tx = db.begin().await?;
@@ -654,10 +680,7 @@ pub(crate) async fn offboard_global_user(
tx.commit().await?;
Ok(Json(OffboardResponse {
conflicts: vec![],
summary: Some(total_summary),
}))
Ok(Json(OffboardResponse::done(total_summary)))
}
// ---- Validation helpers ----
@@ -769,7 +792,7 @@ async fn check_path_conflicts(
w_id: &str,
username: &str,
reassign_to: &str,
) -> Result<Vec<String>> {
) -> Result<Vec<PathConflict>> {
let new_prefix = format!("{}/", reassign_to);
let mut conflicts = Vec::new();
@@ -800,11 +823,14 @@ async fn check_path_conflicts(
"flow" => " AND NOT t1.archived",
_ => "",
};
// A conflict is resolved by deleting one of its two paths, so the source must be the
// departing user's: `starts_with` rather than LIKE, where the `_` usernames may hold
// matches any character and would report another user's item as conflicting with itself.
// SAFETY: `table_name` comes from a hardcoded allowlist `tables`, not user input.
let rows: Vec<String> = sqlx::query_scalar(&format!(
"SELECT REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \
let rows: Vec<(String, String)> = sqlx::query_as(&format!(
"SELECT DISTINCT t1.path, REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \
FROM {table} t1 \
WHERE t1.path LIKE ('u/' || $1 || '/%') AND t1.workspace_id = $2{extra_filter} \
WHERE starts_with(t1.path, 'u/' || $1 || '/') AND t1.workspace_id = $2{extra_filter} \
AND EXISTS ( \
SELECT 1 FROM {table} t2 \
WHERE t2.path = REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \
@@ -818,8 +844,13 @@ async fn check_path_conflicts(
.fetch_all(db)
.await?;
for path in rows {
conflicts.push(format!("{}: {}", table_name, path));
for (source_path, target_path) in rows {
conflicts.push(PathConflict {
workspace_id: w_id.to_string(),
kind: table_name.to_string(),
source_path,
target_path,
});
}
}
@@ -1216,12 +1247,47 @@ async fn offboard_user_from_workspace<'c>(
&new_prefix, username, w_id
).execute(&mut **tx).await?;
// Deleting a script or flow by path leaves its asset usages behind, on the keys the moved
// usages take; such a row is an orphan or the same usage, so it is dropped, not renamed onto.
sqlx::query(
"DELETE FROM asset d WHERE d.workspace_id = $3 AND EXISTS ( \
SELECT 1 FROM asset s \
WHERE s.workspace_id = $3 AND starts_with(s.usage_path, 'u/' || $2 || '/') \
AND s.ctid <> d.ctid AND s.path = d.path AND s.kind = d.kind AND s.usage_kind = d.usage_kind \
AND REGEXP_REPLACE(s.usage_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.usage_path)",
)
.bind(&new_prefix)
.bind(username)
.bind(w_id)
.execute(&mut **tx)
.await?;
sqlx::query!(
r#"UPDATE asset SET usage_path = REGEXP_REPLACE(usage_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE usage_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#,
&new_prefix, username, w_id
).execute(&mut **tx).await?;
// ---- dependency_map ----
// Deleting an item by path leaves its rows here, so an item deleted to make room at the
// target still holds the keys the moved rows take. A row already holding a moved row's final
// key is such an orphan or the same edge, so it is dropped rather than renamed onto.
// SAFETY: `column` comes from the hardcoded list below, not user input.
for column in ["importer_path", "imported_path"] {
sqlx::query(&format!(
"DELETE FROM dependency_map d WHERE d.workspace_id = $3 AND EXISTS ( \
SELECT 1 FROM dependency_map s \
WHERE s.workspace_id = $3 AND starts_with(s.{column}, 'u/' || $2 || '/') \
AND s.ctid <> d.ctid AND s.importer_node_id = d.importer_node_id AND s.importer_kind = d.importer_kind \
AND REGEXP_REPLACE(s.importer_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.importer_path \
AND REGEXP_REPLACE(s.imported_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.imported_path)"
))
.bind(&new_prefix)
.bind(username)
.bind(w_id)
.execute(&mut **tx)
.await?;
}
sqlx::query!(
r#"UPDATE dependency_map SET importer_path = REGEXP_REPLACE(importer_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE importer_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#,
&new_prefix, username, w_id
+4
View File
@@ -26,6 +26,10 @@ pub struct AuditLog {
pub resource: Option<String>,
pub parameters: Option<serde_json::Value>,
pub span: Option<String>,
#[sqlx(default)]
pub client_ip: Option<String>,
#[sqlx(default)]
pub user_agent: Option<String>,
}
#[derive(Deserialize)]
+5 -1
View File
@@ -17,7 +17,8 @@ benchmark = []
parquet = []
aws_auth = ["dep:aws-sdk-sts", "dep:aws-config"]
otel = ["dep:opentelemetry-semantic-conventions", "dep:opentelemetry-otlp", "dep:opentelemetry_sdk",
"dep:tracing-opentelemetry", "dep:opentelemetry-appender-tracing", "dep:tonic", "dep:opentelemetry"]
"dep:tracing-opentelemetry", "dep:opentelemetry-appender-tracing", "dep:tonic", "dep:opentelemetry",
"dep:opentelemetry-http", "dep:reqwest_otel"]
smtp = ["dep:mail-send", "dep:rustls", "dep:tokio-rustls", "dep:rustls-native-certs", "dep:webpki-roots"]
scoped_cache = []
cloud = []
@@ -142,6 +143,9 @@ opentelemetry = { workspace = true, optional = true }
tracing-opentelemetry = { workspace = true, optional = true }
opentelemetry-appender-tracing = { workspace = true, optional = true }
tonic = { workspace = true, optional = true }
opentelemetry-http = { workspace = true, optional = true }
# The reqwest the OTLP/HTTP exporter is built on, for a client of our own around it.
reqwest_otel = { package = "reqwest", version = "0.12", features = ["blocking"], optional = true }
equivalent = "1.0.2"
[dev-dependencies]
+317
View File
@@ -0,0 +1,317 @@
//! The address a request comes from, for decisions that must not be spoofable (per-IP rate
//! limits, token IP allowlists).
//!
//! Forwarding headers are believed only when the TCP peer is in `TRUSTED_PROXIES`. Then either
//! `CLIENT_IP_HEADER` names the one header the edge in front writes authoritatively, or
//! `X-Forwarded-For` is read from the right, stopping at the first hop that is not itself a
//! trusted proxy. Everything left of that hop was written by the client and is ignored.
//! `X-Real-IP` is never read implicitly: proxies that do not set it pass the client's own through.
use std::net::{IpAddr, SocketAddr};
use std::sync::LazyLock;
use axum::extract::{ConnectInfo, FromRequestParts};
use axum::http::{request::Parts, HeaderMap, HeaderName};
use ipnet::IpNet;
/// Loopback, private and link-local networks: where a reverse proxy in front of Windmill
/// usually connects from. Anything else in front (a CDN, a public load balancer) must be listed
/// in `TRUSTED_PROXIES`, or its own address is taken as the client's. Job code on the same
/// network is trusted too, so a deployment where jobs can reach the server directly should list
/// its proxy's exact address instead.
const DEFAULT_TRUSTED_PROXIES: &[&str] = &[
"127.0.0.0/8",
"::1/128",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"169.254.0.0/16",
"fc00::/7",
"fe80::/10",
];
pub struct ClientIpConfig {
pub trusted: Vec<IpNet>,
pub header: Option<HeaderName>,
}
/// `TRUSTED_PROXIES`: comma-separated IPs or CIDRs; set but empty, or `none`, trusts no proxy.
/// `CLIENT_IP_HEADER`: a header such as `CloudFront-Viewer-Address`, `CF-Connecting-IP` or
/// `X-Real-IP` that the trusted edge overwrites on every request, read instead of
/// `X-Forwarded-For`.
pub static CLIENT_IP_CONFIG: LazyLock<ClientIpConfig> = LazyLock::new(|| {
let trusted = match std::env::var("TRUSTED_PROXIES") {
Ok(v) => parse_trusted_proxies(&v),
Err(_) => parse_trusted_proxies(&DEFAULT_TRUSTED_PROXIES.join(",")),
};
let header = std::env::var("CLIENT_IP_HEADER")
.ok()
.filter(|v| !v.trim().is_empty())
.and_then(|v| match HeaderName::try_from(v.trim()) {
Ok(h) => Some(h),
Err(_) => {
tracing::error!("CLIENT_IP_HEADER: {v:?} is not a header name, ignoring it");
None
}
});
ClientIpConfig { trusted, header }
});
fn parse_trusted_proxies(v: &str) -> Vec<IpNet> {
if v.trim().eq_ignore_ascii_case("none") {
return vec![];
}
v.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.filter_map(|s| {
let parsed = s
.parse::<IpNet>()
.ok()
.or_else(|| s.parse::<IpAddr>().ok().map(IpNet::from));
if parsed.is_none() {
tracing::error!("TRUSTED_PROXIES: ignoring invalid entry {s:?}");
}
parsed
})
.collect()
}
/// The client address of a request: `None` when the server was not given the connection's
/// peer (a router served without connect info, as in tests or internal dispatch).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ClientIp(pub Option<IpAddr>);
impl<S: Send + Sync> FromRequestParts<S> for ClientIp {
type Rejection = std::convert::Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
Ok(ClientIp(client_ip_of_parts(parts)))
}
}
pub fn client_ip_of_parts(parts: &Parts) -> Option<IpAddr> {
let peer = parts
.extensions
.get::<ConnectInfo<SocketAddr>>()
.map(|c| c.0.ip())?;
Some(resolve_client_ip(peer, &parts.headers, &CLIENT_IP_CONFIG))
}
/// An IPv4 client of a dual-stack listener arrives as `::ffff:a.b.c.d`; compare it as IPv4 so
/// IPv4 networks match it.
pub fn canonical(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(ip),
v4 => v4,
}
}
fn is_trusted(ip: IpAddr, trusted: &[IpNet]) -> bool {
trusted.iter().any(|n| n.contains(&ip))
}
/// An address as proxies write it: bare, `ip:port` or `[v6]:port`.
fn parse_addr(bytes: &[u8]) -> Option<IpAddr> {
let s = std::str::from_utf8(bytes).ok()?.trim();
s.parse::<IpAddr>()
.ok()
.or_else(|| s.parse::<SocketAddr>().ok().map(|a| a.ip()))
.map(canonical)
}
/// `CloudFront-Viewer-Address` always ends in the source port, after an unbracketed IPv6
/// address. Read generically, `2001:db8::1:4430` is itself a valid address, so each source port
/// would name a different client.
fn parse_addr_then_port(bytes: &[u8]) -> Option<IpAddr> {
let s = std::str::from_utf8(bytes).ok()?.trim();
let (ip, port) = s.rsplit_once(':')?;
port.parse::<u16>().ok()?;
let ip = ip
.strip_prefix('[')
.and_then(|i| i.strip_suffix(']'))
.unwrap_or(ip);
ip.parse::<IpAddr>().ok().map(canonical)
}
pub fn resolve_client_ip(peer: IpAddr, headers: &HeaderMap, cfg: &ClientIpConfig) -> IpAddr {
let peer = canonical(peer);
if !is_trusted(peer, &cfg.trusted) {
return peer;
}
if let Some(name) = &cfg.header {
let mut values = headers.get_all(name).iter();
return match (values.next(), values.next()) {
(Some(v), None) if name.as_str() == "cloudfront-viewer-address" => {
parse_addr_then_port(v.as_bytes()).unwrap_or(peer)
}
(Some(v), None) => parse_addr(v.as_bytes()).unwrap_or(peer),
_ => peer,
};
}
// Split on raw bytes: a field that is not valid UTF-8 must stay in the list as a hop we cannot
// read, not vanish and let the fields around it shift into its place.
let hops: Vec<&[u8]> = headers
.get_all("x-forwarded-for")
.iter()
.flat_map(|v| v.as_bytes().split(|b| *b == b','))
.collect();
let mut client = peer;
for hop in hops.iter().rev() {
// A hop we cannot read ends what can be believed: the last trusted address stands.
let Some(ip) = parse_addr(hop) else {
return client;
};
client = ip;
if !is_trusted(ip, &cfg.trusted) {
return ip;
}
}
client
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderValue;
fn headers(pairs: &[(&'static str, &[u8])]) -> HeaderMap {
let mut h = HeaderMap::new();
for (k, v) in pairs {
h.append(*k, HeaderValue::from_bytes(v).unwrap());
}
h
}
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
fn cfg(trusted: &str, header: Option<&'static str>) -> ClientIpConfig {
ClientIpConfig {
trusted: parse_trusted_proxies(trusted),
header: header.map(HeaderName::from_static),
}
}
fn defaults() -> ClientIpConfig {
cfg(&DEFAULT_TRUSTED_PROXIES.join(","), None)
}
#[test]
fn untrusted_peer_ignores_forwarding_headers() {
let h = headers(&[("x-forwarded-for", b"10.0.0.9")]);
assert_eq!(
resolve_client_ip(ip("1.2.3.4"), &h, &defaults()),
ip("1.2.3.4")
);
let c = cfg("10.0.0.0/8", Some("cf-connecting-ip"));
let h = headers(&[("cf-connecting-ip", b"5.5.5.5")]);
assert_eq!(resolve_client_ip(ip("1.2.3.4"), &h, &c), ip("1.2.3.4"));
}
#[test]
fn forwarded_for_is_read_from_the_right() {
// A client-written leftmost entry is skipped: the proxy appended the real address.
let h = headers(&[("x-forwarded-for", b"6.6.6.6, 5.5.5.5, 10.0.0.2")]);
assert_eq!(
resolve_client_ip(ip("10.0.0.1"), &h, &defaults()),
ip("5.5.5.5")
);
let h = headers(&[
("x-forwarded-for", b"6.6.6.6"),
("x-forwarded-for", b"5.5.5.5"),
]);
assert_eq!(
resolve_client_ip(ip("10.0.0.1"), &h, &defaults()),
ip("5.5.5.5")
);
}
#[test]
fn real_ip_is_not_read_implicitly() {
let h = headers(&[("x-real-ip", b"5.5.5.5")]);
assert_eq!(
resolve_client_ip(ip("10.0.0.1"), &h, &defaults()),
ip("10.0.0.1")
);
}
#[test]
fn unreadable_hop_stops_at_the_last_trusted_address() {
let h = headers(&[("x-forwarded-for", b"5.5.5.5, garbage, 10.0.0.2")]);
assert_eq!(
resolve_client_ip(ip("10.0.0.1"), &h, &defaults()),
ip("10.0.0.2")
);
// A non-UTF-8 field is a hop too, not a field to drop.
let h = headers(&[
("x-forwarded-for", b"6.6.6.6"),
("x-forwarded-for", b"\x80, 10.0.0.2"),
]);
assert_eq!(
resolve_client_ip(ip("10.0.0.1"), &h, &defaults()),
ip("10.0.0.2")
);
}
#[test]
fn a_configured_cdn_range_is_walked_through() {
let c = cfg("10.0.0.0/8, 130.176.0.0/16", None);
let h = headers(&[("x-forwarded-for", b"5.5.5.5, 130.176.1.1")]);
assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("5.5.5.5"));
assert_eq!(
resolve_client_ip(ip("10.0.0.1"), &h, &defaults()),
ip("130.176.1.1")
);
}
#[test]
fn configured_header_replaces_forwarded_for() {
let c = cfg("10.0.0.0/8", Some("cloudfront-viewer-address"));
let h = headers(&[
("x-forwarded-for", b"6.6.6.6"),
(
"cloudfront-viewer-address",
b"2001:0db8:85a3:0000:0000:8a2e:0370:7334:46532",
),
]);
assert_eq!(
resolve_client_ip(ip("10.0.0.1"), &h, &c),
ip("2001:db8:85a3::8a2e:370:7334")
);
let h = headers(&[("cloudfront-viewer-address", b"5.5.5.5:443")]);
assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("5.5.5.5"));
// Compressed IPv6 with a short port also parses as a bare address: the port must go.
for port in ["4430", "4431"] {
let v = format!("2001:db8::1:{port}");
let h = headers(&[("cloudfront-viewer-address", v.as_bytes())]);
assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("2001:db8::1"));
}
// Absent, repeated or unreadable: the peer, never a guess.
let h = headers(&[("x-forwarded-for", b"6.6.6.6")]);
assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("10.0.0.1"));
let h = headers(&[
("cloudfront-viewer-address", b"5.5.5.5:1"),
("cloudfront-viewer-address", b"6.6.6.6:1"),
]);
assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("10.0.0.1"));
}
#[test]
fn mapped_v4_is_v4_and_none_trusts_no_proxy() {
assert_eq!(
resolve_client_ip(ip("::ffff:1.2.3.4"), &HeaderMap::new(), &defaults()),
ip("1.2.3.4")
);
let h = headers(&[("x-forwarded-for", b"5.5.5.5")]);
assert_eq!(
resolve_client_ip(ip("127.0.0.1"), &h, &cfg("none", None)),
ip("127.0.0.1")
);
assert_eq!(
resolve_client_ip(ip("127.0.0.1"), &h, &cfg("", None)),
ip("127.0.0.1")
);
}
}
@@ -924,6 +924,7 @@ pub const ENV_SETTINGS: &[&str] = &[
"WORKER_GROUP",
"SAML_METADATA",
"INSTANCE_IS_DEV",
"TRUSTED_PROXIES",
"OTEL_METRICS",
"OTEL_TRACING",
"OTEL_LOGS",
@@ -932,6 +933,12 @@ pub const ENV_SETTINGS: &[&str] = &[
"OTEL_METRICS_ENABLED",
"OTEL_TRACING_ENABLED",
"OTEL_LOGS_ENABLED",
"OTEL_LOGS_EXCLUDE_AUDIT",
// OTEL_AUDIT_LOGS_HEADERS is left out for the same reason as the exporter headers above.
"OTEL_AUDIT_LOGS_ENABLED",
"OTEL_AUDIT_LOGS_ENDPOINT",
"OTEL_AUDIT_LOGS_PROTOCOL",
"OTEL_AUDIT_LOGS_WORKSPACES",
"OTEL_EXPORTER_OTLP_ENDPOINT",
"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
+225 -36
View File
@@ -649,6 +649,21 @@ pub struct OtelSettings {
pub metrics_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub logs_enabled: Option<bool>,
/// Leave audit events out of the logs export.
#[serde(skip_serializing_if = "Option::is_none")]
pub logs_exclude_audit: Option<bool>,
/// A second logs exporter that receives audit events only.
#[serde(skip_serializing_if = "Option::is_none")]
pub audit_logs_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub audit_logs_endpoint: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub audit_logs_headers: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub audit_logs_protocol: Option<String>,
/// Restrict the audit export to these workspaces; instance-level entries are always kept.
#[serde(skip_serializing_if = "Option::is_none")]
pub audit_logs_workspaces: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tracing_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -1200,6 +1215,11 @@ const SENSITIVE_SETTINGS: &[&str] = &[
"powershell_repo_pat",
"workspace_registries",
"sandbox_registry_auth",
"nuget_config",
"maven_settings_xml",
"cargo_registries",
// A webhook URL is commonly its own credential.
"instance_events_webhook",
];
/// Object-valued settings that contain sensitive sub-fields.
@@ -1224,8 +1244,55 @@ const NESTED_SENSITIVE_FIELDS: &[(&str, &[&str])] = &[
("custom_instance_pg_databases", &["user_pwd"]),
("external_instance_pg", &["password"]),
("github_enterprise_app", &["private_key"]),
(
"otel",
&["otel_exporter_otlp_headers", "audit_logs_headers"],
),
];
/// Settings that are maps-of-objects where each child has sensitive sub-fields.
const NESTED_MAP_SENSITIVE: &[(&str, &[&str])] = &[
("oauths", &["secret", "signing_secret"]),
("external_secrets", &["token", "approle_secret_id"]),
];
/// Calls `f` on every part of setting `key`'s value that holds a secret, as listed in
/// [`SENSITIVE_SETTINGS`], [`NESTED_SENSITIVE_FIELDS`] and [`NESTED_MAP_SENSITIVE`]. Logs
/// and API reads both redact through it, so a new secret is listed once, there.
fn visit_secrets(
key: &str,
value: &mut serde_json::Value,
f: &mut dyn FnMut(&mut serde_json::Value),
) {
if SENSITIVE_SETTINGS.contains(&key) {
f(value);
return;
}
if let Some((_, fields)) = NESTED_SENSITIVE_FIELDS.iter().find(|(k, _)| *k == key) {
if let Some(obj) = value.as_object_mut() {
for field in *fields {
if let Some(v) = obj.get_mut(*field) {
f(v);
}
}
}
return;
}
if let Some((_, fields)) = NESTED_MAP_SENSITIVE.iter().find(|(k, _)| *k == key) {
if let Some(entries) = value.as_object_mut() {
for entry in entries.values_mut() {
if let Some(obj) = entry.as_object_mut() {
for field in *fields {
if let Some(v) = obj.get_mut(*field) {
f(v);
}
}
}
}
}
}
}
fn redact_json_value(value: &serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::String(s) => serde_json::json!(redact_string(s)),
@@ -1234,42 +1301,89 @@ fn redact_json_value(value: &serde_json::Value) -> serde_json::Value {
}
fn mask_nested_sensitive(key: &str, value: &serde_json::Value) -> serde_json::Value {
for &(parent_key, sub_fields) in NESTED_SENSITIVE_FIELDS {
if key == parent_key {
if let serde_json::Value::Object(map) = value {
let mut masked = map.clone();
for &field in sub_fields {
if let Some(v) = masked.get(field) {
masked.insert(field.to_string(), redact_json_value(v));
}
}
return serde_json::Value::Object(masked);
}
let mut masked = value.clone();
visit_secrets(key, &mut masked, &mut |v| *v = redact_json_value(v));
masked
}
/// What the settings read endpoints return in place of a stored secret unless the caller
/// passes `dangerously_reveal_secrets=true`. A write carrying it back keeps the stored value
/// at that spot ([`restore_redacted_secrets`]), so a redacted read round-trips through a write.
pub const REDACTED_SECRET: &str =
"__REDACTED__ (read it with dangerously_reveal_secrets=true; send this back unchanged to keep the stored value)";
/// Replaces every secret in setting `key`'s value with [`REDACTED_SECRET`]. Only non-empty
/// strings are replaced, recursing into objects and arrays, so the value keeps the shape its
/// typed config field parses, and an unset secret still reads as unset.
pub fn redact_setting_secrets(key: &str, value: &mut serde_json::Value) {
fn redact_leaves(v: &mut serde_json::Value) {
match v {
serde_json::Value::String(s) if !s.is_empty() => *s = REDACTED_SECRET.to_string(),
serde_json::Value::Array(items) => items.iter_mut().for_each(redact_leaves),
serde_json::Value::Object(obj) => obj.values_mut().for_each(redact_leaves),
_ => {}
}
}
// Settings that are maps-of-objects where each child has a sensitive sub-field.
const NESTED_MAP_SENSITIVE: &[(&str, &[&str])] = &[
("oauths", &["secret", "signing_secret"]),
("external_secrets", &["token", "approle_secret_id"]),
];
for &(parent_key, child_fields) in NESTED_MAP_SENSITIVE {
if key == parent_key {
if let serde_json::Value::Object(entries) = value {
let mut masked = entries.clone();
for (_entry_key, entry_val) in masked.iter_mut() {
if let serde_json::Value::Object(ref mut obj) = entry_val {
for &child_field in child_fields {
if let Some(v) = obj.get(child_field) {
obj.insert(child_field.to_string(), redact_json_value(v));
}
}
}
visit_secrets(key, value, &mut redact_leaves);
}
pub fn contains_redacted_secret(value: &serde_json::Value) -> bool {
match value {
serde_json::Value::String(s) => s == REDACTED_SECRET,
serde_json::Value::Array(items) => items.iter().any(contains_redacted_secret),
serde_json::Value::Object(obj) => obj.values().any(contains_redacted_secret),
_ => false,
}
}
/// Puts the stored value back wherever `desired` carries [`REDACTED_SECRET`], matched by JSON
/// path against `current`. Fails rather than store the placeholder when nothing is stored there.
pub fn restore_redacted_secrets(
key: &str,
desired: &mut serde_json::Value,
current: Option<&serde_json::Value>,
) -> Result<(), String> {
fn walk(
path: &mut String,
desired: &mut serde_json::Value,
current: Option<&serde_json::Value>,
) -> Result<(), String> {
match desired {
serde_json::Value::String(s) if s == REDACTED_SECRET => match current {
Some(c) if !c.is_null() => {
*desired = c.clone();
Ok(())
}
return serde_json::Value::Object(masked);
_ => Err(format!(
"{path} is the redacted placeholder, but no value is stored there to keep"
)),
},
serde_json::Value::Object(obj) => {
for (k, v) in obj.iter_mut() {
let len = path.len();
path.push('.');
path.push_str(k);
walk(path, v, current.and_then(|c| c.get(k.as_str())))?;
path.truncate(len);
}
Ok(())
}
serde_json::Value::Array(items) => {
for (i, v) in items.iter_mut().enumerate() {
let len = path.len();
path.push_str(&format!("[{i}]"));
walk(path, v, current.and_then(|c| c.get(i)))?;
path.truncate(len);
}
Ok(())
}
_ => Ok(()),
}
}
value.clone()
if !contains_redacted_secret(desired) {
return Ok(());
}
walk(&mut key.to_string(), desired, current)
}
fn redact_string(s: &str) -> String {
@@ -1518,6 +1632,15 @@ pub async fn sync_global_settings_declarative(
desired: &BTreeMap<String, serde_json::Value>,
observer: &impl ConfigWriteObserver,
) -> anyhow::Result<()> {
let mut restored = None;
if desired.values().any(contains_redacted_secret) {
let mut copy = desired.clone();
for (key, value) in copy.iter_mut() {
restore_redacted_secrets(key, value, current.get(key)).map_err(anyhow::Error::msg)?;
}
restored = Some(copy);
}
let desired = restored.as_ref().unwrap_or(desired);
for url_key in [
crate::global_settings::GITHUB_APP_WEBHOOK_BASE_URL_SETTING,
crate::global_settings::API_BASE_URL_SETTING,
@@ -1786,20 +1909,24 @@ pub fn resolve_env_refs(settings: &mut GlobalSettings) -> Result<(), String> {
impl InstanceConfig {
/// Read the full instance configuration from the database.
pub async fn from_db(db: &sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<Self> {
Self::read_from_db(db, true).await
Self::read_from_db(db, true, true).await
}
/// The instance configuration as an API response may carry it: `from_db` without
/// `SERVER_SECRET_SETTINGS` unless `server_secrets_exported()`. It holds admin-entered
/// credentials (`license_key`, `scim_token`, SMTP and OAuth secrets), so callers must
/// have checked superadmin.
pub async fn from_db_for_api(db: &sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<Self> {
Self::read_from_db(db, server_secrets_exported()).await
/// `SERVER_SECRET_SETTINGS` unless `server_secrets_exported()`, and with every secret
/// replaced by [`REDACTED_SECRET`] unless `reveal_secrets`. Callers must have checked
/// superadmin.
pub async fn from_db_for_api(
db: &sqlx::Pool<sqlx::Postgres>,
reveal_secrets: bool,
) -> anyhow::Result<Self> {
Self::read_from_db(db, server_secrets_exported(), reveal_secrets).await
}
async fn read_from_db(
db: &sqlx::Pool<sqlx::Postgres>,
include_server_secrets: bool,
reveal_secrets: bool,
) -> anyhow::Result<Self> {
// Read global_settings table → flat map → deserialize into GlobalSettings
let rows: Vec<(String, serde_json::Value)> =
@@ -1812,6 +1939,12 @@ impl InstanceConfig {
.filter(|(name, _)| {
include_server_secrets || !SERVER_SECRET_SETTINGS.contains(&name.as_str())
})
.map(|(name, mut value)| {
if !reveal_secrets {
redact_setting_secrets(&name, &mut value);
}
(name, value)
})
.collect();
let global_settings: GlobalSettings =
serde_json::from_value(serde_json::Value::Object(map))?;
@@ -2835,6 +2968,49 @@ mod tests {
);
}
#[test]
fn redacted_settings_parse_and_restore_on_write() {
let stored = serde_json::json!({
"custom_instance_pg_databases": {
"user_pwd": "pg-secret",
"databases": { "mydb": { "success": true, "tag": "t" } }
},
"custom_instance_replication_pwd": "repl-secret",
"workspace_registries": { "ws": { "npm": { "token": "reg-secret" } } },
"oauths": { "google": { "id": "client-id", "secret": "oauth-secret" } },
"nuget_config": "<add key=\"ClearTextPassword\" value=\"nuget-secret\" />",
"otel": { "otel_exporter_otlp_endpoint": "https://otel", "otel_exporter_otlp_headers": "authorization=otel-secret" },
"base_url": "https://example.com",
});
let mut read = stored.clone();
for (key, value) in read.as_object_mut().unwrap().iter_mut() {
redact_setting_secrets(key, value);
}
let text = read.to_string();
for secret in [
"pg-secret",
"repl-secret",
"reg-secret",
"oauth-secret",
"nuget-secret",
"otel-secret",
] {
assert!(!text.contains(secret), "{secret} leaked: {text}");
}
assert_eq!(read["oauths"]["google"]["id"], "client-id");
assert_eq!(read["base_url"], "https://example.com");
// The redacted read still parses into the typed config the API returns.
serde_json::from_value::<GlobalSettings>(read.clone()).unwrap();
for (key, value) in read.as_object_mut().unwrap().iter_mut() {
restore_redacted_secrets(key, value, stored.get(key)).unwrap();
}
assert_eq!(read, stored);
let mut orphan = serde_json::json!({ "smtp_password": REDACTED_SECRET });
assert!(restore_redacted_secrets("smtp_settings", &mut orphan, None).is_err());
}
#[test]
fn db_oversize_alert_defaults() {
let alert: DbOversizeAlert = serde_json::from_str("{}").unwrap();
@@ -2959,6 +3135,19 @@ mod tests {
assert!(formatted.contains("****"));
}
#[test]
fn format_setting_value_redacts_otel_headers() {
let val = serde_json::json!({
"otel_exporter_otlp_endpoint": "http://collector:4317",
"otel_exporter_otlp_headers": "Authorization=Bearer main-token-12345",
"audit_logs_headers": "Authorization=Bearer audit-token-67890"
});
let formatted = format_setting_value("otel", &val);
assert!(!formatted.contains("main-token-12345"));
assert!(!formatted.contains("audit-token-67890"));
assert!(formatted.contains("http://collector:4317"));
}
#[test]
fn format_setting_value_redacts_nested_credentials() {
let val = serde_json::json!({
+61
View File
@@ -37,6 +37,7 @@ pub mod azure_workload_identity;
pub mod bench;
pub mod cache;
pub mod client;
pub mod client_ip;
pub mod data_metrics;
pub mod datatable_roles;
#[cfg(all(feature = "private", feature = "enterprise"))]
@@ -98,6 +99,7 @@ pub mod job_provenance;
pub mod jobs;
pub mod jwt;
pub mod login_rate_limit;
pub mod request_origin;
pub mod more_serde;
pub mod oauth2;
#[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))]
@@ -482,6 +484,10 @@ lazy_static::lazy_static! {
pub static ref OTEL_METRICS_ENABLED: AtomicBool = AtomicBool::new(std::env::var("OTEL_METRICS").is_ok());
pub static ref OTEL_TRACING_ENABLED: AtomicBool = AtomicBool::new(std::env::var("OTEL_TRACING").is_ok());
pub static ref OTEL_LOGS_ENABLED: AtomicBool = AtomicBool::new(std::env::var("OTEL_LOGS").is_ok());
/// Leave audit events out of the logs export, for when the audit export carries them.
pub static ref OTEL_LOGS_EXCLUDE_AUDIT: AtomicBool = AtomicBool::new(env_bool("OTEL_LOGS_EXCLUDE_AUDIT"));
pub static ref OTEL_AUDIT_LOGS_EXPORT: std::sync::RwLock<Option<OtelAuditLogsExport>> =
std::sync::RwLock::new(OtelAuditLogsExport::from_env());
pub static ref METRICS_DEBUG_ENABLED: AtomicBool = AtomicBool::new(false);
@@ -3467,3 +3473,58 @@ impl KillpillSender {
// self.already_sent.load(Ordering::SeqCst)
// }
}
fn env_bool(var: &str) -> bool {
std::env::var(var).is_ok_and(|x| x.parse::<bool>().unwrap_or(false))
}
/// An OTLP logs exporter of its own for audit events, beside the logs export: audit events can
/// go to long-term storage while the service logs go elsewhere, or nowhere.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OtelAuditLogsExport {
pub endpoint: String,
/// `key=value` pairs separated by commas, as in `OTEL_EXPORTER_OTLP_HEADERS`.
pub headers: Option<String>,
/// `grpc` (the default) or `http/protobuf`.
pub protocol: Option<String>,
/// Only the audit events of these workspaces, and of the instance itself, are exported.
/// `None` exports every workspace.
pub workspaces: Option<Vec<String>>,
}
impl OtelAuditLogsExport {
pub fn new(
enabled: bool,
endpoint: Option<String>,
headers: Option<String>,
protocol: Option<String>,
workspaces: Option<Vec<String>>,
) -> Option<Self> {
let endpoint = endpoint.filter(|e| !e.trim().is_empty())?;
enabled.then(|| Self {
endpoint: endpoint.trim().to_string(),
headers: headers.filter(|h| !h.trim().is_empty()),
protocol: protocol.filter(|p| !p.trim().is_empty()),
workspaces: workspaces
.map(|w| {
w.iter()
.map(|w| w.trim().to_string())
.filter(|w| !w.is_empty())
.collect::<Vec<_>>()
})
.filter(|w| !w.is_empty()),
})
}
fn from_env() -> Option<Self> {
Self::new(
env_bool("OTEL_AUDIT_LOGS_ENABLED"),
std::env::var("OTEL_AUDIT_LOGS_ENDPOINT").ok(),
std::env::var("OTEL_AUDIT_LOGS_HEADERS").ok(),
std::env::var("OTEL_AUDIT_LOGS_PROTOCOL").ok(),
std::env::var("OTEL_AUDIT_LOGS_WORKSPACES")
.ok()
.map(|v| v.split(',').map(str::to_string).collect()),
)
}
}
@@ -53,32 +53,6 @@ static GLOBAL_LIMIT: LazyLock<i32> = LazyLock::new(|| {
.unwrap_or(DEFAULT_GLOBAL_LIMIT)
});
/// Extract client IP from proxy headers. Only meaningful when behind a trusted
/// reverse proxy (e.g. CLOUD_HOSTED). Returns `None` if no proxy header is present.
pub fn extract_client_ip(headers: &axum::http::HeaderMap) -> Option<String> {
if let Some(real_ip) = headers.get("x-real-ip") {
if let Ok(ip) = real_ip.to_str() {
let trimmed = ip.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
}
if let Some(forwarded_for) = headers.get("x-forwarded-for") {
if let Ok(ips) = forwarded_for.to_str() {
if let Some(first_ip) = ips.split(',').next() {
let trimmed = first_ip.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
}
}
None
}
fn too_many_attempts() -> Error {
Error::Generic(
StatusCode::TOO_MANY_REQUESTS,
@@ -91,7 +65,7 @@ fn too_many_attempts() -> Error {
/// a general throttle on login traffic per server instance.
/// Per-IP is only active on CLOUD_HOSTED or when LOGIN_RATE_LIMIT_PER_IP is explicitly set.
pub fn check_and_increment_login_attempt(
headers: &axum::http::HeaderMap,
client_ip: Option<std::net::IpAddr>,
email: &str,
) -> Result<()> {
// Global limit: always on, uses atomics (single key, no need for a map)
@@ -99,8 +73,8 @@ pub fn check_and_increment_login_attempt(
// Per-IP limit: CLOUD_HOSTED or explicit opt-in
if *CLOUD_HOSTED || *PER_IP_LIMIT_EXPLICIT {
if let Some(ip) = extract_client_ip(headers) {
if !IP_RATE_LIMIT.try_increment(ip, *PER_IP_LIMIT) {
if let Some(ip) = client_ip {
if !IP_RATE_LIMIT.try_increment(ip.to_string(), *PER_IP_LIMIT) {
return Err(too_many_attempts());
}
}
+14
View File
@@ -63,6 +63,20 @@ pub(crate) fn init_logs_bridge_for_service(
None
}
#[cfg(not(feature = "private"))]
pub(crate) fn init_audit_logs_bridge(_mode: &Mode, _hostname: &str, _env: &str) -> Option<EnvFilter> {
None
}
#[cfg(not(feature = "private"))]
pub(crate) fn init_audit_logs_bridge_for_service(
_service: &str,
_hostname: &str,
_env: &str,
) -> Option<EnvFilter> {
None
}
/// Export the log records still batched, for a process about to exit.
#[cfg(not(feature = "private"))]
pub async fn flush_otel_logs() {}
@@ -0,0 +1,192 @@
//! Where the request being served came from: the client's IP address and user agent, as
//! recorded on the audit entries it writes.
use std::net::IpAddr;
use std::sync::{Arc, LazyLock};
use http::HeaderMap;
use ipnet::IpNet;
use crate::utils::truncate_chars;
use crate::worker::CLOUD_HOSTED;
const USER_AGENT_MAX_CHARS: usize = 512;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RequestOrigin {
pub client_ip: Option<IpAddr>,
pub user_agent: Option<String>,
}
tokio::task_local! {
static REQUEST_ORIGIN: Arc<RequestOrigin>;
}
/// Run `f` with `origin` as the origin of every audit entry it writes. Task-locals do not
/// cross `tokio::spawn`, so an entry written from a spawned task records no origin.
pub async fn scope<F: std::future::Future>(origin: RequestOrigin, f: F) -> F::Output {
REQUEST_ORIGIN.scope(Arc::new(origin), f).await
}
/// The origin of the request being served, `None` outside a request.
pub fn current() -> Option<Arc<RequestOrigin>> {
REQUEST_ORIGIN.try_with(|o| o.clone()).ok()
}
/// The proxies whose forwarding headers are believed. `TRUSTED_PROXIES` (comma-separated
/// addresses or CIDRs, empty for none) replaces the default: loopback, plus the private
/// ranges on cloud, where every request arrives through our own load balancer. Private
/// ranges are not trusted by default elsewhere: a self-hosted instance is often reached
/// directly from a private network, and its clients could then name any address they like.
static TRUSTED_PROXIES: LazyLock<Vec<IpNet>> =
LazyLock::new(|| match std::env::var("TRUSTED_PROXIES") {
Ok(v) => parse_trusted_proxies(&v),
Err(_) => {
let mut nets = vec!["127.0.0.0/8", "::1/128"];
if *CLOUD_HOSTED {
nets.extend(["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]);
}
nets.into_iter().filter_map(|n| n.parse().ok()).collect()
}
});
fn parse_trusted_proxies(v: &str) -> Vec<IpNet> {
v.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.filter_map(|s| {
let parsed = s
.parse::<IpNet>()
.ok()
.or_else(|| s.parse::<IpAddr>().ok().map(IpNet::from));
if parsed.is_none() {
tracing::warn!("Ignoring invalid TRUSTED_PROXIES entry: {s}");
}
parsed
})
.collect()
}
impl RequestOrigin {
/// `peer` is the address the connection came from; `None` when the request did not arrive
/// over a socket, and then no header is believed either.
pub fn from_request(peer: Option<IpAddr>, headers: &HeaderMap) -> Self {
Self {
client_ip: peer.map(|p| client_ip(p, headers, &TRUSTED_PROXIES)),
user_agent: headers
.get(http::header::USER_AGENT)
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|s| truncate_chars(s, USER_AGENT_MAX_CHARS).to_string()),
}
}
}
fn parse_hop(s: &str) -> Option<IpAddr> {
let s = s.trim();
s.parse::<IpAddr>()
.ok()
.or_else(|| s.parse::<std::net::SocketAddr>().ok().map(|a| a.ip()))
.map(|ip| ip.to_canonical())
}
/// The first address that is not a trusted proxy, walking `X-Forwarded-For` back from the
/// peer: each trusted hop vouches for the address before it, an untrusted one for nothing,
/// so entries left of it are whatever the client wrote. `X-Real-IP` is read only when there
/// is no `X-Forwarded-For`.
fn client_ip(peer: IpAddr, headers: &HeaderMap, trusted: &[IpNet]) -> IpAddr {
let is_trusted = |ip: &IpAddr| trusted.iter().any(|n| n.contains(ip));
let mut current = peer.to_canonical();
if !is_trusted(&current) {
return current;
}
// Bytes that are not UTF-8 are kept as entries that fail to parse, so they stop the walk
// rather than vanish and let the client's own entries, or X-Real-IP, stand in.
let values: Vec<String> = headers
.get_all("x-forwarded-for")
.iter()
.map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned())
.collect();
let hops: Vec<&str> = values.iter().flat_map(|v| v.split(',')).collect();
if values.is_empty() {
if let Some(ip) = headers
.get("x-real-ip")
.and_then(|v| v.to_str().ok())
.and_then(parse_hop)
{
return ip;
}
return current;
}
for hop in hops.iter().rev() {
if !is_trusted(&current) {
break;
}
match parse_hop(hop) {
Some(ip) => current = ip,
None => break,
}
}
current
}
#[cfg(test)]
mod tests {
use super::*;
fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap {
let mut h = HeaderMap::new();
for (k, v) in pairs {
h.append(*k, v.parse().unwrap());
}
h
}
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
#[test]
fn forwarded_addresses_are_believed_only_through_trusted_hops() {
let trusted = parse_trusted_proxies("10.0.0.0/8, 127.0.0.1");
let xff = headers(&[("x-forwarded-for", "6.6.6.6, 1.2.3.4, 10.0.0.2")]);
// An untrusted peer's headers say nothing.
assert_eq!(client_ip(ip("8.8.8.8"), &xff, &trusted), ip("8.8.8.8"));
// Trusted peer and trusted hop: the client is the first untrusted address, and the
// entry the client itself wrote left of it is ignored.
assert_eq!(client_ip(ip("10.0.0.1"), &xff, &trusted), ip("1.2.3.4"));
// Every hop trusted: the leftmost one.
let all_trusted = headers(&[("x-forwarded-for", "10.1.1.1, 10.0.0.2")]);
assert_eq!(
client_ip(ip("127.0.0.1"), &all_trusted, &trusted),
ip("10.1.1.1")
);
// An unparseable hop stops the walk at the last address vouched for.
let garbage = headers(&[("x-forwarded-for", "1.2.3.4, unknown")]);
assert_eq!(
client_ip(ip("10.0.0.1"), &garbage, &trusted),
ip("10.0.0.1")
);
// A hop that is not UTF-8 stops the walk too, and does not let X-Real-IP in.
let mut binary = headers(&[("x-real-ip", "5.5.5.5")]);
binary.append(
"x-forwarded-for",
http::HeaderValue::from_bytes(b"\x80, 1.2.3.4").unwrap(),
);
assert_eq!(client_ip(ip("10.0.0.1"), &binary, &trusted), ip("1.2.3.4"));
let mut binary_last = headers(&[("x-real-ip", "5.5.5.5")]);
binary_last.append(
"x-forwarded-for",
http::HeaderValue::from_bytes(b"1.2.3.4, \x80").unwrap(),
);
assert_eq!(client_ip(ip("10.0.0.1"), &binary_last, &trusted), ip("10.0.0.1"));
// X-Real-IP, only from a trusted peer and only without X-Forwarded-For.
let real = headers(&[("x-real-ip", "5.5.5.5")]);
assert_eq!(client_ip(ip("10.0.0.1"), &real, &trusted), ip("5.5.5.5"));
assert_eq!(client_ip(ip("8.8.8.8"), &real, &trusted), ip("8.8.8.8"));
// Nothing trusted.
assert_eq!(client_ip(ip("10.0.0.1"), &xff, &[]), ip("10.0.0.1"));
}
}
+129 -3
View File
@@ -67,6 +67,14 @@ fn create_targets_filter(default_env_filter: LevelFilter) -> Targets {
}
}
fn audit_filter() -> Targets {
Targets::new().with_target(AUDIT_TARGET, LevelFilter::INFO)
}
fn not_audit_filter() -> tracing_subscriber::filter::FilterFn<impl Fn(&tracing::Metadata<'_>) -> bool> {
tracing_subscriber::filter::filter_fn(|m| m.target() != AUDIT_TARGET)
}
pub const LOGS_SERVICE: &str = "logs/services/";
pub const LOGS_AUDIT: &str = "logs/audit/";
@@ -120,6 +128,7 @@ pub fn initialize_tracing(
let opentelemetry: Option<EnvFilter> = None;
let logs_bridge = crate::otel_oss::init_logs_bridge(&mode, hostname, environment);
let audit_logs_bridge = crate::otel_oss::init_audit_logs_bridge(&mode, hostname, environment);
use tracing_appender::rolling::{RollingFileAppender, Rotation};
@@ -168,6 +177,9 @@ pub fn initialize_tracing(
// Create a common filter for OTEL logs bridge and tracing layer to respect RUST_LOG
let otel_logs_filter = file_env_filter.clone();
let otel_logs_without_audit = crate::OTEL_LOGS_EXCLUDE_AUDIT
.load(std::sync::atomic::Ordering::Relaxed)
.then(not_audit_filter);
// Apply filter to the opentelemetry tracing layer to prevent debug events from being attached to spans
#[cfg(all(feature = "otel", feature = "enterprise"))]
@@ -180,7 +192,17 @@ pub fn initialize_tracing(
let opentelemetry_filtered = opentelemetry;
let base_layer = tracing_subscriber::registry()
.with(logs_bridge.with_filter(otel_logs_filter))
.with(
logs_bridge
.with_filter(otel_logs_filter)
.with_filter(otel_logs_without_audit),
)
// Audit events reach their own export whatever RUST_LOG is set to.
.with(
audit_logs_bridge
.with_filter(audit_filter())
.with_filter(audit_workspace_filter()),
)
.with(opentelemetry_filtered);
// The service log files are written to be indexed, not tailed, so they always carry the
@@ -229,9 +251,18 @@ pub fn initialize_tracing(
/// value, masked by a list of known secret fields rather than by shape, and that is fit
/// for the operator's own stdout but not for a collector.
pub fn initialize_subcommand_tracing(service: &str, hostname: &str, environment: &str) {
let logs_bridge = crate::otel_oss::init_logs_bridge_for_service(service, hostname, environment);
let logs_bridge = (!crate::OTEL_LOGS_EXCLUDE_AUDIT.load(std::sync::atomic::Ordering::Relaxed))
.then(|| crate::otel_oss::init_logs_bridge_for_service(service, hostname, environment))
.flatten();
let audit_logs_bridge =
crate::otel_oss::init_audit_logs_bridge_for_service(service, hostname, environment);
tracing_subscriber::registry()
.with(logs_bridge.with_filter(Targets::new().with_target(AUDIT_TARGET, LevelFilter::INFO)))
.with(logs_bridge.with_filter(audit_filter()))
.with(
audit_logs_bridge
.with_filter(audit_filter())
.with_filter(audit_workspace_filter()),
)
.with(
tracing_subscriber::fmt::layer().with_filter(
EnvFilter::builder()
@@ -242,6 +273,50 @@ pub fn initialize_subcommand_tracing(service: &str, hostname: &str, environment:
.init();
}
/// Keeps the audit events of the listed workspaces and lets every other event through.
/// Entries about the instance itself are recorded under workspace `global` and always kept:
/// no workspace stands behind them, and dropping them would hide settings changes.
struct AuditWorkspaceFilter(std::collections::HashSet<String>);
impl AuditWorkspaceFilter {
fn new(workspaces: Vec<String>) -> Self {
Self(workspaces.into_iter().collect())
}
}
impl<S> tracing_subscriber::layer::Filter<S> for AuditWorkspaceFilter {
fn enabled(&self, _: &tracing::Metadata<'_>, _: &Context<'_, S>) -> bool {
true
}
fn event_enabled(&self, event: &Event<'_>, _: &Context<'_, S>) -> bool {
if event.metadata().target() != AUDIT_TARGET {
return true;
}
struct Workspace<'a>(&'a std::collections::HashSet<String>, Option<bool>);
impl tracing::field::Visit for Workspace<'_> {
fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
if field.name() == "workspace_id" {
self.1 = Some(value == "global" || self.0.contains(value));
}
}
fn record_debug(&mut self, _: &tracing::field::Field, _: &dyn std::fmt::Debug) {}
}
let mut ws = Workspace(&self.0, None);
event.record(&mut ws);
ws.1.unwrap_or(true)
}
}
/// The workspace scope of the audit export, `None` for every workspace.
fn audit_workspace_filter() -> Option<AuditWorkspaceFilter> {
crate::OTEL_AUDIT_LOGS_EXPORT
.read()
.ok()
.and_then(|e| e.as_ref().and_then(|e| e.workspaces.clone()))
.map(AuditWorkspaceFilter::new)
}
lazy_static::lazy_static! {
pub static ref LOG_COUNTING_BY_MIN: Arc<RwLock<HashMap<String, LogCounter>>> = Arc::new(RwLock::new(HashMap::new()));
}
@@ -290,3 +365,54 @@ where
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[derive(Clone, Default)]
struct Seen(Arc<Mutex<Vec<String>>>);
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Seen {
fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) {
struct Msg(String);
impl tracing::field::Visit for Msg {
fn record_debug(&mut self, f: &tracing::field::Field, v: &dyn std::fmt::Debug) {
if f.name() == "message" {
self.0 = format!("{v:?}");
}
}
}
let mut m = Msg(String::new());
event.record(&mut m);
self.0.lock().unwrap().push(m.0);
}
}
/// The two exports as `initialize_tracing` filters them: the logs export without audit
/// events, and the audit export with audit events of the listed workspaces only.
#[test]
fn audit_and_logs_exports_split_events() {
let logs = Seen::default();
let audit = Seen::default();
tracing::subscriber::with_default(
tracing_subscriber::registry()
.with(logs.clone().with_filter(Some(not_audit_filter())))
.with(
audit
.clone()
.with_filter(audit_filter())
.with_filter(Some(AuditWorkspaceFilter::new(vec!["kept".to_string()]))),
),
|| {
tracing::info!(target: AUDIT_TARGET, workspace_id = "kept", "a");
tracing::info!(target: AUDIT_TARGET, workspace_id = "dropped", "b");
tracing::info!(target: AUDIT_TARGET, workspace_id = "global", "c");
tracing::info!(workspace_id = "kept", "d");
},
);
assert_eq!(*logs.0.lock().unwrap(), ["d"]);
assert_eq!(*audit.0.lock().unwrap(), ["a", "c"]);
}
}
+117
View File
@@ -81,6 +81,7 @@ bitflags::bitflags! {
const RESTRICT_PUBLIC_RUN_SHARING = 1 << 4;
const RESTRICT_GUEST_APP_DEPLOYMENT = 1 << 5;
const REQUIRE_ISOLATED_FORKS = 1 << 6;
const REQUIRE_SSO = 1 << 7;
}
}
@@ -95,6 +96,7 @@ pub enum ProtectionRuleKind {
RestrictPublicRunSharing,
RestrictGuestAppDeployment,
RequireIsolatedForks,
RequireSso,
}
impl ProtectionRuleKind {
@@ -119,6 +121,7 @@ impl ProtectionRuleKind {
ProtectionRules::RESTRICT_GUEST_APP_DEPLOYMENT
}
ProtectionRuleKind::RequireIsolatedForks => ProtectionRules::REQUIRE_ISOLATED_FORKS,
ProtectionRuleKind::RequireSso => ProtectionRules::REQUIRE_SSO,
}
}
@@ -143,6 +146,9 @@ impl ProtectionRuleKind {
ProtectionRuleKind::RequireIsolatedForks => {
"Forks of this workspace must isolate its data: no shared object storage or ducklake, and every data table cloned"
}
ProtectionRuleKind::RequireSso => {
"Every member of this workspace other than a service account must sign in with SSO"
}
}
}
}
@@ -1555,6 +1561,117 @@ pub async fn check_user_against_rule(
Ok(RuleCheckResult::Allowed)
}
struct SsoRuleset {
name: String,
bypass_users: Vec<String>,
bypass_groups: Vec<String>,
}
/// `workspace_id`'s `RequireSso` rulesets, read uncached so a rule just turned on already
/// refuses the next join.
async fn sso_rulesets(
conn: &mut sqlx::PgConnection,
workspace_id: &str,
) -> Result<Vec<SsoRuleset>> {
Ok(sqlx::query_as!(
SsoRuleset,
"SELECT name, bypass_users, bypass_groups FROM workspace_protection_rule
WHERE workspace_id = $1 AND (rules & $2) <> 0 ORDER BY name",
workspace_id,
ProtectionRules::REQUIRE_SSO.bits(),
)
.fetch_all(&mut *conn)
.await?)
}
/// The first of `rulesets` that holds a member named `username` in `groups`.
fn sso_ruleset_holding<'a>(
rulesets: &'a [SsoRuleset],
username: Option<&str>,
groups: &[String],
) -> Option<&'a str> {
rulesets
.iter()
.find(|r| {
!(username.is_some_and(|u| r.bypass_users.iter().any(|b| b == u))
|| r.bypass_groups.iter().any(|g| groups.contains(g)))
})
.map(|r| r.name.as_str())
}
/// Refuses seating `email` in `workspace_id` while a `RequireSso` rule there holds them and their
/// account signs in with a password. `pending_oauth` passes: it can only become a password
/// account through [`check_password_login_allowed`]. An email with no account yet passes too, for
/// the same reason. `username` is the one they get in the workspace; without it their instance
/// username is what bypass lists are matched against. A new member is in `all` and nothing else.
///
/// This and [`check_password_login_allowed`] each read what the other writes without locking, so
/// a join and a password switch of the same account committing at the same instant can both pass.
/// A lock shared by both would have to be taken in one order with the invite, membership and
/// `password` row locks of every member path, bulk joins included, or it deadlocks them.
pub async fn check_new_member_sso(
conn: &mut sqlx::PgConnection,
workspace_id: &str,
email: &str,
username: Option<&str>,
) -> Result<()> {
let rulesets = sso_rulesets(conn, workspace_id).await?;
if rulesets.is_empty() {
return Ok(());
}
let account = sqlx::query!(
"SELECT login_type, username FROM password WHERE email = $1",
email
)
.fetch_optional(&mut *conn)
.await?;
let Some(account) = account.filter(|a| a.login_type == "password") else {
return Ok(());
};
let username = username.or(account.username.as_deref());
let groups = ["all".to_string()];
if let Some(ruleset) = sso_ruleset_holding(&rulesets, username, &groups) {
return Err(Error::BadRequest(format!(
"Ruleset {ruleset} of {workspace_id} requires SSO: {email} signs in with a password, \
so it cannot join this workspace"
)));
}
Ok(())
}
/// Refuses giving `email` a password login while a `RequireSso` rule of a workspace they are a
/// non-service-account member of holds them.
pub async fn check_password_login_allowed(
conn: &mut sqlx::PgConnection,
email: &str,
) -> Result<()> {
let memberships = sqlx::query!(
r#"SELECT u.workspace_id, u.username,
COALESCE(array_agg(g.group_) FILTER (WHERE g.group_ IS NOT NULL), '{}') AS "groups!"
FROM usr u
LEFT JOIN usr_to_group g ON g.workspace_id = u.workspace_id AND g.usr = u.username
WHERE u.email = $1 AND NOT u.is_service_account
AND EXISTS (SELECT 1 FROM workspace_protection_rule r
WHERE r.workspace_id = u.workspace_id AND (r.rules & $2) <> 0)
GROUP BY u.workspace_id, u.username"#,
email,
ProtectionRules::REQUIRE_SSO.bits(),
)
.fetch_all(&mut *conn)
.await?;
for m in memberships {
let rulesets = sso_rulesets(conn, &m.workspace_id).await?;
if let Some(ruleset) = sso_ruleset_holding(&rulesets, Some(&m.username), &m.groups) {
return Err(Error::BadRequest(format!(
"Ruleset {ruleset} of {} requires SSO for its members, so {email} cannot sign in \
with a password",
m.workspace_id
)));
}
}
Ok(())
}
/// The roles members of `workspace_id` get in a fork of it, merged across its rulesets: where two
/// rulesets map the same role, the first by name wins. Unmapped roles carry over unchanged.
pub async fn fork_role_mapping(
@@ -23,6 +23,11 @@ use crate::oauth::{no_redirect_http_client_pinned, AuthorizationManager};
pub struct McpClientCredentials {
pub client_id: String,
pub client_secret: Option<String>,
/// Whether this call registered (or re-registered) Windmill at the server
/// rather than reusing the stored client. Registration makes the server
/// contact an author-chosen host and writes the instance-wide
/// `mcp_oauth_client` table, so callers acting for a user audit it.
pub newly_registered: bool,
/// The token endpoint and the addresses it resolved to during SSRF validation.
/// Both are private so that [`Self::token_request`] is the only way to obtain
/// the URL: it returns it together with a client pinned to those addresses, so
@@ -175,6 +180,7 @@ pub async fn get_or_refresh_mcp_client(
return Ok(McpClientCredentials {
client_id: client.client_id,
client_secret: decrypted_secret,
newly_registered: false,
token_endpoint: client.token_endpoint,
token_endpoint_target,
});
@@ -261,6 +267,7 @@ pub async fn get_or_refresh_mcp_client(
Ok(McpClientCredentials {
client_id,
client_secret,
newly_registered: true,
token_endpoint: metadata.token_endpoint,
token_endpoint_target,
})
@@ -311,6 +318,7 @@ mod tests {
let credentials = McpClientCredentials {
client_id: "id".to_string(),
client_secret: None,
newly_registered: false,
token_endpoint: "http://unresolvable.invalid/token".to_string(),
token_endpoint_target: windmill_common::ssrf::ValidatedTarget {
host: "unresolvable.invalid".to_string(),
@@ -17,13 +17,14 @@ use serde::{Deserialize, Serialize};
use sqlx::PgConnection;
use std::sync::Arc;
use windmill_api_auth::{
build_scope_path_filter, check_scopes, create_token_internal, require_is_writer, ApiAuthed,
NewToken,
build_scope_path_filter, check_run_scopes, check_scopes, create_token_internal,
require_is_writer, ApiAuthed, NewToken,
};
use windmill_audit::{audit_oss::audit_log, ActionKind};
use windmill_common::{
db::UserDB,
error::{Error, JsonResult, Result},
runnable_ref::RunnableRef,
DB,
};
@@ -165,6 +166,10 @@ async fn create_native_trigger<T: External>(
check_scopes(&authed, || {
format!("native_triggers:write:{}", &data.script_path)
})?;
check_run_scopes(
&authed,
&[RunnableRef::from_path(&data.script_path, data.is_flow)?],
)?;
require_is_writer_on_runnable(
&authed,
&data.script_path,
@@ -303,6 +308,10 @@ async fn update_native_trigger_handler<T: External>(
check_scopes(&authed, || {
format!("native_triggers:write:{}", &data.script_path)
})?;
check_run_scopes(
&authed,
&[RunnableRef::from_path(&data.script_path, data.is_flow)?],
)?;
require_is_writer_on_runnable(
&authed,
&data.script_path,
+34
View File
@@ -5619,6 +5619,40 @@ pub async fn custom_concurrency_key(
.await
}
/// A job's concurrency key, and whether its limit has held it back without letting it in yet.
pub async fn concurrency_key_and_hold(
db: &Pool<Postgres>,
job_id: &Uuid,
) -> windmill_common::error::Result<Option<(String, bool)>> {
let fut = async || {
sqlx::query!(
"SELECT key, original_scheduled_for IS NOT NULL AND released_at IS NULL AS \"held!\"
FROM concurrency_key WHERE job_id = $1",
job_id
)
.fetch_optional(db)
.await
};
fut.retry(
ConstantBuilder::default()
.with_delay(std::time::Duration::from_secs(3))
.with_max_times(5)
.build(),
)
.notify(|err, dur| {
tracing::error!(
"Could not get concurrency key for job {job_id}, retrying in {dur:#?}, err: {err:#?}"
);
})
.await
.map(|r| r.map(|r| (r.key, r.held)))
.map_err(|e| {
Error::internal_err(format!(
"Could not get concurrency key for job {job_id}: {e:#}"
))
})
}
pub async fn concurrency_key(
db: &Pool<Postgres>,
id: &Uuid,
+14 -9
View File
@@ -295,15 +295,20 @@ pub async fn create_many_http_triggers(
.await
.map_err(|err| error_wrapper(&new_http_trigger.config.route_path, err))?;
let new = trigger_save_runnables::<HttpTrigger>(new_http_trigger)?;
windmill_api_auth::composed::check_new_hub_paths(&new, &[], &authed, &db, &w_id)
.await
.map_err(|err| match err {
Error::PermissionDenied(msg) => Error::PermissionDenied(format!(
"Error occurred for HTTP route at route path: {}, error: {msg}",
new_http_trigger.config.route_path
)),
err => err,
})?;
let checked = match windmill_api_auth::check_run_scopes(&authed, &new) {
Ok(()) => {
windmill_api_auth::composed::check_new_hub_paths(&new, &[], &authed, &db, &w_id)
.await
}
err => err,
};
checked.map_err(|err| match err {
Error::PermissionDenied(msg) => Error::PermissionDenied(format!(
"Error occurred for HTTP route at route path: {}, error: {msg}",
new_http_trigger.config.route_path
)),
err => err,
})?;
let route_path_key =
check_if_route_exist(&db, &new_http_trigger.config, &w_id, None).await?;
@@ -4,7 +4,7 @@ use async_trait::async_trait;
use itertools::Itertools;
use serde_json::value::RawValue;
use sqlx::{types::Json as SqlxJson, PgConnection};
use windmill_api_auth::{check_scopes, ApiAuthed};
use windmill_api_auth::ApiAuthed;
use windmill_common::DB;
use windmill_common::{
db::UserDB,
@@ -22,25 +22,12 @@ use super::{
WebsocketTrigger,
};
/// A websocket_triggers:write token can configure secondary runnables that the
/// listener later executes under the trigger owner's identity: a `$flow:`/
/// `$script:` URL resolver and `initial_messages` of kind `runnable_result`.
/// That execution happens in a background task where the reconstructed authed is
/// scopeless (so its check_scopes is a no-op), so enforce run scope here, at
/// create/update time, against the API caller's token. Reading the paths here also
/// refuses, for any caller, one that does not parse.
fn check_secondary_runnable_scopes(
authed: &ApiAuthed,
config: &WebsocketConfigRequest,
) -> Result<()> {
/// Refuses a `$flow:`/`$script:` URL resolver or `runnable_result` initial message whose path
/// does not parse: `config_runnables` leaves those out, so the save's run-scope check never sees
/// them.
fn check_secondary_runnables_parse(config: &WebsocketConfigRequest) -> Result<()> {
for runnable in secondary_runnables(&config.url, config.initial_messages.as_deref()) {
let runnable = runnable?;
let kind = if runnable.is_flow() {
"flows"
} else {
"scripts"
};
check_scopes(authed, || format!("jobs:run:{kind}:{}", runnable.path()))?;
runnable?;
}
Ok(())
}
@@ -157,7 +144,7 @@ impl TriggerCrud for WebsocketTrigger {
w_id: &str,
trigger: TriggerData<Self::TriggerConfigRequest>,
) -> Result<()> {
check_secondary_runnable_scopes(authed, &trigger.config)?;
check_secondary_runnables_parse(&trigger.config)?;
let resolved_edited_by = trigger.base.resolve_edited_by(authed);
let resolved_permissioned_as = trigger.base.resolve_permissioned_as(authed);
let filters = trigger
@@ -237,7 +224,7 @@ impl TriggerCrud for WebsocketTrigger {
path: &str,
trigger: TriggerData<Self::TriggerConfigRequest>,
) -> Result<()> {
check_secondary_runnable_scopes(authed, &trigger.config)?;
check_secondary_runnables_parse(&trigger.config)?;
let resolved_edited_by = trigger.base.resolve_edited_by(authed);
let resolved_permissioned_as = trigger.base.resolve_permissioned_as(authed);
let filters = trigger
+3 -2
View File
@@ -13,8 +13,7 @@ use sql_builder::{bind::Bind, SqlBuilder};
use sqlx::{FromRow, PgConnection};
use std::fmt::Debug;
use windmill_api_auth::{
build_scope_path_predicate, check_scopes,
composed::check_new_hub_paths,
build_scope_path_predicate, check_run_scopes, check_scopes, composed::check_new_hub_paths,
ApiAuthed,
};
use windmill_common::{
@@ -597,6 +596,7 @@ async fn create_trigger<T: TriggerCrud>(
.validate_new(&db, &workspace_id, &new_trigger.config)
.await?;
let new = trigger_save_runnables::<T>(&new_trigger)?;
check_run_scopes(&authed, &new)?;
check_new_hub_paths(&new, &[], &authed, &db, &workspace_id).await?;
let mut tx = user_db.begin(&authed).await?;
@@ -872,6 +872,7 @@ async fn update_trigger<T: TriggerCrud>(
.validate_edit(&db, &workspace_id, &edit_trigger.config, path)
.await?;
let new_runnables = trigger_save_runnables::<T>(&edit_trigger)?;
check_run_scopes(&authed, &new_runnables)?;
let mut tx = user_db.begin(&authed).await?;
+19
View File
@@ -136,6 +136,13 @@ pub enum BranchChosen {
pub struct Approval {
pub resume_id: u16,
pub approver: String,
/// Kept on the step because the resume rows that also record it are deleted with the run.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub approved_at: Option<chrono::DateTime<chrono::Utc>>,
/// False for a rejection the flow continued past (`continue_on_disapprove_timeout`): the
/// step succeeds and lists who rejected it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub approved: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@@ -210,6 +217,7 @@ struct UntaggedFlowStatusModule {
type_: String,
id: Option<String>,
count: Option<u16>,
home: Option<HomeListing>,
progress: Option<u8>,
job: Option<Uuid>,
iterator: Option<Iterator>,
@@ -266,6 +274,12 @@ pub enum AgentAction {
},
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HomeListing {
#[serde(skip_serializing_if = "Option::is_none")]
pub step_summary: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ApprovalCall {
pub function_name: String,
@@ -282,6 +296,10 @@ pub enum FlowStatusModule {
id: String,
count: u16,
job: Uuid,
/// Set while waiting on an approval step with `show_on_home`, so the Home list of
/// approvals reads it here rather than in each run's flow definition.
#[serde(skip_serializing_if = "Option::is_none")]
home: Option<HomeListing>,
},
WaitingForExecutor {
id: String,
@@ -385,6 +403,7 @@ impl<'de> Deserialize<'de> for FlowStatusModule {
job: untagged
.job
.ok_or_else(|| serde::de::Error::missing_field("job"))?,
home: untagged.home,
}),
"WaitingForExecutor" => Ok(FlowStatusModule::WaitingForExecutor {
id: untagged
+4
View File
@@ -604,6 +604,10 @@ pub struct Suspend {
pub continue_on_disapprove_timeout: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub skin: Option<ApprovalSkin>,
/// Lists the waiting step on its approvers' Home. Off unless set: an approval announced
/// elsewhere (a resume link sent to a chat) would otherwise sit there unanswered.
#[serde(skip_serializing_if = "Option::is_none")]
pub show_on_home: Option<bool>,
}
/// How an approval request is presented, on the approval page and in Slack/Teams messages.
+40 -1
View File
@@ -12,6 +12,41 @@ use std::path::PathBuf;
pub const MAX_VOLUMES_PER_JOB: usize = 10;
/// Object requests a pull or a sync-back keeps in flight for one volume.
pub const VOLUME_TRANSFER_CONCURRENCY: usize = 16;
/// An upload holds its whole file in memory, so a sync-back bounds the bytes of the uploads in
/// flight as well as their count: a file at least this large is uploaded alone.
pub const VOLUME_UPLOAD_BYTES_IN_FLIGHT: u64 = 256 * 1024 * 1024;
/// Deletes `paths` concurrently, an object already gone counting as deleted. Returns how many
/// were deleted, or the first failure and how many failed: a delete is never assumed to succeed.
pub async fn delete_objects(
client: &dyn object_store::ObjectStore,
paths: Vec<object_store::path::Path>,
) -> Result<usize, String> {
use futures::StreamExt;
let results: Vec<Result<(), String>> = futures::stream::iter(paths)
.map(|path| async move {
match client.delete(&path).await {
Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
Err(e) => Err(format!("{path}: {e}")),
}
})
.buffer_unordered(VOLUME_TRANSFER_CONCURRENCY)
.collect()
.await;
let total = results.len();
let failures: Vec<String> = results.into_iter().filter_map(Result::err).collect();
match failures.first() {
None => Ok(total),
Some(first) => Err(format!(
"failed to delete {} of {total} removed file(s), first: {first}",
failures.len()
)),
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEntry {
pub size: u64,
@@ -25,7 +60,10 @@ pub struct FileEntry {
pub fn compute_md5_hex(data: &[u8]) -> String {
use md5::{Digest, Md5};
let result = Md5::digest(data);
md5_digest_hex(&Md5::digest(data))
}
pub fn md5_digest_hex(result: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut hex = String::with_capacity(32);
for &b in result.iter() {
@@ -112,6 +150,7 @@ pub struct SyncStats {
pub file_count: usize,
pub uploaded: usize,
pub skipped: usize,
pub deleted: usize,
}
pub fn validate_volume_name(name: &str) -> Result<(), String> {
@@ -3,6 +3,7 @@ pub(crate) use crate::volume_ee::*;
#[cfg(not(feature = "private"))]
#[cfg(feature = "parquet")]
#[derive(Default)]
pub(crate) struct LeaseRenewalGuard(pub Option<tokio::task::JoinHandle<()>>);
#[cfg(not(feature = "private"))]
@@ -94,6 +95,7 @@ pub(crate) async fn sync_volumes_sql_worker(
_worker_name: &str,
_conn: &windmill_common::worker::Connection,
_job_succeeded: bool,
_lease_renewal: LeaseRenewalGuard,
) {
}
@@ -108,5 +110,6 @@ pub(crate) async fn sync_volumes_http_worker(
_worker_name: &str,
_conn: &windmill_common::worker::Connection,
_job_succeeded: bool,
_lease_renewal: LeaseRenewalGuard,
) {
}
+20 -20
View File
@@ -7072,7 +7072,7 @@ mount {{
states: Vec::new(),
writable: Vec::new(),
client: None,
lease_renewal: crate::volume_oss::LeaseRenewalGuard(None),
lease_renewal: Default::default(),
};
#[cfg(feature = "parquet")]
@@ -7617,11 +7617,9 @@ mount {{
// Volume sync-back and lease release
#[cfg(feature = "parquet")]
if !volume_setup.states.is_empty() {
// Stop lease renewal before sync-back
volume_setup.lease_renewal.0.take().map(|h| h.abort());
if let Some(ref vol_client) = volume_setup.client {
if let Connection::Sql(db) = conn {
let lease_renewal = std::mem::take(&mut volume_setup.lease_renewal);
match (conn, volume_setup.client.as_ref()) {
(Connection::Sql(db), Some(vol_client)) => {
Box::pin(crate::volume_oss::sync_volumes_sql_worker(
&volume_setup.states,
&volume_setup.writable,
@@ -7632,23 +7630,25 @@ mount {{
worker_name,
conn,
result.is_ok(),
lease_renewal,
))
.await;
}
}
if let Connection::Http(http) = conn {
Box::pin(crate::volume_oss::sync_volumes_http_worker(
&volume_setup.states,
&volume_setup.writable,
http,
&job.workspace_id,
job.id,
worker_name,
conn,
result.is_ok(),
))
.await;
(Connection::Http(http), _) => {
Box::pin(crate::volume_oss::sync_volumes_http_worker(
&volume_setup.states,
&volume_setup.writable,
http,
&job.workspace_id,
job.id,
worker_name,
conn,
result.is_ok(),
lease_renewal,
))
.await;
}
(Connection::Sql(_), None) => {}
}
// Clean up absolute-path symlinks created by setup_volume_mount_paths
+16 -4
View File
@@ -41,7 +41,8 @@ use windmill_common::db::Authed;
use windmill_common::flow_conversations::{add_message_to_conversation_tx, MessageType};
use windmill_common::flow_status::{
ApprovalConditions, ContinuedOnError, FlowJobDuration, FlowJobsDuration,
FlowStatusModuleWParent, Iterator as FlowIterator, JobResult, MAX_CONTINUED_ON_ERROR,
FlowStatusModuleWParent, HomeListing, Iterator as FlowIterator, JobResult,
MAX_CONTINUED_ON_ERROR,
};
use windmill_common::flows::{add_virtual_items_if_necessary, Branch, FlowNodeId, StopAfterIf};
use windmill_common::jobs::{
@@ -3600,6 +3601,7 @@ pub struct ResumeRow {
pub approver: Option<String>,
pub approved: bool,
pub resume_id: i32,
pub created_at: chrono::DateTime<chrono::Utc>,
}
impl ResumeRow {
@@ -4195,7 +4197,7 @@ async fn push_next_flow_job(
// Query for both step-level resumes (job = step_id) and flow-level resumes (job = flow_id)
// Flow-level resumes allow pre-approvals that can be consumed by any suspend step
let resumes = sqlx::query_as::<_, ResumeRow>(
"SELECT value, approver, resume_id, approved FROM resume_job WHERE job = $1 OR job = $2 ORDER BY created_at ASC",
"SELECT value, approver, resume_id, approved, created_at FROM resume_job WHERE job = $1 OR job = $2 ORDER BY created_at ASC",
)
.bind(last)
.bind(flow_job.id)
@@ -4356,7 +4358,9 @@ async fn push_next_flow_job(
resume_id: r.resume_id as u16,
approver: r
.approver.clone()
.unwrap_or_else(|| "unknown".to_string())
.unwrap_or_else(|| "unknown".to_string()),
approved_at: Some(r.created_at),
approved: Some(r.approved),
})
.collect::<Vec<_>>()
),
@@ -4399,7 +4403,14 @@ async fn push_next_flow_job(
json!(FlowStatusModule::WaitingForEvents {
id: status_module.id(),
count: required_events,
job: last
job: last,
home: (suspend.show_on_home == Some(true)).then(|| HomeListing {
step_summary: usize::try_from(status.step - 1)
.ok()
.and_then(|i| flow.modules.get(i))
.and_then(|m| m.summary.clone())
.filter(|s| !s.is_empty()),
}),
}),
(required_events.saturating_sub(resume_messages.len() as u16)) as i32,
Duration::from_secs(
@@ -7574,6 +7585,7 @@ mod tests {
approver: Some("ann".to_string()),
approved: false,
resume_id: 0,
created_at: chrono::Utc::now(),
};
assert_eq!(
denial(json!({"reason": " too risky "})).disapproval_error(),
+1 -1
View File
@@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts";
import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts";
import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts";
export const VERSION = "v1.884.1";
export const VERSION = "v1.885.0";
export async function login(email: string, password: string): Promise<string> {
return await windmill.UserService.login({
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@windmill-labs/chat-sdk",
"version": "1.884.1",
"version": "1.885.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@windmill-labs/chat-sdk",
"version": "1.884.1",
"version": "1.885.0",
"license": "Apache-2.0",
"devDependencies": {
"@ai-sdk/react": "^4.0.102",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@windmill-labs/chat-sdk",
"description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app",
"version": "1.884.1",
"version": "1.885.0",
"author": "Ruben Fiszel",
"license": "Apache-2.0",
"homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme",
@@ -1,7 +1,8 @@
import { Command } from "@cliffy/command";
import { Confirm } from "@cliffy/prompt/confirm";
import { colors } from "@cliffy/ansi/colors";
import { sep as SEP } from "node:path";
import { readdir, stat } from "node:fs/promises";
import { join, sep as SEP } from "node:path";
import { GlobalOptions, isDatatableMigrationPath } from "../../types.ts";
import { isFileResource, isFilesetResource } from "../../utils/utils.ts";
import { SyncOptions, mergeConfigWithConfigFile } from "../../core/conf.ts";
@@ -412,6 +413,29 @@ export async function rehashOnly(
return counts;
}
/**
* Whether `target` (a file, or any file under a folder) is dropped by the
* includes/excludes alone: `ignore` also drops every file that is not a
* Windmill item, which `unfiltered` (built without those rules) drops too.
*/
async function isFilteredByIncludes(
target: string,
ignore: (p: string, isD: boolean) => boolean,
unfiltered: (p: string, isD: boolean) => boolean,
): Promise<boolean> {
const native = target.replaceAll("/", SEP);
const filtered = (p: string) => ignore(p, false) && !unfiltered(p, false);
let info;
try {
info = await stat(native);
} catch {
return false;
}
if (!info.isDirectory()) return filtered(native);
const entries = await readdir(native, { recursive: true, withFileTypes: true });
return entries.some((e) => e.isFile() && filtered(join(e.parentPath, e.name)));
}
/**
* Normalize the tree's shared lockfiles, unless the run asked to stay inside one
* folder: shared lockfiles are workspace-wide, so the pass reads and rewrites
@@ -473,6 +497,18 @@ export async function generateMetadata(
if (folder === "") {
folder = undefined;
}
// Normalize to forward slashes (Windows users may use backslashes) and strip
// a trailing slash to match deprecated flow/app handler behavior
folder = folder?.replaceAll("\\", "/").replace(/\/$/, "");
// Strip file extension if user passed a specific file path (e.g. f/test/script.ts)
const folderNoExt = folder?.replace(/\.[^/.]+$/, "");
const isPathInFolder = (p: string) =>
folder !== undefined &&
(p.startsWith(folder + "/") || p === folder || p === folderNoExt);
let walkedInFolder = false;
const noteWalked = (p: string) => {
if (isPathInFolder(p.replaceAll("\\", "/"))) walkedInFolder = true;
};
const workspace = await resolveWorkspace(opts);
await requireLogin(opts);
@@ -506,6 +542,10 @@ export async function generateMetadata(
// === Collect stale scripts ===
if (!skipScripts) {
for (const e of await walkLocalScripts(codebases, ignore)) {
// A file target (`f/x/task.deno.ts`, `f/x/task__mod/script.ts`) matches the
// local path, a folder target the remote one.
noteWalked(e);
noteWalked(scriptPathToRemotePath(e));
await generateScriptMetadataInternal(
e,
workspace,
@@ -523,6 +563,7 @@ export async function generateMetadata(
// === Collect stale flows ===
if (!skipFlows) {
for (const flowFolder of await walkLocalFlowFolders(ignore)) {
noteWalked(flowFolder);
await generateFlowLockInternal(
flowFolder,
true, // dryRun - populate tree
@@ -538,6 +579,7 @@ export async function generateMetadata(
// === Collect stale apps ===
if (!skipApps) {
for (const { folder: appFolder, rawApp } of await walkLocalAppItems(ignore)) {
noteWalked(appFolder);
await generateAppLocksInternal(
appFolder,
rawApp,
@@ -551,6 +593,27 @@ export async function generateMetadata(
}
}
// Tree nodes also cover workspace dependency files, which the walk never lists.
if (folder && !walkedInFolder && ![...tree.allPaths()].some(isPathInFolder)) {
const unfiltered = await ignoreF({
...opts, includes: undefined, excludes: undefined, extraIncludes: undefined,
});
if (await isFilteredByIncludes(folder, ignore, unfiltered)) {
const pattern = (await stat(folder.replaceAll("/", SEP))).isDirectory()
? `${folder}/**`
: folder;
log.warn(colors.yellow(
`Nothing under "${folder}" was checked: the includes/excludes in effect (wmill.yaml or -i/-e) filter it out. ` +
`Pass --includes "${pattern}" to check it, after removing any excludes that match it.`
));
} else {
log.warn(colors.yellow(`No scripts, flows or apps to check under "${folder}".`));
}
// Same reason as the up-to-date path below: the conversion still applies.
await maybeDedupeLockfiles(opts, workspace, codebases, ignore, rawWorkspaceDependencies, tree, folder);
return;
}
// === Propagate staleness through imports ===
tree.propagateStaleness();
@@ -597,14 +660,6 @@ export async function generateMetadata(
// === Filter by folder if specified ===
let filteredItems = staleItems;
if (folder) {
// Normalize to forward slashes (Windows users may use backslashes)
folder = folder.replaceAll("\\", "/");
// Strip trailing slash to match deprecated flow/app handler behavior
if (folder.endsWith("/")) {
folder = folder.substring(0, folder.length - 1);
}
// Strip file extension if user passed a specific file path (e.g. f/test/script.ts)
const folderNoExt = folder.replace(/\.[^/.]+$/, "");
// Check if an item is inside the specified folder
const isInsideFolder = (item: StaleItem) => {
const normalizedFolder = item.folder.replaceAll("\\", "/");
@@ -612,7 +667,6 @@ export async function generateMetadata(
return normalizedFolder === folder || normalizedFolder.startsWith(folder + "/")
|| normalizedPath === folder || normalizedPath === folderNoExt;
};
const isPathInFolder = (p: string) => p.startsWith(folder + "/") || p === folder || p === folderNoExt;
// Check if a tree path or any of its transitive deps is inside the folder
const touchesFolder = (treePath: string) => {
if (isPathInFolder(treePath)) return true;
+1
View File
@@ -54,6 +54,7 @@ export async function pull(opts: GlobalOptions) {
if (hubBaseUrl !== DEFAULT_HUB_BASE_URL) {
const hubSecret = (await wmill.getGlobal({
key: "hub_api_secret",
dangerouslyRevealSecrets: true,
})) as string | undefined;
log.info("Fetching resource types from private hub: " + hubBaseUrl);
if (hubSecret) {
+38 -15
View File
@@ -38,6 +38,7 @@ import {
pullInstanceSettings,
pushInstanceConfigs,
pushInstanceSettings,
REDACTED_SECRET_PREFIX,
type SimplifiedSettings,
} from "../../core/settings.ts";
import { deepEqual, readTextFile } from "../../utils/utils.ts";
@@ -183,6 +184,7 @@ export type InstanceSyncOptions = {
yes?: boolean;
prefix?: string;
prefixSettings?: boolean;
showSecrets?: boolean;
};
export async function pickInstance(
@@ -667,25 +669,42 @@ export async function getActiveInstance(opts: {
async function getConfig(opts: InstanceSyncOptions & { outputFile?: string; showSecrets?: boolean }) {
await pickInstance(opts, false);
const config = await wmill.getInstanceConfig() as any;
// In interactive mode, mask secrets by default and prompt
const hasSecrets = config?.global_settings?.license_key || config?.global_settings?.jwt_secret;
let showSecrets = opts.showSecrets ?? false;
if (!showSecrets && hasSecrets && process.stdout.isTTY && !opts.outputFile) {
log.warn("Config contains sensitive fields (license_key, jwt_secret). They are masked by default.");
log.warn("Use --show-secrets to include them, or press Y to show them now.");
showSecrets = await Confirm.prompt({ message: "Show secrets?", default: false });
} else if (!process.stdout.isTTY || opts.outputFile) {
// Non-interactive or writing to file: always include secrets
showSecrets = true;
}
let config = await wmill.getInstanceConfig({ dangerouslyRevealSecrets: showSecrets }) as any;
if (!showSecrets && config?.global_settings) {
const settings = config?.global_settings ?? {};
const serverRedacted = JSON.stringify(settings).includes(REDACTED_SECRET_PREFIX);
// A server without redaction ignores the parameter and returns its secrets in clear.
const clearFromOlderServer =
!showSecrets && !serverRedacted && Boolean(settings.license_key || settings.jwt_secret);
const interactive = process.stdout.isTTY && !opts.outputFile;
// Masking such an export is only safe on screen: applied back, that server would store the mask.
if (clearFromOlderServer && !interactive) {
throw new Error(
"This server does not redact secrets, so a redacted export would overwrite them when applied back. Pass --show-secrets to export them."
);
}
const redacted = !showSecrets && (serverRedacted || clearFromOlderServer);
if (redacted && interactive) {
log.warn(
clearFromOlderServer
? "Config contains sensitive fields (license_key, jwt_secret). They are masked by default. Use --show-secrets to include them, or press Y to show them now."
: "Secrets (license key, passwords, tokens) are redacted. Use --show-secrets to include them, or press Y to show them now."
);
showSecrets = await Confirm.prompt({ message: "Show secrets?", default: false });
if (showSecrets) {
config = await wmill.getInstanceConfig({ dangerouslyRevealSecrets: true }) as any;
}
} else if (redacted) {
log.infoStderr(
"Secrets are redacted: pass --show-secrets to include them. Pushing this export back keeps the stored secrets, but it cannot set up another instance."
);
}
if (!showSecrets && clearFromOlderServer) {
if (config.global_settings.license_key) config.global_settings.license_key = "***";
if (config.global_settings.jwt_secret) config.global_settings.jwt_secret = "***";
}
if (config?.global_settings && !config.global_settings.jwt_secret) {
if (showSecrets && config?.global_settings && !config.global_settings.jwt_secret) {
log.infoStderr(
"jwt_secret, rsa_keys and the instance database secrets are not part of the export: the server withholds them (EXPORT_SERVER_SECRETS=false). This export cannot fully restore or migrate the instance."
);
@@ -778,6 +797,10 @@ const command = new Command()
.option("--dry-run", "Perform a dry run without making changes")
.option("--skip-users", "Skip pulling users")
.option("--skip-settings", "Skip pulling settings")
.option(
"--show-secrets",
"Pull secrets (license key, passwords, tokens) in clear instead of redacted",
)
.option("--skip-configs", "Skip pulling configs (worker groups)")
.option("--skip-groups", "Skip pulling instance groups")
.option("--include-workspaces", "Also pull workspaces")
@@ -826,7 +849,7 @@ const command = new Command()
.command("get-config")
.description("Dump the current instance config (global settings + worker configs) as YAML")
.option("-o, --output-file <file:string>", "Write YAML to a file instead of stdout")
.option("--show-secrets", "Include sensitive fields (license key, JWT secret) without prompting")
.option("--show-secrets", "Include secrets (license key, passwords, tokens) in clear without prompting")
.option(
"--instance <instance:string>",
"Name of the instance, override the active instance",
+1 -1
View File
@@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork";
// (e.g. utils.ts) can read it without importing main.ts and creating a circular
// dependency (main → workspace → utils → main) that triggers a TDZ.
// Re-exported from main.ts for backwards compatibility.
export const VERSION = "1.884.1";
export const VERSION = "1.885.0";
+79 -4
View File
@@ -103,6 +103,60 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [
* so a file that still carries one must not show as differing from the workspace. */
export const RETIRED_SETTINGS = ["guest_access_enabled"] as const;
/** How the server's settings reads begin a secret they withheld (without `dangerouslyRevealSecrets`). */
export const REDACTED_SECRET_PREFIX = "__REDACTED__";
function keepUnchangedLocalSecrets(redacted: any, revealed: any, local: any): any {
if (typeof redacted === "string" && redacted.startsWith(REDACTED_SECRET_PREFIX)) {
return local !== undefined && deepEqual(local, revealed) ? local : redacted;
}
if (Array.isArray(redacted)) {
return redacted.map((v, i) =>
keepUnchangedLocalSecrets(v, revealed?.[i], local?.[i])
);
}
if (redacted && typeof redacted === "object") {
return Object.fromEntries(
Object.entries(redacted).map(([k, v]) => [
k,
keepUnchangedLocalSecrets(v, revealed?.[k], local?.[k]),
])
);
}
return redacted;
}
/**
* The remote settings as pull and push compare them with the local file. Unless
* `showSecrets`, a remote secret stays redacted, except where the local file already holds
* that same value: comparing against the redacted value alone would flag every secret as
* changed on each sync, while the revealed one must not reach the printed diff or the file.
*/
async function remoteSettingsAgainstLocal(
opts: InstanceSyncOptions,
readLocal: () => Promise<GlobalSetting[]>
): Promise<GlobalSetting[]> {
if (opts.showSecrets) {
return await wmill.listGlobalSettings({ dangerouslyRevealSecrets: true });
}
const redacted = await wmill.listGlobalSettings();
if (!JSON.stringify(redacted).includes(REDACTED_SECRET_PREFIX)) {
return redacted;
}
const revealed = await wmill.listGlobalSettings({
dangerouslyRevealSecrets: true,
});
const local = await readLocal();
return redacted.map((s) => ({
...s,
value: keepUnchangedLocalSecrets(
s.value,
revealed.find((r) => r.name === s.name)?.value,
local.find((l) => l.name === s.name)?.value
),
}));
}
// Legacy settings interface for reading old settings.yaml files
interface LegacySimplifiedSettings {
auto_invite_enabled?: boolean;
@@ -708,7 +762,10 @@ export async function pushWorkspaceKey(
}
}
export async function readInstanceSettings(opts: InstanceSyncOptions) {
export async function readInstanceSettings(
opts: InstanceSyncOptions,
silent = false
) {
let localSettings: GlobalSetting[] = [];
await checkInstanceSettingsPath(opts);
@@ -718,7 +775,7 @@ export async function readInstanceSettings(opts: InstanceSyncOptions) {
instanceSettingsPath
)) as GlobalSetting[];
} catch {
log.warn(`No ${instanceSettingsPath} found`);
if (!silent) log.warn(`No ${instanceSettingsPath} found`);
}
return localSettings;
}
@@ -781,7 +838,22 @@ export async function pullInstanceSettings(
opts: InstanceSyncOptions,
preview = false
) {
const remoteSettings = await wmill.listGlobalSettings();
const remoteSettings = await remoteSettingsAgainstLocal(
opts,
async () =>
await processInstanceSettings(
await readInstanceSettings(opts, true),
"decode"
)
);
if (
!preview &&
JSON.stringify(remoteSettings).includes(REDACTED_SECRET_PREFIX)
) {
log.info(
"Secrets are redacted in the pulled settings: pass --show-secrets to include them. Pushing them back keeps the stored secrets."
);
}
await checkInstanceSettingsPath(opts);
@@ -818,9 +890,12 @@ export async function pushInstanceSettings(
opts: InstanceSyncOptions,
preview: boolean = false
) {
const remoteSettings = await wmill.listGlobalSettings();
let localSettings: GlobalSetting[] = await readInstanceSettings(opts);
localSettings = await processInstanceSettings(localSettings, "decode");
const remoteSettings = await remoteSettingsAgainstLocal(
opts,
async () => localSettings
);
if (opts.baseUrl) {
localSettings = localSettings.filter((s) => s.name !== "base_url");
+4 -3
View File
File diff suppressed because one or more lines are too long
+39 -22
View File
@@ -229,12 +229,15 @@ export async function generateScriptMetadataInternal(
// the metadata sync actually reads untouched.
const metadataInFolder = isFolderLayout && language !== "dbt";
// For folder layout, parseMetadataFile is called with remotePath which
// will find __mod/script.yaml via the folder layout fallback
const metadataWithType = await parseMetadataFile(
remotePath,
undefined,
);
// A tree run's dry pass only detects staleness; it must not create missing
// metadata, or a folder-scoped run writes files for every script it walks.
// A script without metadata is stale, and the generation pass creates it.
const detectOnly = tree !== undefined && dryRun && !opts.rehashOnly;
// For folder layout, the lookup uses remotePath, which finds
// __mod/script.yaml via the folder layout fallback
const existingMetadata = detectOnly
? await findMetadataFile(remotePath)
: await parseMetadataFile(remotePath, undefined);
// read script content — a dbt project's descriptor is optional, and absent
// means an empty descriptor rather than a script that cannot be pushed.
@@ -242,7 +245,9 @@ export async function generateScriptMetadataInternal(
if (isMissingDbtDescriptor(scriptPath, e)) return "";
throw e;
});
const metadataContent = await readTextFile(metadataWithType.path);
const metadataContent = existingMetadata
? await readTextFile(existingMetadata.path)
: "";
const filteredRawWorkspaceDependencies = filterWorkspaceDependencies(
rawWorkspaceDependencies,
@@ -306,7 +311,8 @@ export async function generateScriptMetadataInternal(
}
// Use checkHash (includes module hashes) so module changes are detected as stale
const isDirectlyStale = !(await checkifMetadataUptodate(remotePath, checkHash, conf, checkSubpath));
const isDirectlyStale = !existingMetadata ||
!(await checkifMetadataUptodate(remotePath, checkHash, conf, checkSubpath));
// Tree-based dependency tracking
if (tree) {
@@ -347,6 +353,9 @@ export async function generateScriptMetadataInternal(
log.info(colors.gray(`Generating metadata for ${scriptPath}`));
}
const metadataWithType = existingMetadata ??
(await parseMetadataFile(remotePath, undefined));
const metadataParsedContent = metadataWithType?.payload as Record<
string,
any
@@ -1088,18 +1097,10 @@ export async function parseMetadataFileIfExists(
}
}
export async function parseMetadataFile(
scriptPath: string,
generateMetadataIfMissing:
| (GlobalOptions & {
path: string;
workspaceRemote: Workspace;
schemaOnly?: boolean;
rawWorkspaceDependencies: Record<string, string>;
codebases: SyncCodebase[]
})
| undefined
): Promise<{ isJson: boolean; payload: any; path: string }> {
/** The script's metadata file, flat or folder layout, or undefined when it has none. */
async function findMetadataFile(
scriptPath: string
): Promise<{ isJson: boolean; payload: any; path: string } | undefined> {
let metadataFilePath = scriptPath + ".script.json";
try {
await stat(metadataFilePath);
@@ -1143,13 +1144,29 @@ export async function parseMetadataFile(
isJson: false,
};
} catch {
// fall through to create metadata
return undefined;
}
}
}
}
}
export async function parseMetadataFile(
scriptPath: string,
generateMetadataIfMissing:
| (GlobalOptions & {
path: string;
workspaceRemote: Workspace;
schemaOnly?: boolean;
rawWorkspaceDependencies: Record<string, string>;
codebases: SyncCodebase[]
})
| undefined
): Promise<{ isJson: boolean; payload: any; path: string }> {
const existing = await findMetadataFile(scriptPath);
if (existing) return existing;
// no metadata file at all. Create it
metadataFilePath = scriptPath + ".script.yaml";
const metadataFilePath = scriptPath + ".script.yaml";
log.info(
(await blueColor())(
`Creating script metadata file for ${metadataFilePath}`
+55 -2
View File
@@ -595,7 +595,7 @@ describe("generate-metadata folder argument", () => {
});
});
test("non-existent folder shows up-to-date", async () => {
test("non-existent folder says nothing was found", async () => {
await withTestBackend(async (backend, tempDir) => {
await setupWorkspace(backend, tempDir, "nonexistent_folder_test");
@@ -609,7 +609,60 @@ describe("generate-metadata folder argument", () => {
);
expect(result.code).toEqual(0);
expect(result.stdout).toContain("up-to-date");
const output = result.stdout + result.stderr;
expect(output).toContain('No scripts, flows or apps to check under "f/does_not_exist"');
expect(output).not.toContain("up-to-date");
});
});
test("--strict-folder-boundaries creates no metadata outside the folder", async () => {
await withTestBackend(async (backend, tempDir) => {
await setupWorkspace(backend, tempDir, "strict_missing_metadata_test");
await createLocalScript(tempDir, "f/panel", "edited");
// Scripts kept without metadata on purpose, outside the folder
await mkdir(`${tempDir}/f/starbase`, { recursive: true });
await writeFile(
`${tempDir}/f/starbase/bare.ts`,
`export async function main() {\n return 1;\n}\n`,
"utf-8"
);
const result = await backend.runCLICommand(
["generate-metadata", "--yes", "f/panel", "--strict-folder-boundaries"],
tempDir,
"strict_missing_metadata_test"
);
expect(result.code).toEqual(0);
expect(result.stdout + result.stderr).toContain("f/panel/edited");
await expect(stat(`${tempDir}/f/starbase/bare.script.yaml`)).rejects.toThrow();
await expect(stat(`${tempDir}/f/starbase/bare.script.lock`)).rejects.toThrow();
const lockfile = await readFile(`${tempDir}/wmill-lock.yaml`, "utf-8");
expect(lockfile).toContain("f/panel/edited");
});
});
test("folder outside the includes says it was not checked", async () => {
await withTestBackend(async (backend, tempDir) => {
await setupWorkspace(backend, tempDir, "folder_outside_includes_test");
await writeFile(`${tempDir}/wmill.yaml`, `defaultTs: bun
includes:
- "f/starbase/**"
excludes: []`, "utf-8");
await createLocalScript(tempDir, "f/panel", "edited");
const result = await backend.runCLICommand(
["generate-metadata", "--yes", "f/panel"],
tempDir,
"folder_outside_includes_test"
);
expect(result.code).toEqual(0);
const output = result.stdout + result.stderr;
expect(output).toContain('Nothing under "f/panel" was checked');
expect(output).not.toContain("up-to-date");
});
});
});
+23
View File
@@ -164,6 +164,18 @@ Symbols, not line numbers, are cited: they drift less.
reset require `login_type = 'password'`; `set_password` also accepts `pending_oauth` and turns
the account into a `password` one in the same statement (an account created ahead of its owner
gets its first credential that way, or through the OAuth claim below).
- **`RequireSso` protection rule** (workspace-level, `check_new_member_sso` /
`check_password_login_allowed` in `windmill-common/src/workspaces.rs`): a `password` account
held by it (not a service account, not a bypasser by username or group, admins included) cannot
join the workspace, and no member it holds can become a `password` account. It gates both
transitions, never sign-in: password members already in the workspace keep logging in, which only
the instance's `disable_password_login` stops. A new path that seats a member or writes
`login_type = 'password'` (or a password on a `pending_oauth` account) must call the matching
check in the transaction that writes. The two checks take no lock, so a join and a password
switch of the same account at the same instant can both pass; the automatic joins (domain auto-add and auto-invite,
instance groups) skip the user instead of failing, and a git sync pull into a fork fails rather
than seat a held sync identity. The
superadmin instance import (`POST /users/overwrite`) restores accounts as given, unchecked.
- **Login links** (`login_link` table, `POST /users/login_links` superadmin-only,
`GET /auth/login_link/{token}` unauthenticated): single-use, ≤15 min, a session cookie and a
302 to a same-origin `rd`. `require_login_type` on the mint refuses (409) an account whose
@@ -220,3 +232,14 @@ Symbols, not line numbers, are cited: they drift less.
profile routes are cloud-gated; for the rest, cloud only adds quotas.
- **`CREATE_WORKSPACE_REQUIRE_SUPERADMIN`** defaults to `true` when unset; only the literal
`"true"` enables it when set.
- **The client IP** (`windmill-common/src/client_ip.rs`, the `ClientIp` extractor) is the TCP
peer unless that peer is in `TRUSTED_PROXIES` (comma-separated CIDRs; unset means loopback,
private and link-local ranges; `none` trusts nothing). Behind a trusted peer, `X-Forwarded-For`
is read from the right up to the first untrusted hop, or, with `CLIENT_IP_HEADER` set, only that
header (`CloudFront-Viewer-Address`, `CF-Connecting-IP`, an nginx `X-Real-IP`). `X-Real-IP` is
never read implicitly: Caddy and most ingresses pass a client's own through. A CDN in front of
the load balancer (CloudFront on app.windmill.dev) needs `CLIENT_IP_HEADER` or its ranges in
`TRUSTED_PROXIES`, or its edge address is the client. The private-range default also trusts
job containers that can reach the server directly; such a deployment should list its proxy's
exact address. Only the main API server carries the peer: a router called without connect
info (tests, internal dispatch) sees `None`, and per-IP decisions skip or refuse it.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@windmill-labs/components",
"version": "1.884.1",
"version": "1.885.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@windmill-labs/components",
"version": "1.884.1",
"version": "1.885.0",
"hasInstallScript": true,
"license": "AGPL-3.0",
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@windmill-labs/components",
"version": "1.884.1",
"version": "1.885.0",
"scripts": {
"dev": "vite dev",
"dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev",
+63 -18
View File
@@ -15,10 +15,16 @@ import {
WorkspaceService
} from './gen'
import {
AI_REVIEW_MODEL_SETTING_NAME,
AI_REVIEW_PROVIDER_SETTING_NAME,
AI_REVIEW_REASONING_SETTING_NAME,
aiUserDisabled,
COPILOT_SESSION_MODEL_SETTING_NAME,
COPILOT_SESSION_PROVIDER_SETTING_NAME,
COPILOT_SESSION_REASONING_SETTING_NAME
COPILOT_SESSION_REASONING_SETTING_NAME,
SCRIPT_GEN_MODEL_SETTING_NAME,
SCRIPT_GEN_PROVIDER_SETTING_NAME,
SCRIPT_GEN_REASONING_SETTING_NAME
} from './stores'
import { getLocalSetting, storeLocalSetting } from './utils'
import {
@@ -28,20 +34,51 @@ import {
const USER_CUSTOM_PROMPTS_KEY = 'userCustomAIPrompts'
const sessionModel = getLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME)
const sessionProvider = getLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME)
const sessionReasoning = getLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME)
export const copilotSessionModel = writable<ReasoningProviderModel | undefined>(
sessionModel && sessionProvider
? {
// Strip the deprecated /thinking suffix on read; the default effort
// (resolved later) restores reasoning for migrated selections.
model: stripLegacyThinkingSuffix(sessionModel),
provider: sessionProvider as AIProvider,
...(sessionReasoning ? { reasoning: sessionReasoning } : {})
}
: undefined
)
type PickSettings = { model: string; provider: string; reasoning: string }
const LAST_PICK_SETTINGS: PickSettings = {
model: COPILOT_SESSION_MODEL_SETTING_NAME,
provider: COPILOT_SESSION_PROVIDER_SETTING_NAME,
reasoning: COPILOT_SESSION_REASONING_SETTING_NAME
}
const SCRIPT_GEN_PICK_SETTINGS: PickSettings = {
model: SCRIPT_GEN_MODEL_SETTING_NAME,
provider: SCRIPT_GEN_PROVIDER_SETTING_NAME,
reasoning: SCRIPT_GEN_REASONING_SETTING_NAME
}
const AI_REVIEW_PICK_SETTINGS: PickSettings = {
model: AI_REVIEW_MODEL_SETTING_NAME,
provider: AI_REVIEW_PROVIDER_SETTING_NAME,
reasoning: AI_REVIEW_REASONING_SETTING_NAME
}
function readStoredPick(settings: PickSettings): ReasoningProviderModel | undefined {
const model = getLocalSetting(settings.model)
const provider = getLocalSetting(settings.provider)
const reasoning = getLocalSetting(settings.reasoning)
if (!model || !provider) return undefined
return {
// Strip the deprecated /thinking suffix on read; the default effort
// (resolved later) restores reasoning for migrated selections.
model: stripLegacyThinkingSuffix(model),
provider: provider as AIProvider,
...(reasoning ? { reasoning } : {})
}
}
function storePick(settings: PickSettings, pick: ReasoningProviderModel) {
storeLocalSetting(settings.model, pick.model)
storeLocalSetting(settings.provider, pick.provider)
storeLocalSetting(settings.reasoning, pick.reasoning)
}
export const copilotSessionModel = writable(readStoredPick(LAST_PICK_SETTINGS))
// Script generation's own pick, which neither follows nor sets the last pick.
export const scriptGenModel = writable(readStoredPick(SCRIPT_GEN_PICK_SETTINGS))
// AI review's own pick outside a session; inside one, a review starts on the session's model.
export const aiReviewModel = writable(readStoredPick(AI_REVIEW_PICK_SETTINGS))
export type CopilotInfo = {
enabled: boolean
@@ -304,9 +341,17 @@ export function invalidateWorkspaceCopilotInfo(workspace?: string) {
* until it has one. */
export function setLastModelPick(model: ReasoningProviderModel) {
copilotSessionModel.set(model)
storeLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME, model.model)
storeLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME, model.provider)
storeLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME, model.reasoning)
storePick(LAST_PICK_SETTINGS, model)
}
export function setScriptGenModelPick(model: ReasoningProviderModel) {
scriptGenModel.set(model)
storePick(SCRIPT_GEN_PICK_SETTINGS, model)
}
export function setAiReviewModelPick(model: ReasoningProviderModel) {
aiReviewModel.set(model)
storePick(AI_REVIEW_PICK_SETTINGS, model)
}
// Leaves copilotSessionModel alone: the pick is shared with sessions in other workspaces, which may
+87 -73
View File
@@ -112,10 +112,12 @@
import { editorPositionMap } from '$lib/utils'
import { extToLang, langToExt } from '$lib/editorLangUtils'
import { aiChatManager, type AIChatManager } from './copilot/chat/AIChatManager.svelte'
import type { Selection } from 'monaco-editor'
import { canHavePreprocessor, getPreprocessorModuleCode } from '$lib/script_helpers'
import { setMonacoTypescriptOptions } from './monacoLanguagesOptions'
import { copilotInfo } from '$lib/aiStore'
import { createCodeSelection, type CodeSelection, type CodeSource } from './copilot/chat/context'
import { getOpenInSessionHandoff, withEditorFlush } from './sessions/openInSessionContext'
import { openSourceInSession } from './sessions/sessionSwitch.svelte'
import { getDbSchemas } from './apps/components/display/dbtable/metadata'
import { rawAppLintStore, type MonacoLintError } from './raw_apps/lintStore'
import { MarkerSeverity } from 'monaco-editor'
@@ -168,7 +170,10 @@
loadAsync?: boolean
key?: string | undefined
class?: string | undefined
moduleId?: string
/** The item an AI session is told the selected code belongs to. Unset for code of no item. */
codeSource?: CodeSource
/** The language an AI session is told the code is in, when `scriptLang` only colours it. */
codeSourceLang?: CodeSelection['lang']
enablePreprocessorSnippet?: boolean
/** When set, enables raw app lint collection mode and reports Monaco markers to the lint store under this key */
rawAppRunnableKey?: string | undefined
@@ -210,7 +215,8 @@
loadAsync = false,
key = undefined,
class: clazz = undefined,
moduleId = undefined,
codeSource = undefined,
codeSourceLang = undefined,
enablePreprocessorSnippet = false,
rawAppRunnableKey = undefined,
preparedAssetsSqlQueries,
@@ -282,6 +288,22 @@
const completionInfo = $derived(
sessionScopedChatManager ? sessionScopedChatManager.aiInfo : $copilotInfo
)
const sessionHandoff = getOpenInSessionHandoff()
const inIframe = BROWSER && window.self !== window.top
// The item's own hand-off: one of another kind is an outer editor's.
const handoffSource = $derived.by(() => {
if (!codeSource) return undefined
const source = sessionHandoff?.source(
codeSource.kind === 'flow' ? { moduleId: codeSource.part } : undefined
)
return source?.target?.kind === codeSource.kind ? source : undefined
})
// The path the item's draft is stored under, which the session's tools read it by.
const codePath = $derived(handoffSource?.target?.path || codeSource?.path)
// In a session, ⌘K goes to its chat instead.
const newSessionSource = $derived(
sessionScopedChatManager || inIframe || !$copilotInfo.enabled ? undefined : handoffSource
)
// let graphqlService: MonacoGraphQLAPI | undefined = undefined
let fetchedDbSchema: DBSchema | undefined = $state(undefined)
@@ -398,18 +420,56 @@
}
}
export function getSelectedLines(): string | undefined {
if (editor) {
const selection = editor.getSelection()
if (selection) {
const range: IRange = {
startLineNumber: selection.startLineNumber,
/** The selected lines, whole, or the cursor's line. */
function getCodeSelection(): CodeSelection | undefined {
const selection = editor?.getSelection()
const model = editor?.getModel()
if (!selection || !model || !codeSource || !codePath || !scriptLang) return undefined
const { startLineNumber: startLine, endLineNumber, endColumn } = selection
// A selection dragged to the start of a line holds none of it.
const endLine =
endColumn === 1 && endLineNumber > startLine ? endLineNumber - 1 : endLineNumber
return createCodeSelection(
{ ...codeSource, path: codePath },
{
startLine,
endLine,
content: model.getValueInRange({
startLineNumber: startLine,
startColumn: 1,
endLineNumber: selection.endLineNumber + 1,
endColumn: 1
}
return editor.getModel()?.getValueInRange(range)
endLineNumber: endLine,
endColumn: model.getLineMaxColumn(endLine)
}),
lang: codeSourceLang ?? (scriptLang as CodeSelection['lang'])
}
)
}
async function sendInlinePrompt(prompt: string): Promise<boolean> {
const selection = getCodeSelection()
if (!selection || !newSessionSource) return false
try {
await openSourceInSession(withEditorFlush(newSessionSource, flushPendingChanges), {
seedPrompt: prompt,
autoSend: true,
seedPick: selection
})
} catch (e) {
sendUserToast(e instanceof Error ? e.message : String(e), true)
return false
}
closeAIInlineWidget()
return true
}
/** Go to the session's chat, with the selected lines. Outside a session no chat is on screen. */
function attachSelectionToChat() {
if (!sessionScopedChatManager) return
const selection = editor?.getSelection()?.isEmpty() ? undefined : getCodeSelection()
if (selection) {
sessionScopedChatManager.attachCodeSelection(selection)
} else {
sessionScopedChatManager.focusInput()
}
}
@@ -982,8 +1042,6 @@
// Inline ai chat widget
let showInlineAIChat = $state(false)
let inlineAIChatSelection: Selection | null = $state(null)
let selectedCode = $state('')
export async function reviewAndApplyCode(code: string, opts?: ReviewChangesOpts) {
await aiChatEditorHandler?.reviewChanges(code, opts)
@@ -1618,9 +1676,6 @@
editor?.addCommand(KeyMod.CtrlCmd | KeyCode.DownArrow, function () {
if (aiChatManager.pendingNewCode) {
aiChatManager.scriptEditorApplyCode?.(aiChatManager.pendingNewCode)
if (showInlineAIChat) {
closeAIInlineWidget()
}
}
})
@@ -1649,35 +1704,16 @@
})
editor?.addCommand(KeyMod.CtrlCmd | KeyCode.KeyL, function () {
const selectedLines = getSelectedLines()
const selection = editor?.getSelection()
const hasSelection =
selection &&
(selection.startLineNumber !== selection.endLineNumber ||
selection.startColumn !== selection.endColumn)
// Only a session pane has a chat on screen to send the lines to.
const chat = sessionScopedChatManager
if (!chat) return
if (hasSelection && selectedLines) {
chat.addSelectedLinesToContext(
selectedLines,
selection.startLineNumber,
selection.endLineNumber,
moduleId
)
} else {
chat.focusInput()
}
// Monaco runs a command for whichever editor has focus, this one or not.
if (editor?.hasWidgetFocus()) attachSelectionToChat()
})
editor?.addCommand(KeyMod.CtrlCmd | KeyCode.KeyK, function () {
if ($copilotInfo.enabled) {
aiChatEditorHandler?.rejectAll()
if (showInlineAIChat) {
closeAIInlineWidget()
} else {
showAIInlineWidget()
}
if (!editor?.hasWidgetFocus()) return
if (newSessionSource) {
showInlineAIChat = !showInlineAIChat
} else {
attachSelectionToChat()
}
})
@@ -1896,30 +1932,10 @@
})
}
function showAIInlineWidget() {
if (!editor) return
inlineAIChatSelection = editor.getSelection()
if (!inlineAIChatSelection) {
return
}
const model = editor.getModel()
selectedCode = ''
if (model) {
selectedCode = model.getValueInRange(inlineAIChatSelection)
}
showInlineAIChat = true
aiChatInlineWidget?.focusInput()
}
function closeAIInlineWidget() {
showInlineAIChat = false
inlineAIChatSelection = null
selectedCode = ''
}
let aiChatInlineWidget: AIChatInlineWidget | null = $state(null)
$effect(() => {
const fontSize = small ? editorFontSize.small : editorFontSize.regular
if (editor) {
@@ -2008,9 +2024,6 @@
rejectCodeChanges()
} else if ((e.ctrlKey || e.metaKey) && e.key === 'ArrowDown' && aiChatManager.pendingNewCode) {
acceptCodeChanges()
if (showInlineAIChat) {
closeAIInlineWidget()
}
}
}
$effect(() => {
@@ -2250,14 +2263,15 @@
<GlobalReviewButtons onAcceptAll={acceptCodeChanges} onRejectAll={rejectCodeChanges} />
{/if}
{#if editor && $copilotInfo.enabled && aiChatEditorHandler}
{#if editor && showInlineAIChat && newSessionSource}
<AIChatInlineWidget
bind:this={aiChatInlineWidget}
bind:show={showInlineAIChat}
{editor}
editorHandler={aiChatEditorHandler}
selection={inlineAIChatSelection}
{selectedCode}
line={editor.getSelection()?.startLineNumber ?? 1}
onSend={sendInlinePrompt}
onClose={(refocus) => {
closeAIInlineWidget()
if (refocus) editor?.focus()
}}
/>
{/if}

Some files were not shown because too many files have changed in this diff Show More