merge: backend resource and profile settings
This commit is contained in:
commit
981f0501a3
|
|
@ -0,0 +1,3 @@
|
||||||
|
{"id":"orch-plan-20260708-104512-1","ticket_id":"00001KX0DSMPT","kind":"after","related_ticket":"00001KX0G06VA","note":"This Ticket is queued while `00001KX0G06VA` is inprogress because both touch Workspace/Backend profile/resource launch surfaces (`workspace-server` settings/API/hosts/server and profile archive/resource fetch integration). Sequence after the active resource-fetch implementation to avoid conflicting public API and ProfileSourceArchive authority-boundary changes.","author":"orchestrator","at":"2026-07-08T10:45:12Z"}
|
||||||
|
{"id":"orch-plan-20260708-104530-2","ticket_id":"00001KX0DSMPT","kind":"waiting_capacity_note","note":"Queue review after Dashboard authorization. The declared dependency `00001KWZ5KERY` is closed, so that blocker is resolved. However `00001KX0G06VA` is currently inprogress on branch `work/00001KX0G06VA-resource-fetch-api` and changes the same ProfileSourceArchive/resource/workspace-server launch API surfaces this Ticket needs to build on. Leave this Ticket queued until the active resource-fetch branch is reviewed/merged or its API shape is otherwise decided; then re-route/start from the updated orchestration branch.","author":"orchestrator","at":"2026-07-08T10:45:30Z"}
|
||||||
|
{"id":"orch-plan-20260708-115622-3","ticket_id":"00001KX0DSMPT","kind":"accepted_plan","accepted_plan":{"summary":"`00001KWZ5KERY` と `00001KX0G06VA` が closed/merged になり、previous waiting reason は解除された。Workspace/Profile editing API/pages を updated orchestration branch から実装開始する。","branch":"work/00001KX0DSMPT-workspace-profile-settings","worktree":"/home/hare/Projects/yoi/.worktree/00001KX0DSMPT-workspace-profile-settings","role_plan":"単一 sibling Coder Pod に implementation worktree を委譲し、Workspace/Profile settings scoped APIs、safe Profile registry/source read-write model、settings UI pages、Backend discovery invalidation、launch candidate integration、diagnostic/redaction tests を実装する。完了後、別 sibling Reviewer Pod で Ticket IntentPacket / ProfileSourceArchive/resource-fetch authority boundary / acceptance criteria に照らして read-only review する。"},"author":"orchestrator","at":"2026-07-08T11:56:22Z"}
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
---
|
---
|
||||||
title: 'Add Workspace settings API and pages for Workspace/Profile editing'
|
title: 'Add Workspace settings API and pages for Workspace/Profile editing'
|
||||||
state: 'queued'
|
state: 'closed'
|
||||||
created_at: '2026-07-08T08:34:01Z'
|
created_at: '2026-07-08T08:34:01Z'
|
||||||
updated_at: '2026-07-08T10:44:13Z'
|
updated_at: '2026-07-08T13:20:27Z'
|
||||||
assignee: null
|
assignee: null
|
||||||
queued_by: 'workspace-panel'
|
queued_by: 'workspace-panel'
|
||||||
queued_at: '2026-07-08T10:44:13Z'
|
queued_at: '2026-07-08T10:44:13Z'
|
||||||
|
|
|
||||||
33
.yoi/tickets/00001KX0DSMPT/resolution.md
Normal file
33
.yoi/tickets/00001KX0DSMPT/resolution.md
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
完了。
|
||||||
|
|
||||||
|
実装内容:
|
||||||
|
- Workspace/Profile settings scoped API を追加した。
|
||||||
|
- Workspace metadata read/update と safe identity/source summaries を扱う Settings API を追加した。
|
||||||
|
- Profile registry/source read/update API を追加し、create/update/delete と revision/etag-style optimistic checks を実装した。
|
||||||
|
- Backend profile settings model に safe source ids/display paths、Decodal/ProfileSourceArchive validation、selector uniqueness、path/symlink escape protection、source size checks、typed diagnostics を追加した。
|
||||||
|
- Profile updates 後に Backend profile discovery / validation / launch options を再構築し、Worker launch profile candidates と Settings profile list が同じ discovery result を使うようにした。
|
||||||
|
- invalid project profile は relevant profile summary に diagnostics を付与し、Worker launch candidates から除外し、candidate validation でも reject するようにした。
|
||||||
|
- Browser-facing responses/UI から host absolute paths、secret values、Runtime endpoints/tokens、socket/session paths、runtime-local store paths、archive content/digest、raw resource handles、backend-private paths を出さないようにした。
|
||||||
|
- Settings UI に Workspace overview と Profile list/source editor surface を追加した。
|
||||||
|
- Focused backend/web tests を追加/強化した。
|
||||||
|
|
||||||
|
主な commit / merge:
|
||||||
|
- implementation: `3eefd333 feat: add workspace profile settings`
|
||||||
|
- review fix: `0c2ca1ea fix: harden profile settings validation`
|
||||||
|
- merge into orchestration: `0bf3638c merge: workspace profile settings`
|
||||||
|
|
||||||
|
Review:
|
||||||
|
- 初回 external review は request_changes。
|
||||||
|
- follow-up external review は approve。merge-blocking issue なし。
|
||||||
|
|
||||||
|
Final validation in Orchestrator worktree:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(91 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
|
||||||
|
補足:
|
||||||
|
- implementation branch merge 時に Ticket record conflict が発生したため、Orchestrator 側の Ticket item/thread を保持して解決した。product/code changes は merge 済み。
|
||||||
|
|
@ -30,4 +30,352 @@ Marked ready by `yoi ticket state`.
|
||||||
Ticket を `workspace-panel` が queued にしました。
|
Ticket を `workspace-panel` が queued にしました。
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: decision author: orchestrator at: 2026-07-08T10:45:48Z -->
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Routing decision: blocked_by_dependency_or_missing_authority
|
||||||
|
|
||||||
|
Reason:
|
||||||
|
- Declared dependency `00001KWZ5KERY` is now closed, so the original Decodal/ProfileSourceArchive prerequisite is satisfied。
|
||||||
|
- However `00001KX0G06VA` is currently `inprogress` on branch `work/00001KX0G06VA-resource-fetch-api`。
|
||||||
|
- This Ticket’s Workspace/Profile editing API and pages need to build on the same profile/resource/workspace-server launch surfaces that `00001KX0G06VA` is actively changing(ProfileSourceArchive resource handling, workspace-server settings/API/hosts/server, Browser-facing profile launch configuration)。
|
||||||
|
- Starting this Ticket now would create a high-conflict parallel branch and risks designing Profile editing against the wrong resource-fetch/public API boundary。
|
||||||
|
- Therefore this routing pass leaves the Ticket queued and does not record `queued -> inprogress`, create a worktree, or spawn role Pods。
|
||||||
|
|
||||||
|
Evidence checked:
|
||||||
|
- Ticket body / thread / artifacts。
|
||||||
|
- `TicketRelationQuery(00001KX0DSMPT)`: depends_on `00001KWZ5KERY`; target is closed。
|
||||||
|
- `TicketOrchestrationPlanQuery(00001KX0DSMPT)`: prior record 0 件だったため、今回 `after 00001KX0G06VA` と waiting-capacity note を記録。
|
||||||
|
- `TicketList`: queued はこの Ticket 1件、inprogress は `00001KX0G06VA` 1件。
|
||||||
|
- Orchestrator worktree git status: clean on `orchestration`。
|
||||||
|
|
||||||
|
Next action:
|
||||||
|
- `00001KX0G06VA` の implementation/review/merge outcome を待つ。
|
||||||
|
- resource-fetch API shape が merge されたら、この Ticket を再 routing し、updated orchestration branch から start する。
|
||||||
|
|
||||||
|
Escalate if:
|
||||||
|
- 人間が `00001KX0G06VA` を中断してこの Ticket を先に実装する、または両者を同一 combined worktree で統合実装する方針に切り替えたい場合。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: decision author: orchestrator at: 2026-07-08T11:56:03Z -->
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Routing decision: implementation_ready
|
||||||
|
|
||||||
|
Reason:
|
||||||
|
- Previous waiting reason is resolved: `00001KX0G06VA` is now merged/validated/closed, so the ProfileSourceArchive resource-fetch API shape this Ticket depends on is stable enough to build against。
|
||||||
|
- Declared dependency `00001KWZ5KERY` is also closed, so Decodal Profile source model / ProfileSourceArchive boundary is available。
|
||||||
|
- Ticket body gives concrete Workspace/Profile settings API, read/write source model, UI routes, diagnostics, redaction invariants, and validation criteria。
|
||||||
|
- typed relation blocker is resolved (`depends_on 00001KWZ5KERY` target closed); no active inprogress Ticket remains。
|
||||||
|
- The user requested sequential consumption once no blocker remains, and the Dashboard queue authorization is already present。
|
||||||
|
|
||||||
|
Evidence checked:
|
||||||
|
- Ticket body / thread / artifacts。
|
||||||
|
- `TicketRelationQuery(00001KX0DSMPT)`: outgoing `depends_on 00001KWZ5KERY`; target is closed。
|
||||||
|
- `TicketOrchestrationPlanQuery(00001KX0DSMPT)`: prior `after 00001KX0G06VA` / waiting note; `00001KX0G06VA` is now closed with merge commit `01f94b75` and close commit `a645ee5b`。
|
||||||
|
- Orchestrator worktree git status: clean on `orchestration`。
|
||||||
|
- queued Ticket 一覧: this Ticket 1件。inprogress は 0 件。
|
||||||
|
|
||||||
|
IntentPacket:
|
||||||
|
|
||||||
|
Intent:
|
||||||
|
- Workspace-scoped Browser API and pages for Workspace metadata and Profile registry/source editing, using Backend as the authority and the Decodal/ProfileSourceArchive model already merged。
|
||||||
|
- Frontend should edit Profiles through safe Backend APIs, not filesystem paths, and Worker launch profile candidates should reflect updated Backend discovery/validation state。
|
||||||
|
|
||||||
|
Binding decisions / invariants:
|
||||||
|
- Workspace/Profile editing APIs live under `/api/w/<workspace-id>/settings...` or consistent scoped Workspace API paths。
|
||||||
|
- Browser-facing API/UI must not expose host absolute paths, secret values, Runtime endpoints/tokens, socket/session paths, runtime-local store paths, archive content/digest, or raw resource handles。
|
||||||
|
- Profile source references use safe ids/artifact ids/display paths rather than raw absolute paths。
|
||||||
|
- Writes must validate syntax/schema/selector uniqueness/path safety before commit and return typed diagnostics。
|
||||||
|
- Decodal/ProfileSourceArchive source model from `00001KWZ5KERY` and resource-fetch boundary from `00001KX0G06VA` are authority inputs; do not reintroduce Runtime filesystem discovery。
|
||||||
|
- Runtime direct sync is out of scope; Backend discovery/launch options invalidation is in scope。
|
||||||
|
|
||||||
|
Requirements / acceptance criteria:
|
||||||
|
- Workspace metadata read/update API works for display name and safe identity/source summaries。
|
||||||
|
- Profile registry/source read/update APIs support create/update/delete with revision/etag-style optimistic check。
|
||||||
|
- Settings UI has Workspace overview and Profile list/source editor routes under `/w/<workspace-id>/settings...`。
|
||||||
|
- Profile updates re-run Backend discovery/validation and update Worker launch profile candidates。
|
||||||
|
- Duplicate selector, invalid registry schema, invalid Decodal syntax, path/symlink escape, artifact too large, and concurrent update conflict return typed diagnostics。
|
||||||
|
- Browser WorkingDirectory / Worker launch profile candidates and settings Profile list share the same Backend discovery result。
|
||||||
|
|
||||||
|
Implementation latitude:
|
||||||
|
- Endpoint naming, module boundaries, revision token shape, source/artifact id representation, UI component split, and editor implementation can follow existing workspace-server / Svelte style。
|
||||||
|
- v0 plain textarea/editor is acceptable; no heavyweight editor required。
|
||||||
|
- Imported source write support can be limited to bounded module root or deferred with typed diagnostics if not needed for core v0。
|
||||||
|
|
||||||
|
Escalate if:
|
||||||
|
- Secret value editor, multi-user auth/RBAC, Runtime direct sync, Plugin/MCP/sandbox artifact sync, Ticket/Objective/Memory editor integration, or a new Profile source semantic model beyond Decodal/ProfileSourceArchive is required。
|
||||||
|
|
||||||
|
Validation:
|
||||||
|
- `cargo test -p yoi-workspace-server`
|
||||||
|
- `cargo check -p yoi`
|
||||||
|
- `cd web/workspace && deno task check && deno task test`
|
||||||
|
- `git diff --check`
|
||||||
|
- `yoi ticket doctor`
|
||||||
|
- `nix build .#yoi --no-link`
|
||||||
|
|
||||||
|
Current code map:
|
||||||
|
- Workspace/profile settings backend: `crates/workspace-server/src/server.rs`, `hosts.rs`, `config.rs`, `resource_broker.rs`, Decodal/archive helpers。
|
||||||
|
- Profile archive/config: `crates/worker-runtime/src/profile_archive.rs`, `config_bundle.rs` for source model reference。
|
||||||
|
- Frontend settings: `web/workspace/src/routes/w/[workspaceId]/settings/**`, `web/workspace/src/lib/workspace-settings/**`, worker launch profile candidate helpers。
|
||||||
|
|
||||||
|
Critical risks / reviewer focus:
|
||||||
|
- No raw paths/secrets/runtime internals or resource handles leak to Browser。
|
||||||
|
- Profile editing updates the same Backend discovery/launch options used by Worker launch。
|
||||||
|
- Optimistic concurrency and path/symlink escape checks fail closed。
|
||||||
|
- Decodal validation is real and not only superficial string checks。
|
||||||
|
- Existing Runtime resource fetch / ProfileSourceArchive authority boundaries remain intact。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: state_changed author: orchestrator at: 2026-07-08T11:56:36Z from: queued to: inprogress reason: routing_acceptance_implementation_ready field: state -->
|
||||||
|
|
||||||
|
## State changed
|
||||||
|
|
||||||
|
Queued acceptance recorded after previous waiting reason was resolved.
|
||||||
|
|
||||||
|
Checked context:
|
||||||
|
- Ticket body / thread / artifacts。
|
||||||
|
- `TicketRelationQuery(00001KX0DSMPT)`: depends_on `00001KWZ5KERY`; target is closed。
|
||||||
|
- `TicketOrchestrationPlanQuery(00001KX0DSMPT)`: prior `after 00001KX0G06VA` / waiting note を確認。`00001KX0G06VA` is now closed / merged。
|
||||||
|
- Orchestrator worktree git status: clean on `orchestration`。
|
||||||
|
- queued Ticket はこの Ticket 1件のみ。inprogress は 0 件。
|
||||||
|
|
||||||
|
Acceptance basis:
|
||||||
|
- Previous blocker/waiting reason is resolved。
|
||||||
|
- concrete missing decision / information は残っていない。
|
||||||
|
- Ticket scope is Workspace/Profile settings API and pages using already-merged Decodal/ProfileSourceArchive and resource-fetch boundaries。
|
||||||
|
- side effect はこの `queued -> inprogress` acceptance 後に、worktree-workflow に沿って implementation worktree を作成してから開始する。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: implementation_report author: orchestrator at: 2026-07-08T11:58:14Z -->
|
||||||
|
|
||||||
|
## Implementation report
|
||||||
|
|
||||||
|
Implementation routing update:
|
||||||
|
|
||||||
|
- Worktree-workflow に従い implementation worktree を作成した。
|
||||||
|
- Worktree: `/home/hare/Projects/yoi/.worktree/00001KX0DSMPT-workspace-profile-settings`
|
||||||
|
- Branch: `work/00001KX0DSMPT-workspace-profile-settings`
|
||||||
|
- Worktree には tracked `.yoi` project records が見えている。
|
||||||
|
- `.yoi/memory` / `.yoi/runtime` / `.yoi/log` / `.yoi/logs` / `.yoi/local` / `.yoi/*.lock` / `.yoi/*secret*` は作成直後に存在しないことを確認した。
|
||||||
|
- Sibling Coder Pod `yoi-coder-00001KX0DSMPT-profile-settings` を起動した。
|
||||||
|
- Scope policy: runtime workspace root は read-only、implementation worktree は write 可。Coder task では root/original workspace での read/write/validation/git operation を禁止し、この implementation worktree だけを作業対象に指定した。
|
||||||
|
- 完了後は diff / validation evidence を Orchestrator が確認し、別 sibling Reviewer Pod に read-only review を依頼する。`StopPod` は既知の不具合があるため使用しない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: implementation_report author: orchestrator at: 2026-07-08T12:03:23Z -->
|
||||||
|
|
||||||
|
## Implementation report
|
||||||
|
|
||||||
|
Implementation routing recovery note:
|
||||||
|
|
||||||
|
- Initial Coder Pod `yoi-coder-00001KX0DSMPT-profile-settings` failed its first turn with provider `context_length_exceeded` before producing implementation output。
|
||||||
|
- Ticket remains `inprogress`; worktree/branch already exist and are clean at creation baseline。
|
||||||
|
- Recovery plan: avoid `StopPod` and retry with a fresh minimal Coder task that reads the Ticket records from the worktree instead of embedding the full IntentPacket in the prompt. If scope registry prevents a fresh Pod, fallback is to use the existing Pod with a much smaller instruction or ask for human cleanup/authority。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: implementation_report author: orchestrator at: 2026-07-08T12:40:07Z -->
|
||||||
|
|
||||||
|
## Implementation report
|
||||||
|
|
||||||
|
Implementation progress report:
|
||||||
|
|
||||||
|
- Recovery Coder Pod `yoi-coder2-00001KX0DSMPT-profile-settings` completed implementation and committed `3eefd333 feat: add workspace profile settings` on branch `work/00001KX0DSMPT-workspace-profile-settings`.
|
||||||
|
- Worktree status was clean after commit。
|
||||||
|
- Changed files include:
|
||||||
|
- `crates/workspace-server/src/profile_settings.rs` (new)
|
||||||
|
- `crates/workspace-server/src/{server.rs,hosts.rs,companion.rs,lib.rs}`
|
||||||
|
- `web/workspace/src/lib/workspace-settings/{profile-api.ts,profile-types.ts,model.ts}`
|
||||||
|
- `web/workspace/src/lib/workspace-api/http.ts`
|
||||||
|
- `web/workspace/src/routes/w/[workspaceId]/settings/+page.svelte`
|
||||||
|
- child implementation also committed `.yoi/tickets/00001KX0DSMPT/{item.md,thread.md}` changes; Orchestrator will preserve authoritative Ticket thread/item records during integration if conflicts occur。
|
||||||
|
- Implementation summary:
|
||||||
|
- Added scoped Workspace/Profile settings API for workspace metadata and profile registry/source read/write。
|
||||||
|
- Added Backend profile settings model with safe source ids/display paths, revision checks, Decodal validation, selector uniqueness checks, path/symlink escape protection, and typed diagnostics。
|
||||||
|
- Profile updates rebuild Backend profile discovery/launch options so Worker launch profile candidates and settings profile list use the same discovery result。
|
||||||
|
- Extended settings UI with Workspace overview and Profiles list/editor surface using scoped APIs and safe summaries。
|
||||||
|
- Browser-facing responses avoid raw host paths, runtime internals, archive digests/content, and resource handles。
|
||||||
|
- Orchestrator reran validation in the implementation worktree:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(80 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
- External review will be requested via a read-only sibling Reviewer Pod. `StopPod` は使わない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: review author: reviewer at: 2026-07-08T12:49:09Z status: request_changes -->
|
||||||
|
|
||||||
|
## Review: request changes
|
||||||
|
|
||||||
|
External review result: request_changes
|
||||||
|
|
||||||
|
Blockers:
|
||||||
|
|
||||||
|
1. Profile mutation validation failures are not returned as typed diagnostics。
|
||||||
|
- scoped settings handlers call `profile_settings::*` with `?` directly (`server.rs:881-945`).
|
||||||
|
- `ApiError::from(Error)` initializes `diagnostics: Vec::new()` (`server.rs:3355-3360`).
|
||||||
|
- profile errors such as `profile_selector_duplicate`, `profile_source_syntax_invalid`, `profile_source_path_escape`, `profile_registry_revision_conflict` fall through to `BAD_GATEWAY` (`server.rs:3403-3414`) with an empty diagnostics array (`server.rs:3420-3423`).
|
||||||
|
- Recorded requirement says duplicate selector, invalid registry/schema/Decodal, path/symlink escape, artifact too large, and concurrency conflicts must return typed diagnostics.
|
||||||
|
|
||||||
|
2. Worker launch profile candidates can include invalid project profiles。
|
||||||
|
- `load_profile_settings` attaches Decodal/source validation errors from `validate_project_profiles` only to top-level `diagnostics` (`profile_settings.rs:327`, `663-707`).
|
||||||
|
- each project `WorkspaceProfileSummary` only gets `source_summary` diagnostics (`profile_settings.rs:304-323`).
|
||||||
|
- `worker_profile_candidates_for_root` includes project profiles when `profile.diagnostics.is_empty()` (`server.rs:2989-2992`).
|
||||||
|
- `is_profile_candidate` accepts any discovered project profile id (`profile_settings.rs:629-635`).
|
||||||
|
- Result: registry entry with invalid Decodal source can still appear in launch options and be accepted as a candidate until spawn-time archive resolution fails.
|
||||||
|
- This violates the intent that profile updates re-run Backend discovery/validation and Worker launch candidates share the same effective validated discovery result.
|
||||||
|
|
||||||
|
3. Registry/default updates can commit references that are not actually Backend-published/valid。
|
||||||
|
- `validate_default_profile` accepts any string beginning with `project:` without checking that the project selector exists in submitted registry or discovery result (`profile_settings.rs:946-955`).
|
||||||
|
- `update_profile_registry` only validates source content if the expected source file already exists (`profile_settings.rs:463-468`) before writing the registry (`profile_settings.rs:470`).
|
||||||
|
- This permits API writes that persist nonexistent project defaults or missing project source references, contrary to the invariant that writes validate schema/selector/source references before commit and defaults/candidates are Backend-published.
|
||||||
|
|
||||||
|
Validation performed:
|
||||||
|
- Read Ticket `00001KX0DSMPT` item/thread, IntentPacket, binding invariants, acceptance criteria, implementation report, and reviewer focus。
|
||||||
|
- Read-only inspection in implementation worktree `/home/hare/Projects/yoi/.worktree/00001KX0DSMPT-workspace-profile-settings`。
|
||||||
|
- Inspected implementation commit scope and relevant backend/frontend files。
|
||||||
|
- Relied on Orchestrator-provided validation results; did not modify files or run root/original workspace operations。
|
||||||
|
|
||||||
|
Non-blocking follow-ups:
|
||||||
|
- Negative-test coverage is thinner than reviewer focus: duplicate selector, invalid registry schema, symlink escape, artifact size, redaction, concurrent update API response shape, and launch-candidate invalidation need stronger coverage.
|
||||||
|
- UI implements profile list/editor on single `/settings` page with anchors/forms rather than separate `/settings/profiles/...` pages. This may be acceptable under implementation latitude, but confirm route granularity if it matters.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: implementation_report author: orchestrator at: 2026-07-08T13:07:39Z -->
|
||||||
|
|
||||||
|
## Implementation report
|
||||||
|
|
||||||
|
Review-fix implementation report:
|
||||||
|
|
||||||
|
- Recovery Coder Pod completed requested changes and committed follow-up `0c2ca1ea fix: harden profile settings validation` on branch `work/00001KX0DSMPT-workspace-profile-settings`.
|
||||||
|
- Worktree status was clean after commit。
|
||||||
|
- Fix summary:
|
||||||
|
- Profile settings validation errors now map to typed Browser diagnostics with non-empty `diagnostics` arrays and appropriate HTTP statuses(revision conflict 409、invalid/duplicate/path/schema/source/profile errors 400、unknown source/selector 404)。
|
||||||
|
- Project profile discovery attaches source/Decodal validation failures to the relevant `WorkspaceProfileSummary`。
|
||||||
|
- Invalid project profiles are excluded from Worker launch candidates and rejected by candidate validation。
|
||||||
|
- Registry/default writes validate default selector existence, selector/source consistency, missing source files, path/symlink escape, source size, Decodal/ProfileSourceArchive validity, and invalid registry schema before commit。
|
||||||
|
- Added/strengthened tests for duplicate selector, invalid Decodal/schema, stale revision conflict, too-large source, symlink escape redaction, invalid launch candidate rejection, and missing/default reference rejection。
|
||||||
|
- Orchestrator reran validation in the implementation worktree:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(91 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
- Requesting follow-up external review against `3eefd333..0c2ca1ea` and full combined implementation。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: review author: reviewer at: 2026-07-08T13:18:55Z status: approve -->
|
||||||
|
|
||||||
|
## Review: approve
|
||||||
|
|
||||||
|
External follow-up review result: approve
|
||||||
|
|
||||||
|
Blockers: none.
|
||||||
|
|
||||||
|
Validation performed read-only in implementation worktree. Reviewer inspected Ticket records, `0c2ca1ea`, fix diff `3eefd333..0c2ca1ea`, and relevant server/profile/UI code. Reviewer did not rerun heavy validation and relied on Orchestrator-reported passing validation.
|
||||||
|
|
||||||
|
Findings:
|
||||||
|
- Prior blocker 1 resolved: profile mutation failures now return typed Browser diagnostics with populated diagnostics rather than generic empty diagnostics. Server-side handlers/tests cover invalid source mutations and missing-source registry mutations with non-empty diagnostic arrays and bad-request status。
|
||||||
|
- Prior blocker 2 resolved: invalid/missing/Decodal-invalid project profile sources are surfaced on relevant profile summaries, invalid project profiles are excluded from Worker launch candidates, and candidate validation rejects invalid project profile ids with regression coverage。
|
||||||
|
- Prior blocker 3 resolved: registry/default update paths validate selector/default existence, selector/source-id correspondence, missing source files, source path safety including symlink escape rejection, source size, Decodal/ProfileSourceArchive validity, and invalid registry schema before accepting mutations。
|
||||||
|
- Browser-facing profile/settings summaries expose bounded ids, labels, relative display paths, revision/configured booleans, and diagnostics; no host absolute paths, socket/session paths, runtime-local store paths, runtime endpoints/tokens, backend-private paths, archive digests, raw resource handles, or secret values were found in inspected API/UI surfaces。
|
||||||
|
- Profile detail exposes editable source content as intended settings-editor payload, not resolved archive/resource bundle。
|
||||||
|
- Decodal/ProfileSourceArchive validation remains behind server-side checked source path/archive boundary; Runtime filesystem discovery was not reintroduced for profile validation or launch。
|
||||||
|
- Single-page settings UI route structure is acceptable under implementation latitude and not a blocker。
|
||||||
|
|
||||||
|
Non-blocking follow-up:
|
||||||
|
- If merge target accumulated additional `.yoi/tickets/00001KX0DSMPT/thread.md` edits, resolve Ticket-record conflicts normally during merge; this does not affect product/code correctness.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: state_changed author: orchestrator at: 2026-07-08T13:20:09Z from: inprogress to: done reason: merged_validated_review_approved field: state -->
|
||||||
|
|
||||||
|
## State changed
|
||||||
|
|
||||||
|
Merge/validation acceptance:
|
||||||
|
|
||||||
|
- Follow-up external review approved the implementation after blocker fixes。
|
||||||
|
- Implementation branch `work/00001KX0DSMPT-workspace-profile-settings` was merged into the orchestration branch with merge commit `0bf3638c merge: workspace profile settings`。
|
||||||
|
- Ticket-record conflicts during merge were resolved by preserving Orchestrator-side Ticket item/thread records; product/code changes were merged。
|
||||||
|
- Final validation in Orchestrator worktree passed:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(91 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
|
||||||
|
Implementation commits:
|
||||||
|
- `3eefd333 feat: add workspace profile settings`
|
||||||
|
- `0c2ca1ea fix: harden profile settings validation`
|
||||||
|
|
||||||
|
No merge-blocking issues remain.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: state_changed author: hare at: 2026-07-08T13:20:27Z from: done to: closed reason: closed field: state -->
|
||||||
|
|
||||||
|
## State changed
|
||||||
|
|
||||||
|
Ticket を closed にしました。
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: close author: hare at: 2026-07-08T13:20:27Z status: closed -->
|
||||||
|
|
||||||
|
## 完了
|
||||||
|
|
||||||
|
完了。
|
||||||
|
|
||||||
|
実装内容:
|
||||||
|
- Workspace/Profile settings scoped API を追加した。
|
||||||
|
- Workspace metadata read/update と safe identity/source summaries を扱う Settings API を追加した。
|
||||||
|
- Profile registry/source read/update API を追加し、create/update/delete と revision/etag-style optimistic checks を実装した。
|
||||||
|
- Backend profile settings model に safe source ids/display paths、Decodal/ProfileSourceArchive validation、selector uniqueness、path/symlink escape protection、source size checks、typed diagnostics を追加した。
|
||||||
|
- Profile updates 後に Backend profile discovery / validation / launch options を再構築し、Worker launch profile candidates と Settings profile list が同じ discovery result を使うようにした。
|
||||||
|
- invalid project profile は relevant profile summary に diagnostics を付与し、Worker launch candidates から除外し、candidate validation でも reject するようにした。
|
||||||
|
- Browser-facing responses/UI から host absolute paths、secret values、Runtime endpoints/tokens、socket/session paths、runtime-local store paths、archive content/digest、raw resource handles、backend-private paths を出さないようにした。
|
||||||
|
- Settings UI に Workspace overview と Profile list/source editor surface を追加した。
|
||||||
|
- Focused backend/web tests を追加/強化した。
|
||||||
|
|
||||||
|
主な commit / merge:
|
||||||
|
- implementation: `3eefd333 feat: add workspace profile settings`
|
||||||
|
- review fix: `0c2ca1ea fix: harden profile settings validation`
|
||||||
|
- merge into orchestration: `0bf3638c merge: workspace profile settings`
|
||||||
|
|
||||||
|
Review:
|
||||||
|
- 初回 external review は request_changes。
|
||||||
|
- follow-up external review は approve。merge-blocking issue なし。
|
||||||
|
|
||||||
|
Final validation in Orchestrator worktree:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(91 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
|
||||||
|
補足:
|
||||||
|
- implementation branch merge 時に Ticket record conflict が発生したため、Orchestrator 側の Ticket item/thread を保持して解決した。product/code changes は merge 済み。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
---
|
---
|
||||||
title: 'Add Runtime-to-Backend resource fetch REST API'
|
title: 'Add Runtime-to-Backend resource fetch REST API'
|
||||||
state: 'inprogress'
|
state: 'closed'
|
||||||
created_at: '2026-07-08T09:12:33Z'
|
created_at: '2026-07-08T09:12:33Z'
|
||||||
updated_at: '2026-07-08T10:40:25Z'
|
updated_at: '2026-07-08T11:54:55Z'
|
||||||
assignee: null
|
assignee: null
|
||||||
queued_by: 'workspace-panel'
|
queued_by: 'workspace-panel'
|
||||||
queued_at: '2026-07-08T10:04:10Z'
|
queued_at: '2026-07-08T10:04:10Z'
|
||||||
|
|
|
||||||
36
.yoi/tickets/00001KX0G06VA/resolution.md
Normal file
36
.yoi/tickets/00001KX0G06VA/resolution.md
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
完了。
|
||||||
|
|
||||||
|
実装内容:
|
||||||
|
- Runtime-to-Backend resource fetch contract を追加した。
|
||||||
|
- Backend-issued typed resource handle と `BackendResourceBroker` を実装した。
|
||||||
|
- v0 resource kind `profile_source_archive` を fetch / verify / cache できるようにした。
|
||||||
|
- embedded direct Runtime path と remote Runtime HTTP path が同じ typed resource contract を使うようにした。
|
||||||
|
- Runtime は handle に基づき archive を fetch し、digest / max bytes / content type / expiry / binding を検証してから cache/reuse するようにした。
|
||||||
|
- Backend broker は stored issued handle を authority として扱い、Runtime-provided mutable handle fields による expiry / max_bytes / policy tampering を fail closed するようにした。
|
||||||
|
- Runtime cache は Backend authorization / expiry / binding を bypass しないようにした。
|
||||||
|
- Decodal ProfileSourceArchive / config bundle path を resource fetch boundary に接続し、Runtime filesystem discovery を再導入しない形にした。
|
||||||
|
- Browser-facing summaries は internal resource handle / endpoint / raw path / archive content/digest/store path / token 等を出さないようにした。
|
||||||
|
- Focused worker-runtime / workspace-server tests を追加した。
|
||||||
|
|
||||||
|
主な commit / merge:
|
||||||
|
- implementation: `57e96d3b feat: add backend resource fetch api`
|
||||||
|
- review fix: `e716ae44 fix: harden backend resource handles`
|
||||||
|
- merge into orchestration: `01f94b75 merge: backend resource fetch api`
|
||||||
|
|
||||||
|
Review:
|
||||||
|
- 初回 external review は request_changes。
|
||||||
|
- follow-up external review は approve。merge-blocking issue なし。
|
||||||
|
|
||||||
|
Final validation in Orchestrator worktree:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p worker-runtime --features ws-server,fs-store`: pass(45 lib tests + 5 main tests + doc tests)
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(77 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
|
||||||
|
補足:
|
||||||
|
- Reviewer の non-blocking follow-up: stored `audit_correlation_id` echo と Runtime-side response `resource_id` check、remote HTTP response-size limiting のさらなる強化余地。
|
||||||
|
- queued `00001KX0DSMPT` については、resource-fetch API shape が確定したため再 routing 可能。
|
||||||
|
|
@ -176,3 +176,222 @@ Implementation routing update:
|
||||||
- 完了後は diff / validation evidence を Orchestrator が確認し、別 sibling Reviewer Pod に read-only review を依頼する。`StopPod` は既知の不具合があるため使用しない。
|
- 完了後は diff / validation evidence を Orchestrator が確認し、別 sibling Reviewer Pod に read-only review を依頼する。`StopPod` は既知の不具合があるため使用しない。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
<!-- event: implementation_report author: orchestrator at: 2026-07-08T11:20:23Z -->
|
||||||
|
|
||||||
|
## Implementation report
|
||||||
|
|
||||||
|
Implementation progress report:
|
||||||
|
|
||||||
|
- Coder Pod completed implementation and committed `57e96d3b feat: add backend resource fetch api` on branch `work/00001KX0G06VA-resource-fetch-api`.
|
||||||
|
- Worktree status was clean after commit.
|
||||||
|
- Changed files include:
|
||||||
|
- `crates/worker-runtime/src/resource.rs` (new)
|
||||||
|
- `crates/workspace-server/src/resource_broker.rs` (new)
|
||||||
|
- `crates/worker-runtime/src/{config_bundle.rs,http_server.rs,main.rs,profile_archive.rs,worker_backend.rs}`
|
||||||
|
- `crates/workspace-server/src/{hosts.rs,server.rs,companion.rs}`
|
||||||
|
- `Cargo.lock`, `package.nix`
|
||||||
|
- Implementation summary:
|
||||||
|
- Added typed resource handle/request/response model and Runtime resource client/cache path。
|
||||||
|
- Added Backend resource broker for v0 `profile_source_archive` resources。
|
||||||
|
- Embedded direct path and remote Runtime HTTP path share the resource contract。
|
||||||
|
- Runtime verifies digest, max bytes/content type, expiry/binding, and cache reuse before using fetched profile archives。
|
||||||
|
- Config bundle/profile archive path can use resource handle without Runtime filesystem discovery。
|
||||||
|
- Browser-facing summaries redact internal resource handles/endpoints/raw paths/archive details。
|
||||||
|
- Added focused tests for handle issue/verify, runtime mismatch, digest mismatch, oversized response, direct/remote resource fetch, Browser redaction, and config-bundle/resource archive integration。
|
||||||
|
- Orchestrator reran validation in the implementation worktree:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p worker-runtime --features ws-server,fs-store`: pass(42 lib tests + 5 main tests + doc tests)
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(71 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
- External review will be requested via a read-only sibling Reviewer Pod. `StopPod` は使わない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: review author: reviewer at: 2026-07-08T11:27:23Z status: request_changes -->
|
||||||
|
|
||||||
|
## Review: request changes
|
||||||
|
|
||||||
|
External review result: request_changes
|
||||||
|
|
||||||
|
Blockers:
|
||||||
|
|
||||||
|
1. Backend handle verification が Runtime から送られた mutable handle fields を信頼している。
|
||||||
|
- `crates/workspace-server/src/resource_broker.rs` の fetch validation は expiry / max-bytes を `request.handle` から確認しており、broker-stored issued handle の authority fields と照合していない。
|
||||||
|
- 有効な nonce/resource/digest を持つ Runtime が以下を改変できる可能性がある。
|
||||||
|
- `expires_at_unix_seconds` を延長して expiry を bypass。
|
||||||
|
- `max_bytes` を増やして oversized rejection を bypass。
|
||||||
|
- redaction/scope/generation など他 policy fields も stored issued handle に bind されていない。
|
||||||
|
- Backend-issued handle を Backend が検証し、expired/oversized handles が fail closed typed diagnostics になるという Ticket requirement に反する。
|
||||||
|
|
||||||
|
2. Runtime cache が Backend authorization / expiry / binding を bypass している。
|
||||||
|
- `ProfileRuntimeWorkerFactory::resolve_profile_source_archive` は fetch 前に digest keyed `profile_archive_cache` を見る。
|
||||||
|
- 一度 archive が cache されると、同一 digest の後続 config bundle は Backend verification なしで reuse でき、expired handle / runtime-worker-workspace mismatch でも成功し得る。
|
||||||
|
- 「Runtime cannot fetch/use Workspace-derived resources without Backend-issued handle」「Runtime verifies expiry/binding」「expired/unauthorized/mismatch cases produce diagnostics」に反する。
|
||||||
|
|
||||||
|
3. security contract の acceptance-level tests が不足している。
|
||||||
|
- happy-path broker issue/fetch、runtime mismatch、browser projection redaction はあるが、以下の meaningful coverage が不足している。
|
||||||
|
- tampered expired handle / expiry extension。
|
||||||
|
- worker mismatch。
|
||||||
|
- REST 経由 missing resource。
|
||||||
|
- Runtime response verification の digest mismatch。
|
||||||
|
- tampered `max_bytes` による oversized response。
|
||||||
|
- remote HTTP resource-fetch path が同じ contract を使うこと。
|
||||||
|
- 上記 defect が存在しているため、単なる coverage gap ではなく core Ticket intent の boundary regression を許している。
|
||||||
|
|
||||||
|
Validation / inspection performed:
|
||||||
|
- implementation worktree `/home/hare/Projects/yoi/.worktree/00001KX0G06VA-resource-fetch-api` のみを使用。
|
||||||
|
- Ticket item/thread/orchestration plan を確認。
|
||||||
|
- `git show --stat --check 57e96d3b`, `git show --name-only 57e96d3b`, relevant implementation files を inspection。
|
||||||
|
- Orchestrator-reported validation pass を参照し、Reviewer は heavy tests を再実行していない。
|
||||||
|
|
||||||
|
Non-blocking follow-ups:
|
||||||
|
- New `reqwest` dependency and `package.nix` cargo hash update は HTTP Runtime resource client と `nix build` pass により妥当。
|
||||||
|
- broader resource kind 追加前に、stored issued handle policy fields の完全比較、または signed/opaque handle representation を検討するとよい。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: implementation_report author: orchestrator at: 2026-07-08T11:45:42Z -->
|
||||||
|
|
||||||
|
## Implementation report
|
||||||
|
|
||||||
|
Review-fix implementation report:
|
||||||
|
|
||||||
|
- Coder Pod completed requested changes and committed follow-up `e716ae44 fix: harden backend resource handles` on branch `work/00001KX0G06VA-resource-fetch-api`.
|
||||||
|
- Worktree status was clean after commit.
|
||||||
|
- Fix summary:
|
||||||
|
- Backend broker now treats broker-stored issued handle as authority。
|
||||||
|
- Request handle must match stored issued handle; expiry and `max_bytes` validation use stored policy fields, not mutable Runtime-provided fields。
|
||||||
|
- Tampered scope/policy fields fail closed。
|
||||||
|
- Runtime archive cache no longer bypasses Backend authorization: Runtime calls `BackendResourceClient` and verifies response before reusing digest-cached archive。
|
||||||
|
- Expired/unauthorized handles now block cached reuse。
|
||||||
|
- Added focused security-contract tests for expiry extension/expired handle rejection, worker mismatch, policy tampering, REST missing-resource diagnostic, Runtime digest mismatch, oversized response despite `max_bytes` tampering, and remote HTTP path using the same Backend contract as direct broker path。
|
||||||
|
- Orchestrator reran validation in the implementation worktree:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p worker-runtime --features ws-server,fs-store`: pass(45 lib tests + 5 main tests + doc tests)
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(77 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
- Requesting follow-up external review against `57e96d3b..e716ae44` and full combined implementation。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: review author: reviewer at: 2026-07-08T11:53:02Z status: approve -->
|
||||||
|
|
||||||
|
## Review: approve
|
||||||
|
|
||||||
|
External follow-up review result: approve
|
||||||
|
|
||||||
|
Blockers: none.
|
||||||
|
|
||||||
|
Validation performed:
|
||||||
|
- Read-only review in implementation worktree `/home/hare/Projects/yoi/.worktree/00001KX0G06VA-resource-fetch-api`。
|
||||||
|
- Ticket item/thread, branch/log/status, `57e96d3b..e716ae44` fix diff, and relevant implementation files を確認。
|
||||||
|
- Reviewer は validation suite を再実行せず、Orchestrator-reported passing validation を evidence として確認。
|
||||||
|
|
||||||
|
Findings:
|
||||||
|
- Prior blocker 1 fixed: Backend は mutable request handle policy fields を信頼しない。`BackendResourceBroker` は issued `BackendResourceHandle` を resource と共に保存し、stored expiry/max_bytes を検証してから request handle と stored issued handle を比較する。tampering は `Expired` / `Oversized` / `Unauthorized` diagnostics で fail closed。expiry extension、policy tampering、worker/runtime mismatch、max_bytes tampering tests あり。
|
||||||
|
- Prior blocker 2 fixed: Runtime cache は Backend authorization を bypass しない。`resolve_profile_source_archive` は先に Backend fetch を行い、handle に対して response verify してから digest cache を reuse/insert する。cache test は second-use backend `Expired` rejection と backend call count を確認している。
|
||||||
|
- Prior blocker 3 fixed: security contract tests が meaningful に追加されている。
|
||||||
|
- `resource_broker.rs`: expired/expiry extension、worker mismatch、runtime mismatch、policy tampering、stored max_bytes oversized。
|
||||||
|
- `resource.rs`: Runtime digest mismatch と oversized response verification。
|
||||||
|
- `server.rs`: REST missing-resource diagnostic と remote HTTP contract/tampering path。
|
||||||
|
- `worker_backend.rs`: cache authorization。
|
||||||
|
- Browser redaction: `ConfigBundleSummary` redaction test。
|
||||||
|
- Typed/direct/remote contract: `BackendResourceFetchRequest/Response/Error` は shared typed structs。embedded direct path は `BackendResourceBroker` を `BackendResourceClient` として使い、remote HTTP は同じ request shape を `/internal/runtime/resources/fetch` に POST する。
|
||||||
|
- Browser-facing redaction remains strong: browser-safe summaries は profile source graph summary のみを出し、handle nonce/resource id/archive digest/runtime-worker binding/token/internal endpoint/raw path を出さない。
|
||||||
|
- ProfileSourceArchive integration は normal Backend/Browser launch で Backend-owned resource boundary を使う。generated bundles は resource handle を持ち inline archive を持たず、Runtime は fetched archive bytes から resolve する。filesystem profile discovery は explicit no-config-bundle compatibility/debug fallback のみ。
|
||||||
|
|
||||||
|
Non-blocking follow-ups:
|
||||||
|
- stored `audit_correlation_id` の echo と Runtime-side response `resource_id` check を追加すると diagnostic integrity がさらに強くなる。
|
||||||
|
- remote HTTP resource fetch が trusted Backend/Runtime links を越えて露出する場合は、JSON body materialization 前の explicit client-side timeout/response-size limiting を検討する。
|
||||||
|
|
||||||
|
Effect on queued `00001KX0DSMPT`:
|
||||||
|
- blocking concern なし。profile/archive details は redacted summaries behind boundary に留まっており、future settings UI/API が profile metadata を consume しても handles を露出しない設計と互換。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: state_changed author: orchestrator at: 2026-07-08T11:54:39Z from: inprogress to: done reason: merged_validated_review_approved field: state -->
|
||||||
|
|
||||||
|
## State changed
|
||||||
|
|
||||||
|
Merge/validation acceptance:
|
||||||
|
|
||||||
|
- Follow-up external review approved the implementation after blocker fix。
|
||||||
|
- Implementation branch `work/00001KX0G06VA-resource-fetch-api` was merged into the orchestration branch with merge commit `01f94b75 merge: backend resource fetch api`。
|
||||||
|
- Final validation in Orchestrator worktree passed:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p worker-runtime --features ws-server,fs-store`: pass(45 lib tests + 5 main tests + doc tests)
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(77 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
|
||||||
|
Implementation commits:
|
||||||
|
- `57e96d3b feat: add backend resource fetch api`
|
||||||
|
- `e716ae44 fix: harden backend resource handles`
|
||||||
|
|
||||||
|
No merge-blocking issues remain. Reviewer noted no blocking concern for queued `00001KX0DSMPT`; the resource-fetch API shape is now stable enough for that follow-up to be re-routed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: state_changed author: hare at: 2026-07-08T11:54:54Z from: done to: closed reason: closed field: state -->
|
||||||
|
|
||||||
|
## State changed
|
||||||
|
|
||||||
|
Ticket を closed にしました。
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- event: close author: hare at: 2026-07-08T11:54:55Z status: closed -->
|
||||||
|
|
||||||
|
## 完了
|
||||||
|
|
||||||
|
完了。
|
||||||
|
|
||||||
|
実装内容:
|
||||||
|
- Runtime-to-Backend resource fetch contract を追加した。
|
||||||
|
- Backend-issued typed resource handle と `BackendResourceBroker` を実装した。
|
||||||
|
- v0 resource kind `profile_source_archive` を fetch / verify / cache できるようにした。
|
||||||
|
- embedded direct Runtime path と remote Runtime HTTP path が同じ typed resource contract を使うようにした。
|
||||||
|
- Runtime は handle に基づき archive を fetch し、digest / max bytes / content type / expiry / binding を検証してから cache/reuse するようにした。
|
||||||
|
- Backend broker は stored issued handle を authority として扱い、Runtime-provided mutable handle fields による expiry / max_bytes / policy tampering を fail closed するようにした。
|
||||||
|
- Runtime cache は Backend authorization / expiry / binding を bypass しないようにした。
|
||||||
|
- Decodal ProfileSourceArchive / config bundle path を resource fetch boundary に接続し、Runtime filesystem discovery を再導入しない形にした。
|
||||||
|
- Browser-facing summaries は internal resource handle / endpoint / raw path / archive content/digest/store path / token 等を出さないようにした。
|
||||||
|
- Focused worker-runtime / workspace-server tests を追加した。
|
||||||
|
|
||||||
|
主な commit / merge:
|
||||||
|
- implementation: `57e96d3b feat: add backend resource fetch api`
|
||||||
|
- review fix: `e716ae44 fix: harden backend resource handles`
|
||||||
|
- merge into orchestration: `01f94b75 merge: backend resource fetch api`
|
||||||
|
|
||||||
|
Review:
|
||||||
|
- 初回 external review は request_changes。
|
||||||
|
- follow-up external review は approve。merge-blocking issue なし。
|
||||||
|
|
||||||
|
Final validation in Orchestrator worktree:
|
||||||
|
- `git diff --check`: pass
|
||||||
|
- `cargo test -p worker-runtime --features ws-server,fs-store`: pass(45 lib tests + 5 main tests + doc tests)
|
||||||
|
- `cargo test -p yoi-workspace-server`: pass(77 lib tests + 2 main tests)
|
||||||
|
- `cargo check -p yoi`: pass
|
||||||
|
- `cd web/workspace && deno task check`: pass(0 errors / 0 warnings)
|
||||||
|
- `cd web/workspace && deno task test`: pass(17 tests)
|
||||||
|
- `yoi ticket doctor`: ok
|
||||||
|
- `nix build .#yoi --no-link`: pass
|
||||||
|
|
||||||
|
補足:
|
||||||
|
- Reviewer の non-blocking follow-up: stored `audit_correlation_id` echo と Runtime-side response `resource_id` check、remote HTTP response-size limiting のさらなる強化余地。
|
||||||
|
- queued `00001KX0DSMPT` については、resource-fetch API shape が確定したため再 routing 可能。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
|
||||||
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -5936,6 +5936,7 @@ dependencies = [
|
||||||
"llm-engine",
|
"llm-engine",
|
||||||
"manifest",
|
"manifest",
|
||||||
"protocol",
|
"protocol",
|
||||||
|
"reqwest",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"session-store",
|
"session-store",
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ required-features = ["ws-server", "fs-store"]
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
fs-store = []
|
fs-store = []
|
||||||
http-server = ["dep:axum", "dep:tower"]
|
http-server = ["dep:axum", "dep:tower", "dep:reqwest"]
|
||||||
ws-server = ["http-server", "axum/ws", "dep:futures", "tokio/sync"]
|
ws-server = ["http-server", "axum/ws", "dep:futures", "tokio/sync"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|
@ -28,6 +28,7 @@ serde = { workspace = true, features = ["derive"] }
|
||||||
session-store.workspace = true
|
session-store.workspace = true
|
||||||
sha2.workspace = true
|
sha2.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
|
reqwest = { version = "0.13", optional = true, default-features = false, features = ["json", "rustls"] }
|
||||||
tar.workspace = true
|
tar.workspace = true
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
tokio = { workspace = true, features = ["net", "rt", "sync", "time"] }
|
tokio = { workspace = true, features = ["net", "rt", "sync", "time"] }
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ use crate::profile_archive::{
|
||||||
ProfileArchiveError, ProfileSourceArchive, ProfileSourceArchiveRef,
|
ProfileArchiveError, ProfileSourceArchive, ProfileSourceArchiveRef,
|
||||||
VerifiedProfileSourceArchive,
|
VerifiedProfileSourceArchive,
|
||||||
};
|
};
|
||||||
|
use crate::resource::{BackendResourceHandle, validate_resource_handle_text};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
|
@ -24,6 +25,8 @@ pub struct ConfigBundle {
|
||||||
pub declarations: Vec<ConfigDeclaration>,
|
pub declarations: Vec<ConfigDeclaration>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub profile_source_archive: Option<ProfileSourceArchive>,
|
pub profile_source_archive: Option<ProfileSourceArchive>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub profile_source_archive_handle: Option<BackendResourceHandle>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ConfigBundle {
|
impl ConfigBundle {
|
||||||
|
|
@ -75,6 +78,27 @@ impl ConfigBundle {
|
||||||
lines.push(format!("profile_archive_entrypoint\0{selector}\0{path}"));
|
lines.push(format!("profile_archive_entrypoint\0{selector}\0{path}"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(handle) = &self.profile_source_archive_handle {
|
||||||
|
lines.push(format!(
|
||||||
|
"profile_archive_handle\0{}\0{}\0{}\0{}\0{}",
|
||||||
|
handle.workspace_id,
|
||||||
|
handle.resource_id,
|
||||||
|
handle.digest,
|
||||||
|
handle.revision,
|
||||||
|
handle.max_bytes
|
||||||
|
));
|
||||||
|
for (selector, path) in handle
|
||||||
|
.profile_source_graph
|
||||||
|
.as_ref()
|
||||||
|
.map(|graph| &graph.entrypoints)
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
{
|
||||||
|
lines.push(format!(
|
||||||
|
"profile_archive_handle_entrypoint\0{selector}\0{path}"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
lines.sort();
|
lines.sort();
|
||||||
let mut hasher = Sha256::new();
|
let mut hasher = Sha256::new();
|
||||||
|
|
@ -105,7 +129,12 @@ impl ConfigBundle {
|
||||||
profile_source_archive: self
|
profile_source_archive: self
|
||||||
.profile_source_archive
|
.profile_source_archive
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|archive| archive.reference.source_graph.clone()),
|
.map(|archive| archive.reference.source_graph.clone())
|
||||||
|
.or_else(|| {
|
||||||
|
self.profile_source_archive_handle
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|handle| handle.profile_source_graph.clone())
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -253,6 +282,33 @@ pub(crate) fn validate_config_bundle(bundle: &ConfigBundle) -> Result<(), Runtim
|
||||||
RuntimeError::InvalidRequest(format!("invalid profile source archive: {err}"))
|
RuntimeError::InvalidRequest(format!("invalid profile source archive: {err}"))
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
|
if let Some(handle) = &bundle.profile_source_archive_handle {
|
||||||
|
for (label, value) in [
|
||||||
|
("resource handle workspace id", handle.workspace_id.as_str()),
|
||||||
|
("resource handle resource id", handle.resource_id.as_str()),
|
||||||
|
("resource handle digest", handle.digest.as_str()),
|
||||||
|
("resource handle nonce", handle.nonce.as_str()),
|
||||||
|
("resource handle revision", handle.revision.as_str()),
|
||||||
|
("resource handle content type", handle.content_type.as_str()),
|
||||||
|
(
|
||||||
|
"resource handle audit correlation id",
|
||||||
|
handle.audit_correlation_id.as_str(),
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
validate_resource_handle_text(label, value).map_err(RuntimeError::InvalidRequest)?;
|
||||||
|
}
|
||||||
|
if !handle.digest.starts_with("sha256:") {
|
||||||
|
return Err(RuntimeError::InvalidRequest(
|
||||||
|
"resource handle digest must use sha256:<hex>".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if handle.profile_source_graph.is_none() {
|
||||||
|
return Err(RuntimeError::InvalidRequest(
|
||||||
|
"profile source archive resource handle must include source graph summary"
|
||||||
|
.to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -529,6 +585,7 @@ mod tests {
|
||||||
reference: reference.to_string(),
|
reference: reference.to_string(),
|
||||||
}],
|
}],
|
||||||
profile_source_archive: None,
|
profile_source_archive: None,
|
||||||
|
profile_source_archive_handle: None,
|
||||||
}
|
}
|
||||||
.with_computed_digest()
|
.with_computed_digest()
|
||||||
}
|
}
|
||||||
|
|
@ -560,6 +617,53 @@ mod tests {
|
||||||
validate_config_bundle(&bundle_with_declaration("vault:team.api-key")).unwrap();
|
validate_config_bundle(&bundle_with_declaration("vault:team.api-key")).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bundle_summary_redacts_runtime_internal_resource_handle() {
|
||||||
|
let mut bundle = bundle_with_declaration("secret:github-token");
|
||||||
|
let source_graph = crate::profile_archive::ProfileSourceGraphSummary {
|
||||||
|
entrypoints: std::collections::BTreeMap::from([(
|
||||||
|
"default".to_string(),
|
||||||
|
"profiles/default.dcdl".to_string(),
|
||||||
|
)]),
|
||||||
|
source_count: 1,
|
||||||
|
import_count: 0,
|
||||||
|
total_source_bytes: 16,
|
||||||
|
};
|
||||||
|
bundle.profile_source_archive_handle = Some(crate::resource::BackendResourceHandle {
|
||||||
|
kind: crate::resource::BackendResourceKind::ProfileSourceArchive,
|
||||||
|
workspace_id: "workspace-1".to_string(),
|
||||||
|
scope_id: Some("scope-1".to_string()),
|
||||||
|
runtime_id: Some("runtime-1".to_string()),
|
||||||
|
worker_id: Some("worker-1".to_string()),
|
||||||
|
resource_id: "profile-source-archive:test".to_string(),
|
||||||
|
digest: "sha256:0123456789abcdef".to_string(),
|
||||||
|
operation: crate::resource::BackendResourceOperation::FetchArchive,
|
||||||
|
expires_at_unix_seconds: 4_102_444_800,
|
||||||
|
nonce: "nonce-not-for-browser".to_string(),
|
||||||
|
revision: "rev-1".to_string(),
|
||||||
|
generation: Some(1),
|
||||||
|
max_bytes: 128,
|
||||||
|
content_type: crate::resource::PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
redaction: crate::resource::ResourceRedactionPolicy::RuntimeInternalOnly,
|
||||||
|
audit_correlation_id: "audit-1".to_string(),
|
||||||
|
profile_source_graph: Some(source_graph),
|
||||||
|
});
|
||||||
|
let rendered = serde_json::to_string(&bundle.summary()).unwrap();
|
||||||
|
assert!(rendered.contains("profile_source_archive"));
|
||||||
|
for forbidden in [
|
||||||
|
"nonce-not-for-browser",
|
||||||
|
"profile-source-archive:test",
|
||||||
|
"sha256:0123456789abcdef",
|
||||||
|
"runtime-1",
|
||||||
|
"worker-1",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
!rendered.contains(forbidden),
|
||||||
|
"leaked {forbidden}: {rendered}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_unsafe_bundle_ids_and_refs() {
|
fn rejects_unsafe_bundle_ids_and_refs() {
|
||||||
for id in ["bundle/1", "bundle?x", "bundle&x", "bundle#x", " bundle"] {
|
for id in ["bundle/1", "bundle?x", "bundle&x", "bundle#x", " bundle"] {
|
||||||
|
|
|
||||||
|
|
@ -850,6 +850,7 @@ mod tests {
|
||||||
}],
|
}],
|
||||||
declarations: Vec::new(),
|
declarations: Vec::new(),
|
||||||
profile_source_archive: None,
|
profile_source_archive: None,
|
||||||
|
profile_source_archive_handle: None,
|
||||||
}
|
}
|
||||||
.with_computed_digest()
|
.with_computed_digest()
|
||||||
}
|
}
|
||||||
|
|
@ -1137,6 +1138,7 @@ mod ws_tests {
|
||||||
}],
|
}],
|
||||||
declarations: Vec::new(),
|
declarations: Vec::new(),
|
||||||
profile_source_archive: None,
|
profile_source_archive: None,
|
||||||
|
profile_source_archive_handle: None,
|
||||||
}
|
}
|
||||||
.with_computed_digest()
|
.with_computed_digest()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,7 @@ pub mod interaction;
|
||||||
pub mod management;
|
pub mod management;
|
||||||
pub mod observation;
|
pub mod observation;
|
||||||
pub mod profile_archive;
|
pub mod profile_archive;
|
||||||
|
pub mod resource;
|
||||||
mod runtime;
|
mod runtime;
|
||||||
pub mod worker_backend;
|
pub mod worker_backend;
|
||||||
pub mod working_directory;
|
pub mod working_directory;
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,14 @@ fn build_runtime(config: &ProcessConfig) -> Result<Runtime, ProcessError> {
|
||||||
if let Some(runtime_base_dir) = config.worker_runtime_base_dir.clone() {
|
if let Some(runtime_base_dir) = config.worker_runtime_base_dir.clone() {
|
||||||
factory = factory.with_runtime_base_dir(runtime_base_dir);
|
factory = factory.with_runtime_base_dir(runtime_base_dir);
|
||||||
}
|
}
|
||||||
|
if let Some(endpoint) = config.backend_resource_endpoint.clone() {
|
||||||
|
factory = factory.with_resource_client(Arc::new(
|
||||||
|
worker_runtime::resource::HttpBackendResourceClient::new(
|
||||||
|
endpoint,
|
||||||
|
config.backend_resource_token.clone(),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
if let Some(profile) = config.profile.clone() {
|
if let Some(profile) = config.profile.clone() {
|
||||||
factory = factory.with_profile(profile);
|
factory = factory.with_profile(profile);
|
||||||
}
|
}
|
||||||
|
|
@ -173,6 +181,13 @@ where
|
||||||
config.worker_runtime_base_dir =
|
config.worker_runtime_base_dir =
|
||||||
Some(PathBuf::from(take_value(&flag, inline_value, &mut args)?));
|
Some(PathBuf::from(take_value(&flag, inline_value, &mut args)?));
|
||||||
}
|
}
|
||||||
|
"--backend-resource-endpoint" => {
|
||||||
|
config.backend_resource_endpoint =
|
||||||
|
Some(take_value(&flag, inline_value, &mut args)?);
|
||||||
|
}
|
||||||
|
"--backend-resource-token" => {
|
||||||
|
config.backend_resource_token = Some(take_value(&flag, inline_value, &mut args)?);
|
||||||
|
}
|
||||||
"--profile" => {
|
"--profile" => {
|
||||||
config.profile = Some(take_value(&flag, inline_value, &mut args)?);
|
config.profile = Some(take_value(&flag, inline_value, &mut args)?);
|
||||||
}
|
}
|
||||||
|
|
@ -317,6 +332,8 @@ struct ProcessConfig {
|
||||||
worker_store_dir: Option<PathBuf>,
|
worker_store_dir: Option<PathBuf>,
|
||||||
worker_metadata_dir: Option<PathBuf>,
|
worker_metadata_dir: Option<PathBuf>,
|
||||||
worker_runtime_base_dir: Option<PathBuf>,
|
worker_runtime_base_dir: Option<PathBuf>,
|
||||||
|
backend_resource_endpoint: Option<String>,
|
||||||
|
backend_resource_token: Option<String>,
|
||||||
profile: Option<String>,
|
profile: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -330,6 +347,8 @@ impl ProcessConfig {
|
||||||
worker_store_dir: None,
|
worker_store_dir: None,
|
||||||
worker_metadata_dir: None,
|
worker_metadata_dir: None,
|
||||||
worker_runtime_base_dir: None,
|
worker_runtime_base_dir: None,
|
||||||
|
backend_resource_endpoint: None,
|
||||||
|
backend_resource_token: None,
|
||||||
profile: None,
|
profile: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -405,6 +424,8 @@ Options:\n\
|
||||||
--worker-store-dir <PATH> Worker session store directory\n\
|
--worker-store-dir <PATH> Worker session store directory\n\
|
||||||
--worker-metadata-dir <PATH> Worker metadata directory\n\
|
--worker-metadata-dir <PATH> Worker metadata directory\n\
|
||||||
--worker-runtime-base-dir <PATH> Worker controller runtime directory\n\
|
--worker-runtime-base-dir <PATH> Worker controller runtime directory\n\
|
||||||
|
--backend-resource-endpoint <URL> Internal Backend resource fetch endpoint for resource handles\n\
|
||||||
|
--backend-resource-token <TOKEN> Optional bearer token for the Backend resource fetch endpoint\n\
|
||||||
--store <memory|fs> Runtime catalog store selection (default: memory)\n\
|
--store <memory|fs> Runtime catalog store selection (default: memory)\n\
|
||||||
--fs-root <PATH> Runtime catalog filesystem store root\n\
|
--fs-root <PATH> Runtime catalog filesystem store root\n\
|
||||||
--local-token <TOKEN> Minimal local bearer token placeholder\n\
|
--local-token <TOKEN> Minimal local bearer token placeholder\n\
|
||||||
|
|
|
||||||
|
|
@ -472,7 +472,7 @@ fn validate_archive_path(path: &str) -> Result<(), ProfileArchiveError> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sha256_hex(data: &[u8]) -> String {
|
pub fn sha256_hex(data: &[u8]) -> String {
|
||||||
let digest = Sha256::digest(data);
|
let digest = Sha256::digest(data);
|
||||||
let mut out = String::from("sha256:");
|
let mut out = String::from("sha256:");
|
||||||
for byte in digest.as_slice() {
|
for byte in digest.as_slice() {
|
||||||
|
|
|
||||||
336
crates/worker-runtime/src/resource.rs
Normal file
336
crates/worker-runtime/src/resource.rs
Normal file
|
|
@ -0,0 +1,336 @@
|
||||||
|
use crate::identity::{RuntimeId, WorkerId};
|
||||||
|
use crate::profile_archive::{ProfileSourceArchive, ProfileSourceArchiveRef, sha256_hex};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
pub const PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE: &str =
|
||||||
|
"application/vnd.yoi.profile-source-archive+tar";
|
||||||
|
pub const DEFAULT_PROFILE_SOURCE_ARCHIVE_MAX_BYTES: u64 = 2 * 1024 * 1024;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum BackendResourceKind {
|
||||||
|
ProfileSourceArchive,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum BackendResourceOperation {
|
||||||
|
FetchArchive,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct BackendResourceHandle {
|
||||||
|
pub kind: BackendResourceKind,
|
||||||
|
pub workspace_id: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub scope_id: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub runtime_id: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub worker_id: Option<String>,
|
||||||
|
pub resource_id: String,
|
||||||
|
pub digest: String,
|
||||||
|
pub operation: BackendResourceOperation,
|
||||||
|
pub expires_at_unix_seconds: i64,
|
||||||
|
pub nonce: String,
|
||||||
|
pub revision: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub generation: Option<u64>,
|
||||||
|
pub max_bytes: u64,
|
||||||
|
pub content_type: String,
|
||||||
|
pub redaction: ResourceRedactionPolicy,
|
||||||
|
pub audit_correlation_id: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub profile_source_graph: Option<crate::profile_archive::ProfileSourceGraphSummary>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum ResourceRedactionPolicy {
|
||||||
|
RuntimeInternalOnly,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct BackendResourceFetchRequest {
|
||||||
|
pub handle: BackendResourceHandle,
|
||||||
|
pub runtime_id: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub worker_id: Option<String>,
|
||||||
|
pub audit_correlation_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct BackendResourceFetchResponse {
|
||||||
|
pub kind: BackendResourceKind,
|
||||||
|
pub resource_id: String,
|
||||||
|
pub digest: String,
|
||||||
|
pub content_type: String,
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub audit_correlation_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
|
||||||
|
#[serde(tag = "code", rename_all = "snake_case")]
|
||||||
|
pub enum BackendResourceError {
|
||||||
|
#[error("backend resource handle is expired")]
|
||||||
|
Expired,
|
||||||
|
#[error("backend resource handle is unauthorized: {message}")]
|
||||||
|
Unauthorized { message: String },
|
||||||
|
#[error("backend resource kind is unsupported")]
|
||||||
|
UnsupportedKind,
|
||||||
|
#[error("backend resource is missing")]
|
||||||
|
MissingResource,
|
||||||
|
#[error("backend resource digest mismatch: expected {expected}, got {actual}")]
|
||||||
|
DigestMismatch { expected: String, actual: String },
|
||||||
|
#[error("backend resource response is oversized: limit {max_bytes}, actual {actual_bytes}")]
|
||||||
|
Oversized { max_bytes: u64, actual_bytes: u64 },
|
||||||
|
#[error("backend resource content type mismatch: expected {expected}, got {actual}")]
|
||||||
|
ContentTypeMismatch { expected: String, actual: String },
|
||||||
|
#[error("backend resource transport failed: {message}")]
|
||||||
|
Transport { message: String },
|
||||||
|
#[error("backend resource response is invalid: {message}")]
|
||||||
|
InvalidResponse { message: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait BackendResourceClient: Send + Sync + 'static {
|
||||||
|
async fn fetch_resource(
|
||||||
|
&self,
|
||||||
|
request: BackendResourceFetchRequest,
|
||||||
|
) -> Result<BackendResourceFetchResponse, BackendResourceError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "http-server")]
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct HttpBackendResourceClient {
|
||||||
|
endpoint: String,
|
||||||
|
bearer_token: Option<String>,
|
||||||
|
client: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "http-server")]
|
||||||
|
impl HttpBackendResourceClient {
|
||||||
|
pub fn new(endpoint: impl Into<String>, bearer_token: Option<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
endpoint: endpoint.into(),
|
||||||
|
bearer_token,
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "http-server")]
|
||||||
|
#[async_trait]
|
||||||
|
impl BackendResourceClient for HttpBackendResourceClient {
|
||||||
|
async fn fetch_resource(
|
||||||
|
&self,
|
||||||
|
request: BackendResourceFetchRequest,
|
||||||
|
) -> Result<BackendResourceFetchResponse, BackendResourceError> {
|
||||||
|
let builder = self.client.post(&self.endpoint).json(&request);
|
||||||
|
let builder = if let Some(token) = self.bearer_token.as_deref() {
|
||||||
|
builder.bearer_auth(token)
|
||||||
|
} else {
|
||||||
|
builder
|
||||||
|
};
|
||||||
|
let response = builder
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|err| BackendResourceError::Transport {
|
||||||
|
message: err.to_string(),
|
||||||
|
})?;
|
||||||
|
if response.status().is_success() {
|
||||||
|
response
|
||||||
|
.json::<BackendResourceFetchResponse>()
|
||||||
|
.await
|
||||||
|
.map_err(|err| BackendResourceError::InvalidResponse {
|
||||||
|
message: err.to_string(),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
let status = response.status();
|
||||||
|
match response.json::<BackendResourceError>().await {
|
||||||
|
Ok(error) => Err(error),
|
||||||
|
Err(err) => Err(BackendResourceError::Transport {
|
||||||
|
message: format!("backend resource fetch failed with HTTP {status}: {err}"),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
pub struct ProfileSourceArchiveCache {
|
||||||
|
archives: Mutex<HashMap<String, ProfileSourceArchive>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProfileSourceArchiveCache {
|
||||||
|
pub fn get(&self, digest: &str) -> Option<ProfileSourceArchive> {
|
||||||
|
self.archives.lock().ok()?.get(digest).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert(&self, archive: ProfileSourceArchive) {
|
||||||
|
if let Ok(mut archives) = self.archives.lock() {
|
||||||
|
archives.insert(archive.reference.digest.clone(), archive);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_profile_source_archive_fetch_request(
|
||||||
|
handle: BackendResourceHandle,
|
||||||
|
runtime_id: &RuntimeId,
|
||||||
|
worker_id: Option<&WorkerId>,
|
||||||
|
) -> BackendResourceFetchRequest {
|
||||||
|
let audit_correlation_id = handle.audit_correlation_id.clone();
|
||||||
|
BackendResourceFetchRequest {
|
||||||
|
handle,
|
||||||
|
runtime_id: runtime_id.as_str().to_string(),
|
||||||
|
worker_id: worker_id.map(|id| id.as_str().to_string()),
|
||||||
|
audit_correlation_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn profile_source_archive_from_response(
|
||||||
|
handle: &BackendResourceHandle,
|
||||||
|
response: BackendResourceFetchResponse,
|
||||||
|
) -> Result<ProfileSourceArchive, BackendResourceError> {
|
||||||
|
if handle.kind != BackendResourceKind::ProfileSourceArchive
|
||||||
|
|| response.kind != BackendResourceKind::ProfileSourceArchive
|
||||||
|
{
|
||||||
|
return Err(BackendResourceError::UnsupportedKind);
|
||||||
|
}
|
||||||
|
if handle.operation != BackendResourceOperation::FetchArchive {
|
||||||
|
return Err(BackendResourceError::Unauthorized {
|
||||||
|
message: "resource handle operation is not fetch_archive".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if response.content_type != handle.content_type {
|
||||||
|
return Err(BackendResourceError::ContentTypeMismatch {
|
||||||
|
expected: handle.content_type.clone(),
|
||||||
|
actual: response.content_type,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let actual_bytes = response.bytes.len() as u64;
|
||||||
|
if actual_bytes > handle.max_bytes {
|
||||||
|
return Err(BackendResourceError::Oversized {
|
||||||
|
max_bytes: handle.max_bytes,
|
||||||
|
actual_bytes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let actual_digest = sha256_hex(&response.bytes);
|
||||||
|
if actual_digest != handle.digest || response.digest != handle.digest {
|
||||||
|
return Err(BackendResourceError::DigestMismatch {
|
||||||
|
expected: handle.digest.clone(),
|
||||||
|
actual: if response.digest != handle.digest {
|
||||||
|
response.digest
|
||||||
|
} else {
|
||||||
|
actual_digest
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(ProfileSourceArchive {
|
||||||
|
reference: ProfileSourceArchiveRef {
|
||||||
|
id: handle.resource_id.clone(),
|
||||||
|
digest: handle.digest.clone(),
|
||||||
|
size_bytes: actual_bytes,
|
||||||
|
source_graph: handle.profile_source_graph.clone().ok_or_else(|| {
|
||||||
|
BackendResourceError::InvalidResponse {
|
||||||
|
message: "profile source archive handle omitted source graph summary"
|
||||||
|
.to_string(),
|
||||||
|
}
|
||||||
|
})?,
|
||||||
|
},
|
||||||
|
content: response.bytes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate_resource_handle_text(label: &str, value: &str) -> Result<(), String> {
|
||||||
|
if value.trim().is_empty() {
|
||||||
|
return Err(format!("{label} must not be empty"));
|
||||||
|
}
|
||||||
|
if value.len() > 256 || value.contains('\0') || value.contains('\n') || value.contains('\r') {
|
||||||
|
return Err(format!("{label} contains unsupported boundary text"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::profile_archive::ProfileSourceGraphSummary;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
fn graph() -> ProfileSourceGraphSummary {
|
||||||
|
ProfileSourceGraphSummary {
|
||||||
|
source_count: 1,
|
||||||
|
total_source_bytes: 4,
|
||||||
|
entrypoints: BTreeMap::from([(
|
||||||
|
"default".to_string(),
|
||||||
|
"profiles/default.dcdl".to_string(),
|
||||||
|
)]),
|
||||||
|
import_count: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_for(bytes: &[u8]) -> BackendResourceHandle {
|
||||||
|
BackendResourceHandle {
|
||||||
|
kind: BackendResourceKind::ProfileSourceArchive,
|
||||||
|
workspace_id: "workspace-test".to_string(),
|
||||||
|
scope_id: Some("workspace-profile-source".to_string()),
|
||||||
|
runtime_id: Some("runtime-test".to_string()),
|
||||||
|
worker_id: Some("worker-test".to_string()),
|
||||||
|
resource_id: "profile-source-archive:test".to_string(),
|
||||||
|
digest: sha256_hex(bytes),
|
||||||
|
operation: BackendResourceOperation::FetchArchive,
|
||||||
|
expires_at_unix_seconds: 4_102_444_800,
|
||||||
|
nonce: "nonce-test".to_string(),
|
||||||
|
revision: sha256_hex(bytes),
|
||||||
|
generation: Some(1),
|
||||||
|
max_bytes: 1024,
|
||||||
|
content_type: PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
redaction: ResourceRedactionPolicy::RuntimeInternalOnly,
|
||||||
|
audit_correlation_id: "audit-test".to_string(),
|
||||||
|
profile_source_graph: Some(graph()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_verification_detects_digest_mismatch() {
|
||||||
|
let bytes = b"archive-bytes";
|
||||||
|
let handle = handle_for(bytes);
|
||||||
|
let error = profile_source_archive_from_response(
|
||||||
|
&handle,
|
||||||
|
BackendResourceFetchResponse {
|
||||||
|
kind: BackendResourceKind::ProfileSourceArchive,
|
||||||
|
resource_id: handle.resource_id.clone(),
|
||||||
|
digest: handle.digest.clone(),
|
||||||
|
content_type: PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
bytes: b"tampered-bytes".to_vec(),
|
||||||
|
audit_correlation_id: handle.audit_correlation_id.clone(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(error, BackendResourceError::DigestMismatch { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_verification_rejects_oversized_bytes() {
|
||||||
|
let bytes = b"archive-bytes";
|
||||||
|
let mut handle = handle_for(bytes);
|
||||||
|
handle.max_bytes = 2;
|
||||||
|
let error = profile_source_archive_from_response(
|
||||||
|
&handle,
|
||||||
|
BackendResourceFetchResponse {
|
||||||
|
kind: BackendResourceKind::ProfileSourceArchive,
|
||||||
|
resource_id: handle.resource_id.clone(),
|
||||||
|
digest: handle.digest.clone(),
|
||||||
|
content_type: PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
bytes: bytes.to_vec(),
|
||||||
|
audit_correlation_id: handle.audit_correlation_id.clone(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(error, BackendResourceError::Oversized { .. }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1628,6 +1628,7 @@ mod tests {
|
||||||
reference: "capability:read".to_string(),
|
reference: "capability:read".to_string(),
|
||||||
}],
|
}],
|
||||||
profile_source_archive: None,
|
profile_source_archive: None,
|
||||||
|
profile_source_archive_handle: None,
|
||||||
}
|
}
|
||||||
.with_computed_digest()
|
.with_computed_digest()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,10 @@ use crate::execution::{
|
||||||
WorkerExecutionRunState, WorkerExecutionSpawnRequest, WorkerExecutionSpawnResult,
|
WorkerExecutionRunState, WorkerExecutionSpawnRequest, WorkerExecutionSpawnResult,
|
||||||
};
|
};
|
||||||
use crate::interaction::{WorkerInput, WorkerInputKind};
|
use crate::interaction::{WorkerInput, WorkerInputKind};
|
||||||
|
use crate::resource::{
|
||||||
|
BackendResourceClient, BackendResourceError, ProfileSourceArchiveCache,
|
||||||
|
build_profile_source_archive_fetch_request, profile_source_archive_from_response,
|
||||||
|
};
|
||||||
use crate::working_directory::{WorkingDirectoryBinding, WorkingDirectoryMaterializer};
|
use crate::working_directory::{WorkingDirectoryBinding, WorkingDirectoryMaterializer};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use manifest::paths;
|
use manifest::paths;
|
||||||
|
|
@ -46,7 +50,7 @@ pub trait RuntimeWorkerFactory: Send + Sync + 'static {
|
||||||
|
|
||||||
/// Production factory that resolves a normal Worker profile and spawns it under
|
/// Production factory that resolves a normal Worker profile and spawns it under
|
||||||
/// `WorkerController`.
|
/// `WorkerController`.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ProfileRuntimeWorkerFactory {
|
pub struct ProfileRuntimeWorkerFactory {
|
||||||
profile_base_dir: PathBuf,
|
profile_base_dir: PathBuf,
|
||||||
cwd: PathBuf,
|
cwd: PathBuf,
|
||||||
|
|
@ -54,6 +58,8 @@ pub struct ProfileRuntimeWorkerFactory {
|
||||||
worker_metadata_dir: Option<PathBuf>,
|
worker_metadata_dir: Option<PathBuf>,
|
||||||
profile: Option<String>,
|
profile: Option<String>,
|
||||||
runtime_base_dir: Option<PathBuf>,
|
runtime_base_dir: Option<PathBuf>,
|
||||||
|
resource_client: Option<Arc<dyn BackendResourceClient>>,
|
||||||
|
profile_archive_cache: Arc<ProfileSourceArchiveCache>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ProfileRuntimeWorkerFactory {
|
impl ProfileRuntimeWorkerFactory {
|
||||||
|
|
@ -66,6 +72,8 @@ impl ProfileRuntimeWorkerFactory {
|
||||||
worker_metadata_dir: None,
|
worker_metadata_dir: None,
|
||||||
profile: None,
|
profile: None,
|
||||||
runtime_base_dir: None,
|
runtime_base_dir: None,
|
||||||
|
resource_client: None,
|
||||||
|
profile_archive_cache: Arc::new(ProfileSourceArchiveCache::default()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -96,6 +104,11 @@ impl ProfileRuntimeWorkerFactory {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_resource_client(mut self, resource_client: Arc<dyn BackendResourceClient>) -> Self {
|
||||||
|
self.resource_client = Some(resource_client);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
fn store_dir(&self) -> Result<PathBuf, String> {
|
fn store_dir(&self) -> Result<PathBuf, String> {
|
||||||
self.store_dir
|
self.store_dir
|
||||||
.clone()
|
.clone()
|
||||||
|
|
@ -152,6 +165,56 @@ impl ProfileRuntimeWorkerFactory {
|
||||||
}
|
}
|
||||||
Self::runtime_profile_value(&request.request.profile)
|
Self::runtime_profile_value(&request.request.profile)
|
||||||
}
|
}
|
||||||
|
async fn resolve_profile_source_archive(
|
||||||
|
&self,
|
||||||
|
bundle: &crate::config_bundle::ConfigBundle,
|
||||||
|
request: &WorkerExecutionSpawnRequest,
|
||||||
|
) -> Result<crate::profile_archive::VerifiedProfileSourceArchive, String> {
|
||||||
|
if let Some(archive) = verified_profile_source_archive(bundle)
|
||||||
|
.map_err(|err| format!("failed to verify profile source archive: {err}"))?
|
||||||
|
{
|
||||||
|
return Ok(archive);
|
||||||
|
}
|
||||||
|
let handle = bundle
|
||||||
|
.profile_source_archive_handle
|
||||||
|
.clone()
|
||||||
|
.ok_or_else(|| {
|
||||||
|
format!(
|
||||||
|
"config bundle {} does not contain a ProfileSourceArchive resource handle",
|
||||||
|
bundle.metadata.id
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let client = self.resource_client.as_ref().ok_or_else(|| {
|
||||||
|
format!(
|
||||||
|
"config bundle {} requires a Backend resource client for profile source archive fetch",
|
||||||
|
bundle.metadata.id
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let fetch_request = build_profile_source_archive_fetch_request(
|
||||||
|
handle.clone(),
|
||||||
|
&request.worker_ref.runtime_id,
|
||||||
|
Some(&request.worker_ref.worker_id),
|
||||||
|
);
|
||||||
|
let response = client
|
||||||
|
.fetch_resource(fetch_request)
|
||||||
|
.await
|
||||||
|
.map_err(format_backend_resource_error)?;
|
||||||
|
let fetched_archive = profile_source_archive_from_response(&handle, response)
|
||||||
|
.map_err(format_backend_resource_error)?;
|
||||||
|
if let Some(cached) = self.profile_archive_cache.get(&handle.digest) {
|
||||||
|
return cached
|
||||||
|
.verify()
|
||||||
|
.map_err(|err| format!("failed to verify cached profile source archive: {err}"));
|
||||||
|
}
|
||||||
|
self.profile_archive_cache.insert(fetched_archive.clone());
|
||||||
|
fetched_archive
|
||||||
|
.verify()
|
||||||
|
.map_err(|err| format!("failed to verify fetched profile source archive: {err}"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_backend_resource_error(error: BackendResourceError) -> String {
|
||||||
|
format!("backend resource fetch failed: {error}")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
|
|
@ -174,14 +237,9 @@ impl RuntimeWorkerFactory for ProfileRuntimeWorkerFactory {
|
||||||
.unwrap_or_else(|| self.cwd.clone());
|
.unwrap_or_else(|| self.cwd.clone());
|
||||||
let (mut manifest, loader) = if let Some(bundle) = request.config_bundle.as_ref() {
|
let (mut manifest, loader) = if let Some(bundle) = request.config_bundle.as_ref() {
|
||||||
let selector = profile.as_deref().unwrap_or("builtin:default");
|
let selector = profile.as_deref().unwrap_or("builtin:default");
|
||||||
let archive = verified_profile_source_archive(bundle)
|
let archive = self
|
||||||
.map_err(|err| format!("failed to verify profile source archive: {err}"))?
|
.resolve_profile_source_archive(bundle, &request)
|
||||||
.ok_or_else(|| {
|
.await?;
|
||||||
format!(
|
|
||||||
"config bundle {} does not contain a ProfileSourceArchive",
|
|
||||||
bundle.metadata.id
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
let manifest = archive
|
let manifest = archive
|
||||||
.resolve_profile(selector, &worker_root, &worker_name)
|
.resolve_profile(selector, &worker_root, &worker_name)
|
||||||
.map_err(|err| format!("failed to resolve profile source archive: {err}"))?;
|
.map_err(|err| format!("failed to resolve profile source archive: {err}"))?;
|
||||||
|
|
@ -643,6 +701,7 @@ where
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use std::collections::{BTreeMap, VecDeque};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
@ -653,6 +712,7 @@ mod tests {
|
||||||
ConfigBundleRef, CreateWorkerRequest, DirtyStatePolicy, MaterializerKind, ProfileSelector,
|
ConfigBundleRef, CreateWorkerRequest, DirtyStatePolicy, MaterializerKind, ProfileSelector,
|
||||||
RepositorySelector, WorkingDirectoryRepository, WorkingDirectoryRequest,
|
RepositorySelector, WorkingDirectoryRepository, WorkingDirectoryRequest,
|
||||||
};
|
};
|
||||||
|
use crate::execution::WorkerExecutionContext;
|
||||||
use crate::identity::RuntimeId;
|
use crate::identity::RuntimeId;
|
||||||
use crate::management::RuntimeOptions;
|
use crate::management::RuntimeOptions;
|
||||||
use crate::observation::{TranscriptQuery, TranscriptRole};
|
use crate::observation::{TranscriptQuery, TranscriptRole};
|
||||||
|
|
@ -791,10 +851,130 @@ mod tests {
|
||||||
}],
|
}],
|
||||||
declarations: Vec::new(),
|
declarations: Vec::new(),
|
||||||
profile_source_archive: None,
|
profile_source_archive: None,
|
||||||
|
profile_source_archive_handle: None,
|
||||||
}
|
}
|
||||||
.with_computed_digest()
|
.with_computed_digest()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sample_profile_archive() -> crate::profile_archive::ProfileSourceArchive {
|
||||||
|
let entrypoints =
|
||||||
|
BTreeMap::from([("default".to_string(), "profiles/default.dcdl".to_string())]);
|
||||||
|
let sources = BTreeMap::from([(
|
||||||
|
"profiles/default.dcdl".to_string(),
|
||||||
|
r#"{
|
||||||
|
slug = "default";
|
||||||
|
description = "Default";
|
||||||
|
scope = "workspace_read";
|
||||||
|
}"#
|
||||||
|
.to_string(),
|
||||||
|
)]);
|
||||||
|
crate::profile_archive::ProfileSourceArchive::build(
|
||||||
|
crate::profile_archive::ProfileSourceArchiveInput {
|
||||||
|
id: "profile-source-archive:test".to_string(),
|
||||||
|
entrypoints,
|
||||||
|
imports: BTreeMap::new(),
|
||||||
|
sources,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_for_archive(
|
||||||
|
archive: &crate::profile_archive::ProfileSourceArchive,
|
||||||
|
) -> crate::resource::BackendResourceHandle {
|
||||||
|
crate::resource::BackendResourceHandle {
|
||||||
|
kind: crate::resource::BackendResourceKind::ProfileSourceArchive,
|
||||||
|
workspace_id: "workspace-test".to_string(),
|
||||||
|
scope_id: Some("workspace-profile-source".to_string()),
|
||||||
|
runtime_id: Some("runtime-test".to_string()),
|
||||||
|
worker_id: Some("worker-test".to_string()),
|
||||||
|
resource_id: archive.reference.id.clone(),
|
||||||
|
digest: archive.reference.digest.clone(),
|
||||||
|
operation: crate::resource::BackendResourceOperation::FetchArchive,
|
||||||
|
expires_at_unix_seconds: 4_102_444_800,
|
||||||
|
nonce: "nonce-test".to_string(),
|
||||||
|
revision: archive.reference.digest.clone(),
|
||||||
|
generation: Some(1),
|
||||||
|
max_bytes: crate::resource::DEFAULT_PROFILE_SOURCE_ARCHIVE_MAX_BYTES,
|
||||||
|
content_type: crate::resource::PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
redaction: crate::resource::ResourceRedactionPolicy::RuntimeInternalOnly,
|
||||||
|
audit_correlation_id: "audit-test".to_string(),
|
||||||
|
profile_source_graph: Some(archive.reference.source_graph.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response_for_archive(
|
||||||
|
handle: &crate::resource::BackendResourceHandle,
|
||||||
|
archive: &crate::profile_archive::ProfileSourceArchive,
|
||||||
|
) -> crate::resource::BackendResourceFetchResponse {
|
||||||
|
crate::resource::BackendResourceFetchResponse {
|
||||||
|
kind: crate::resource::BackendResourceKind::ProfileSourceArchive,
|
||||||
|
resource_id: handle.resource_id.clone(),
|
||||||
|
digest: handle.digest.clone(),
|
||||||
|
content_type: crate::resource::PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
bytes: archive.content.clone(),
|
||||||
|
audit_correlation_id: handle.audit_correlation_id.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct SequencedResourceClient {
|
||||||
|
responses: Arc<
|
||||||
|
Mutex<
|
||||||
|
VecDeque<
|
||||||
|
Result<
|
||||||
|
crate::resource::BackendResourceFetchResponse,
|
||||||
|
crate::resource::BackendResourceError,
|
||||||
|
>,
|
||||||
|
>,
|
||||||
|
>,
|
||||||
|
>,
|
||||||
|
call_count: Arc<AtomicUsize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl crate::resource::BackendResourceClient for SequencedResourceClient {
|
||||||
|
async fn fetch_resource(
|
||||||
|
&self,
|
||||||
|
_request: crate::resource::BackendResourceFetchRequest,
|
||||||
|
) -> Result<
|
||||||
|
crate::resource::BackendResourceFetchResponse,
|
||||||
|
crate::resource::BackendResourceError,
|
||||||
|
> {
|
||||||
|
self.call_count.fetch_add(1, Ordering::SeqCst);
|
||||||
|
self.responses
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.pop_front()
|
||||||
|
.expect("missing sequenced resource response")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_request_with_bundle(
|
||||||
|
bundle: crate::config_bundle::ConfigBundle,
|
||||||
|
) -> WorkerExecutionSpawnRequest {
|
||||||
|
let worker_ref = crate::identity::WorkerRef::new(
|
||||||
|
RuntimeId::new("runtime-test").unwrap(),
|
||||||
|
crate::identity::WorkerId::new("worker-test").unwrap(),
|
||||||
|
);
|
||||||
|
WorkerExecutionSpawnRequest {
|
||||||
|
worker_ref: worker_ref.clone(),
|
||||||
|
request: CreateWorkerRequest {
|
||||||
|
profile: ProfileSelector::RuntimeDefault,
|
||||||
|
config_bundle: ConfigBundleRef {
|
||||||
|
id: bundle.metadata.id.clone(),
|
||||||
|
digest: bundle.metadata.digest.clone(),
|
||||||
|
},
|
||||||
|
initial_input: None,
|
||||||
|
working_directory_request: None,
|
||||||
|
working_directory: None,
|
||||||
|
},
|
||||||
|
context: WorkerExecutionContext::new(worker_ref, Arc::new(|_, _| panic!("unused"))),
|
||||||
|
working_directory: None,
|
||||||
|
config_bundle: Some(bundle),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn create_request(_name: &str) -> CreateWorkerRequest {
|
fn create_request(_name: &str) -> CreateWorkerRequest {
|
||||||
let bundle = test_bundle();
|
let bundle = test_bundle();
|
||||||
CreateWorkerRequest {
|
CreateWorkerRequest {
|
||||||
|
|
@ -847,6 +1027,37 @@ mod tests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn cached_profile_archive_still_requires_backend_authorization() {
|
||||||
|
let archive = sample_profile_archive();
|
||||||
|
let handle = handle_for_archive(&archive);
|
||||||
|
let call_count = Arc::new(AtomicUsize::new(0));
|
||||||
|
let client = SequencedResourceClient {
|
||||||
|
responses: Arc::new(Mutex::new(VecDeque::from([
|
||||||
|
Ok(response_for_archive(&handle, &archive)),
|
||||||
|
Err(crate::resource::BackendResourceError::Expired),
|
||||||
|
]))),
|
||||||
|
call_count: call_count.clone(),
|
||||||
|
};
|
||||||
|
let factory = ProfileRuntimeWorkerFactory::new(tempfile::tempdir().unwrap().path())
|
||||||
|
.with_resource_client(Arc::new(client));
|
||||||
|
let mut bundle = test_bundle();
|
||||||
|
bundle.profile_source_archive_handle = Some(handle);
|
||||||
|
bundle = bundle.with_computed_digest();
|
||||||
|
|
||||||
|
factory
|
||||||
|
.resolve_profile_source_archive(&bundle, &spawn_request_with_bundle(bundle.clone()))
|
||||||
|
.await
|
||||||
|
.expect("first fetch should authorize and cache archive");
|
||||||
|
let err = factory
|
||||||
|
.resolve_profile_source_archive(&bundle, &spawn_request_with_bundle(bundle.clone()))
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
|
||||||
|
assert!(err.contains("expired"), "unexpected error: {err}");
|
||||||
|
assert_eq!(call_count.load(Ordering::SeqCst), 2);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn builtin_profile_selector_is_not_double_prefixed() {
|
fn builtin_profile_selector_is_not_double_prefixed() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|
|
||||||
|
|
@ -392,6 +392,7 @@ fn spawn_companion_worker(runtime: &RuntimeRegistry) -> CompanionWorkerState {
|
||||||
working_directory_request: None,
|
working_directory_request: None,
|
||||||
resolved_working_directory_request: None,
|
resolved_working_directory_request: None,
|
||||||
resolved_working_directory: None,
|
resolved_working_directory: None,
|
||||||
|
resolved_config_bundle: None,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -455,6 +456,7 @@ fn companion_config_bundle() -> ConfigBundle {
|
||||||
}],
|
}],
|
||||||
declarations: Vec::new(),
|
declarations: Vec::new(),
|
||||||
profile_source_archive: Some(companion_profile_archive()),
|
profile_source_archive: Some(companion_profile_archive()),
|
||||||
|
profile_source_archive_handle: None,
|
||||||
}
|
}
|
||||||
.with_computed_digest()
|
.with_computed_digest()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
use crate::Error;
|
use crate::Error;
|
||||||
|
use crate::resource_broker::BackendResourceBroker;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use reqwest::StatusCode;
|
use reqwest::StatusCode;
|
||||||
use reqwest::blocking::{Client as BlockingHttpClient, RequestBuilder};
|
use reqwest::blocking::{Client as BlockingHttpClient, RequestBuilder};
|
||||||
|
|
@ -306,6 +307,8 @@ pub struct WorkerSpawnRequest {
|
||||||
pub resolved_working_directory_request: Option<WorkingDirectoryRequest>,
|
pub resolved_working_directory_request: Option<WorkingDirectoryRequest>,
|
||||||
#[serde(skip, default)]
|
#[serde(skip, default)]
|
||||||
pub resolved_working_directory: Option<WorkingDirectoryClaim>,
|
pub resolved_working_directory: Option<WorkingDirectoryClaim>,
|
||||||
|
#[serde(skip, default)]
|
||||||
|
pub resolved_config_bundle: Option<ConfigBundle>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
|
@ -1032,6 +1035,7 @@ pub struct EmbeddedWorkerRuntime {
|
||||||
host_id: String,
|
host_id: String,
|
||||||
runtime: worker_runtime::Runtime,
|
runtime: worker_runtime::Runtime,
|
||||||
execution_enabled: bool,
|
execution_enabled: bool,
|
||||||
|
resource_broker: BackendResourceBroker,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn embedded_runtime_options() -> EmbeddedRuntimeOptions {
|
fn embedded_runtime_options() -> EmbeddedRuntimeOptions {
|
||||||
|
|
@ -1082,6 +1086,11 @@ impl EmbeddedWorkerRuntime {
|
||||||
Ok(embedded)
|
Ok(embedded)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_resource_broker(mut self, resource_broker: BackendResourceBroker) -> Self {
|
||||||
|
self.resource_broker = resource_broker;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub fn from_runtime(workspace_id: impl AsRef<str>, runtime: worker_runtime::Runtime) -> Self {
|
pub fn from_runtime(workspace_id: impl AsRef<str>, runtime: worker_runtime::Runtime) -> Self {
|
||||||
let runtime_id = runtime
|
let runtime_id = runtime
|
||||||
.runtime_id()
|
.runtime_id()
|
||||||
|
|
@ -1093,6 +1102,7 @@ impl EmbeddedWorkerRuntime {
|
||||||
host_id: host_id_for_embedded_workspace(workspace_id.as_ref()),
|
host_id: host_id_for_embedded_workspace(workspace_id.as_ref()),
|
||||||
runtime,
|
runtime,
|
||||||
execution_enabled: false,
|
execution_enabled: false,
|
||||||
|
resource_broker: BackendResourceBroker::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1339,11 +1349,24 @@ impl WorkspaceWorkerRuntime for EmbeddedWorkerRuntime {
|
||||||
.profile
|
.profile
|
||||||
.clone()
|
.clone()
|
||||||
.unwrap_or_else(|| embedded_profile_selector(&request.intent));
|
.unwrap_or_else(|| embedded_profile_selector(&request.intent));
|
||||||
let config_bundle = match default_embedded_config_bundle(&profile).and_then(|bundle| {
|
let runtime_id = EmbeddedRuntimeId::new(self.runtime_id.clone());
|
||||||
self.runtime
|
let config_bundle = match request
|
||||||
.store_config_bundle(bundle)
|
.resolved_config_bundle
|
||||||
.map_err(|err| err.to_string())
|
.clone()
|
||||||
}) {
|
.map(Ok)
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
default_embedded_config_bundle(
|
||||||
|
&profile,
|
||||||
|
&self.host_id,
|
||||||
|
runtime_id.as_ref(),
|
||||||
|
&self.resource_broker,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.and_then(|bundle| {
|
||||||
|
self.runtime
|
||||||
|
.store_config_bundle(bundle)
|
||||||
|
.map_err(|err| err.to_string())
|
||||||
|
}) {
|
||||||
Ok(availability) => availability.reference,
|
Ok(availability) => availability.reference,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
diagnostics.push(diagnostic(
|
diagnostics.push(diagnostic(
|
||||||
|
|
@ -1717,6 +1740,7 @@ pub struct RemoteWorkerRuntime {
|
||||||
cached_capabilities: RuntimeCapabilitySummary,
|
cached_capabilities: RuntimeCapabilitySummary,
|
||||||
cached_status: String,
|
cached_status: String,
|
||||||
host_id: String,
|
host_id: String,
|
||||||
|
resource_broker: BackendResourceBroker,
|
||||||
http: BlockingHttpClient,
|
http: BlockingHttpClient,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1740,10 +1764,16 @@ impl RemoteWorkerRuntime {
|
||||||
bearer_token: config.bearer_token,
|
bearer_token: config.bearer_token,
|
||||||
cached_capabilities: config.cached_capabilities,
|
cached_capabilities: config.cached_capabilities,
|
||||||
cached_status: config.cached_status,
|
cached_status: config.cached_status,
|
||||||
|
resource_broker: BackendResourceBroker::default(),
|
||||||
http,
|
http,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_resource_broker(mut self, resource_broker: BackendResourceBroker) -> Self {
|
||||||
|
self.resource_broker = resource_broker;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
fn endpoint(&self, path: &str) -> String {
|
fn endpoint(&self, path: &str) -> String {
|
||||||
format!("{}{}", self.base_url, path)
|
format!("{}{}", self.base_url, path)
|
||||||
}
|
}
|
||||||
|
|
@ -2025,7 +2055,19 @@ impl WorkspaceWorkerRuntime for RemoteWorkerRuntime {
|
||||||
.profile
|
.profile
|
||||||
.clone()
|
.clone()
|
||||||
.unwrap_or_else(|| embedded_profile_selector(&request.intent));
|
.unwrap_or_else(|| embedded_profile_selector(&request.intent));
|
||||||
let sync = match default_embedded_config_bundle(&profile) {
|
let runtime_id = EmbeddedRuntimeId::new(self.runtime_id.clone());
|
||||||
|
let sync = match request
|
||||||
|
.resolved_config_bundle
|
||||||
|
.clone()
|
||||||
|
.map(Ok)
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
default_embedded_config_bundle(
|
||||||
|
&profile,
|
||||||
|
&self.host_id,
|
||||||
|
runtime_id.as_ref(),
|
||||||
|
&self.resource_broker,
|
||||||
|
)
|
||||||
|
}) {
|
||||||
Ok(bundle) => self.sync_config_bundle(bundle),
|
Ok(bundle) => self.sync_config_bundle(bundle),
|
||||||
Err(error) => ConfigBundleSyncResult {
|
Err(error) => ConfigBundleSyncResult {
|
||||||
state: WorkerOperationState::Rejected,
|
state: WorkerOperationState::Rejected,
|
||||||
|
|
@ -2365,19 +2407,31 @@ fn embedded_worker_execution_status_label(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_embedded_config_bundle(profile: &ProfileSelector) -> Result<ConfigBundle, String> {
|
fn default_embedded_config_bundle(
|
||||||
|
profile: &ProfileSelector,
|
||||||
|
workspace_id: &str,
|
||||||
|
runtime_id: Option<&EmbeddedRuntimeId>,
|
||||||
|
resource_broker: &BackendResourceBroker,
|
||||||
|
) -> Result<ConfigBundle, String> {
|
||||||
let id = format!(
|
let id = format!(
|
||||||
"workspace-runtime-{}",
|
"workspace-runtime-{}",
|
||||||
embedded_profile_label(profile)
|
embedded_profile_label(profile)
|
||||||
.unwrap_or_else(|| "default".to_string())
|
.unwrap_or_else(|| "default".to_string())
|
||||||
.replace([':', '/', ' '], "-")
|
.replace([':', '/', ' '], "-")
|
||||||
);
|
);
|
||||||
|
let archive = default_profile_source_archive(profile)?;
|
||||||
|
let handle = resource_broker.issue_profile_source_archive_handle(
|
||||||
|
workspace_id.to_string(),
|
||||||
|
runtime_id,
|
||||||
|
None,
|
||||||
|
archive,
|
||||||
|
);
|
||||||
Ok(ConfigBundle {
|
Ok(ConfigBundle {
|
||||||
metadata: ConfigBundleMetadata {
|
metadata: ConfigBundleMetadata {
|
||||||
id,
|
id,
|
||||||
digest: String::new(),
|
digest: String::new(),
|
||||||
revision: "workspace-runtime-v0".to_string(),
|
revision: "workspace-runtime-v0".to_string(),
|
||||||
workspace_id: "workspace-server".to_string(),
|
workspace_id: workspace_id.to_string(),
|
||||||
created_at: "runtime-generated".to_string(),
|
created_at: "runtime-generated".to_string(),
|
||||||
provenance: ConfigBundleProvenance {
|
provenance: ConfigBundleProvenance {
|
||||||
source: "workspace-server".to_string(),
|
source: "workspace-server".to_string(),
|
||||||
|
|
@ -2389,7 +2443,8 @@ fn default_embedded_config_bundle(profile: &ProfileSelector) -> Result<ConfigBun
|
||||||
label: embedded_profile_label(profile),
|
label: embedded_profile_label(profile),
|
||||||
}],
|
}],
|
||||||
declarations: Vec::new(),
|
declarations: Vec::new(),
|
||||||
profile_source_archive: Some(default_profile_source_archive(profile)?),
|
profile_source_archive: None,
|
||||||
|
profile_source_archive_handle: Some(handle),
|
||||||
}
|
}
|
||||||
.with_computed_digest())
|
.with_computed_digest())
|
||||||
}
|
}
|
||||||
|
|
@ -2967,6 +3022,8 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn embedded_builtin_decodal_profiles_resolve_through_archive() {
|
fn embedded_builtin_decodal_profiles_resolve_through_archive() {
|
||||||
let root = tempfile::tempdir().unwrap();
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
let broker = BackendResourceBroker::default();
|
||||||
|
let runtime_id = EmbeddedRuntimeId::new("runtime-test".to_string()).unwrap();
|
||||||
for selector in [
|
for selector in [
|
||||||
ProfileSelector::RuntimeDefault,
|
ProfileSelector::RuntimeDefault,
|
||||||
ProfileSelector::Builtin("builtin:companion".to_string()),
|
ProfileSelector::Builtin("builtin:companion".to_string()),
|
||||||
|
|
@ -2975,13 +3032,30 @@ mod tests {
|
||||||
ProfileSelector::Builtin("builtin:coder".to_string()),
|
ProfileSelector::Builtin("builtin:coder".to_string()),
|
||||||
ProfileSelector::Builtin("builtin:reviewer".to_string()),
|
ProfileSelector::Builtin("builtin:reviewer".to_string()),
|
||||||
] {
|
] {
|
||||||
let bundle = default_embedded_config_bundle(&selector).unwrap();
|
let bundle = default_embedded_config_bundle(
|
||||||
let archive = bundle
|
&selector,
|
||||||
.profile_source_archive
|
"workspace-test",
|
||||||
.as_ref()
|
Some(&runtime_id),
|
||||||
.unwrap()
|
&broker,
|
||||||
.verify()
|
)
|
||||||
|
.unwrap();
|
||||||
|
let handle = bundle.profile_source_archive_handle.as_ref().unwrap();
|
||||||
|
assert!(bundle.profile_source_archive.is_none());
|
||||||
|
let response = broker
|
||||||
|
.fetch_profile_source_archive(
|
||||||
|
worker_runtime::resource::BackendResourceFetchRequest {
|
||||||
|
handle: handle.clone(),
|
||||||
|
runtime_id: runtime_id.as_str().to_string(),
|
||||||
|
worker_id: None,
|
||||||
|
audit_correlation_id: handle.audit_correlation_id.clone(),
|
||||||
|
},
|
||||||
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
let archive =
|
||||||
|
worker_runtime::resource::profile_source_archive_from_response(handle, response)
|
||||||
|
.unwrap()
|
||||||
|
.verify()
|
||||||
|
.unwrap();
|
||||||
let selector_key = match &selector {
|
let selector_key = match &selector {
|
||||||
ProfileSelector::RuntimeDefault => "default".to_string(),
|
ProfileSelector::RuntimeDefault => "default".to_string(),
|
||||||
ProfileSelector::Builtin(name) => name.clone(),
|
ProfileSelector::Builtin(name) => name.clone(),
|
||||||
|
|
@ -2996,14 +3070,25 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn embedded_archive_rejects_unknown_selectors() {
|
fn embedded_archive_rejects_unknown_selectors() {
|
||||||
|
let broker = BackendResourceBroker::default();
|
||||||
|
let runtime_id = EmbeddedRuntimeId::new("runtime-test".to_string()).unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
default_embedded_config_bundle(&ProfileSelector::Builtin(
|
default_embedded_config_bundle(
|
||||||
"builtin:missing".to_string()
|
&ProfileSelector::Builtin("builtin:missing".to_string()),
|
||||||
))
|
"workspace-test",
|
||||||
|
Some(&runtime_id),
|
||||||
|
&broker,
|
||||||
|
)
|
||||||
.is_err()
|
.is_err()
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
default_embedded_config_bundle(&ProfileSelector::Named("custom".to_string())).is_err()
|
default_embedded_config_bundle(
|
||||||
|
&ProfileSelector::Named("custom".to_string()),
|
||||||
|
"workspace-test",
|
||||||
|
Some(&runtime_id),
|
||||||
|
&broker,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -3030,6 +3115,7 @@ mod tests {
|
||||||
reference: "capability:read".to_string(),
|
reference: "capability:read".to_string(),
|
||||||
}],
|
}],
|
||||||
profile_source_archive: None,
|
profile_source_archive: None,
|
||||||
|
profile_source_archive_handle: None,
|
||||||
}
|
}
|
||||||
.with_computed_digest()
|
.with_computed_digest()
|
||||||
}
|
}
|
||||||
|
|
@ -3326,6 +3412,7 @@ mod tests {
|
||||||
working_directory_request: None,
|
working_directory_request: None,
|
||||||
resolved_working_directory_request: None,
|
resolved_working_directory_request: None,
|
||||||
resolved_working_directory: None,
|
resolved_working_directory: None,
|
||||||
|
resolved_config_bundle: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -3458,6 +3545,7 @@ mod tests {
|
||||||
working_directory_request: None,
|
working_directory_request: None,
|
||||||
resolved_working_directory_request: None,
|
resolved_working_directory_request: None,
|
||||||
resolved_working_directory: None,
|
resolved_working_directory: None,
|
||||||
|
resolved_config_bundle: None,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
@ -3560,6 +3648,7 @@ mod tests {
|
||||||
working_directory_request: None,
|
working_directory_request: None,
|
||||||
resolved_working_directory_request: None,
|
resolved_working_directory_request: None,
|
||||||
resolved_working_directory: None,
|
resolved_working_directory: None,
|
||||||
|
resolved_config_bundle: None,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
@ -3591,6 +3680,7 @@ mod tests {
|
||||||
working_directory_request: None,
|
working_directory_request: None,
|
||||||
resolved_working_directory_request: None,
|
resolved_working_directory_request: None,
|
||||||
resolved_working_directory: None,
|
resolved_working_directory: None,
|
||||||
|
resolved_config_bundle: None,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,10 @@ pub mod config;
|
||||||
pub mod hosts;
|
pub mod hosts;
|
||||||
pub mod identity;
|
pub mod identity;
|
||||||
pub mod observation;
|
pub mod observation;
|
||||||
|
pub mod profile_settings;
|
||||||
pub mod records;
|
pub mod records;
|
||||||
pub mod repositories;
|
pub mod repositories;
|
||||||
|
pub mod resource_broker;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod store;
|
pub mod store;
|
||||||
|
|
||||||
|
|
|
||||||
1478
crates/workspace-server/src/profile_settings.rs
Normal file
1478
crates/workspace-server/src/profile_settings.rs
Normal file
File diff suppressed because it is too large
Load Diff
336
crates/workspace-server/src/resource_broker.rs
Normal file
336
crates/workspace-server/src/resource_broker.rs
Normal file
|
|
@ -0,0 +1,336 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use chrono::{Duration, Utc};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use uuid::Uuid;
|
||||||
|
use worker_runtime::identity::{RuntimeId, WorkerId};
|
||||||
|
use worker_runtime::profile_archive::ProfileSourceArchive;
|
||||||
|
use worker_runtime::resource::{
|
||||||
|
BackendResourceClient, BackendResourceError, BackendResourceFetchRequest,
|
||||||
|
BackendResourceFetchResponse, BackendResourceHandle, BackendResourceKind,
|
||||||
|
BackendResourceOperation, DEFAULT_PROFILE_SOURCE_ARCHIVE_MAX_BYTES,
|
||||||
|
PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE, ResourceRedactionPolicy,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
pub struct BackendResourceBroker {
|
||||||
|
resources: Arc<Mutex<HashMap<String, StoredResource>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct StoredResource {
|
||||||
|
runtime_id: Option<String>,
|
||||||
|
worker_id: Option<String>,
|
||||||
|
handle: BackendResourceHandle,
|
||||||
|
archive: ProfileSourceArchive,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BackendResourceBroker {
|
||||||
|
pub fn issue_profile_source_archive_handle(
|
||||||
|
&self,
|
||||||
|
workspace_id: impl Into<String>,
|
||||||
|
runtime_id: Option<&RuntimeId>,
|
||||||
|
worker_id: Option<&WorkerId>,
|
||||||
|
archive: ProfileSourceArchive,
|
||||||
|
) -> BackendResourceHandle {
|
||||||
|
let workspace_id = workspace_id.into();
|
||||||
|
let nonce = Uuid::now_v7().to_string();
|
||||||
|
let audit_correlation_id = format!("resource-fetch-{nonce}");
|
||||||
|
let expires_at = Utc::now() + Duration::minutes(15);
|
||||||
|
let handle = BackendResourceHandle {
|
||||||
|
kind: BackendResourceKind::ProfileSourceArchive,
|
||||||
|
workspace_id: workspace_id.clone(),
|
||||||
|
scope_id: Some("workspace-profile-source".to_string()),
|
||||||
|
runtime_id: runtime_id.map(|id| id.as_str().to_string()),
|
||||||
|
worker_id: worker_id.map(|id| id.as_str().to_string()),
|
||||||
|
resource_id: archive.reference.id.clone(),
|
||||||
|
digest: archive.reference.digest.clone(),
|
||||||
|
operation: BackendResourceOperation::FetchArchive,
|
||||||
|
expires_at_unix_seconds: expires_at.timestamp(),
|
||||||
|
nonce: nonce.clone(),
|
||||||
|
revision: archive.reference.digest.clone(),
|
||||||
|
generation: None,
|
||||||
|
max_bytes: DEFAULT_PROFILE_SOURCE_ARCHIVE_MAX_BYTES,
|
||||||
|
content_type: PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
redaction: ResourceRedactionPolicy::RuntimeInternalOnly,
|
||||||
|
audit_correlation_id,
|
||||||
|
profile_source_graph: Some(archive.reference.source_graph.clone()),
|
||||||
|
};
|
||||||
|
let stored = StoredResource {
|
||||||
|
runtime_id: runtime_id.map(|id| id.as_str().to_string()),
|
||||||
|
worker_id: worker_id.map(|id| id.as_str().to_string()),
|
||||||
|
handle: handle.clone(),
|
||||||
|
archive,
|
||||||
|
};
|
||||||
|
if let Ok(mut resources) = self.resources.lock() {
|
||||||
|
resources.insert(nonce, stored);
|
||||||
|
}
|
||||||
|
handle
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fetch_profile_source_archive(
|
||||||
|
&self,
|
||||||
|
request: BackendResourceFetchRequest,
|
||||||
|
) -> Result<BackendResourceFetchResponse, BackendResourceError> {
|
||||||
|
verify_handle_shape(&request.handle)?;
|
||||||
|
let stored = self
|
||||||
|
.resources
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| BackendResourceError::Transport {
|
||||||
|
message: "resource broker lock poisoned".to_string(),
|
||||||
|
})?
|
||||||
|
.get(&request.handle.nonce)
|
||||||
|
.cloned()
|
||||||
|
.ok_or(BackendResourceError::MissingResource)?;
|
||||||
|
verify_handle_shape(&stored.handle)?;
|
||||||
|
if stored.handle.expires_at_unix_seconds < Utc::now().timestamp() {
|
||||||
|
return Err(BackendResourceError::Expired);
|
||||||
|
}
|
||||||
|
let actual_bytes = stored.archive.content.len() as u64;
|
||||||
|
if actual_bytes > stored.handle.max_bytes {
|
||||||
|
return Err(BackendResourceError::Oversized {
|
||||||
|
max_bytes: stored.handle.max_bytes,
|
||||||
|
actual_bytes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if request.handle != stored.handle {
|
||||||
|
return Err(BackendResourceError::Unauthorized {
|
||||||
|
message: "resource handle does not match broker-issued handle".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if let Some(expected_runtime_id) = stored.runtime_id.as_deref() {
|
||||||
|
if expected_runtime_id != request.runtime_id {
|
||||||
|
return Err(BackendResourceError::Unauthorized {
|
||||||
|
message: "runtime id does not match resource handle".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(expected_worker_id) = stored.worker_id.as_deref() {
|
||||||
|
if Some(expected_worker_id) != request.worker_id.as_deref() {
|
||||||
|
return Err(BackendResourceError::Unauthorized {
|
||||||
|
message: "worker id does not match resource handle".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(BackendResourceFetchResponse {
|
||||||
|
kind: BackendResourceKind::ProfileSourceArchive,
|
||||||
|
resource_id: stored.archive.reference.id,
|
||||||
|
digest: stored.archive.reference.digest,
|
||||||
|
content_type: PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
bytes: stored.archive.content,
|
||||||
|
audit_correlation_id: request.audit_correlation_id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl BackendResourceClient for BackendResourceBroker {
|
||||||
|
async fn fetch_resource(
|
||||||
|
&self,
|
||||||
|
request: BackendResourceFetchRequest,
|
||||||
|
) -> Result<BackendResourceFetchResponse, BackendResourceError> {
|
||||||
|
self.fetch_profile_source_archive(request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_handle_shape(handle: &BackendResourceHandle) -> Result<(), BackendResourceError> {
|
||||||
|
if handle.kind != BackendResourceKind::ProfileSourceArchive {
|
||||||
|
return Err(BackendResourceError::UnsupportedKind);
|
||||||
|
}
|
||||||
|
if handle.operation != BackendResourceOperation::FetchArchive {
|
||||||
|
return Err(BackendResourceError::Unauthorized {
|
||||||
|
message: "resource handle operation is not fetch_archive".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if handle.content_type != PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE {
|
||||||
|
return Err(BackendResourceError::ContentTypeMismatch {
|
||||||
|
expected: PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
actual: handle.content_type.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use worker_runtime::identity::{RuntimeId, WorkerId};
|
||||||
|
use worker_runtime::profile_archive::{
|
||||||
|
ProfileSourceArchive, ProfileSourceArchiveRef, ProfileSourceGraphSummary, sha256_hex,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn archive() -> ProfileSourceArchive {
|
||||||
|
let content = b"archive-content".to_vec();
|
||||||
|
let mut entrypoints = BTreeMap::new();
|
||||||
|
entrypoints.insert("default".to_string(), "profiles/default.dcdl".to_string());
|
||||||
|
ProfileSourceArchive {
|
||||||
|
reference: ProfileSourceArchiveRef {
|
||||||
|
id: "profile-source-archive:test".to_string(),
|
||||||
|
digest: sha256_hex(&content),
|
||||||
|
size_bytes: content.len() as u64,
|
||||||
|
source_graph: ProfileSourceGraphSummary {
|
||||||
|
entrypoints,
|
||||||
|
source_count: 1,
|
||||||
|
import_count: 0,
|
||||||
|
total_source_bytes: content.len() as u64,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
content,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn archive_with_len(len: usize) -> ProfileSourceArchive {
|
||||||
|
let content = vec![b'x'; len];
|
||||||
|
let mut entrypoints = BTreeMap::new();
|
||||||
|
entrypoints.insert("default".to_string(), "profiles/default.dcdl".to_string());
|
||||||
|
ProfileSourceArchive {
|
||||||
|
reference: ProfileSourceArchiveRef {
|
||||||
|
id: format!("profile-source-archive:test-{len}"),
|
||||||
|
digest: sha256_hex(&content),
|
||||||
|
size_bytes: content.len() as u64,
|
||||||
|
source_graph: ProfileSourceGraphSummary {
|
||||||
|
entrypoints,
|
||||||
|
source_count: 1,
|
||||||
|
import_count: 0,
|
||||||
|
total_source_bytes: content.len() as u64,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
content,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request(
|
||||||
|
handle: BackendResourceHandle,
|
||||||
|
runtime_id: &RuntimeId,
|
||||||
|
worker_id: Option<&WorkerId>,
|
||||||
|
) -> BackendResourceFetchRequest {
|
||||||
|
BackendResourceFetchRequest {
|
||||||
|
audit_correlation_id: handle.audit_correlation_id.clone(),
|
||||||
|
handle,
|
||||||
|
runtime_id: runtime_id.as_str().to_string(),
|
||||||
|
worker_id: worker_id.map(|id| id.as_str().to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_issues_and_verifies_profile_source_archive_handles() {
|
||||||
|
let broker = BackendResourceBroker::default();
|
||||||
|
let runtime_id = RuntimeId::new("runtime-test").unwrap();
|
||||||
|
let handle = broker.issue_profile_source_archive_handle(
|
||||||
|
"workspace-test",
|
||||||
|
Some(&runtime_id),
|
||||||
|
None,
|
||||||
|
archive(),
|
||||||
|
);
|
||||||
|
let response = broker
|
||||||
|
.fetch_profile_source_archive(BackendResourceFetchRequest {
|
||||||
|
handle: handle.clone(),
|
||||||
|
runtime_id: runtime_id.as_str().to_string(),
|
||||||
|
worker_id: None,
|
||||||
|
audit_correlation_id: handle.audit_correlation_id.clone(),
|
||||||
|
})
|
||||||
|
.expect("fetch succeeds");
|
||||||
|
assert_eq!(response.digest, handle.digest);
|
||||||
|
assert_eq!(response.content_type, PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_rejects_runtime_mismatch() {
|
||||||
|
let broker = BackendResourceBroker::default();
|
||||||
|
let runtime_a = RuntimeId::new("runtime-a").unwrap();
|
||||||
|
let handle = broker.issue_profile_source_archive_handle(
|
||||||
|
"workspace-test",
|
||||||
|
Some(&runtime_a),
|
||||||
|
None,
|
||||||
|
archive(),
|
||||||
|
);
|
||||||
|
let err = broker
|
||||||
|
.fetch_profile_source_archive(request(
|
||||||
|
handle,
|
||||||
|
&RuntimeId::new("runtime-b").unwrap(),
|
||||||
|
None,
|
||||||
|
))
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(err, BackendResourceError::Unauthorized { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_rejects_worker_mismatch() {
|
||||||
|
let broker = BackendResourceBroker::default();
|
||||||
|
let runtime_id = RuntimeId::new("runtime-test").unwrap();
|
||||||
|
let worker_a = WorkerId::new("worker-a").unwrap();
|
||||||
|
let worker_b = WorkerId::new("worker-b").unwrap();
|
||||||
|
let handle = broker.issue_profile_source_archive_handle(
|
||||||
|
"workspace-test",
|
||||||
|
Some(&runtime_id),
|
||||||
|
Some(&worker_a),
|
||||||
|
archive(),
|
||||||
|
);
|
||||||
|
let err = broker
|
||||||
|
.fetch_profile_source_archive(request(handle, &runtime_id, Some(&worker_b)))
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(err, BackendResourceError::Unauthorized { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_rejects_expiry_extension_from_request_handle() {
|
||||||
|
let broker = BackendResourceBroker::default();
|
||||||
|
let runtime_id = RuntimeId::new("runtime-test").unwrap();
|
||||||
|
let handle = broker.issue_profile_source_archive_handle(
|
||||||
|
"workspace-test",
|
||||||
|
Some(&runtime_id),
|
||||||
|
None,
|
||||||
|
archive(),
|
||||||
|
);
|
||||||
|
broker
|
||||||
|
.resources
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.get_mut(&handle.nonce)
|
||||||
|
.unwrap()
|
||||||
|
.handle
|
||||||
|
.expires_at_unix_seconds = 1;
|
||||||
|
let mut extended = handle;
|
||||||
|
extended.expires_at_unix_seconds = 4_102_444_800;
|
||||||
|
let err = broker
|
||||||
|
.fetch_profile_source_archive(request(extended, &runtime_id, None))
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(err, BackendResourceError::Expired));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_rejects_policy_tampered_request_handle() {
|
||||||
|
let broker = BackendResourceBroker::default();
|
||||||
|
let runtime_id = RuntimeId::new("runtime-test").unwrap();
|
||||||
|
let mut handle = broker.issue_profile_source_archive_handle(
|
||||||
|
"workspace-test",
|
||||||
|
Some(&runtime_id),
|
||||||
|
None,
|
||||||
|
archive(),
|
||||||
|
);
|
||||||
|
handle.scope_id = Some("tampered-scope".to_string());
|
||||||
|
let err = broker
|
||||||
|
.fetch_profile_source_archive(request(handle, &runtime_id, None))
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(err, BackendResourceError::Unauthorized { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_uses_stored_max_bytes_when_request_handle_is_tampered() {
|
||||||
|
let broker = BackendResourceBroker::default();
|
||||||
|
let runtime_id = RuntimeId::new("runtime-test").unwrap();
|
||||||
|
let archive = archive_with_len((DEFAULT_PROFILE_SOURCE_ARCHIVE_MAX_BYTES + 1) as usize);
|
||||||
|
let mut handle = broker.issue_profile_source_archive_handle(
|
||||||
|
"workspace-test",
|
||||||
|
Some(&runtime_id),
|
||||||
|
None,
|
||||||
|
archive,
|
||||||
|
);
|
||||||
|
handle.max_bytes = DEFAULT_PROFILE_SOURCE_ARCHIVE_MAX_BYTES + 1024;
|
||||||
|
let err = broker
|
||||||
|
.fetch_profile_source_archive(request(handle, &runtime_id, None))
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(err, BackendResourceError::Oversized { .. }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,13 +6,14 @@ use axum::extract::{Path as AxumPath, Query, State};
|
||||||
use axum::http::header::{CONTENT_TYPE, LOCATION};
|
use axum::http::header::{CONTENT_TYPE, LOCATION};
|
||||||
use axum::http::{StatusCode, Uri};
|
use axum::http::{StatusCode, Uri};
|
||||||
use axum::response::{IntoResponse, Response};
|
use axum::response::{IntoResponse, Response};
|
||||||
use axum::routing::{delete, get, post};
|
use axum::routing::{delete, get, post, put};
|
||||||
use axum::{Json, Router};
|
use axum::{Json, Router};
|
||||||
use chrono::{SecondsFormat, Utc};
|
use chrono::{SecondsFormat, Utc};
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
use worker_runtime::worker_backend::WorkerRuntimeExecutionBackend;
|
use worker_runtime::resource::{BackendResourceError, BackendResourceFetchRequest};
|
||||||
|
use worker_runtime::worker_backend::{ProfileRuntimeWorkerFactory, WorkerRuntimeExecutionBackend};
|
||||||
use worker_runtime::working_directory::{
|
use worker_runtime::working_directory::{
|
||||||
LocalGitWorktreeMaterializer, WorkingDirectoryDiagnostic, WorkingDirectoryMaterializer,
|
LocalGitWorktreeMaterializer, WorkingDirectoryDiagnostic, WorkingDirectoryMaterializer,
|
||||||
};
|
};
|
||||||
|
|
@ -35,6 +36,11 @@ use crate::observation::{
|
||||||
BackendObservationProxy, ClientWorkerEventWsFrame, ClientWorkerEventsWsQuery,
|
BackendObservationProxy, ClientWorkerEventWsFrame, ClientWorkerEventsWsQuery,
|
||||||
ObservationProxyError, RuntimeObservationClient, RuntimeObservationSourceConfig,
|
ObservationProxyError, RuntimeObservationClient, RuntimeObservationSourceConfig,
|
||||||
};
|
};
|
||||||
|
use crate::profile_settings::{
|
||||||
|
CreateWorkspaceProfileSourceRequest, DeleteWorkspaceProfileSourceRequest,
|
||||||
|
UpdateWorkspaceMetadataRequest, UpdateWorkspaceProfileRegistryRequest,
|
||||||
|
UpdateWorkspaceProfileSourceRequest,
|
||||||
|
};
|
||||||
use crate::records::{
|
use crate::records::{
|
||||||
LocalProjectRecordReader, ObjectiveDetail, ProjectRecordList, TicketDetail, TicketSummary,
|
LocalProjectRecordReader, ObjectiveDetail, ProjectRecordList, TicketDetail, TicketSummary,
|
||||||
};
|
};
|
||||||
|
|
@ -42,6 +48,7 @@ use crate::repositories::{
|
||||||
ConfiguredRepository, RepositoryListProjection, RepositoryLogRead, RepositoryLookupError,
|
ConfiguredRepository, RepositoryListProjection, RepositoryLogRead, RepositoryLookupError,
|
||||||
RepositoryRegistryReader, RepositorySummary,
|
RepositoryRegistryReader, RepositorySummary,
|
||||||
};
|
};
|
||||||
|
use crate::resource_broker::BackendResourceBroker;
|
||||||
use crate::store::{ControlPlaneStore, WorkspaceRecord};
|
use crate::store::{ControlPlaneStore, WorkspaceRecord};
|
||||||
use crate::{Error, Result};
|
use crate::{Error, Result};
|
||||||
use worker_runtime::catalog::{
|
use worker_runtime::catalog::{
|
||||||
|
|
@ -154,6 +161,7 @@ pub struct WorkspaceApi {
|
||||||
runtime: Arc<RuntimeRegistry>,
|
runtime: Arc<RuntimeRegistry>,
|
||||||
companion: Arc<CompanionConsole>,
|
companion: Arc<CompanionConsole>,
|
||||||
observation_proxy: BackendObservationProxy,
|
observation_proxy: BackendObservationProxy,
|
||||||
|
resource_broker: BackendResourceBroker,
|
||||||
working_directory_materializer: Arc<LocalGitWorktreeMaterializer>,
|
working_directory_materializer: Arc<LocalGitWorktreeMaterializer>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -162,21 +170,46 @@ impl WorkspaceApi {
|
||||||
let materializer = Arc::new(LocalGitWorktreeMaterializer::new(
|
let materializer = Arc::new(LocalGitWorktreeMaterializer::new(
|
||||||
config.embedded_runtime_store_root.clone(),
|
config.embedded_runtime_store_root.clone(),
|
||||||
));
|
));
|
||||||
let execution_backend =
|
let resource_broker = BackendResourceBroker::default();
|
||||||
WorkerRuntimeExecutionBackend::from_workspace(config.workspace_root.clone())
|
let execution_backend = WorkerRuntimeExecutionBackend::new(
|
||||||
.map_err(|err| {
|
ProfileRuntimeWorkerFactory::new(config.workspace_root.clone())
|
||||||
crate::Error::Store(format!(
|
.with_resource_client(Arc::new(resource_broker.clone())),
|
||||||
"failed to initialize embedded Worker backend: {err}"
|
)
|
||||||
))
|
.map_err(|err| {
|
||||||
})?
|
crate::Error::Store(format!(
|
||||||
.with_working_directory_materializer((*materializer).clone());
|
"failed to initialize embedded Worker backend: {err}"
|
||||||
Self::new_with_execution_backend(config, store, Arc::new(execution_backend)).await
|
))
|
||||||
|
})?
|
||||||
|
.with_working_directory_materializer((*materializer).clone());
|
||||||
|
Self::new_with_execution_backend_and_broker(
|
||||||
|
config,
|
||||||
|
store,
|
||||||
|
Arc::new(execution_backend),
|
||||||
|
resource_broker,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
async fn new_with_execution_backend(
|
async fn new_with_execution_backend(
|
||||||
config: ServerConfig,
|
config: ServerConfig,
|
||||||
store: Arc<dyn ControlPlaneStore>,
|
store: Arc<dyn ControlPlaneStore>,
|
||||||
execution_backend: Arc<dyn worker_runtime::execution::WorkerExecutionBackend>,
|
execution_backend: Arc<dyn worker_runtime::execution::WorkerExecutionBackend>,
|
||||||
|
) -> Result<Self> {
|
||||||
|
Self::new_with_execution_backend_and_broker(
|
||||||
|
config,
|
||||||
|
store,
|
||||||
|
execution_backend,
|
||||||
|
BackendResourceBroker::default(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn new_with_execution_backend_and_broker(
|
||||||
|
config: ServerConfig,
|
||||||
|
store: Arc<dyn ControlPlaneStore>,
|
||||||
|
execution_backend: Arc<dyn worker_runtime::execution::WorkerExecutionBackend>,
|
||||||
|
resource_broker: BackendResourceBroker,
|
||||||
) -> Result<Self> {
|
) -> Result<Self> {
|
||||||
store
|
store
|
||||||
.upsert_workspace(&WorkspaceRecord {
|
.upsert_workspace(&WorkspaceRecord {
|
||||||
|
|
@ -193,13 +226,17 @@ impl WorkspaceApi {
|
||||||
config.embedded_runtime_store_root.clone(),
|
config.embedded_runtime_store_root.clone(),
|
||||||
execution_backend,
|
execution_backend,
|
||||||
)
|
)
|
||||||
|
.map(|runtime| runtime.with_resource_broker(resource_broker.clone()))
|
||||||
.map_err(|err| {
|
.map_err(|err| {
|
||||||
crate::Error::Store(format!("invalid embedded Worker backend: {err}"))
|
crate::Error::Store(format!("invalid embedded Worker backend: {err}"))
|
||||||
})?,
|
})?,
|
||||||
);
|
);
|
||||||
for remote_config in config.remote_runtime_sources.iter().cloned() {
|
for remote_config in config.remote_runtime_sources.iter().cloned() {
|
||||||
runtime
|
runtime.register(
|
||||||
.register(RemoteWorkerRuntime::new(remote_config).map_err(|err| err.into_error())?);
|
RemoteWorkerRuntime::new(remote_config)
|
||||||
|
.map(|host| host.with_resource_broker(resource_broker.clone()))
|
||||||
|
.map_err(|err| err.into_error())?,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let runtime = Arc::new(runtime);
|
let runtime = Arc::new(runtime);
|
||||||
let companion = Arc::new(CompanionConsole::new(runtime.clone()));
|
let companion = Arc::new(CompanionConsole::new(runtime.clone()));
|
||||||
|
|
@ -214,6 +251,7 @@ impl WorkspaceApi {
|
||||||
runtime,
|
runtime,
|
||||||
companion,
|
companion,
|
||||||
observation_proxy,
|
observation_proxy,
|
||||||
|
resource_broker,
|
||||||
working_directory_materializer,
|
working_directory_materializer,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -231,6 +269,24 @@ pub fn build_router(api: WorkspaceApi) -> Router {
|
||||||
Router::new()
|
Router::new()
|
||||||
.route("/api/workspace", get(get_workspace))
|
.route("/api/workspace", get(get_workspace))
|
||||||
.route("/api/w/{workspace_id}/workspace", get(scoped_get_workspace))
|
.route("/api/w/{workspace_id}/workspace", get(scoped_get_workspace))
|
||||||
|
.route(
|
||||||
|
"/api/w/{workspace_id}/settings/workspace",
|
||||||
|
get(scoped_get_workspace_settings).put(scoped_update_workspace_settings),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/w/{workspace_id}/settings/profiles",
|
||||||
|
get(scoped_get_profile_settings).post(scoped_create_profile_source),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/w/{workspace_id}/settings/profiles/registry",
|
||||||
|
put(scoped_update_profile_registry),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/w/{workspace_id}/settings/profiles/{profile_source_id}",
|
||||||
|
get(scoped_get_profile_source)
|
||||||
|
.put(scoped_update_profile_source)
|
||||||
|
.delete(scoped_delete_profile_source),
|
||||||
|
)
|
||||||
.route("/api/tickets", get(list_tickets))
|
.route("/api/tickets", get(list_tickets))
|
||||||
.route("/api/w/{workspace_id}/tickets", get(scoped_list_tickets))
|
.route("/api/w/{workspace_id}/tickets", get(scoped_list_tickets))
|
||||||
.route("/api/tickets/{id}", get(get_ticket))
|
.route("/api/tickets/{id}", get(get_ticket))
|
||||||
|
|
@ -328,6 +384,10 @@ pub fn build_router(api: WorkspaceApi) -> Router {
|
||||||
"/api/w/{workspace_id}/settings/runtime-connections/remotes/{runtime_id}/test",
|
"/api/w/{workspace_id}/settings/runtime-connections/remotes/{runtime_id}/test",
|
||||||
post(scoped_test_remote_runtime_connection),
|
post(scoped_test_remote_runtime_connection),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/internal/runtime/resources/fetch",
|
||||||
|
post(post_internal_runtime_resource_fetch),
|
||||||
|
)
|
||||||
.route("/api/companion/status", get(get_companion_status))
|
.route("/api/companion/status", get(get_companion_status))
|
||||||
.route(
|
.route(
|
||||||
"/api/w/{workspace_id}/companion/status",
|
"/api/w/{workspace_id}/companion/status",
|
||||||
|
|
@ -777,6 +837,116 @@ async fn scoped_get_workspace(
|
||||||
get_workspace(State(api)).await
|
get_workspace(State(api)).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn scoped_get_workspace_settings(
|
||||||
|
State(api): State<WorkspaceApi>,
|
||||||
|
AxumPath(path): AxumPath<ScopedWorkspacePath>,
|
||||||
|
) -> ApiResult<Json<crate::profile_settings::WorkspaceMetadataSettingsResponse>> {
|
||||||
|
validate_workspace_scope(&api, &path.workspace_id)?;
|
||||||
|
Ok(Json(crate::profile_settings::workspace_metadata_settings(
|
||||||
|
&api.config.workspace_root,
|
||||||
|
&api.config.workspace_id,
|
||||||
|
&api.config.workspace_created_at,
|
||||||
|
&api.config.workspace_display_name,
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn scoped_update_workspace_settings(
|
||||||
|
State(api): State<WorkspaceApi>,
|
||||||
|
AxumPath(path): AxumPath<ScopedWorkspacePath>,
|
||||||
|
Json(request): Json<UpdateWorkspaceMetadataRequest>,
|
||||||
|
) -> ApiResult<Json<crate::profile_settings::WorkspaceMetadataMutationResponse>> {
|
||||||
|
validate_workspace_scope(&api, &path.workspace_id)?;
|
||||||
|
let workspace =
|
||||||
|
crate::profile_settings::update_workspace_metadata(&api.config.workspace_root, request)?;
|
||||||
|
Ok(Json(
|
||||||
|
crate::profile_settings::WorkspaceMetadataMutationResponse {
|
||||||
|
workspace,
|
||||||
|
diagnostics: vec![RuntimeDiagnostic {
|
||||||
|
code: "workspace_metadata_updated".to_string(),
|
||||||
|
severity: DiagnosticSeverity::Info,
|
||||||
|
message: "Workspace display metadata was updated.".to_string(),
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn scoped_get_profile_settings(
|
||||||
|
State(api): State<WorkspaceApi>,
|
||||||
|
AxumPath(path): AxumPath<ScopedWorkspacePath>,
|
||||||
|
) -> ApiResult<Json<crate::profile_settings::ProfileSettingsResponse>> {
|
||||||
|
validate_workspace_scope(&api, &path.workspace_id)?;
|
||||||
|
Ok(Json(crate::profile_settings::load_profile_settings(
|
||||||
|
&api.config.workspace_id,
|
||||||
|
&api.config.workspace_root,
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn scoped_create_profile_source(
|
||||||
|
State(api): State<WorkspaceApi>,
|
||||||
|
AxumPath(path): AxumPath<ScopedWorkspacePath>,
|
||||||
|
Json(request): Json<CreateWorkspaceProfileSourceRequest>,
|
||||||
|
) -> ApiResult<Json<crate::profile_settings::ProfileSettingsMutationResponse>> {
|
||||||
|
validate_workspace_scope(&api, &path.workspace_id)?;
|
||||||
|
Ok(Json(crate::profile_settings::create_profile_source(
|
||||||
|
&api.config.workspace_id,
|
||||||
|
&api.config.workspace_root,
|
||||||
|
request,
|
||||||
|
)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn scoped_update_profile_registry(
|
||||||
|
State(api): State<WorkspaceApi>,
|
||||||
|
AxumPath(path): AxumPath<ScopedWorkspacePath>,
|
||||||
|
Json(request): Json<UpdateWorkspaceProfileRegistryRequest>,
|
||||||
|
) -> ApiResult<Json<crate::profile_settings::ProfileSettingsMutationResponse>> {
|
||||||
|
validate_workspace_scope(&api, &path.workspace_id)?;
|
||||||
|
Ok(Json(crate::profile_settings::update_profile_registry(
|
||||||
|
&api.config.workspace_id,
|
||||||
|
&api.config.workspace_root,
|
||||||
|
request,
|
||||||
|
)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn scoped_get_profile_source(
|
||||||
|
State(api): State<WorkspaceApi>,
|
||||||
|
AxumPath((workspace_id, profile_source_id)): AxumPath<(String, String)>,
|
||||||
|
) -> ApiResult<Json<crate::profile_settings::WorkspaceProfileSourceDetailResponse>> {
|
||||||
|
validate_workspace_scope(&api, &workspace_id)?;
|
||||||
|
Ok(Json(crate::profile_settings::read_profile_source(
|
||||||
|
&api.config.workspace_id,
|
||||||
|
&api.config.workspace_root,
|
||||||
|
&profile_source_id,
|
||||||
|
)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn scoped_update_profile_source(
|
||||||
|
State(api): State<WorkspaceApi>,
|
||||||
|
AxumPath((workspace_id, profile_source_id)): AxumPath<(String, String)>,
|
||||||
|
Json(request): Json<UpdateWorkspaceProfileSourceRequest>,
|
||||||
|
) -> ApiResult<Json<crate::profile_settings::ProfileSettingsMutationResponse>> {
|
||||||
|
validate_workspace_scope(&api, &workspace_id)?;
|
||||||
|
Ok(Json(crate::profile_settings::update_profile_source(
|
||||||
|
&api.config.workspace_id,
|
||||||
|
&api.config.workspace_root,
|
||||||
|
&profile_source_id,
|
||||||
|
request,
|
||||||
|
)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn scoped_delete_profile_source(
|
||||||
|
State(api): State<WorkspaceApi>,
|
||||||
|
AxumPath((workspace_id, profile_source_id)): AxumPath<(String, String)>,
|
||||||
|
Json(request): Json<DeleteWorkspaceProfileSourceRequest>,
|
||||||
|
) -> ApiResult<Json<crate::profile_settings::ProfileSettingsMutationResponse>> {
|
||||||
|
validate_workspace_scope(&api, &workspace_id)?;
|
||||||
|
Ok(Json(crate::profile_settings::delete_profile_source(
|
||||||
|
&api.config.workspace_id,
|
||||||
|
&api.config.workspace_root,
|
||||||
|
&profile_source_id,
|
||||||
|
request,
|
||||||
|
)?))
|
||||||
|
}
|
||||||
|
|
||||||
async fn scoped_list_tickets(
|
async fn scoped_list_tickets(
|
||||||
State(api): State<WorkspaceApi>,
|
State(api): State<WorkspaceApi>,
|
||||||
AxumPath(path): AxumPath<ScopedWorkspacePath>,
|
AxumPath(path): AxumPath<ScopedWorkspacePath>,
|
||||||
|
|
@ -1445,7 +1615,9 @@ async fn add_remote_runtime_connection(
|
||||||
vec![diagnostic],
|
vec![diagnostic],
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let active_runtime = RemoteWorkerRuntime::new(active_config).map_err(|err| err.into_error())?;
|
let active_runtime = RemoteWorkerRuntime::new(active_config)
|
||||||
|
.map(|host| host.with_resource_broker(api.resource_broker.clone()))
|
||||||
|
.map_err(|err| err.into_error())?;
|
||||||
local_config.runtimes.remote.push(remote_config);
|
local_config.runtimes.remote.push(remote_config);
|
||||||
write_workspace_backend_config_for_settings(&api, &local_config)?;
|
write_workspace_backend_config_for_settings(&api, &local_config)?;
|
||||||
api.runtime.register_or_replace(active_runtime);
|
api.runtime.register_or_replace(active_runtime);
|
||||||
|
|
@ -1600,12 +1772,24 @@ async fn create_workspace_worker(
|
||||||
State(api): State<WorkspaceApi>,
|
State(api): State<WorkspaceApi>,
|
||||||
Json(request): Json<BrowserCreateWorkerRequest>,
|
Json(request): Json<BrowserCreateWorkerRequest>,
|
||||||
) -> ApiResult<Json<BrowserCreateWorkerResponse>> {
|
) -> ApiResult<Json<BrowserCreateWorkerResponse>> {
|
||||||
let profile_selector = profile_selector_for_candidate(&request.profile).ok_or_else(|| {
|
let profile_selector =
|
||||||
settings_bad_request(
|
profile_selector_for_candidate_with_root(&api.config.workspace_root, &request.profile)
|
||||||
"unsupported_worker_profile",
|
.ok_or_else(|| {
|
||||||
"profile must be selected from Backend-published worker profile candidates",
|
settings_bad_request(
|
||||||
)
|
"unsupported_worker_profile",
|
||||||
})?;
|
"profile must be selected from Backend-published worker profile candidates",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let resolved_config_bundle = if request.profile.starts_with("project:") {
|
||||||
|
crate::profile_settings::build_workspace_profile_config_bundle(
|
||||||
|
&api.config.workspace_root,
|
||||||
|
&api.config.workspace_id,
|
||||||
|
&api.config.workspace_created_at,
|
||||||
|
&request.profile,
|
||||||
|
)?
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
let display_name = sanitize_worker_display_name(&request.display_name).ok_or_else(|| {
|
let display_name = sanitize_worker_display_name(&request.display_name).ok_or_else(|| {
|
||||||
settings_bad_request(
|
settings_bad_request(
|
||||||
"invalid_worker_display_name",
|
"invalid_worker_display_name",
|
||||||
|
|
@ -1663,6 +1847,7 @@ async fn create_workspace_worker(
|
||||||
working_directory_request: None,
|
working_directory_request: None,
|
||||||
resolved_working_directory_request: None,
|
resolved_working_directory_request: None,
|
||||||
resolved_working_directory,
|
resolved_working_directory,
|
||||||
|
resolved_config_bundle,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.map_err(|err| err.into_error())?;
|
.map_err(|err| err.into_error())?;
|
||||||
|
|
@ -1696,6 +1881,33 @@ async fn create_workspace_worker(
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn post_internal_runtime_resource_fetch(
|
||||||
|
State(api): State<WorkspaceApi>,
|
||||||
|
Json(request): Json<BackendResourceFetchRequest>,
|
||||||
|
) -> std::result::Result<
|
||||||
|
Json<worker_runtime::resource::BackendResourceFetchResponse>,
|
||||||
|
(StatusCode, Json<BackendResourceError>),
|
||||||
|
> {
|
||||||
|
api.resource_broker
|
||||||
|
.fetch_profile_source_archive(request)
|
||||||
|
.map(Json)
|
||||||
|
.map_err(|error| (backend_resource_error_status(&error), Json(error)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn backend_resource_error_status(error: &BackendResourceError) -> StatusCode {
|
||||||
|
match error {
|
||||||
|
BackendResourceError::Expired => StatusCode::GONE,
|
||||||
|
BackendResourceError::Unauthorized { .. } => StatusCode::UNAUTHORIZED,
|
||||||
|
BackendResourceError::MissingResource => StatusCode::NOT_FOUND,
|
||||||
|
BackendResourceError::UnsupportedKind
|
||||||
|
| BackendResourceError::DigestMismatch { .. }
|
||||||
|
| BackendResourceError::Oversized { .. }
|
||||||
|
| BackendResourceError::ContentTypeMismatch { .. }
|
||||||
|
| BackendResourceError::InvalidResponse { .. } => StatusCode::BAD_REQUEST,
|
||||||
|
BackendResourceError::Transport { .. } => StatusCode::BAD_GATEWAY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn get_companion_status(
|
async fn get_companion_status(
|
||||||
State(api): State<WorkspaceApi>,
|
State(api): State<WorkspaceApi>,
|
||||||
) -> ApiResult<Json<CompanionStatusResponse>> {
|
) -> ApiResult<Json<CompanionStatusResponse>> {
|
||||||
|
|
@ -2687,7 +2899,7 @@ fn worker_launch_options_response(api: &WorkspaceApi) -> WorkerLaunchOptionsResp
|
||||||
WorkerLaunchOptionsResponse {
|
WorkerLaunchOptionsResponse {
|
||||||
workspace_id: api.config.workspace_id.clone(),
|
workspace_id: api.config.workspace_id.clone(),
|
||||||
runtimes,
|
runtimes,
|
||||||
profiles: worker_profile_candidates(),
|
profiles: worker_profile_candidates_for_root(&api.config.workspace_root),
|
||||||
repositories: working_directory_repository_options(api),
|
repositories: working_directory_repository_options(api),
|
||||||
working_directories: working_directory_summaries(api).unwrap_or_default(),
|
working_directories: working_directory_summaries(api).unwrap_or_default(),
|
||||||
diagnostics: Vec::new(),
|
diagnostics: Vec::new(),
|
||||||
|
|
@ -2757,8 +2969,16 @@ fn working_directory_request_for_browser(
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
fn worker_profile_candidates() -> Vec<WorkerLaunchProfileCandidate> {
|
fn worker_profile_candidates() -> Vec<WorkerLaunchProfileCandidate> {
|
||||||
vec![
|
worker_profile_candidates_for_root(Path::new("."))
|
||||||
|
.into_iter()
|
||||||
|
.filter(|candidate| candidate.id == "builtin:coder" || candidate.id == "runtime_default")
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn worker_profile_candidates_for_root(workspace_root: &Path) -> Vec<WorkerLaunchProfileCandidate> {
|
||||||
|
let mut candidates = vec![
|
||||||
WorkerLaunchProfileCandidate {
|
WorkerLaunchProfileCandidate {
|
||||||
id: "builtin:coder".to_string(),
|
id: "builtin:coder".to_string(),
|
||||||
label: "Coding Worker".to_string(),
|
label: "Coding Worker".to_string(),
|
||||||
|
|
@ -2769,14 +2989,37 @@ fn worker_profile_candidates() -> Vec<WorkerLaunchProfileCandidate> {
|
||||||
label: "Runtime default".to_string(),
|
label: "Runtime default".to_string(),
|
||||||
description: "Use the selected Runtime's default profile.".to_string(),
|
description: "Use the selected Runtime's default profile.".to_string(),
|
||||||
},
|
},
|
||||||
]
|
];
|
||||||
|
candidates.extend(
|
||||||
|
crate::profile_settings::project_profile_candidates(workspace_root)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|profile| profile.diagnostics.is_empty())
|
||||||
|
.map(|profile| WorkerLaunchProfileCandidate {
|
||||||
|
id: profile.profile_id,
|
||||||
|
label: profile.label,
|
||||||
|
description: profile
|
||||||
|
.description
|
||||||
|
.unwrap_or_else(|| "Workspace Decodal profile source.".to_string()),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
candidates
|
||||||
}
|
}
|
||||||
|
|
||||||
fn profile_selector_for_candidate(profile: &str) -> Option<ProfileSelector> {
|
fn profile_selector_for_candidate(profile: &str) -> Option<ProfileSelector> {
|
||||||
match profile {
|
crate::profile_settings::selector_for_builtin_candidate(profile)
|
||||||
"builtin:coder" => Some(ProfileSelector::Builtin("builtin:coder".to_string())),
|
.filter(|_| matches!(profile, "builtin:coder" | "runtime_default"))
|
||||||
"runtime_default" => Some(ProfileSelector::RuntimeDefault),
|
}
|
||||||
_ => None,
|
|
||||||
|
fn profile_selector_for_candidate_with_root(
|
||||||
|
workspace_root: &Path,
|
||||||
|
profile: &str,
|
||||||
|
) -> Option<ProfileSelector> {
|
||||||
|
if profile_selector_for_candidate(profile).is_some() {
|
||||||
|
profile_selector_for_candidate(profile)
|
||||||
|
} else if crate::profile_settings::is_profile_candidate(workspace_root, profile) {
|
||||||
|
crate::profile_settings::selector_for_builtin_candidate(profile)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -3118,10 +3361,15 @@ struct ApiError {
|
||||||
|
|
||||||
impl From<Error> for ApiError {
|
impl From<Error> for ApiError {
|
||||||
fn from(error: Error) -> Self {
|
fn from(error: Error) -> Self {
|
||||||
Self {
|
let diagnostics = match &error {
|
||||||
error,
|
Error::RuntimeOperationFailed { code, message, .. } => vec![RuntimeDiagnostic {
|
||||||
diagnostics: Vec::new(),
|
code: code.clone(),
|
||||||
}
|
severity: DiagnosticSeverity::Error,
|
||||||
|
message: sanitize_backend_error(message),
|
||||||
|
}],
|
||||||
|
_ => Vec::new(),
|
||||||
|
};
|
||||||
|
Self { error, diagnostics }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -3161,6 +3409,23 @@ impl IntoResponse for ApiError {
|
||||||
Error::RuntimeOperationFailed { code, .. } if code == "remote_runtime_unsupported" => {
|
Error::RuntimeOperationFailed { code, .. } if code == "remote_runtime_unsupported" => {
|
||||||
StatusCode::NOT_IMPLEMENTED
|
StatusCode::NOT_IMPLEMENTED
|
||||||
}
|
}
|
||||||
|
Error::RuntimeOperationFailed { code, .. }
|
||||||
|
if code == "profile_registry_revision_conflict"
|
||||||
|
|| code == "profile_source_revision_conflict"
|
||||||
|
|| code == "workspace_metadata_revision_conflict" =>
|
||||||
|
{
|
||||||
|
StatusCode::CONFLICT
|
||||||
|
}
|
||||||
|
Error::RuntimeOperationFailed { code, .. }
|
||||||
|
if code == "unknown_profile_source" || code == "unknown_profile_selector" =>
|
||||||
|
{
|
||||||
|
StatusCode::NOT_FOUND
|
||||||
|
}
|
||||||
|
Error::RuntimeOperationFailed { code, .. }
|
||||||
|
if code == "workspace_display_name_invalid" || code.starts_with("profile_") =>
|
||||||
|
{
|
||||||
|
StatusCode::BAD_REQUEST
|
||||||
|
}
|
||||||
Error::RuntimeOperationFailed { code, .. } if code.ends_with("_blocked") => {
|
Error::RuntimeOperationFailed { code, .. } if code.ends_with("_blocked") => {
|
||||||
StatusCode::CONFLICT
|
StatusCode::CONFLICT
|
||||||
}
|
}
|
||||||
|
|
@ -3178,12 +3443,18 @@ impl IntoResponse for ApiError {
|
||||||
Error::RuntimeOperationFailed { .. } => StatusCode::BAD_GATEWAY,
|
Error::RuntimeOperationFailed { .. } => StatusCode::BAD_GATEWAY,
|
||||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
};
|
};
|
||||||
|
let response_message = match &self.error {
|
||||||
|
Error::RuntimeOperationFailed { code, message, .. } => {
|
||||||
|
format!("{code}: {}", sanitize_backend_error(message))
|
||||||
|
}
|
||||||
|
_ => sanitize_backend_error(&self.error.to_string()),
|
||||||
|
};
|
||||||
(
|
(
|
||||||
status,
|
status,
|
||||||
[(CONTENT_TYPE, "application/json")],
|
[(CONTENT_TYPE, "application/json")],
|
||||||
Json(serde_json::json!({
|
Json(serde_json::json!({
|
||||||
"error": status.canonical_reason().unwrap_or("error"),
|
"error": status.canonical_reason().unwrap_or("error"),
|
||||||
"message": self.error.to_string(),
|
"message": response_message,
|
||||||
"diagnostics": self.diagnostics,
|
"diagnostics": self.diagnostics,
|
||||||
}))
|
}))
|
||||||
.to_string(),
|
.to_string(),
|
||||||
|
|
@ -3199,10 +3470,11 @@ mod tests {
|
||||||
use axum::http::Request;
|
use axum::http::Request;
|
||||||
use futures::{SinkExt, StreamExt};
|
use futures::{SinkExt, StreamExt};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use std::sync::Arc;
|
use std::{fs, sync::Arc};
|
||||||
use tokio_tungstenite::connect_async;
|
use tokio_tungstenite::connect_async;
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
use tokio_tungstenite::tungstenite::Message;
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
|
use worker_runtime::resource::BackendResourceClient;
|
||||||
|
|
||||||
use crate::hosts::{
|
use crate::hosts::{
|
||||||
TicketWorkerRole, WorkerInputKind, WorkerOperationState, WorkerSpawnAcceptanceRequirement,
|
TicketWorkerRole, WorkerInputKind, WorkerOperationState, WorkerSpawnAcceptanceRequirement,
|
||||||
|
|
@ -3255,6 +3527,210 @@ mod tests {
|
||||||
assert!(!sanitized.contains("/home/example"));
|
assert!(!sanitized.contains("/home/example"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn profile_settings_api_returns_typed_diagnostics_for_duplicate_selector() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let response = profile_settings_request(
|
||||||
|
dir.path(),
|
||||||
|
"POST",
|
||||||
|
"/settings/profiles",
|
||||||
|
json!({
|
||||||
|
"name": "coder",
|
||||||
|
"content": valid_profile_source("coder"),
|
||||||
|
"registry_revision": "missing"
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.0, StatusCode::BAD_REQUEST);
|
||||||
|
assert_diagnostic(&response.1, "profile_selector_duplicate");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn profile_settings_api_returns_typed_diagnostics_for_invalid_decodal() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let response = profile_settings_request(
|
||||||
|
dir.path(),
|
||||||
|
"POST",
|
||||||
|
"/settings/profiles",
|
||||||
|
json!({
|
||||||
|
"name": "bad",
|
||||||
|
"content": "not decodal",
|
||||||
|
"registry_revision": "missing"
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.0, StatusCode::BAD_REQUEST);
|
||||||
|
assert!(
|
||||||
|
diagnostic_codes(&response.1)
|
||||||
|
.iter()
|
||||||
|
.any(|code| code.starts_with("profile_source_"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn profile_settings_api_returns_typed_diagnostic_for_invalid_registry_schema() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
fs::create_dir_all(dir.path().join(".yoi")).unwrap();
|
||||||
|
fs::write(dir.path().join(".yoi/profiles.toml"), "[profile\n").unwrap();
|
||||||
|
let response = profile_settings_request(
|
||||||
|
dir.path(),
|
||||||
|
"POST",
|
||||||
|
"/settings/profiles",
|
||||||
|
json!({
|
||||||
|
"name": "schema",
|
||||||
|
"content": valid_profile_source("schema"),
|
||||||
|
"registry_revision": test_file_revision(&dir.path().join(".yoi/profiles.toml"))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.0, StatusCode::BAD_REQUEST);
|
||||||
|
assert_diagnostic(&response.1, "profile_registry_schema_invalid");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn profile_settings_api_returns_conflict_diagnostic_for_stale_revision() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let response = profile_settings_request(
|
||||||
|
dir.path(),
|
||||||
|
"POST",
|
||||||
|
"/settings/profiles",
|
||||||
|
json!({
|
||||||
|
"name": "alpha",
|
||||||
|
"content": valid_profile_source("alpha"),
|
||||||
|
"registry_revision": "stale"
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.0, StatusCode::CONFLICT);
|
||||||
|
assert_diagnostic(&response.1, "profile_registry_revision_conflict");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn profile_settings_api_returns_typed_diagnostic_for_too_large_source() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let response = profile_settings_request(
|
||||||
|
dir.path(),
|
||||||
|
"POST",
|
||||||
|
"/settings/profiles",
|
||||||
|
json!({
|
||||||
|
"name": "large",
|
||||||
|
"content": "x".repeat((256 * 1024) + 1),
|
||||||
|
"registry_revision": "missing"
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.0, StatusCode::BAD_REQUEST);
|
||||||
|
assert_diagnostic(&response.1, "profile_source_too_large");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn profile_settings_api_redacts_symlink_escape_response() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
fs::create_dir_all(dir.path().join(".yoi/profiles")).unwrap();
|
||||||
|
fs::write(dir.path().join(".yoi/profiles.toml"), "").unwrap();
|
||||||
|
let outside = dir.path().join("outside.dcdl");
|
||||||
|
fs::write(&outside, valid_profile_source("escape")).unwrap();
|
||||||
|
std::os::unix::fs::symlink(&outside, dir.path().join(".yoi/profiles/escape.dcdl")).unwrap();
|
||||||
|
let response = profile_settings_request(
|
||||||
|
dir.path(),
|
||||||
|
"PUT",
|
||||||
|
"/settings/profiles/registry",
|
||||||
|
json!({
|
||||||
|
"registry_revision": test_file_revision(&dir.path().join(".yoi/profiles.toml")),
|
||||||
|
"default_profile": null,
|
||||||
|
"profiles": [{ "name": "escape", "profile_source_id": "project:escape" }]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.0, StatusCode::BAD_REQUEST);
|
||||||
|
assert_diagnostic(&response.1, "profile_source_symlink_escape");
|
||||||
|
let rendered = response.1.to_string();
|
||||||
|
assert!(!rendered.contains(dir.path().to_string_lossy().as_ref()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn worker_launch_rejects_invalid_project_profile_candidate() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
fs::create_dir_all(dir.path().join(".yoi/profiles")).unwrap();
|
||||||
|
fs::write(
|
||||||
|
dir.path().join(".yoi/profiles.toml"),
|
||||||
|
"[profile.bad]\npath = \"profiles/bad.dcdl\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
fs::write(dir.path().join(".yoi/profiles/bad.dcdl"), "not decodal").unwrap();
|
||||||
|
assert!(
|
||||||
|
worker_profile_candidates_for_root(dir.path())
|
||||||
|
.iter()
|
||||||
|
.all(|candidate| candidate.id != "project:bad")
|
||||||
|
);
|
||||||
|
assert!(profile_selector_for_candidate_with_root(dir.path(), "project:bad").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_profile_source(slug: &str) -> String {
|
||||||
|
format!(
|
||||||
|
r#"{{
|
||||||
|
slug = "{slug}";
|
||||||
|
description = "Test";
|
||||||
|
scope = "workspace_read";
|
||||||
|
}}"#
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_file_revision(path: &Path) -> String {
|
||||||
|
let Ok(metadata) = fs::metadata(path) else {
|
||||||
|
return "missing".to_string();
|
||||||
|
};
|
||||||
|
let modified = metadata
|
||||||
|
.modified()
|
||||||
|
.ok()
|
||||||
|
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
|
||||||
|
.map(|duration| duration.as_nanos())
|
||||||
|
.unwrap_or_default();
|
||||||
|
format!("rev:{modified}:{}", metadata.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn profile_settings_request(
|
||||||
|
workspace_root: &Path,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
body: Value,
|
||||||
|
) -> (StatusCode, Value) {
|
||||||
|
let app = test_app(workspace_root.to_path_buf()).await;
|
||||||
|
let request = Request::builder()
|
||||||
|
.method(method)
|
||||||
|
.uri(format!("/api/w/{TEST_WORKSPACE_ID}{path}"))
|
||||||
|
.header(CONTENT_TYPE, "application/json")
|
||||||
|
.body(Body::from(body.to_string()))
|
||||||
|
.unwrap();
|
||||||
|
let response = app.oneshot(request).await.unwrap();
|
||||||
|
let status = response.status();
|
||||||
|
let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
|
||||||
|
let json = serde_json::from_slice::<Value>(&bytes).unwrap();
|
||||||
|
(status, json)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn diagnostic_codes(response: &Value) -> Vec<String> {
|
||||||
|
response["diagnostics"]
|
||||||
|
.as_array()
|
||||||
|
.expect("diagnostics array")
|
||||||
|
.iter()
|
||||||
|
.map(|diagnostic| diagnostic["code"].as_str().unwrap().to_string())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_diagnostic(response: &Value, code: &str) {
|
||||||
|
let codes = diagnostic_codes(response);
|
||||||
|
assert!(
|
||||||
|
!codes.is_empty(),
|
||||||
|
"diagnostics must not be empty: {response}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
codes.iter().any(|actual| actual == code),
|
||||||
|
"missing {code}: {codes:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct DeterministicExecutionBackend {
|
struct DeterministicExecutionBackend {
|
||||||
contexts: std::sync::Mutex<
|
contexts: std::sync::Mutex<
|
||||||
|
|
@ -3375,16 +3851,161 @@ mod tests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn test_app(workspace_root: impl Into<PathBuf>) -> Router {
|
async fn test_api(workspace_root: impl Into<PathBuf>) -> WorkspaceApi {
|
||||||
let store = SqliteWorkspaceStore::in_memory().unwrap();
|
let store = SqliteWorkspaceStore::in_memory().unwrap();
|
||||||
let api = WorkspaceApi::new_with_execution_backend(
|
WorkspaceApi::new_with_execution_backend(
|
||||||
test_server_config(workspace_root),
|
test_server_config(workspace_root),
|
||||||
Arc::new(store),
|
Arc::new(store),
|
||||||
Arc::new(DeterministicExecutionBackend::default()),
|
Arc::new(DeterministicExecutionBackend::default()),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap()
|
||||||
build_router(api)
|
}
|
||||||
|
|
||||||
|
async fn test_app(workspace_root: impl Into<PathBuf>) -> Router {
|
||||||
|
build_router(test_api(workspace_root).await)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_profile_archive() -> worker_runtime::profile_archive::ProfileSourceArchive {
|
||||||
|
use worker_runtime::profile_archive::{ProfileSourceArchive, ProfileSourceArchiveInput};
|
||||||
|
ProfileSourceArchive::build(ProfileSourceArchiveInput {
|
||||||
|
id: "profile-source-archive:server-test".to_string(),
|
||||||
|
entrypoints: std::collections::BTreeMap::from([(
|
||||||
|
"default".to_string(),
|
||||||
|
"profiles/default.dcdl".to_string(),
|
||||||
|
)]),
|
||||||
|
imports: std::collections::BTreeMap::new(),
|
||||||
|
sources: std::collections::BTreeMap::from([(
|
||||||
|
"profiles/default.dcdl".to_string(),
|
||||||
|
r#"{
|
||||||
|
slug = "default";
|
||||||
|
description = "Default";
|
||||||
|
scope = "workspace_read";
|
||||||
|
}"#
|
||||||
|
.to_string(),
|
||||||
|
)]),
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn missing_resource_handle() -> worker_runtime::resource::BackendResourceHandle {
|
||||||
|
worker_runtime::resource::BackendResourceHandle {
|
||||||
|
kind: worker_runtime::resource::BackendResourceKind::ProfileSourceArchive,
|
||||||
|
workspace_id: "workspace-test".to_string(),
|
||||||
|
scope_id: Some("workspace-profile-source".to_string()),
|
||||||
|
runtime_id: Some("runtime-test".to_string()),
|
||||||
|
worker_id: None,
|
||||||
|
resource_id: "profile-source-archive:missing".to_string(),
|
||||||
|
digest: "sha256:0000000000000000000000000000000000000000000000000000000000000000"
|
||||||
|
.to_string(),
|
||||||
|
operation: worker_runtime::resource::BackendResourceOperation::FetchArchive,
|
||||||
|
expires_at_unix_seconds: 4_102_444_800,
|
||||||
|
nonce: "missing-nonce".to_string(),
|
||||||
|
revision: "missing-revision".to_string(),
|
||||||
|
generation: None,
|
||||||
|
max_bytes: worker_runtime::resource::DEFAULT_PROFILE_SOURCE_ARCHIVE_MAX_BYTES,
|
||||||
|
content_type: worker_runtime::resource::PROFILE_SOURCE_ARCHIVE_CONTENT_TYPE.to_string(),
|
||||||
|
redaction: worker_runtime::resource::ResourceRedactionPolicy::RuntimeInternalOnly,
|
||||||
|
audit_correlation_id: "audit-missing".to_string(),
|
||||||
|
profile_source_graph: Some(
|
||||||
|
worker_runtime::profile_archive::ProfileSourceGraphSummary {
|
||||||
|
entrypoints: std::collections::BTreeMap::from([(
|
||||||
|
"default".to_string(),
|
||||||
|
"profiles/default.dcdl".to_string(),
|
||||||
|
)]),
|
||||||
|
source_count: 1,
|
||||||
|
import_count: 0,
|
||||||
|
total_source_bytes: 0,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn internal_resource_fetch_rest_returns_typed_missing_resource() {
|
||||||
|
let workspace = tempfile::tempdir().unwrap();
|
||||||
|
init_clean_git_workspace(workspace.path());
|
||||||
|
let app = test_app(workspace.path()).await;
|
||||||
|
let handle = missing_resource_handle();
|
||||||
|
let response = app
|
||||||
|
.oneshot(
|
||||||
|
Request::post("/internal/runtime/resources/fetch")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Body::from(
|
||||||
|
serde_json::to_vec(
|
||||||
|
&worker_runtime::resource::BackendResourceFetchRequest {
|
||||||
|
audit_correlation_id: handle.audit_correlation_id.clone(),
|
||||||
|
runtime_id: "runtime-test".to_string(),
|
||||||
|
worker_id: None,
|
||||||
|
handle,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||||
|
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
|
let error: worker_runtime::resource::BackendResourceError =
|
||||||
|
serde_json::from_slice(&bytes).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
worker_runtime::resource::BackendResourceError::MissingResource
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn remote_http_resource_fetch_uses_backend_resource_contract() {
|
||||||
|
let workspace = tempfile::tempdir().unwrap();
|
||||||
|
init_clean_git_workspace(workspace.path());
|
||||||
|
let api = test_api(workspace.path()).await;
|
||||||
|
let broker = api.resource_broker.clone();
|
||||||
|
let archive = test_profile_archive();
|
||||||
|
let runtime_id = worker_runtime::identity::RuntimeId::new("runtime-test").unwrap();
|
||||||
|
let handle = broker.issue_profile_source_archive_handle(
|
||||||
|
"workspace-test",
|
||||||
|
Some(&runtime_id),
|
||||||
|
None,
|
||||||
|
archive,
|
||||||
|
);
|
||||||
|
let app = build_router(api);
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||||
|
let client = worker_runtime::resource::HttpBackendResourceClient::new(
|
||||||
|
format!("http://{addr}/internal/runtime/resources/fetch"),
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
|
||||||
|
let response = client
|
||||||
|
.fetch_resource(worker_runtime::resource::BackendResourceFetchRequest {
|
||||||
|
audit_correlation_id: handle.audit_correlation_id.clone(),
|
||||||
|
runtime_id: runtime_id.as_str().to_string(),
|
||||||
|
worker_id: None,
|
||||||
|
handle: handle.clone(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("remote HTTP resource fetch succeeds");
|
||||||
|
assert_eq!(response.digest, handle.digest);
|
||||||
|
|
||||||
|
let mut tampered = handle;
|
||||||
|
tampered.scope_id = Some("tampered".to_string());
|
||||||
|
let error = client
|
||||||
|
.fetch_resource(worker_runtime::resource::BackendResourceFetchRequest {
|
||||||
|
audit_correlation_id: tampered.audit_correlation_id.clone(),
|
||||||
|
runtime_id: runtime_id.as_str().to_string(),
|
||||||
|
worker_id: None,
|
||||||
|
handle: tampered,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
worker_runtime::resource::BackendResourceError::Unauthorized { .. }
|
||||||
|
));
|
||||||
|
server.abort();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn runtime_test_bundle() -> worker_runtime::config_bundle::ConfigBundle {
|
fn runtime_test_bundle() -> worker_runtime::config_bundle::ConfigBundle {
|
||||||
|
|
@ -3406,6 +4027,7 @@ mod tests {
|
||||||
}],
|
}],
|
||||||
declarations: Vec::new(),
|
declarations: Vec::new(),
|
||||||
profile_source_archive: None,
|
profile_source_archive: None,
|
||||||
|
profile_source_archive_handle: None,
|
||||||
}
|
}
|
||||||
.with_computed_digest()
|
.with_computed_digest()
|
||||||
}
|
}
|
||||||
|
|
@ -4386,6 +5008,7 @@ mod tests {
|
||||||
working_directory_request: None,
|
working_directory_request: None,
|
||||||
resolved_working_directory_request: None,
|
resolved_working_directory_request: None,
|
||||||
resolved_working_directory: None,
|
resolved_working_directory: None,
|
||||||
|
resolved_config_bundle: None,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.expect("spawn worker");
|
.expect("spawn worker");
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,7 @@ rustPlatform.buildRustPackage rec {
|
||||||
filter = sourceFilter;
|
filter = sourceFilter;
|
||||||
};
|
};
|
||||||
|
|
||||||
cargoHash = "sha256-g9Bh9qQ1fGZtzsjO2/vc4jZdrH5YoCR0rOgs//xUDrU=";
|
cargoHash = "sha256-Pk6pRrtQlMAw2Shl+nQyX81FHQsHlKYAsxtg0M4Ya8Y=";
|
||||||
|
|
||||||
depsExtraArgs = {
|
depsExtraArgs = {
|
||||||
# Older fetchCargoVendor utilities used crates.io's API download endpoint,
|
# Older fetchCargoVendor utilities used crates.io's API download endpoint,
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,31 @@ export async function loadJson<T>(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function requireJson<T>(response: Response, path: string): Promise<T> {
|
||||||
|
if (!response.ok) {
|
||||||
|
const text = await response.text();
|
||||||
|
throw new Error(text || `${path} request failed (${response.status})`);
|
||||||
|
}
|
||||||
|
return (await response.json()) as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function workspaceApiJson<T>(path: string): Promise<T> {
|
||||||
|
return requireJson<T>(await fetch(path), path);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function workspaceApiJsonWithBody<T>(path: string, init: RequestInit): Promise<T> {
|
||||||
|
return requireJson<T>(
|
||||||
|
await fetch(path, {
|
||||||
|
headers: {
|
||||||
|
"content-type": "application/json",
|
||||||
|
...(init.headers ?? {}),
|
||||||
|
},
|
||||||
|
...init,
|
||||||
|
}),
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function formatDate(value: string): string {
|
export function formatDate(value: string): string {
|
||||||
const date = new Date(value);
|
const date = new Date(value);
|
||||||
if (Number.isNaN(date.getTime())) {
|
if (Number.isNaN(date.getTime())) {
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ export type Diagnostic = {
|
||||||
|
|
||||||
export type SettingsSectionId =
|
export type SettingsSectionId =
|
||||||
| "runtime-connections"
|
| "runtime-connections"
|
||||||
|
| "profile-sources"
|
||||||
| "backend-config"
|
| "backend-config"
|
||||||
| "workspace-identity";
|
| "workspace-identity";
|
||||||
|
|
||||||
|
|
@ -84,6 +85,18 @@ export const SETTINGS_SECTIONS: readonly SettingsSection[] = [
|
||||||
"Test negotiation is an observation only; checked_at, health, compatibility, and capability results are not persisted to local config.",
|
"Test negotiation is an observation only; checked_at, health, compatibility, and capability results are not persisted to local config.",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "profile-sources",
|
||||||
|
label: "Profile Sources",
|
||||||
|
status: "editable",
|
||||||
|
summary:
|
||||||
|
"Manage the workspace-scoped Decodal Profile registry and source files used by Backend-published launch profile discovery.",
|
||||||
|
bullets: [
|
||||||
|
"Selectors are source-qualified (builtin:* or project:*); raw profile source paths, archive content, archive digests, resource handles, and runtime tokens are not exposed.",
|
||||||
|
"Profile source edits are validated through the Backend ProfileSourceArchive/Decodal boundary before they are persisted.",
|
||||||
|
"Launch profile candidates refresh from the same Backend projection after registry or source updates.",
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "backend-config",
|
id: "backend-config",
|
||||||
label: "Backend Config",
|
label: "Backend Config",
|
||||||
|
|
|
||||||
81
web/workspace/src/lib/workspace-settings/profile-api.ts
Normal file
81
web/workspace/src/lib/workspace-settings/profile-api.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
||||||
|
import { workspaceApiJson, workspaceApiJsonWithBody } from "../workspace-api/http";
|
||||||
|
import type {
|
||||||
|
ProfileSettingsMutationResponse,
|
||||||
|
ProfileSettingsResponse,
|
||||||
|
WorkspaceMetadataMutationResponse,
|
||||||
|
WorkspaceMetadataSettingsResponse,
|
||||||
|
WorkspaceProfileSourceDetailResponse,
|
||||||
|
} from "./profile-types";
|
||||||
|
|
||||||
|
export function fetchWorkspaceMetadataSettings(workspaceId: string): Promise<WorkspaceMetadataSettingsResponse> {
|
||||||
|
return workspaceApiJson(`/api/w/${encodeURIComponent(workspaceId)}/settings/workspace`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateWorkspaceMetadataSettings(
|
||||||
|
workspaceId: string,
|
||||||
|
request: { display_name: string; revision: string },
|
||||||
|
): Promise<WorkspaceMetadataMutationResponse> {
|
||||||
|
return workspaceApiJsonWithBody(`/api/w/${encodeURIComponent(workspaceId)}/settings/workspace`, {
|
||||||
|
method: "PUT",
|
||||||
|
body: JSON.stringify(request),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchProfileSettings(workspaceId: string): Promise<ProfileSettingsResponse> {
|
||||||
|
return workspaceApiJson(`/api/w/${encodeURIComponent(workspaceId)}/settings/profiles`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createProfileSource(
|
||||||
|
workspaceId: string,
|
||||||
|
request: { name: string; description?: string; content: string; registry_revision: string },
|
||||||
|
): Promise<ProfileSettingsMutationResponse> {
|
||||||
|
return workspaceApiJsonWithBody(`/api/w/${encodeURIComponent(workspaceId)}/settings/profiles`, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(request),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateProfileRegistry(
|
||||||
|
workspaceId: string,
|
||||||
|
request: {
|
||||||
|
registry_revision: string;
|
||||||
|
default_profile?: string | null;
|
||||||
|
profiles: Array<{ name: string; description?: string | null; profile_source_id?: string | null }>;
|
||||||
|
},
|
||||||
|
): Promise<ProfileSettingsMutationResponse> {
|
||||||
|
return workspaceApiJsonWithBody(`/api/w/${encodeURIComponent(workspaceId)}/settings/profiles/registry`, {
|
||||||
|
method: "PUT",
|
||||||
|
body: JSON.stringify(request),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchProfileSource(
|
||||||
|
workspaceId: string,
|
||||||
|
sourceId: string,
|
||||||
|
): Promise<WorkspaceProfileSourceDetailResponse> {
|
||||||
|
return workspaceApiJson(
|
||||||
|
`/api/w/${encodeURIComponent(workspaceId)}/settings/profiles/${encodeURIComponent(sourceId)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateProfileSource(
|
||||||
|
workspaceId: string,
|
||||||
|
sourceId: string,
|
||||||
|
request: { content: string; revision: string },
|
||||||
|
): Promise<ProfileSettingsMutationResponse> {
|
||||||
|
return workspaceApiJsonWithBody(
|
||||||
|
`/api/w/${encodeURIComponent(workspaceId)}/settings/profiles/${encodeURIComponent(sourceId)}`,
|
||||||
|
{ method: "PUT", body: JSON.stringify(request) },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteProfileSource(
|
||||||
|
workspaceId: string,
|
||||||
|
sourceId: string,
|
||||||
|
request: { registry_revision: string; source_revision: string },
|
||||||
|
): Promise<ProfileSettingsMutationResponse> {
|
||||||
|
return workspaceApiJsonWithBody(
|
||||||
|
`/api/w/${encodeURIComponent(workspaceId)}/settings/profiles/${encodeURIComponent(sourceId)}`,
|
||||||
|
{ method: "DELETE", body: JSON.stringify(request) },
|
||||||
|
);
|
||||||
|
}
|
||||||
60
web/workspace/src/lib/workspace-settings/profile-types.ts
Normal file
60
web/workspace/src/lib/workspace-settings/profile-types.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
import type { Diagnostic } from "./model";
|
||||||
|
|
||||||
|
export type WorkspaceMetadataSettingsResponse = {
|
||||||
|
workspace_id: string;
|
||||||
|
display_name: string;
|
||||||
|
created_at: string;
|
||||||
|
revision: string;
|
||||||
|
source: string;
|
||||||
|
diagnostics: Diagnostic[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WorkspaceMetadataMutationResponse = {
|
||||||
|
workspace: WorkspaceMetadataSettingsResponse;
|
||||||
|
diagnostics: Diagnostic[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WorkspaceProfileSummary = {
|
||||||
|
profile_id: string;
|
||||||
|
selector: string;
|
||||||
|
label: string;
|
||||||
|
source_kind: "builtin" | "project" | string;
|
||||||
|
profile_source_id?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
editable: boolean;
|
||||||
|
is_default: boolean;
|
||||||
|
diagnostics: Diagnostic[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WorkspaceProfileSourceSummary = {
|
||||||
|
profile_source_id: string;
|
||||||
|
display_path: string;
|
||||||
|
kind: "decodal" | string;
|
||||||
|
editable: boolean;
|
||||||
|
revision: string;
|
||||||
|
size_bytes: number;
|
||||||
|
diagnostics: Diagnostic[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ProfileSettingsResponse = {
|
||||||
|
workspace_id: string;
|
||||||
|
registry_revision: string;
|
||||||
|
default_profile?: string | null;
|
||||||
|
profiles: WorkspaceProfileSummary[];
|
||||||
|
sources: WorkspaceProfileSourceSummary[];
|
||||||
|
diagnostics: Diagnostic[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WorkspaceProfileSourceDetailResponse = {
|
||||||
|
workspace_id: string;
|
||||||
|
profile: WorkspaceProfileSummary;
|
||||||
|
source: WorkspaceProfileSourceSummary;
|
||||||
|
content: string;
|
||||||
|
diagnostics: Diagnostic[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ProfileSettingsMutationResponse = {
|
||||||
|
workspace_id: string;
|
||||||
|
settings: ProfileSettingsResponse;
|
||||||
|
diagnostics: Diagnostic[];
|
||||||
|
};
|
||||||
|
|
@ -13,6 +13,21 @@
|
||||||
type RuntimeConnectionMutationResponse,
|
type RuntimeConnectionMutationResponse,
|
||||||
type RuntimeConnectionSettingsResponse,
|
type RuntimeConnectionSettingsResponse,
|
||||||
} from "$lib/workspace-settings/model";
|
} from "$lib/workspace-settings/model";
|
||||||
|
import type {
|
||||||
|
ProfileSettingsResponse,
|
||||||
|
WorkspaceMetadataSettingsResponse,
|
||||||
|
WorkspaceProfileSourceDetailResponse,
|
||||||
|
} from "$lib/workspace-settings/profile-types";
|
||||||
|
import {
|
||||||
|
createProfileSource,
|
||||||
|
deleteProfileSource,
|
||||||
|
fetchProfileSettings,
|
||||||
|
fetchProfileSource,
|
||||||
|
fetchWorkspaceMetadataSettings,
|
||||||
|
updateProfileRegistry,
|
||||||
|
updateProfileSource,
|
||||||
|
updateWorkspaceMetadataSettings,
|
||||||
|
} from "$lib/workspace-settings/profile-api";
|
||||||
|
|
||||||
type RemoteAddForm = {
|
type RemoteAddForm = {
|
||||||
runtime_id: string;
|
runtime_id: string;
|
||||||
|
|
@ -44,6 +59,19 @@
|
||||||
display_name: "",
|
display_name: "",
|
||||||
endpoint: "",
|
endpoint: "",
|
||||||
});
|
});
|
||||||
|
let workspaceMetadata = $state<WorkspaceMetadataSettingsResponse | null>(null);
|
||||||
|
let profileSettings = $state<ProfileSettingsResponse | null>(null);
|
||||||
|
let selectedProfileSource = $state<WorkspaceProfileSourceDetailResponse | null>(null);
|
||||||
|
let profileSourceContent = $state("");
|
||||||
|
let newProfileName = $state("");
|
||||||
|
let newProfileDescription = $state("");
|
||||||
|
let newProfileContent = $state("{\n slug = \"workspace-profile\";\n description = \"Workspace profile\";\n scope = \"workspace_read\";\n}\n");
|
||||||
|
let profileLoading = $state(true);
|
||||||
|
let profileMessage = $state<string | null>(null);
|
||||||
|
let profileDiagnostics = $state<Diagnostic[]>([]);
|
||||||
|
let profileSubmitting = $state(false);
|
||||||
|
let workspaceNameDraft = $state("");
|
||||||
|
let defaultProfileDraft = $state("");
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (!workspaceId) {
|
if (!workspaceId) {
|
||||||
|
|
@ -83,6 +111,179 @@
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (!workspaceId) {
|
||||||
|
profileLoading = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cancelled = false;
|
||||||
|
async function loadProfileAndWorkspaceSettings() {
|
||||||
|
profileLoading = true;
|
||||||
|
profileMessage = null;
|
||||||
|
profileDiagnostics = [];
|
||||||
|
try {
|
||||||
|
const [workspace, profiles] = await Promise.all([
|
||||||
|
fetchWorkspaceMetadataSettings(workspaceId),
|
||||||
|
fetchProfileSettings(workspaceId),
|
||||||
|
]);
|
||||||
|
if (!cancelled) {
|
||||||
|
workspaceMetadata = workspace;
|
||||||
|
workspaceNameDraft = workspace.display_name;
|
||||||
|
profileSettings = profiles;
|
||||||
|
defaultProfileDraft = profiles.default_profile ?? "";
|
||||||
|
profileDiagnostics = [...workspace.diagnostics, ...profiles.diagnostics];
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (!cancelled) {
|
||||||
|
profileMessage = err instanceof Error ? err.message : "profile settings request failed";
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (!cancelled) {
|
||||||
|
profileLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loadProfileAndWorkspaceSettings();
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
async function refreshProfileSettings() {
|
||||||
|
profileSettings = await fetchProfileSettings(workspaceId);
|
||||||
|
profileDiagnostics = profileSettings.diagnostics;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitWorkspaceName() {
|
||||||
|
if (!workspaceMetadata) return;
|
||||||
|
profileSubmitting = true;
|
||||||
|
profileMessage = null;
|
||||||
|
try {
|
||||||
|
const response = await updateWorkspaceMetadataSettings(workspaceId, {
|
||||||
|
display_name: workspaceNameDraft,
|
||||||
|
revision: workspaceMetadata.revision,
|
||||||
|
});
|
||||||
|
workspaceMetadata = response.workspace;
|
||||||
|
workspaceNameDraft = response.workspace.display_name;
|
||||||
|
profileDiagnostics = response.diagnostics.concat(response.workspace.diagnostics);
|
||||||
|
profileMessage = "Workspace display name updated.";
|
||||||
|
} catch (err) {
|
||||||
|
profileMessage = err instanceof Error ? err.message : "workspace update failed";
|
||||||
|
} finally {
|
||||||
|
profileSubmitting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitProfileRegistry() {
|
||||||
|
if (!profileSettings) return;
|
||||||
|
profileSubmitting = true;
|
||||||
|
profileMessage = null;
|
||||||
|
try {
|
||||||
|
const response = await updateProfileRegistry(workspaceId, {
|
||||||
|
registry_revision: profileSettings.registry_revision,
|
||||||
|
default_profile: defaultProfileDraft || null,
|
||||||
|
profiles: profileSettings.profiles
|
||||||
|
.filter((profile) => profile.source_kind === "project")
|
||||||
|
.map((profile) => ({
|
||||||
|
name: profile.selector.replace(/^project:/, ""),
|
||||||
|
description: profile.description ?? null,
|
||||||
|
profile_source_id: profile.profile_source_id ?? null,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
profileSettings = response.settings;
|
||||||
|
defaultProfileDraft = response.settings.default_profile ?? "";
|
||||||
|
profileDiagnostics = response.diagnostics.concat(response.settings.diagnostics);
|
||||||
|
profileMessage = "Profile registry updated.";
|
||||||
|
} catch (err) {
|
||||||
|
profileMessage = err instanceof Error ? err.message : "profile registry update failed";
|
||||||
|
} finally {
|
||||||
|
profileSubmitting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitNewProfileSource() {
|
||||||
|
if (!profileSettings) return;
|
||||||
|
profileSubmitting = true;
|
||||||
|
profileMessage = null;
|
||||||
|
try {
|
||||||
|
const response = await createProfileSource(workspaceId, {
|
||||||
|
name: newProfileName,
|
||||||
|
description: newProfileDescription || undefined,
|
||||||
|
content: newProfileContent,
|
||||||
|
registry_revision: profileSettings.registry_revision,
|
||||||
|
});
|
||||||
|
profileSettings = response.settings;
|
||||||
|
defaultProfileDraft = response.settings.default_profile ?? "";
|
||||||
|
profileDiagnostics = response.diagnostics.concat(response.settings.diagnostics);
|
||||||
|
newProfileName = "";
|
||||||
|
newProfileDescription = "";
|
||||||
|
profileMessage = "Profile source created.";
|
||||||
|
} catch (err) {
|
||||||
|
profileMessage = err instanceof Error ? err.message : "profile source create failed";
|
||||||
|
} finally {
|
||||||
|
profileSubmitting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function selectProfileSource(sourceId: string) {
|
||||||
|
profileSubmitting = true;
|
||||||
|
profileMessage = null;
|
||||||
|
try {
|
||||||
|
selectedProfileSource = await fetchProfileSource(workspaceId, sourceId);
|
||||||
|
profileSourceContent = selectedProfileSource.content;
|
||||||
|
profileDiagnostics = selectedProfileSource.diagnostics.concat(
|
||||||
|
selectedProfileSource.source.diagnostics,
|
||||||
|
selectedProfileSource.profile.diagnostics,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
profileMessage = err instanceof Error ? err.message : "profile source load failed";
|
||||||
|
} finally {
|
||||||
|
profileSubmitting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitProfileSourceUpdate() {
|
||||||
|
if (!selectedProfileSource) return;
|
||||||
|
profileSubmitting = true;
|
||||||
|
profileMessage = null;
|
||||||
|
try {
|
||||||
|
const response = await updateProfileSource(workspaceId, selectedProfileSource.source.profile_source_id, {
|
||||||
|
content: profileSourceContent,
|
||||||
|
revision: selectedProfileSource.source.revision,
|
||||||
|
});
|
||||||
|
profileSettings = response.settings;
|
||||||
|
defaultProfileDraft = response.settings.default_profile ?? "";
|
||||||
|
profileDiagnostics = response.diagnostics.concat(response.settings.diagnostics);
|
||||||
|
await selectProfileSource(selectedProfileSource.source.profile_source_id);
|
||||||
|
profileMessage = "Profile source updated.";
|
||||||
|
} catch (err) {
|
||||||
|
profileMessage = err instanceof Error ? err.message : "profile source update failed";
|
||||||
|
} finally {
|
||||||
|
profileSubmitting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitProfileSourceDelete() {
|
||||||
|
if (!profileSettings || !selectedProfileSource) return;
|
||||||
|
profileSubmitting = true;
|
||||||
|
profileMessage = null;
|
||||||
|
try {
|
||||||
|
const response = await deleteProfileSource(workspaceId, selectedProfileSource.source.profile_source_id, {
|
||||||
|
registry_revision: profileSettings.registry_revision,
|
||||||
|
source_revision: selectedProfileSource.source.revision,
|
||||||
|
});
|
||||||
|
profileSettings = response.settings;
|
||||||
|
selectedProfileSource = null;
|
||||||
|
profileSourceContent = "";
|
||||||
|
profileDiagnostics = response.diagnostics.concat(response.settings.diagnostics);
|
||||||
|
profileMessage = "Profile source deleted.";
|
||||||
|
} catch (err) {
|
||||||
|
profileMessage = err instanceof Error ? err.message : "profile source delete failed";
|
||||||
|
} finally {
|
||||||
|
profileSubmitting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function submitRemoteRuntime() {
|
async function submitRemoteRuntime() {
|
||||||
submitting = true;
|
submitting = true;
|
||||||
mutationMessage = null;
|
mutationMessage = null;
|
||||||
|
|
@ -410,8 +611,109 @@
|
||||||
{/if}
|
{/if}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="card profile-settings" id="profile-sources" aria-labelledby="profile-settings-title">
|
||||||
|
<header class="settings-section-header">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">editable</p>
|
||||||
|
<h2 id="profile-settings-title">Profile Sources</h2>
|
||||||
|
</div>
|
||||||
|
<span class="badge success">Backend scoped</span>
|
||||||
|
</header>
|
||||||
|
<p>
|
||||||
|
Workspace profile settings are surfaced as source-qualified selectors and Decodal source summaries. The browser never receives raw host paths, runtime endpoints, tokens, resource handles, archive content, or archive digests.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{#if profileLoading}
|
||||||
|
<p class="status-message">Loading profile settings…</p>
|
||||||
|
{:else}
|
||||||
|
<div class="grid settings-grid">
|
||||||
|
<form class="settings-form" onsubmit={(event) => { event.preventDefault(); submitWorkspaceName(); }}>
|
||||||
|
<h3>Workspace display name</h3>
|
||||||
|
<label>
|
||||||
|
<span>Display name</span>
|
||||||
|
<input bind:value={workspaceNameDraft} autocomplete="off" />
|
||||||
|
</label>
|
||||||
|
<p class="settings-note">Workspace id: <code>{workspaceMetadata?.workspace_id ?? workspaceId}</code></p>
|
||||||
|
<button type="submit" disabled={profileSubmitting || !workspaceMetadata}>Save workspace name</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form class="settings-form" onsubmit={(event) => { event.preventDefault(); submitProfileRegistry(); }}>
|
||||||
|
<h3>Default launch profile</h3>
|
||||||
|
<label>
|
||||||
|
<span>Default selector</span>
|
||||||
|
<select bind:value={defaultProfileDraft} disabled={!profileSettings}>
|
||||||
|
<option value="">Runtime default</option>
|
||||||
|
{#each profileSettings?.profiles ?? [] as profile}
|
||||||
|
<option value={profile.selector}>{profile.label} ({profile.selector})</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<button type="submit" disabled={profileSubmitting || !profileSettings}>Save profile registry</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="settings-table-wrapper">
|
||||||
|
<h3>Discovered profiles</h3>
|
||||||
|
<table class="settings-table">
|
||||||
|
<thead>
|
||||||
|
<tr><th>Selector</th><th>Label</th><th>Source</th><th>Status</th><th>Action</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{#each profileSettings?.profiles ?? [] as profile}
|
||||||
|
<tr>
|
||||||
|
<td><code>{profile.selector}</code></td>
|
||||||
|
<td>{profile.label}</td>
|
||||||
|
<td>{profile.source_kind}</td>
|
||||||
|
<td>{profile.diagnostics.length === 0 ? "ok" : `${profile.diagnostics.length} diagnostics`}</td>
|
||||||
|
<td>
|
||||||
|
{#if profile.profile_source_id}
|
||||||
|
<button type="button" onclick={() => selectProfileSource(profile.profile_source_id!)} disabled={profileSubmitting}>Open source</button>
|
||||||
|
{:else}
|
||||||
|
<span class="settings-note">builtin</span>
|
||||||
|
{/if}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{/each}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid settings-grid">
|
||||||
|
<form class="settings-form" onsubmit={(event) => { event.preventDefault(); submitNewProfileSource(); }}>
|
||||||
|
<h3>Create project profile source</h3>
|
||||||
|
<label><span>Name</span><input bind:value={newProfileName} placeholder="team-coder" autocomplete="off" /></label>
|
||||||
|
<label><span>Description</span><input bind:value={newProfileDescription} placeholder="Optional summary" autocomplete="off" /></label>
|
||||||
|
<label><span>Decodal source</span><textarea bind:value={newProfileContent} rows="8"></textarea></label>
|
||||||
|
<button type="submit" disabled={profileSubmitting || !profileSettings}>Create source</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{#if selectedProfileSource}
|
||||||
|
<form class="settings-form" onsubmit={(event) => { event.preventDefault(); submitProfileSourceUpdate(); }}>
|
||||||
|
<h3>Edit {selectedProfileSource.profile.label}</h3>
|
||||||
|
<p class="settings-note">Source id: <code>{selectedProfileSource.source.profile_source_id}</code>; display path: {selectedProfileSource.source.display_path}</p>
|
||||||
|
<label><span>Decodal source</span><textarea bind:value={profileSourceContent} rows="14"></textarea></label>
|
||||||
|
<div class="settings-actions">
|
||||||
|
<button type="submit" disabled={profileSubmitting}>Validate & save source</button>
|
||||||
|
<button type="button" class="danger" onclick={submitProfileSourceDelete} disabled={profileSubmitting}>Delete source</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{:else}
|
||||||
|
<div class="settings-empty-state">
|
||||||
|
<h3>No profile source selected</h3>
|
||||||
|
<p>Open a project source from the discovered profile table to edit it.</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if profileMessage}
|
||||||
|
<p class="status-message">{profileMessage}</p>
|
||||||
|
{/if}
|
||||||
|
{@render DiagnosticsList({ diagnostics: profileDiagnostics })}
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
|
||||||
<div class="grid settings-grid">
|
<div class="grid settings-grid">
|
||||||
{#each SETTINGS_SECTIONS.filter((section) => section.id !== "runtime-connections") as section}
|
{#each SETTINGS_SECTIONS.filter((section) => section.id !== "runtime-connections" && section.id !== "profile-sources") as section}
|
||||||
<section class="card settings-section" id={section.id} aria-labelledby={`${section.id}-title`}>
|
<section class="card settings-section" id={section.id} aria-labelledby={`${section.id}-title`}>
|
||||||
<header class="settings-section-header">
|
<header class="settings-section-header">
|
||||||
<div>
|
<div>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user